Skip to main content

miniextendr_api/externalptr/
sidecar.rs

1//! Typed sidecar fields: [`Sidecar<T>`] keeps a Rust-typed value in the
2//! external pointer's `prot` list.
3//!
4//! A Rust struct cannot root an R value: the GC doesn't trace Rust memory, so
5//! a `SEXP` stored in a struct field is freed as soon as R drops its own
6//! references. A `Sidecar<T>` field holds no data of its own once the struct
7//! is wrapped. Its value lives in the external pointer's protection list,
8//! after the type ID and the user slot, so the pointer roots it for as long as
9//! the pointer is reachable, and `saveRDS()` writes it with the pointer. The
10//! struct holds nothing that points back at its pointer: the value is read
11//! and written through the `ExternalPtr<T>` handle, which keeps the pointer
12//! alive for as long as it exists (#1856).
13//!
14//! The type is named in one place (this module) and re-exported from
15//! [`crate::externalptr`]; its final name is #1857.
16
17use std::any::{Any, TypeId};
18use std::cell::{Ref, RefCell, RefMut};
19use std::collections::HashMap;
20use std::fmt;
21use std::marker::PhantomData;
22use std::rc::Rc;
23
24use super::{
25    NO_HANDLE_CLASS, PROT_TYPE_ID_INDEX, PROT_VEC_LEN, TypedExternal, receiver_class,
26    refuse_restored, unwrap_class_handle,
27};
28use crate::condition::{ConditionCall, RCondition};
29use crate::from_r::TryFromSexp;
30use crate::into_r::IntoR;
31use crate::sys::{R_ExternalPtrAddr, R_ExternalPtrProtected};
32use crate::{R_xlen_t, SEXP, SEXPTYPE, SexpExt};
33
34// region: Sidecar<T>
35
36/// A sidecar field whose value R roots: it lives in the external pointer's
37/// protection list, typed as `T` on the Rust side.
38///
39/// Declare it as `#[r_data] pub keys: Sidecar<Vec<i32>>` on a
40/// `#[derive(ExternalPtr)]` struct. The derive generates accessors as
41/// associated functions of the struct, with the field's visibility. They take
42/// an owner handle, which keeps the pointer alive, not the struct:
43///
44/// | `#[r_data(...)]` | Rust accessors |
45/// |---|---|
46/// | `ref` | `fn keys(ptr: &impl SidecarOwner<Self>) -> T` |
47/// | `mut` | `fn set_keys(ptr: &mut impl SidecarOwnerMut<Self>, value: T)` |
48/// | `ref, mut`, or a bare `#[r_data]` | both |
49///
50/// Rust code sees no `SEXP`s, slot indices or other R plumbing: a plain
51/// `fn new() -> Self` constructor fills the field with [`Sidecar::new`], and
52/// a method that needs the value takes a view as its receiver
53/// (`self: ExternalPtrRef<'_, Self>` / `mut self: ExternalPtrMut<'_, Self>`)
54/// and calls `Self::keys(&self)` / `Self::set_keys(&mut self, v)`; other Rust
55/// code writes `Engine::keys(&ptr)`. The R side keeps its own accessors whatever the
56/// option: for a `pub` field, `Type_get_keys(x)` / `Type_set_keys(x, value)`,
57/// an R6 active binding (`r6(r_data_accessors)`), an S7 property
58/// (`s7(r_data_accessors)`), or `x$keys` / `x$keys <- value` on an S3, S4 or
59/// env class (`s3(r_data_accessors)` & co.). The R setter validates the new
60/// value with `TryFromSexp::<T>` and stores the value R gave.
61///
62/// ```ignore
63/// #[derive(ExternalPtr)]
64/// #[externalptr(r6)]
65/// pub struct Engine {
66///     n: i32,
67///     #[r_data] _r: RSidecar,
68///     #[r_data(ref, mut)] pub keys: Sidecar<Vec<i32>>,
69///     #[r_data(ref)] pub labels: Sidecar<Vec<String>>,
70///     #[r_data(ref, mut)] cache: Sidecar<Option<List>>,
71/// }
72///
73/// #[miniextendr(r6(r_data_accessors))]
74/// impl Engine {
75///     pub fn new(n: i32) -> Self {
76///         Engine {
77///             n,
78///             _r: RSidecar,
79///             keys: Sidecar::new((1..=n).collect()),
80///             labels: Sidecar::new(vec![]),
81///             cache: Sidecar::default(),
82///         }
83///     }
84///     pub fn key_count(self: ExternalPtrRef<'_, Self>) -> usize { Self::keys(&self).len() }
85///     pub fn remember(mut self: ExternalPtrMut<'_, Self>, value: List) {
86///         Self::set_cache(&mut self, Some(value))
87///     }
88/// }
89///
90/// // From any other Rust code holding the handle:
91/// let mut ptr = ExternalPtr::new(Engine::new(3));
92/// Engine::set_keys(&mut ptr, vec![9]);
93/// assert_eq!(Engine::keys(&ptr), vec![9]);
94/// ```
95///
96/// The accessors take [`super::ExternalPtrRef`] / [`super::ExternalPtrMut`]
97/// views (receivers, arguments, `borrow()` / `borrow_mut()`) or an
98/// `ExternalPtr`, which they borrow for the call: shared for the getter,
99/// exclusive for the setter. A plain `&self` receiver has no route back to
100/// an R owner.
101///
102/// # Values
103///
104/// - `T: IntoR + TryFromSexp`, with `T::Error: Display` for the getter's panic
105///   message.
106/// - A getter converts the slot with `TryFromSexp`, so a converting type
107///   (`Vec<i32>`, `String`) copies on every read. A conversion failure is a
108///   panic naming the field and the type; the framework turns it into an R
109///   error.
110/// - `Sidecar<SEXP>`, `Sidecar<List>` and `Sidecar<DataFrame>` keep an
111///   arbitrary R object unconverted. The getter returns a view that the slot
112///   roots only until the next write to that field; don't hold it across one.
113/// - [`Sidecar::new`] converts its value with `IntoR` at once and roots the
114///   R object it gives until a slot holds it (#2216). A fresh `SEXP` or list
115///   passed to it is safe from that moment; it needs its own protection only
116///   before the call.
117///
118/// # Lifecycle
119///
120/// - **Pending.** [`Sidecar::new(v)`](Sidecar::new) and [`Default`]
121///   (`Sidecar::new(T::default())`) convert `v` to its R object and hold it
122///   as a pending value in the struct, rooted in a main-thread pool until a
123///   slot holds it or the last copy drops. That is the only state a `Sidecar`
124///   has: before the struct is wrapped, after `*ptr = Engine::new(..)`, after
125///   `ExternalPtr::into_inner`. They run on R's main thread; any other
126///   thread panics. A `Sidecar` is `!Send`, so a pending value, and the
127///   struct holding it, stays on R's main thread, where its last copy drops.
128/// - **Flushed when wrapped.** `ExternalPtr::new` and the trait ABI's `mx_wrap`
129///   move every pending value into the pointer's protection list. From then
130///   on the value lives in R only, and the field is empty.
131/// - **Flushed on every access to the field.** The handle getter and setter,
132///   and the R getter and setter, first move that field's pending value into
133///   its slot (the setters drop it: the write supersedes it). So
134///   `*ptr.borrow_mut() = Engine::new(..)` or
135///   `ptr.borrow_mut().keys = Sidecar::new(v)` takes effect at the next
136///   access from either side. A
137///   `saveRDS()` before any access writes the old slot value.
138/// - **Loaded when the value leaves its pointer.** `ExternalPtr::into_inner`
139///   and `into_raw` read each slot of the pointer being consumed back into its
140///   field as a pending value (unless one is pending already), rooted as a
141///   new one is, so wrapping the value again keeps the values.
142/// - **A `self -> Self` method** leaves the values in the pointer across the
143///   call; the write-back flushes only what the method set with
144///   `Sidecar::new`. `Self { n: .., ..self }` keeps the values,
145///   `Self::new(..)` replaces them.
146/// - **Clone.** `Sidecar::clone` shares the pending R object and its root,
147///   which is none once the struct is wrapped. `ExternalPtr::clone` and
148///   `clone_from` copy the slot values as R objects, so the two pointers
149///   share them until one side writes the field: every write replaces the
150///   slot, and R copies a shared value before modifying it in place. A struct
151///   cloned outside its handle carries no sidecar values; clone the handle.
152/// - **`*ptr = new` and `mem::swap(&mut *a, &mut *b)`** are plain Rust
153///   moves. The sidecar values stay in each pointer's protection list; only
154///   pending values travel with the struct.
155/// - **After `readRDS()`** a type that derives `Serialize` and
156///   `Deserialize` gets its value back at the first access, and the slots
157///   the save kept with it (#2186). Any other type has no Rust value. The
158///   standalone R accessors (`Type_get_f()` / `Type_set_f()`), the R6 active bindings and
159///   the S7 properties read and write the protection list directly, checked
160///   by the type ID stored with it. The `$` / `[[` / `$<-` / `[[<-` field
161///   methods of `s3(r_data_accessors)` & co. refuse the restored pointer
162///   instead, with the classed restored-object errors: they pass
163///   `require_live` to the same accessor (#1891).
164///
165/// Use the accessors on R's main thread only. Off the main thread an
166/// accessor panics with a clear message before it touches R.
167///
168/// # A save names the values by their R names
169///
170/// A saved object (`saveRDS()`, `serialize()`) stores one slot per `Sidecar`
171/// field, named after the field's R name: the `#[r_data(name = "..")]` value,
172/// else the Rust field name (#2187, #2215). After a reload, the standalone R
173/// accessors, the R6 bindings, the S7 properties and a serde type's restored
174/// value (#2186) find each field's slot by that name. So the R name is the
175/// save format:
176///
177/// - Reordering, adding or removing `Sidecar` fields keeps earlier saves
178///   readable. A field the save has no slot for raises the classed
179///   [`RESTORED_MISSING_SLOT_CLASS`](super::RESTORED_MISSING_SLOT_CLASS)
180///   error from an R accessor; a serde type's restored value gets the
181///   field's [`Sidecar`] from its decoded struct instead.
182/// - Renaming the Rust field keeps them readable too, as long as the R name
183///   stays: a field without `name = ..` keeps its old ident as
184///   `#[r_data(name = "old")]`.
185/// - Renaming the R name orphans the field's slot in every earlier save: the
186///   field reads as one the save lacks.
187/// - Retyping a field keeps its name, so an earlier save's slot is read as the
188///   new type; a getter that can't convert it panics naming the field.
189///
190/// A save from another version of the crate (the `version` in its
191/// `Cargo.toml`, which the stored type ID records) is refused with the classed
192/// `miniextendr_restored_other_version` error (#1872), unless the type
193/// derives serde and serde reads the save (#2186).
194///
195/// # Methods that need sidecar values take a view
196///
197/// A `&self` / `&mut self` method sees the struct, which holds no reference
198/// to its pointer, so it can't reach the values. Take a view instead:
199/// `self: ExternalPtrRef<'_, Self>` to read, `mut self: ExternalPtrMut<'_, Self>`
200/// to write (`Deref` still gives the struct fields). The same holds for a
201/// struct moved out of its pointer through `&mut` (`mem::replace`,
202/// `mem::take`): it carries nothing to follow, so nothing can read a freed R
203/// object (#1856). A trait method takes its owner as
204/// `self: ExternalPtrRef<'_, Self>` or `self: ExternalPtrMut<'_, Self>`
205/// ([`ExternalPtrRef`](crate::ExternalPtrRef)), over an `ExternalPtr` or a
206/// trait-ABI object, and passes it to the same accessors. A `&self` trait
207/// method, such as one of a standard trait with a fixed signature, and the
208/// high-level ALTREP data traits receive only the struct (#1880).
209/// ALTREP derives also accept `#[r_data] Sidecar<T>` fields: with
210/// `#[altrep(manual, no_lowlevel)]`, low-level callbacks recover the handle
211/// through [`crate::altrep_data1_as_unchecked`] and call the associated
212/// accessors. Those derives emit no R class field wrappers.
213///
214/// A plain `SEXP` field under `#[r_data]` is a compile error: nothing would
215/// root it. Use `Sidecar<SEXP>`.
216pub struct Sidecar<T> {
217    /// The value the field holds while it is not in a pointer's slot.
218    pending: RefCell<Option<Pending>>,
219    /// The field's type: its accessors convert the slot to it, and the
220    /// struct's auto traits follow it as if it held a `T`.
221    _value: PhantomData<T>,
222}
223
224/// A value on its way into a slot: its R object, rooted from the moment the
225/// `Sidecar` holds it until a slot owns the GC edge (#2216).
226#[derive(#[automatically_derived]impl ::core::clone::Clone for Pending {
    #[inline]
    fn clone(&self) -> Self {
        Pending {
            sexp: ::core::clone::Clone::clone(&self.sexp),
            root: ::core::clone::Clone::clone(&self.root),
        }
    }
}Clone)]
227struct Pending {
228    sexp: SEXP,
229    root: Rc<PendingRoot>,
230}
231
232/// Shared by the clones of a pending value: cloning needs no R call, and the
233/// last copy releases the root. `Rc` keeps a `Sidecar`, and so the struct
234/// holding it, on R's main thread, where the release happens.
235struct PendingRoot(crate::protect_pool::ProtectKey);
236
237impl Drop for PendingRoot {
238    fn drop(&mut self) {
239        let key = self.0;
240        crate::with_r_thread(move || super::unroot_owned(key));
241    }
242}
243
244impl<T: IntoR + 'static> Sidecar<T> {
245    /// A sidecar field holding `value`, pending until the struct is wrapped
246    /// in an `ExternalPtr`.
247    ///
248    /// Converts `value` with `IntoR` and roots the R object until a slot
249    /// holds it, so a fresh R value is safe from here on.
250    ///
251    /// # Panics
252    ///
253    /// Off R's main thread, before converting; or when the conversion fails.
254    pub fn new(value: T) -> Self {
255        // Converts `value` and roots its R object on R's main thread (#2216).
256        if !crate::is_r_main_thread() {
    {
        ::core::panicking::panic_fmt(format_args!("`Sidecar::new` converts its value on R\'s main thread: call it there, not from a thread the package spawned"));
    }
};assert!(
257            crate::is_r_main_thread(),
258            "`Sidecar::new` converts its value on R's main thread: call it there, \
259             not from a thread the package spawned",
260        );
261        // `root_owned` roots the fresh object across the pool's growth.
262        let (sexp, key) = crate::with_r_thread(move || {
263            let sexp = value.into_sexp();
264            (sexp, super::root_owned(sexp))
265        });
266        Self {
267            pending: RefCell::new(Some(Pending {
268                sexp,
269                root: Rc::new(PendingRoot(key)),
270            })),
271            _value: PhantomData,
272        }
273    }
274}
275
276impl<T> Sidecar<T> {
277    /// Drops a pending value, which a write to the slot supersedes.
278    fn discard_pending(&self) {
279        *self.pending.borrow_mut() = None;
280    }
281
282    /// Moves a pending value into slot `index` of `prot`, if there is one.
283    /// On R's main thread; `set_vector_elt` allocates nothing.
284    fn flush_into(&self, prot: SEXP, index: usize) {
285        let Some(Pending { sexp, root }) = self.pending.borrow_mut().take() else {
286            return;
287        };
288        prot.set_vector_elt(prot_index(index), sexp);
289        // The slot owns the GC edge now.
290        drop(root);
291    }
292
293    /// Reads slot `index` of `prot` back into the field as its pending value,
294    /// unless one is pending already. On R's main thread.
295    fn load_from(&self, prot: SEXP, index: usize) {
296        if self.pending.borrow().is_some() {
297            return;
298        }
299        // The old owner still roots the slot while the pool grows. Root the
300        // slot itself, not the old protection list, so independent pending
301        // fields do not retain one another's values.
302        let sexp = prot.vector_elt(prot_index(index));
303        *self.pending.borrow_mut() = Some(Pending {
304            sexp,
305            root: Rc::new(PendingRoot(super::root_owned(sexp))),
306        });
307    }
308}
309
310impl<T> Clone for Sidecar<T> {
311    /// A `Sidecar` sharing this field's pending R object, and its root, if
312    /// any. The value in a pointer's slot is not copied: clone the
313    /// `ExternalPtr`.
314    fn clone(&self) -> Self {
315        Self {
316            pending: RefCell::new(self.pending.borrow().clone()),
317            _value: PhantomData,
318        }
319    }
320}
321
322impl<T: Default + IntoR + 'static> Default for Sidecar<T> {
323    /// `Sidecar::new(T::default())`.
324    fn default() -> Self {
325        Self::new(T::default())
326    }
327}
328
329impl<T> fmt::Debug for Sidecar<T> {
330    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
331        f.debug_struct("Sidecar")
332            .field("pending", &self.pending.borrow().is_some())
333            .finish()
334    }
335}
336
337/// The element of `prot` at `at`, the slot of `Sidecar` field `name`,
338/// converted to `T`.
339fn convert_slot<T: TryFromSexp>(prot: SEXP, at: R_xlen_t, name: &str, owner_type: &str) -> T
340where
341    <T as TryFromSexp>::Error: fmt::Display,
342{
343    let slot = prot.vector_elt(at);
344    match T::try_from_sexp(slot) {
345        Ok(value) => value,
346        Err(err) => {
    ::core::panicking::panic_fmt(format_args!("sidecar field `{1}` of `{2}` holds an R value that does not convert to `{0}`: {3}",
            std::any::type_name::<T>(), name, owner_type, err));
}panic!(
347            "sidecar field `{name}` of `{owner_type}` holds an R value that does not convert to `{}`: {err}",
348            std::any::type_name::<T>(),
349        ),
350    }
351}
352
353/// Panics unless this is R's main thread. No R API: the message names the
354/// field and the owning type.
355fn assert_main_thread(name: &str, owner_type: &str) {
356    if !crate::is_r_main_thread() {
357        {
    ::core::panicking::panic_fmt(format_args!("sidecar field `{0}` of `{1}`: its accessors run on R\'s main thread only; this call came from another thread (a thread the package spawned)",
            name, owner_type));
};panic!(
358            "sidecar field `{name}` of `{owner_type}`: its accessors run on R's main thread only; \
359             this call came from another thread (a thread the package spawned)",
360        );
361    }
362}
363
364// endregion
365
366// region: The handle's view of the fields
367
368/// A `Sidecar<T>` field, as the handle sees it through the
369/// `TypedExternal::__mx_visit_sidecars` hook the derive emits. Every method
370/// runs on R's main thread.
371#[doc(hidden)]
372pub trait SidecarField {
373    /// Moves a pending value into slot `index` of `prot`.
374    fn __mx_flush(&self, prot: SEXP, index: usize);
375    /// Reads slot `index` of `prot` back into the field as its pending value,
376    /// unless one is pending already.
377    fn __mx_load(&self, prot: SEXP, index: usize);
378    /// Drops a pending value, which a write to the slot supersedes.
379    fn __mx_discard_pending(&self);
380}
381
382impl<T> SidecarField for Sidecar<T> {
383    fn __mx_flush(&self, prot: SEXP, index: usize) {
384        self.flush_into(prot, index);
385    }
386
387    fn __mx_load(&self, prot: SEXP, index: usize) {
388        self.load_from(prot, index);
389    }
390
391    fn __mx_discard_pending(&self) {
392        self.discard_pending();
393    }
394}
395
396/// Moves every pending value of `value`'s `Sidecar` fields into its slot of
397/// `prot`, the protection list of the pointer holding `value`. On R's main
398/// thread.
399pub(crate) fn flush_sidecars<T: TypedExternal>(value: &T, prot: SEXP) {
400    value.__mx_visit_sidecars(&mut |index, _, field| field.__mx_flush(prot, index));
401}
402
403/// Reads every slot of `prot`, the protection list of the pointer `value` is
404/// leaving, back into its `Sidecar` field as a pending value (unless one is
405/// pending already). On R's main thread.
406pub(crate) fn load_sidecars<T: TypedExternal>(value: &T, prot: SEXP) {
407    value.__mx_visit_sidecars(&mut |index, _, field| field.__mx_load(prot, index));
408}
409
410/// Drops every pending value of `value`'s `Sidecar` fields.
411pub(crate) fn discard_pending_sidecars<T: TypedExternal>(value: &T) {
412    value.__mx_visit_sidecars(&mut |_, _, field| field.__mx_discard_pending());
413}
414
415/// Flushes a freshly wrapped value's pending values into its pointer's
416/// protection list: the three construction sites and
417/// `restore_after_consuming` call this once the `EXTPTRSXP` exists.
418///
419/// # Safety
420///
421/// On R's main thread; `any_raw` must own a `RefCell<T>`, and `owner` must be
422/// the live `EXTPTRSXP` holding it, with a `prot` list built by `ExternalPtr`.
423pub(super) unsafe fn init_sidecars<T: TypedExternal>(any_raw: *mut Box<dyn Any>, owner: SEXP) {
424    let value = unsafe { &*any_raw }
425        .downcast_ref::<RefCell<T>>()
426        .expect("ExternalPtr stores a T at construction")
427        .borrow();
428    let prot = unsafe { R_ExternalPtrProtected(owner) };
429    unsafe { name_slots::<T>(prot) };
430    flush_sidecars(&*value, prot);
431}
432
433/// Initializes the slots of a trait-ABI owner using the ordinary sidecar
434/// layout and visitation hook. The Rust allocation remains erased storage;
435/// it must never be wrapped as `ExternalPtr<T>` (which expects `Any` storage).
436///
437/// # Safety
438/// On R's main thread inside an R unwind boundary. `owner` must be the
439/// caller-rooted external pointer owning `value`, with its finalizer already
440/// registered.
441pub(crate) unsafe fn init_erased_sidecars<T: TypedExternal>(value: &T, owner: SEXP) {
442    unsafe {
443        let type_id = super::type_id_symbol_unchecked::<T>();
444        let prot =
445            crate::sys::Rf_allocVector_unchecked(SEXPTYPE::VECSXP, super::prot_vec_len::<T>());
446        // Attach before the next allocation (the slot names' attribute cell):
447        // the owner roots `prot` from here on.
448        crate::sys::R_SetExternalPtrProtected_unchecked(owner, prot);
449        prot.set_vector_elt_unchecked(PROT_TYPE_ID_INDEX, type_id);
450        name_slots::<T>(prot);
451        flush_sidecars(value, prot);
452    }
453}
454
455/// Copies every `Sidecar` slot of the pointer `source` into the pointer
456/// `target`: the two share the R values until one side writes a field.
457///
458/// # Safety
459///
460/// On R's main thread; both must be live `EXTPTRSXP`s built by `ExternalPtr`
461/// for a `T`. `set_vector_elt` allocates nothing.
462pub(super) unsafe fn copy_sidecar_slots<T: TypedExternal>(source: SEXP, target: SEXP) {
463    let from = unsafe { R_ExternalPtrProtected(source) };
464    let to = unsafe { R_ExternalPtrProtected(target) };
465    for index in 0..T::R_SLOT_COUNT {
466        let at = prot_index(index);
467        to.set_vector_elt(at, from.vector_elt(at));
468    }
469}
470
471/// Reads `T`'s `Sidecar` field `index` of the object `ptr` holds, after
472/// moving the field's pending value into the slot.
473///
474/// Called by the getters `#[derive(ExternalPtr)]` generates
475/// (`T::field(&ptr)`); `field` selects the struct's `Sidecar` field.
476///
477/// # Panics
478///
479/// Off R's main thread, naming the field, before touching R; or when the
480/// slot does not convert to `T`.
481#[doc(hidden)]
482pub fn sidecar_get<O, T>(
483    ptr: &impl super::SidecarOwner<O>,
484    index: usize,
485    name: &'static str,
486    field: fn(&O) -> &Sidecar<T>,
487) -> T
488where
489    O: TypedExternal,
490    T: IntoR + TryFromSexp,
491    <T as TryFromSexp>::Error: fmt::Display,
492{
493    assert_main_thread(name, O::TYPE_NAME);
494    let value = ptr.__mx_read();
495    // SAFETY: on R's main thread; the handle's EXTPTRSXP is live and was
496    // built for an `O`.
497    let prot = unsafe { R_ExternalPtrProtected(super::ExternalPtrRef::as_sexp(&value)) };
498    field(&value).flush_into(prot, index);
499    convert_slot::<T>(prot, prot_index(index), name, O::TYPE_NAME)
500}
501
502/// Stores `value` in `T`'s `Sidecar` field `index` of the object `ptr` holds,
503/// dropping the field's pending value, which this write supersedes.
504///
505/// Called by the setters `#[derive(ExternalPtr)]` generates
506/// (`T::set_field(&mut ptr, value)`); `field` selects the struct's `Sidecar`
507/// field.
508///
509/// # Panics
510///
511/// Off R's main thread, naming the field, before touching R.
512#[doc(hidden)]
513pub fn sidecar_set<O, T>(
514    ptr: &mut impl super::SidecarOwnerMut<O>,
515    index: usize,
516    name: &'static str,
517    field: fn(&O) -> &Sidecar<T>,
518    value: T,
519) where
520    O: TypedExternal,
521    T: IntoR,
522{
523    assert_main_thread(name, O::TYPE_NAME);
524    let target = ptr.__mx_write();
525    // SAFETY: as in `sidecar_get`. Storing allocates nothing.
526    let prot = unsafe { R_ExternalPtrProtected(super::ExternalPtrMut::as_sexp(&target)) };
527    field(&target).discard_pending();
528    prot.set_vector_elt(prot_index(index), value.into_sexp());
529}
530
531// endregion
532
533// region: Slot names (#2187)
534
535#[doc =
r" Each type's slot names, preserved for the session and shared by every"]
#[doc =
r#" protection list of the type: `""` for the type ID and the user slot,"#]
#[doc = r" then the `Sidecar` fields' R names, in slot order."]
const SLOT_NAMES: ::std::thread::LocalKey<RefCell<HashMap<TypeId, SEXP>>> =
    {
        #[allow(mismatched_lifetime_syntaxes)]
        #[inline]
        fn __rust_std_internal_init_fn(_lifetime_elision:
                ::std::marker::PhantomData<&'static ()>)
            -> RefCell<HashMap<TypeId, SEXP>> {
            RefCell::new(HashMap::new())
        }
        unsafe {
            ::std::thread::LocalKey::new(const {
                        if ::std::mem::needs_drop::<RefCell<HashMap<TypeId,
                                    SEXP>>>() {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::LazyStorage<RefCell<HashMap<TypeId,
                                        SEXP>>, ()> =
                                        ::std::thread::local_impl::LazyStorage::new();
                                    __RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
                                        || __rust_std_internal_init_fn(::std::marker::PhantomData))
                                }
                        } else {
                            |__rust_std_internal_init|
                                {
                                    #[thread_local]
                                    static __RUST_STD_INTERNAL_VAL:
                                        ::std::thread::local_impl::LazyStorage<RefCell<HashMap<TypeId,
                                        SEXP>>, !> =
                                        ::std::thread::local_impl::LazyStorage::new();
                                    __RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
                                        || __rust_std_internal_init_fn(::std::marker::PhantomData))
                                }
                        }
                    })
        }
    };thread_local! {
536    /// Each type's slot names, preserved for the session and shared by every
537    /// protection list of the type: `""` for the type ID and the user slot,
538    /// then the `Sidecar` fields' R names, in slot order.
539    static SLOT_NAMES: RefCell<HashMap<TypeId, SEXP>> = RefCell::new(HashMap::new());
540}
541
542/// Names `prot`'s slots after `T`'s `Sidecar` fields. A save then keeps the
543/// names, so the version that reads it finds each field by name
544/// ([`saved_slot`]), whatever fields it added, removed or reordered since.
545/// The names vector is the type's own, built once; this allocates only the
546/// attribute's cell.
547///
548/// # Safety
549///
550/// On R's main thread, with `prot` a rooted protection list built for a `T`.
551pub(crate) unsafe fn name_slots<T: TypedExternal>(prot: SEXP) {
552    let cached = SLOT_NAMES.with_borrow(|names| names.get(&TypeId::of::<T>()).copied());
553    let names = cached.unwrap_or_else(|| {
554        // Preserved before it is filled, so the CHARSXPs it receives are
555        // reachable as they are made.
556        let names =
557            unsafe { crate::sys::Rf_allocVector(SEXPTYPE::STRSXP, super::prot_vec_len::<T>()) };
558        unsafe { crate::sys::R_PreserveObject(names) };
559        for (index, name) in T::SIDECAR_NAMES.iter().enumerate() {
560            names.set_string_elt(prot_index(index), SEXP::charsxp(name));
561        }
562        SLOT_NAMES.with_borrow_mut(|cache| cache.insert(TypeId::of::<T>(), names));
563        names
564    });
565    prot.set_names(names);
566}
567
568/// The position in the saved protection list `prot` of `Sidecar` field
569/// `index`, named `name`: found by name when the save carries slot names,
570/// else by position (a save by this version made before slots were named).
571/// `None` when the save has no slot for the field.
572pub(crate) fn saved_slot(prot: SEXP, index: usize, name: &str) -> Option<R_xlen_t> {
573    let names = prot.get_attr(SEXP::names_symbol());
574    if names.type_of() == SEXPTYPE::STRSXP && names.xlength() == prot.xlength() {
575        (PROT_VEC_LEN..names.xlength())
576            .find(|&at| crate::list::text_name(names.string_elt(at)) == Some(name))
577    } else {
578        Some(prot_index(index)).filter(|&at| at < prot.xlength())
579    }
580}
581
582/// Whether the saved protection list `prot` carries slot names.
583pub(crate) fn has_slot_names(prot: SEXP) -> bool {
584    let names = prot.get_attr(SEXP::names_symbol());
585    names.type_of() == SEXPTYPE::STRSXP && names.xlength() == prot.xlength()
586}
587
588/// Raises the classed error for a read of `Sidecar` field `name` that a save
589/// of an `O` has no slot for.
590fn missing_slot<O: TypedExternal>(name: &str) -> ! {
591    RCondition::Error {
592        message: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the saved `{0}` has no `{1}` field: the version that saved it did not have it",
                O::TYPE_NAME, name))
    })format!(
593            "the saved `{}` has no `{name}` field: the version that saved it did not have it",
594            O::TYPE_NAME
595        ),
596        class: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [super::RESTORED_MISSING_SLOT_CLASS.to_owned()]))vec![super::RESTORED_MISSING_SLOT_CLASS.to_owned()],
597        data: Some(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [("field".to_owned(),
                    crate::RValue::Character(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                                [Some(name.to_owned())]))))]))vec![(
598            "field".to_owned(),
599            crate::RValue::Character(vec![Some(name.to_owned())]),
600        )]),
601        call: ConditionCall::Inherit,
602    }
603    .raise()
604}
605
606// endregion
607
608// region: The R accessors
609
610/// The protection-list position of `Sidecar` field `index`.
611pub(super) fn prot_index(index: usize) -> R_xlen_t {
612    let index = R_xlen_t::try_from(index).expect("sidecar index exceeds R_xlen_t::MAX");
613    PROT_VEC_LEN + index
614}
615
616/// The external pointer an R accessor's receiver `x` carries: `x` itself, or
617/// the pointer an R6 / S4 / S7 handle, an environment or a list holds in
618/// `.ptr`, the shapes an instance method's receiver takes
619/// ([`unwrap_class_handle`]). So `Type_get_f(x)` and the `$` / `[[` field
620/// methods of `r_data_accessors` read a list that carries the handle (#1848).
621/// A bare pointer costs one `TYPEOF` compare; an S4 receiver reads its `ptr`
622/// slot through `methods::slot()`, which allocates. The pointer is reachable
623/// from `x`, which the caller's `.Call()` frame roots.
624///
625/// # Panics
626///
627/// When `x` carries no external pointer, with the classed
628/// [`NO_HANDLE_CLASS`] error ([`refuse_no_handle`]).
629///
630/// # Safety
631///
632/// Must be called from R's main thread with a valid `x`.
633unsafe fn sidecar_receiver<T: TypedExternal>(x: SEXP) -> SEXP {
634    if x.type_of() == SEXPTYPE::EXTPTRSXP {
635        return x;
636    }
637    match unsafe { unwrap_class_handle(x) } {
638        Some(ptr) => ptr,
639        None => refuse_no_handle::<T>(x),
640    }
641}
642
643/// What an R accessor's receiver holds instead of a live `T` (#1920).
644#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for Refused {
}
#[automatically_derived]impl ::core::clone::Clone for Refused {
    #[inline]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::Copy for Refused { }Copy)]
