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
use core::{alloc::{Allocator, Layout, AllocError}, sync::atomic::{AtomicPtr, Ordering}, ptr::NonNull, iter::FusedIterator};
use alloc::{alloc::Global};
use crate::{InnerFlag, FALSE, TRUE};
use core::fmt::Debug;

struct FillQueueNode<T> {
    init: InnerFlag,
    prev: *mut Self,
    v: T
}

#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub struct FillQueue<T, A: Allocator = Global> {
    head: AtomicPtr<FillQueueNode<T>>,
    alloc: A
}

impl<T> FillQueue<T> {
    /// Creates a new [`FillQueue`] with the global allocator.
    /// # Example
    /// ```rust
    /// use utils_atomics::prelude::*;
    /// 
    /// let queue = FillQueue::<i32>::new();
    /// ```
    #[inline(always)]
    pub const fn new () -> Self {
        Self::new_in(Global)
    }
}

impl<T, A: Allocator> FillQueue<T, A> {
    /// Creates a new [`FillQueue`] with the given allocator.
    /// # Example
    /// ```rust
    /// #![feature(allocator_api)]
    /// 
    /// use utils_atomics::prelude::*;
    /// use std::alloc::Global;
    /// 
    /// let queue = FillQueue::<i32>::new_in(Global);
    /// ```
    #[inline(always)]
    pub const fn new_in (alloc: A) -> Self {
        Self {
            head: AtomicPtr::new(core::ptr::null_mut()),
            alloc
        }
    }

    /// Returns a reference to this queue's allocator.
    /// # Example
    /// ```rust
    /// #![feature(allocator_api)]
    /// 
    /// use utils_atomics::prelude::*;
    /// use std::alloc::Global;
    /// 
    /// let queue = FillQueue::<i32>::new();
    /// let alloc : &Global = queue.allocator();
    /// ```
    #[inline(always)]
    pub fn allocator (&self) -> &A {
        &self.alloc
    }

    /// Returns `true` if the que is currently empty, `false` otherwise.
    /// # Safety
    /// Whilst this method is not unsafe, it's result should be considered immediately stale.
    /// # Example
    /// ```rust
    /// use utils_atomics::prelude::*;
    /// 
    /// let queue = FillQueue::<i32>::new();
    /// assert!(queue.is_empty());
    /// ```
    #[inline(always)]
    pub fn is_empty (&self) -> bool {
        self.head.load(Ordering::Relaxed).is_null()
    }

    /// Uses atomic operations to push an element to the queue.
    /// # Panics
    /// This method panics if `alloc` fails to allocate the memory needed for the node.
    /// # Example
    /// ```rust
    /// use utils_atomics::prelude::*;
    /// 
    /// let queue = FillQueue::<i32>::new();
    /// queue.push(1);
    /// assert_eq!(queue.chop().next(), Some(1));
    /// ```
    #[inline(always)]
    pub fn push (&self, v: T) {
        self.try_push(v).unwrap()
    }

    /// Uses non-atomic operations to push an element to the queue.
    /// # Panics
    /// This method panics if `alloc` fails to allocate the memory needed for the node.
    /// # Example
    /// ```rust
    /// use utils_atomics::prelude::*;
    /// 
    /// let mut queue = FillQueue::<i32>::new();
    /// queue.push_mut(1);
    /// assert_eq!(queue.chop_mut().next(), Some(1));
    /// ```
    #[inline(always)]
    pub fn push_mut (&mut self, v: T) {
        self.try_push_mut(v).unwrap()
    }

    /// Uses atomic operations to push an element to the queue.
    /// # Errors
    /// This method returns an error if `alloc` fails to allocate the memory needed for the node.
    /// # Example
    /// ```rust
    /// use utils_atomics::prelude::*;
    /// 
    /// let queue = FillQueue::<i32>::new();
    /// assert!(queue.try_push(1).is_ok());
    /// assert_eq!(queue.chop().next(), Some(1));
    /// ```
    pub fn try_push (&self, v: T) -> Result<(), AllocError> {
        let node = FillQueueNode {
            init: InnerFlag::new(FALSE),
            prev: core::ptr::null_mut(),
            v
        };

        let ptr = self.alloc.allocate(Layout::new::<FillQueueNode<T>>())?.cast::<FillQueueNode<T>>();
        unsafe {
            ptr.as_ptr().write(node)
        }

        let prev = self.head.swap(ptr.as_ptr(), Ordering::AcqRel);
        unsafe {
            let rf = &mut *ptr.as_ptr();
            rf.prev = prev;
            rf.init.store(TRUE, Ordering::Release);
        }

        Ok(())
    }

