vexillo 0.2.0

A bit flags macro.
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
use ::core::fmt::Debug;
use ::core::hash::Hash;
use ::core::ops::{
    Not,
    BitAnd, BitAndAssign,
    BitOr, BitOrAssign,
    BitXor, BitXorAssign,
    Add, AddAssign,
    Sub, SubAssign,
    Index,
    Range,
};
use vexmacro::const_binary_search_fn;

pub trait Flags: 'static
    + Sized
    + Send
    + Sync
    + Debug
    + Copy
    + Eq
    + Ord
    + Hash
    // Bitwise
    + Not
    + BitAnd<Self, Output = Self>
    + BitAndAssign<Self>
    + BitOr<Self, Output = Self>
    + BitOrAssign<Self>
    + BitXor<Self, Output = Self>
    + BitXorAssign<Self>
    + Add<Self, Output = Self>
    + AddAssign<Self>
    + Sub<Self, Output = Self>
    + SubAssign<Self>
    + Index<u32, Output = bool>
    + Index<usize, Output = bool>
{
    /// The type that is used for the internal bitmasks.
    type MaskType;
    type MasksArrayType;
    type BytesArrayType;
    
    /// The total number of bits for this type. This is equal to `size_of::<Self> * 8`.
    const BITS: u32;
    const USED_BITS: u32;
    const UNUSED_BITS: u32;
    /// The total number of bits for the mask type.
    const MASK_BITS: u32;
    /// The total number of bytes for the mask type.
    const MASK_SIZE: usize;
    /// The total number of masks in the internal array.
    const MASK_COUNT: usize;
    
    /// The total number of single-bit flags.
    const SINGLE_FLAG_COUNT: usize;
    /// The total number of union flags (flags composed of multiple other flags).
    const GROUP_FLAG_COUNT: usize;
    /// The total number of single and group flags.
    const TOTAL_FLAG_COUNT: usize;
    /// An instance with none of the bits set to 1.
    const NONE: Self;
    /// An instance with all of the bits set to 1.
    const ALL: Self;
    
    /// A table of all flags ordered first by [single, group], then ordered by declaration order.
    /// 
    /// - `FLAGS_TABLE[..SINGLE_FLAG_COUNT]` are the single flags.
    /// - `FLAGS_TALE[SINGLE_FLAG_COUNT..]` are the group flags.
    const FLAGS_TABLE: &'static [FlagRow<Self>];
    
    const SINGLE_FLAGS: &'static [FlagRow<Self>];
    const GROUP_FLAGS: &'static [FlagRow<Self>];
    const BIT_ORDERED_FLAGS_TABLE: &'static [FlagIndex];
    const ORDERED_FLAGS_TABLE: &'static [FlagIndex];
    const ORDERED_SINGLE_FLAG_INDICES: &'static [FlagIndex];
    const ORDERED_GROUP_FLAG_INDICES: &'static [FlagIndex];
    
    /// Create a new instance with none of the bits set.
    fn new() -> Self;
    /// Create a new instance with none of the bits set.
    fn none() -> Self;
    /// Create a new instance with all of the bits set.
    fn all() -> Self;
    /// Create a union of all `flags`.
    fn union(flags: &[Self]) -> Self;
    /// Create a union of all `flags` without all `removals`.
    fn union_without(flags: &[Self], removals: &[Self]) -> Self;
    /// Try to find a flag by its name. Returns [None] if the flag was not found.
    fn try_find(name: &str) -> Option<Self>;
    /// Find a flag by its name. Panics if the flag was not found.
    fn find(name: &str) -> Self;
    /// Find a flag by its name. Returns `default` if the flag was not found.
    fn find_or(name: &str, default: Self) -> Self;
    /// Find a flag by its name. Returns `NONE` if the flag was not found.
    fn find_or_none(name: &str) -> Self;
    /// Return the number of ones in the binary representation of `self`.
    fn count_ones(self) -> u32;
    /// Return the number of zeros in the binary representation of `self`.
    fn count_zeros(self) -> u32;
    /// Get the bit at `index`.
    fn get(self, index: u32) -> bool;
    /// Set the bit at `index`.
    fn set(&mut self, index: u32, on: bool) -> &mut Self;
    /// Swap the bit at `index`.
    fn swap(&mut self, index: u32, on: bool) -> bool;
    /// Create an instance with the bit at the given `inde` set to 1.
    fn from_index(index: u32) -> Self;
    /// Add all of the bits present in `flag`.
    fn add(&mut self, flag: Self) -> &mut Self;
    /// Add all of the bits present in all `flags`.
    fn add_all(&mut self, flags: &[Self]) -> &mut Self;
    /// Remove all of the bits present in `flag`.
    fn remove(&mut self, flag: Self) -> &mut Self;
    /// Remove all of the bits present in all `flags`.
    fn remove_all(&mut self, flags: &[Self]) -> &mut Self;
    /// Join with `flag`.
    fn with(self, flag: Self) -> Self;
    /// Join with all `flags`.
    fn with_all(self, flags: &[Self]) -> Self;
    /// Exclude `flag`.
    fn without(self, flag: Self) -> Self;
    /// Exclude all `flags`.
    fn without_all(self, flags: &[Self]) -> Self;
    /// Test if all bits of `flag` are present in `self`.
    fn has_all(self, flag: Self) -> bool;
    /// Test if none of the bits of `flag` are present in `self`.
    fn has_none(self, flag: Self) -> bool;
    /// Test if any of the bits of `flag` are present in `self`.
    fn has_any(self, flag: Self) -> bool;
    /// Returns the inner `masks` as a slice.
    fn as_slice(&self) -> &[Self::MaskType];
    /// Returns the inner `masks` as a mutable slice.
    fn as_mut_slice(&mut self) -> &mut [Self::MaskType];
    /// Decompose `self` into the inner `masks` array.
    fn into_inner(self) -> Self::MasksArrayType;
    /// Return `self` as a slice of bytes. Endianess is dependent on the target architecture. This is meant to be used for FFI. If you need serialization, use `to_be_bytes`, `to_le_bytes`, or `to_ne_bytes`.
    fn as_bytes(&self) -> &[u8];
    /// Return `self` as a mutable slice of bytes. Endianess is dependent on the target architecture. This is meant to be used for FFI. If you need serialization, use `to_be_bytes`, `to_le_bytes`, or `to_ne_bytes`.
    fn as_mut_bytes(&mut self) -> &mut [u8];
    /// Return `self` as Big-Endian bytes.
    fn to_be_bytes(self) -> Self::BytesArrayType;
    /// Create a new instance from Big-Endian `bytes`.
    fn from_be_bytes(bytes: Self::BytesArrayType) -> Self;
    /// Return `self` as Little-Endian bytes.
    fn to_le_bytes(self) -> Self::BytesArrayType;
    /// Create a new instance from Little-Endian `bytes`.
    fn from_le_bytes(bytes: Self::BytesArrayType) -> Self;
    /// Return `self` as Native-Endian bytes.
    fn to_ne_bytes(self) -> Self::BytesArrayType;
    /// Create a new instance from Native-Endian `bytes`.
    fn from_ne_bytes(bytes: Self::BytesArrayType) -> Self;
    /// Bitwise NOT.
    fn not(self) -> Self;
    /// Bitwise AND.
    fn and(self, other: Self) -> Self;
    /// Bitwise OR.
    fn or(self, other: Self) -> Self;
    /// Bitwise XOR.
    fn xor(self, other: Self) -> Self;
    /// Bitwise NAND.
    fn nand(self, other: Self) -> Self;
    /// Bitwise NOR.
    fn nor(self, other: Self) -> Self;
    /// Bitwise XNOR.
    fn xnor(self, other: Self) -> Self;
    /// Bitwise IMPLY.
    fn imply(self, other: Self) -> Self;
    /// Bitwise NIMPLY.
    fn nimply(self, other: Self) -> Self;
    /// Test for equality.
    fn eq(self, other: Self) -> Self;
    /// Test for inequality.
    fn ne(self, other: Self) -> Self;
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FlagIndex {
    index: u16,
}

impl FlagIndex {
    #[must_use]
    #[inline(always)]
    pub const fn new(index: u16) -> Self {
        Self { index }
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn index(self) -> usize {
        self.index as _
    }
}

#[derive(Debug, Clone, Copy)]
pub struct FlagRow<T: Flags> {
    pub name: &'static str,
    pub value: T,
    sub_flag_indices: Option<&'static [FlagIndex]>,
}

impl<T: Flags> FlagRow<T> {
    #[must_use]
    #[inline(always)]
    pub const fn single(name: &'static str, value: T) -> Self {
        Self { name, value, sub_flag_indices: None }
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn group(
        name: &'static str,
        value: T,
        sub_flag_indices: &'static [FlagIndex],
    ) -> Self {
        Self {
            name,
            value,
            sub_flag_indices: Some(sub_flag_indices),
        }
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn bits(&self) -> u32 {
        if let Some(subflags) = self.sub_flag_indices {
            subflags.len() as u32
        } else {
            1
        }
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn sub_flag_indices(&self) -> &'static [FlagIndex] {
        if let Some(subflags) = self.sub_flag_indices {
            subflags
        } else {
            &[]
        }
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FlagGroupInfo {
    /// The bit count.
    pub bits: u32,
    /// The index in the flag table.
    pub index: u16,
}

#[derive(Clone)]
pub struct FlagTables<T: Flags, const TABLE_LEN: usize, const SINGLE_COUNT: usize, const GROUP_COUNT: usize> {
    pub rows: [FlagRow<T>; TABLE_LEN],
    pub name_ordered_row_indices: [FlagIndex; TABLE_LEN],
    pub name_ordered_single_indices: [FlagIndex; SINGLE_COUNT],
    pub name_ordered_group_indices: [FlagIndex; GROUP_COUNT],
    pub bit_ordered_group_indices: [FlagIndex; GROUP_COUNT],
}

#[derive(Clone, Copy)]
pub struct FlagRows<T: Flags> {
    pub rows: &'static [FlagRow<T>],
}

impl<T: Flags> FlagRows<T> {
    #[must_use]
    #[inline(always)]
    pub const fn new(rows: &'static [FlagRow<T>]) -> Self {
        Self { rows }
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn rows(&self, range: Range<usize>) -> FlagRows<T> {
        FlagRows::new(crate::internal::subslice(self.rows, range))
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn row(&self, index: usize) -> &'static FlagRow<T> {
        &self.rows[index]
    }
}

impl<
    T: Flags,
    const TABLE_LEN: usize,
    const SINGLE_COUNT: usize,
    const GROUP_COUNT: usize
> FlagTables<T, TABLE_LEN, SINGLE_COUNT, GROUP_COUNT> {
    #[must_use]
    #[inline(always)]
    pub const fn len() -> usize {
        TABLE_LEN
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn single_len() -> usize {
        SINGLE_COUNT
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn group_len() -> usize {
        GROUP_COUNT
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn singles_range() -> Range<usize> {
        0..SINGLE_COUNT
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn groups_range() -> Range<usize> {
        SINGLE_COUNT..TABLE_LEN
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn row(&'static self, index: u16) -> &'static FlagRow<T> {
        &self.rows[index as usize]
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn rows(&'static self, range: Range<usize>) -> FlagRows<T> {
        FlagRows::new(crate::internal::subslice(&self.rows, range))
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn singles(&'static self) -> FlagRows<T> {
        self.rows(Self::singles_range())
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn groups(&'static self) -> FlagRows<T> {
        self.rows(Self::groups_range())
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn name(&'static self, index: u16) -> &'static str {
        self.row(index).name
    }
    
    #[must_use]
    #[inline(always)]
    pub const fn value(&'static self, index: u16) -> T {
        self.row(index).value
    }
    
    #[inline(always)]
    const fn rev_bit_count_search_cmp(lhs: u32, rhs_index: FlagIndex, context: &[FlagRow<T>]) -> ::core::cmp::Ordering {
        use ::core::cmp::Ordering::*;
        let rhs = context[rhs_index.index()].bits();
        if lhs > rhs {
            Less
        } else if lhs < rhs {
            Greater
        } else {
            Equal
        }
    }
    
    const_binary_search_fn!(
        use Self::rev_bit_count_search_cmp;
        #[must_use]
        #[inline(always)]
        const fn bit_count_binary_search(static u32, static FlagIndex, context: &[FlagRow<T>]) -> usize
    );
    
    /// Returns the first index of the row in `self.bit_ordered_group_indices` where `row.bits <= bits`.
    #[inline]
    #[must_use]
    #[track_caller]
    const fn upper_bit_count_search(&'static self, bits: u32, range: Range<usize>) -> usize {
        let start = range.start;
        Self::bit_count_binary_search(
            bits,
            crate::internal::subslice(&self.bit_ordered_group_indices, range),
            &self.rows
        ) + start
    }
    
    #[inline]
    #[must_use]
    #[track_caller]
    const fn upper_bit_count_search_full(&'static self, bits: u32) -> usize {
        self.upper_bit_count_search(
            bits,
            0..self.bit_ordered_group_indices.len()
        )
    }
}

#[derive(Clone)]
pub struct FlagConstants<
    T: Flags,
    const SINGLE_COUNT: usize,
    const GROUP_COUNT: usize,
    const TOTAL_COUNT: usize,
> {
    // Counts
    pub single_flag_count: usize,
    pub group_flag_count: usize,
    pub total_flag_count: usize,
    // Sizes
    pub bits: u32,
    pub mask_bits: u32,
    pub mask_count: usize,
    // Arrays
    pub table: FlagTables<T, TOTAL_COUNT, SINGLE_COUNT, GROUP_COUNT>,
}