645enum Refused {
646    /// No external pointer at all ([`refuse_no_handle`]).
647    NoPointer,
648    /// A pointer without an address that `T` did not build.
649    NullPointer,
650    /// A live pointer to another type.
651    OtherType,
652}
653
654/// The message of a receiver refusal (#1920): the type's own
655/// ([`TypedExternal::FIELD_ERROR_MESSAGE`]), else one naming `receiver`'s R
656/// class, which is what the user sees (the field methods dispatched on it),
657/// else, for a receiver without a class, one naming the Rust type.
658fn refusal_message<T: TypedExternal>(receiver: SEXP, refused: Refused) -> String {
659    if let Some(message) = T::FIELD_ERROR_MESSAGE {
660        return message.to_owned();
661    }
662    match (receiver_class(receiver), refused) {
663        (Some(class), Refused::NoPointer) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this `{0}` object holds no pointer",
                class))
    })format!("this `{class}` object holds no pointer"),
664        (Some(class), Refused::NullPointer) => {
665            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this `{0}` object holds a null pointer",
                class))
    })format!("this `{class}` object holds a null pointer")
666        }
667        (Some(class), Refused::OtherType) => {
668            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this `{0}` object holds a pointer of another type",
                class))
    })format!("this `{class}` object holds a pointer of another type")
