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
use crate::sync::IndexSpinlock;
use core::marker::PhantomData;
use core::num::NonZeroUsize;
use core::sync::atomic::AtomicU32;
use core::sync::atomic::AtomicUsize;
use core::sync::atomic::Ordering;

// #[allow(dead_code)]
// #[allow(unions_with_drop_fields)]
// pub union Swap<T, U>
// where
//     T: Sized,
// {
//     base: T,
//     other: U,
// }
// // #[allow(dead_code)]
// impl<T, U> Swap<T, U>
// where
//     T: Sized,
// {
//     pub const unsafe fn get(value: T) -> U {
//         return Swap { base: value }.other;
//     }
// }

struct Unique<T> {
    ptr: *const T,           // *const for variance
    _marker: PhantomData<T>, // For the drop checker
}

// Deriving Send and Sync is safe because we are the Unique owners
// of this data. It's like Unique<T> is "just" T.
unsafe impl<T: Send> Send for Unique<T> {}
unsafe impl<T: Sync> Sync for Unique<T> {}

impl<T> Unique<T> {
    pub const fn new(ptr: *mut T) -> Self {
        Unique {
            ptr: ptr,
            _marker: PhantomData,
        }
    }

    pub fn as_ptr(&self) -> *mut T {
        self.ptr as *mut T
    }
}

/// A MPMC Queue based on Dmitry Vyukov's queue.  
/// However, there is a slight modification where head and tail can be locked, as my implementation of Dmitry's queue failed some tests under peak contention  - and I've opted for a more conservative queue
pub const QUEUE_NULL: usize = 0;
#[repr(C)]
pub struct QueueUsize<'a> {
    _cache_pad_0: [u8; 64],
    // buffer: &'a [AtomicUsize],
    buffer: Unique<AtomicUsize>,
    // buffer_ptr : *const AtomicUsize,
    capacity: u32,
    buffer_capacity_mask: u32,
    _cache_pad_1: [u8; 64],
    head: IndexSpinlock,
    _cache_pad_2: [u8; 64],
    tail: IndexSpinlock,
    _cache_pad_3: [u8; 64],
    _lifetime: PhantomData<&'a AtomicUsize>,
}

impl<'a> QueueUsize<'a> {
    // const CAPACITY_MASK : u32 = CAPACITY as u32 - 1;

    pub const unsafe fn from_static(
        slice: &'a *mut AtomicUsize,
        capacity: usize,
    ) -> QueueUsize<'a> {
        //pub const fn new(buffer_ptr : *const usize, capacity : usize)->Queue{

        return QueueUsize {
            head: IndexSpinlock::new(0),
            tail: IndexSpinlock::new(0),
            buffer: Unique::new(*slice),
            // buffer_ptr : slice.as_ptr() as *const AtomicUsize,
            capacity: capacity as u32,
            buffer_capacity_mask: capacity as u32 - 1,
            _cache_pad_0: [0; 64],
            _cache_pad_1: [0; 64],
            _cache_pad_2: [0; 64],
            _cache_pad_3: [0; 64],
            _lifetime: PhantomData,
        };
    }
    pub fn clear(&self) {
        let mut tail = self.tail.lock();
        let mut head = self.head.lock();
        for i in 0..self.capacity {
            unsafe {
                self.buffer
                    .as_ptr()
                    .offset(i as isize)
                    .as_ref()
                    .unwrap()
                    .store(QUEUE_NULL, Ordering::Relaxed);
            }
        }
        tail.write(0);
        head.write(0);
    }

    pub fn enqueue(&self, value: NonZeroUsize) -> bool {
        let v = value.get();
        debug_assert_ne!(v, QUEUE_NULL);

        let mut tail = self.tail.lock();
        let tail_value = tail.read();

        let storage = unsafe {
            self.buffer
                .as_ptr()
                .offset(tail_value as isize)
                .as_ref()
                .unwrap()
        }; //self.get_storage(tail_value as usize);
        let stored_value = storage.load(Ordering::Relaxed);
        if stored_value != QUEUE_NULL {
            return false;
        }
        storage.store(v, Ordering::Relaxed);
        tail.write(tail_value.wrapping_add(1) & self.buffer_capacity_mask);
        return true;
    }

    pub fn dequeue(&self) -> Option<NonZeroUsize> {
        let mut head = self.head.lock();
        let head_value = head.read();
        let storage = unsafe {
            self.buffer
                .as_ptr()
                .offset(head_value as isize)
                .as_ref()
                .unwrap()
        }; //self.get_storage(head_value as usize);
        let stored_value = storage.load(Ordering::Relaxed);
        if stored_value == QUEUE_NULL {
            return None;
        }
        storage.store(QUEUE_NULL, Ordering::Relaxed);
        head.write(head_value.wrapping_add(1) & self.buffer_capacity_mask);
        unsafe {
            return Some(NonZeroUsize::new_unchecked(stored_value));
        }
    }
}

