amity 0.6.3

Concurrency algorithms
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! Provides [`Sender`] and [`Receiver`] - broadcasting channel.
//!
//! # Example
//!
//! ```rust
//! use amity::broad::{Receiver, Sender};
//!
//! fn main() {
//!     // Create a new broadcast channel with an initial value
//!     let mut tx = Sender::new(0u32);
//!     let mut rx = tx.receiver();
//!
//!     // Sender sends a new value
//!     tx.send(42);
//!
//!     // Receiver receives the new value
//!     if let Some(value) = rx.recv() {
//!         println!("Received value: {}", value);
//!     }
//! }
//! ```

use alloc::{borrow::ToOwned, sync::Arc};

use lock_api::{RawRwLock, RwLock};

use crate::triple::{Idx, TripleBuffer};

pub struct Broadcast<T, L = crate::DefaultRawRwLock> {
    buffer: TripleBuffer<(T, u64)>,
    consumer: RwLock<L, Idx>,
}

impl<T, L> Broadcast<T, L>
where
    L: RawRwLock,
{
    /// Update the consumer, fetch consumer value reference,
    /// call provided function with the value and whether it was updated.
    /// Returns the result of the function.
    pub fn read<R>(&self, current: &mut u64, f: impl FnOnce(&T, bool) -> R) -> R {
        if !self.buffer.consumed() {
            let mut write = self.consumer.write();
            if !self.buffer.consumed() {
                let (new_consumer, published) = unsafe { self.buffer.consume(*write) };
                assert!(published);
                *write = new_consumer;
            }

            let (value, version) = unsafe { self.buffer.get_unchecked(*write) };

            if *version > *current {
                *current = *version;
                f(value, true)
            } else {
                f(value, false)
            }
        } else {
            let read = self.consumer.read();
            let (value, version) = unsafe { self.buffer.get_unchecked(*read) };

            if *version > *current {
                *current = *version;
                f(value, true)
            } else {
                f(value, false)
            }
        }
    }

    /// Receive new value if it was set since last receive.
    #[inline]
    #[must_use]
    pub fn recv(&self, current: &mut u64) -> Option<T>
    where
        T: Clone,
    {
        self.read(
            current,
            |value, updated| {
                if updated { Some(value.clone()) } else { None }
            },
        )
    }

    /// Receive new value if it was set since last receive and clone it into `value`.
    /// Returns `true` if the value was updated, `false` otherwise.
    #[inline]
    pub fn recv_into(&self, current: &mut u64, value: &mut T) -> bool
    where
        T: Clone,
    {
        self.read(current, |buffer, updated| {
            if updated {
                value.clone_from(buffer);
                true
            } else {
                false
            }
        })
    }

    /// Returns last set value.
    #[inline]
    #[must_use]
    pub fn last(&self, current: &mut u64) -> T
    where
        T: Clone,
    {
        self.read(current, |value, _| value.clone())
    }

    /// Updates `value` with the last set value.
    #[inline]
    pub fn last_into(&self, current: &mut u64, value: &mut T)
    where
        T: Clone,
    {
        self.read(current, |buffer, _| value.clone_from(buffer))
    }

    /// Calls provided function with mutable reference to the value.
    /// Bumps version and publishes the value.
    ///
    /// # Safety
    ///
    /// This function is unsafe because only single producer is allowed to call this function at a time.
    ///
    /// Use `Sender` for safe usage.
    pub unsafe fn write<R>(
        &self,
        producer: &mut Idx,
        current: &mut u64,
        f: impl FnOnce(&mut T) -> R,
    ) -> R {
        let (buffer, version) = unsafe { self.buffer.get_unchecked_mut(*producer) };

        let r = f(buffer);

        *current += 1;
        *version += *current;

        (*producer, _) = unsafe { self.buffer.publish(*producer) };
        r
    }

    /// Send new value to all receivers.
    /// If you need to clone the value to use this method, consider using [`send_from`](Self::send_from) instead.
    ///
    /// # Safety
    ///
    /// This function is unsafe because only single producer is allowed to call this function at a time.
    ///
    /// Use `Sender` for safe usage.
    #[inline]
    pub unsafe fn send(&self, producer: &mut Idx, current: &mut u64, value: T) {
        unsafe {
            self.write(producer, current, move |buffer| {
                *buffer = value;
            });
        }
    }

    /// Send new value to all receivers.
    ///
    /// Clones value from `value` into the buffer.
    /// This is especially useful for types that are expensive to clone, like `String` or `Vec`, or structs containing them.
    /// since they can reuse resources from previous values.
    ///
    /// # Safety
    ///
    /// This function is unsafe because only single producer is allowed to call this function at a time.
    ///
    /// Use `Sender` for safe usage.
    #[inline]
    pub unsafe fn send_from(&self, producer: &mut Idx, current: &mut u64, value: &T)
    where
        T: Clone,
    {
        unsafe {
            self.write(producer, current, move |buffer| {
                buffer.clone_from(value);
            });
        }
    }

    /// Send new value to all receivers.
    ///
    /// Converts value to owned type using `ToOwned` trait.
    /// This is especially useful for types that are expensive to clone, like `String` or `Vec`, or structs containing them.
    /// since they can reuse resources from previous values.
    ///
    /// # Safety
    ///
    /// This function is unsafe because only single producer is allowed to call this function at a time.
    ///
    /// Use `Sender` for safe usage.
    #[inline]
    pub unsafe fn send_from_borrow<U>(&self, producer: &mut Idx, current: &mut u64, value: &U)
    where
        U: ToOwned<Owned = T> + ?Sized,
    {
        unsafe {
            self.write(producer, current, move |buffer| {
                value.clone_into(buffer);
            });
        }
    }

    /// Creates a new broadcasting channel with the given initial value.
    #[must_use]
    pub fn new(initial: T) -> (Self, u64, Idx)
    where
        T: Clone,
    {
        let producer = Idx::default();
        let consumer = producer.other();
        let version = 0;

        let broadcast = Broadcast {
            buffer: TripleBuffer::new(
                (initial.clone(), version),
                (initial.clone(), version),
                (initial.clone(), version),
            ),
            consumer: RwLock::new(consumer),
        };

        (broadcast, version, producer)
    }

    /// Converts the channel into [`Sender`].
    #[inline]
    #[must_use]
    pub fn into_sender(self, producer: Idx, version: u64) -> Sender<T, L> {
        Sender {
            broadcast: Arc::new(self),
            producer,
            version,
        }
    }
}

