ptab 0.1.7

Lock-free concurrent table optimized for read-heavy workloads
Documentation
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
use core::fmt::Debug;
use core::fmt::Display;
use core::fmt::Formatter;
use core::fmt::Result;

use crate::params::Params;
use crate::params::ParamsExt;

macro_rules! internal_index {
  ($name:ident) => {
    #[repr(transparent)]
    pub(crate) struct $name<P>
    where
      P: ?Sized,
    {
      source: usize,
      marker: ::core::marker::PhantomData<fn(P)>,
    }

    impl<P> $name<P>
    where
      P: ?Sized,
    {
      #[inline]
      pub(crate) const fn new(source: usize) -> Self {
        Self {
          source,
          marker: ::core::marker::PhantomData,
        }
      }

      #[inline]
      pub(crate) const fn get(self) -> usize {
        self.source
      }
    }

    impl<P> Clone for $name<P>
    where
      P: ?Sized,
    {
      #[inline]
      fn clone(&self) -> Self {
        *self
      }
    }

    impl<P> Copy for $name<P> where P: ?Sized {}

    impl<P> ::core::cmp::PartialEq for $name<P>
    where
      P: ?Sized,
    {
      #[inline]
      fn eq(&self, other: &Self) -> bool {
        self.source == other.source
      }
    }

    impl<P> ::core::fmt::Debug for $name<P>
    where
      P: ?Sized,
    {
      #[inline]
      fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
        ::core::fmt::Debug::fmt(&self.source, f)
      }
    }
  };
}

// -----------------------------------------------------------------------------
// Detached Index
// -----------------------------------------------------------------------------

/// An opaque index identifying a table entry.
///
/// Returned by [`PTab::insert`] and [`PTab::write`]; used to access or remove
/// entries.
///
/// # Generational Indices
///
/// Each index contains a generational component that changes when a slot is
/// reused. This helps mitigate the [ABA problem]: a stale index from a removed
/// entry will not match a new entry occupying the same slot.
///
/// # Examples
///
/// ```
/// use ptab::PTab;
///
/// let table: PTab<i32> = PTab::new();
///
/// let idx = table.insert(42).unwrap();
///
/// // Access the entry by index
/// assert_eq!(table.read(idx), Some(42));
///
/// // Indices are Copy
/// let idx2 = idx;
/// assert_eq!(table.read(idx2), Some(42));
/// ```
///
/// [`PTab`]: crate::public::PTab
/// [`PTab::insert`]: crate::public::PTab::insert
/// [`PTab::write`]: crate::public::PTab::write
/// [ABA problem]: https://en.wikipedia.org/wiki/ABA_problem
#[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Detached {
  bits: usize,
}

impl Detached {
  /// Creates a [`Detached`] index from its raw bit representation.
  ///
  /// # Warning
  ///
  /// An arbitrary bit pattern may not correspond to a valid table entry; using
  /// it is safe but will return [`None`] or `false` from table operations.
  #[inline]
  pub const fn from_bits(bits: usize) -> Self {
    Self { bits }
  }

  /// Returns the raw bit representation of this index.
  ///
  /// See [`from_bits`] to reconstruct an index.
  ///
  /// [`from_bits`]: Self::from_bits
  #[inline]
  pub const fn into_bits(self) -> usize {
    self.bits
  }

  /// Translates this index into its `(number, serial)` components.
  #[inline]
  pub const fn decompose<P>(self) -> (u32, u32)
  where
    P: Params + ?Sized,
  {
    let abstract_idx: Abstract<P> = detached_to_abstract(self);

    let number: u32 = (abstract_idx.get() & P::ID_MASK_ENTRY) as u32;
    let serial: u32 = (abstract_idx.get() >> P::ID_MASK_BITS) as u32;

    (number, serial)
  }
}

impl Debug for Detached {
  #[inline]
  fn fmt(&self, f: &mut Formatter<'_>) -> Result {
    Debug::fmt(&self.bits, f)
  }
}

impl Display for Detached {
  #[inline]
  fn fmt(&self, f: &mut Formatter<'_>) -> Result {
    Display::fmt(&self.bits, f)
  }
}

impl Detached {
  #[inline]
  pub(crate) const fn from_abstract<P>(other: Abstract<P>) -> Self
  where
    P: Params + ?Sized,
  {
    abstract_to_detached(other)
  }
}

