enumoid 0.5.0

Enum Indexed Containers
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
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
use crate::sub_base::BitsetWordTrait;
use crate::sub_base::RawSizeWord;
use std::cmp::Ordering;
use std::fmt;
use std::fmt::Debug;
use std::hash::Hash;
use std::hash::Hasher;
use std::iter::Iterator;
use std::iter::Map;
use std::mem;

macro_rules! hint_assert {
    ($x:expr, $($arg:tt)*) => {
      debug_assert!($x, $($arg)*);
      if !$x {
        std::hint::unreachable_unchecked();
      }
    }
}

/// Iterator for Enumoids.
pub type EnumoidIter<T> =
  Map<<T as Enumoid>::WordRange, fn(<T as Enumoid>::Word) -> T>;

/// A counter between 0 and the number of values inhabiting `T`.
pub struct EnumSize<T: Enumoid>(T::Word);

impl<T: Enumoid> Copy for EnumSize<T> {}

impl<T: Enumoid> Clone for EnumSize<T> {
  fn clone(&self) -> Self {
    *self
  }
}

impl<T: Enumoid> Debug for EnumSize<T> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_tuple("EnumSize").field(&self.0).finish()
  }
}

impl<T: Enumoid> PartialEq for EnumSize<T> {
  fn eq(&self, other: &Self) -> bool {
    self.0 == other.0
  }
}

impl<T: Enumoid> Eq for EnumSize<T> {}

impl<T: Enumoid> PartialOrd for EnumSize<T> {
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.cmp(other))
  }
}

impl<T: Enumoid> Ord for EnumSize<T> {
  fn cmp(&self, other: &Self) -> Ordering {
    self.0.cmp(&other.0)
  }
}

impl<T: Enumoid> Hash for EnumSize<T> {
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.0.hash(state);
  }
}

impl<T: Enumoid> EnumSize<T> {
  pub const EMPTY: EnumSize<T> = EnumSize(T::Word::ZERO);
  pub const FULL: EnumSize<T> = EnumSize(T::SIZE_WORD);

  #[inline]
  pub fn from_last(value: T) -> Self {
    EnumSize(value.into_word().inc())
  }

  #[inline]
  pub(crate) unsafe fn from_word_unchecked(value: T::Word) -> Self {
    unsafe {
      hint_assert!(
        value <= T::SIZE_WORD,
        "from_word_unchecked: Size out of bounds: {:?} > {:?}",
        value,
        T::SIZE_WORD
      );
    }
    EnumSize(value)
  }

  pub fn from_word(sz: T::Word) -> Option<Self> {
    if sz <= T::SIZE_WORD {
      Some(EnumSize(sz))
    } else {
      None
    }
  }

  pub fn from_usize(sz: usize) -> Option<Self> {
    if sz <= T::SIZE {
      Some(EnumSize(T::Word::from_usize_unchecked(sz)))
    } else {
      None
    }
  }

  #[inline]
  pub fn into_word(self) -> T::Word {
    self.0
  }

  #[inline]
  pub fn into_usize(self) -> usize {
    self.0.as_()
  }

  #[inline]
  pub fn into_last_index(self) -> Option<EnumIndex<T>> {
    if self.0 > T::Word::ZERO {
      Some(unsafe { EnumIndex::from_word_unchecked(self.0.dec()) })
    } else {
      None
    }
  }

  #[inline]
  pub fn into_last(self) -> Option<T> {
    self.into_last_index().map(|i| i.into_value())
  }

  /// Returns the next index or None.
  ///
  /// # Panics
  /// Panics if the value is beyond the size.
  #[inline]
  pub fn next_index(self, index: EnumIndex<T>) -> Option<EnumIndex<T>> {
    assert!(index.0 < self.0);
    let nw = index.0.inc();
    if nw < self.0 {
      Some(unsafe { EnumIndex::from_word_unchecked(nw) })
    } else {
      None
    }
  }

