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
//! [`Bag`] is a lock-free concurrent unordered set.
//!
//! Work-in-progress.

use super::Queue;

use std::fmt::{self, Debug};
use std::mem::MaybeUninit;

const STORAGE_LEN: usize = std::mem::size_of::<usize>() * 4;

/// [`Bag`] is a lock-free concurrent unordered set.
pub struct Bag<T: 'static> {
    /// Primary storage.
    _storage: [MaybeUninit<T>; STORAGE_LEN],

    /// Primary storage metadata.
    _metadata: usize,

    /// Fallback storage.
    queue: Queue<T>,
}

impl<T: 'static> Bag<T> {
    /// Pushes an instance of `T`.
    ///
    /// # Examples
    ///
    /// ```
    /// use scc::Bag;
    ///
    /// let bag: Bag<usize> = Bag::default();
    ///
    /// bag.push(11);
    /// ```
    #[inline]
    pub fn push(&self, val: T) {
        self.queue.push(val);
    }

    /// Pops a random element in the [`Bag`] if not empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use scc::Bag;
    ///
    /// let bag: Bag<usize> = Bag::default();
    ///
    /// bag.push(37);
    ///
    /// assert_eq!(bag.pop(), Some(37));
    /// assert!(bag.pop().is_none());
    /// ```
    #[allow(clippy::missing_panics_doc)]
    #[inline]
    pub fn pop(&self) -> Option<T> {
        self.queue
            .pop()
            .map(|mut e| unsafe { e.get_mut().unwrap().take_inner() })
    }

    /// Returns `true` if the [`Bag`] is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use scc::Bag;
    ///
    /// let bag: Bag<usize> = Bag::default();
    /// assert!(bag.is_empty());
    ///
    /// bag.push(7);
    /// assert!(!bag.is_empty());
    /// ```
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.queue.is_empty()
    }
}

impl<T: 'static + Clone> Clone for Bag<T> {
    #[inline]
    fn clone(&self) -> Self {
        Bag {
            _storage: unsafe { MaybeUninit::uninit().assume_init() },
            _metadata: 0,
            queue: self.queue.clone(),
        }
    }
}

impl<T: 'static + Debug> Debug for Bag<T> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.queue.fmt(f)
    }
}

impl<T: 'static> Default for Bag<T> {
    #[inline]
    fn default() -> Self {
        Self {
            _storage: unsafe { MaybeUninit::uninit().assume_init() },
            _metadata: 0,
            queue: Queue::default(),
        }
    }
}