1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
use crate::implementation::{SharedImpl, SharedProjection};
use crate::locks::{SharedReadLock, SharedReadLockInner};
use crate::projection::Projector;
use crate::{PoisonPolicy, SharedMut};
use std::sync::{Arc, Mutex};

/// The [`Shared`] object is similar to Rust's [`std::sync::Arc`], but adds the ability to project.
#[repr(transparent)]
pub struct Shared<T: ?Sized> {
    inner: SharedImpl<T>,
}

// UNSAFETY: The construction and projection of Shared requires Send + Sync, so we can guarantee that
// all instances of SharedMutImpl are Send + Sync.
unsafe impl<T: ?Sized> Send for Shared<T> {}
unsafe impl<T: ?Sized> Sync for Shared<T> {}

#[cfg(feature = "serde")]
use serde::Serialize;

#[cfg(feature = "serde")]
impl<'a, T: Serialize> Serialize for Shared<T>
where
    &'a T: Serialize + 'static,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.read().serialize(serializer)
    }
}

impl<T: ?Sized> Clone for Shared<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<T: std::fmt::Debug> std::fmt::Debug for Shared<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.read().fmt(f)
    }
}

impl<T: ?Sized> From<Box<T>> for Shared<T>
where
    Box<T>: Send + Sync,
{
    fn from(value: Box<T>) -> Self {
        Self {
            inner: SharedImpl::Arc(Arc::from(value)),
        }
    }
}

// Use for transmutation from SharedMut to Shared.
impl<T: ?Sized> From<SharedImpl<T>> for Shared<T> {
    fn from(inner: SharedImpl<T>) -> Self {
        Self { inner }
    }
}

// Use for transmutation from SharedMut to Shared.
impl<T: ?Sized> From<SharedMut<T>> for Shared<T> {
    fn from(shared_rw: SharedMut<T>) -> Self {
        Self {
            inner: shared_rw.inner_impl,
        }
    }
}

impl<T: ?Sized> Shared<T> {
    pub fn from_box(t: Box<T>) -> Self
    where
        Box<T>: Send + Sync,
    {
        Self {
            inner: SharedImpl::Arc(Arc::from(t)),
        }
    }
}

impl<T: Send> Shared<T> {
    /// The [`Shared::new`] function requires a type that is both `Send + Sync`. If this is not possible, you may call
    /// [`Shared::new_unsync`] to create a [`Shared`] implementation that uses a [`Mutex`].
    ///
    /// This will fail to compile:
    ///
    /// ```compile_fail
    /// # use std::{cell::Cell, marker::PhantomData};
    /// # use keepcalm::*;
    /// # pub type Unsync = PhantomData<Cell<()>>;
    /// Shared::new(Unsync {});
    /// ```
    ///
    /// This will work:
    ///
    /// ```rust
    /// # use std::{cell::Cell, marker::PhantomData};
    /// # use keepcalm::*;
    /// # pub type Unsync = PhantomData<Cell<()>>;
    /// Shared::new_unsync(Unsync {});
    /// ```
    pub fn new_unsync(t: T) -> Self {
        Self {
            inner: SharedImpl::Mutex(PoisonPolicy::Panic, Arc::new(Mutex::new(t))),
        }
    }
}

impl<T: Send + Sync + 'static> Shared<T> {
    pub fn new(t: T) -> Self {
        Self {
            inner: SharedImpl::Arc(Arc::new(t)),
        }
    }

    /// Attempt to unwrap this object if we are the only holder of its value.
    pub fn try_unwrap(self) -> Result<T, Self> {
        match self.inner.try_unwrap() {
            Ok(x) => Ok(x),
            Err(inner) => Err(Self { inner }),
        }
    }
}

impl<T: ?Sized, P: ?Sized> SharedProjection<P> for (Shared<T>, Arc<Projector<T, P>>) {
    fn read(&self) -> SharedReadLock<P> {
        struct HiddenLock<'a, T: ?Sized, P: ?Sized> {
            lock: SharedReadLock<'a, T>,
            projector: &'a Projector<T, P>,
        }

