kast_util/
parc.rs

1use std::sync::Arc;
2
3#[derive(Default)]
4pub struct Parc<T: ?Sized>(Arc<T>);
5
6impl<T: ?Sized + std::fmt::Debug> std::fmt::Debug for Parc<T> {
7    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8        let value: &T = self;
9        value.fmt(f)
10    }
11}
12
13impl<T: ?Sized> From<Parc<T>> for Arc<T> {
14    fn from(val: Parc<T>) -> Self {
15        val.0
16    }
17}
18
19impl<T: ?Sized> From<Arc<T>> for Parc<T> {
20    fn from(value: Arc<T>) -> Self {
21        Self(value)
22    }
23}
24
25impl<T> Parc<T> {
26    pub fn new(value: T) -> Self {
27        Self(Arc::new(value))
28    }
29    pub fn as_ptr(&self) -> *const T {
30        Arc::as_ptr(&self.0)
31    }
32}
33
34impl<T: ?Sized> std::ops::Deref for Parc<T> {
35    type Target = T;
36    fn deref(&self) -> &Self::Target {
37        &self.0
38    }
39}
40
41impl<T: ?Sized> Clone for Parc<T> {
42    fn clone(&self) -> Self {
43        Self(self.0.clone())
44    }
45}
46
47impl<T: ?Sized> PartialEq for Parc<T> {
48    fn eq(&self, other: &Self) -> bool {
49        Arc::ptr_eq(&self.0, &other.0)
50    }
51}
52
53impl<T: ?Sized> Eq for Parc<T> {}
54
55impl<T: ?Sized> PartialOrd for Parc<T> {
56    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
57        Some(self.cmp(other))
58    }
59}
60
61impl<T: ?Sized> Ord for Parc<T> {
62    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
63        let p1: *const () = Arc::as_ptr(&self.0) as _;
64        let p2: *const () = Arc::as_ptr(&other.0) as _;
65        p1.cmp(&p2)
66    }
67}
68
69impl<T: ?Sized> std::hash::Hash for Parc<T> {
70    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
71        Arc::as_ptr(&self.0).hash(state)
72    }
73}
74
75impl<T: ?Sized + std::fmt::Display> std::fmt::Display for Parc<T> {
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        T::fmt(self, f)
78    }
79}