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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

use super::{Cell, ClosedError, Result, Slice};
use crate::sync::primitive::{AtomicBool, AtomicUsize, AtomicWaker, IsZst, Ordering};
use alloc::alloc::Layout;
use core::{
    fmt,
    marker::PhantomData,
    ops::Deref,
    panic::{RefUnwindSafe, UnwindSafe},
    ptr::NonNull,
};
use crossbeam_utils::CachePadded;

type Pair<'a, T> = super::Pair<Slice<'a, Cell<T>>>;

const MINIMUM_CAPACITY: usize = 2;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Side {
    Sender,
    Receiver,
}

#[derive(Clone, Copy)]
pub struct Cursor {
    head: usize,
    tail: usize,
    capacity: usize,
}

impl fmt::Debug for Cursor {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Cursor")
            .field("head", &self.head)
            .field("tail", &self.tail)
            .field("len", &self.len())
            .field("capacity", &self.capacity())
            .field("is_empty", &self.is_empty())
            .field("is_full", &self.is_full())
            .field("is_contiguous", &self.is_contiguous())
            .finish()
    }
}

impl Cursor {
    #[inline]
    fn new(capacity: usize) -> Self {
        Self {
            head: 0,
            tail: 0,
            capacity,
        }
    }

    #[inline]
    fn invariants(&self) {
        unsafe {
            assume!(
                self.capacity >= MINIMUM_CAPACITY,
                "the capacity must be at least the MINIMUM_CAPACITY value"
            );
            assume!(
                self.head < self.capacity,
                "the `head` pointer should be strictly less than the capacity"
            );
            assume!(
                self.tail < self.capacity,
                "the `tail` pointer should be strictly less than the capacity"
            );
            let len = count(self.head, self.tail, self.capacity);
            assume!(
                len < self.capacity,
                "the computed `len` should be strictly less than the capacity"
            );
        }
    }

    #[inline]
    pub fn capacity(&self) -> usize {
        self.invariants();
        // To make cursor management easier, we never allow the callers to hit the total capacity.
        // We also account for this when allocating the state by adding 1 to the request capacity.
        self.capacity - 1
    }

    #[inline]
    fn cap(&self) -> usize {
        self.invariants();
        self.capacity
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.invariants();
        count(self.head, self.tail, self.cap())
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.invariants();
        self.tail == self.head
    }

    #[inline]
    pub fn is_full(&self) -> bool {
        self.invariants();
        count(self.tail, self.head, self.cap()) == 1
    }

    #[inline]
    pub fn recv_len(&self) -> usize {
        self.invariants();
        self.len()
    }

    #[inline]
    pub fn send_capacity(&self) -> usize {
        self.invariants();
        self.capacity() - self.recv_len()
    }

    #[inline]
    pub fn increment_head(&mut self, n: usize) {
        self.invariants();
        unsafe {
            assume!(
                n <= self.capacity(),
                "n should never exceed the total capacity"
            );
        }
        self.head = self.wrap_add(self.head, n);
        self.invariants();
    }

    #[inline]
    pub fn increment_tail(&mut self, n: usize) {
        self.invariants();
        unsafe {
            assume!(
                n <= self.capacity(),
                "n should never exceed the total capacity"
            );
        }
        self.tail = self.wrap_add(self.tail, n);
        self.invariants();
    }

    #[inline]
    fn wrap_add(&self, idx: usize, addend: usize) -> usize {
        wrap_index(idx.wrapping_add(addend), self.cap())
    }

    #[inline]
    fn is_contiguous(&self) -> bool {
        self.tail >= self.head
    }
}

/// Returns the index in the underlying buffer for a given logical element index.
#[inline]
fn wrap_index(index: usize, size: usize) -> usize {
    // size is always a power of 2
    unsafe {
        assume!(
            size.is_power_of_two(),
            "The calculations in the lengths rely on the capacity being a power of 2"
        );
        assume!(
            size >= MINIMUM_CAPACITY,
            "The calculations in the lengths rely on the capacity being at least {}",
            MINIMUM_CAPACITY
        );
    }
    index & (size - 1)
}

/// Calculate the number of elements left to be read in the buffer
#[inline]
fn count(head: usize, tail: usize, size: usize) -> usize {
    // size is always a power of 2
    unsafe {
        assume!(
            size.is_power_of_two(),
            "The calculations in the lengths rely on the capacity being a power of 2"
        );
        assume!(
            size >= MINIMUM_CAPACITY,
            "The calculations in the lengths rely on the capacity being at least {}",
            MINIMUM_CAPACITY
        );
    }
    (tail.wrapping_sub(head)) & (size - 1)
}

/// The synchronized state between two peers
///
/// The internal design of the cursor management is based on [`alloc::collections::VecDeque`].
pub struct State<T> {
    header: NonNull<Header<T>>,
    pub cursor: Cursor,
}

impl<T> fmt::Debug for State<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("State")
            .field("header", self.deref())
            .field("cursor", &self.cursor)
            .finish()
    }
}

