Skip to main content

miniextendr_api/
strvec.rs

1//! Thin wrapper around R character vector (`STRSXP`).
2//!
3//! Provides safe construction and element insertion for string vectors.
4
5use std::borrow::Cow;
6
7use crate::SEXPTYPE::STRSXP;
8use crate::from_r::{
9    SexpError, SexpTypeError, TryFromSexp, charsxp_to_borrowed_str_or_panic,
10    charsxp_to_cow_or_panic,
11};
12use crate::gc_protect::{ChildRoots, OwnedProtect, ProtectScope};
13use crate::into_r::IntoR;
14use crate::{Preserved, SEXP, SexpExt};
15
16/// Borrowed view over an R character vector (`STRSXP`).
17///
18/// Strings returned by the view carry `'a`. Constructors must tie that lifetime
19/// to a root that keeps the source reachable. [`ProtectedStrVec::as_strvec`]
20/// does so through a borrow of its owner.
21///
22/// [`try_from_root`](Self::try_from_root) borrows a lifetime-carrying root.
23/// Generated wrappers use this path for `StrVec<'_>` parameters. Raw
24/// `TryFromSexp` is unavailable: a copyable SEXP cannot constrain the view's
25/// lifetime. Use [`ProtectedStrVec`] when the result must own its root.
26///
27/// `Copy` and cheap (a `SEXP` and a retention reference); covariant in `'a`.
28/// Uncached ALTREP elements read through a rooted view stay alive for `'a`.
29#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'a>
    ::core::clone::TrivialClone for StrVec<'a> {
}
#[automatically_derived]impl<'a> ::core::clone::Clone for StrVec<'a> {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<SEXP>;
        let _: ::core::clone::AssertParamIsClone<Option<&'a ChildRoots>>;
        *self
    }
}Clone, #[automatically_derived]impl<'a> ::core::marker::Copy for StrVec<'a> { }Copy)]
30pub struct StrVec<'a>(SEXP, Option<&'a ChildRoots>);
31
32impl std::fmt::Debug for StrVec<'_> {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        f.debug_tuple("StrVec").field(&self.0).finish()
35    }
36}
37
38impl<'a> StrVec<'a> {
39    /// Strings do not retain a pointer to a native numeric vector.
40    #[doc(hidden)]
41    pub const NATIVE_BORROW: Option<crate::from_r::NativeBorrow> = None;
42
43    /// Wrap an existing `STRSXP` without additional checks.
44    ///
45    /// # Safety
46    ///
47    /// Caller must ensure `sexp` is a valid character vector (`STRSXP`)
48    /// that stays GC-reachable for the inferred lifetime `'a`. An ALTREP class
49    /// must also retain every CHARSXP read through this raw view for `'a`;
50    /// otherwise use `try_from_root` or `ProtectedStrVec`.
51    #[inline]
52    pub const unsafe fn from_raw(sexp: SEXP) -> Self {
53        StrVec(sexp, None)
54    }
55
56    /// Get the underlying `SEXP`.
57    #[inline]
58    pub const fn as_sexp(self) -> SEXP {
59        self.0
60    }
61
62    /// Length of the character vector (number of elements).
63    #[inline]
64    pub fn len(self) -> isize {
65        self.0.xlength()
66    }
67
68    /// Returns true if the vector is empty.
69    #[inline]
70    pub fn is_empty(self) -> bool {
71        self.len() == 0
72    }
73
74    /// Get the CHARSXP at the given index.
75    ///
76    /// Returns `None` if out of bounds.
77    #[inline]
78    pub fn get_charsxp(self, idx: isize) -> Option<SEXP> {
79        if idx < 0 || idx >= self.len() {
80            return None;
81        }
82        let charsxp = self.0.string_elt(idx);
83        Some(match self.1 {
84            // The root/owner behind this reference lives for 'a.
85            Some(children) => unsafe { children.protect(self.0, charsxp) },
86            None => charsxp, // from_raw's caller guarantees element retention
87        })
88    }
89
90    /// Get the string at the given index (zero-copy), leashed to `'a`.
91    ///
92    /// Returns `None` if out of bounds or if the element is `NA_character_`.
93    /// Panics if the CHARSXP is not UTF-8/ASCII. A UTF-8 process locale can
94    /// still contain explicitly tagged Latin-1 strings; use
95    /// [`get_cow`](Self::get_cow) when those must be translated.
96    #[inline]
97    pub fn get_str(self, idx: isize) -> Option<&'a str> {
98        let charsxp = self.get_charsxp(idx)?;
99        unsafe {
100            if charsxp == SEXP::na_string() {
101                return None;
102            }
103            // The read fabricates &'static; covariance narrows it to &'a.
104            Some(charsxp_to_borrowed_str_or_panic(charsxp))
105        }
106    }
107
108    /// Get the string at the given index as `Cow<str>` (encoding-safe), leashed to `'a`.
109    ///
110    /// Returns `Cow::Borrowed` for UTF-8 strings (zero-copy), `Cow::Owned` for
111    /// non-UTF-8 strings (translated via `Rf_translateCharUTF8`).
112    /// Returns `None` if out of bounds or `NA_character_`. Panics on a string
113    /// marked as bytes or one that is not valid UTF-8, which is not text; a
114    /// `Vec<String>` or `Vec<Cow<str>>` argument refuses such an element with
115    /// an argument error instead.
116    #[inline]
117    pub fn get_cow(self, idx: isize) -> Option<Cow<'a, str>> {
118        let charsxp = self.get_charsxp(idx)?;
119        unsafe {
120            if charsxp == SEXP::na_string() {
121                return None;
122            }
123            Some(charsxp_to_cow_or_panic(charsxp))
124        }
125    }
126
127    /// Get the string at the given index as `&'static str` — the courageous escape.
128    ///
129    /// Unlike [`get_str`](Self::get_str), the returned reference is **not** leashed
130    /// to `'a`, so it can be stored in an `ExternalPtr`, a global, or sent across
131    /// threads. The string data lives in R's CHARSXP; the CHARSXP must remain
132    /// reachable. For an uncached ALTREP element, retain this view's protection
133    /// scope or `ProtectedStrVec` owner as well as the source vector.
134    ///
135    /// # Safety
136    ///
137    /// The caller must keep the returned CHARSXP reachable for as long as the
138    /// reference is used. Rooting an ordinary source STRSXP suffices; an ALTREP
139    /// source may need this view's scope/owner or a separate root for the child.
140    /// Letting R collect that child is use-after-free.
141    #[inline]
142    pub unsafe fn get_str_static(self, idx: isize) -> Option<&'static str> {
143        let charsxp = self.get_charsxp(idx)?;
144        unsafe {
145            if charsxp == SEXP::na_string() {
146                return None;
147            }
148            Some(charsxp_to_borrowed_str_or_panic(charsxp))
149        }
150    }
151
152    /// Get the string at the given index as `Cow<'static, str>` — the courageous escape.
153    ///
154    /// `Cow` analogue of [`get_str_static`](Self::get_str_static); same rooting
155    /// obligation for the borrowed (`Cow::Borrowed`) case.
156    ///
157    /// # Safety
158    ///
159    /// See [`get_str_static`](Self::get_str_static).
160    #[inline]
161    pub unsafe fn get_cow_static(self, idx: isize) -> Option<Cow<'static, str>> {
162        let charsxp = self.get_charsxp(idx)?;
163        unsafe {
164            if charsxp == SEXP::na_string() {
165                return None;
166            }
167            Some(charsxp_to_cow_or_panic(charsxp))
168        }
169    }
170
171    /// Iterate over UTF-8/ASCII elements as `Option<&str>` (leashed to `'a`).
172    ///
173    /// `NA_character_` elements yield `None`; UTF-8/ASCII strings yield
174    /// `Some(&str)`. Panics on other encodings; use [`iter_cow`](Self::iter_cow)
175    /// to translate them.
176    #[inline]
177    pub fn iter(self) -> StrVecIter<'a> {
178        StrVecIter {
179            vec: self,
180            idx: 0,
181            len: self.len(),
182        }
183    }
184
185    /// Iterate over elements as `Option<Cow<str>>` (encoding-safe, leashed to `'a`).
186    ///
187    /// Like [`iter`](Self::iter) but handles non-UTF-8 CHARSXPs gracefully.
188    #[inline]
189    pub fn iter_cow(self) -> StrVecCowIter<'a> {
190        StrVecCowIter {
191            vec: self,
192            idx: 0,
193            len: self.len(),
194        }
195    }
196
197    // region: Safe element insertion
198
199    /// Set a CHARSXP at the given index, protecting it during insertion.
200    ///
201    /// This is the safe way to insert a freshly allocated CHARSXP into a string vector.
202    ///
203    /// # Safety
204    ///
205    /// - Must be called from the R main thread
206    /// - `charsxp` must be a valid CHARSXP (from `Rf_mkChar*` or `STRING_ELT`)
207    /// - `self` must be a valid, protected STRSXP
208    ///
209    /// # Panics
210    ///
211    /// Panics if `idx` is out of bounds.
212    #[inline]
213    pub unsafe fn set_charsxp(self, idx: isize, charsxp: SEXP) {
214        if !(idx >= 0 && idx < self.len()) {
    { ::core::panicking::panic_fmt(format_args!("index out of bounds")); }
};assert!(idx >= 0 && idx < self.len(), "index out of bounds");
215        // SAFETY: caller guarantees R main thread and valid SEXPs
216        unsafe {
217            // Protect CHARSXP during SET_STRING_ELT.
218            // Note: Rf_mkCharLenCE returns a CHARSXP that may be from the global
219            // CHARSXP cache, but protection is still needed for newly allocated ones.
220            let _guard = OwnedProtect::new(charsxp);
221            self.0.set_string_elt(idx, charsxp);
222        }
223    }
224
225    /// Set a CHARSXP without protecting it.
226    ///
227    /// # Safety
228    ///
229    /// In addition to the safety requirements of [`set_charsxp`](Self::set_charsxp):
230    /// - The caller must ensure `charsxp` is already protected or from the
231    ///   global CHARSXP cache.
232    #[inline]
233    pub unsafe fn set_charsxp_unchecked(self, idx: isize, charsxp: SEXP) {
234        if true {
    if !(idx >= 0 && idx < self.len()) {
        { ::core::panicking::panic_fmt(format_args!("index out of bounds")); }
    };
};debug_assert!(idx >= 0 && idx < self.len(), "index out of bounds");
235        // SAFETY: caller guarantees charsxp is protected/cached
236        self.0.set_string_elt(idx, charsxp);
237    }
238
239    /// Set an element from a Rust string.
240    ///
241    /// Creates a CHARSXP from the string and inserts it safely.
242    ///
243    /// # Safety
244    ///
245    /// - Must be called from the R main thread
246    /// - `self` must be a valid, protected STRSXP
247    ///
248    /// # Panics
249    ///
250    /// Panics if `idx` is out of bounds.
251    #[inline]
252    pub unsafe fn set_str(self, idx: isize, s: &str) {
253        if !(idx >= 0 && idx < self.len()) {
    { ::core::panicking::panic_fmt(format_args!("index out of bounds")); }
};assert!(idx >= 0 && idx < self.len(), "index out of bounds");
254        // SAFETY: caller guarantees R main thread
255        unsafe {
256            let charsxp = SEXP::charsxp(s);
257            // CHARSXP may be cached, but protect anyway for safety
258            let _guard = OwnedProtect::new(charsxp);
259            self.0.set_string_elt(idx, charsxp);
260        }
261    }
262
263    /// Set an element to `NA_character_`.
264    ///
265    /// # Safety
266    ///
267    /// - Must be called from the R main thread
268    /// - `self` must be a valid, protected STRSXP
269    ///
270    /// # Panics
271    ///
272    /// Panics if `idx` is out of bounds.
273    #[inline]
274    pub unsafe fn set_na(self, idx: isize) {
275        if !(idx >= 0 && idx < self.len()) {
    { ::core::panicking::panic_fmt(format_args!("index out of bounds")); }
};assert!(idx >= 0 && idx < self.len(), "index out of bounds");
276        // R_NaString is a global constant, no protection needed
277        self.0.set_string_elt(idx, SEXP::na_string());
278    }
279
280    /// Set an element from an optional string.
281    ///
282    /// `None` becomes `NA_character_`.
283    ///
284    /// # Safety
285    ///
286    /// - Must be called from the R main thread
287    /// - `self` must be a valid, protected STRSXP
288    ///
289    /// # Panics
290    ///
291    /// Panics if `idx` is out of bounds.
292    #[inline]
293    pub unsafe fn set_opt_str(self, idx: isize, s: Option<&str>) {
294        match s {
295            Some(s) => unsafe { self.set_str(idx, s) },
296            None => unsafe { self.set_na(idx) },
297        }
298    }
299    // endregion
300}
301
302// region: StrVec iterators
303
304/// Iterator over `StrVec` elements as `Option<&str>` (leashed to `'a`).
305///
306/// Yields `None` for `NA_character_`, `Some(&str)` for valid strings.
307/// Zero-copy — each `&str` borrows directly from R's CHARSXP.
308pub struct StrVecIter<'a> {
309    vec: StrVec<'a>,
310    idx: isize,
311    len: isize,
312}
313
314impl<'a> Iterator for StrVecIter<'a> {
315    type Item = Option<&'a str>;
316
317    #[inline]
318    fn next(&mut self) -> Option<Self::Item> {
319        if self.idx >= self.len {
320            return None;
321        }
322        let value = self.vec.get_str(self.idx);
323        self.idx += 1;
324        Some(value)
325    }
326
327    #[inline]
328    fn size_hint(&self) -> (usize, Option<usize>) {
329        let remaining = (self.len - self.idx) as usize;
330        (remaining, Some(remaining))
331    }
332}
333
334impl ExactSizeIterator for StrVecIter<'_> {}
335
336/// Iterator over `StrVec` elements as `Option<Cow<'a, str>>`.
337///
338/// Like [`StrVecIter`] but handles non-UTF-8 CHARSXPs via `Rf_translateCharUTF8`.
339pub struct StrVecCowIter<'a> {
340    vec: StrVec<'a>,
341    idx: isize,
342    len: isize,
343}
344
345impl<'a> Iterator for StrVecCowIter<'a> {
346    type Item = Option<Cow<'a, str>>;
347
348    #[inline]
349    fn next(&mut self) -> Option<Self::Item> {
350        if self.idx >= self.len {
351            return None;
352        }
353        let value = self.vec.get_cow(self.idx);
354        self.idx += 1;
355        Some(value)
356    }
357
358    #[inline]
359    fn size_hint(&self) -> (usize, Option<usize>) {
360        let remaining = (self.len - self.idx) as usize;
361        (remaining, Some(remaining))
362    }
363}
364
365impl ExactSizeIterator for StrVecCowIter<'_> {}
366
367impl<'a> IntoIterator for StrVec<'a> {
368    type Item = Option<&'a str>;
369    type IntoIter = StrVecIter<'a>;
370
371    #[inline]
372    fn into_iter(self) -> Self::IntoIter {
373        self.iter()
374    }
375}
376
377// endregion
378
379// region: StrVecBuilder - efficient batch string vector construction
380
381/// Builder for constructing string vectors with efficient protection management.
382///
383/// # Example
384///
385/// ```ignore
386/// unsafe fn build_strvec(strings: &[&str]) -> SEXP {
387///     let scope = ProtectScope::new();
388///     let builder = StrVecBuilder::new(&scope, strings.len() as isize);
389///
390///     for (i, s) in strings.iter().enumerate() {
391///         builder.set_str(i as isize, s);
392///     }
393///
394///     builder.into_sexp()
395/// }
396/// ```
397pub struct StrVecBuilder<'a> {
398    vec: SEXP,
399    _scope: &'a ProtectScope,
400}
401
402impl<'a> StrVecBuilder<'a> {
403    /// Create a new string vector builder with the given length.
404    ///
405    /// # Safety
406    ///
407    /// Must be called from the R main thread.
408    #[inline]
409    pub unsafe fn new(scope: &'a ProtectScope, len: usize) -> Self {
410        // SAFETY: caller guarantees R main thread
411        let vec = unsafe { scope.alloc_character(len).into_raw() };
412        Self { vec, _scope: scope }
413    }
414
415    /// Create a new string vector builder via the **unchecked** FFI allocation path.
416    ///
417    /// `_unchecked` twin of [`new`](Self::new): the STRSXP is allocated with
418    /// `Rf_allocVector_unchecked` (see [`ProtectScope::alloc_character_unchecked`]),
419    /// bypassing the main-thread assertion. Use inside ALTREP callbacks,
420    /// `with_r_unwind_protect`, or `with_r_thread` bodies, and pair element
421    /// insertion with the `_unchecked` string-element setters.
422    ///
423    /// # Safety
424    ///
425    /// Must be called from the R main thread, in a context where the checked-FFI
426    /// assertion is intentionally bypassed (see CLAUDE.md "FFI thread checking").
427    #[inline]
428    pub unsafe fn new_unchecked(scope: &'a ProtectScope, len: usize) -> Self {
429        // SAFETY: caller guarantees R main thread in a checked-bypass context.
430        let vec = unsafe { scope.alloc_character_unchecked(len).into_raw() };
431        Self { vec, _scope: scope }
432    }
433
434    /// Set an element from a Rust string.
435    ///
436    /// # Safety
437    ///
438    /// Must be called from the R main thread.
439    #[inline]
440    pub unsafe fn set_str(&self, idx: isize, s: &str) {
441        if true {
    if !(idx >= 0 && idx < self.vec.xlength()) {
        ::core::panicking::panic("assertion failed: idx >= 0 && idx < self.vec.xlength()")
    };
};debug_assert!(idx >= 0 && idx < self.vec.xlength());
442        let charsxp = SEXP::charsxp(s);
443        self.vec.set_string_elt(idx, charsxp);
444    }
445
446    /// Set an element to `NA_character_`.
447    ///
448    /// # Safety
449    ///
450    /// Must be called from the R main thread.
451    #[inline]
452    pub unsafe fn set_na(&self, idx: isize) {
453        if true {
    if !(idx >= 0 && idx < self.vec.xlength()) {
        ::core::panicking::panic("assertion failed: idx >= 0 && idx < self.vec.xlength()")
    };
};debug_assert!(idx >= 0 && idx < self.vec.xlength());
454        self.vec.set_string_elt(idx, SEXP::na_string());
455    }
456
457    /// Set an element from an optional string.
458    ///
459    /// # Safety
460    ///
461    /// Must be called from the R main thread.
462    #[inline]
463    pub unsafe fn set_opt_str(&self, idx: isize, s: Option<&str>) {
464        match s {
465            // SAFETY: caller guarantees R main thread
466            Some(s) => unsafe { self.set_str(idx, s) },
467            None => unsafe { self.set_na(idx) },
468        }
469    }
470
471    /// Get the underlying SEXP.
472    #[inline]
473    pub fn as_sexp(&self) -> SEXP {
474        self.vec
475    }
476
477    /// Convert to a `StrVec` view, leashed to the builder's protect scope `'a`.
478    #[inline]
479    pub fn into_strvec(self) -> StrVec<'a> {
480        // The builder allocates an ordinary STRSXP, whose elements are traced
481        // directly. Its scope already roots that vector for 'a.
482        StrVec(self.vec, None)
483    }
484
485    /// Convert to the underlying SEXP.
486    #[inline]
487    pub fn into_sexp(self) -> SEXP {
488        self.vec
489    }
490
491    /// Get the length.
492    #[inline]
493    pub fn len(&self) -> isize {
494        self.vec.xlength()
495    }
496
497    /// Check if empty.
498    #[inline]
499    pub fn is_empty(&self) -> bool {
500        self.len() == 0
501    }
502}
503// endregion
504
505// region: Trait implementations
506
507impl IntoR for StrVec<'_> {
508    type Error = std::convert::Infallible;
509    fn try_into_sexp(self) -> Result<SEXP, Self::Error> {
510        Ok(self.into_sexp())
511    }
512    unsafe fn try_into_sexp_unchecked(self) -> Result<SEXP, Self::Error> {
513        self.try_into_sexp()
514    }
515    #[inline]
516    fn into_sexp(self) -> SEXP {
517        self.0
518    }
519}
520
521impl<'a> StrVec<'a> {
522    /// Borrow a character vector for the lifetime of its root.
523    ///
524    /// The result cannot acquire a lifetime longer than the supplied root.
525    /// Raw `TryFromSexp` is intentionally unavailable for this borrowed view.
526    ///
527    /// ```compile_fail
528    /// use miniextendr_api::{Root, StrVec};
529    /// fn escape<'a>(root: Root<'a>) -> StrVec<'static> {
530    ///     StrVec::try_from_root(root).unwrap()
531    /// }
532    /// ```
533    pub fn try_from_root(root: crate::Root<'a>) -> Result<Self, SexpError> {
534        let sexp = root.get();
535        let actual = sexp.type_of();
536        if actual != STRSXP {
537            return Err(SexpTypeError {
538                expected: STRSXP,
539                actual,
540            }
541            .into());
542        }
543        // The root, not an unconstrained return annotation, fixes `'a`.
544        Ok(StrVec(sexp, Some(root.child_roots())))
545    }
546}
547// endregion
548
549// region: ProtectedStrVec — GC-protected string vector with proper lifetimes
550
551/// GC-protected view over an R character vector (`STRSXP`).
552///
553/// Unlike [`StrVec`] (which is `Copy` and trusts the caller for GC protection),
554/// `ProtectedStrVec` holds a [`Preserved`] root on the STRSXP for its Rust
555/// lifetime. It can outlive a `.Call` frame and be dropped in any order
556/// relative to other handles.
557/// Borrowed strings and iterators are tied to `&self`. It is `!Send + !Sync`:
558/// reading and releasing the R object must happen on R's main thread.
559///
560/// # When to use
561///
562/// - **`StrVec`**: for SEXP arguments to `.Call` (R protects them), or when you
563///   manage protection yourself. Lightweight, `Copy`.
564/// - **`ProtectedStrVec`**: when you allocate or receive an STRSXP and need to
565///   keep it alive beyond the immediate scope. Not `Copy`.
566///
567/// # Example
568///
569/// ```ignore
570/// #[miniextendr]
571/// pub fn count_unique(strings: ProtectedStrVec) -> i32 {
572///     let unique: HashSet<&str> = strings.iter()
573///         .filter_map(|s| s)
574///         .collect();
575///     unique.len() as i32
576/// }
577/// ```
578pub struct ProtectedStrVec {
579    sexp: SEXP,
580    /// `None` for [`from_sexp_trusted`](Self::from_sexp_trusted), whose caller
581    /// roots `sexp`. The field also makes the handle `!Send + !Sync`.
582    _root: Option<Preserved>,
583    children: ChildRoots,
584    len: isize,
585}
586
587impl ProtectedStrVec {
588    /// Create a protected view over an STRSXP.
589    ///
590    /// Roots the SEXP with a [`Preserved`] handle, released on drop,
591    /// independently of R's protection stack. Use
592    /// [`from_sexp_trusted`](Self::from_sexp_trusted) only when another owner
593    /// guarantees reachability for this handle's entire lifetime.
594    ///
595    /// # Safety
596    ///
597    /// - `sexp` must be a valid STRSXP.
598    /// - Must be called from the R main thread.
599    #[inline]
600    pub unsafe fn new(sexp: SEXP) -> Self {
601        // Root before the length read, which can run an ALTREP callback.
602        let root = Preserved::new(sexp);
603        Self {
604            sexp,
605            len: sexp.xlength(),
606            _root: Some(root),
607            children: ChildRoots::default(),
608        }
609    }
610
611    /// Create a view without adding GC protection.
612    ///
613    /// Use this when the SEXP is already protected by R (e.g., a `.Call`
614    /// argument, or in a `ProtectScope`) for the handle's entire lifetime.
615    /// Avoids an additional preserved root.
616    ///
617    /// The lifetime-bound `&str` borrows are still enforced — this only
618    /// skips acquiring a root; the unsafe caller must supply it.
619    ///
620    /// # Safety
621    ///
622    /// - `sexp` must be a valid STRSXP.
623    /// - `sexp` must remain GC-protected for the lifetime of this struct.
624    /// - Must be called from the R main thread.
625    #[inline]
626    pub unsafe fn from_sexp_trusted(sexp: SEXP) -> Self {
627        Self {
628            sexp,
629            _root: None,
630            children: ChildRoots::default(),
631            len: sexp.xlength(),
632        }
633    }
634
635    /// Number of elements.
636    #[inline]
637    pub fn len(&self) -> isize {
638        self.len
639    }
640
641    /// Whether the vector is empty.
642    #[inline]
643    pub fn is_empty(&self) -> bool {
644        self.len == 0
645    }
646
647    /// Get the string at index (zero-copy, lifetime tied to `&self`).
648    ///
649    /// Returns `None` for out-of-bounds or `NA_character_`.
650    #[inline]
651    pub fn get_str(&self, idx: isize) -> Option<&str> {
652        self.as_strvec().get_str(idx)
653    }
654
655    /// Get the string at index as `Cow<str>` (encoding-safe, lifetime tied to `&self`).
656    #[inline]
657    pub fn get_cow(&self, idx: isize) -> Option<Cow<'_, str>> {
658        self.as_strvec().get_cow(idx)
659    }
660
661    /// Iterate over elements as `Option<&str>` (lifetime tied to `&self`).
662    #[inline]
663    pub fn iter(&self) -> ProtectedStrVecIter<'_> {
664        ProtectedStrVecIter {
665            vec: self,
666            idx: 0,
667            len: self.len,
668        }
669    }
670
671    /// Iterate over elements as `Option<Cow<str>>` (encoding-safe).
672    #[inline]
673    pub fn iter_cow(&self) -> ProtectedStrVecCowIter<'_> {
674        ProtectedStrVecCowIter {
675            vec: self,
676            idx: 0,
677            len: self.len,
678        }
679    }
680
681    /// Get the underlying SEXP (still protected by this handle).
682    #[inline]
683    pub fn as_sexp(&self) -> SEXP {
684        self.sexp
685    }
686
687    /// Get the inner `StrVec` view, leashed to `&self` (the protect guard).
688    #[inline]
689    pub fn as_strvec(&self) -> StrVec<'_> {
690        // The owned root (or from_sexp_trusted's caller) keeps the parent
691        // reachable; uncached children live in this owner's pool. Both outlive
692        // the borrowed view, without materializing or changing the source.
693        StrVec(self.sexp, Some(&self.children))
694    }
695}
696
697/// Iterator over `ProtectedStrVec` with lifetime tied to the protection guard.
698pub struct ProtectedStrVecIter<'a> {
699    vec: &'a ProtectedStrVec,
700    idx: isize,
701    len: isize,
702}
703
704impl<'a> Iterator for ProtectedStrVecIter<'a> {
705    type Item = Option<&'a str>;
706
707    #[inline]
708    fn next(&mut self) -> Option<Self::Item> {
709        if self.idx >= self.len {
710            return None;
711        }
712        let result = self.vec.get_str(self.idx);
713        self.idx += 1;
714        // get_str returns None for NA; we need to distinguish "end of iter" from "NA element"
715        // Wrap: Some(None) = NA, Some(Some(&str)) = value, None = end
716        Some(result)
717    }
718
719    #[inline]
720    fn size_hint(&self) -> (usize, Option<usize>) {
721        let remaining = (self.len - self.idx) as usize;
722        (remaining, Some(remaining))
723    }
724}
725
726impl ExactSizeIterator for ProtectedStrVecIter<'_> {}
727
728/// Encoding-safe iterator over `ProtectedStrVec`.
729pub struct ProtectedStrVecCowIter<'a> {
730    vec: &'a ProtectedStrVec,
731    idx: isize,
732    len: isize,
733}
734
735impl<'a> Iterator for ProtectedStrVecCowIter<'a> {
736    type Item = Option<Cow<'a, str>>;
737
738    #[inline]
739    fn next(&mut self) -> Option<Self::Item> {
740        if self.idx >= self.len {
741            return None;
742        }
743        let result = self.vec.get_cow(self.idx);
744        self.idx += 1;
745        Some(result)
746    }
747
748    #[inline]
749    fn size_hint(&self) -> (usize, Option<usize>) {
750        let remaining = (self.len - self.idx) as usize;
751        (remaining, Some(remaining))
752    }
753}
754
755impl ExactSizeIterator for ProtectedStrVecCowIter<'_> {}
756
757impl<'a> IntoIterator for &'a ProtectedStrVec {
758    type Item = Option<&'a str>;
759    type IntoIter = ProtectedStrVecIter<'a>;
760
761    #[inline]
762    fn into_iter(self) -> Self::IntoIter {
763        self.iter()
764    }
765}
766
767impl IntoR for ProtectedStrVec {
768    type Error = std::convert::Infallible;
769    fn try_into_sexp(self) -> Result<SEXP, Self::Error> {
770        Ok(self.as_sexp())
771    }
772    unsafe fn try_into_sexp_unchecked(self) -> Result<SEXP, Self::Error> {
773        Ok(self.as_sexp())
774    }
775    #[inline]
776    fn into_sexp(self) -> SEXP {
777        self.as_sexp()
778    }
779}
780
781impl TryFromSexp for ProtectedStrVec {
782    type Error = SexpError;
783    const CHARACTER_ONLY: bool = true;
784
785    fn try_from_sexp(sexp: SEXP) -> Result<Self, Self::Error> {
786        let actual = sexp.type_of();
787        if actual != STRSXP {
788            return Err(SexpTypeError {
789                expected: STRSXP,
790                actual,
791            }
792            .into());
793        }
794        // A raw conversion has no frame lifetime. Its result must own a root
795        // even when the input happens to be a .Call argument.
796        Ok(unsafe { ProtectedStrVec::new(sexp) })
797    }
798}
799
800impl std::fmt::Debug for ProtectedStrVec {
801    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
802        f.debug_struct("ProtectedStrVec")
803            .field("len", &self.len)
804            .finish()
805    }
806}
807// endregion