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
//! A library for different methods of allocating unique identifiers efficiently.
//!
//! Provided methods:
//!
//! * [Slab] - Allocates id in a slab-like manner, handling automatic
//!   reclamation by keeping a record of which identifier slot to allocate next.
//!
//! # Examples
//!
//! ```rust
//! let mut alloc = idalloc::Slab::<u32>::new();
//! assert_eq!(0u32, alloc.next());
//! assert_eq!(1u32, alloc.next());
//! alloc.free(0u32);
//! ```
#[deny(missing_docs)]
use std::fmt;

/// A type that can be used an allocator index.
pub trait Id: Copy + fmt::Display + fmt::Debug {
    /// Allocate the initial, unallocated value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use idalloc::Id as _;
    ///
    /// assert_eq!(0, u16::initial());
    /// assert_eq!(0, u16::initial());
    /// ```
    fn initial() -> Self;

    /// Get the index as a usize.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use idalloc::Id as _;
    ///
    /// assert_eq!(42, 42u16.as_usize());
    /// assert_eq!(42, 42u32.as_usize());
    /// ```
    fn as_usize(self) -> usize;

    /// Increment the index and return the incremented value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use idalloc::Id as _;
    ///
    /// assert_eq!(1, 0u16.increment());
    /// assert_eq!(1, 0u32.increment());
    /// ```
    fn increment(self) -> Self;

    /// Take the value and replace the existing value with the none variant.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use idalloc::Id as _;
    ///
    /// let mut v = 1u32;
    /// assert_eq!(1u32, v.take());
    /// assert_eq!(u32::none(), v);
    /// ```
    fn take(&mut self) -> Self;

    /// Test if the current value is none, and panic with the given message if
    /// if is.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use idalloc::Id as _;
    ///
    /// let mut v = 1u32;
    /// assert_eq!(1u32, v.expect("value must be defined"));
    /// ```
    fn expect(self, m: &str) -> Self;

    /// Construct the none sentinel value for this type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use idalloc::Id as _;
    ///
    /// assert!(u32::none().is_none());
    /// ```
    fn none() -> Self;

    /// Test if the value is the none sentinel value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use idalloc::Id as _;
    ///
    /// assert!(u32::none().is_none());
    /// ```
    fn is_none(self) -> bool;
}

macro_rules! impl_primitive_index {
    ($ty:ident) => {
        impl Id for $ty {
            #[inline(always)]
            fn initial() -> Self {
                0
            }

            #[inline(always)]
            fn as_usize(self) -> usize {
                self as usize
            }

            #[inline(always)]
            fn increment(self) -> Self {
                if self.is_none() {
                    panic!("index `{}` is out of bounds: 0-{}", self, std::$ty::MAX);
                }

                self + 1
            }

            #[inline(always)]
            fn take(&mut self) -> Self {
                std::mem::replace(self, Self::none())
            }

            #[inline(always)]
            fn expect(self, m: &str) -> Self {
                if self.is_none() {
                    panic!("{}", m);
                }

                self
            }

            #[inline(always)]
            fn none() -> Self {
                std::$ty::MAX
            }

            #[inline(always)]
            fn is_none(self) -> bool {
                self == Self::none()
            }
        }
    };
}

impl_primitive_index!(u8);
impl_primitive_index!(u16);
impl_primitive_index!(u32);
impl_primitive_index!(u64);
impl_primitive_index!(u128);

/// A slab-based id allocator which can deal with automatic reclamation as ids
/// are [freed][Slab::free].
///
/// # Examples
///
/// ```rust
/// use idalloc::Slab;
///
/// let mut alloc = Slab::<u32>::new();
///
/// let mut alloc = Slab::<u32>::new();
/// assert_eq!(0, alloc.next());
/// assert_eq!(1, alloc.next());
/// alloc.free(0);
/// assert_eq!(0, alloc.next());
/// assert_eq!(2, alloc.next());
/// alloc.free(0);
/// alloc.free(0);
/// alloc.free(1);
/// assert_eq!(1, alloc.next());
/// assert_eq!(0, alloc.next());
/// assert_eq!(3, alloc.next());
/// ```
pub struct Slab<I>
where
    I: Id,
{
    data: Vec<I>,
    next: I,
}

impl<I> Slab<I>
where
    I: Id,
{
    /// Construct a new slab allocator.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use idalloc::Slab;
    ///
    /// let mut alloc = Slab::<u32>::new();
    ///
    /// let mut alloc = Slab::<u32>::new();
    /// assert_eq!(0, alloc.next());
    /// assert_eq!(1, alloc.next());
    /// alloc.free(0);
    /// assert_eq!(0, alloc.next());
    /// ```
    pub fn new() -> Self {
        Self {
            data: Vec::new(),
            next: I::initial(),
        }
    }

    /// Allocate the next id.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let mut alloc = idalloc::Slab::<u32>::new();
    /// assert_eq!(0u32, alloc.next());
    /// assert_eq!(1u32, alloc.next());
    /// ```
    pub fn next(&mut self) -> I {
        let index = self.next;

        self.next = if let Some(entry) = self.data.get_mut(self.next.as_usize()) {
            entry.take().expect("next index is null")
        } else {
            self.data.push(I::none());
            self.next.increment()
        };

        index
    }

    /// Free the specified id.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let mut alloc = idalloc::Slab::<u32>::new();
    /// let id = alloc.next();
    /// assert!(!alloc.free(id + 1));
    /// assert!(alloc.free(id));
    /// assert!(!alloc.free(id));
    /// ```
    pub fn free(&mut self, index: I) -> bool {
        if let Some(entry) = self.data.get_mut(index.as_usize()) {
            if entry.is_none() {
                *entry = self.next;
                self.next = index;
                return true;
            }
        }

        false
    }
}

impl<I> Default for Slab<I>
where
    I: Id,
{
    fn default() -> Self {
        Self::new()
    }
}