/// Safety: synchronization of state is managed through atomic values
unsafe impl<T: Send> Send for State<T> {}

/// Safety: synchronization of state is managed through atomic values
unsafe impl<T: Sync> Sync for State<T> {}

/// The data behind the header pointer itself is unwind safe
impl<T: RefUnwindSafe> UnwindSafe for State<T> {}

impl<T> Clone for State<T> {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            header: self.header,
            cursor: self.cursor,
        }
    }
}

impl<T> Deref for State<T> {
    type Target = Header<T>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        unsafe { self.header.as_ref() }
    }
}

impl<T> State<T> {
    #[inline]
    pub fn new(capacity: usize) -> Self {
        // If we're sending a zero-sized type, set the capacity to the maximum value, since we're
        // not sending any data and just coordinating cursors at this point
        let capacity = if T::IS_ZST {
            // The total capacity must be a power of two
            usize::MAX / 2 + 1
        } else {
            // Add 1 to the requested capacity so it's easier to manage cursor wrapping
            core::cmp::max(capacity + 1, MINIMUM_CAPACITY).next_power_of_two()
        };
        let header = Header::alloc(capacity).expect("could not allocate channel");
        let cursor = Cursor::new(capacity);
        Self { header, cursor }
    }

    /// Tries to acquire more unfilled slots on the channel
    ///
    /// If the channel is closed, an error is returned. If the channel has at least one slot of
    /// capacity, `true` is returned. Otherwise `false` is returned.
    #[inline]
    pub fn acquire_capacity(&mut self) -> Result<bool> {
        if !self.open.load(Ordering::Acquire) {
            return Err(ClosedError);
        }

        // update the cached version
        self.cursor.head = self.head.load(Ordering::Acquire);

        let is_full = self.cursor.is_full();

        Ok(!is_full)
    }

    /// Tries to acquire more filled slots on the channel
    ///
    /// If the channel is closed, an error is returned. If the channel has at least one slot of
    /// capacity, `true` is returned. Otherwise `false` is returned.
    #[inline]
    pub fn acquire_filled(&mut self) -> Result<bool> {
        self.cursor.tail = self.tail.load(Ordering::Acquire);

        if !self.cursor.is_empty() {
            return Ok(true);
        }

        if !self.open.load(Ordering::Acquire) {
            // make one more effort to load the remaining items
            self.cursor.tail = self.tail.load(Ordering::Acquire);

            if !self.cursor.is_empty() {
                return Ok(true);
            }

            return Err(ClosedError);
        }

        Ok(false)
    }

    /// Notifies the peer of `head` updates for the given cursor
    #[inline]
    pub fn persist_head(&self, prev: Cursor) {
        // nothing changed
        if prev.head == self.cursor.head {
            return;
        }

        self.head.store(self.cursor.head, Ordering::Release);

        self.sender.wake();
    }

    /// Notifies the peer of `tail` updates for the given cursor
    #[inline]
    pub fn persist_tail(&self, prev: Cursor) {
        // nothing changed
        if prev.tail == self.cursor.tail {
            return;
        }

        self.tail.store(self.cursor.tail, Ordering::Release);

        self.receiver.wake();
    }

    #[inline]
    fn data(&self) -> &[Cell<T>] {
        unsafe {
            // Safety: the state must still be allocated and the cursor inbounds
            let ptr = self.data_ptr();
            let capacity = self.cursor.capacity;
            core::slice::from_raw_parts(ptr, capacity)
        }
    }

    #[inline]
    fn data_ptr(&self) -> *const Cell<T> {
        unsafe {
            // If the type is zero-sized, no need to calculate offsets
            if T::IS_ZST {
                return NonNull::<Cell<T>>::dangling().as_ptr();
            }

            // Safety: the state must still be allocated and the cursor inbounds
            let capacity = self.cursor.capacity;
            let (_, offset) = Header::<T>::layout_unchecked(capacity);

            let ptr = self.header.as_ptr() as *const u8;
            let ptr = ptr.add(offset);
            ptr as *const Cell<T>
        }
    }

    /// Closes one side of the channel and notifies the peer of the event
    #[inline]
    pub fn close(&mut self, side: Side) {
        // notify the other side that we've closed the channel
        match side {
            Side::Sender => self.receiver.wake(),
            Side::Receiver => self.sender.wake(),
        }

        let was_open = self.open.swap(false, Ordering::SeqCst);

        // make sure the peer is notified before fully dropping the contents
        match side {
            Side::Sender => self.receiver.wake(),
            Side::Receiver => self.sender.wake(),
        }

        if !was_open {
            unsafe {
                // Safety: we synchronization closing between the two peers through atomic
                // variables. At this point both sides have agreed on its final state.
                self.drop_contents();
            }
        }
    }

    /// Returns the channel slots as two pairs of filled and unfilled slices
    #[inline]
    pub fn as_pairs(&self) -> (Pair<T>, Pair<T>) {
        let data = self.data();
        self.data_to_pairs(data)
    }

