prosa-utils 0.4.2

ProSA utils
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
macro_rules! impl_producer_queue {
    // Single producer, non optional
    ("single-producer", "non-optional", $p:ty, $n:ident) => {
        /// Push an item in the queue.
        /// Return an error if it can't
        ///
        /// # Safety
        ///
        /// - Only one thread can push into the queue otherwise the queue may block.
        pub unsafe fn push(&self, val: T) -> Result<(), QueueError<T>> {
            let tail = self.tail.load(std::sync::atomic::Ordering::Relaxed);
            let next_tail = (tail + 1) % self.max_capacity();
            if next_tail != self.get_head() {
                match self.items[tail as usize].compare_exchange(
                    std::ptr::null_mut(),
                    Box::into_raw(Box::new(val)),
                    std::sync::atomic::Ordering::Release,
                    std::sync::atomic::Ordering::SeqCst,
                ) {
                    Ok(_) => {
                        self.tail
                            .store(next_tail, std::sync::atomic::Ordering::Relaxed);
                        Ok(())
                    }
                    Err(item_ptr) => {
                        let item: Box<T>;
                        unsafe {
                            item = Box::from_raw(item_ptr);
                        }

                        Err(QueueError::Full(item, self.len() as usize))
                    }
                }
            } else {
                Err(QueueError::Full(val, $n))
            }
        }
    };
    // Single producer, optional
    ("single-producer", "optional", $p:ty, $n:ident) => {
        /// Push an item in the queue.
        /// Return the id of the element in the queue, or an error if it can't push the item
        ///
        /// # Safety
        ///
        /// - Only one thread can push into the queue otherwise the queue may block.
        pub unsafe fn push(&self, val: T) -> Result<($p, $p), QueueError<T>> {
            let tail = self.tail.load(std::sync::atomic::Ordering::Relaxed);
            let next_tail = (tail + 1) % self.max_capacity();
            if next_tail != self.get_head() {
                match self.items[tail as usize].compare_exchange(
                    std::ptr::null_mut(),
                    Box::into_raw(Box::new(Some(val))),
                    std::sync::atomic::Ordering::Release,
                    std::sync::atomic::Ordering::SeqCst,
                ) {
                    Ok(_) => {
                        self.tail
                            .store(next_tail, std::sync::atomic::Ordering::Relaxed);
                        Ok((self.get_head(), tail))
                    }
                    Err(item_ptr) => {
                        let item: Box<Option<T>>;
                        unsafe {
                            item = Box::from_raw(item_ptr);
                        }

                        Err(QueueError::Full(item.unwrap(), self.len() as usize))
                    }
                }
            } else {
                Err(QueueError::Full(val, $n))
            }
        }
    };
    // Multiple producers, non optional
    ("multi-producers", "non-optional", $p:ty, $n:ident) => {
        /// Push an item in the queue.
        /// Return an error if it can't
        pub fn push(&self, val: T) -> Result<(), QueueError<T>> {
            loop {
                let tail = self.tail.load(std::sync::atomic::Ordering::Acquire);
                let next_tail = (tail + 1) % self.max_capacity();
                if next_tail != self.get_head() {
                    if self
                        .tail
                        .compare_exchange_weak(
                            tail,
                            next_tail,
                            std::sync::atomic::Ordering::Release,
                            std::sync::atomic::Ordering::SeqCst,
                        )
                        .is_ok()
                    {
                        let val_ptr = Box::into_raw(Box::new(val));
                        while self.items[tail as usize]
                            .compare_exchange(
                                std::ptr::null_mut(),
                                val_ptr,
                                std::sync::atomic::Ordering::Release,
                                std::sync::atomic::Ordering::SeqCst,
                            )
                            .is_err()
                        {}
                        return Ok(());
                    }
                } else {
                    return Err(QueueError::Full(val, $n));
                }
            }
        }
    };
}
pub(crate) use impl_producer_queue;

