miniextendr_api/externalptr/altrep_helpers.rs
1//! ALTREP helpers for `ExternalPtr` — data1/data2 slot access.
2//!
3//! Convenience functions for ALTREP implementations that store their data
4//! in `ExternalPtr` slots. Also provides the `Sidecar` marker type for
5//! `#[r_data]` fields.
6
7use super::{ErasedExternalPtr, ExternalPtr, TypedExternal};
8use crate::SEXP;
9
10/// Extract the ALTREP data1 slot as a typed `ExternalPtr<T>`.
11///
12/// This is a convenience function for ALTREP implementations that store
13/// their data in an `ExternalPtr` in the data1 slot.
14///
15/// # Safety
16///
17/// - `x` must be a valid ALTREP SEXP
18/// - Must be called from the R main thread
19///
20/// # Example
21///
22/// ```ignore
23/// impl Altrep for MyAltrepClass {
24/// const HAS_LENGTH: bool = true;
25/// fn length(x: SEXP) -> R_xlen_t {
26/// match unsafe { altrep_data1_as::<MyData>(x) } {
27/// Some(ext) => ext.data.len() as R_xlen_t,
28/// None => 0,
29/// }
30/// }
31/// }
32/// ```
33#[inline]
34pub unsafe fn altrep_data1_as<T: TypedExternal>(x: SEXP) -> Option<ExternalPtr<T>> {
35 unsafe { ExternalPtr::wrap_sexp(SEXP::altrep_data1_raw(x)) }
36}
37
38/// Extract the ALTREP data1 slot (unchecked version).
39///
40/// Skips thread safety checks for performance-critical ALTREP callbacks.
41///
42/// # Safety
43///
44/// - `x` must be a valid ALTREP SEXP
45/// - Must be called from the R main thread (guaranteed in ALTREP callbacks)
46#[inline]
47pub unsafe fn altrep_data1_as_unchecked<T: TypedExternal>(x: SEXP) -> Option<ExternalPtr<T>> {
48 unsafe { ExternalPtr::wrap_sexp_unchecked(SEXP::altrep_data1_raw_unchecked(x)) }
49}
50
51/// Extract the ALTREP data2 slot as a typed `ExternalPtr<T>`.
52///
53/// Similar to `altrep_data1_as`, but for the data2 slot.
54///
55/// # Safety
56///
57/// - `x` must be a valid ALTREP SEXP
58/// - Must be called from the R main thread
59#[inline]
60pub unsafe fn altrep_data2_as<T: TypedExternal>(x: SEXP) -> Option<ExternalPtr<T>> {
61 unsafe { ExternalPtr::wrap_sexp(x.altrep_data2_raw()) }
62}
63
64/// Extract the ALTREP data2 slot (unchecked version).
65///
66/// Skips thread safety checks for performance-critical ALTREP callbacks.
67///
68/// # Safety
69///
70/// - `x` must be a valid ALTREP SEXP
71/// - Must be called from the R main thread (guaranteed in ALTREP callbacks)
72#[inline]
73pub unsafe fn altrep_data2_as_unchecked<T: TypedExternal>(x: SEXP) -> Option<ExternalPtr<T>> {
74 unsafe { ExternalPtr::wrap_sexp_unchecked(x.altrep_data2_raw_unchecked()) }
75}
76
77/// Get a mutable reference to data in ALTREP data1 slot via `ErasedExternalPtr`.
78///
79/// This is useful for ALTREP methods that need to mutate the underlying data.
80///
81/// # Safety
82///
83/// - `x` must be a valid ALTREP SEXP
84/// - Must be called from the R main thread
85/// - The caller must ensure no other references to the data exist
86///
87/// # Example
88///
89/// ```ignore
90/// fn dataptr(x: SEXP, _writable: bool) -> *mut c_void {
91/// match unsafe { altrep_data1_mut::<MyData>(x) } {
92/// Some(data) => data.buffer.as_mut_ptr().cast(),
93/// None => core::ptr::null_mut(),
94/// }
95/// }
96/// ```
97///
98/// Takes no `RefCell` borrow: the ALTREP callbacks read their data unchecked
99/// until #2103 measures the checked read.
100#[inline]
101pub unsafe fn altrep_data1_mut<T: TypedExternal>(x: SEXP) -> Option<&'static mut T> {
102 unsafe { data1_value_mut(ErasedExternalPtr::from_sexp(SEXP::altrep_data1_raw(x))) }
103}
104
105/// Get a mutable reference to data in ALTREP data1 slot (unchecked version).
106///
107/// Skips thread safety checks for performance-critical ALTREP callbacks.
108///
109/// # Safety
110///
111/// - `x` must be a valid ALTREP SEXP
112/// - Must be called from the R main thread (guaranteed in ALTREP callbacks)
113/// - The caller must ensure no other references to the data exist
114#[inline]
115pub unsafe fn altrep_data1_mut_unchecked<T: TypedExternal>(x: SEXP) -> Option<&'static mut T> {
116 unsafe {
117 data1_value_mut(ErasedExternalPtr::from_sexp(
118 SEXP::altrep_data1_raw_unchecked(x),
119 ))
120 }
121}
122
123/// The `T` that `erased` holds, with no `RefCell` borrow.
124///
125/// # Safety
126///
127/// As for [`altrep_data1_mut`]. The `'static` lifetime is sound for the
128/// callback: R's GC protects the ALTREP object, and so its data1, while the
129/// callback runs.
130#[inline]
131unsafe fn data1_value_mut<T: TypedExternal>(erased: ErasedExternalPtr) -> Option<&'static mut T> {
132 erased
133 .downcast_cell::<T>()
134 // SAFETY: caller contract; `RefCell::as_ptr` may be written through.
135 .map(|cell| unsafe { &mut *cell.as_ptr() })
136}
137
138// Tests for ExternalPtr require R runtime, so they are in rpkg/src/rust/lib.rs
139// endregion
140
141// region: Sidecar Marker Type for #[r_data] Fields
142
143/// Marker type for enabling R sidecar accessors in an `ExternalPtr` struct.
144///
145/// When used with `#[derive(ExternalPtr)]` and `#[r_data]`, this field acts as
146/// a selector that enables R-facing accessors for sibling `#[r_data]` fields.
147///
148/// # Supported Field Types
149///
150/// - **[`Sidecar<T>`](super::Sidecar)** - a typed value kept in the external
151/// pointer's protection list (not in the struct), so the pointer roots it
152/// and `saveRDS()` writes it; Rust reads and writes it through the
153/// accessors the derive generates
154/// - **`i32`, `f64`, `bool`, `u8`** - scalars read with `Rf_as*` on write and
155/// returned as a fresh length-1 vector on read
156/// - **Any `IntoR + TryFromSexp` type** - converted on every read and write
157/// (e.g., `String`, `Vec<T>`)
158/// - **[`Computed`]** - a read-only field computed from the Rust value by a
159/// getter function (`#[r_data(get = "Self::f")]`)
160///
161/// `#[r_data(read_only)]` on a public field of the first three kinds makes
162/// it read-only from R (#2268): R gets no setter, and the field methods, an
163/// R6 active binding and an S7 property refuse a write as they refuse one
164/// to a `Computed` field. The Rust accessors of a `Sidecar` field stay.
165///
166/// Every field but a `Sidecar` lives in the Rust struct, so a reader always
167/// sees the Rust value and a writer either converts into it or gets an error.
168/// Those values sit behind the pointer's address, which `saveRDS` does not
169/// write. `Sidecar` values travel with the pointer.
170///
171/// # Example
172///
173/// ```ignore
174/// use miniextendr_api::externalptr::{RSidecar, Sidecar};
175///
176/// #[derive(ExternalPtr)]
177/// pub struct MyType {
178/// pub x: i32,
179///
180/// /// Selector field - enables R wrapper generation
181/// #[r_data]
182/// r: RSidecar,
183///
184/// /// Rooted value - MyType_get_keys() / MyType_set_keys(), and
185/// /// `MyType::keys(&ptr)` / `MyType::set_keys(&mut ptr, v)` in Rust
186/// #[r_data]
187/// pub keys: Sidecar<Vec<i32>>,
188///
189/// /// Zero-overhead scalar - MyType_get_count() / MyType_set_count()
190/// #[r_data]
191/// pub count: i32,
192///
193/// /// Conversion type - MyType_get_name() / MyType_set_name()
194/// #[r_data]
195/// pub name: String,
196/// }
197/// ```
198///
199/// # Design Notes
200///
201/// - `RSidecar` is a ZST (zero-sized type) - no runtime cost
202/// - Only `pub` `#[r_data]` fields get R wrapper functions generated
203/// - Multiple `RSidecar` fields in one struct is a compile error
204#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
205pub struct RSidecar;
206
207/// Marker type of a read-only R field computed from the Rust value
208/// (#1883).
209///
210/// Declare it as `#[r_data(get = "Self::f")] pub f: Computed` on a
211/// `#[derive(ExternalPtr)]` struct with an [`RSidecar`] selector. `get`
212/// names a plain Rust function `fn(&Self) -> T` with `T: IntoR`, resolved in
213/// the struct's module (a leading `Self` is the struct); it needs no
214/// `#[miniextendr]`. The field holds no value: it is a zero-sized marker that
215/// gives the computed field its place among the type's R fields, so every
216/// struct literal writes `f: Computed` once, as it writes `_r: RSidecar`.
217///
218/// ```ignore
219/// #[derive(ExternalPtr)]
220/// #[externalptr(s3)]
221/// pub struct Engine {
222/// inner: Model,
223/// #[r_data] _r: RSidecar,
224/// #[r_data(get = "Self::group_by")] pub group_by: Computed,
225/// #[r_data(name = "keys")] pub r_keys: Sidecar<SEXP>,
226/// #[r_data(get = "Self::n_rows")] pub n_rows: Computed,
227/// }
228///
229/// impl Engine {
230/// fn group_by(&self) -> Vec<String> { self.inner.group_by.clone() }
231/// fn n_rows(&self) -> i32 { self.inner.n_rows() }
232/// }
233/// ```
234///
235/// What the derive generates for it:
236///
237/// - the standalone getter `Engine_get_group_by(x)`, and an arm in the
238/// `$` / `[[` field methods of `s3(r_data_accessors)` & co., at the field's
239/// declared place among the `Sidecar` and struct fields;
240/// - no setter: no `Engine_set_group_by()`, and under the get/set form an
241/// assignment (`x$group_by <- v`) raises `miniextendr_read_only_field`,
242/// as an R6 active binding does; an S7 property has no setter, so S7
243/// refuses the assignment (#1888). An `#[r_data(read_only)]` field is
244/// read-only from R the same way (#2268).
245///
246/// The getter runs on R's main thread with the live Rust value, so a
247/// computed field refuses a pointer restored from a saved session like a
248/// struct field does. Its errors are its own: a `rust_error!(class = ...)`
249/// in the getter reaches R with that class. A getter returning
250/// `Result<T, E>` is an error boundary, as a `#[miniextendr]` function's
251/// `Result` is (#2269): `Ok` reads the value, `Err` raises the error with
252/// the classes and fields of its
253/// [`RConditionData`](crate::condition::RConditionData) impl (else its serde
254/// shape, else its `Debug` text), and `Err(())` of a `Result<T, ()>` reads
255/// `NULL`. The getter takes `&Self`, so it can't read `Sidecar` values
256/// (#1856), which are R fields already.
257///
258/// Only a `pub` `Computed` field reaches R.
259#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
260pub struct Computed;
261// endregion
262
263// region: The computed getter's `Result` probe (#2269)
264
265/// What a computed field's getter gave, as the generated getter reads it.
266/// Sorted by the autoref probe on [`ComputedProbe`], since the derive sees
267/// the getter's path, not its return type.
268#[doc(hidden)]
269pub enum ComputedRead<T, E> {
270 /// A value to convert with `IntoR`: the getter's value, or its `Ok`.
271 Value(T),
272 /// `Err(())` of a `Result<T, ()>`: the field reads `NULL`, as a
273 /// function's `Result<T, ()>` return does.
274 Null,
275 /// `Err(e)` of any other `Result<T, E>`: raised as a classed R error.
276 Err(E),
277}
278
279/// The autoref probe of a computed getter's value `V`. The generated getter
280/// calls `(&&&ComputedProbe::of(&value)).__mx_computed_read(value)` with the
281/// three traits in scope; method lookup tries the receiver `&&&ComputedProbe<V>`
282/// first, so the impl on the deepest reference that fits `V` wins:
283/// [`ComputedReadNull`] for `Result<T, ()>`, then [`ComputedReadResult`] for
284/// any `Result<T, E>`, then [`ComputedReadValue`] for anything else.
285#[doc(hidden)]
286pub struct ComputedProbe<V>(::core::marker::PhantomData<V>);
287
288impl<V> ComputedProbe<V> {
289 /// The probe of `value`'s type.
290 #[doc(hidden)]
291 #[inline(always)]
292 pub fn of(_value: &V) -> Self {
293 ComputedProbe(::core::marker::PhantomData)
294 }
295}
296
297/// First arm: `Result<T, ()>`, whose `Err(())` reads `NULL`.
298#[doc(hidden)]
299pub trait ComputedReadNull {
300 type Value;
301 type Ok;
302 fn __mx_computed_read(
303 &self,
304 value: Self::Value,
305 ) -> ComputedRead<Self::Ok, ::core::convert::Infallible>;
306}
307
308impl<T> ComputedReadNull for &&ComputedProbe<Result<T, ()>> {
309 type Value = Result<T, ()>;
310 type Ok = T;
311 #[inline(always)]
312 fn __mx_computed_read(
313 &self,
314 value: Result<T, ()>,
315 ) -> ComputedRead<T, ::core::convert::Infallible> {
316 match value {
317 Ok(value) => ComputedRead::Value(value),
318 Err(()) => ComputedRead::Null,
319 }
320 }
321}
322
323/// Second arm: any other `Result<T, E>`, whose `Err` is raised.
324#[doc(hidden)]
325pub trait ComputedReadResult {
326 type Value;
327 type Ok;
328 type Err;
329 fn __mx_computed_read(&self, value: Self::Value) -> ComputedRead<Self::Ok, Self::Err>;
330}
331
332impl<T, E> ComputedReadResult for &ComputedProbe<Result<T, E>> {
333 type Value = Result<T, E>;
334 type Ok = T;
335 type Err = E;
336 #[inline(always)]
337 fn __mx_computed_read(&self, value: Result<T, E>) -> ComputedRead<T, E> {
338 match value {
339 Ok(value) => ComputedRead::Value(value),
340 Err(error) => ComputedRead::Err(error),
341 }
342 }
343}
344
345/// Last arm: any other value, read as it is.
346#[doc(hidden)]
347pub trait ComputedReadValue {
348 type Value;
349 fn __mx_computed_read(
350 &self,
351 value: Self::Value,
352 ) -> ComputedRead<Self::Value, ::core::convert::Infallible>;
353}
354
355impl<V> ComputedReadValue for ComputedProbe<V> {
356 type Value = V;
357 #[inline(always)]
358 fn __mx_computed_read(&self, value: V) -> ComputedRead<V, ::core::convert::Infallible> {
359 ComputedRead::Value(value)
360 }
361}
362// endregion