    #[inline]
    fn data_to_pairs<'a>(&self, data: &'a [Cell<T>]) -> (Pair<'a, T>, Pair<'a, T>) {
        self.cursor.invariants();

        let head = self.cursor.head;
        let tail = self.cursor.tail;

        let (filled, unfilled) = if self.cursor.is_contiguous() {
            unsafe {
                assume!(data.len() >= tail, "data must span the tail length");
            }
            let (data, unfilled_head) = data.split_at(tail);

            unsafe {
                assume!(data.len() >= head, "data must span the head length");
            }
            let (unfilled_tail, filled_head) = data.split_at(head);

            let filled = Pair {
                head: Slice(filled_head),
                tail: Slice(&[]),
            };
            let unfilled = Pair {
                head: Slice(unfilled_head),
                tail: Slice(unfilled_tail),
            };
            (filled, unfilled)
        } else {
            unsafe {
                assume!(data.len() >= head, "data must span the head length");
            }
            let (data, filled_head) = data.split_at(head);

            unsafe {
                assume!(data.len() >= tail, "data must span the tail length");
            }
            let (filled_tail, unfilled_head) = data.split_at(tail);

            let filled = Pair {
                head: Slice(filled_head),
                tail: Slice(filled_tail),
            };
            let unfilled = Pair {
                head: Slice(unfilled_head),
                tail: Slice(&[]),
            };
            (filled, unfilled)
        };

        unsafe {
            assume!(
                filled.len() == self.cursor.recv_len(),
                "filled len should agree with the cursor len {} == {}\n{:?}",
                filled.len(),
                self.cursor.recv_len(),
                self.cursor
            );
        }

        (filled, unfilled)
    }

    /// Frees the contents of the channel
    ///
    /// # Safety
    ///
    /// Each side must have synchronized and agreed on the final state before calling this
    #[inline]
    unsafe fn drop_contents(&mut self) {
        // refresh the cursor from the shared state
        self.cursor.head = self.head.load(Ordering::Acquire);
        self.cursor.tail = self.tail.load(Ordering::Acquire);

        // release all of the filled data
        let (filled, _unfilled) = self.as_pairs();
        if !T::IS_ZST {
            for cell in filled.iter() {
                drop(cell.take());
            }
        }

        // make sure we free any stored wakers
        let header = self.header.as_mut();
        drop(header.receiver.take());
        drop(header.sender.take());

        // free the header
        let ptr = self.header.as_ptr() as *mut u8;
        let capacity = self.cursor.capacity;
        let (layout, _offset) = Header::<T>::layout_unchecked(capacity);
        alloc::alloc::dealloc(ptr, layout)
    }
}

pub struct Header<T> {
    head: CachePadded<AtomicUsize>,
    tail: CachePadded<AtomicUsize>,
    open: CachePadded<AtomicBool>,
    pub receiver: AtomicWaker,
    pub sender: AtomicWaker,
    data: PhantomData<T>,
}

impl<T> fmt::Debug for Header<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Header")
            .field("head", &self.head.load(Ordering::Relaxed))
            .field("tail", &self.tail.load(Ordering::Relaxed))
            .field("open", &self.open.load(Ordering::Relaxed))
            .field("receiver", &self.receiver)
            .field("sender", &self.sender)
            .finish()
    }
}

impl<T> Header<T> {
    /// Allocates a header and data slice for the given capacity
    fn alloc(capacity: usize) -> Option<NonNull<Self>> {
        unsafe {
            // Safety: we assume that `alloc` gives us a valid pointer to write to
            let (layout, _offset) = Self::layout(capacity).ok()?;
            let state = alloc::alloc::alloc(layout);
            let state = state as *mut Self;
            let state = NonNull::new(state)?;

            state.as_ptr().write(Self::new());

            Some(state)
        }
    }

    #[inline]
    fn new() -> Self {
        Self {
            head: CachePadded::new(AtomicUsize::new(0)),
            tail: CachePadded::new(AtomicUsize::new(0)),
            sender: AtomicWaker::new(),
            receiver: AtomicWaker::new(),
            open: CachePadded::new(AtomicBool::new(true)),
            data: PhantomData,
        }
    }

    /// Computes the checked layout for the header
    #[inline]
    fn layout(capacity: usize) -> Result<(Layout, usize), alloc::alloc::LayoutError> {
        let header_layout = Layout::new::<Self>();
        // A slice of cells is allocated in the same region as the header
        let data_layout = Layout::array::<Cell<T>>(capacity)?;
        let (layout, offset) = header_layout.extend(data_layout)?;
        Ok((layout, offset))
    }

    /// Computes the memory layout of the header without checking of its validatity
    ///
    /// # Safety
    ///
    /// The layout must have been previously checked before calling this.
    #[inline]
    unsafe fn layout_unchecked(capacity: usize) -> (Layout, usize) {
        if let Ok(v) = Self::layout(capacity) {
            v
        } else {
            core::hint::unreachable_unchecked()
        }
    }
}