potential-well 1.1.0

Atomic boxes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! [`Well`] and [`WellMut`] traits.
use core::{
    ops::{Deref, DerefMut},
    pin::Pin,
    ptr::NonNull,
};

#[cfg(feature = "alloc")]
use {
    crate::atomic::{PotentialAtomic, PotentialAtomicOption},
    alloc::{boxed::Box, rc::Rc, sync::Arc},
};

/// Place that can store a smart pointer.
///
/// # Safety
///
/// Types that implement this trait assert that:
///
/// 1. The `insert` and `remove` methods are true inverses of each other with no side effects.
/// 2. The pointer to the data is stable on [`Deref`] and [`DerefMut`] (if implemented), *and* this
///    pointer is the same as the one that is returned by [`remove`].
/// 3. The data may be read even when outside the well.
/// 4. If [`DerefMut`] is implemented, the data may be mutated even when outside the well.
///
/// [`insert`]: Well::insert
/// [`remove`]: Well::remove
pub unsafe trait Well: Deref<Target: Sized> {
    /// Put the data back into the well.
    ///
    /// # Safety
    ///
    /// The pointer passed to [`insert`] must previously have been received from [`remove`].
    ///
    /// [`insert`]: Well::insert
    /// [`remove`]: Well::remove
    unsafe fn insert(ptr: NonNull<Self::Target>) -> Self;

    /// Take the data out of the well.
    fn remove(self) -> NonNull<Self::Target>;
}