    /// Uses non-atomic operations to push an element to the queue.
    /// # Safety
    /// This method is safe because the mutable reference guarantees we are the only thread that can access this queue.
    /// # Errors
    /// This method returns an error if `alloc` fails to allocate the memory needed for the node.
    /// # Example
    /// ```rust
    /// use utils_atomics::prelude::*;
    /// 
    /// let mut queue = FillQueue::<i32>::new();
    /// assert!(queue.try_push_mut(1).is_ok());
    /// assert_eq!(queue.chop_mut().next(), Some(1));
    /// ```
    pub fn try_push_mut (&mut self, v: T) -> Result<(), AllocError> {
        let node = FillQueueNode {
            init: InnerFlag::new(TRUE),
            prev: core::ptr::null_mut(),
            v
        };

        let mut ptr = self.alloc.allocate(Layout::new::<FillQueueNode<T>>())?.cast::<FillQueueNode<T>>();
        unsafe {
            ptr.as_ptr().write(node);
            let prev = core::ptr::replace(self.head.get_mut(), ptr.as_ptr());
            ptr.as_mut().prev = prev;
            Ok(())
        }
    }
}

impl<T, A: Allocator> FillQueue<T, A> {
    /// Returns a LIFO (Last In First Out) iterator over a chopped chunk of a [`FillQueue`].
    /// The elements that find themselves inside the chopped region of the queue will be accessed through non-atomic operations.
    /// # Example
    /// ```rust
    /// use utils_atomics::prelude::*;
    /// 
    /// let queue = FillQueue::<i32>::new();
    /// 
    /// queue.push(1);
    /// queue.push(2);
    /// queue.push(3);
    /// 
    /// let mut iter = queue.chop();
    /// assert_eq!(iter.next(), Some(3));
    /// assert_eq!(iter.next(), Some(2));
    /// assert_eq!(iter.next(), Some(1));
    /// assert_eq!(iter.next(), None)
    /// ```
    #[inline(always)]
    pub fn chop (&self) -> ChopIter<T, A> where A: Clone {
        let ptr = self.head.swap(core::ptr::null_mut(), Ordering::AcqRel);
        ChopIter { 
            ptr: NonNull::new(ptr),
            alloc: self.alloc.clone()
        }
    }

    /// Returns a LIFO (Last In First Out) iterator over a chopped chunk of a [`FillQueue`]. The chopping is done with non-atomic operations.
    /// # Safety
    /// This method is safe because the mutable reference guarantees we are the only thread that can access this queue.
    /// # Example
    /// ```rust
    /// use utils_atomics::prelude::*;
    /// 
    /// let mut queue = FillQueue::<i32>::new();
    /// 
    /// queue.push_mut(1);
    /// queue.push_mut(2);
    /// queue.push_mut(3);
    /// 
    /// let mut iter = queue.chop_mut();
    /// assert_eq!(iter.next(), Some(3));
    /// assert_eq!(iter.next(), Some(2));
    /// assert_eq!(iter.next(), Some(1));
    /// assert_eq!(iter.next(), None)
    /// ```
    #[inline(always)]
    pub fn chop_mut (&mut self) -> ChopIter<T, A> where A: Clone {
        let ptr = unsafe {
            core::ptr::replace(self.head.get_mut(), core::ptr::null_mut())
        };

        ChopIter { 
            ptr: NonNull::new(ptr),
            alloc: self.alloc.clone()
        }
    }
}

/// Iterator of [`FillQueue::chop`] and [`FillQueue::chop_mut`]
pub struct ChopIter<T, A: Allocator = Global> {
    ptr: Option<NonNull<FillQueueNode<T>>>,
    alloc: A
}

impl<T, A: Allocator> Iterator for ChopIter<T, A> {
    type Item = T;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(ptr) = self.ptr {
            unsafe {
                let node = core::ptr::read(ptr.as_ptr());
                self.alloc.deallocate(ptr.cast(), Layout::new::<FillQueueNode<T>>());

                while node.init.load(Ordering::Acquire) == FALSE { core::hint::spin_loop() }
                self.ptr = NonNull::new(node.prev);
                return Some(node.v)
            }
        }

        None
    }
}

impl<T, A: Allocator> Drop for ChopIter<T, A> {
    #[inline]
    fn drop(&mut self) {
        while let Some(ptr) = self.ptr {
            unsafe {
                let node = core::ptr::read(ptr.as_ptr());
                self.alloc.deallocate(ptr.cast(), Layout::new::<FillQueueNode<T>>());
                
                while node.init.load(Ordering::Acquire) == FALSE { core::hint::spin_loop() }
                self.ptr = NonNull::new(node.prev);
            }
        }
    }
}

impl<T, A: Debug + Allocator> Debug for FillQueue<T, A> {
    #[inline]
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        f.debug_struct("FillQueue").field("alloc", &self.alloc).finish_non_exhaustive()
    }
}

impl<T> FusedIterator for ChopIter<T> {}