Skip to main content

miniextendr_api/externalptr/
snapshot.rs

1//! A saved value that comes back after `readRDS()` (#2186).
2//!
3//! R saves an external pointer without its address: `saveRDS()` writes the
4//! pointer's protection list and tag, and `readRDS()` gives back a pointer
5//! whose address is NULL. A type that is `Serialize + DeserializeOwned` (and
6//! built with miniextendr-api's `serde` feature) keeps its value in that list
7//! instead. The last element of its protection list is a carrier: a
8//! zero-length ALTREP raw vector of a class registered for the type at
9//! `R_init`. R itself calls the class's methods:
10//!
11//! - **`Serialized_state`**, during `serialize()`: the value encoded through
12//!   the crate's serde-to-R path in its exact mode (`serde/exact.rs`, #2256),
13//!   an R list the value comes back from unchanged. It
14//!   reads the value through [`ExternalPtr::borrow`], so a `serialize()` that
15//!   R code runs while a call holds the object mutably (a callback that saves
16//!   `self`) raises the `miniextendr_borrow_conflict` error instead of
17//!   reading a value under a `&mut`. A pointer without a value, or a value
18//!   serde can't encode, gives no state: R writes the empty vector itself,
19//!   and the reload is refused as before.
20//! - **`Unserialize`**, during `unserialize()`, which loads the package (and
21//!   so registers the class) first: decodes the state at once
22//!   (the same exact mode) and keeps the value, or the decoding error, in the
23//!   carrier. It never raises: a failure is kept for the first access.
24//!
25//! R reads the protection list before the pointer exists, so the value is
26//! attached at the pointer's first access ([`attach`]): a method receiver, an
27//! `ExternalPtr<T>` / `&T` / `&mut T` argument, or a sidecar accessor. A
28//! decoding failure is refused there as a restored pointer is, with the
29//! decoding error as `e$parent` ([`super::refuse_restored`]).
30//!
31//! The type opts in by being serde: `#[derive(ExternalPtr)]` emits a probe
32//! ([`SnapshotProbe`]) that resolves to the serde arm ([`SnapshotSerde`])
33//! when the type implements both traits and to the fallback
34//! ([`SnapshotNone`]) otherwise, which keeps the restored refusal. A type
35//! with a hand-written `TypedExternal` impl (the standard library types', or
36//! `impl_typed_external!`'s) has no probe and keeps the refusal (#2243).
37
38use std::any::Any;
39use std::cell::RefCell;
40use std::marker::PhantomData;
41use std::ptr::NonNull;
42use std::sync::OnceLock;
43
44use super::{
45    ExternalPtr, NullAddress, PROT_TYPE_ID_INDEX, PROT_USER_INDEX, PROT_VEC_LEN, TypedExternal,
46    classify_null_address, release_any, saved_identity, sidecar, split_type_id, type_id_str,
47    type_id_symbol,
48};
49use crate::altrep::RBase;
50use crate::altrep_traits::{AltVec, Altrep};
51use crate::condition::{ConditionCall, RCondition};
52use crate::gc_protect::ProtectScope;
53use crate::sys::altrep::R_altrep_class_t;
54use crate::sys::{
55    R_ExternalPtrAddr, R_ExternalPtrProtected, R_MakeExternalPtr, R_RegisterCFinalizerEx,
56    R_SetExternalPtrAddr, R_SetExternalPtrProtected, R_altrep_data1, R_altrep_data2,
57    R_set_altrep_data1, R_set_altrep_data2, Rf_allocVector,
58};
59use crate::{R_xlen_t, Rboolean, SEXP, SEXPTYPE, SexpExt};
60
61/// The class of the condition a failed decoding gives, the `e$parent` of the
62/// restored refusal: the message is serde's.
63pub const DECODE_ERROR_CLASS: &str = "miniextendr_decode_error";
64
65// region: The probe
66
67/// The carrier class of one type, registered at `R_init`. The derive emits
68/// one per type, in its `TypedExternal::__mx_snapshot`.
69#[doc(hidden)]
70pub struct SnapshotClass(OnceLock<R_altrep_class_t>);
71
72impl SnapshotClass {
73    /// A class not registered yet.
74    #[allow(clippy::new_without_default)]
75    pub const fn new() -> Self {
76        Self(OnceLock::new())
77    }
78}
79
80/// How a value of `T` goes into a save and comes back from one: its carrier
81/// class and the serde encoding. `T::__mx_snapshot()` gives it for a serde
82/// type.
83#[doc(hidden)]
84pub struct Snapshot<T> {
85    class: &'static SnapshotClass,
86    encode: fn(&T) -> Result<SEXP, String>,
87    decode: fn(SEXP) -> Result<T, String>,
88}
89
90impl<T> Clone for Snapshot<T> {
91    fn clone(&self) -> Self {
92        *self
93    }
94}
95
96impl<T> Copy for Snapshot<T> {}
97
98/// The receiver of the snapshot probe: the type's class cell. The derive
99/// calls `(&SnapshotProbe::<Self>::new(&CLASS)).__mx_snapshot()` with
100/// [`SnapshotSerde`] and [`SnapshotNone`] in scope, in the type's own
101/// `TypedExternal` impl, where the type is concrete.
102#[doc(hidden)]
103pub struct SnapshotProbe<T>(
104    // Read by the serde arm only.
105    #[cfg_attr(not(feature = "serde"), allow(dead_code))] &'static SnapshotClass,
106    PhantomData<fn() -> T>,
107);
108
109impl<T> SnapshotProbe<T> {
110    /// The probe for `T`, whose carrier class is `class`.
111    pub const fn new(class: &'static SnapshotClass) -> Self {
112        Self(class, PhantomData)
113    }
114}
115
116/// Snapshot probe, serde arm: `T: Serialize + DeserializeOwned`. This impl,
117/// on the probe taking `&self`, matches the receiver `&SnapshotProbe<T>` by
118/// value; [`SnapshotNone`] needs one more auto-ref and is reached only when
119/// `T` is not serde.
120///
121/// The trait exists without the `serde` feature so the generated `use`
122/// resolves; it then has no impl, and every type takes [`SnapshotNone`].
123#[doc(hidden)]
124pub trait SnapshotSerde {
125    /// The type probed.
126    type Value;
127    /// How a value goes into a save and comes back.
128    fn __mx_snapshot(&self) -> Option<Snapshot<Self::Value>>;
129}
130
131#[cfg(feature = "serde")]
132impl<T> SnapshotSerde for SnapshotProbe<T>
133where
134    T: TypedExternal + ::serde::Serialize + ::serde::de::DeserializeOwned,
135{
136    type Value = T;
137
138    fn __mx_snapshot(&self) -> Option<Snapshot<T>> {
139        Some(Snapshot {
140            class: self.0,
141            encode: |value| crate::serde::exact::to_r_exact(value).map_err(|e| e.to_string()),
142            decode: |state| crate::serde::exact::from_r_exact(state).map_err(|e| e.to_string()),
143        })
144    }
145}
146
147/// Snapshot probe, fallback arm: a type that is not serde has no snapshot,
148/// and a pointer to it restored from a saved session is refused.
149#[doc(hidden)]
150pub trait SnapshotNone {
151    /// The type probed.
152    type Value;
153    /// `None`.
154    fn __mx_snapshot(&self) -> Option<Snapshot<Self::Value>>;
155}
156
157impl<T> SnapshotNone for &SnapshotProbe<T> {
158    type Value = T;
159
160    fn __mx_snapshot(&self) -> Option<Snapshot<T>> {
161        None
162    }
163}
164
165/// Whether `T`'s protection list ends in a carrier slot.
166#[inline]
167pub(super) fn has_carrier_slot<T: TypedExternal>() -> bool {
168    T::__mx_snapshot().is_some()
169}
170
171// endregion
172
173// region: The carrier class
174
175/// The carrier ALTREP class of `T`: a zero-length raw vector whose
176/// `Serialized_state` encodes the value and whose `Unserialize` decodes it.
177///
178/// `data1` is the owning pointer while the value lives in it, and a holder
179/// ([`Decoded`]) from `Unserialize` until the first access attaches the
180/// value; `data2` is then the state that was read, which a save before the
181/// first access writes back unchanged.
182struct Carrier<T>(PhantomData<T>);
183
184impl<T: TypedExternal> Altrep for Carrier<T> {
185    fn length(_x: SEXP) -> R_xlen_t {
186        0
187    }
188
189    const HAS_SERIALIZED_STATE: bool = true;
190
191    fn serialized_state(x: SEXP) -> SEXP {
192        // SAFETY: an ALTREP method, on R's main thread, with a carrier of `T`.
193        unsafe { serialized_state::<T>(x) }
194    }
195
196    const HAS_UNSERIALIZE: bool = true;
197
198    fn unserialize(_class: SEXP, state: SEXP) -> SEXP {
199        // SAFETY: an ALTREP method, on R's main thread; `state` is rooted by
200        // R's reader.
201        unsafe { unserialize::<T>(state) }
202    }
203}
204
205impl<T: TypedExternal> AltVec for Carrier<T> {
206    // A zero-length vector's data is never read; R gives such vectors the
207    // pointer 0x1 too. Without these, R's defaults would raise on a
208    // `DATAPTR()` (a plain copy, a version-2 save).
209    const HAS_DATAPTR: bool = true;
210
211    fn dataptr(_x: SEXP, _writable: bool) -> *mut core::ffi::c_void {
212        NonNull::<u8>::dangling().as_ptr().cast()
213    }
214
215    const HAS_DATAPTR_OR_NULL: bool = true;
216
217    fn dataptr_or_null(_x: SEXP) -> *const core::ffi::c_void {
218        NonNull::<u8>::dangling().as_ptr().cast_const().cast()
219    }
220}
221
222/// The carrier class name of the type with ID `id`:
223/// `miniextendr_saved:<crate>::<Type>`, without the crate version or the
224/// module path ([`saved_identity`]), so a save by any version, or of a type
225/// since moved to another module, finds the class. A hand-written ID
226/// without a version is used whole.
227fn class_name_of(id: &str) -> String {
228    match saved_identity(id) {
229        Some((crate_name, _, name)) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr_saved:{0}::{1}",
                crate_name, name))
    })format!("miniextendr_saved:{crate_name}::{name}"),