macro_rules! impl_consumer_id_queue {
    // Standard queue
    ("non-optional", $p:ty) => {
        /// Try to pull an item from the queue after a consume.
        ///
        /// # Safety
        ///
        /// - The `id` need to be take from the consume method, otherwise the queue may block.
        pub unsafe fn try_pull_id(&self, id: $p) -> Option<T> {
            let item_ptr = self.items[id as usize]
                .swap(std::ptr::null_mut(), std::sync::atomic::Ordering::Release);
            if !item_ptr.is_null() {
                let item: Box<T>;
                unsafe {
                    item = Box::from_raw(item_ptr);
                }

                Some(*item)
            } else {
                None
            }
        }
    };
    // Optional queue
    ("optional", $p:ty) => {
        /// Try to pull an item from the queue.
        /// The item need to be in the queue otherwise it will not try.
        pub fn try_pull_id(&self, id: $p) -> Option<T> {
            // The id that want to be pulled, need to be in the queue range to avoid consuming outside objects
            let head = self.get_head();
            let tail = self.get_tail();
            if crate::queue::id_in_queue!(id, head, tail) {
                let item_ptr = self.items[id as usize].swap(
                    Box::into_raw(Box::new(None)),
                    std::sync::atomic::Ordering::Release,
                );
                if !item_ptr.is_null() {
                    let item: Box<Option<T>>;
                    unsafe {
                        item = Box::from_raw(item_ptr);
                    }

                    *item
                } else {
                    // If the pointer was null put back a null in it
                    let item_ptr = self.items[id as usize]
                        .swap(std::ptr::null_mut(), std::sync::atomic::Ordering::Release);
                    if !item_ptr.is_null() {
                        let item: Box<Option<T>>;
                        unsafe {
                            item = Box::from_raw(item_ptr);
                        }

                        *item
                    } else {
                        None
                    }
                }
            } else {
                None
            }
        }
    };
}
pub(crate) use impl_consumer_id_queue;

macro_rules! impl_consume_queue {
    // Non optional, Single consumer
    ("non-optional", "single-consumer", $p:ty) => {
        /// Try to consume an item from the queue
        ///
        /// # Safety
        ///
        /// - Only one thread can consume from the queue otherwise the queue may block.
        pub unsafe fn try_consume(&self) -> Result<Option<$p>, QueueError<T>> {
            if !self.is_empty() {
                Ok(self
                    .head
                    .fetch_update(
                        std::sync::atomic::Ordering::Relaxed,
                        std::sync::atomic::Ordering::Relaxed,
                        |head| Some((head + 1) % self.max_capacity()),
                    )
                    .ok())
            } else {
                Err(QueueError::Empty)
            }
        }

        /// Consume an item from the queue
        ///
        /// # Safety
        ///
        /// - Only one thread can consume from the queue otherwise the queue may block.
        pub unsafe fn consume(&self) -> Result<$p, QueueError<T>> {
            if !self.is_empty() {
                self.head
                    .fetch_update(
                        std::sync::atomic::Ordering::Relaxed,
                        std::sync::atomic::Ordering::Relaxed,
                        |head| Some((head + 1) % self.max_capacity()),
                    )
                    .map_err(|e| QueueError::Retrieve(e as usize))
            } else {
                Err(QueueError::Empty)
            }
        }
    };
    // Non optional, Multiple consumers
    ("non-optional", "multi-consumers", $p:ty) => {
        /// Try to consume an item from the queue
        pub fn try_consume(&self) -> Result<Option<$p>, QueueError<T>> {
            let head = self.head.load(std::sync::atomic::Ordering::Acquire);
            if head != self.get_tail() {
                if self
                    .head
                    .compare_exchange_weak(
                        head,
                        (head + 1) % self.max_capacity(),
                        std::sync::atomic::Ordering::Release,
                        std::sync::atomic::Ordering::SeqCst,
                    )
                    .is_ok()
                {
                    Ok(Some(head))
                } else {
                    Ok(None)
                }
            } else {
                Err(QueueError::Empty)
            }
        }

        /// Consume an item from the queue
        pub fn consume(&self) -> Result<$p, QueueError<T>> {
            loop {
                let head = self.head.load(std::sync::atomic::Ordering::Acquire);
                if head != self.get_tail() {
                    if self
                        .head
                        .compare_exchange(
                            head,
                            (head + 1) % self.max_capacity(),
                            std::sync::atomic::Ordering::Release,
                            std::sync::atomic::Ordering::SeqCst,
                        )
                        .is_ok()
                    {
                        return Ok(head);
                    }
                } else {
                    return Err(QueueError::Empty);
                }
            }
        }
    };
    // Optional
    ("optional", "single-consumer", $p:ty) => {};
    ("optional", "multi-consumers", $p:ty) => {};
}
pub(crate) use impl_consume_queue;