// -----------------------------------------------------------------------------
// Abstract Index
// -----------------------------------------------------------------------------

internal_index!(Abstract);

impl<P> Abstract<P>
where
  P: Params + ?Sized,
{
  #[inline]
  pub(crate) const fn from_detached(other: Detached) -> Self {
    detached_to_abstract(other)
  }
}

// -----------------------------------------------------------------------------
// Concrete Index
// -----------------------------------------------------------------------------

internal_index!(Concrete);

impl<P> Concrete<P>
where
  P: Params + ?Sized,
{
  #[inline]
  pub(crate) const fn from_abstract(other: Abstract<P>) -> Self {
    abstract_to_concrete(other)
  }

  #[inline]
  pub(crate) const fn from_detached(other: Detached) -> Self {
    detached_to_concrete(other)
  }
}

// -----------------------------------------------------------------------------
// Index Mapping
// -----------------------------------------------------------------------------

/// Extracts the [`Abstract`] sequential index from a [`Detached`] index.
#[inline]
const fn detached_to_abstract<P>(detached: Detached) -> Abstract<P>
where
  P: Params + ?Sized,
{
  let mut value: usize = detached.into_bits() & !P::ID_MASK_ENTRY;
  value |= (detached.into_bits() >> P::ID_SHIFT_BLOCK) & P::ID_MASK_BLOCK;
  value |= (detached.into_bits() & P::ID_MASK_INDEX) << P::ID_SHIFT_INDEX;
  Abstract::new(value)
}

/// Extracts the [`Concrete`] cache-aware index from a [`Detached`] index.
#[inline]
const fn detached_to_concrete<P>(detached: Detached) -> Concrete<P>
where
  P: Params + ?Sized,
{
  Concrete::new(detached.into_bits() & P::ID_MASK_ENTRY)
}

/// Converts an [`Abstract`] sequential index to a [`Concrete`] cache-aware index.
#[inline]
const fn abstract_to_concrete<P>(abstract_idx: Abstract<P>) -> Concrete<P>
where
  P: Params + ?Sized,
{
  let mut value: usize = 0;
  value += (abstract_idx.get() & P::ID_MASK_BLOCK) << P::ID_SHIFT_BLOCK;
  value += (abstract_idx.get() >> P::ID_SHIFT_INDEX) & P::ID_MASK_INDEX;
  Concrete::new(value)
}