  /// Returns the next element or None.
  ///
  /// # Panics
  /// Panics if the value is beyond the size.
  #[inline]
  pub fn next(self, value: T) -> Option<T> {
    self.next_index(value.into()).map(|i| i.into_value())
  }

  /// Returns the previous index or None.
  ///
  /// # Panics
  /// Panics if the value is beyond the size.
  #[inline]
  pub fn prev_index(self, index: EnumIndex<T>) -> Option<EnumIndex<T>> {
    assert!(index.0 < self.0);
    if index.0 > T::Word::ZERO {
      Some(unsafe { EnumIndex::from_word_unchecked(index.0.dec()) })
    } else {
      None
    }
  }

  /// Returns the previous element or None.
  ///
  /// # Panics
  /// Panics if the value is beyond the size.
  #[inline]
  pub fn prev(self, value: T) -> Option<T> {
    self.prev_index(value.into()).map(|i| i.into_value())
  }

  /// Returns the next index or wraps around to the beginning.
  ///
  /// # Panics
  /// Panics if the value is beyond the size.
  #[inline]
  pub fn next_index_wrapped(self, index: EnumIndex<T>) -> EnumIndex<T> {
    assert!(index.0 < self.0);
    let nw = index.0.inc();
    let q = if nw < self.0 { nw } else { T::Word::ZERO };
    unsafe { EnumIndex::from_word_unchecked(q) }
  }

  /// Returns the next element or wraps around to the beginning.
  ///
  /// # Panics
  /// Panics if the value is beyond the size.
  #[inline]
  pub fn next_wrapped(self, value: T) -> T {
    self.next_index_wrapped(value.into()).into_value()
  }

  /// Returns the previous index or wraps around to the end.
  ///
  /// # Panics
  /// Panics if the value is beyond the size.
  #[inline]
  pub fn prev_index_wrapped(self, index: EnumIndex<T>) -> EnumIndex<T> {
    assert!(index.0 < self.0);
    let q = if index.0 > T::Word::ZERO {
      index.0
    } else {
      self.0
    }
    .dec();
    unsafe { EnumIndex::from_word_unchecked(q) }
  }

  /// Returns the previous element or wraps around to the end.
  ///
  /// # Panics
  /// Panics if the value is beyond the size.
  #[inline]
  pub fn prev_wrapped(self, value: T) -> T {
    self.prev_index_wrapped(value.into()).into_value()
  }

  #[inline]
  pub fn contains_index(self, index: EnumIndex<T>) -> bool {
    index.0 < self.0
  }

  #[inline]
  pub fn contains(self, value: T) -> bool {
    value.into_word() < self.0
  }

  /// Returns the next size larger or None.
  #[inline]
  pub fn increase(self) -> Option<Self> {
    if self.0 < T::SIZE_WORD {
      Some(unsafe { EnumSize::from_word_unchecked(self.0.inc()) })
    } else {
      None
    }
  }

  /// Returns the next size smaller or None.
  #[inline]
  pub fn decrease(self) -> Option<Self> {
    if self.0 > T::Word::ZERO {
      Some(unsafe { EnumSize::from_word_unchecked(self.0.dec()) })
    } else {
      None
    }
  }

  #[inline]
  pub fn iter(self) -> EnumoidIter<T> {
    T::word_range(T::Word::ZERO, self.0)
      .map(|w| unsafe { T::from_word_unchecked(w) })
  }

  #[inline]
  pub fn iter_until(self, until: T) -> EnumoidIter<T> {
    T::word_range(T::Word::ZERO, self.0.min(until.into_word().inc()))
      .map(|w| unsafe { T::from_word_unchecked(w) })
  }

  #[inline]
  pub fn iter_from(self, from: T) -> EnumoidIter<T> {
    T::word_range(from.into_word(), self.0)
      .map(|w| unsafe { T::from_word_unchecked(w) })
  }

