unique_pointer/
unique_pointer.rs

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