unique_pointer/
unique_pointer.rs

1use std::alloc::Layout;
2use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd};
3use std::convert::{AsMut, AsRef};
4use std::fmt::{Debug, Formatter, Pointer};
5use std::hash::{Hash, Hasher};
6use std::ops::{Deref, DerefMut};
7
8use crate::{RefCounter, UniquePointee};
9
10/// `UniquePointer` is an experimental data structure that makes
11/// extensive use of unsafe rust to provide a shared pointer
12/// throughout the runtime of a rust program as transparently as
13/// possible.
14///
15/// [UniquePointer]'s design's purpose is two-fold:
16///
17/// - Leverage the implementation of circular data structures such as
18/// Lisp cons cells.
19///
20/// - Making easier the task of practicing the implementation of basic
21/// computer science data-structures (e.g.: Binary Trees, Linked Lists
22/// etc) such that the concept of pointer is as close to C as possible
23/// in terms of developer experience and so when a CS teacher speaks
24/// in terms of pointers, students can use [UniquePointer] in their
25/// data-structures knowing that cloning their data-structures also
26/// means cloning the pointers transparently.
27///
28/// In fact, the author designed `UniquePointer` while studying the
29/// MIT CourseWare material of professor Erik Demaine in addition to
30/// studying lisp "cons" cells.
31///
32/// To this point the author reiterates: `UniquePointer` is an
33/// **experimental** data-structure designed primarily as a
34/// building-block of other data-structures in rust.
35///
36/// `UniquePointer` provides the methods [`UniquePointer::cast_mut`]
37/// and [`UniquePointer::cast_const`] not unlike those of raw
38/// pointers, and also implements the methods
39/// [`UniquePointer::as_ref`] and [`UniquePointer::as_mut`] with a
40/// signature compatible with that of the [AsRef] and [AsMut]
41/// traits such that users of raw pointers can migrate to
42/// [UniquePointer] without much difficulty.
43///
44/// `UniquePointer` is designed a way such that Enums and Structs
45/// using `UniquePointer` can safely clone `UniquePointer` while the
46/// memory address and provenance of its value is shared.
47///
48/// [UniquePointer] is able to extend lifetimes because it maintains
49/// its own reference counting outside of the rust compiler.
50///
51/// Reference Counting is provided by [RefCounter] which uses unsafe
52/// rust to ensure that ref counts are shared across cloned objects
53/// memory.
54///
55/// Both [UniquePointer] and [RefCounter] use relatively obscure
56/// rust techniques under the hood to allow writing in non-mut
57/// references in strategic occasions such as incrementing its
58/// reference count within its [Clone] implementation.
59///
60/// UniquePointer only supports [Sized] types, that is, [Zero-Sized
61/// Types](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts)
62/// (ZSTs) are not supported.
63///
64/// Example
65///
66/// ```
67/// use unique_pointer::UniquePointer;
68///
69/// fn create_unique_pointer<'a>() -> UniquePointer<&'a str> {
70///     UniquePointer::from("string")
71/// }
72/// let mut value: UniquePointer<&'_ str> = create_unique_pointer();
73///
74/// assert_eq!(value.is_null(), false);
75///
76/// assert_eq!(value.is_allocated(), true);
77/// assert!(value.addr() > 0, "address should not be null");
78/// assert_eq!(value.is_written(), true);
79/// assert_eq!(value.inner_ref(), &"string");
80///
81/// assert_eq!(value.read(), "string");
82/// assert_eq!(value.as_ref(), Some(&"string"));
83/// ```
84///
85/// # Caveats
86///
87/// - Only supports types that implement [Debug]
88/// - Does not support [ZSTs](https://doc.rust-lang.org/nomicon/exotic-sizes.html#zero-sized-types-zsts) (Zero-Sized Types)
89/// - [UniquePointer] **IS NOT THREAD SAFE**
90///
91/// # Lisp Cons Cell Example
92///
93/// ```
94/// use std::iter::Extend;
95///
96/// use unique_pointer::{RefCounter, UniquePointer};
97/// # use std::borrow::Cow;
98/// # use std::convert::{AsMut, AsRef};
99/// #
100/// # #[derive(Clone, PartialOrd, Ord, Default, PartialEq, Eq)]
101/// # pub enum Value<'c> {
102/// #     #[default]
103/// #     Nil,
104/// #     String(Cow<'c, str>),
105/// #     Byte(u8),
106/// #     UInt(u64),
107/// #     Int(i64),
108/// # }
109/// # impl<'c> Value<'_> {
110/// #     pub fn nil() -> Value<'c> {
111/// #         Value::Nil
112/// #     }
113/// #
114/// #     pub fn is_nil(&self) -> bool {
115/// #         if *self == Value::Nil {
116/// #             true
117/// #         } else {
118/// #             false
119/// #         }
120/// #     }
121/// # }
122/// #
123/// # impl<'c> Drop for Value<'c> {
124/// #     fn drop(&mut self) {}
125/// # }
126/// #
127/// # impl std::fmt::Display for Value<'_> {
128/// #     fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
129/// #         write!(
130/// #             f,
131/// #             "{}",
132/// #             match self {
133/// #                 Value::Nil => "nil".to_string(),
134/// #                 Value::String(h) => format!("{}", h),
135/// #                 Value::Byte(h) => format!("{}", h),
136/// #                 Value::UInt(h) => format!("{}", h),
137/// #                 Value::Int(h) => format!("{}", h),
138/// #             }
139/// #         )
140/// #     }
141/// # }
142/// # impl std::fmt::Debug for Value<'_> {
143/// #     fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
144/// #         write!(
145/// #             f,
146/// #             "{}",
147/// #             match self {
148/// #                 Value::Nil => "nil".to_string(),
149/// #                 Value::String(h) => format!("{:#?}", h),
150/// #                 Value::Byte(h) => format!("{}u8", h),
151/// #                 Value::UInt(h) => format!("{}u64", h),
152/// #                 Value::Int(h) => format!("{}i64", h),
153/// #             }
154/// #         )
155/// #     }
156/// # }
157/// #
158/// # impl<'c> From<u8> for Value<'c> {
159/// #     fn from(value: u8) -> Value<'c> {
160/// #         Value::Byte(value)
161/// #     }
162/// # }
163/// # impl<'c> From<u64> for Value<'c> {
164/// #     fn from(value: u64) -> Value<'c> {
165/// #         Value::UInt(value)
166/// #     }
167/// # }
168/// # impl<'c> From<i64> for Value<'c> {
169/// #     fn from(value: i64) -> Value<'c> {
170/// #         Value::Int(value)
171/// #     }
172/// # }
173/// # impl<'c> From<&'c str> for Value<'c> {
174/// #     fn from(value: &'c str) -> Value<'c> {
175/// #         Value::String(Cow::from(value))
176/// #     }
177/// # }
178/// # impl<'c> From<Cow<'c, str>> for Value<'c> {
179/// #     fn from(value: Cow<'c, str>) -> Value<'c> {
180/// #         Value::from(value.into_owned())
181/// #     }
182/// # }
183/// # impl<'c> From<&'c mut str> for Value<'c> {
184/// #     fn from(value: &'c mut str) -> Value<'c> {
185/// #         Value::String(Cow::<'c, str>::Borrowed(&*value))
186/// #     }
187/// # }
188/// # impl<'c> From<String> for Value<'c> {
189/// #     fn from(value: String) -> Value<'c> {
190/// #         Value::String(Cow::from(value))
191/// #     }
192/// # }
193/// # impl<'c> From<Option<String>> for Value<'c> {
194/// #     fn from(value: Option<String>) -> Value<'c> {
195/// #         match value {
196/// #             None => Value::Nil,
197/// #             Some(value) => Value::from(value),
198/// #         }
199/// #     }
200/// # }
201/// #
202/// # impl<'c> AsRef<Value<'c>> for Value<'c> {
203/// #     fn as_ref(&self) -> &Value<'c> {
204/// #         unsafe { &*self }
205/// #     }
206/// # }
207/// # impl<'c> AsMut<Value<'c>> for Value<'c> {
208/// #     fn as_mut(&mut self) -> &mut Value<'c> {
209/// #         unsafe { &mut *self }
210/// #     }
211/// # }
212/// #
213/// # impl<'c> PartialEq<&Value<'c>> for Value<'c> {
214/// #     fn eq(&self, other: &&Value<'c>) -> bool {
215/// #         let other = unsafe { &**other };
216/// #         self == other
217/// #     }
218/// # }
219/// #
220/// # impl<'c> PartialEq<&mut Value<'c>> for Value<'c> {
221/// #     fn eq(&self, other: &&mut Value<'c>) -> bool {
222/// #         let other = unsafe { &**other };
223/// #         self == other
224/// #     }
225/// # }
226/// #
227///
228/// #[derive(Debug)]
229/// pub struct Cell<'c> {
230///     head: UniquePointer<Value<'c>>,
231///     tail: UniquePointer<Cell<'c>>,
232///     refs: RefCounter,
233///     length: usize,
234/// }
235///
236/// impl<'c> Cell<'c> {
237///     pub fn nil() -> Cell<'c> {
238///         Cell {
239///             head: UniquePointer::<Value<'c>>::null(),
240///             tail: UniquePointer::<Cell<'c>>::null(),
241///             refs: RefCounter::null(),
242///             length: 0,
243///         }
244///     }
245///
246///     pub fn is_nil(&self) -> bool {
247///         self.head.is_null() && self.tail.is_null()
248///     }
249///
250///     pub fn new(value: Value<'c>) -> Cell<'c> {
251///         let mut cell = Cell::nil();
252///         cell.write(value);
253///         cell
254///     }
255///
256///     fn write(&mut self, value: Value<'c>) {
257///         self.head.write(value);
258///         self.refs.write(1);
259///         self.length = 1;
260///     }
261///
262///     fn swap_head(&mut self, other: &mut Self) {
263///         self.head = unsafe {
264///             let head = other.head.propagate();
265///             other.head = self.head.propagate();
266///             head
267///         };
268///     }
269///
270///     fn swap_refs(&mut self, other: &mut Self) {
271///         self.refs = {
272///             let refs = other.refs.clone();
273///             other.refs = self.refs.clone();
274///             refs
275///         };
276///     }
277///
278///     pub fn head(&self) -> Option<Value<'c>> {
279///         self.head.try_read()
280///     }
281///
282///     pub fn add(&mut self, new: &mut Cell<'c>) {
283///         new.incr_ref();
284///         self.incr_ref();
285///         if self.head.is_null() {
286///             unsafe {
287///                 if !new.head.is_null() {
288///                     self.swap_head(new);
289///                 }
290///
291///                 if !new.tail.is_null() {
292///                     let tail = new.tail.inner_mut();
293///                     tail.swap_head(new);
294///                     self.swap_refs(new);
295///                 }
296///                 self.tail = UniquePointer::read_only(new);
297///             }
298///         } else {
299///             if self.tail.is_null() {
300///                 self.tail = UniquePointer::read_only(new);
301///             } else {
302///                 self.tail.inner_mut().add(new);
303///             }
304///         }
305///     }
306///
307///     pub fn pop(&mut self) -> bool {
308///         if !self.tail.is_null() {
309///             self.tail.drop_in_place();
310///             self.tail = UniquePointer::null();
311///             true
312///         } else if !self.head.is_null() {
313///             self.head.drop_in_place();
314///             self.head = UniquePointer::null();
315///             true
316///         } else {
317///             false
318///         }
319///     }
320///
321///     pub fn is_empty(&self) -> bool {
322///         self.len() > 0
323///     }
324///
325///     pub fn len(&self) -> usize {
326///         let mut len = 0;
327///         if !self.head.is_null() {
328///             len += 1
329///         }
330///         if let Some(tail) = self.tail() {
331///             len += tail.len();
332///         }
333///         len
334///     }
335///
336///     pub fn tail(&self) -> Option<&'c Cell<'c>> {
337///         self.tail.as_ref()
338///     }
339///
340///     pub fn values(&self) -> Vec<Value<'c>> {
341///         let mut values = Vec::<Value>::new();
342///         if let Some(head) = self.head() {
343///             values.push(head.clone());
344///         }
345///         if let Some(tail) = self.tail() {
346///             values.extend(tail.values());
347///         }
348///         values
349///     }
350///
351///     fn incr_ref(&mut self) {
352///         self.refs += 1;
353///         if !self.tail.is_null() {
354///             if let Some(tail) = self.tail.as_mut() {
355///                 tail.incr_ref();
356///             }
357///         }
358///     }
359///
360///     fn decr_ref(&mut self) {
361///         self.refs -= 1;
362///         if !self.tail.is_null() {
363///             if let Some(tail) = self.tail.as_mut() {
364///                 tail.decr_ref();
365///             }
366///         }
367///     }
368///
369///     fn dealloc(&mut self) {
370///         if self.refs > 0 {
371///             self.decr_ref();
372///         } else {
373///             self.head.drop_in_place();
374///             self.tail.drop_in_place();
375///         }
376///     }
377/// }
378///
379/// impl<'c> From<Value<'c>> for Cell<'c> {
380///     fn from(value: Value<'c>) -> Cell<'c> {
381///         Cell::new(value)
382///     }
383/// }
384/// impl<'c> From<&'c str> for Cell<'c> {
385///     fn from(value: &'c str) -> Cell<'c> {
386///         let value = Value::from(value);
387///         Cell::new(value)
388///     }
389/// }
390/// impl<'c> From<u8> for Cell<'c> {
391///     fn from(value: u8) -> Cell<'c> {
392///         Cell::new(Value::Byte(value))
393///     }
394/// }
395/// impl<'c> From<u64> for Cell<'c> {
396///     fn from(value: u64) -> Cell<'c> {
397///         if value < u8::MAX.into() {
398///             Cell::new(Value::Byte(value as u8))
399///         } else {
400///             Cell::new(Value::UInt(value))
401///         }
402///     }
403/// }
404/// impl<'c> From<i32> for Cell<'c> {
405///     fn from(value: i32) -> Cell<'c> {
406///         if let Ok(value) = TryInto::<u64>::try_into(value) {
407///             Cell::new(Value::UInt(value))
408///         } else {
409///             Cell::new(Value::Int(value.into()))
410///         }
411///     }
412/// }
413/// impl<'c> From<i64> for Cell<'c> {
414///     fn from(value: i64) -> Cell<'c> {
415///         Cell::new(Value::from(value))
416///     }
417/// }
418///
419/// impl<'c> PartialEq<Cell<'c>> for Cell<'c> {
420///     fn eq(&self, other: &Cell<'c>) -> bool {
421///         if self.head.is_null() == other.head.is_null() {
422///             true
423///         } else if let Some(head) = self.head() {
424///             if let Some(value) = other.head() {
425///                 return head == value && (self.tail() == other.tail());
426///             } else {
427///                 false
428///             }
429///         } else {
430///             false
431///         }
432///     }
433/// }
434///
435/// impl<'c> Default for Cell<'c> {
436///     fn default() -> Cell<'c> {
437///         Cell::nil()
438///     }
439/// }
440/// impl<'c> Clone for Cell<'c> {
441///     fn clone(&self) -> Cell<'c> {
442///         let mut cell = Cell::nil();
443///         cell.refs = self.refs.clone();
444///         if self.head.is_not_null() {
445///             cell.head = self.head.clone();
446///         }
447///         if self.tail.is_not_null() {
448///             cell.tail = self.tail.clone();
449///         }
450///         cell
451///     }
452/// }
453/// impl<'c> Drop for Cell<'c> {
454///     fn drop(&mut self) {
455///         self.dealloc();
456///     }
457/// }
458/// ```
459///
460#[doc(alias = "Pointer")]
461pub struct UniquePointer<T: UniquePointee> {
462    mut_addr: usize,
463    mut_ptr: *mut T,
464    refs: RefCounter,
465    alloc: bool,
466    is_copy: bool,
467    written: bool,
468}
469
470impl<'c, T: UniquePointee + 'c> UniquePointer<T> {
471    /// creates a NULL `UniquePointer` ready to be written via [write].
472    pub fn null() -> UniquePointer<T> {
473        UniquePointer {
474            mut_addr: 0,
475            mut_ptr: std::ptr::null_mut::<T>(),
476            refs: RefCounter::new(),
477            written: false,
478            alloc: false,
479            is_copy: false,
480        }
481    }
482
483    /// creates a new `UniquePointer` by effectively
484    /// reading the value referenced by [src]
485    ///
486    pub fn from_ref(src: &T) -> UniquePointer<T> {
487        let mut up = UniquePointer::<T>::null();
488        up.write_ref(src);
489        up
490    }
491
492    /// `from_ref_mut` creates a new `UniquePointer` by effectively
493    /// reading the value referenced by `src`
494    ///
495    pub fn from_ref_mut(src: &mut T) -> UniquePointer<T> {
496        let mut up = UniquePointer::<T>::null();
497        up.write_ref_mut(src);
498        up
499    }
500
501    /// is designed for use within the [Clone] implementation
502    /// of `UniquePointer`.
503    ///
504    /// The [copy] method creates a NULL `UniquePointer` flagged as
505    /// [`is_copy`] such that a double-free does not happen in
506    /// [dealloc].
507    fn copy() -> UniquePointer<T> {
508        let mut up = UniquePointer::<T>::null();
509        up.is_copy = true;
510        up
511    }
512
513    /// produces a copy of a `UniquePointer` which is not a copy in
514    /// the sense that [`UniquePointer::is_copy`] returns true.
515    ///
516    /// Because of that rationale a double-free occurs if there are
517    /// two or more "containers" (e.g.: [struct]s and [enum]s)
518    /// implementing [Drop] and holding the same propagated
519    /// `UniquePointer` instance. For this reason
520    /// [`UniquePointer::propagate`] is unsafe.
521    ///
522    /// [`UniquePointer::propagate`] can be relatively observed as a
523    /// drop-in replacement to [`UniquePointer::clone`] for cases
524    /// when, for instance, swapping `UniquePointer` "instances"
525    /// between instances of `UniquePointer`-containing (structs,
526    /// enums and/or unions) is desired.
527    ///
528    /// Example
529    ///
530    /// ```
531    /// use unique_pointer::UniquePointer;
532    /// use std::fmt::Debug;
533    /// use std::cmp::PartialEq;
534    ///
535    /// #[derive(Clone, Debug)]
536    /// pub struct BinaryTreeNode<T: Debug> {
537    ///     pub item: T,
538    ///     pub parent: UniquePointer<BinaryTreeNode<T>>,
539    ///     pub left: UniquePointer<BinaryTreeNode<T>>,
540    ///     pub right: UniquePointer<BinaryTreeNode<T>>,
541    /// }
542    /// impl<T: Debug> BinaryTreeNode<T> {
543    ///     pub fn new(item: T) -> BinaryTreeNode<T> {
544    ///         BinaryTreeNode {
545    ///             item,
546    ///             parent: UniquePointer::null(),
547    ///             left: UniquePointer::null(),
548    ///             right: UniquePointer::null(),
549    ///         }
550    ///     }
551    ///
552    ///     pub fn rotate_left(&mut self) {
553    ///         if self.parent.is_null() {
554    ///             if self.right.is_not_null() {
555    ///                 self.parent = unsafe { self.right.propagate() };
556    ///                 self.right = UniquePointer::null();
557    ///             }
558    ///         }
559    ///     }
560    ///
561    ///     pub fn set_parent(&mut self, parent: &mut BinaryTreeNode<T>) {
562    ///         self.parent = UniquePointer::read_only(parent);
563    ///     }
564    ///
565    ///     pub fn set_left(&mut self, left: &mut BinaryTreeNode<T>) {
566    ///         left.set_parent(self);
567    ///         self.left = UniquePointer::read_only(left);
568    ///     }
569    ///
570    ///     pub fn set_right(&mut self, right: &mut BinaryTreeNode<T>) {
571    ///         right.set_parent(self);
572    ///         self.right = UniquePointer::read_only(right);
573    ///     }
574    /// }
575    ///
576    /// let mut node_a = BinaryTreeNode::new("A");
577    /// let mut node_b = BinaryTreeNode::new("B");
578    /// let mut node_c = BinaryTreeNode::new("C");
579    /// node_a.set_left(&mut node_b);
580    /// node_a.set_right(&mut node_c);
581    ///
582    /// ```
583    pub unsafe fn propagate(&self) -> UniquePointer<T> {
584        self.incr_ref();
585        let mut back_node = UniquePointer::<T>::null();
586        back_node.set_mut_ptr(self.mut_ptr, false);
587        back_node.refs = self.refs.clone();
588        back_node.alloc = self.alloc;
589        back_node.written = self.written;
590        back_node
591    }
592
593    /// calls [`UniquePointer::copy_from_ref`] to create a *read-only* `UniquePointer` from a
594    /// reference of `T`, useful for iterating over self-referential
595    /// data structures.
596    ///
597    /// Example:
598    ///
599    /// ```
600    /// use unique_pointer::UniquePointer;
601    ///
602    /// pub struct Data<'r> {
603    ///     value: &'r String,
604    /// }
605    /// impl <'r> Data<'r> {
606    ///     pub fn new<T: std::fmt::Display>(value: T) -> Data<'r> {
607    ///         let value = value.to_string();
608    ///         Data {
609    ///             value: UniquePointer::read_only(&value).extend_lifetime()
610    ///         }
611    ///     }
612    /// }
613    /// ```
614    pub fn read_only(data: &T) -> UniquePointer<T> {
615        UniquePointer::copy_from_ref(data, 1)
616    }
617
618    /// calls [`UniquePointer::copy_from_mut_ptr`] to create a *read-only*
619    /// `UniquePointer` from a reference of `T`, useful for
620    /// iterating over self-referential data structures that use
621    /// [RefCounter] to count refs.
622    ///
623    /// Note: [`UniquePointer::read_only`] might be a better alternative when `T` is
624    /// a data structure that does not use [RefCounter].
625    pub fn copy_from_ref(data: &T, refs: usize) -> UniquePointer<T> {
626        let ptr = (data as *const T).cast_mut();
627        UniquePointer::copy_from_mut_ptr(ptr, refs)
628    }
629
630    /// creates a *read-only* `UniquePointer`
631    /// from a reference of `T`, useful for iterating over
632    /// self-referential data structures that use [RefCounter] to
633    /// count refs.
634    ///
635    /// Note: [`UniquePointer::read_only`] might be a better alternative when `T` is
636    /// a data structure that does not use [RefCounter].
637    pub fn copy_from_mut_ptr(ptr: *mut T, refs: usize) -> UniquePointer<T> {
638        let addr = UniquePointer::provenance_of_mut_ptr(ptr);
639        let refs = RefCounter::from(refs);
640        UniquePointer {
641            mut_addr: addr,
642            mut_ptr: ptr,
643            refs: refs,
644            written: true,
645            alloc: true,
646            is_copy: true,
647        }
648    }
649
650    /// returns the value containing both the provenance and
651    /// memory address of a pointer
652    pub fn addr(&self) -> usize {
653        self.mut_addr
654    }
655
656    /// returns the reference count of a `UniquePointer`
657    pub fn refs(&self) -> usize {
658        *self.refs
659    }
660
661    /// returns true if the `UniquePointer` is NULL.
662    pub fn is_null(&self) -> bool {
663        let mut_is_null = self.mut_ptr.is_null();
664        if mut_is_null {
665            assert!(self.mut_addr == 0);
666        } else {
667            assert!(self.mut_addr != 0);
668        }
669        let is_null = mut_is_null;
670        is_null
671    }
672
673    /// returns true if the `UniquePointer` is not
674    /// NULL. [`UniquePointer::is_not_null`] is a idiomatic shortcut
675    /// to negating a call to [`UniquePointer::is_null`] such that the
676    /// negation is less likely to be clearly visible.
677    pub fn is_not_null(&self) -> bool {
678        !self.is_null()
679    }
680
681    /// returns true if the `UniquePointer` is not a
682    /// copy. [`UniquePointer::is_not_copy`] is a idiomatic shortcut
683    /// to negating a call to [`UniquePointer::is_copy`] such that the
684    /// negation is less likely to be clearly visible.
685    pub fn is_not_copy(&self) -> bool {
686        !self.is_copy
687    }
688
689    /// returns true if the `UniquePointer` is not NULL
690    /// and is not flagged as a copy, meaning it can be deallocated
691    /// without concern for double-free.
692    pub fn can_dealloc(&self) -> bool {
693        self.alloc && self.is_not_copy() && self.is_not_null()
694    }
695
696    /// returns true if the `UniquePointer` has been
697    /// allocated and therefore is no longer a NULL pointer.
698    pub fn is_allocated(&self) -> bool {
699        let is_allocated = self.is_not_null() && self.alloc;
700        is_allocated
701    }
702
703    /// returns true if the `UniquePointer` has been written to
704    pub fn is_written(&self) -> bool {
705        let is_written = self.is_allocated() && self.written;
706        is_written
707    }
708
709    /// returns true if a `UniquePointer` is a "copy" of
710    /// another `UniquePointer` in the sense that dropping or
711    /// "hard-deallocating" said `UniquePointer` does not incur a
712    /// double-free.
713    pub fn is_copy(&self) -> bool {
714        self.is_copy
715    }
716
717    /// allocates memory in a null `UniquePointer`
718    pub fn alloc(&mut self) {
719        if self.is_allocated() {
720            return;
721        }
722
723        let layout = Layout::new::<T>();
724        let mut_ptr = unsafe {
725            let ptr = std::alloc::alloc_zeroed(layout);
726            if ptr.is_null() {
727                std::alloc::handle_alloc_error(layout);
728            }
729            ptr as *mut T
730        };
731        self.set_mut_ptr(mut_ptr, false);
732        self.alloc = true;
733    }
734
735    /// compatibility API to a raw mut pointer's [`pointer::cast_mut`].
736    pub fn cast_mut(&self) -> *mut T {
737        if self.is_null() {
738            panic!("{:#?}", self);
739        } else {
740            self.mut_ptr
741        }
742    }
743
744    /// compatibility API to a raw const pointer's [`pointer::cast_const`].
745    pub fn cast_const(&self) -> *const T {
746        if self.is_null() {
747            panic!("{:#?}", self);
748        } else {
749            self.mut_ptr.cast_const()
750        }
751    }
752
753    /// allocates memory and writes the given value into the
754    /// newly allocated area.
755    pub fn write(&mut self, data: T) {
756        self.alloc();
757
758        unsafe {
759            self.mut_ptr.write(data);
760        }
761
762        self.written = true;
763    }
764
765    /// takes a mutable reference to a value and
766    /// writes to a `UniquePointer`
767    pub fn write_ref_mut(&mut self, data: &mut T) {
768        self.alloc();
769        unsafe {
770            let ptr = data as *mut T;
771            ptr.copy_to(self.mut_ptr, 1);
772        };
773        self.written = true;
774    }
775
776    /// takes a read-only reference to a value and
777    /// writes to a `UniquePointer`
778    pub fn write_ref(&mut self, data: &T) {
779        self.alloc();
780        unsafe {
781            let ptr = data as *const T;
782            ptr.copy_to(self.mut_ptr, 1);
783        };
784        self.written = true;
785    }
786
787    /// swaps the memory addresses storing `T` with other `UniquePointer`
788    pub fn swap(&mut self, other: &mut Self) {
789        if self.is_null() && other.is_null() {
790            return;
791        }
792        if self.mut_ptr.is_null() {
793            self.alloc();
794        }
795        if other.mut_ptr.is_null() {
796            other.alloc();
797        }
798        unsafe {
799            self.mut_ptr.swap(other.mut_ptr);
800        }
801    }
802
803    /// reads data from memory `UniquePointer`. Panics if
804    /// the pointer is either null or allocated but never written to.
805    pub fn read(&self) -> T {
806        if !self.is_written() {
807            panic!("{:#?} not written", self);
808        }
809        let ptr = self.cast_const();
810        unsafe { ptr.read() }
811    }
812
813    /// reads data from memory `UniquePointer`
814    pub fn try_read(&self) -> Option<T> {
815        if self.is_written() {
816            Some(self.read())
817        } else {
818            None
819        }
820    }
821
822    /// obtains a read-only reference to the value inside
823    /// `UniquePointer` but does not increment references
824    pub fn inner_ref(&self) -> &'c T {
825        if self.mut_ptr.is_null() {
826            panic!("NULL POINTER: {:#?}", self);
827        }
828        unsafe { std::mem::transmute::<&T, &'c T>(&*self.cast_const()) }
829    }
830
831    /// obtains a mutable reference to the value inside
832    /// `UniquePointer` but does not increment references
833    pub fn inner_mut(&mut self) -> &'c mut T {
834        if self.mut_ptr.is_null() {
835            panic!("NULL POINTER: {:#?}", self);
836        }
837        unsafe { std::mem::transmute::<&mut T, &'c mut T>(&mut *self.mut_ptr) }
838    }
839
840    /// compatibility layer to [`std::pointer::as_ref`]
841    pub fn as_ref(&self) -> Option<&'c T> {
842        if self.is_written() {
843            Some(self.inner_ref())
844        } else {
845            None
846        }
847    }
848
849    /// compatibility layer to [`std::pointer::as_mut`]
850    pub fn as_mut(&mut self) -> Option<&'c mut T> {
851        if self.is_written() {
852            Some(self.inner_mut())
853        } else {
854            None
855        }
856    }
857
858    /// deallocates a `UniquePointer`.
859    ///
860    /// The [soft] boolean argument indicates whether the
861    /// `UniquePointer` should have its reference count decremented or
862    /// deallocated immediately.
863    ///
864    /// During "soft" deallocation (`soft=true`) calls to `dealloc`
865    /// only really deallocate memory when the reference gets down to
866    /// zero, until then each `dealloc(true)` call simply decrements
867    /// the reference count.
868    ///
869    /// Conversely during "hard" deallocation (`soft=false`) the
870    /// UniquePointer in question gets immediately deallocated,
871    /// possibly incurring a double-free or causing Undefined
872    /// Behavior.
873    pub fn dealloc(&mut self, soft: bool) {
874        if self.is_null() {
875            return;
876        }
877        if soft && self.refs > 0 {
878            self.decr_ref();
879        } else {
880            self.free();
881        }
882    }
883
884    /// sets the internal raw pointer of a `UniquePointer`.
885    ///
886    /// Prior to setting the new pointer, it checks whether the
887    /// internal pointer is non-null and matches its provenance
888    /// address, such that "copies" do not incur a double-free.
889    ///
890    /// When [ptr] is a NULL pointer and the internal pointer of
891    /// `UniquePointer` in question is NOT NULL, then it is
892    /// deallocated prior to setting it to NULL.
893    fn set_mut_ptr(&mut self, ptr: *mut T, dealloc: bool) {
894        if ptr.is_null() {
895            if dealloc && self.is_allocated() {
896                self.alloc = false;
897                self.written = false;
898                self.mut_addr = 0;
899                let layout = Layout::new::<T>();
900                unsafe {
901                    std::alloc::dealloc(self.mut_ptr as *mut u8, layout);
902                };
903                self.mut_ptr = std::ptr::null_mut::<T>();
904            }
905
906            self.set_mut_addr(0);
907        } else {
908            self.set_mut_addr(UniquePointer::<T>::provenance_of_mut_ptr(ptr));
909        }
910        self.mut_ptr = ptr;
911    }
912
913    /// deallocates the memory used by `UniquePointer`
914    /// once its references get down to zero.
915    pub fn drop_in_place(&mut self) {
916        self.dealloc(true);
917    }
918
919    fn set_mut_addr(&mut self, addr: usize) {
920        self.mut_addr = addr;
921    }
922
923    /// is internally used by [dealloc] when the number of
924    /// references gets down to zero in a "soft" deallocation and
925    /// immediately in a "hard" deallocation.
926    ///
927    /// See [dealloc] for more information regarding the difference
928    /// between "soft" and "hard" deallocation.
929    fn free(&mut self) {
930        if !self.can_dealloc() {
931            return;
932        }
933        if !self.is_null() {
934            self.set_mut_ptr(std::ptr::null_mut::<T>(), false);
935            self.refs.drain();
936        }
937        self.alloc = false;
938        self.written = false;
939    }
940
941    /// utility method to extend the lifetime
942    /// of references of data created within a function.
943    ///
944    /// Example
945    ///
946    /// ```
947    /// use unique_pointer::UniquePointer;
948    ///
949    /// pub struct Data<'r> {
950    ///     value: &'r String,
951    /// }
952    /// impl <'r> Data<'r> {
953    ///     pub fn new<T: std::fmt::Display>(value: T) -> Data<'r> {
954    ///         let value = value.to_string();
955    ///         Data {
956    ///             value: UniquePointer::read_only(&value).extend_lifetime()
957    ///         }
958    ///     }
959    /// }
960    /// ```
961    pub fn extend_lifetime<'t>(&self) -> &'t T {
962        unsafe { std::mem::transmute::<&T, &'t T>(self.inner_ref()) }
963    }
964
965    /// utility method to extend the lifetime
966    /// of references of data created within a function.
967    ///
968    /// Example
969    ///
970    /// ```
971    /// use unique_pointer::UniquePointer;
972    ///
973    /// pub struct Data<'r> {
974    ///     value: &'r mut String,
975    /// }
976    /// impl <'r> Data<'r> {
977    ///     pub fn new<T: std::fmt::Display>(value: T) -> Data<'r> {
978    ///         let value = value.to_string();
979    ///         Data {
980    ///             value: UniquePointer::read_only(&value).extend_lifetime_mut()
981    ///         }
982    ///     }
983    /// }
984    /// ```
985    pub fn extend_lifetime_mut<'t>(&mut self) -> &'t mut T {
986        unsafe { std::mem::transmute::<&mut T, &'t mut T>(self.inner_mut()) }
987    }
988}
989
990impl<T: UniquePointee> UniquePointer<T> {
991    /// helper method that returns the
992    /// address and provenance of a const pointer
993    pub fn provenance_of_const_ptr(ptr: *const T) -> usize {
994        ptr.expose_provenance()
995    }
996
997    /// helper method that returns the
998    /// address and provenance of a mut pointer
999    pub fn provenance_of_mut_ptr(ptr: *mut T) -> usize {
1000        ptr.expose_provenance()
1001    }
1002
1003    /// helper method that returns the
1004    /// address and provenance of a reference
1005    pub fn provenance_of_ref(ptr: &T) -> usize {
1006        (&raw const ptr).expose_provenance()
1007    }
1008
1009    /// helper method that returns the
1010    /// address and provenance of a mutable reference
1011    pub fn provenance_of_mut(mut ptr: &mut T) -> usize {
1012        (&raw mut ptr).expose_provenance()
1013    }
1014}
1015
1016#[allow(unused)]
1017impl<'c, T: UniquePointee + 'c> UniquePointer<T> {
1018    /// unsafe method that turns a "self reference"
1019    /// into a mutable "self reference"
1020    unsafe fn meta_mut(&'c self) -> &'c mut UniquePointer<T> {
1021        unsafe {
1022            let ptr = self.meta_mut_ptr();
1023            let up = &mut *ptr;
1024            std::mem::transmute::<&mut UniquePointer<T>, &'c mut UniquePointer<T>>(up)
1025        }
1026    }
1027
1028    /// unsafe method that turns a [`*mut UniquePointer`] from a "self reference"
1029    unsafe fn meta_mut_ptr(&self) -> *mut UniquePointer<T> {
1030        let ptr = self as *const UniquePointer<T>;
1031        unsafe {
1032            let ptr: *mut UniquePointer<T> =
1033                std::mem::transmute::<*const UniquePointer<T>, *mut UniquePointer<T>>(ptr);
1034            ptr
1035        }
1036    }
1037}
1038#[allow(invalid_reference_casting)]
1039impl<T: UniquePointee> UniquePointer<T> {
1040    /// `incr_ref` uses unsafe rust to increment references of a
1041    /// non-mut reference to `UniquePointer`
1042    fn incr_ref(&self) {
1043        if self.is_null() {
1044            return;
1045        }
1046        unsafe {
1047            let ptr = self.meta_mut_ptr();
1048            let up = &mut *ptr;
1049            up.refs.incr();
1050        }
1051    }
1052
1053    /// uses unsafe rust to decrement references of a
1054    /// non-mut reference to `UniquePointer`
1055    fn decr_ref(&self) {
1056        if self.refs == 0 {
1057            return;
1058        }
1059        unsafe {
1060            let ptr = self.meta_mut_ptr();
1061            let up = &mut *ptr;
1062            up.refs.decr();
1063        }
1064    }
1065}
1066impl<T: UniquePointee> AsRef<T> for UniquePointer<T> {
1067    fn as_ref(&self) -> &T {
1068        if self.is_null() {
1069            panic!("null pointer: {:#?}", self);
1070        }
1071        self.inner_ref()
1072    }
1073}
1074impl<T: UniquePointee> AsMut<T> for UniquePointer<T> {
1075    fn as_mut(&mut self) -> &mut T {
1076        if self.is_null() {
1077            panic!("null pointer: {:#?}", self);
1078        }
1079        self.inner_mut()
1080    }
1081}
1082
1083impl<T: UniquePointee> Deref for UniquePointer<T> {
1084    type Target = T;
1085
1086    fn deref(&self) -> &T {
1087        self.inner_ref()
1088    }
1089}
1090
1091impl<T: UniquePointee> DerefMut for UniquePointer<T> {
1092    fn deref_mut(&mut self) -> &mut T {
1093        self.inner_mut()
1094    }
1095}
1096
1097impl<T: UniquePointee> Drop for UniquePointer<T>
1098where
1099    T: Debug,
1100{
1101    fn drop(&mut self) {
1102        self.drop_in_place();
1103    }
1104}
1105
1106impl<T: UniquePointee> From<&T> for UniquePointer<T>
1107where
1108    T: Debug,
1109{
1110    fn from(data: &T) -> UniquePointer<T> {
1111        UniquePointer::<T>::from_ref(data)
1112    }
1113}
1114impl<T: UniquePointee> From<&mut T> for UniquePointer<T>
1115where
1116    T: Debug,
1117{
1118    fn from(data: &mut T) -> UniquePointer<T> {
1119        UniquePointer::<T>::from_ref_mut(data)
1120    }
1121}
1122impl<T: UniquePointee> From<T> for UniquePointer<T>
1123where
1124    T: Debug,
1125{
1126    fn from(data: T) -> UniquePointer<T> {
1127        UniquePointer::from_ref(&data)
1128    }
1129}
1130/// The [Clone] implementation of `UniquePointer` is special
1131/// because it flags cloned values as clones such that a double-free
1132/// doesn not occur.
1133impl<T: UniquePointee> Clone for UniquePointer<T>
1134where
1135    T: Debug,
1136{
1137    fn clone(&self) -> UniquePointer<T> {
1138        self.incr_ref();
1139        let mut clone = UniquePointer::<T>::copy();
1140        clone.set_mut_ptr(self.mut_ptr, false);
1141        clone.refs = self.refs.clone();
1142        clone.alloc = self.alloc;
1143        clone.written = self.written;
1144        clone
1145    }
1146}
1147
1148impl<T: UniquePointee> Pointer for UniquePointer<T>
1149where
1150    T: Debug,
1151{
1152    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
1153        write!(f, "{:016x}", self.addr())
1154    }
1155}
1156
1157impl<T: UniquePointee> Debug for UniquePointer<T>
1158where
1159    T: Debug,
1160{
1161    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
1162        write!(
1163            f,
1164            "UniquePointer{}",
1165            [
1166                format!("{:016x}", self.addr()),
1167                if self.is_not_null() {
1168                    [
1169                        format!("[src={:#?}]", self.inner_ref()),
1170                        format!("[refs={}]", self.refs),
1171                    ]
1172                    .join("")
1173                } else {
1174                    [
1175                        format!("[refs={}]", self.refs),
1176                        format!("[alloc={}]", self.alloc),
1177                        format!("[written={}]", self.written),
1178                    ]
1179                    .join("")
1180                },
1181                format!("[is_copy={}]", self.is_copy),
1182            ]
1183            .join("")
1184        )
1185    }
1186}
1187
1188impl<T: UniquePointee + PartialEq> PartialEq<UniquePointer<T>> for UniquePointer<T> {
1189    fn eq(&self, fles: &UniquePointer<T>) -> bool {
1190        if self.addr() == fles.addr() {
1191            return true;
1192        }
1193        if self.is_null() {
1194            let eq = fles.is_null();
1195            return eq;
1196        }
1197        self.inner_ref().eq(fles.inner_ref())
1198    }
1199}
1200impl<T: UniquePointee + Eq> Eq for UniquePointer<T> {}
1201impl<T: UniquePointee + PartialOrd> PartialOrd<UniquePointer<T>> for UniquePointer<T> {
1202    fn partial_cmp(&self, other: &UniquePointer<T>) -> Option<Ordering> {
1203        if self.is_null() {
1204            return None;
1205        }
1206        if self.addr() == other.addr() {
1207            return Some(Ordering::Equal);
1208        }
1209        self.inner_ref().partial_cmp(other.inner_ref())
1210    }
1211}
1212
1213impl<T: UniquePointee + PartialOrd> PartialOrd<T> for UniquePointer<T> {
1214    fn partial_cmp(&self, other: &T) -> Option<Ordering> {
1215        if self.is_null() {
1216            return None;
1217        }
1218        self.inner_ref().partial_cmp(other)
1219    }
1220}
1221impl<T: UniquePointee + PartialEq> PartialEq<T> for UniquePointer<T> {
1222    fn eq(&self, other: &T) -> bool {
1223        if self.is_null() {
1224            return false;
1225        }
1226        self.inner_ref().eq(other)
1227    }
1228}
1229
1230impl<T: UniquePointee + Ord> Ord for UniquePointer<T> {
1231    fn cmp(&self, other: &Self) -> Ordering {
1232        if self.is_null() {
1233            return Ordering::Less;
1234        }
1235        self.inner_ref().cmp(other.inner_ref())
1236    }
1237}
1238
1239impl<T: UniquePointee + Hash> Hash for UniquePointer<T> {
1240    fn hash<H: Hasher>(&self, state: &mut H) {
1241        self.inner_ref().hash(state)
1242    }
1243}
1244
1245// impl<T: Deref, S: Deref> PartialEq<&UniquePointer<S>> for UniquePointer<T>
1246// where
1247//     T: PartialEq<S::Target> + UniquePointee,
1248//     S: UniquePointee,
1249// {
1250//     fn eq(&self, other: &&UniquePointer<S>) -> bool {
1251//         T::eq(self, other)
1252//     }
1253
1254//     fn ne(&self, other: &&UniquePointer<S>) -> bool {
1255//         T::ne(self, other)
1256//     }
1257// }
1258
1259// impl<T: Deref, S: Deref> PartialEq<UniquePointer<S>> for UniquePointer<T>
1260// where
1261//     T: PartialEq<S::Target> + UniquePointee,
1262//     S: UniquePointee,
1263// {
1264//     fn eq(&self, other: &UniquePointer<S>) -> bool {
1265//         T::eq(self, other)
1266//     }
1267
1268//     fn ne(&self, other: &UniquePointer<S>) -> bool {
1269//         T::ne(self, other)
1270//     }
1271// }
1272
1273// impl<T: Deref<Target: Eq> + Eq + PartialEq<<T as Deref>::Target>> Eq for UniquePointer<T> where
1274//     T: UniquePointee
1275// {
1276// }
1277
1278// impl<T: Deref, S: Deref> PartialOrd<UniquePointer<S>> for UniquePointer<T>
1279// where
1280//     T: PartialOrd<S::Target> + UniquePointee,
1281//     S: UniquePointee,
1282// {
1283//     fn partial_cmp(&self, other: &UniquePointer<S>) -> Option<Ordering> {
1284//         T::partial_cmp(self, other)
1285//     }
1286
1287//     fn lt(&self, other: &UniquePointer<S>) -> bool {
1288//         T::lt(self, other)
1289//     }
1290
1291//     fn le(&self, other: &UniquePointer<S>) -> bool {
1292//         T::le(self, other)
1293//     }
1294
1295//     fn gt(&self, other: &UniquePointer<S>) -> bool {
1296//         T::gt(self, other)
1297//     }
1298
1299//     fn ge(&self, other: &UniquePointer<S>) -> bool {
1300//         T::ge(self, other)
1301//     }
1302// }
1303
1304// impl<T: Deref<Target: Ord> + Ord + PartialOrd<<T as Deref>::Target>> Ord for UniquePointer<T>
1305// where
1306//     T: UniquePointee,
1307// {
1308//     fn cmp(&self, other: &Self) -> Ordering {
1309//         T::cmp(self, other)
1310//     }
1311// }
1312
1313// impl<T: Deref<Target: Hash> + Hash> Hash for UniquePointer<T>
1314// where
1315//     T: UniquePointee,
1316// {
1317//     fn hash<H: Hasher>(&self, state: &mut H) {
1318//         T::hash(self, state);
1319//     }
1320// }