uwheel/wheels/
wheel_ext.rs

1/// Extension trait for becoming a wheel
2pub trait WheelExt {
3    /// Returns the current head of the wheel
4    fn head(&self) -> usize;
5    /// Returns the current tail of the wheel
6    fn tail(&self) -> usize;
7    /// Returns the total number of slots which may be bigger than `Self::capacity`
8    fn num_slots(&self) -> usize;
9    /// Returns the number of wheel slots
10    fn capacity(&self) -> usize;
11
12    /// Returns the size of the wheel in bytes or `None` if it cannot be computed
13    fn size_bytes(&self) -> Option<usize> {
14        None
15    }
16
17    /// Returns `true` if the wheel is empty or `false` if it contains slots
18    fn is_empty(&self) -> bool {
19        self.tail() == self.head()
20    }
21
22    /// Returns the current number of used slots
23    fn len(&self) -> usize {
24        count(self.tail(), self.head(), self.num_slots())
25    }
26
27    /// Locate slot id `addend` forward
28    #[inline]
29    fn slot_idx_forward_from_head(&self, addend: usize) -> usize {
30        self.wrap_add(self.head(), addend)
31    }
32
33    /// Locate slot id `subtrahend` backward
34    #[inline]
35    fn slot_idx_backward_from_head(&self, subtrahend: usize) -> usize {
36        self.wrap_sub(self.head(), subtrahend)
37    }
38
39    /// Returns the index in the underlying buffer for a given logical element
40    /// index + addend.
41    #[inline]
42    fn wrap_add(&self, idx: usize, addend: usize) -> usize {
43        wrap_index(idx.wrapping_add(addend), self.num_slots())
44    }
45
46    /// Returns the index in the underlying buffer for a given logical element
47    /// index - subtrahend.
48    #[inline]
49    fn wrap_sub(&self, idx: usize, subtrahend: usize) -> usize {
50        wrap_index(idx.wrapping_sub(subtrahend), self.num_slots())
51    }
52}
53
54/// Returns the index in the underlying buffer for a given logical element index.
55#[inline]
56pub(crate) fn wrap_index(index: usize, size: usize) -> usize {
57    // size is always a power of 2
58    debug_assert!(size.is_power_of_two());
59    index & (size - 1)
60}
61
62/// Calculate the number of elements left to be read in the buffer
63#[inline]
64pub(crate) fn count(tail: usize, head: usize, size: usize) -> usize {
65    // size is always a power of 2
66    (head.wrapping_sub(tail)) & (size - 1)
67}