  #[inline]
  pub fn iter_from_until(self, from: T, until: T) -> EnumoidIter<T> {
    let w = until.into_word().inc();
    if w < self.0 {
      unsafe { EnumSize::from_word_unchecked(w) }.iter_from(from)
    } else {
      self.iter_from(from)
    }
  }
}

/// A counter between 0 and the highest index into the values inhabiting `T`.
pub struct EnumIndex<T: Enumoid>(T::Word);

impl<T: Enumoid> Copy for EnumIndex<T> {}

impl<T: Enumoid> Clone for EnumIndex<T> {
  fn clone(&self) -> Self {
    *self
  }
}

impl<T: Enumoid> Debug for EnumIndex<T> {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.debug_tuple("EnumIndex").field(&self.0).finish()
  }
}

impl<T: Enumoid> PartialEq for EnumIndex<T> {
  fn eq(&self, other: &Self) -> bool {
    self.0 == other.0
  }
}

impl<T: Enumoid> Eq for EnumIndex<T> {}

impl<T: Enumoid> PartialOrd for EnumIndex<T> {
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
    Some(self.cmp(other))
  }
}

impl<T: Enumoid> Ord for EnumIndex<T> {
  fn cmp(&self, other: &Self) -> Ordering {
    self.0.cmp(&other.0)
  }
}

impl<T: Enumoid> Hash for EnumIndex<T> {
  fn hash<H: Hasher>(&self, state: &mut H) {
    self.0.hash(state);
  }
}

impl<T: Enumoid> EnumIndex<T> {
  #[inline]
  pub(crate) unsafe fn from_word_unchecked(value: T::Word) -> Self {
    unsafe {
      hint_assert!(
        value < T::SIZE_WORD,
        "from_word_unchecked: Index out of bounds: {:?} >= {:?}",
        value,
        T::SIZE_WORD
      );
    }
    EnumIndex(value)
  }

  pub fn from_usize(sz: usize) -> Option<Self> {
    if sz < T::SIZE {
      Some(EnumIndex(T::Word::from_usize_unchecked(sz)))
    } else {
      None
    }
  }

  pub fn from_value(value: T) -> Self {
    unsafe { Self::from_word_unchecked(value.into_word()) }
  }

  #[inline]
  pub fn into_value(self) -> T {
    unsafe { T::from_word_unchecked(self.0) }
  }

  #[inline]
  pub fn into_word(self) -> T::Word {
    unsafe {
      hint_assert!(
        self.0 < T::SIZE_WORD,
        "Index out of bounds: {:?} >= {:?}",
        self.0,
        T::SIZE
      );
    };
    self.0
  }

  #[inline]
  pub fn into_usize(self) -> usize {
    self.into_word().as_()
  }

  /// Returns the next index or None.
  #[inline]
  pub fn next(self) -> Option<Self> {
    EnumSize::FULL.next_index(self)
  }

  /// Returns the previous index or None.
  #[inline]
  pub fn prev(self) -> Option<Self> {
    EnumSize::FULL.prev_index(self)
  }

  /// Returns the next index or wraps around to the beginning.
  #[inline]
  pub fn next_wrapped(self) -> Self {
    EnumSize::FULL.next_index_wrapped(self)
  }

  /// Returns the previous index or wraps around to the end.
  #[inline]
  pub fn prev_wrapped(self) -> Self {
    EnumSize::FULL.prev_index_wrapped(self)
  }
}

impl<T: Enumoid> From<T> for EnumIndex<T> {
  #[inline]
  fn from(value: T) -> Self {
    EnumIndex(value.into_word())
  }
}

/// Trait for enumerable types.
///
/// Some members are hidden. Impls should only be defined via the `Enumoid` derive macro.
pub trait Enumoid: Sized {
  type Word: RawSizeWord;
  const SIZE: usize;
  const FIRST: Self;
  const LAST: Self;
  fn into_word(self) -> Self::Word;