        impl<'a, T: ?Sized, P: ?Sized> std::ops::Deref for HiddenLock<'a, T, P> {
            type Target = P;
            fn deref(&self) -> &Self::Target {
                (self.projector).project(&*self.lock)
            }
        }

        let lock = HiddenLock {
            lock: self.0.read(),
            projector: &self.1,
        };

        SharedReadLock {
            inner: SharedReadLockInner::Projection(Box::new(lock)),
        }
    }
}

impl<T: ?Sized> Shared<T> {
    pub fn project<P: ?Sized + 'static, I: Into<Projector<T, P>>>(&self, projector: I) -> Shared<P>
    where
        T: 'static,
    {
        let projector: Projector<T, P> = projector.into();
        let projectable = Arc::new((self.clone(), Arc::new(projector)));
        Shared {
            inner: SharedImpl::ProjectionRO(projectable),
        }
    }

    pub fn project_fn<P: ?Sized + 'static, RO: (Fn(&T) -> &P) + Send + Sync + 'static>(
        &self,
        ro: RO,
    ) -> Shared<P>
    where
        T: 'static,
    {
        let projectable = Arc::new((self.clone(), Arc::new(Projector::new(ro))));
        Shared {
            inner: SharedImpl::ProjectionRO(projectable),
        }
    }

    pub fn read(&self) -> SharedReadLock<T> {
        self.inner.lock_read()
    }
}

#[cfg(test)]
mod test {
    use crate::project_cast;

    use super::*;

    #[allow(unused)]
    fn ensure_send<T: Send>() {}
    #[allow(unused)]
    fn ensure_sync<T: Sync>() {}

    #[allow(unused)]
    fn test_types() {
        ensure_send::<Shared<usize>>();
        ensure_sync::<Shared<usize>>();
        ensure_send::<Shared<dyn AsRef<str>>>();
        ensure_sync::<Shared<dyn AsRef<str>>>();
    }

    #[test]
    pub fn test_shared() {
        let shared = Shared::new(1);
        assert_eq!(*shared.read(), 1);
    }

    #[test]
    pub fn test_shared_projection() {
        let shared = Shared::new((1, 2));
        let shared_proj = shared.project_fn(|x| &x.0);
        assert_eq!(*shared_proj.read(), 1);
        let shared_proj = shared.project_fn(|x| &x.1);
        assert_eq!(*shared_proj.read(), 2);
    }

    #[test]
    pub fn test_unsized() {
        let shared: Shared<dyn AsRef<str>> =
            Shared::new("123".to_owned()).project(project_cast!(x: String => dyn AsRef<str>));
        assert_eq!(shared.read().as_ref(), "123");

        let shared: Shared<[i32]> = Shared::from_box(Box::new([1, 2, 3]));
        assert_eq!(shared.read()[0], 1);
    }

    #[test]
    pub fn test_unwrap() {
        let shared = Shared::new(1);
        let res = shared.try_unwrap().expect("Expected to unwrap");
        assert_eq!(res, 1);

        let shared = Shared::new(1);
        let shared2 = shared.clone();
        // We can't unwrap with multiple references
        assert!(matches!(shared.try_unwrap(), Err(_)));
        // We can now unwrap
        assert!(matches!(shared2.try_unwrap(), Ok(_)));
    }

    #[test]
    pub fn test_unsync() {
        use std::{cell::Cell, marker::PhantomData};
        pub type Unsync = PhantomData<Cell<()>>;
        Shared::new_unsync(Unsync {});
    }

    #[cfg(feature = "serde")]
    #[test]
    pub fn test_serde() {
        fn serialize<S: serde::Serialize>(_: S) {}
        let shared = Shared::new((1, 2, 3));
        serialize(shared);
    }
}