/// Implementation of trait alias that uses trait aliases.
#[cfg(feature = "nightly")]
macro_rules! trait_alias {
    (
        $(#[$attr:meta])*
        $vis:vis trait $t:ident = ($($bound:tt)*);
    ) => {
        $(#[$attr])*
        ///
        /// Implemented as a trait alias with the `nightly` feature,
        /// and an automatically-implemented trait otherwise.
        $vis trait $t = $($bound)*;
    }
}

/// Implementation of trait alias that uses traits.
#[cfg(not(feature = "nightly"))]
macro_rules! trait_alias {
    (
        $(#[$attr:meta])*
        $vis:vis trait $t:ident = ($($bound:tt)*);
    ) => {
        $(#[$attr])*
        ///
        /// Implemented as a trait alias with the `nightly` feature,
        /// and an automatically-implemented trait otherwise.
        $vis trait $t: $($bound)* {}
        impl<T: $($bound)*> $t for T {}
    }
}

trait_alias! {
    /// Alias for <code>[Well] + [DerefMut]</code>.
    pub trait WellMut = (DerefMut + Well);
}

// SAFETY: A pointer in its almost-rawest form.
unsafe impl<T> Well for &T {
    #[inline]
    unsafe fn insert(ptr: NonNull<T>) -> Self {
        // SAFETY: Ensured by caller.
        unsafe { ptr.as_ref() }
    }

    #[inline]
    fn remove(self) -> NonNull<T> {
        NonNull::from(self)
    }
}

// SAFETY: A pointer in its almost-rawest form.
unsafe impl<T> Well for Pin<&T> {
    #[inline]
    unsafe fn insert(ptr: NonNull<T>) -> Self {
        // SAFETY: Ensured by caller.
        unsafe { Pin::new_unchecked(ptr.as_ref()) }
    }

    #[inline]
    fn remove(self) -> NonNull<T> {
        NonNull::from(self.get_ref())
    }
}

// SAFETY: A pointer in its almost-rawest form.
unsafe impl<T> Well for &mut T {
    #[inline]
    unsafe fn insert(mut ptr: NonNull<T>) -> Self {
        // SAFETY: Ensured by caller.
        unsafe { ptr.as_mut() }
    }

    #[inline]
    fn remove(self) -> NonNull<T> {
        NonNull::from(self)
    }
}

// SAFETY: A pointer in its almost-rawest form.
unsafe impl<T> Well for Pin<&mut T> {
    #[inline]
    unsafe fn insert(mut ptr: NonNull<T>) -> Self {
        // SAFETY: Ensured by caller.
        unsafe { Pin::new_unchecked(ptr.as_mut()) }
    }

    #[inline]
    fn remove(self) -> NonNull<T> {
        // SAFETY: We can only get a pinned version back out of the well.
        unsafe { NonNull::from(self.get_unchecked_mut()) }
    }
}

#[cfg(any(test, feature = "alloc"))]
// SAFETY: `Box` just wraps a pointer.
unsafe impl<T> Well for Box<T> {
    #[inline]
    unsafe fn insert(ptr: NonNull<T>) -> Self {
        // SAFETY: Ensured by caller.
        unsafe { Box::from_raw(ptr.as_ptr()) }
    }

    #[inline]
    fn remove(self) -> NonNull<T> {
        // SAFETY: Box's pointer is always non-null.
        unsafe { NonNull::new_unchecked(Box::into_raw(self)) }
    }
}

#[cfg(any(test, feature = "alloc"))]
// SAFETY: If we keep the pin, everything works out.
unsafe impl<T> Well for Pin<Box<T>> {
    #[inline]
    unsafe fn insert(ptr: NonNull<T>) -> Self {
        // SAFETY: Ensured by caller.
        unsafe { Pin::new_unchecked(Box::from_raw(ptr.as_ptr())) }
    }

    #[inline]
    fn remove(self) -> NonNull<T> {
        // SAFETY: Box's pointer is always non-null, and we're not moving anything out of the box.
        unsafe { NonNull::new_unchecked(Box::into_raw(Pin::into_inner_unchecked(self))) }
    }
}

#[cfg(feature = "alloc")]
// SAFETY: `Rc` accounts for the reference-counter offsets in `into_raw` and `from_raw`.
unsafe impl<T> Well for Rc<T> {
    #[inline]
    unsafe fn insert(ptr: NonNull<T>) -> Self {
        // SAFETY: Ensured by caller.
        unsafe { Rc::from_raw(ptr.as_ptr()) }
    }

    #[inline]
    fn remove(self) -> NonNull<T> {
        // SAFETY: Rc's pointer is always non-null.
        unsafe { NonNull::new_unchecked(Rc::into_raw(self).cast_mut()) }
    }
}

#[cfg(feature = "alloc")]
// SAFETY: If we keep the pin, everything works out.
unsafe impl<T> Well for Pin<Rc<T>> {
    #[inline]
    unsafe fn insert(ptr: NonNull<T>) -> Self {
        // SAFETY: Ensured by caller.
        unsafe { Pin::new_unchecked(Rc::from_raw(ptr.as_ptr())) }
    }

    #[inline]
    fn remove(self) -> NonNull<T> {
        // SAFETY: Rc's pointer is always non-null, and we're not moving anything out of the `Rc`.
        unsafe { NonNull::new_unchecked(Rc::into_raw(Pin::into_inner_unchecked(self)).cast_mut()) }
    }
}

#[cfg(feature = "alloc")]
// SAFETY: `Arc` accounts for the reference-counter offsets in `into_raw` and `from_raw`.
unsafe impl<T> Well for Arc<T> {
    #[inline]
    unsafe fn insert(ptr: NonNull<T>) -> Self {
        // SAFETY: Ensured by caller.
        unsafe { Arc::from_raw(ptr.as_ptr()) }
    }

    #[inline]
    fn remove(self) -> NonNull<T> {
        // SAFETY: Arc's pointer is always non-null.
        unsafe { NonNull::new_unchecked(Arc::into_raw(self).cast_mut()) }
    }
}

#[cfg(feature = "alloc")]
// SAFETY: If we keep the pin, everything works out.
unsafe impl<T> Well for Pin<Arc<T>> {
    #[inline]
    unsafe fn insert(ptr: NonNull<T>) -> Self {
        // SAFETY: Ensured by caller.
        unsafe { Pin::new_unchecked(Arc::from_raw(ptr.as_ptr())) }
    }

    #[inline]
    fn remove(self) -> NonNull<T> {
        // SAFETY: Arc's pointer is always non-null, and we're not moving anything out of the `Arc`.
        unsafe { NonNull::new_unchecked(Arc::into_raw(Pin::into_inner_unchecked(self)).cast_mut()) }
    }
}

/// Potential well, representing a generic container.
///
/// Useful for recursive data structures, since it avoids recursive types.
///
/// # Examples
///
/// Atomic linked list via [`PotentialWell`]:
///
/// ```
/// use potential_well::{PotentialWell, PotentialAtomicOption};
///
/// struct Link<T, W: PotentialWell = Box<()>> {
///     data: T,
///     next: PotentialAtomicOption<Link<T, W>, W>
/// }
/// struct List<T, W: PotentialWell = Box<()>> {
///     root: PotentialAtomicOption<Link<T, W>, W>,
/// }
///
/// let list: List<u32> = List {
///     root: PotentialAtomicOption::some(Box::new(Link {
///         data: 1,
///         next: PotentialAtomicOption::some(Box::new(Link {
///             data: 2,
///             next: PotentialAtomicOption::some(Box::new(Link {
///                 data: 3,
///                 next: PotentialAtomicOption::none(),
///             }))
///         })),
///     })),
/// };
///
/// // no Drop implementation needed!
/// drop(list);
/// ```
///
/// Without [`PotentialWell`], you immediately run into trouble:
///
/// ```compile_fail
/// use potential_well::{Well, AtomicOption};
///
/// // recursive type: Link<T, Box<Link<T, Box<Link<T, ...>>>>>
/// struct Link<T, W: Well<Target = Link<T, Self>>> {
///     data: T,
///     next: AtomicOption<W>,
/// }
/// struct List<T, W: Well<Target = Link<T, Self>>> {
///     root: AtomicOption<W>,
/// }
///
/// let list: List<u32, Box<_>> = List {
///     root: AtomicOption::some(Box::new(Link {
///         data: 1,
///         next: AtomicOption::some(Box::new(Link {
///             data: 2,
///             next: AtomicOption::some(Box::new(Link {
///                 data: 3,
///                 next: AtomicOption::none(),
///             }))
///         })),
///     })),
/// };
/// ```
pub trait PotentialWell {
    /// Makes a well of a particular type.
    type Well<T>: Well<Target = T>;

    /// Makes that well.
    fn new<T>(data: T) -> Self::Well<T>;
}

#[cfg(any(test, feature = "alloc"))]
impl PotentialWell for Box<()> {
    type Well<T> = Box<T>;

    #[inline]
    fn new<T>(data: T) -> Box<T> {
        Box::new(data)
    }
}

#[cfg(any(test, feature = "alloc"))]
impl PotentialWell for Pin<Box<()>> {
    type Well<T> = Pin<Box<T>>;

    #[inline]
    fn new<T>(data: T) -> Pin<Box<T>> {
        Box::pin(data)
    }
}

#[cfg(feature = "alloc")]
impl PotentialWell for Rc<()> {
    type Well<T> = Rc<T>;

    #[inline]
    fn new<T>(data: T) -> Rc<T> {
        Rc::new(data)
    }
}

#[cfg(feature = "alloc")]
impl PotentialWell for Pin<Rc<()>> {
    type Well<T> = Pin<Rc<T>>;

    #[inline]
    fn new<T>(data: T) -> Pin<Rc<T>> {
        Rc::pin(data)
    }
}

#[cfg(feature = "alloc")]
impl PotentialWell for Arc<()> {
    type Well<T> = Arc<T>;

    #[inline]
    fn new<T>(data: T) -> Arc<T> {
        Arc::new(data)
    }
}

#[cfg(feature = "alloc")]
impl PotentialWell for Pin<Arc<()>> {
    type Well<T> = Pin<Arc<T>>;

    #[inline]
    fn new<T>(data: T) -> Pin<Arc<T>> {
        Arc::pin(data)
    }
}

/// Gets a well from a [`PotentialWell`].
///
/// In case you haven't gotten the joke by now, an "atom in a box" is called a [potential well] in
/// physics, and well, kinetic energy is the opposite of potential energy.
///
/// It's a bad joke. But this type shouldn't be necessary unless you're writing *really* generic
/// code, since most of the time, you'll be using one of the many aliases for [`PotentialAtomic`]
/// and [`PotentialAtomicOption`], which will just turn something like
/// <code>[KineticWell]&lt;T, W&lt;()&gt;&gt;</code> into <code>W&lt;T&gt;</code>.
///
/// [potential well]: https://en.wikipedia.org/wiki/Potential_well
pub type KineticWell<T, W> = <W as PotentialWell>::Well<T>;

/// Alias for <code>[PotentialAtomic]&lt;T, [Box]&lt;()&gt;&gt;</code>
#[cfg(feature = "alloc")]
pub type AtomicBox<T> = PotentialAtomic<T, Box<()>>;

/// Alias for <code>[PotentialAtomic]&lt;T, [Pin]&lt;[Box]&lt;()&gt;&gt;&gt;</code>
#[cfg(feature = "alloc")]
pub type AtomicPinBox<T> = PotentialAtomic<T, Pin<Box<()>>>;

/// Alias for <code>[PotentialAtomic]&lt;T, [Rc]&lt;()&gt;&gt;</code>
#[cfg(feature = "alloc")]
pub type AtomicRc<T> = PotentialAtomic<T, Rc<()>>;

/// Alias for <code>[PotentialAtomic]&lt;T, [Pin]&lt;[Rc]&lt;()&gt;&gt;&gt;</code>
#[cfg(feature = "alloc")]
pub type AtomicPinRc<T> = PotentialAtomic<T, Pin<Rc<()>>>;

/// Alias for <code>[PotentialAtomic]&lt;T, [Arc]&lt;()&gt;&gt;</code>
#[cfg(feature = "alloc")]
pub type AtomicArc<T> = PotentialAtomic<T, Arc<()>>;

/// Alias for <code>[PotentialAtomic]&lt;T, [Pin]&lt;[Arc]&lt;()&gt;&gt;&gt;</code>
#[cfg(feature = "alloc")]
pub type AtomicPinArc<T> = PotentialAtomic<T, Pin<Arc<()>>>;

/// Alias for <code>[PotentialAtomicOption]&lt;T, [Box]&lt;()&gt;&gt;</code>
#[cfg(feature = "alloc")]
pub type AtomicOptionBox<T> = PotentialAtomicOption<T, Box<()>>;

/// Alias for <code>[PotentialAtomicOption]&lt;T, [Pin]&lt;[Box]&lt;()&gt;&gt;&gt;</code>
#[cfg(feature = "alloc")]
pub type AtomicOptionPinBox<T> = PotentialAtomicOption<T, Pin<Box<()>>>;

/// Alias for <code>[PotentialAtomicOption]&lt;T, [Rc]&lt;()&gt;&gt;</code>
#[cfg(feature = "alloc")]
pub type AtomicOptionRc<T> = PotentialAtomicOption<T, Rc<()>>;

/// Alias for <code>[PotentialAtomicOption]&lt;T, [Pin]&lt;[Rc]&lt;()&gt;&gt;&gt;</code>
#[cfg(feature = "alloc")]
pub type AtomicOptionPinRc<T> = PotentialAtomicOption<T, Pin<Rc<()>>>;

/// Alias for <code>[PotentialAtomicOption]&lt;T, [Arc]&lt;()&gt;&gt;</code>
#[cfg(feature = "alloc")]
pub type AtomicOptionArc<T> = PotentialAtomicOption<T, Arc<()>>;

/// Alias for <code>[PotentialAtomicOption]&lt;T, [Pin]&lt;[Arc]&lt;()&gt;&gt;&gt;</code>
#[cfg(feature = "alloc")]
pub type AtomicOptionPinArc<T> = PotentialAtomicOption<T, Pin<Arc<()>>>;