  #[doc(hidden)]
  type WordRange: Iterator<Item = Self::Word>;
  #[doc(hidden)]
  const SIZE_WORD: Self::Word;
  /// # Safety
  /// The input word must be less than SIZE.
  #[doc(hidden)]
  unsafe fn from_word_unchecked(value: Self::Word) -> Self;
  #[doc(hidden)]
  fn word_range(base: Self::Word, sz: Self::Word) -> Self::WordRange;

  #[inline]
  fn from_word(value: Self::Word) -> Option<Self> {
    if value < Self::SIZE_WORD {
      Some(unsafe { Self::from_word_unchecked(value) })
    } else {
      None
    }
  }

  #[inline]
  fn next(self) -> Option<Self> {
    EnumSize::FULL.next(self)
  }

  #[inline]
  fn prev(self) -> Option<Self> {
    EnumSize::FULL.prev(self)
  }

  #[inline]
  fn next_wrapped(self) -> Self {
    EnumSize::FULL.next_wrapped(self)
  }

  #[inline]
  fn prev_wrapped(self) -> Self {
    EnumSize::FULL.prev_wrapped(self)
  }

  #[inline]
  fn iter() -> EnumoidIter<Self> {
    EnumSize::FULL.iter()
  }

  #[inline]
  fn iter_until(until: Self) -> EnumoidIter<Self> {
    EnumSize::from_last(until).iter()
  }

  #[inline]
  fn iter_from(from: Self) -> EnumoidIter<Self> {
    EnumSize::FULL.iter_from(from)
  }

  #[inline]
  fn iter_from_until(from: Self, until: Self) -> EnumoidIter<Self> {
    EnumSize::from_last(until).iter_from(from)
  }
}

/// Workaround for const generics not supporting associated consts yet.
///
/// All the members are hidden. Impls should only be defined via the `Enumoid` derive macro.
pub trait EnumArrayHelper<V: Sized>: Enumoid {
  #[doc(hidden)]
  type PartialArray: Sized;
  #[doc(hidden)]
  type TotalArray: Sized;

  #[doc(hidden)]
  fn partial_slice(p: &Self::PartialArray) -> &[mem::MaybeUninit<V>];
  #[doc(hidden)]
  fn partial_slice_mut(
    p: &mut Self::PartialArray,
  ) -> &mut [mem::MaybeUninit<V>];
  /// # Safety
  /// All the elements in the input array must be initialised.
  #[doc(hidden)]
  unsafe fn partial_to_total(p: Self::PartialArray) -> Self::TotalArray;

  #[doc(hidden)]
  fn total_slice(t: &Self::TotalArray) -> &[V];
  #[doc(hidden)]
  fn total_slice_mut(t: &mut Self::TotalArray) -> &mut [V];
  #[doc(hidden)]
  fn total_to_partial(t: Self::TotalArray) -> Self::PartialArray;

  #[inline]
  #[allow(clippy::uninit_assumed_init)]
  #[doc(hidden)]
  fn new_partial() -> Self::PartialArray {
    unsafe { mem::MaybeUninit::uninit().assume_init() }
  }
}

/// Workaround for const generics not supporting associated consts yet.
///
/// All the members are hidden. Impls should only be defined via the `Enumoid` derive macro.
pub trait EnumSetHelper<BitsetWord: BitsetWordTrait>: Enumoid {
  #[doc(hidden)]
  type BitsetWord: BitsetWordTrait;
  #[doc(hidden)]
  type BitsetArray: Sized;
  #[doc(hidden)]
  const BITSET_WORD_BITS: usize;
  #[doc(hidden)]
  const BITSET_WORDS: usize = Self::SIZE.div_ceil(Self::BITSET_WORD_BITS);
  #[doc(hidden)]
  const DEFAULT_BITSET: Self::BitsetArray;
  #[doc(hidden)]
  fn slice_bitset(arr: &Self::BitsetArray) -> &[Self::BitsetWord];
  #[doc(hidden)]
  fn slice_bitset_mut(arr: &mut Self::BitsetArray) -> &mut [Self::BitsetWord];
}