/// Converts an [`Abstract`] sequential index to a [`Detached`] index.
#[inline]
const fn abstract_to_detached<P>(abstract_idx: Abstract<P>) -> Detached
where
  P: Params + ?Sized,
{
  let index: usize = abstract_idx.get() & !P::ID_MASK_ENTRY;
  let index: usize = index | abstract_to_concrete(abstract_idx).get();
  let value: Detached = Detached::from_bits(index);
  debug_assert!(detached_to_abstract::<P>(value).get() == abstract_idx.get());
  value
}

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
  use std::collections::HashSet;

  use crate::index::Abstract;
  use crate::index::Concrete;
  use crate::index::Detached;
  use crate::params::CACHE_LINE_SLOTS;
  use crate::params::Params;
  use crate::params::ParamsExt;
  use crate::utils::each_capacity;

  #[expect(clippy::clone_on_copy)]
  #[test]
  fn abstract_clone_copy() {
    let a: Abstract<()> = Abstract::new(123);
    let b: Abstract<()> = a.clone();
    let c: Abstract<()> = b;

    assert_eq!(a, b);
    assert_eq!(b, c);
    assert_eq!(c, a);
  }

  #[expect(clippy::clone_on_copy)]
  #[test]
  fn concrete_clone_copy() {
    let a: Concrete<()> = Concrete::new(123);
    let b: Concrete<()> = a.clone();
    let c: Concrete<()> = b;

    assert_eq!(a, b);
    assert_eq!(b, c);
    assert_eq!(c, a);
  }

  #[test]
  fn abstract_debug_transparency() {
    let value: usize = 123;
    let index: Abstract<()> = Abstract::new(value);

    assert_eq!(format!("{index:?}"), format!("{value:?}"));
  }

  #[test]
  fn concrete_debug_transparency() {
    let value: usize = 123;
    let index: Concrete<()> = Concrete::new(value);

    assert_eq!(format!("{index:?}"), format!("{value:?}"));
  }

  #[test]
  fn detached_debug_transparency() {
    let value: usize = 123;
    let index: Detached = Detached::from_bits(value);

    assert_eq!(format!("{index:?}"), format!("{value:?}"));
  }

  #[test]
  fn detached_display_transparency() {
    let value: usize = 123;
    let index: Detached = Detached::from_bits(value);

    assert_eq!(format!("{index}"), format!("{value}"));
  }

  #[test]
  fn detached_bits_roundtrip() {
    let data: usize = usize::MAX >> 2;
    let bits: usize = Detached::from_bits(data).into_bits();

    assert_eq!(data, bits);
  }

  #[test]
  fn detached_decompose() {
    each_capacity!({
      for generation in 0..3 {
        let offset: usize = generation * P::LENGTH.as_usize();

        for index in 0..P::LENGTH.as_usize() {
          let abstract_idx: Abstract<P> = Abstract::new(offset + index);
          let detached_idx: Detached = Detached::from_abstract(abstract_idx);

          let components: (u32, u32) = detached_idx.decompose::<P>();

          assert_eq!(components.0 as usize, index);
          assert_eq!(components.1 as usize, generation);
        }
      }
    });
  }

  #[test]
  fn abstract_to_concrete_covers_all_slots() {
    each_capacity!({
      let mut used: HashSet<usize> = HashSet::with_capacity(P::LENGTH.as_usize());

      for index in 0..P::LENGTH.as_usize() {
        let abstract_idx: Abstract<P> = Abstract::new(index);
        let concrete_idx: Concrete<P> = Concrete::from_abstract(abstract_idx);

        used.insert(concrete_idx.get());
      }

      assert_eq!(used.len(), P::LENGTH.as_usize());
      assert_eq!(used.iter().min(), Some(&0));
      assert_eq!(used.iter().max(), Some(&(P::LENGTH.as_usize() - 1)));
    });
  }

  #[test]
  fn abstract_to_detached_roundtrip() {
    each_capacity!({
      for index in 0..P::LENGTH.as_usize() {
        let abstract_idx: Abstract<P> = Abstract::new(index);
        let detached_idx: Detached = Detached::from_abstract(abstract_idx);
        let recovery_idx: Abstract<P> = Abstract::from_detached(detached_idx);

        assert_eq!(abstract_idx, recovery_idx);
      }
    });
  }

  #[test]
  fn concrete_from_detached_matches_from_abstract() {
    each_capacity!({
      for index in 0..P::LENGTH.as_usize() {
        let abstract_idx: Abstract<P> = Abstract::new(index);
        let detached_idx: Detached = Detached::from_abstract(abstract_idx);

        let from_abstract: Concrete<P> = Concrete::from_abstract(abstract_idx);
        let from_detached: Concrete<P> = Concrete::from_detached(detached_idx);

        assert_eq!(from_abstract, from_detached);
      }
    });
  }

  #[test]
  fn cache_line_distribution() {
    // Verify that consecutive base indices are distributed across cache lines
    each_capacity!('block: {
      if P::BLOCKS.get() <= 1 {
        break 'block; // Skip solo blocks
      }

      // First `CACHE_LINE_SLOTS` indices should map to different blocks
      let mut blocks: HashSet<usize> = HashSet::with_capacity(CACHE_LINE_SLOTS);

      for index in 0..P::LENGTH.as_usize() {
        let abstract_idx: Abstract<P> = Abstract::new(index);
        let concrete_idx: Concrete<P> = Concrete::from_abstract(abstract_idx);

        blocks.insert(concrete_idx.get() / CACHE_LINE_SLOTS);
      }

      assert_eq!(blocks.len(), P::BLOCKS.get());
      assert_eq!(blocks.iter().min(), Some(&0));
      assert_eq!(blocks.iter().max(), Some(&(P::BLOCKS.get() - 1)));
    });
  }

  #[test]
  fn serial_number_preservation() {
    each_capacity!({
      for generation in 0..16 {
        let serial: usize = generation * P::LENGTH.as_usize();

        for index in 0..P::LENGTH.as_usize() {
          let abstract_idx: Abstract<P> = Abstract::new(serial + index);
          let detached_idx: Detached = Detached::from_abstract(abstract_idx);
          let recovery_idx: Abstract<P> = Abstract::from_detached(detached_idx);

          assert_eq!(abstract_idx.get(), serial + index);
          assert_eq!(abstract_idx, recovery_idx);
        }
      }
    });
  }
}