sovran_arc/
arcmo.rs

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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
use std::fmt::Debug;
use std::sync::{Arc, Mutex, Weak};

/// A wrapper combining Arc and Mutex for convenient shared mutable access to optional values
/// Only works with types that implement Clone
pub struct Arcmo<T: Clone> {
    inner: Arc<Mutex<Option<T>>>,
}

impl<T: Clone> Arcmo<T> {
    /// Creates a new empty Arcmo
    pub fn none() -> Self {
        Self {
            inner: Arc::new(Mutex::new(None)),
        }
    }

    /// Creates a new Arcmo containing Some(value)
    pub fn some(value: T) -> Self {
        Self {
            inner: Arc::new(Mutex::new(Some(value))),
        }
    }

    /// Modifies the contained value if it exists using the provided closure
    pub fn modify<F, R>(&self, f: F) -> Option<R>
    where
        F: FnOnce(&mut T) -> R,
    {
        let mut guard = self.inner.lock().unwrap();
        guard.as_mut().map(f)
    }

    /// Sets the value to None and returns the previous value if it existed
    pub fn take(&self) -> Option<T> {
        self.inner.lock().unwrap().take()
    }

    /// Sets the value to Some(value) and returns the previous value if it existed
    pub fn replace(&self, value: T) -> Option<T> {
        self.inner.lock().unwrap().replace(value)
    }

    /// Returns a copy of the contained value if it exists
    pub fn value(&self) -> Option<T> {
        self.inner.lock().unwrap().clone()
    }

    /// Returns true if the contained value is Some
    pub fn is_some(&self) -> bool {
        self.inner.lock().unwrap().is_some()
    }

    /// Returns true if the contained value is None
    pub fn is_none(&self) -> bool {
        self.inner.lock().unwrap().is_none()
    }

    /// Returns a weak reference to the contained value
    pub fn downgrade(&self) -> WeakArcmo<T> {
        WeakArcmo {
            inner: Arc::downgrade(&self.inner)
        }
    }
}

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

impl<T: Clone + Debug> Debug for Arcmo<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Arcmo")
            .field("inner", &self.inner)
            .finish()
    }
}

impl<T: Clone + Default> Default for Arcmo<T> {
    fn default() -> Self {
        Self::none()
    }
}

/// A weak reference wrapper for Arcmo
pub struct WeakArcmo<T: Clone> {
    inner: Weak<Mutex<Option<T>>>
}

impl<T: Clone> WeakArcmo<T> {
    /// Attempts to modify the value if it exists and the original Arcmo still exists
    pub fn modify<F, R>(&self, f: F) -> Option<R>
    where
        F: FnOnce(&mut T) -> R,
    {
        self.inner
            .upgrade()
            .and_then(|arc| {
                let mut guard = arc.lock().unwrap();
                guard.as_mut().map(f)
            })
    }

    /// Attempts to get a copy of the value if it exists and the original Arcmo still exists
    pub fn value(&self) -> Option<T> {
        self.inner
            .upgrade()
            .and_then(|arc| arc.lock().unwrap().clone())
    }

    /// Returns true if both the original Arcmo exists and contains Some value
    pub fn is_some(&self) -> bool {
        self.inner
            .upgrade()
            .map(|arc| arc.lock().unwrap().is_some())
            .unwrap_or(false)
    }

    /// Returns true if either the original Arcmo is dropped or contains None
    pub fn is_none(&self) -> bool {
        !self.is_some()
    }
}

impl<T: Clone> Debug for WeakArcmo<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WeakArcmo")
            .field("inner", &self.inner)
            .finish()
    }
}

// Example usage and tests
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default() {
        let arcmo: Arcmo<Vec<i32>> = Arcmo::default();
        assert!(arcmo.is_none());

        let int_arcmo: Arcmo<i32> = Arcmo::default();
        assert!(int_arcmo.is_none());
    }

    #[test]
    fn test_basic_usage() {
        let v = Arcmo::some(1);

        v.modify(|v| *v = 42);
        assert_eq!(v.value(), Some(42));
    }

    #[test]
    fn test_none() {
        let v: Arcmo<i32> = Arcmo::none();
        assert!(v.is_none());
        assert_eq!(v.value(), None);

        // modify does nothing when value is None
        v.modify(|v| *v = 42);
        assert_eq!(v.value(), None);

        let v2 = Arcmo::<i32>::none();
        assert!(v2.is_none());
        assert_eq!(v2.value(), None);

        // modify does nothing when value is None
        v.modify(|v2| *v2 = 42);
        assert_eq!(v2.value(), None);
    }

    #[test]
    fn test_take_and_replace() {
        let v = Arcmo::some(1);

        assert_eq!(v.take(), Some(1));
        assert!(v.is_none());

        assert_eq!(v.replace(42), None);
        assert_eq!(v.value(), Some(42));
    }

    #[test]
    fn test_multiple_references() {
        let v1 = Arcmo::some(1);
        let v2 = v1.clone();

        v1.modify(|v| *v = 42);
        assert_eq!(v2.value(), Some(42));

        v1.take();
        assert!(v2.is_none());
    }

    #[test]
    fn test_is_some() {
        // Test with initial Some value
        let v = Arcmo::some(42);
        assert!(v.is_some());

        // Test after modification
        v.modify(|x| *x = 100);
        assert!(v.is_some());

        // Test with None
        let v2: Arcmo<i32> = Arcmo::none();
        assert!(!v2.is_some());

        // Test after taking value
        v.take();
        assert!(!v.is_some());

        // Test after replacing None with Some
        v.replace(200);
        assert!(v.is_some());

        // Test with cloned reference
        let v3 = v.clone();
        assert!(v3.is_some());
    }

    #[test]
    fn test_weak_reference() {
        let strong = Arcmo::some(42);
        let weak = strong.downgrade();

        // Test value access
        assert_eq!(weak.value(), Some(42));

        // Test after dropping the strong reference
        drop(strong);
        assert_eq!(weak.value(), None);
    }

    #[test]
    fn test_weak_with_none() {
        let strong = Arcmo::none();
        let weak = strong.downgrade();

        // Test value access with None
        assert_eq!(weak.value(), None);
        assert!(weak.is_none());
        assert!(!weak.is_some());

        // Replace with Some value
        strong.replace(42);
        assert_eq!(weak.value(), Some(42));
        assert!(!weak.is_none());
        assert!(weak.is_some());

        // Take value back to None
        strong.take();
        assert_eq!(weak.value(), None);
        assert!(weak.is_none());
        assert!(!weak.is_some());
    }

    #[test]
    fn test_weak_modification() {
        let strong = Arcmo::some(vec![1, 2, 3]);
        let weak = strong.downgrade();

        // Modify through weak reference
        let length = weak.modify(|v| {
            v.push(4);
            v.len()
        });
        assert_eq!(length, Some(4));
        assert_eq!(strong.value(), Some(vec![1, 2, 3, 4]));

        // After dropping the strong reference
        drop(strong);
        let result = weak.modify(|v| v.push(5));
        assert_eq!(result, None);
    }
}