230        None => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr_saved:{0}", id))
    })format!("miniextendr_saved:{id}"),
231    }
232}
233
234#[doc =
r" The carrier class names registered so far, each with the ID of the"]
#[doc =
r" type that registered it. Only `R_init`, on R's main thread, claims."]
const CLAIMED: ::std::thread::LocalKey<RefCell<Vec<(String, &'static str)>>> =
    {
        const __RUST_STD_INTERNAL_INIT: RefCell<Vec<(String, &'static str)>> =
            { RefCell::new(Vec::new()) };
        unsafe {
            ::std::thread::LocalKey::new(const {
                        if ::std::mem::needs_drop::<RefCell<Vec<(String,
                                    &'static str)>>>() {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::EagerStorage<RefCell<Vec<(String,
                                        &'static str)>>> =
                                        ::std::thread::local_impl::EagerStorage::new(__RUST_STD_INTERNAL_INIT);
                                    __RUST_STD_INTERNAL_VAL.get()
                                }
                        } else {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        RefCell<Vec<(String, &'static str)>> =
                                        __RUST_STD_INTERNAL_INIT;
                                    &__RUST_STD_INTERNAL_VAL
                                }
                        }
                    })
        }
    };thread_local! {
235    /// The carrier class names registered so far, each with the ID of the
236    /// type that registered it. Only `R_init`, on R's main thread, claims.
237    static CLAIMED: RefCell<Vec<(String, &'static str)>> = const { RefCell::new(Vec::new()) };
238}
239
240/// Claims the carrier class `name` for the type with ID `id`. Two serde
241/// types of one crate with the same name would share the class, and each
242/// would read the other's saves, so the second one is an error naming both
243/// types' paths. Claiming a name again for the same type is a no-op.
244fn claim(
245    claimed: &mut Vec<(String, &'static str)>,
246    name: &str,
247    id: &'static str,
248) -> Result<(), String> {
249    match claimed
250        .iter()
251        .find(|(claimed_name, _)| claimed_name == name)
252    {
253        Some(&(_, other)) if other != id => {
254            let path = |id| split_type_id(id).2;
255            Err(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("miniextendr: the serde `ExternalPtr` types `{0}` and `{1}` have the same name in one crate. A saved object is found by its crate and type name, so each would read the other\'s saves; rename one",
                path(other), path(id)))
    })format!(
256                "miniextendr: the serde `ExternalPtr` types `{}` and `{}` have the same name in \
257                 one crate. A saved object is found by its crate and type name, so each would \
258                 read the other's saves; rename one",
259                path(other),
260                path(id),
261            ))
262        }
263        Some(_) => Ok(()),
264        None => {
265            claimed.push((name.to_owned(), id));
266            Ok(())
267        }
268    }
269}
270
271/// Registers `T`'s carrier class when `T` is serde, once. The registration
272/// function `#[derive(ExternalPtr)]` emits for the type calls it from
273/// `R_init` (through `MX_ALTREP_REGISTRATIONS`).
274///
275/// # Panics
276///
277/// When another serde type of `T`'s crate with `T`'s name registered its
278/// class first (`claim`). `R_init` turns the panic into an R error, so the
279/// package does not load.
280#[doc(hidden)]
281pub fn register<T: TypedExternal>() {
282    let Some(snapshot) = T::__mx_snapshot() else {
283        return;
284    };
285    let id = type_id_str::<T>();
286    let name = class_name_of(id);
287    // Release the borrow before raising.
288    let claimed = CLAIMED.with_borrow_mut(|claimed| claim(claimed, &name, id));
289    if let Err(message) = claimed {
290        { ::core::panicking::panic_fmt(format_args!("{0}", message)); };panic!("{message}");
291    }
292    snapshot.class.0.get_or_init(|| {
293        let name = std::ffi::CString::new(name).expect("a type ID has no NUL byte");
294        // SAFETY: during `R_init`, after the package name and DLL are set.
295        let class = unsafe {
296            crate::altrep::make_class_by_base(
297                name.as_ptr(),
298                crate::AltrepPkgName::as_ptr(),
299                RBase::Raw,
300            )
301        };
302        // SAFETY: a fresh raw class.
303        unsafe {
304            crate::altrep_bridge::install_base::<Carrier<T>>(class);
305            crate::altrep_bridge::install_vec::<Carrier<T>>(class);
306        }
307        class
308    });
309}
310
311/// `T`'s registered carrier class, if `T` is serde and its class is
312/// registered (it is not while the wrappers are generated).
313fn carrier_class<T: TypedExternal>() -> Option<(Snapshot<T>, R_altrep_class_t)> {
314    let snapshot = T::__mx_snapshot()?;
315    let class = *snapshot.class.0.get()?;
316    Some((snapshot, class))
317}
318
319/// Puts a carrier for the value `owner` holds in the last slot of its new
320/// protection list. A construction site calls it after the address is set.
321///
322/// # Safety
323///
324/// On R's main thread, with `owner` a rooted pointer built for a `T` whose
325/// protection list is `prot_vec_len::<T>()` long.
326pub(super) unsafe fn init_carrier<T: TypedExternal>(owner: SEXP) {
327    let Some((_, class)) = carrier_class::<T>() else {
328        return;
329    };
330    // `R_new_altrep` protects its data while it allocates; the owner roots
331    // the protection list.
332    let carrier = unsafe { class.new_altrep(owner, SEXP::nil()) };
333    let prot = unsafe { R_ExternalPtrProtected(owner) };
334    prot.set_vector_elt(prot.xlength() - 1, carrier);
335}
336
337// endregion
338
339// region: Saving and reading back
340
341/// What `Unserialize` decoded: the value until the first access takes it, or
342/// the condition decoding raised. The holder pointer in the carrier's `data1`
343/// owns it, freed by the ordinary finalizer.
344type Decoded<T> = RefCell<Option<Result<T, RCondition>>>;
345
346/// The decoded value a holder pointer owns, when `holder` is one for `T`.
347///
348/// # Safety
349///
350/// On R's main thread with a valid `holder`.
351unsafe fn decoded<'a, T: TypedExternal>(holder: SEXP) -> Option<&'a Decoded<T>> {
352    if holder.type_of() != SEXPTYPE::EXTPTRSXP {
353        return None;
354    }
355    let any_raw = unsafe { R_ExternalPtrAddr(holder) }.cast::<Box<dyn Any>>();
356    if any_raw.is_null() {
357        return None;
358    }
359    unsafe { &*any_raw }.downcast_ref::<Decoded<T>>()
360}
361
362/// `Serialized_state`: the state of the carrier `x`.
363///
364/// # Safety
365///
366/// On R's main thread, with `x` a carrier of `T`.
367unsafe fn serialized_state<T: TypedExternal>(x: SEXP) -> SEXP {
368    let data1 = unsafe { R_altrep_data1(x) };
369    // Read back and not attached yet (or not decodable): save what was read.
370    if unsafe { decoded::<T>(data1) }.is_some() {
371        return unsafe { R_altrep_data2(x) };
372    }
373    let Some(snapshot) = T::__mx_snapshot() else {
374        return SEXP::null();
375    };
376    if data1.type_of() != SEXPTYPE::EXTPTRSXP {
377        return SEXP::null();
378    }
379    // SAFETY: on R's main thread with an EXTPTRSXP; the handle is borrowed,
380    // the carrier's owner roots the pointer.
381    let Some(ptr) = (unsafe { ExternalPtr::<T>::wrap_sexp(data1) }) else {
382        return SEXP::null();
383    };
384    // A running call holding the value mutably raises
385    // `miniextendr_borrow_conflict` here, which aborts the `serialize()`.
386    let value = ptr.borrow();
387    // A value serde can't encode: no state, so R writes the empty vector and
388    // the reload is refused, as before the type was serde.
389    (snapshot.encode)(&value).unwrap_or(SEXP::null())
390}
391
392/// `Unserialize`: decodes `state` into a holder and returns a carrier
393/// holding it. Never raises (only an R error from the type's own
394/// `Deserialize` code carries on).
395///
396/// # Safety
397///
398/// On R's main thread, during `unserialize()`, after `T`'s class was
399/// registered (R loads the package first); `state` is rooted.
400unsafe fn unserialize<T: TypedExternal>(state: SEXP) -> SEXP {
401    let (snapshot, class) =
402        carrier_class::<T>().expect("R unserializes a carrier only after its class is registered");
403    let decoded: Decoded<T> = RefCell::new(Some(decode(snapshot.decode, state)));
404    let inner: Box<dyn Any> = Box::new(decoded);
405    let any_raw = Box::into_raw(Box::new(inner));
406    // Own the allocation until the finalizer that frees it is registered.
407    let allocation = unsafe { Box::from_raw(any_raw) };
408    let scope = unsafe { ProtectScope::new() };
409    let holder = unsafe { R_MakeExternalPtr(std::ptr::null_mut(), SEXP::nil(), SEXP::nil()) };
410    unsafe { scope.protect(holder) };
411    unsafe { R_RegisterCFinalizerEx(holder, Some(release_any), Rboolean::TRUE) };
412    let any_raw = Box::into_raw(allocation);
413    unsafe { R_SetExternalPtrAddr(holder, any_raw.cast()) };
414    unsafe { class.new_altrep(holder, state) }
415}
416
417/// Decodes `state`, catching a panic: an `RCondition` as itself, any other
418/// as a [`DECODE_ERROR_CLASS`] condition with its message. An R error keeps
419/// unwinding: its jump belongs to R (#2244).
420fn decode<T>(decode: fn(SEXP) -> Result<T, String>, state: SEXP) -> Result<T, RCondition> {
421    let decoding_failed = |message: String| RCondition::Error {
422        message,
423        class: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [DECODE_ERROR_CLASS.to_owned()]))vec![DECODE_ERROR_CLASS.to_owned()],
424        data: None,
425        call: ConditionCall::None,
426    };
427    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| decode(state))) {
428        Ok(Ok(value)) => Ok(value),
429        Ok(Err(message)) => Err(decoding_failed(message)),
430        Err(payload) if payload.is::<crate::unwind_protect::RUnwind>() => {
431            std::panic::resume_unwind(payload)
432        }
433        Err(payload) => match payload.downcast::<RCondition>() {
434            Ok(condition) => Err(*condition),
435            Err(payload) => Err(decoding_failed(
436                crate::unwind_protect::panic_payload_to_string(&*payload).into_owned(),
437            )),
438        },
439    }
440}
441
442// endregion
443
444// region: Attaching at first access
445
446/// What [`attach`] did with a pointer without an address.
447pub(crate) enum Attach {
448    /// The decoded value is in the pointer now.
449    Attached,
450    /// The save could not be decoded; the pointer stays without a value.
451    Failed,
452    /// No carrier of `T`: not a serde type, a save without one (a version-2
453    /// save, one read where the package was missing), or not a save of `T`.
454    NoCarrier,
455}
456
457/// The carrier of `sexp`'s saved protection list, and what it decoded, when
458/// `sexp` is a save of `T` with one.
459///
460/// # Safety
461///
462/// On R's main thread, with `sexp` a valid `EXTPTRSXP` without an address.
463unsafe fn saved_carrier<'a, T: TypedExternal>(sexp: SEXP) -> Option<(SEXP, &'a Decoded<T>)> {
464    let (_, class) = carrier_class::<T>()?;
465    if !#[allow(non_exhaustive_omitted_patterns)] match unsafe {
        classify_null_address::<T>(sexp)
    } {
    NullAddress::Restored | NullAddress::OtherVersion { .. } => true,
    _ => false,
}matches!(
466        unsafe { classify_null_address::<T>(sexp) },
467        NullAddress::Restored | NullAddress::OtherVersion { .. }
468    ) {
469        return None;
470    }
471    let saved = unsafe { R_ExternalPtrProtected(sexp) };
472    let len = saved.xlength();
473    if saved.type_of() != SEXPTYPE::VECSXP || len <= PROT_VEC_LEN {
474        return None;
475    }
476    let carrier = saved.vector_elt(len - 1);
477    if !unsafe { class.inherits(carrier) } {
478        return None;
479    }
480    let decoded = unsafe { decoded::<T>(R_altrep_data1(carrier)) }?;
481    Some((carrier, decoded))
482}
483
484/// The condition decoding `sexp`'s save raised, when `T` is serde and the
485/// save carries a value it could not decode.
486///
487/// # Safety
488///
489/// As [`saved_carrier`].
490pub(crate) unsafe fn decode_failure<T: TypedExternal>(sexp: SEXP) -> Option<RCondition> {
491    let (_, decoded) = unsafe { saved_carrier::<T>(sexp) }?;
492    match &*decoded.borrow() {
493        Some(Err(cause)) => Some(cause.clone()),
494        _ => None,
495    }
496}
497
498/// Gives `sexp`, a pointer without an address, the value its save decoded,
499/// when `T` is serde and the save carries one (#2186): the first access of a
500/// pointer `readRDS()` gave back. Raises nothing: a failure stays in the
501/// carrier, for the caller's refusal ([`super::refuse_restored`]) to name as
502/// `e$parent`.
503///
504/// The pointer gets a protection list in this version's layout, as a save by
505/// any version of the crate is attached: its type ID and slot names, the
506/// saved user slot, for each `Sidecar` field the saved slot of its R name
507/// (#2187) or else the decoded value's pending value (`#[serde(skip)]` gives
508/// the field's `Default`), and the carrier, which holds the pointer from now
509/// on.
510///
511/// # Safety
512///
513/// On R's main thread, with `sexp` a valid `EXTPTRSXP` without an address,
514/// rooted for the call.
515#[cold]
516pub(crate) unsafe fn attach<T: TypedExternal>(sexp: SEXP) -> Attach {
517    let Some((carrier, decoded)) = (unsafe { saved_carrier::<T>(sexp) }) else {
518        return Attach::NoCarrier;
519    };
520    let value = {
521        let mut slot = decoded.borrow_mut();
522        match slot.take() {
523            Some(Ok(value)) => value,
524            failed @ Some(Err(_)) => {
525                *slot = failed;
526                return Attach::Failed;
527            }
528            None => return Attach::NoCarrier,
529        }
530    };
531    unsafe { install::<T>(sexp, carrier, value) };
532    Attach::Attached
533}
534
535/// Puts `value` in `sexp`, as construction puts a new value in a new pointer
536/// (the finalizer first, then the address), with the protection list
537/// [`attach`] describes.
538///
539/// # Safety
540///
541/// As [`attach`]; `carrier` is the last element of `sexp`'s saved list.
542unsafe fn install<T: TypedExternal>(sexp: SEXP, carrier: SEXP, value: T) {
543    let saved = unsafe { R_ExternalPtrProtected(sexp) };
544    let scope = unsafe { ProtectScope::new() };
545    // Detached from `sexp` below, the saved list stays rooted by the scope
546    // while its slots are read.
547    unsafe { scope.protect(saved) };
548    let prot = unsafe { Rf_allocVector(SEXPTYPE::VECSXP, super::prot_vec_len::<T>()) };
549    unsafe { scope.protect(prot) };
550    prot.set_vector_elt(PROT_TYPE_ID_INDEX, unsafe { type_id_symbol::<T>() });
551    prot.set_vector_elt(PROT_USER_INDEX, saved.vector_elt(PROT_USER_INDEX));
552    if T::R_SLOT_COUNT > 0 {
553        unsafe { sidecar::name_slots::<T>(prot) };
554    }
555    unsafe { R_SetExternalPtrProtected(sexp, prot) };
556    // A field the save has a slot for keeps it; the others take the decoded
557    // value's pending value, rooted until the slot holds it (#2216).
558    value.__mx_visit_sidecars(
559        &mut |index, name, field| match saved_field_slot(saved, index, name) {
560            Some(at) => prot.set_vector_elt(sidecar::prot_index(index), saved.vector_elt(at)),
561            None => field.__mx_flush(prot, index),
562        },
563    );
564    sidecar::discard_pending_sidecars(&value);
565    prot.set_vector_elt(prot.xlength() - 1, carrier);
566    unsafe { R_set_altrep_data1(carrier, sexp) };
567    unsafe { R_set_altrep_data2(carrier, SEXP::nil()) };
568
569    let (_, any_raw) = ExternalPtr::<T>::erase(value);
570    // Own the allocation until the finalizer that frees it is registered.
571    let allocation = unsafe { Box::from_raw(any_raw) };
572    unsafe { R_RegisterCFinalizerEx(sexp, super::finalizer::<T>(), Rboolean::TRUE) };
573    let any_raw = Box::into_raw(allocation);
574    unsafe { R_SetExternalPtrAddr(sexp, any_raw.cast()) };
575}
576
577/// The position in the saved list `saved` of `Sidecar` field `index`, named
578/// `name`: by name ([`sidecar::saved_slot`]), or, in a list without slot
579/// names (a version whose type had no `Sidecar` field), by position, short
580/// of the carrier in the last slot.
581fn saved_field_slot(saved: SEXP, index: usize, name: &str) -> Option<R_xlen_t> {
582    if sidecar::has_slot_names(saved) {
583        sidecar::saved_slot(saved, index, name)
584    } else {
585        Some(sidecar::prot_index(index)).filter(|&at| at < saved.xlength() - 1)
586    }
587}
588
589// endregion
590
591#[cfg(test)]
592mod tests;