crossync 0.1.2

A fast concurrent programming suite for Rust.
Documentation
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
use std::cell::UnsafeCell;
use std::fmt;
use std::ops::{Add, Sub, BitAnd, BitOr, BitXor};
use crate::core::smutex::SMutex;

/// A generic atomic type that provides thread-safe access to **ANY** type `T`.
/// Uses `SMutex` internally for synchronization.
///
/// Unlike std atomics which only work with primitive types, this works with:
/// - Primitives (bool, integers, floats)
/// - Structs and enums
/// - Strings and collections
/// - Any custom type
pub struct Atomic<T> {
    mutex: SMutex,
    value: UnsafeCell<T>,
}

// Safety: Atomic<T> can be shared across threads if T is Send
unsafe impl<T: Send> Sync for Atomic<T> {}
unsafe impl<T: Send> Send for Atomic<T> {}

/// Core operations - work with ANY type T
impl<T> Atomic<T> {
    /// Creates a new atomic value.
    pub fn new(value: T) -> Self {
        Self {
            mutex: SMutex::new(),
            value: UnsafeCell::new(value),
        }
    }

    /// Consumes the atomic and returns the contained value.
    pub fn into_inner(self) -> T {
        self.value.into_inner()
    }

    /// Returns a mutable reference to the underlying value.
    /// This is safe because it requires a mutable reference to self.
    pub fn get_mut(&mut self) -> &mut T {
        self.value.get_mut()
    }

    /// Applies a function to the value and returns the result.
    /// The function receives an immutable reference to the value.
    pub fn with<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&T) -> R,
    {
        let _guard = self.mutex.lock_group();
        unsafe { f(&*self.value.get()) }
    }

    /// Applies a function to the value mutably.
    /// The function receives a mutable reference to modify the value.
    pub fn with_mut<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut T) -> R,
    {
        let _guard = self.mutex.lock();
        unsafe { f(&mut *self.value.get()) }
    }

    /// Replaces the value with a new one computed from a closure.
    /// Returns the old value.
    pub fn replace_with<F>(&self, f: F) -> T
    where
        F: FnOnce(&T) -> T,
    {
        let _guard = self.mutex.lock();
        unsafe {
            let old = std::ptr::read(self.value.get());
            let new = f(&old);
            std::ptr::write(self.value.get(), new);
            old
        }
    }

    /// Updates the value using a closure.
    /// The closure receives a mutable reference and can modify in-place.
    pub fn update<F>(&self, f: F)
    where
        F: FnOnce(&mut T),
    {
        let _guard = self.mutex.lock();
        unsafe { f(&mut *self.value.get()) }
    }

    /// Tries to update the value using a closure.
    /// Returns Ok(()) if the closure returns true, Err(()) otherwise.
    pub fn try_update<F>(&self, f: F) -> Result<(), ()>
    where
        F: FnOnce(&mut T) -> bool,
    {
        let _guard = self.mutex.lock();
        unsafe {
            if f(&mut *self.value.get()) {
                Ok(())
            } else {
                Err(())
            }
        }
    }
}

/// Operations for Clone types
impl<T: Clone> Atomic<T> {
    /// Loads a clone of the value from the atomic.
    pub fn load(&self) -> T {
        let _guard = self.mutex.lock_group();
        unsafe { (*self.value.get()).clone() }
    }

    /// Stores a value into the atomic.
    pub fn store(&self, val: T) {
        let _guard = self.mutex.lock();
        unsafe {
            *self.value.get() = val;
        }
    }

    /// Swaps the value, returning the previous value.
    pub fn swap(&self, val: T) -> T {
        let _guard = self.mutex.lock();
        unsafe {
            let old = (*self.value.get()).clone();
            *self.value.get() = val;
            old
        }
    }

    /// Takes the value, replacing it with a default.
    pub fn take_default(&self) -> T
    where
        T: Default,
    {
        self.swap(T::default())
    }
}

/// Operations for Copy types (optimized, no cloning)
impl<T: Copy> Atomic<T> {
    /// Loads a copy of the value (optimized for Copy types).
    pub fn load_copy(&self) -> T {
        let _guard = self.mutex.lock_group();
        unsafe { *self.value.get() }
    }