macro_rules! impl_consumer_queue {
    // Single consumer, non optional
    ("single-consumer", "non-optional", $p:ty) => {
        /// Try to pull an item from the queue.
        ///
        /// For a single consumer, it return a `Full` error if the queue was full to notify that item can be push again in the queue.
        ///
        /// # Safety
        ///
        /// - Only one thread can pull from the queue otherwise the queue may block.
        pub unsafe fn try_pull(&self) -> Result<Option<T>, QueueError<T>> {
            let head = self.head.load(std::sync::atomic::Ordering::Relaxed);
            let tail = self.tail.load(std::sync::atomic::Ordering::Relaxed);
            if head != tail {
                let item_ptr = self.items[head as usize]
                    .swap(std::ptr::null_mut(), std::sync::atomic::Ordering::Release);
                if !item_ptr.is_null() {
                    let item: Box<T>;
                    unsafe {
                        item = Box::from_raw(item_ptr);
                    }

                    self.head.store(
                        (head + 1) % self.max_capacity(),
                        std::sync::atomic::Ordering::Relaxed,
                    );

                    if (tail + 1) % (N as $p) != head {
                        Ok(Some(*item))
                    } else {
                        Err(QueueError::<T>::Full(*item, N))
                    }
                } else {
                    Ok(None)
                }
            } else {
                Err(QueueError::Empty)
            }
        }

        /// Pull an item from the queue.
        ///
        /// For a single consumer, it return a `Full` error if the queue was full to notify that item can be push again in the queue.
        ///
        /// # Safety
        ///
        /// - Only one thread can pull from the queue otherwise the queue may block.
        pub unsafe fn pull(&self) -> Result<T, QueueError<T>> {
            let head = self.head.load(std::sync::atomic::Ordering::Relaxed);
            let tail = self.tail.load(std::sync::atomic::Ordering::Relaxed);
            if head != tail {
                let mut item_ptr = self.items[head as usize]
                    .swap(std::ptr::null_mut(), std::sync::atomic::Ordering::Release);
                while item_ptr.is_null() {
                    item_ptr = self.items[head as usize]
                        .swap(std::ptr::null_mut(), std::sync::atomic::Ordering::Release);
                }

                let item: Box<T>;
                unsafe {
                    item = Box::from_raw(item_ptr);
                }

                self.head.store(
                    (head + 1) % self.max_capacity(),
                    std::sync::atomic::Ordering::Relaxed,
                );

                if (tail + 1) % (N as $p) != head {
                    Ok(*item)
                } else {
                    Err(QueueError::<T>::Full(*item, N))
                }
            } else {
                Err(QueueError::Empty)
            }
        }
    };
    // Multiple consumers, non optional
    ("multi-consumers", "non-optional", $p:ty) => {
        /// Try to pull an item from the queue.
        pub fn try_pull(&self) -> Result<Option<T>, QueueError<T>> {
            let head = self.head.load(std::sync::atomic::Ordering::Acquire);
            if head != self.get_tail() {
                if self
                    .head
                    .compare_exchange_weak(
                        head,
                        (head + 1) % self.max_capacity(),
                        std::sync::atomic::Ordering::Release,
                        std::sync::atomic::Ordering::SeqCst,
                    )
                    .is_ok()
                {
                    let mut item_ptr = self.items[head as usize]
                        .swap(std::ptr::null_mut(), std::sync::atomic::Ordering::Release);
                    while item_ptr.is_null() {
                        item_ptr = self.items[head as usize]
                            .swap(std::ptr::null_mut(), std::sync::atomic::Ordering::Release);
                    }

                    let item: Box<T>;
                    unsafe {
                        item = Box::from_raw(item_ptr);
                    }

                    Ok(Some(*item))
                } else {
                    Ok(None)
                }
            } else {
                Err(QueueError::Empty)
            }
        }

        /// Pull an item from the queue.
        pub fn pull(&self) -> Result<T, QueueError<T>> {
            loop {
                let head = self.head.load(std::sync::atomic::Ordering::Acquire);
                if head != self.get_tail() {
                    if self
                        .head
                        .compare_exchange(
                            head,
                            (head + 1) % self.max_capacity(),
                            std::sync::atomic::Ordering::Release,
                            std::sync::atomic::Ordering::SeqCst,
                        )
                        .is_ok()
                    {
                        let mut item_ptr = self.items[head as usize]
                            .swap(std::ptr::null_mut(), std::sync::atomic::Ordering::Release);
                        while item_ptr.is_null() {
                            item_ptr = self.items[head as usize]
                                .swap(std::ptr::null_mut(), std::sync::atomic::Ordering::Release);
                        }

                        let item: Box<T>;
                        unsafe {
                            item = Box::from_raw(item_ptr);
                        }

                        return Ok(*item);
                    }
                } else {
                    return Err(QueueError::Empty);
                }
            }
        }
    };
    // Multiple consumers, optional
    ("multi-consumers", "optional", $p:ty) => {
        /// Try to pull an item from the queue.
        pub fn try_pull(&self) -> Result<Option<T>, QueueError<T>> {
            let head = self.head.load(std::sync::atomic::Ordering::Acquire);
            if head != self.get_tail() {
                if self
                    .head
                    .compare_exchange_weak(
                        head,
                        (head + 1) % self.max_capacity(),
                        std::sync::atomic::Ordering::Release,
                        std::sync::atomic::Ordering::SeqCst,
                    )
                    .is_ok()
                {
                    let mut item_ptr = self.items[head as usize]
                        .swap(std::ptr::null_mut(), std::sync::atomic::Ordering::Release);
                    while item_ptr.is_null() {
                        item_ptr = self.items[head as usize]
                            .swap(std::ptr::null_mut(), std::sync::atomic::Ordering::Release);
                    }

                    let item: Box<Option<T>>;
                    unsafe {
                        item = Box::from_raw(item_ptr);
                    }

                    Ok(*item)
                } else {
                    Ok(None)
                }
            } else {
                Err(QueueError::Empty)
            }
        }

        /// Pull an item from the queue.
        pub fn pull(&self) -> Result<T, QueueError<T>> {
            loop {
                let head = self.head.load(std::sync::atomic::Ordering::Acquire);
                if head != self.get_tail() {
                    if self
                        .head
                        .compare_exchange(
                            head,
                            (head + 1) % self.max_capacity(),
                            std::sync::atomic::Ordering::Release,
                            std::sync::atomic::Ordering::SeqCst,
                        )
                        .is_ok()
                    {
                        let mut item_ptr = self.items[head as usize]
                            .swap(std::ptr::null_mut(), std::sync::atomic::Ordering::Release);
                        while item_ptr.is_null() {
                            item_ptr = self.items[head as usize]
                                .swap(std::ptr::null_mut(), std::sync::atomic::Ordering::Release);
                        }

                        let item: Box<Option<T>>;
                        unsafe {
                            item = Box::from_raw(item_ptr);
                        }

                        if let Some(item) = *item {
                            // An item is available
                            return Ok(item);
                        } else {
                            // The item has been pulled before, call pull again for another item
                            return self.pull();
                        }
                    }
                } else {
                    return Err(QueueError::Empty);
                }
            }
        }
    };
}
pub(crate) use impl_consumer_queue;

