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).
3738use std::any::Any;
39use std::cell::RefCell;
40use std::marker::PhantomData;
41use std::ptr::NonNull;
42use std::sync::OnceLock;
4344use super::{
45ExternalPtr, NullAddress, PROT_TYPE_ID_INDEX, PROT_USER_INDEX, PROT_VEC_LEN, TypedExternal,
46classify_null_address, release_any, saved_identity, sidecar, split_type_id, type_id_str,
47type_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::{
55R_ExternalPtrAddr, R_ExternalPtrProtected, R_MakeExternalPtr, R_RegisterCFinalizerEx,
56R_SetExternalPtrAddr, R_SetExternalPtrProtected, R_altrep_data1, R_altrep_data2,
57R_set_altrep_data1, R_set_altrep_data2, Rf_allocVector,
58};
59use crate::{R_xlen_t, Rboolean, SEXP, SEXPTYPE, SexpExt};
6061/// 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";
6465// region: The probe
6667/// 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>);
7172impl SnapshotClass {
73/// A class not registered yet.
74#[allow(clippy::new_without_default)]
75pub const fn new() -> Self {
76Self(OnceLock::new())
77 }
78}
7980/// 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}
8990impl<T> Clonefor Snapshot<T> {
91fn clone(&self) -> Self {
92*self93 }
94}
9596impl<T> Copyfor Snapshot<T> {}
9798/// 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,
106PhantomData<fn() -> T>,
107);
108109impl<T> SnapshotProbe<T> {
110/// The probe for `T`, whose carrier class is `class`.
111pub const fn new(class: &'static SnapshotClass) -> Self {
112Self(class, PhantomData)
113 }
114}
115116/// 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.
126type Value;
127/// How a value goes into a save and comes back.
128fn __mx_snapshot(&self) -> Option<Snapshot<Self::Value>>;
129}
130131#[cfg(feature = "serde")]
132impl<T> SnapshotSerde for SnapshotProbe<T>
133where
134T: TypedExternal + ::serde::Serialize + ::serde::de::DeserializeOwned,
135{
136type Value = T;
137138fn __mx_snapshot(&self) -> Option<Snapshot<T>> {
139Some(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}
146147/// 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.
152type Value;
153/// `None`.
154fn __mx_snapshot(&self) -> Option<Snapshot<Self::Value>>;
155}
156157impl<T> SnapshotNonefor &SnapshotProbe<T> {
158type Value = T;
159160fn __mx_snapshot(&self) -> Option<Snapshot<T>> {
161None162 }
163}
164165/// 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}
170171// endregion
172173// region: The carrier class
174175/// 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>);
183184impl<T: TypedExternal> Altrepfor Carrier<T> {
185fn length(_x: SEXP) -> R_xlen_t {
1860
187}
188189const HAS_SERIALIZED_STATE: bool = true;
190191fn serialized_state(x: SEXP) -> SEXP {
192// SAFETY: an ALTREP method, on R's main thread, with a carrier of `T`.
193unsafe { serialized_state::<T>(x) }
194 }
195196const HAS_UNSERIALIZE: bool = true;
197198fn unserialize(_class: SEXP, state: SEXP) -> SEXP {
199// SAFETY: an ALTREP method, on R's main thread; `state` is rooted by
200 // R's reader.
201unsafe { unserialize::<T>(state) }
202 }
203}
204205impl<T: TypedExternal> AltVecfor 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).
209const HAS_DATAPTR: bool = true;
210211fn dataptr(_x: SEXP, _writable: bool) -> *mut core::ffi::c_void {
212NonNull::<u8>::dangling().as_ptr().cast()
213 }
214215const HAS_DATAPTR_OR_NULL: bool = true;
216217fn dataptr_or_null(_x: SEXP) -> *const core::ffi::c_void {
218NonNull::<u8>::dangling().as_ptr().cast_const().cast()
219 }
220}
221222/// 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 {
228match saved_identity(id) {
229Some((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}"),
230None => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("miniextendr_saved:{0}", id))
})format!("miniextendr_saved:{id}"),
231 }
232}
233234#[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.
237static CLAIMED: RefCell<Vec<(String, &'static str)>> = const { RefCell::new(Vec::new()) };
238}239240/// 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> {
249match claimed250 .iter()
251 .find(|(claimed_name, _)| claimed_name == name)
252 {
253Some(&(_, other)) if other != id => {
254let path = |id| split_type_id(id).2;
255Err(::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 }
263Some(_) => Ok(()),
264None => {
265claimed.push((name.to_owned(), id));
266Ok(())
267 }
268 }
269}
270271/// 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>() {
282let Some(snapshot) = T::__mx_snapshot() else {
283return;
284 };
285let id = type_id_str::<T>();
286let name = class_name_of(id);
287// Release the borrow before raising.
288let claimed = CLAIMED.with_borrow_mut(|claimed| claim(claimed, &name, id));
289if let Err(message) = claimed {
290{ ::core::panicking::panic_fmt(format_args!("{0}", message)); };panic!("{message}");
291 }
292snapshot.class.0.get_or_init(|| {
293let 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.
295let class = unsafe {
296crate::altrep::make_class_by_base(
297name.as_ptr(),
298crate::AltrepPkgName::as_ptr(),
299 RBase::Raw,
300 )
301 };
302// SAFETY: a fresh raw class.
303unsafe {
304crate::altrep_bridge::install_base::<Carrier<T>>(class);
305crate::altrep_bridge::install_vec::<Carrier<T>>(class);
306 }
307class308 });
309}
310311/// `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)> {
314let snapshot = T::__mx_snapshot()?;
315let class = *snapshot.class.0.get()?;
316Some((snapshot, class))
317}
318319/// 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) {
327let Some((_, class)) = carrier_class::<T>() else {
328return;
329 };
330// `R_new_altrep` protects its data while it allocates; the owner roots
331 // the protection list.
332let carrier = unsafe { class.new_altrep(owner, SEXP::nil()) };
333let prot = unsafe { R_ExternalPtrProtected(owner) };
334prot.set_vector_elt(prot.xlength() - 1, carrier);
335}
336337// endregion
338339// region: Saving and reading back
340341/// 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>>>;
345346/// 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>> {
352if holder.type_of() != SEXPTYPE::EXTPTRSXP {
353return None;
354 }
355let any_raw = unsafe { R_ExternalPtrAddr(holder) }.cast::<Box<dyn Any>>();
356if any_raw.is_null() {
357return None;
358 }
359unsafe { &*any_raw }.downcast_ref::<Decoded<T>>()
360}
361362/// `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 {
368let data1 = unsafe { R_altrep_data1(x) };
369// Read back and not attached yet (or not decodable): save what was read.
370if unsafe { decoded::<T>(data1) }.is_some() {
371return unsafe { R_altrep_data2(x) };
372 }
373let Some(snapshot) = T::__mx_snapshot() else {
374return SEXP::null();
375 };
376if data1.type_of() != SEXPTYPE::EXTPTRSXP {
377return 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.
381let Some(ptr) = (unsafe { ExternalPtr::<T>::wrap_sexp(data1) }) else {
382return SEXP::null();
383 };
384// A running call holding the value mutably raises
385 // `miniextendr_borrow_conflict` here, which aborts the `serialize()`.
386let 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}
391392/// `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 {
401let (snapshot, class) =
402carrier_class::<T>().expect("R unserializes a carrier only after its class is registered");
403let decoded: Decoded<T> = RefCell::new(Some(decode(snapshot.decode, state)));
404let inner: Box<dyn Any> = Box::new(decoded);
405let any_raw = Box::into_raw(Box::new(inner));
406// Own the allocation until the finalizer that frees it is registered.
407let allocation = unsafe { Box::from_raw(any_raw) };
408let scope = unsafe { ProtectScope::new() };
409let holder = unsafe { R_MakeExternalPtr(std::ptr::null_mut(), SEXP::nil(), SEXP::nil()) };
410unsafe { scope.protect(holder) };
411unsafe { R_RegisterCFinalizerEx(holder, Some(release_any), Rboolean::TRUE) };
412let any_raw = Box::into_raw(allocation);
413unsafe { R_SetExternalPtrAddr(holder, any_raw.cast()) };
414unsafe { class.new_altrep(holder, state) }
415}
416417/// 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> {
421let decoding_failed = |message: String| RCondition::Error {
422message,
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 };
427match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| decode(state))) {
428Ok(Ok(value)) => Ok(value),
429Ok(Err(message)) => Err(decoding_failed(message)),
430Err(payload) if payload.is::<crate::unwind_protect::RUnwind>() => {
431 std::panic::resume_unwind(payload)
432 }
433Err(payload) => match payload.downcast::<RCondition>() {
434Ok(condition) => Err(*condition),
435Err(payload) => Err(decoding_failed(
436crate::unwind_protect::panic_payload_to_string(&*payload).into_owned(),
437 )),
438 },
439 }
440}
441442// endregion
443444// region: Attaching at first access
445446/// What [`attach`] did with a pointer without an address.
447pub(crate) enum Attach {
448/// The decoded value is in the pointer now.
449Attached,
450/// The save could not be decoded; the pointer stays without a value.
451Failed,
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`.
454NoCarrier,
455}
456457/// 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>)> {
464let (_, class) = carrier_class::<T>()?;
465if !#[allow(non_exhaustive_omitted_patterns)] match unsafe {
classify_null_address::<T>(sexp)
} {
NullAddress::Restored | NullAddress::OtherVersion { .. } => true,
_ => false,
}matches!(
466unsafe { classify_null_address::<T>(sexp) },
467 NullAddress::Restored | NullAddress::OtherVersion { .. }
468 ) {
469return None;
470 }
471let saved = unsafe { R_ExternalPtrProtected(sexp) };
472let len = saved.xlength();
473if saved.type_of() != SEXPTYPE::VECSXP || len <= PROT_VEC_LEN {
474return None;
475 }
476let carrier = saved.vector_elt(len - 1);
477if !unsafe { class.inherits(carrier) } {
478return None;
479 }
480let decoded = unsafe { decoded::<T>(R_altrep_data1(carrier)) }?;
481Some((carrier, decoded))
482}
483484/// 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> {
491let (_, decoded) = unsafe { saved_carrier::<T>(sexp) }?;
492match &*decoded.borrow() {
493Some(Err(cause)) => Some(cause.clone()),
494_ => None,
495 }
496}
497498/// 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 {
517let Some((carrier, decoded)) = (unsafe { saved_carrier::<T>(sexp) }) else {
518return Attach::NoCarrier;
519 };
520let value = {
521let mut slot = decoded.borrow_mut();
522match slot.take() {
523Some(Ok(value)) => value,
524 failed @ Some(Err(_)) => {
525*slot = failed;
526return Attach::Failed;
527 }
528None => return Attach::NoCarrier,
529 }
530 };
531unsafe { install::<T>(sexp, carrier, value) };
532 Attach::Attached533}
534535/// 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) {
543let saved = unsafe { R_ExternalPtrProtected(sexp) };
544let scope = unsafe { ProtectScope::new() };
545// Detached from `sexp` below, the saved list stays rooted by the scope
546 // while its slots are read.
547unsafe { scope.protect(saved) };
548let prot = unsafe { Rf_allocVector(SEXPTYPE::VECSXP, super::prot_vec_len::<T>()) };
549unsafe { scope.protect(prot) };
550prot.set_vector_elt(PROT_TYPE_ID_INDEX, unsafe { type_id_symbol::<T>() });
551prot.set_vector_elt(PROT_USER_INDEX, saved.vector_elt(PROT_USER_INDEX));
552if T::R_SLOT_COUNT > 0 {
553unsafe { sidecar::name_slots::<T>(prot) };
554 }
555unsafe { 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).
558value.__mx_visit_sidecars(
559&mut |index, name, field| match saved_field_slot(saved, index, name) {
560Some(at) => prot.set_vector_elt(sidecar::prot_index(index), saved.vector_elt(at)),
561None => field.__mx_flush(prot, index),
562 },
563 );
564 sidecar::discard_pending_sidecars(&value);
565prot.set_vector_elt(prot.xlength() - 1, carrier);
566unsafe { R_set_altrep_data1(carrier, sexp) };
567unsafe { R_set_altrep_data2(carrier, SEXP::nil()) };
568569let (_, any_raw) = ExternalPtr::<T>::erase(value);
570// Own the allocation until the finalizer that frees it is registered.
571let allocation = unsafe { Box::from_raw(any_raw) };
572unsafe { R_RegisterCFinalizerEx(sexp, super::finalizer::<T>(), Rboolean::TRUE) };
573let any_raw = Box::into_raw(allocation);
574unsafe { R_SetExternalPtrAddr(sexp, any_raw.cast()) };
575}
576577/// 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> {
582if sidecar::has_slot_names(saved) {
583 sidecar::saved_slot(saved, index, name)
584 } else {
585Some(sidecar::prot_index(index)).filter(|&at| at < saved.xlength() - 1)
586 }
587}
588589// endregion
590591#[cfg(test)]
592mod tests;