    /// Swaps the value, returning the previous value (optimized for Copy types).
    pub fn swap_copy(&self, val: T) -> T {
        let _guard = self.mutex.lock();
        unsafe {
            let old = *self.value.get();
            *self.value.get() = val;
            old
        }
    }
}

/// Compare and exchange operations
impl<T: Clone + PartialEq> Atomic<T> {
    /// Stores a value if the current value is the same as `current`.
    /// Returns `Ok(old_value)` on success, `Err(current_value)` on failure.
    pub fn compare_exchange(&self, current: T, new: T) -> Result<T, T> {
        let _guard = self.mutex.lock();
        unsafe {
            let val = (*self.value.get()).clone();
            if val == current {
                *self.value.get() = new;
                Ok(val)
            } else {
                Err(val)
            }
        }
    }

    /// Weak version of compare_exchange (same as strong for sync-based impl).
    pub fn compare_exchange_weak(&self, current: T, new: T) -> Result<T, T> {
        self.compare_exchange(current, new)
    }

    /// Compares and sets the value, returning the previous value.
    pub fn compare_and_swap(&self, current: T, new: T) -> T {
        match self.compare_exchange(current, new) {
            Ok(val) | Err(val) => val,
        }
    }

    /// Fetches the value and updates it with a function.
    pub fn fetch_update<F>(&self, mut f: F) -> Result<T, T>
    where
        F: FnMut(&T) -> Option<T>,
    {
        let _guard = self.mutex.lock();
        unsafe {
            let old = (*self.value.get()).clone();
            if let Some(new) = f(&old) {
                *self.value.get() = new;
                Ok(old)
            } else {
                Err(old)
            }
        }
    }
}

// Numeric operations for Copy types
impl<T: Copy + Add<Output = T>> Atomic<T> {
    /// Adds to the current value, returning the previous value.
    pub fn fetch_add(&self, val: T) -> T {
        let _guard = self.mutex.lock();
        unsafe {
            let old = *self.value.get();
            *self.value.get() = old + val;
            old
        }
    }
}

impl<T: Copy + Sub<Output = T>> Atomic<T> {
    /// Subtracts from the current value, returning the previous value.
    pub fn fetch_sub(&self, val: T) -> T {
        let _guard = self.mutex.lock();
        unsafe {
            let old = *self.value.get();
            *self.value.get() = old - val;
            old
        }
    }
}

// Bitwise operations for Copy types (excluding bool to avoid conflicts)
impl<T: Copy + BitAnd<Output = T>> Atomic<T> {
    /// Performs bitwise AND, returning the previous value.
    pub fn fetch_and_bits(&self, val: T) -> T {
        let _guard = self.mutex.lock();
        unsafe {
            let old = *self.value.get();
            *self.value.get() = old & val;
            old
        }
    }
}

impl<T: Copy + BitOr<Output = T>> Atomic<T> {
    /// Performs bitwise OR, returning the previous value.
    pub fn fetch_or_bits(&self, val: T) -> T {
        let _guard = self.mutex.lock();
        unsafe {
            let old = *self.value.get();
            *self.value.get() = old | val;
            old
        }
    }
}

impl<T: Copy + BitXor<Output = T>> Atomic<T> {
    /// Performs bitwise XOR, returning the previous value.
    pub fn fetch_xor_bits(&self, val: T) -> T {
        let _guard = self.mutex.lock();
        unsafe {
            let old = *self.value.get();
            *self.value.get() = old ^ val;
            old
        }
    }
}

impl<T: Copy + PartialOrd> Atomic<T> {
    /// Stores the maximum of the current value and `val`, returning the previous value.
    pub fn fetch_max(&self, val: T) -> T {
        let _guard = self.mutex.lock();
        unsafe {
            let old = *self.value.get();
            if val > old {
                *self.value.get() = val;
            }
            old
        }
    }

    /// Stores the minimum of the current value and `val`, returning the previous value.
    pub fn fetch_min(&self, val: T) -> T {
        let _guard = self.mutex.lock();
        unsafe {
            let old = *self.value.get();
            if val < old {
                *self.value.get() = val;
            }
            old
        }
    }
}