pub struct Receiver<T, L = crate::DefaultRawRwLock> {
    broadcast: Arc<Broadcast<T, L>>,
    version: u64,
}

impl<T, L> Clone for Receiver<T, L> {
    #[inline]
    fn clone(&self) -> Self {
        Receiver {
            broadcast: self.broadcast.clone(),
            version: self.version,
        }
    }

    #[inline]
    fn clone_from(&mut self, source: &Self) {
        self.broadcast.clone_from(&source.broadcast);
        self.version = source.version;
    }
}

impl<T, L> Receiver<T, L>
where
    L: RawRwLock,
{
    /// Read using provided function.
    #[inline]
    pub fn read<R>(&mut self, f: impl FnOnce(&T, bool) -> R) -> R {
        self.broadcast.read(&mut self.version, f)
    }

    /// Receive new value if it was set since last receive.
    #[inline]
    pub fn recv(&mut self) -> Option<T>
    where
        T: Clone,
    {
        self.broadcast.recv(&mut self.version)
    }

    /// Receive new value if it was set since last receive and clone it into `value`.
    /// Returns `true` if the value was updated, `false` otherwise.
    #[inline]
    pub fn recv_into(&mut self, value: &mut T) -> bool
    where
        T: Clone,
    {
        self.broadcast.recv_into(&mut self.version, value)
    }

    /// Returns last set value.
    #[inline]
    pub fn last(&mut self) -> T
    where
        T: Clone,
    {
        self.broadcast.last(&mut self.version)
    }

    /// Updates `value` with the last set value.
    #[inline]
    pub fn last_into(&mut self, value: &mut T)
    where
        T: Clone,
    {
        self.broadcast.last_into(&mut self.version, value)
    }
}

pub struct Sender<T, L = crate::DefaultRawRwLock> {
    broadcast: Arc<Broadcast<T, L>>,
    producer: Idx,
    version: u64,
}