/// Macro to define lockfree queue
macro_rules! impl_lockfree_queue {
    ( $queue:ident, $p:ty, $atomic:ty, $atomic_ptr_data:ty, $producer:tt, $consumer:tt, $optional:tt ) => {
        /// Implementation of an Atomic queue
        pub struct $queue<T, const N: usize> {
            /// Items of the queue
            items: [std::sync::atomic::AtomicPtr<$atomic_ptr_data>; N],
            /// Atomic position in the array of the head value
            head: $atomic,
            /// Atomic position in the array of the tail value
            tail: $atomic,
        }

        impl<T, const N: usize> $queue<T, N> {
            /// Getter of the head position without blocking (not synchronized)
            pub(crate) fn get_head(&self) -> $p {
                self.head.load(std::sync::atomic::Ordering::Relaxed)
            }
            /// Getter of the tail position without blocking (not synchronized)
            pub(crate) fn get_tail(&self) -> $p {
                self.tail.load(std::sync::atomic::Ordering::Relaxed)
            }

            crate::queue::lockfree::impl_consumer_id_queue!($optional, $p);
            crate::queue::lockfree::impl_consume_queue!($optional, $consumer, $p);
            crate::queue::lockfree::impl_producer_queue!($producer, $optional, $p, N);
            crate::queue::lockfree::impl_consumer_queue!($consumer, $optional, $p);
        }

        impl<T, const N: usize> Drop for $queue<T, N> {
            fn drop(&mut self) {
                for atomic_ptr in &self.items {
                    let item_ptr = atomic_ptr.load(std::sync::atomic::Ordering::Relaxed);
                    if !item_ptr.is_null() {
                        unsafe {
                            drop(Box::from_raw(item_ptr));
                        }
                    }
                }
            }
        }

        impl<T, const N: usize> Default for $queue<T, N> {
            fn default() -> Self {
                $queue::<T, N> {
                    items: [const { std::sync::atomic::AtomicPtr::new(std::ptr::null_mut()) }; N],
                    head: <$atomic>::new(0),
                    tail: <$atomic>::new(0),
                }
            }
        }

        impl<T, const N: usize> QueueChecker<$p> for $queue<T, N> {
            crate::queue::impl_queue_checker! {$p}
        }

        impl<T, const N: usize> std::fmt::Debug for $queue<T, N> {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.debug_struct(stringify!($queue))
                    .field("head", &self.get_head())
                    .field("tail", &self.get_tail())
                    .field("len", &self.len())
                    .field("max_capacity", &self.max_capacity())
                    .finish()
            }
        }
    };
}
pub(crate) use impl_lockfree_queue;