669        }
670        (None, Refused::NoPointer) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected ExternalPtr<{0}>, got a non-external-pointer object",
                T::TYPE_NAME))
    })format!(
671            "expected ExternalPtr<{}>, got a non-external-pointer object",
672            T::TYPE_NAME
673        ),
674        (None, Refused::NullPointer) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected ExternalPtr<{0}>, got a null external pointer",
                T::TYPE_NAME))
    })format!(
675            "expected ExternalPtr<{}>, got a null external pointer",
676            T::TYPE_NAME
677        ),
678        (None, Refused::OtherType) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("expected ExternalPtr<{0}>",
                T::TYPE_NAME))
    })format!("expected ExternalPtr<{}>", T::TYPE_NAME),
679    }
680}
681
682/// Raises the error for a receiver that carries no external pointer (#1901):
683/// [`NO_HANDLE_CLASS`], with the type's field-error classes
684/// ([`TypedExternal::FIELD_ERROR_CLASS`], #1899) in front, and for a list or
685/// an environment, the shape an earlier release of a package may have
686/// written to disk, its restored classes
687/// ([`TypedExternal::RESTORED_ERROR_CLASS`]) in front of those: a package
688/// refuses such a save as it refuses a restored pointer, with its no-handle
689/// message ([`TypedExternal::NO_HANDLE_MESSAGE`], #2218), else its restored
690/// message ([`TypedExternal::RESTORED_ERROR_MESSAGE`]), when it sets one.
691/// Another receiver (an atomic vector given the class) was never saved, so
692/// it gets neither (#1919).
693#[cold]
694fn refuse_no_handle<T: TypedExternal>(receiver: SEXP) -> ! {
695    let saved_shape = #[allow(non_exhaustive_omitted_patterns)] match receiver.type_of() {
    SEXPTYPE::VECSXP | SEXPTYPE::ENVSXP => true,
    _ => false,
}matches!(receiver.type_of(), SEXPTYPE::VECSXP | SEXPTYPE::ENVSXP);
696    let restored = if saved_shape {
697        T::RESTORED_ERROR_CLASS
698    } else {
699        &[]
700    };
701    let message =
702        match saved_no_handle_message(saved_shape, T::NO_HANDLE_MESSAGE, T::RESTORED_ERROR_MESSAGE)
703        {
704            Some(message) => message.to_owned(),
705            None => refusal_message::<T>(receiver, Refused::NoPointer),
706        };
707    std::panic::panic_any(RCondition::Error {
708        message,
709        class: no_handle_classes(restored, T::FIELD_ERROR_CLASS),
710        data: None,
711        call: ConditionCall::Inherit,
712    })
713}
714
715/// The package's message for a receiver that carries no pointer, when it is
716/// a list or an environment (`saved_shape`), the shape an earlier release
717/// may have saved: the no-handle message, else the restored message. `None`
718/// leaves the receiver refusal's own wording ([`refusal_message`]).
719fn saved_no_handle_message(
720    saved_shape: bool,
721    no_handle: Option<&'static str>,
722    restored: Option<&'static str>,
723) -> Option<&'static str> {
724    saved_shape.then(|| no_handle.or(restored)).flatten()
725}
726
727/// The classes of [`refuse_no_handle`]: `restored`, then `field_error`, then
728/// [`NO_HANDLE_CLASS`], each class once at its last place. The two lists
729/// usually end in the package's one parent class (`["pkg_saved",
730/// "pkg_error"]` and `["pkg_field", "pkg_error"]`), which then follows both
731/// specific classes, as a class vector goes from specific to general.
732fn no_handle_classes(restored: &[&str], field_error: &[&str]) -> Vec<String> {
733    let all: Vec<&str> = restored
734        .iter()
735        .chain(field_error)
736        .chain(&[NO_HANDLE_CLASS])
737        .copied()
738        .collect();
739    all.iter()
740        .enumerate()
741        .filter(|&(i, c)| !all[i + 1..].contains(c))
742        .map(|(_, c)| (*c).to_owned())
743        .collect()
744}
745
746/// Raises the error for a receiver whose pointer is not a `T` (a pointer of
747/// another type, or one without an address that `T` did not build), worded
748/// by [`refusal_message`], with the type's field-error classes
749/// ([`TypedExternal::FIELD_ERROR_CLASS`], #1899) in front. A type without
750/// them gets the plain panic.
751#[cold]
752fn refuse_other_type<T: TypedExternal>(receiver: SEXP, refused: Refused) -> ! {
753    let message = refusal_message::<T>(receiver, refused);
754    if T::FIELD_ERROR_CLASS.is_empty() {
755        { ::core::panicking::panic_fmt(format_args!("{0}", message)); };panic!("{message}");
756    }
757    std::panic::panic_any(RCondition::Error {
758        message,
759        class: T::FIELD_ERROR_CLASS
760            .iter()
761            .map(|c| (*c).to_owned())
762            .collect(),
763        data: None,
764        call: ConditionCall::Inherit,
765    })
766}
767
768/// Reads the `require_live` flag the R accessors' `.Call()`s pass: `TRUE`
769/// from the `$` / `[[` / `$<-` / `[[<-` field methods, which refuse a
770/// restored pointer, `FALSE` from the standalone accessors, the R6 bindings
771/// and the S7 properties, which read a save (#1891). Anything but `TRUE`
772/// reads as `false`.
773#[doc(hidden)]
774pub fn sidecar_require_live(flag: SEXP) -> bool {
775    flag.as_logical() == Some(true)
776}
777
778/// The `prot` list of the external pointer `x` carries
779/// ([`sidecar_receiver`]), after checking that it points to a `T`, and the
780/// live `T`'s `RefCell` when it still has an address. Allocates nothing for a
781/// pointer, a list or an environment receiver.
782///
783/// A live pointer is checked by `Any::downcast`. A pointer whose address is
784/// NULL (restored from a saved session by `readRDS()` / `unserialize()`)
785/// still holds its sidecar values, so without `require_live` it is accepted
786/// when its stored type ID is `T`'s; one another version of the crate saved
787/// is refused with the classed
788/// [`RESTORED_OTHER_VERSION_CLASS`](super::RESTORED_OTHER_VERSION_CLASS)
789/// error. With `require_live` (the field methods of `r_data_accessors`)
790/// every restored pointer is refused through [`refuse_restored`], so a save
791/// by this version gets [`RESTORED_NO_VALUE_CLASS`](super::RESTORED_NO_VALUE_CLASS).
792/// A serde type's save gets its value first (#2186), and is live.
793///
794/// # Panics
795///
796/// When `x` carries no external pointer to a `T`, or, with `require_live`,
797/// no live one.
798///
799/// # Safety
800///
801/// Must be called from R's main thread with a valid `x`.
802unsafe fn checked_prot<'a, T: TypedExternal>(
803    receiver: SEXP,
804    require_live: bool,
805) -> (SEXP, Option<&'a RefCell<T>>) {
806    let x = unsafe { sidecar_receiver::<T>(receiver) };
807    let mut any_raw = unsafe { R_ExternalPtrAddr(x) }.cast::<Box<dyn Any>>();
808    // A serde type's saved value comes back at any reader (#2186). A save
809    // that could not be decoded reads as a restored pointer, and a refusal
810    // below names the decoding error.
811    if any_raw.is_null()
812        && #[allow(non_exhaustive_omitted_patterns)] match unsafe {
        super::snapshot::attach::<T>(x)
    } {
    super::snapshot::Attach::Attached => true,
    _ => false,
}matches!(
813            unsafe { super::snapshot::attach::<T>(x) },
814            super::snapshot::Attach::Attached
815        )
816    {
817        any_raw = unsafe { R_ExternalPtrAddr(x) }.cast::<Box<dyn Any>>();
818    }
819    // Read after attaching, which gives the pointer a new list.
820    let prot = unsafe { R_ExternalPtrProtected(x) };
821    let live = if any_raw.is_null() {
822        // A save by this version of `T`'s crate, in any module (#2186); the
823        // check compares names and allocates nothing.
824        if require_live
825            || unsafe { super::classify_null_address::<T>(x) } != super::NullAddress::Restored
826        {
827            // A save by this version (`require_live`) or by another version
828            // raises its own error here.
829            unsafe { refuse_restored::<T>(x, receiver) };
830            refuse_other_type::<T>(receiver, Refused::NullPointer);
831        }
832        None
833    } else {
834        if unsafe { super::stored_type_id_symbol(x) }.is_none() {
835            refuse_other_type::<T>(receiver, Refused::OtherType);
836        }
837        match unsafe { &*any_raw }.downcast_ref::<RefCell<T>>() {
838            Some(cell) => Some(cell),
839            None => refuse_other_type::<T>(receiver, Refused::OtherType),
840        }
841    };
842    // A save read by name may hold fewer slots than the type has fields:
843    // its reads look the field up ([`saved_slot`]).
844    if (live.is_some() || !has_slot_names(prot))
845        && !usize::try_from(prot_index(T::R_SLOT_COUNT)).is_ok_and(|len| len <= prot.len())
846    {
847        {
    ::core::panicking::panic_fmt(format_args!("ExternalPtr<{0}> has no sidecar slots: its protection list was not built by `ExternalPtr`",
            T::TYPE_NAME));
};panic!(
848            "ExternalPtr<{}> has no sidecar slots: its protection list was not built by `ExternalPtr`",
849            T::TYPE_NAME
850        );
851    }
852    (prot, live)
853}
854
855/// The live `T` of the external pointer `x` carries ([`sidecar_receiver`]),
856/// borrowed shared, for the R getters of a struct field (a field that is not
857/// a `Sidecar`). A pointer without an address is refused: with the classed
858/// restored-object errors when `T` built it ([`refuse_restored`]), else as a
859/// null pointer ([`refusal_message`]).
860///
861/// # Panics
862///
863/// When `x` carries no live external pointer to a `T`, or with the
864/// `miniextendr_borrow_conflict` R error while a running call holds the value
865/// mutably.
866///
867/// # Safety
868///
869/// Must be called from R's main thread with a valid `x`; the borrow must end
870/// while `x` keeps its value.
871#[doc(hidden)]
872pub unsafe fn sidecar_r_struct<'a, T: TypedExternal>(x: SEXP) -> Ref<'a, T> {
873    super::borrow_value(unsafe { sidecar_r_cell::<T>(x) })
874}
875
876/// The live `T` of the external pointer `x` carries, borrowed mutably, for
877/// the R setters of a struct field; see [`sidecar_r_struct`].
878///
879/// # Panics
880///
881/// When `x` carries no live external pointer to a `T`, or with the
882/// `miniextendr_borrow_conflict` R error while a running call holds the value.
883///
884/// # Safety
885///
886/// Must be called from R's main thread with a valid `x`; the borrow must end
887/// while `x` keeps its value.
888#[doc(hidden)]
889pub unsafe fn sidecar_r_struct_mut<'a, T: TypedExternal>(x: SEXP) -> RefMut<'a, T> {
890    super::borrow_value_mut(unsafe { sidecar_r_cell::<T>(x) })
891}
892
893/// The R getter of the `#[r_data(cache)]` field at cache index `index`
894/// (#2271): the R value an earlier read stored for the live `T` the receiver
895/// `x` carries, else the value of `convert` on it, stored for later reads
896/// when it is `Ok`. An `Err` is the tagged condition of a failed conversion,
897/// returned as is and not stored.
898///
899/// The value is borrowed shared, as [`sidecar_r_struct`] borrows it, before
900/// the stored value is looked up, so a read while a running call holds the
901/// value mutably raises `miniextendr_borrow_conflict` whether or not a value
902/// is stored, and a pointer without a live `T` is refused the same way. Every
903/// exclusive borrow of the value drops what is stored
904/// ([`borrow_value_mut`](super::borrow_value_mut)); see the `field_cache`
905/// module for what stays unseen.
906///
907/// # Safety
908///
909/// Must be called from R's main thread with a valid `x`.
910#[doc(hidden)]
911pub unsafe fn sidecar_r_cached<T: TypedExternal>(
912    x: SEXP,
913    index: usize,
914    convert: impl FnOnce(&T) -> Result<SEXP, SEXP>,
915) -> SEXP {
916    let cell = unsafe { sidecar_r_cell::<T>(x) };
917    let value = super::borrow_value(cell);
918    let key = super::field_cache::cell_key(cell);
919    if let Some(stored) = super::field_cache::cached(key, index) {
920        return stored;
921    }
922    match convert(&value) {
923        Ok(converted) => {
924            super::field_cache::store(key, T::CACHED_FIELD_COUNT, index, converted);
925            converted
926        }
927        Err(condition) => condition,
928    }
929}
930
931/// The body of [`sidecar_r_struct`] and [`sidecar_r_struct_mut`]: the
932/// `RefCell` of the struct behind the pointer `x` carries
933/// ([`sidecar_receiver`]).
934unsafe fn sidecar_r_cell<'a, T: TypedExternal>(receiver: SEXP) -> &'a RefCell<T> {
935    let x = unsafe { sidecar_receiver::<T>(receiver) };
936    let mut any_raw = unsafe { R_ExternalPtrAddr(x) }.cast::<Box<dyn Any>>();
937    // A serde type's saved value comes back here (#2186).
938    if any_raw.is_null()
939        && #[allow(non_exhaustive_omitted_patterns)] match unsafe {
        super::snapshot::attach::<T>(x)
    } {
    super::snapshot::Attach::Attached => true,
    _ => false,
}matches!(
940            unsafe { super::snapshot::attach::<T>(x) },
941            super::snapshot::Attach::Attached
942        )
943    {
944        any_raw = unsafe { R_ExternalPtrAddr(x) }.cast::<Box<dyn Any>>();
945    }
946    if any_raw.is_null() {
947        // A save by this or another version raises its own error here.
948        unsafe { refuse_restored::<T>(x, receiver) };
949        refuse_other_type::<T>(receiver, Refused::NullPointer);
950    }
951    if unsafe { super::stored_type_id_symbol(x) }.is_none() {
952        refuse_other_type::<T>(receiver, Refused::OtherType);
953    }
954    match unsafe { &*any_raw }.downcast_ref::<RefCell<T>>() {
955        Some(cell) => cell,
956        None => refuse_other_type::<T>(receiver, Refused::OtherType),
957    }
958}
959
960/// Checks that `x` carries an external pointer to a `T` ([`sidecar_receiver`]),
961/// live or (without `require_live`) read back by `readRDS()`, before a setter
962/// validates its value.
963///
964/// # Panics
965///
966/// When `x` carries no external pointer to a `T` ([`checked_prot`]), or with
967/// the `miniextendr_borrow_conflict` R error while a running call holds the
968/// value.
969///
970/// # Safety
971///
972/// Must be called from R's main thread with a valid `x`.
973#[doc(hidden)]
974pub unsafe fn sidecar_r_check<T: TypedExternal>(x: SEXP, require_live: bool) {
975    let (_, live) = unsafe { checked_prot::<T>(x, require_live) };
976    if let Some(cell) = live {
977        drop(super::borrow_value_mut(cell));
978    }
979}
980
981/// Whether the receiver `x` (a pointer, or an object carrying one) still has
982/// its Rust value, for the field methods of a type with
983/// `#[externalptr(restored(refuse = "every_read"))]` (#1901), which ask
984/// before a read that never reaches an accessor (`names()`, a name that is
985/// not a field).
986///
987/// With `raise`, a receiver without one is refused as the accessors refuse
988/// it ([`checked_prot`] with `require_live`: the type's restored error, the
989/// no-pointer error, or the other-type error) and a live pointer of another
990/// type is refused too, so the result is always `true`. Without it
991/// (`.DollarNames()`, which serves completion and never raises) the answer
992/// is whether `x` carries a pointer with an address, after attaching a
993/// serde type's saved value (#2186): a list or an environment without one,
994/// or an atomic vector, has none. Completion of a receiver without a value
995/// then lists the type's field names, which need none (#2218).
996///
997/// # Safety
998///
999/// Must be called from R's main thread with a valid `x`.
1000#[doc(hidden)]
1001pub unsafe fn sidecar_r_live<T: TypedExternal>(x: SEXP, raise: bool) -> bool {
1002    if raise {
1003        let _ = unsafe { checked_prot::<T>(x, true) };
1004        return true;
1005    }
1006    let ptr = if x.type_of() == SEXPTYPE::EXTPTRSXP {
1007        Some(x)
1008    } else {
1009        unsafe { unwrap_class_handle(x) }
1010    };
1011    ptr.is_some_and(|ptr| {
1012        // A serde type's saved value comes back here too (#2186); attaching
1013        // raises nothing.
1014        if unsafe { R_ExternalPtrAddr(ptr) }.is_null() {
1015            let _ = unsafe { super::snapshot::attach::<T>(ptr) };
1016        }
1017        !unsafe { R_ExternalPtrAddr(ptr) }.is_null()
1018    })
1019}
1020
1021/// Reads `T`'s `Sidecar` field `index` from the external pointer `x` carries
1022/// ([`sidecar_receiver`]).
1023///
1024/// Called by the R getters `#[derive(ExternalPtr)]` generates. A live
1025/// struct's pending value for the field is flushed into the slot first; a
1026/// pointer without an address (after `readRDS()`) reads its protection list
1027/// as is, unless `require_live` refuses it ([`checked_prot`]).
1028///
1029/// # Panics
1030///
1031/// When `x` carries no external pointer to a `T`, or with the
1032/// `miniextendr_borrow_conflict` R error while a running call holds the value
1033/// mutably.
1034///
1035/// # Safety
1036///
1037/// Must be called from R's main thread with a valid `x`.
1038#[doc(hidden)]
1039pub unsafe fn sidecar_r_get<T: TypedExternal>(x: SEXP, index: usize, require_live: bool) -> SEXP {
1040    let (prot, live) = unsafe { checked_prot::<T>(x, require_live) };
1041    let Some(cell) = live else {
1042        // A restored pointer: the slot of the field's name (#2187).
1043        let name = T::SIDECAR_NAMES[index];
1044        return match saved_slot(prot, index, name) {
1045            Some(at) => prot.vector_elt(at),
1046            None => missing_slot::<T>(name),
1047        };
1048    };
1049    super::borrow_value(cell).__mx_visit_sidecars(&mut |i, _, field| {
1050        if i == index {
1051            field.__mx_flush(prot, i);
1052        }
1053    });
1054    prot.vector_elt(prot_index(index))
1055}
1056
1057/// Stores `value`, which the caller validated with `TryFromSexp::<T>`, in
1058/// `T`'s `Sidecar` field `index` of the external pointer `x` carries
1059/// ([`sidecar_receiver`]).
1060///
1061/// Called by the R setters `#[derive(ExternalPtr)]` generates, after
1062/// [`sidecar_r_check`] with the same `require_live`. A live struct's pending
1063/// value for the field is dropped, since this write supersedes it. The store
1064/// allocates nothing; reading an S4 receiver's slot does, and `value`, an
1065/// argument of the setter's `.Call()`, is rooted by that call.
1066///
1067/// # Panics
1068///
1069/// When `x` carries no external pointer to a `T`, or with the
1070/// `miniextendr_borrow_conflict` R error while a running call holds the
1071/// value.
1072///
1073/// # Safety
1074///
1075/// Must be called from R's main thread with valid `x` and `value`.
1076#[doc(hidden)]
1077pub unsafe fn sidecar_r_set<T: TypedExternal>(
1078    x: SEXP,
1079    index: usize,
1080    value: SEXP,
1081    require_live: bool,
1082) {
1083    let (prot, live) = unsafe { checked_prot::<T>(x, require_live) };
1084    let Some(cell) = live else {
1085        // A restored pointer: the slot of the field's name (#2187).
1086        let name = T::SIDECAR_NAMES[index];
1087        match saved_slot(prot, index, name) {
1088            Some(at) => prot.set_vector_elt(at, value),
1089            None => missing_slot::<T>(name),
1090        }
1091        return;
1092    };
1093    super::borrow_value_mut(cell).__mx_visit_sidecars(&mut |i, _, field| {
1094        if i == index {
1095            field.__mx_discard_pending();
1096        }
1097    });
1098    prot.set_vector_elt(prot_index(index), value);
1099}
1100
1101// endregion
1102
1103#[cfg(test)]
1104mod tests;