unsafe impl<'a> Send for QueueUsize<'a> {}
unsafe impl<'a> Sync for QueueUsize<'a> {}

#[repr(C)]
pub struct QueueU32<'a> {
    _cache_pad_0: [u8; 64],
    buffer: Unique<AtomicU32>,
    // buffer_ptr : *const AtomicUsize,
    capacity: u32,
    // buffer_ptr : *const AtomicUsize,
    buffer_capacity_mask: u32,
    _cache_pad_1: [u8; 64],
    head: IndexSpinlock,
    _cache_pad_2: [u8; 64],
    tail: IndexSpinlock,
    _cache_pad_3: [u8; 64],
    _lifetime: PhantomData<&'a AtomicUsize>,
}

pub const QUEUE_U32_NULL: u32 = 0xFFFFFFFF;
impl<'a> QueueU32<'a> {
    // const CAPACITY_MASK : u32 = CAPACITY as u32 - 1;

    // #[cfg(any(test, feature = "std"))]
    // pub fn new(capacity: usize) -> QueueU32 {
    //     return QueueU32 {
    //         head: IndexSpinlock::new(0),
    //         tail: IndexSpinlock::new(0),
    //         buffer: Unique::new(slice),
    //         capacity: capacity as u32,
    //         // buffer_ptr : slice.as_ptr() as *const AtomicUsize,
    //         buffer_capacity_mask: capacity as u32 - 1,
    //         _cache_pad_0: [0; 64],
    //         _cache_pad_1: [0; 64],
    //         _cache_pad_2: [0; 64],
    //         _cache_pad_3: [0; 64],
    //     };

    // }
    /// This method is a kludge to work around lack of stable const-generics, const unions, etc.  
    /// It is up to the caller to ensure that the pointer passed in is truly static, and is not mutated externally.
    /// Capacity must be a non-zero power of two.
    pub const unsafe fn from_static(slice: &'a *mut AtomicU32, capacity: usize) -> QueueU32<'a> {
        //pub const fn new(buffer_ptr : *const usize, capacity : usize)->Queue{

        return QueueU32 {
            head: IndexSpinlock::new(0),
            tail: IndexSpinlock::new(0),
            buffer: Unique::new(*slice),
            capacity: capacity as u32,
            // buffer_ptr : slice.as_ptr() as *const AtomicUsize,
            buffer_capacity_mask: capacity as u32 - 1,
            _cache_pad_0: [0; 64],
            _cache_pad_1: [0; 64],
            _cache_pad_2: [0; 64],
            _cache_pad_3: [0; 64],
            _lifetime: PhantomData,
        };
    }
    pub fn clear(&self) {
        let mut tail = self.tail.lock();
        let mut head = self.head.lock();
        for i in 0..self.capacity {
            unsafe {
                self.buffer
                    .as_ptr()
                    .offset(i as isize)
                    .as_ref()
                    .unwrap()
                    .store(QUEUE_U32_NULL, Ordering::Relaxed);
            }
        }
        tail.write(0);
        head.write(0);
    }

    pub fn enqueue(&self, value: u32) -> bool {
        debug_assert_ne!(value, QUEUE_U32_NULL);

        let mut tail = self.tail.lock();
        let tail_value = tail.read();

        let storage = unsafe {
            self.buffer
                .as_ptr()
                .offset(tail_value as isize)
                .as_ref()
                .unwrap()
        }; //self.get_storage(tail_value as usize);
        let stored_value = storage.load(Ordering::Relaxed);
        if stored_value != QUEUE_U32_NULL {
            return false;
        }
        storage.store(value, Ordering::Relaxed);
        tail.write(tail_value.wrapping_add(1) & self.buffer_capacity_mask);
        return true;
    }

    pub fn dequeue(&self) -> Option<u32> {
        let mut head = self.head.lock();
        let head_value = head.read();
        let storage = unsafe {
            self.buffer
                .as_ptr()
                .offset(head_value as isize)
                .as_ref()
                .unwrap()
        }; //self.get_storage(head_value as usize);
        let stored_value = storage.load(Ordering::Relaxed);
        if stored_value == QUEUE_U32_NULL {
            return None;
        }
        storage.store(QUEUE_U32_NULL, Ordering::Relaxed);
        head.write(head_value.wrapping_add(1) & self.buffer_capacity_mask);

        return Some(stored_value);
    }
}

unsafe impl<'a> Send for QueueU32<'a> {}
unsafe impl<'a> Sync for QueueU32<'a> {}

#[cfg(test)]
mod test;