embed_collections/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![cfg_attr(docsrs, allow(unused_attributes))]
3#![doc = include_str!("../README.md")]
4
5use std::mem;
6use std::ptr::NonNull;
7
8/// Abstract pointer trait to support various pointer types in collections.
9///
10/// This trait allows the collections to work with:
11/// - `Box<T>`: Owned, automatically dropped.
12/// - `Arc<T>`: Shared ownership.
13/// - `Rc<T>`: Single thread ownership.
14/// - `NonNull<T>`: Raw non-null pointers (manual memory management).
15/// - `*const T`: Raw pointers (recommend to use `NonNull<T>` instead)
16pub trait Pointer: Sized {
17    type Target;
18
19    fn as_ref(&self) -> &Self::Target;
20
21    unsafe fn from_raw(p: *const Self::Target) -> Self;
22
23    fn into_raw(self) -> *const Self::Target;
24}
25
26impl<T> Pointer for *const T {
27    type Target = T;
28
29    #[inline]
30    fn as_ref(&self) -> &Self::Target {
31        unsafe { mem::transmute(*self) }
32    }
33
34    unsafe fn from_raw(p: *const Self::Target) -> Self {
35        p as *const T
36    }
37
38    fn into_raw(self) -> *const Self::Target {
39        self as *const T
40    }
41}
42
43impl<T> Pointer for NonNull<T> {
44    type Target = T;
45
46    #[inline]
47    fn as_ref(&self) -> &Self::Target {
48        unsafe { self.as_ref() }
49    }
50
51    unsafe fn from_raw(p: *const Self::Target) -> Self {
52        unsafe { NonNull::new_unchecked(p as *mut T) }
53    }
54
55    fn into_raw(self) -> *const Self::Target {
56        self.as_ptr()
57    }
58}
59
60impl<T> Pointer for Box<T> {
61    type Target = T;
62
63    #[inline]
64    fn as_ref(&self) -> &Self::Target {
65        &**self
66    }
67
68    unsafe fn from_raw(p: *const Self::Target) -> Self {
69        unsafe { Box::from_raw(p as *mut T) }
70    }
71
72    fn into_raw(self) -> *const Self::Target {
73        Box::into_raw(self)
74    }
75}
76
77impl<T> Pointer for std::rc::Rc<T> {
78    type Target = T;
79
80    #[inline]
81    fn as_ref(&self) -> &Self::Target {
82        &**self
83    }
84
85    unsafe fn from_raw(p: *const Self::Target) -> Self {
86        unsafe { std::rc::Rc::from_raw(p) }
87    }
88
89    fn into_raw(self) -> *const Self::Target {
90        std::rc::Rc::into_raw(self)
91    }
92}
93
94impl<T> Pointer for std::sync::Arc<T> {
95    type Target = T;
96
97    #[inline]
98    fn as_ref(&self) -> &Self::Target {
99        &**self
100    }
101
102    unsafe fn from_raw(p: *const Self::Target) -> Self {
103        unsafe { std::sync::Arc::from_raw(p) }
104    }
105
106    fn into_raw(self) -> *const Self::Target {
107        std::sync::Arc::into_raw(self)
108    }
109}
110
111#[cfg(feature = "dlist")]
112pub mod dlist;
113#[cfg(feature = "slist")]
114pub mod slist;