Skip to main content

BuiltList

Struct BuiltList 

Source
pub struct BuiltList {
    view: List,
    root: Preserved,
}
Expand description

An owned, GC-rooted R list: the plain-list finish of NamedListBuilder.

The list analogue of BuiltDataFrame: it holds a Preserved root for as long as it lives (!Send + !Sync), dereferences to the List view for reads, and returns to R through IntoR. set_class and set_attr allocate while the list stays rooted, and return the handle, so a chain is rooted at every link:

ⓘ
let out = columns.into_list().set_class(&["my_result", "list"]);
call_r_helper(out.as_sexp()); // `out` keeps the list alive across the call
out

A List copied out of the handle (*out) is an unrooted view: it stays valid only while the handle lives.

Fields§

§view: List§root: Preserved

Roots view’s list for as long as the handle lives.

Implementations§

Source§

impl BuiltList

Source

unsafe fn from_root(root: Preserved) -> Self

Take over an existing root of a list.

§Safety

root holds a VECSXP.

Source

pub fn set_class(self, classes: &[&str]) -> Self

Set the class attribute.

Source

pub fn set_attr(self, name: &str, value: impl IntoR) -> Self

Set the attribute name to value.

Methods from Deref<Target = List>§

Source

pub fn as_data_frame(&self) -> Result<BuiltDataFrame, DataFrameError>

Promote this named list to a DataFrame.

§Errors

Returns DataFrameError if the list has no names or columns differ in length.

Source

pub fn is_list(self) -> bool

Return true if the underlying SEXP is a list (VECSXP) according to R.

Uses SexpExt::is_list (VECSXP check) — not is_pair_list (LISTSXP).

Source

pub fn as_sexp(self) -> SEXP

Get the underlying SEXP.

Source

pub fn len(self) -> isize

Length of the list (number of elements).

Source

pub fn is_empty(self) -> bool

Returns true if the list is empty.

Source

pub fn get(self, idx: isize) -> Option<SEXP>

Get raw SEXP element at 0-based index. Returns None if out of bounds.

Source

pub fn get_index<T>(self, idx: isize) -> Option<T>
where T: TryFromSexp,

Get element at 0-based index and convert to type T.

Returns None if index is out of bounds or conversion fails.

The conversion error is discarded, so T’s TryFromSexp::Error is unconstrained — any element type works, not only those whose error is SexpError. Callers that need the error (e.g. to distinguish “missing” from “wrong type”) should use get and convert directly.

Source