impl<T> Sender<T> {
    #[inline]
    #[must_use]
    pub fn new(initial: T) -> Self
    where
        T: Clone,
    {
        Self::with_lock(initial)
    }
}

impl<T, L> Sender<T, L>
where
    L: RawRwLock,
{
    #[inline]
    #[must_use]
    pub fn with_lock(initial: T) -> Self
    where
        T: Clone,
    {
        let (broadcast, version, producer) = Broadcast::new(initial);
        Sender {
            broadcast: Arc::new(broadcast),
            producer,
            version,
        }
    }

    /// Write using provided function
    /// and publish the updated value.
    #[inline]
    pub fn write<R>(&mut self, f: impl FnOnce(&mut T) -> R) -> R {
        unsafe {
            self.broadcast
                .write(&mut self.producer, &mut self.version, f)
        }
    }

    /// Send new value to all receivers.
    /// If you need to clone the value to use this method, consider using [`send_from`](Self::send_from) instead.
    #[inline]
    pub fn send(&mut self, value: T) {
        unsafe {
            self.broadcast
                .send(&mut self.producer, &mut self.version, value);
        }
    }

    /// Send new value to all receivers.
    ///
    /// Clones value from `value` into the buffer.
    /// This is especially useful for types that are expensive to clone, like `String` or `Vec`, or structs containing them.
    /// since they can reuse resources from previous values.
    #[inline]
    pub fn send_from(&mut self, value: &T)
    where
        T: Clone,
    {
        unsafe {
            self.broadcast
                .send_from(&mut self.producer, &mut self.version, value);
        }
    }

    /// Send new value to all receivers.
    ///
    /// Converts value to owned type using `ToOwned` trait.
    /// This is especially useful for types that are expensive to clone, like `String` or `Vec`, or structs containing them.
    /// since they can reuse resources from previous values.
    #[inline]
    pub fn send_from_borrow<U>(&mut self, value: &U)
    where
        U: ToOwned<Owned = T> + ?Sized,
    {
        unsafe {
            self.broadcast
                .send_from_borrow(&mut self.producer, &mut self.version, value);
        }
    }

    /// Creates a new receiver for this channel.
    #[inline]
    #[must_use]
    pub fn receiver(&self) -> Receiver<T, L> {
        Receiver {
            broadcast: self.broadcast.clone(),
            version: 0,
        }
    }

    /// Creates a new cached for this channel.
    #[inline]
    #[must_use]
    pub fn cached(&self) -> Cached<T, L>
    where
        T: Clone,
    {
        Cached::new(self.receiver())
    }
}

/// `Receiver` paired with cached value.
///
/// This allows reading the value from cache and update when needed.
pub struct Cached<T, L = crate::DefaultRawRwLock> {
    get: Receiver<T, L>,
    local: T,
}

impl<T, L> Clone for Cached<T, L>
where
    T: Clone,
{
    #[inline]
    fn clone(&self) -> Self {
        Cached {
            get: self.get.clone(),
            local: self.local.clone(),
        }
    }

    #[inline]
    fn clone_from(&mut self, source: &Self) {
        self.get.clone_from(&source.get);
        self.local.clone_from(&source.local);
    }
}

impl<T, L> Cached<T, L>
where
    L: RawRwLock,
    T: Clone,
{
    /// Create a new broadcasting cache with the given initial value.
    #[inline]
    #[must_use]
    pub fn new(mut get: Receiver<T, L>) -> Self {
        let local = get.last();
        Cached { get, local }
    }

    /// Get the current value from the cache.
    #[inline]
    #[must_use]
    pub fn get(&self) -> &T {
        &self.local
    }

    /// Update the cache with the latest value from the broadcasting channel.
    /// Returns `true` if the value was updated, `false` otherwise.
    #[inline]
    pub fn update(&mut self) -> bool {
        self.get.recv_into(&mut self.local)
    }
}

impl<T, L> From<Receiver<T, L>> for Cached<T, L>
where
    L: RawRwLock,
    T: Clone,
{
    #[inline]
    fn from(get: Receiver<T, L>) -> Self {
        Cached::new(get)
    }
}