yoke/cartable_ptr.rs
1// This file is part of ICU4X. For terms of use, please see the file
2// called LICENSE at the top level of the ICU4X source tree
3// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5//! Types for optional pointers with niche optimization.
6//!
7//! The main type is [`CartableOptionPointer`], which is like `Option<Rc>` but
8//! with a niche so that the resulting `Yoke` has a niche. The following four
9//! types can be stored in the `CartableOptionPointer`:
10//!
11//! 1. `&T`
12//! 2. `Box<T>`
13//! 3. `Rc<T>`
14//! 4. `Arc<T>`
15//!
16//! These four types implement the sealed unsafe trait [`CartablePointerLike`].
17//! In addition, all except `Box<T>` impl [`CloneableCartablePointerLike`],
18//! which allows [`CartableOptionPointer`] to implement `Clone`.
19
20use crate::CloneableCart;
21#[cfg(feature = "alloc")]
22use alloc::boxed::Box;
23#[cfg(feature = "alloc")]
24use alloc::rc::Rc;
25#[cfg(feature = "alloc")]
26use alloc::sync::Arc;
27#[cfg(test)]
28use core::cell::Cell;
29use core::marker::PhantomData;
30use core::ptr::NonNull;
31use stable_deref_trait::StableDeref;
32
33// Safety note: this method MUST return the same value for the same T, even if i.e. the method gets
34// instantiated in different crates. This can be untrue in surprising ways! For example, just
35// returning a const-ref-to-const would not guarantee that.
36// The current implementation always returns the same address for any T, see
37// [the reference](https://doc.rust-lang.org/reference/items/static-items.html#statics--generics):
38// there is exactly one `SENTINEL` item for any T.
39#[inline]
40fn sentinel_for<T>() -> NonNull<T> {
41 static SENTINEL: &u8 = &0x1a; // SUB
42
43 // Safety: SENTINEL is indeed not a null pointer, even after the casts.
44 unsafe { NonNull::new_unchecked(SENTINEL as *const u8 as *mut T) }
45}
46
47#[cfg(test)]
48thread_local! {
49 static DROP_INVOCATIONS: Cell<usize> = const { Cell::new(0) };
50}
51
52mod private {
53 pub trait Sealed {}
54}
55
56use private::Sealed;
57
58/// An object fully representable by a non-null pointer.
59///
60/// # Safety
61///
62/// Implementer safety:
63///
64/// 1. `into_raw` transfers ownership of the values referenced by [`StableDeref`] to the caller,
65/// if there is ownership to transfer
66/// 2. `drop_raw` returns ownership back to the impl, if there is ownership to transfer
67///
68/// Note: if `into_raw` returns the sentinel pointer, memory leaks may occur, but this will not
69/// lead to undefined behaviour.
70///
71/// Note: the pointer `NonNull<Self::Raw>` may or may not be aligned and it should never
72/// be dereferenced. Rust allows unaligned pointers; see [`std::ptr::read_unaligned`].
73pub unsafe trait CartablePointerLike: StableDeref + Sealed {
74 /// The raw type used for [`Self::into_raw`] and [`Self::drop_raw`].
75 #[doc(hidden)]
76 type Raw;
77
78 /// Converts this pointer-like into a pointer.
79 #[doc(hidden)]
80 fn into_raw(self) -> NonNull<Self::Raw>;
81
82 /// Drops any memory associated with this pointer-like.
83 ///
84 /// # Safety
85 ///
86 /// Caller safety:
87 ///
88 /// 1. The pointer MUST have been returned by this impl's `into_raw`.
89 /// 2. The pointer MUST NOT be dangling.
90 #[doc(hidden)]
91 unsafe fn drop_raw(pointer: NonNull<Self::Raw>);
92}
93
94/// An object that implements [`CartablePointerLike`] that also
95/// supports cloning without changing the address of referenced data.
96///
97/// # Safety
98///
99/// Implementer safety:
100///
101/// 1. `addref_raw` must create a new owner such that an additional call to
102/// `drop_raw` does not create a dangling pointer
103/// 2. `addref_raw` must not change the address of any referenced data.
104pub unsafe trait CloneableCartablePointerLike: CartablePointerLike {
105 /// Clones this pointer-like.
106 ///
107 /// # Safety
108 ///
109 /// Caller safety:
110 ///
111 /// 1. The pointer MUST have been returned by this impl's `into_raw`.
112 /// 2. The pointer MUST NOT be dangling.
113 #[doc(hidden)]
114 unsafe fn addref_raw(pointer: NonNull<Self::Raw>);
115}
116
117impl<'a, T> Sealed for &'a T {}
118
119// Safety:
120// 1. There is no ownership to transfer
121// 2. There is no ownership to transfer
122unsafe impl<'a, T> CartablePointerLike for &'a T {
123 type Raw = T;
124
125 #[inline]
126 fn into_raw(self) -> NonNull<T> {
127 self.into()
128 }
129 #[inline]
130 unsafe fn drop_raw(_pointer: NonNull<T>) {
131 // No-op: references are borrowed from elsewhere
132 }
133}
134
135// Safety:
136// 1. There is no ownership
137// 2. The impl is a no-op so no addresses are changed.
138unsafe impl<'a, T> CloneableCartablePointerLike for &'a T {
139 #[inline]
140 unsafe fn addref_raw(_pointer: NonNull<T>) {
141 // No-op: references are borrowed from elsewhere
142 }
143}
144
145#[cfg(feature = "alloc")]
146impl<T> Sealed for Box<T> {}
147
148#[cfg(feature = "alloc")]
149// Safety:
150// 1. `Box::into_raw` says: "After calling this function, the caller is responsible for the
151// memory previously managed by the Box."
152// 2. `Box::from_raw` says: "After calling this function, the raw pointer is owned by the
153// resulting Box."
154unsafe impl<T> CartablePointerLike for Box<T> {
155 type Raw = T;
156
157 #[inline]
158 fn into_raw(self) -> NonNull<T> {
159 NonNull::from(Box::leak(self))
160 }
161 #[inline]
162 unsafe fn drop_raw(pointer: NonNull<T>) {
163 // Safety: per the method's precondition, `pointer` is dereferenceable and was returned by
164 // `Self::into_raw`, i.e. by `Box::leak`. In this circumstances, calling
165 // `Box::from_raw` is safe.
166 let _box = unsafe { Box::from_raw(pointer.as_ptr()) };
167
168 // Boxes are always dropped
169 #[cfg(test)]
170 DROP_INVOCATIONS.with(|x| x.set(x.get() + 1))
171 }
172}
173
174#[cfg(feature = "alloc")]
175impl<T> Sealed for Rc<T> {}
176
177#[cfg(feature = "alloc")]
178// Safety:
179// 1. `Rc::into_raw` says: "Consumes the Rc, returning the wrapped pointer. To avoid a memory
180// leak the pointer must be converted back to an Rc using Rc::from_raw."
181// 2. See 1.
182unsafe impl<T> CartablePointerLike for Rc<T> {
183 type Raw = T;
184
185 #[inline]
186 fn into_raw(self) -> NonNull<T> {
187 // Safety: Rcs must contain data (and not be null)
188 unsafe { NonNull::new_unchecked(Rc::into_raw(self) as *mut T) }
189 }
190
191 #[inline]
192 unsafe fn drop_raw(pointer: NonNull<T>) {
193 // Safety: per the method's precondition, `pointer` is dereferenceable and was returned by
194 // `Self::into_raw`, i.e. by `Rc::into_raw`. In this circumstances, calling
195 // `Rc::from_raw` is safe.
196 let _rc = unsafe { Rc::from_raw(pointer.as_ptr()) };
197
198 // Rc is dropped if refcount is 1
199 #[cfg(test)]
200 if Rc::strong_count(&_rc) == 1 {
201 DROP_INVOCATIONS.with(|x| x.set(x.get() + 1))
202 }
203 }
204}
205
206#[cfg(feature = "alloc")]
207// Safety:
208// 1. The impl increases the refcount such that `Drop` will decrease it.
209// 2. The impl increases refcount without changing the address of data.
210unsafe impl<T> CloneableCartablePointerLike for Rc<T> {
211 #[inline]
212 unsafe fn addref_raw(pointer: NonNull<T>) {
213 // Safety: The caller safety of this function says that:
214 // 1. The pointer was obtained through Rc::into_raw
215 // 2. The associated Rc instance is valid
216 // Further, this impl is not defined for anything but the global allocator.
217 unsafe {
218 Rc::increment_strong_count(pointer.as_ptr());
219 }
220 }
221}
222
223#[cfg(feature = "alloc")]
224impl<T> Sealed for Arc<T> {}
225
226#[cfg(feature = "alloc")]
227// Safety:
228// 1. `Rc::into_raw` says: "Consumes the Arc, returning the wrapped pointer. To avoid a memory
229// leak the pointer must be converted back to an Arc using Arc::from_raw."
230// 2. See 1.
231unsafe impl<T> CartablePointerLike for Arc<T> {
232 type Raw = T;
233
234 #[inline]
235 fn into_raw(self) -> NonNull<T> {
236 // Safety: Arcs must contain data (and not be null)
237 unsafe { NonNull::new_unchecked(Arc::into_raw(self) as *mut T) }
238 }
239 #[inline]
240 unsafe fn drop_raw(pointer: NonNull<T>) {
241 // Safety: per the method's precondition, `pointer` is dereferenceable and was returned by
242 // `Self::into_raw`, i.e. by `Rc::into_raw`. In this circumstances, calling
243 // `Rc::from_raw` is safe.
244 let _arc = unsafe { Arc::from_raw(pointer.as_ptr()) };
245
246 // Arc is dropped if refcount is 1
247 #[cfg(test)]
248 if Arc::strong_count(&_arc) == 1 {
249 DROP_INVOCATIONS.with(|x| x.set(x.get() + 1))
250 }
251 }
252}
253
254#[cfg(feature = "alloc")]
255// Safety:
256// 1. The impl increases the refcount such that `Drop` will decrease it.
257// 2. The impl increases refcount without changing the address of data.
258unsafe impl<T> CloneableCartablePointerLike for Arc<T> {
259 #[inline]
260 unsafe fn addref_raw(pointer: NonNull<T>) {
261 // Safety: The caller safety of this function says that:
262 // 1. The pointer was obtained through Arc::into_raw
263 // 2. The associated Arc instance is valid
264 // Further, this impl is not defined for anything but the global allocator.
265 unsafe {
266 Arc::increment_strong_count(pointer.as_ptr());
267 }
268 }
269}
270
271/// A type with similar semantics as `Option<C<T>>` but with a niche.
272///
273/// This type cannot be publicly constructed. To use this in a `Yoke`, see
274/// [`Yoke::convert_cart_into_option_pointer`].
275///
276/// [`Yoke::convert_cart_into_option_pointer`]: crate::Yoke::convert_cart_into_option_pointer
277#[derive(Debug)]
278pub struct CartableOptionPointer<C>
279where
280 C: CartablePointerLike,
281{
282 /// The inner pointer.
283 ///
284 /// # Invariants
285 ///
286 /// 1. Must be either `SENTINEL_PTR` or created from [`CartablePointerLike::into_raw`]
287 /// 2. If non-sentinel, must _always_ be for a valid `SelectedRc`
288 inner: NonNull<C::Raw>,
289 _cartable: PhantomData<C>,
290}
291
292impl<C> CartableOptionPointer<C>
293where
294 C: CartablePointerLike,
295{
296 /// Creates a new instance corresponding to a `None` value.
297 #[inline]
298 pub(crate) fn none() -> Self {
299 Self {
300 inner: sentinel_for::<C::Raw>(),
301 _cartable: PhantomData,
302 }
303 }
304
305 /// Creates a new instance corresponding to a `Some` value.
306 #[inline]
307 pub(crate) fn from_cartable(cartable: C) -> Self {
308 let inner = cartable.into_raw();
309 debug_assert_ne!(inner, sentinel_for::<C::Raw>());
310 Self {
311 inner,
312 _cartable: PhantomData,
313 }
314 }
315
316 /// Returns whether this instance is `None`. From the return value:
317 ///
318 /// - If `true`, the instance is `None`
319 /// - If `false`, the instance is a valid `SelectedRc`
320 #[inline]
321 pub fn is_none(&self) -> bool {
322 self.inner == sentinel_for::<C::Raw>()
323 }
324}
325
326impl<C> Drop for CartableOptionPointer<C>
327where
328 C: CartablePointerLike,
329{
330 #[inline]
331 fn drop(&mut self) {
332 let ptr = self.inner;
333 if ptr != sentinel_for::<C::Raw>() {
334 // By the invariants, `ptr` is a valid raw value since it's
335 // either that or sentinel, and we just checked for sentinel.
336 // We will replace it with the sentinel and then drop `ptr`.
337 self.inner = sentinel_for::<C::Raw>();
338 // Safety: by the invariants, `ptr` is a valid raw value.
339 unsafe { C::drop_raw(ptr) }
340 }
341 }
342}
343
344impl<C> Clone for CartableOptionPointer<C>
345where
346 C: CloneableCartablePointerLike,
347{
348 #[inline]
349 fn clone(&self) -> Self {
350 let ptr = self.inner;
351 if ptr != sentinel_for::<C::Raw>() {
352 // By the invariants, `ptr` is a valid raw value since it's
353 // either that or sentinel, and we just checked for sentinel.
354 // Safety: by the invariants, `ptr` is a valid raw value.
355 unsafe { C::addref_raw(ptr) }
356 }
357 Self {
358 inner: self.inner,
359 _cartable: PhantomData,
360 }
361 }
362}
363
364// Safety: logically an Option<C>. Has same bounds as Option<C>.
365// The `StableDeref` parts of `C` continue to be `StableDeref`.
366unsafe impl<C> CloneableCart for CartableOptionPointer<C> where
367 C: CloneableCartablePointerLike + CloneableCart
368{
369}
370
371// Safety: logically an Option<C>. Has same bounds as Option<C>
372unsafe impl<C> Send for CartableOptionPointer<C> where C: Send + CartablePointerLike {}
373
374// Safety: logically an Option<C>. Has same bounds as Option<C>
375unsafe impl<C> Sync for CartableOptionPointer<C> where C: Sync + CartablePointerLike {}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380 use crate::Yoke;
381
382 const SAMPLE_BYTES: &[u8] = b"abCDEfg";
383 const W: usize = size_of::<usize>();
384
385 #[test]
386 fn test_sizes() {
387 assert_eq!(W * 4, size_of::<Yoke<[usize; 3], &&[u8]>>());
388 assert_eq!(W * 4, size_of::<Yoke<[usize; 3], Option<&&[u8]>>>());
389 assert_eq!(
390 W * 4,
391 size_of::<Yoke<[usize; 3], CartableOptionPointer<&&[u8]>>>()
392 );
393
394 assert_eq!(W * 4, size_of::<Option<Yoke<[usize; 3], &&[u8]>>>());
395 assert_eq!(W * 5, size_of::<Option<Yoke<[usize; 3], Option<&&[u8]>>>>());
396 assert_eq!(
397 W * 4,
398 size_of::<Option<Yoke<[usize; 3], CartableOptionPointer<&&[u8]>>>>()
399 );
400 }
401
402 #[test]
403 fn test_new_sentinel() {
404 let start = DROP_INVOCATIONS.with(Cell::get);
405 {
406 let _ = CartableOptionPointer::<Rc<&[u8]>>::none();
407 }
408 assert_eq!(start, DROP_INVOCATIONS.with(Cell::get));
409 {
410 let _ = CartableOptionPointer::<Rc<&[u8]>>::none();
411 }
412 assert_eq!(start, DROP_INVOCATIONS.with(Cell::get));
413 }
414
415 #[test]
416 fn test_new_rc() {
417 let start = DROP_INVOCATIONS.with(Cell::get);
418 {
419 let _ = CartableOptionPointer::<Rc<&[u8]>>::from_cartable(SAMPLE_BYTES.into());
420 }
421 assert_eq!(start + 1, DROP_INVOCATIONS.with(Cell::get));
422 }
423
424 #[test]
425 fn test_rc_clone() {
426 let start = DROP_INVOCATIONS.with(Cell::get);
427 {
428 let x = CartableOptionPointer::<Rc<&[u8]>>::from_cartable(SAMPLE_BYTES.into());
429 assert_eq!(start, DROP_INVOCATIONS.with(Cell::get));
430 {
431 let _ = x.clone();
432 }
433 assert_eq!(start, DROP_INVOCATIONS.with(Cell::get));
434 {
435 let _ = x.clone();
436 let _ = x.clone();
437 let _ = x.clone();
438 }
439 assert_eq!(start, DROP_INVOCATIONS.with(Cell::get));
440 }
441 assert_eq!(start + 1, DROP_INVOCATIONS.with(Cell::get));
442 }
443
444 // Miri test for CartableOptionPointer Send/Sync soundness.
445 //
446 // Verifies that a CartableOptionPointer wrapping a Send + !Sync cart can be
447 // safely sent to another thread and dropped, which compiles under the corrected
448 // bounds but would fail under the old (backwards) bounds.
449 #[test]
450 fn test_send_drops_on_another_thread() {
451 use std::marker::PhantomData;
452
453 // ThreadDrop is Send but !Sync
454 struct ThreadDrop {
455 _not_sync: PhantomData<Cell<i32>>,
456 }
457
458 let yoke = Yoke::<usize, Box<ThreadDrop>>::attach_to_cart(
459 Box::new(ThreadDrop {
460 _not_sync: PhantomData,
461 }),
462 |_| 0,
463 )
464 .wrap_cart_in_option()
465 .convert_cart_into_option_pointer();
466
467 // This requires CartableOptionPointer to be Send.
468 // It is Send because Box<ThreadDrop> is Send.
469 // It would NOT be Send under the old bounds because Box<ThreadDrop> is !Sync.
470 std::thread::spawn(move || drop(yoke)).join().unwrap();
471 }
472}