fn text_names(self) -> impl Iterator<Item = (isize, &'static str)>

The names this list can be looked up by: (position, name) for each element whose name is neither NA nor invalid UTF-8, in list order. Empty names are included. Yields nothing when the list has no names attribute.

get_named_sexp, first_duplicate_name, NamedList and the #[derive(TryFromList)] field lookup all walk the names through this, so they agree on which names count.

The &strs point into R’s CHARSXP cache; they stay valid while the list (which roots its names attribute) is reachable.

Source

pub fn get_named_sexp(self, name: &str) -> Option<SEXP>

Get the raw element SEXP associated with name, without conversion.

Returns the element exactly as stored so callers can convert it with any TryFromSexp error type — not only those whose error is SexpError. Returns None when the list has no names attribute or no name matches.

When the name appears more than once, the first element with that name is returned, as R’s x[["name"]] does.

Source

pub fn first_duplicate_name(self) -> Option<String>

The first name that appears more than once in the list, if any.

An R list may repeat a name (list(a = 1, a = 2)), and a List argument accepts such a list, as R does. A function that needs each name to be unique checks for it itself, and words its own error:

use miniextendr_api::{List, miniextendr};

#[miniextendr]
pub fn settings_count(settings: List) -> i32 {
    if let Some(name) = settings.first_duplicate_name() {
        panic!("`settings` has the name {name:?} more than once; each entry needs a unique name");
    }
    settings.len() as i32
}

Only names that can identify an element are compared: NA and empty names are skipped (R lets any number of elements go unnamed), and so are names that are not valid UTF-8. Returns None for a list without a names attribute.

Source

#[doc(hidden)]
pub fn __mx_field_positions<const N: usize>( self, sorted_fields: [&str; N], ) -> Result<[Option<isize>; N], SexpError>

Positions of a derived struct’s fields, for the code #[derive(TryFromList)] generates. Not public API.

sorted_fields holds the struct’s field names in ascending byte order (the derive sorts them); entry k of the result is the position of the first element named sorted_fields[k], or None when no element has that name. One pass over the names, O(n log fields).

A field name that appears more than once is an error (SexpError::DuplicateName): the struct could only keep one of the values. Other repeated names are ignored, as names that are not fields are.

Source

pub fn get_named<T>(self, name: &str) -> Option<T>
where T: TryFromSexp,

Get element by name and convert to type T.

Returns None if name not found or conversion fails.

The conversion error is discarded, so T’s TryFromSexp::Error is unconstrained. Use get_named_sexp and convert directly when you need to inspect the conversion failure.

Source

fn get_attr_opt(self, name: SEXP) -> Option<SEXP>

Get an arbitrary attribute by symbol, returning None for R_NilValue.

Source

pub fn names(self) -> Option<SEXP>

Get the names attribute if present.

Source

pub fn get_class(self) -> Option<SEXP>

Get the class attribute if present.

Source

pub fn get_dim(self) -> Option<SEXP>

Get the dim attribute if present.

Source

pub fn get_dimnames(self) -> Option<SEXP>

Get the dimnames attribute if present.

Source

pub fn get_rownames(self) -> Option<SEXP>

Get row names from the dimnames attribute.

Source

pub fn get_colnames(self) -> Option<SEXP>

Get column names from the dimnames attribute.

Source

pub fn get_levels(self) -> Option<SEXP>

Get the levels attribute if present (for factors).

Source

pub fn get_tsp(self) -> Option<SEXP>

Get the tsp attribute if present (for time series).

Source

pub fn set_names(self, names: SEXP) -> Self

Set the names attribute; returns the same list for chaining.

Equivalent to R’s SET_NAMES(x, n).

Source

pub fn set_class(self, class: SEXP) -> Self

Set the class attribute; returns the same list for chaining.

Equivalent to R’s SET_CLASS(x, n).

Source

pub fn set_dim(self, dim: SEXP) -> Self

Set the dim attribute; returns the same list for chaining.

Equivalent to R’s SET_DIM(x, n).

Source

pub fn set_dimnames(self, dimnames: SEXP) -> Self

Set the dimnames attribute; returns the same list for chaining.

Equivalent to R’s SET_DIMNAMES(x, n).

Source

pub fn set_levels(self, levels: SEXP) -> Self

Set the levels attribute; returns the same list for chaining.

Equivalent to R’s SET_LEVELS(x, l).

Source

pub fn set_class_str(self, classes: &[&str]) -> Self

Set the class attribute from a slice of class names.

This is a convenience wrapper that creates a character vector from the provided strings and sets it as the class attribute.

§Example
ⓘ
let list = List::from_pairs(vec![("x", vec![1, 2, 3])]);
let df = list.set_class_str(&["data.frame"]);
Source

pub fn set_data_frame_class(self) -> Self

Set class = "data.frame" using a cached class STRSXP.

Equivalent to set_class_str(&["data.frame"]) but avoids allocation.

Source

pub fn set_names_str(self, names: &[&str]) -> Self

Set the names attribute from a slice of strings.

This is a convenience wrapper that creates a character vector from the provided strings and sets it as the names attribute.

§Example
ⓘ
let list = List::from_values(vec![1, 2, 3]);
let named = list.set_names_str(&["a", "b", "c"]);
Source

pub fn set_row_names_int(self, n: usize) -> Self

Set row.names for a data.frame using compact integer form.

R internally represents row.names as a compact integer vector c(NA_integer_, -n) when the row names are just 1:n. This is more memory-efficient than storing n strings.

§Example
ⓘ
let list = List::from_pairs(vec![
    ("x", vec![1, 2, 3]),
    ("y", vec![4, 5, 6]),
])
.set_class_str(&["data.frame"])
.set_row_names_int(3);  // Row names: "1", "2", "3"
Source

pub fn set_row_names_str(self, row_names: &[&str]) -> Self

Set row.names from a vector of strings.

Use this when you need custom row names. For simple sequential row names (1, 2, 3, …), use set_row_names_int instead.

§Example
ⓘ
let list = List::from_pairs(vec![
    ("x", vec![1, 2, 3]),
])
.set_class_str(&["data.frame"])
.set_row_names_str(&["row_a", "row_b", "row_c"]);
Source

pub unsafe fn set_elt(self, idx: isize, child: SEXP)

Set an element at the given index, protecting the child during insertion.

This is the safe way to insert a freshly allocated SEXP into a list. The child is protected for the duration of the SET_VECTOR_ELT call, ensuring it cannot be garbage collected.

§Safety
  • Must be called from the R main thread
  • child must be a valid SEXP
  • self must be a valid, protected VECSXP
§Panics

Panics if idx is out of bounds.

§Example
ⓘ
let scope = ProtectScope::new();
let list = List::from_raw(scope.alloc_vecsxp(n).into_raw());

for i in 0..n {
    let child = Rf_allocVector(REALSXP, 10);  // unprotected!
    list.set_elt(i, child);  // safe: protects child during insertion
}
Source

pub unsafe fn set_elt_unchecked(self, idx: isize, child: SEXP)

Set an element without protecting the child.

§Safety

In addition to the safety requirements of set_elt:

  • The caller must ensure child is already protected or that no GC can occur between child allocation and this call.

Use this for performance when you know the child is already protected (e.g., it’s a child of another protected container, or you have an OwnedProtect guard for it).

Source

pub unsafe fn set_elt_with<F>(self, idx: isize, f: F)
where F: FnOnce() -> SEXP,

Set an element using a callback that produces the child.

The callback is executed within a protection scope, so any allocations it performs are protected until insertion completes.

§Safety
  • Must be called from the R main thread
  • self must be a valid, protected VECSXP
§Example
ⓘ
let list = List::from_raw(scope.alloc_vecsxp(n).into_raw());

for i in 0..n {
    list.set_elt_with(i, || {
        let vec = Rf_allocVector(REALSXP, 10);
        fill_vector(vec);  // can allocate internally
        vec
    });
}

Trait Implementations§

Source§

impl Debug for BuiltList

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for BuiltList

Source§

type Target = List

The resulting type after dereferencing.
Source§

fn deref(&self) -> &List

Dereferences the value.
Source§

impl IntoR for BuiltList

Source§

type Error = !

The error type for fallible conversions. Read more
Source§

fn try_into_sexp(self) -> Result<SEXP, Self::Error>

Try to convert this value to an R SEXP. Read more
Source§

unsafe fn try_into_sexp_unchecked(self) -> Result<SEXP, Self::Error>

Try to convert to SEXP without thread safety checks. Read more
Source§

fn into_sexp(self) -> SEXP

Convert this value to an R SEXP, panicking on error. Read more
Source§

unsafe fn into_sexp_unchecked(self) -> SEXP
where Self: Sized,

Convert to SEXP without thread safety checks, panicking on error. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> RDebug for T
where T: Debug,

Source§

fn debug_str(&self) -> String

Get a compact debug string representation.
Source§

fn debug_str_pretty(&self) -> String

Get a pretty-printed debug string with indentation.
Source§

#[doc(hidden)]
unsafe extern "C" fn __RDebug_debug_str_shim( data: *mut c_void, argc: i32, argv: *const SEXP, ) -> SEXP
where Self: Sized + RDebug,

Method shim for RDebug::debug_str. Read more
Source§

#[doc(hidden)]
unsafe extern "C" fn __RDebug_debug_str_pretty_shim( data: *mut c_void, argc: i32, argv: *const SEXP, ) -> SEXP
where Self: Sized + RDebug,

Method shim for RDebug::debug_str_pretty. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> SizeHint for T
where T: ?Sized,

Source§

default fn lower_bound(&self) -> usize

🔬This is a nightly-only experimental API. (core_io_internals)
Returns a lower bound on the number of elements this container-like item contains. For example, an array [u8; 12] could return any value between 0 and 12 inclusively as a correct implementation. Read more
Source§

default fn upper_bound(&self) -> Option<usize>

🔬This is a nightly-only experimental API. (core_io_internals)
Returns an upper bound on the number of elements this container-like item contains if it can be determined, otherwise None. Read more
Source§

final fn size_hint(&self) -> (usize, Option<usize>)

🔬This is a nightly-only experimental API. (core_io_internals)
Returns an estimate for the number of elements this container like type contains. Read more
Source§

impl<T> SizedTypeProperties for T

Source§

#[doc(hidden)]
const SIZE: usize = _

🔬This is a nightly-only experimental API. (sized_type_properties)
Source§

#[doc(hidden)]
const ALIGN: usize = _

🔬This is a nightly-only experimental API. (sized_type_properties)
Source§

#[doc(hidden)]
const ALIGNMENT: Alignment = _

🔬This is a nightly-only experimental API. (ptr_alignment_type)
Source§

#[doc(hidden)]
const IS_ZST: bool = _

🔬This is a nightly-only experimental API. (sized_type_properties)
true if this type requires no storage. false if its size is greater than zero. Read more
Source§

#[doc(hidden)]
const LAYOUT: Layout = _

🔬This is a nightly-only experimental API. (sized_type_properties)
Source§

#[doc(hidden)]
const MAX_SLICE_LEN: usize = _

🔬This is a nightly-only experimental API. (sized_type_properties)
The largest safe length for a [Self]. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.

Layout§

Note: Most layout information is completely unstable and may even differ between compilations. The only exception is types with certain repr(...) attributes. Please see the Rust Reference's “Type Layout” chapter for details on type layout guarantees.

Size: 16 bytes