// Boolean-specific operations
impl Atomic<bool> {
    /// Performs logical AND, returning the previous value.
    pub fn fetch_and(&self, val: bool) -> bool {
        let _guard = self.mutex.lock();
        unsafe {
            let old = *self.value.get();
            *self.value.get() = old && val;
            old
        }
    }

    /// Performs logical OR, returning the previous value.
    pub fn fetch_or(&self, val: bool) -> bool {
        let _guard = self.mutex.lock();
        unsafe {
            let old = *self.value.get();
            *self.value.get() = old || val;
            old
        }
    }

    /// Performs logical XOR, returning the previous value.
    pub fn fetch_xor(&self, val: bool) -> bool {
        let _guard = self.mutex.lock();
        unsafe {
            let old = *self.value.get();
            *self.value.get() = old != val;
            old
        }
    }

    /// Performs logical NAND, returning the previous value.
    pub fn fetch_nand(&self, val: bool) -> bool {
        let _guard = self.mutex.lock();
        unsafe {
            let old = *self.value.get();
            *self.value.get() = !(old && val);
            old
        }
    }
}

// Integer-specific nand operation
macro_rules! impl_nand {
    ($($t:ty),*) => {
        $(
            impl Atomic<$t> {
                /// Performs bitwise NAND, returning the previous value.
                pub fn fetch_nand(&self, val: $t) -> $t {
                    let _guard = self.mutex.lock();
                    unsafe {
                        let old = *self.value.get();
                        *self.value.get() = !(old & val);
                        old
                    }
                }
            }
        )*
    };
}

impl_nand!(i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize);

// String-specific operations
impl Atomic<String> {
    /// Appends a string slice to the atomic string.
    pub fn push_str(&self, s: &str) {
        self.update(|string| string.push_str(s));
    }

    /// Clears the string.
    pub fn clear(&self) {
        self.update(|string| string.clear());
    }

    /// Returns the length of the string.
    pub fn len(&self) -> usize {
        self.with(|string| string.len())
    }

    /// Returns true if the string is empty.
    pub fn is_empty(&self) -> bool {
        self.with(|string| string.is_empty())
    }
}

// Vec-specific operations
impl<T: Clone> Atomic<Vec<T>> {
    /// Pushes an element to the vector.
    pub fn push(&self, value: T) {
        self.update(|vec| vec.push(value));
    }

    /// Pops an element from the vector.
    pub fn pop(&self) -> Option<T> {
        self.with_mut(|vec| vec.pop())
    }

    /// Returns the length of the vector.
    pub fn len(&self) -> usize {
        self.with(|vec| vec.len())
    }

    /// Returns true if the vector is empty.
    pub fn is_empty(&self) -> bool {
        self.with(|vec| vec.is_empty())
    }

    /// Clears the vector.
    pub fn clear(&self) {
        self.update(|vec| vec.clear());
    }

    /// Extends the vector with elements from an iterator.
    pub fn extend<I>(&self, iter: I)
    where
        I: IntoIterator<Item = T>,
    {
        self.update(|vec| vec.extend(iter));
    }
}

// Option-specific operations
impl<T: Clone> Atomic<Option<T>> {
    /// Returns true if the option is Some.
    pub fn is_some(&self) -> bool {
        self.with(|opt| opt.is_some())
    }

    /// Returns true if the option is None.
    pub fn is_none(&self) -> bool {
        self.with(|opt| opt.is_none())
    }

    /// Takes the value out of the option, leaving None in its place.
    pub fn take(&self) -> Option<T> {
        self.with_mut(|opt| opt.take())
    }

    /// Replaces the value, returning the old value.
    pub fn replace(&self, value: T) -> Option<T> {
        self.with_mut(|opt| opt.replace(value))
    }
}

impl<T: Clone + fmt::Debug> fmt::Debug for Atomic<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let value = self.load();
        f.debug_struct("Atomic")
            .field("value", &value)
            .finish()
    }
}

impl<T: Default> Default for Atomic<T> {
    fn default() -> Self {
        Self::new(T::default())
    }
}

impl<T> From<T> for Atomic<T> {
    fn from(value: T) -> Self {
        Self::new(value)
    }
}