miniextendr_api/externalptr/borrowed.rs
1//! Borrowed handles over ordinary or erased external-pointer storage.
2
3use super::{TypedExternal, borrow_value, borrow_value_mut};
4use crate::SEXP;
5use core::cell::{Ref, RefCell, RefMut};
6use core::fmt;
7use core::marker::PhantomData;
8use core::ops::{Deref, DerefMut};
9
10mod sealed {
11 pub trait Owner {}
12}
13
14/// A handle that reaches a concrete value together with its R object, for
15/// the sidecar accessors.
16///
17/// Implemented by [`ExternalPtr`](super::ExternalPtr), [`ExternalPtrRef`]
18/// and [`ExternalPtrMut`]. Generated sidecar getters accept any of these
19/// handles: an `ExternalPtr` borrows its value for the read, a view already
20/// holds the borrow. Implementations are sealed because the owner and data
21/// must describe the same allocation.
22pub trait SidecarOwner<T: TypedExternal + ?Sized>: sealed::Owner {
23 /// The value, borrowed shared, with its R object.
24 #[doc(hidden)]
25 fn __mx_read(&self) -> ExternalPtrRef<'_, T>;
26}
27
28/// A handle accepted by generated sidecar setters: an
29/// [`ExternalPtr`](super::ExternalPtr), which borrows its value exclusively
30/// for the write, or an [`ExternalPtrMut`].
31pub trait SidecarOwnerMut<T: TypedExternal + ?Sized>: SidecarOwner<T> {
32 /// The value, borrowed exclusively, with its R object.
33 #[doc(hidden)]
34 fn __mx_write(&mut self) -> ExternalPtrMut<'_, T>;
35}
36
37/// Where a shared view gets its value: the `RefCell` borrow it holds, or a
38/// view it was reborrowed from.
39enum Shared<'a, T: ?Sized> {
40 Guard(Ref<'a, T>),
41 Reborrow(&'a T),
42}
43
44/// Where an exclusive view gets its value, like [`Shared`].
45enum Exclusive<'a, T: ?Sized> {
46 Guard(RefMut<'a, T>),
47 Reborrow(&'a mut T),
48}
49
50/// A shared borrow of a Rust value together with its R object.
51///
52/// [`ExternalPtr::borrow`](super::ExternalPtr::borrow) makes one, and a
53/// `#[miniextendr]` function or method takes one as a parameter (or as
54/// `self: ExternalPtrRef<'_, Self>`) when it needs the R object as well as
55/// the value: the sidecar accessors, the object's identity
56/// ([`ExternalPtrRef::as_sexp`]). A body that needs only the value takes
57/// `&T`.
58///
59/// The view holds a shared borrow of the value's `RefCell` for its whole
60/// lifetime: a method of the same object that needs it mutably, a `&mut T`
61/// argument holding it, or [`ExternalPtr::borrow_mut`](super::ExternalPtr::borrow_mut)
62/// meanwhile raises the R error of class `miniextendr_borrow_conflict`. It
63/// never owns or consumes the value, can represent ordinary `Any` storage or
64/// erased trait-ABI storage, and cannot cross threads. Pass it on without
65/// moving it with [`rb`](Self::rb).
66///
67/// A borrowed handle cannot outlive its owner:
68/// ```compile_fail,E0515
69/// use miniextendr_api::{ExternalPtr, ExternalPtrRef, TypedExternal};
70/// fn escape<T: TypedExternal>(owner: ExternalPtr<T>) -> ExternalPtrRef<'static, T> {
71/// owner.borrow()
72/// }
73/// ```
74pub struct ExternalPtrRef<'a, T: TypedExternal + ?Sized> {
75 value: Shared<'a, T>,
76 owner: &'a SEXP,
77 _main_thread: PhantomData<*mut ()>,
78}
79
80/// An exclusive borrow of a Rust value together with its R object.
81///
82/// [`ExternalPtr::borrow_mut`](super::ExternalPtr::borrow_mut) makes one, and
83/// a `#[miniextendr]` function or method takes one as a parameter (or as
84/// `self: ExternalPtrMut<'_, Self>`) when it needs the R object as well as
85/// the value, like [`ExternalPtrRef`]. Dereferencing gives mutable access to
86/// the Rust fields; the sidecar setters use the R object. There is no
87/// consuming API.
88///
89/// The view holds an exclusive borrow of the value's `RefCell` for its whole
90/// lifetime: any other borrow of the value meanwhile raises the R error of
91/// class `miniextendr_borrow_conflict`. Pass it on without moving it with
92/// [`rb_mut`](Self::rb_mut), or as a shared view with [`rb`](Self::rb).
93///
94/// A view borrows its handle for as long as it lives:
95/// ```compile_fail,E0502
96/// use miniextendr_api::{ExternalPtr, ExternalPtrMut, ExternalPtrRef, TypedExternal};
97/// fn overlap<T: TypedExternal>(owner: &mut ExternalPtr<T>) {
98/// let mut first = owner.borrow_mut();
99/// let second = owner.borrow();
100/// let _ = (&mut *first, second);
101/// }
102/// ```
103///
104/// A reborrow ends before the view is used again:
105/// ```compile_fail,E0499
106/// use miniextendr_api::{ExternalPtrMut, TypedExternal};
107/// fn twice<T: TypedExternal>(view: &mut ExternalPtrMut<'_, T>) {
108/// let first = view.rb_mut();
109/// let second = view.rb_mut();
110/// let _ = (first, second);
111/// }
112/// ```
113pub struct ExternalPtrMut<'a, T: TypedExternal + ?Sized> {
114 value: Exclusive<'a, T>,
115 owner: &'a SEXP,
116 _main_thread: PhantomData<*mut ()>,
117}
118
119impl<'a, T: TypedExternal + ?Sized> ExternalPtrRef<'a, T> {
120 /// Hold `guard`, a borrow of the value of the R object `owner`.
121 #[inline]
122 pub(super) fn from_guard(owner: &'a SEXP, guard: Ref<'a, T>) -> Self {
123 Self {
124 value: Shared::Guard(guard),
125 owner,
126 _main_thread: PhantomData,
127 }
128 }
129
130 /// A shared view of the same value for a shorter lifetime, to pass on
131 /// without moving this one. The value stays borrowed until this view
132 /// drops.
133 #[inline]
134 pub fn rb(&self) -> ExternalPtrRef<'_, T> {
135 ExternalPtrRef {
136 value: Shared::Reborrow(&**self),
137 owner: self.owner,
138 _main_thread: PhantomData,
139 }
140 }
141
142 /// The R object (`EXTPTRSXP`) holding the value.
143 ///
144 /// An associated function, `ExternalPtrRef::as_sexp(&view)`, so that it
145 /// doesn't hide a method of `T` of the same name.
146 #[inline]
147 pub fn as_sexp(this: &Self) -> SEXP {
148 *this.owner
149 }
150}
151
152impl<'a, T: TypedExternal> ExternalPtrRef<'a, T> {
153 /// Borrow a receiver after its type and argument aliases have been checked.
154 ///
155 /// # Safety
156 /// R's main thread; `cell` must point to the live `RefCell<T>` owned by
157 /// `owner`, whose initialized sidecar slots use `T`'s layout. Its SEXP must
158 /// stay rooted for `'a`; the slot reference alone does not root it. The cell
159 /// must remain valid for `'a`.
160 #[doc(hidden)]
161 pub unsafe fn from_raw_parts(owner: &'a SEXP, cell: *const RefCell<T>) -> Self {
162 Self::from_guard(owner, borrow_value(unsafe { &*cell }))
163 }
164}
165
166impl<'a, T: TypedExternal + ?Sized> ExternalPtrMut<'a, T> {
167 /// Hold `guard`, an exclusive borrow of the value of the R object `owner`.
168 #[inline]
169 pub(super) fn from_guard(owner: &'a SEXP, guard: RefMut<'a, T>) -> Self {
170 Self {
171 value: Exclusive::Guard(guard),
172 owner,
173 _main_thread: PhantomData,
174 }
175 }
176
177 /// A shared view of the same value, for as long as this view isn't used
178 /// mutably.
179 #[inline]
180 pub fn rb(&self) -> ExternalPtrRef<'_, T> {
181 ExternalPtrRef {
182 value: Shared::Reborrow(&**self),
183 owner: self.owner,
184 _main_thread: PhantomData,
185 }
186 }
187
188 /// An exclusive view of the same value for a shorter lifetime, to pass on
189 /// without moving this one.
190 #[inline]
191 pub fn rb_mut(&mut self) -> ExternalPtrMut<'_, T> {
192 let owner = self.owner;
193 ExternalPtrMut {
194 value: Exclusive::Reborrow(&mut **self),
195 owner,
196 _main_thread: PhantomData,
197 }
198 }
199
200 /// The R object (`EXTPTRSXP`) holding the value.
201 ///
202 /// An associated function, `ExternalPtrMut::as_sexp(&view)`, so that it
203 /// doesn't hide a method of `T` of the same name.
204 #[inline]
205 pub fn as_sexp(this: &Self) -> SEXP {
206 *this.owner
207 }
208}
209
210impl<'a, T: TypedExternal> ExternalPtrMut<'a, T> {
211 /// Borrow a receiver after its type and argument aliases have been checked.
212 ///
213 /// # Safety
214 /// R's main thread; `cell` must point to the live `RefCell<T>` owned by
215 /// `owner`, whose initialized sidecar slots use `T`'s layout. Its SEXP must
216 /// stay rooted for `'a`; the slot reference alone does not root it. The cell
217 /// must remain valid for `'a`.
218 #[doc(hidden)]
219 pub unsafe fn from_raw_parts(owner: &'a SEXP, cell: *const RefCell<T>) -> Self {
220 Self::from_guard(owner, borrow_value_mut(unsafe { &*cell }))
221 }
222}
223
224impl<T: TypedExternal + ?Sized> Deref for ExternalPtrRef<'_, T> {
225 type Target = T;
226 #[inline]
227 fn deref(&self) -> &T {
228 match &self.value {
229 Shared::Guard(guard) => guard,
230 Shared::Reborrow(value) => value,
231 }
232 }
233}
234impl<T: TypedExternal + ?Sized> Deref for ExternalPtrMut<'_, T> {
235 type Target = T;
236 #[inline]
237 fn deref(&self) -> &T {
238 match &self.value {
239 Exclusive::Guard(guard) => guard,
240 Exclusive::Reborrow(value) => value,
241 }
242 }
243}
244impl<T: TypedExternal + ?Sized> DerefMut for ExternalPtrMut<'_, T> {
245 #[inline]
246 fn deref_mut(&mut self) -> &mut T {
247 match &mut self.value {
248 Exclusive::Guard(guard) => guard,
249 Exclusive::Reborrow(value) => value,
250 }
251 }
252}
253
254impl<T: TypedExternal + ?Sized + fmt::Debug> fmt::Debug for ExternalPtrRef<'_, T> {
255 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256 fmt::Debug::fmt(&**self, f)
257 }
258}
259impl<T: TypedExternal + ?Sized + fmt::Debug> fmt::Debug for ExternalPtrMut<'_, T> {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 fmt::Debug::fmt(&**self, f)
262 }
263}
264impl<T: TypedExternal + ?Sized + fmt::Display> fmt::Display for ExternalPtrRef<'_, T> {
265 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266 fmt::Display::fmt(&**self, f)
267 }
268}
269impl<T: TypedExternal + ?Sized + fmt::Display> fmt::Display for ExternalPtrMut<'_, T> {
270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271 fmt::Display::fmt(&**self, f)
272 }
273}
274
275impl<T: TypedExternal> sealed::Owner for super::ExternalPtr<T> {}
276impl<T: TypedExternal + ?Sized> sealed::Owner for ExternalPtrRef<'_, T> {}
277impl<T: TypedExternal + ?Sized> sealed::Owner for ExternalPtrMut<'_, T> {}
278
279impl<T: TypedExternal> SidecarOwner<T> for super::ExternalPtr<T> {
280 fn __mx_read(&self) -> ExternalPtrRef<'_, T> {
281 self.borrow()
282 }
283}
284impl<T: TypedExternal + ?Sized> SidecarOwner<T> for ExternalPtrRef<'_, T> {
285 fn __mx_read(&self) -> ExternalPtrRef<'_, T> {
286 self.rb()
287 }
288}
289impl<T: TypedExternal + ?Sized> SidecarOwner<T> for ExternalPtrMut<'_, T> {
290 fn __mx_read(&self) -> ExternalPtrRef<'_, T> {
291 self.rb()
292 }
293}
294impl<T: TypedExternal> SidecarOwnerMut<T> for super::ExternalPtr<T> {
295 fn __mx_write(&mut self) -> ExternalPtrMut<'_, T> {
296 self.borrow_mut()
297 }
298}
299impl<T: TypedExternal + ?Sized> SidecarOwnerMut<T> for ExternalPtrMut<'_, T> {
300 fn __mx_write(&mut self) -> ExternalPtrMut<'_, T> {
301 self.rb_mut()
302 }
303}