devela 0.28.0

A development substrate of coherence.
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
// devela::data::codec::bit::bin::set::definition
//
//! Defines [`set!`]
//

#[doc = crate::_tags!(construction set bit)]
/// Defines a compact set backed by an integer bit mask.
#[doc = crate::_doc_meta!{location("data/codec")}]
///
#[doc = include_str!["./_docs_set.md"]]
#[macro_export]
#[cfg_attr(cargo_primary_package, doc(hidden))]
macro_rules! set· {
    {
        $(#[$struct_attrs:meta])*
        $vis:vis struct $Set:ident($T:ty) {
            $(
                $(#[$f_attrs:meta])*
                $f:ident = $( $start:tt $(..= $end:tt)? ),+ $(,)?;
            )*
        }
        $( traits( $( ! $no_trait:ident ),* $(,)? ); )?
        $( // optional impl blocks
            $(#[$impl_attrs:meta])*
            impl { $($user_impl:item)* }
        )*
    } => {
        $crate::set!(%guard_allowed_type $Set, $T);

        $( #[$struct_attrs] )*
        #[derive(Clone, Copy)]
        $vis struct $Set { bits: $T }
        $(
            $( #[$impl_attrs] )*
            impl $Set { $($user_impl)* }
        )*

        /// Named constants
        impl $Set { $crate::paste! { $(
            // single-bit constants
            #[$crate::compile[all(none($($($end)?)+), xone($(some($start)),+))]]
            $crate::items! {
                /// <span class='stab portability' title='single-bit constant'>`1`</span>
                $(#[$f_attrs])*
                #[allow(non_upper_case_globals)]
                $vis const $f: Self = Self {
                    bits: $crate::set!(%mask $T; $( $start $(..= $end)? ),+)
                };
            }
            // grouped constants
            #[$crate::compile[any(some($($($end)?)+), not(xone($(some($start)),+)))]]
            $crate::items! {
                /// <span class='stab portability' title='grouped constant'>`+`</span>
                $(#[$f_attrs])*
                #[allow(non_upper_case_globals)]
                $vis const $f: Self = Self {
                    bits: $crate::set!(%mask $T; $( $start $(..= $end)? ),+)
                };
            }

            /* per-constant private metadata */
            /// The number of bits in $f.
            #[allow(non_upper_case_globals)]
            pub(crate) const [<_ $f _BITS>]: u32 = Self::$f.bits.count_ones();
            // /// Whether $f is composed of a single bit.
            // #[allow(non_upper_case_globals)]
            // pub(crate) const [<_ $f _IS_SINGLE>]: bool = Self::[<_ $f _BITS>] == 1;
        )* }}

        /// Convenience methods derived from each named constant.
        //
        // Note: The first method links to the named constant to serve as a group marker
        #[allow(dead_code)]
        impl $Set { $crate::paste! { $(
            // for single-bit constants
            #[$crate::compile[all(none($($($end)?)+), xone($(some($start)),+))]]
            $crate::items! {
                #[doc = "Returns `true` if [`" $f "`][Self::" $f "] is present."]
                $vis const fn [<has_ $f:lower>](self) -> bool { self.contains(Self::$f) }
                #[doc = "Returns `true` if all bits in `" $f "` are present."]
                $vis const fn [<contains_ $f:lower>](self) -> bool { self.contains(Self::$f) }
            }
            // for grouped constants
            #[$crate::compile[any(some($($($end)?)+), not(xone($(some($start)),+)))]]
            $crate::items! {
                #[doc = "Returns `true` if the set contains all bits in [`" $f "`][Self::" $f "]."]
                $vis const fn [<contains_ $f:lower>](self) -> bool { self.contains(Self::$f) }
            }
            #[doc = "Returns `true` if the set shares any bit with `" $f "`."]
            $vis const fn [<intersects_ $f:lower>](self) -> bool { self.intersects(Self::$f) }

            #[doc = "Returns `self` with `" $f "` inserted."]
            $vis const fn [<with_ $f:lower>](self) -> Self { self.with(Self::$f) }
            #[doc = "Returns `self` with `" $f "` inserted if `condition` is true."]
            $vis const fn [<with_ $f:lower _if>](self, condition: bool) -> Self {
                self.with_if(condition, Self::$f) }
            #[doc = "Returns `self` with `" $f "` removed."]
            $vis const fn [<without_ $f:lower>](self) -> Self { self.without(Self::$f) }

            /* mutating */
            #[doc = "Sets `" $f "`."]
            $vis const fn [<set_ $f:lower>](&mut self) { self.insert(Self::$f); }
            #[doc = "Sets `" $f "` if `condition` is true."]
            $vis const fn [<set_ $f:lower _if>](&mut self, condition: bool) {
                if condition { self.insert(Self::$f); } }
            #[doc = "Unsets `" $f "`."]
            $vis const fn [<unset_ $f:lower>](&mut self) { self.remove(Self::$f); }
        )* }}

        /// Common set methods
        #[allow(clippy::double_must_use, dead_code)]
        impl $Set {
            /* per-set private metadata */
            /// The binary width needed to show all declared bits in `Debug`.
            pub(crate) const _SET_BIT_WIDTH: usize = {
                let bits = Self::all().bits;
                if bits == 0 { 1 } else { (<$T>::BITS - bits.leading_zeros()) as usize }
            };
            /// The bit width of the declared set domain.
            pub(crate) const _SET_BIT_SIZE: usize = {
                let bits = Self::all().bits;
                if bits == 0 { 0 } else { (<$T>::BITS - bits.leading_zeros()) as usize }
            };
            /// The octal digit width needed to show all declared bits.
            pub(crate) const _SET_OCTAL_WIDTH: usize = Self::_SET_BIT_WIDTH.div_ceil(3);
            /// The hexadecimal digit width needed to show all declared bits.
            pub(crate) const _SET_HEX_WIDTH: usize = Self::_SET_BIT_WIDTH.div_ceil(4);
            // _FIELD_COUNT, _SINGLE_COUNT, _GROUP_COUNT, _FIELD_NAMES

            /* public methods */

            /// Returns an empty set.
            #[must_use]
            $vis const fn new() -> Self { Self { bits: 0 } }
            /// Returns a set from raw bits.
            #[must_use]
            $vis const fn from_bits(bits: $T) -> Self { Self { bits } }

            /// Returns the raw backing bits.
            #[must_use]
            $vis const fn bits(self) -> $T { self.bits }
            /// Returns the union of all declared sets.
            #[must_use]
            $vis const fn all() -> Self { Self { bits: 0 $(| Self::$f.bits)* } }

            /// Returns `true` if no bits are set.
            #[must_use]
            $vis const fn is_empty(self) -> bool { self.bits == 0 }
            /// Returns `true` if all the declared bits are set.
            #[must_use]
            $vis const fn is_full(self) -> bool { self.bits == Self::all().bits }

            /// Returns `true` if all bits in `other` are also set in `self`.
            #[must_use]
            $vis const fn contains(self, other: Self) -> bool { self.is_superset(other) }
            /// An alias of `contains`.
            #[must_use]
            $vis const fn has(self, other: Self) -> bool { self.contains(other) }

            /// Returns `self` with `other` inserted.
            #[must_use]
            $vis const fn with(self, other: Self) -> Self {
                Self { bits: self.bits | other.bits }
            }
            /// Returns `self` with `other` inserted if `condition` is true.
            #[must_use]
            $vis const fn with_if(self, condition: bool, other: Self) -> Self {
                if condition { Self { bits: self.bits | other.bits } } else { self }
            }
            /// Returns `self` with `other` removed.
            #[must_use]
            $vis const fn without(self, other: Self) -> Self {
                Self { bits: self.bits & !other.bits }
            }
            /// Returns `self` with `other` toggled.
            #[must_use]
            $vis const fn toggled(self, other: Self) -> Self {
                Self { bits: self.bits ^ other.bits }
            }
        }

        /// Set operations
        #[allow(clippy::double_must_use, dead_code)]
        impl $Set {
            /// Returns `true` if `self` and `other` share any bit.
            $vis const fn intersects(self, other: Self) -> bool {
                (self.bits & other.bits) != 0
            }
            /// Returns `true` if all bits in `self` are also set in `other`.
            $vis const fn is_subset(self, other: Self) -> bool {
                (self.bits & other.bits) == self.bits
            }
            /// Returns `true` if all bits in `other` are also set in `self`.
            $vis const fn is_superset(self, other: Self) -> bool {
                (self.bits & other.bits) == other.bits
            }

            /// Returns the union of `self` and `other`.
            #[must_use]
            $vis const fn union(self, other: Self) -> Self {
                Self { bits: self.bits | other.bits }
            }
            /// Returns the intersection of `self` and `other`.
            #[must_use]
            $vis const fn intersection(self, other: Self) -> Self {
                Self { bits: self.bits & other.bits }
            }
            /// Returns the difference of `self` and `other`.
            #[must_use]
            $vis const fn difference(self, other: Self) -> Self {
                Self { bits: self.bits & !other.bits }
            }
            /// Returns the symmetric difference of `self` and `other`.
            #[must_use]
            $vis const fn symmetric_difference(self, other: Self) -> Self {
                Self { bits: self.bits ^ other.bits }
            }
        }

        /// Mutating set operations
        #[allow(dead_code)]
        impl $Set {
            /// Clears the set.
            $vis const fn clear(&mut self) { self.bits = 0; }
            /// Inserts all bits from `other`.
            $vis const fn insert(&mut self, other: Self) { self.bits |= other.bits; }
            /// Removes all bits from `other`.
            $vis const fn remove(&mut self, other: Self) { self.bits &= !other.bits; }
            /// Toggles all bits from `other`.
            $vis const fn toggle(&mut self, other: Self) { self.bits ^= other.bits; }
        }

        /* impl utility traits */

        $( #[$crate::compile[nota(PartialEq $(, $no_trait)*)]] )?
        impl ::core::cmp::PartialEq for $Set {
            fn eq(&self, other: &Self) -> bool { self.bits == other.bits }
        }
        $( #[$crate::compile[all(nota(Eq $(, $no_trait)*), nota(PartialEq $(, $no_trait)*))]] )?
        impl ::core::cmp::Eq for $Set {}

        $( #[$crate::compile[nota(PartialOrd $(, $no_trait)*)]] )?
        #[allow(clippy::non_canonical_partial_ord_impl, reason = "would always need Ord")]
        impl ::core::cmp::PartialOrd for $Set {
            fn partial_cmp(&self, other: &Self) -> Option<::core::cmp::Ordering> {
                self.bits.partial_cmp(&other.bits) // Some(self.cmp(other))
            }
        }
        $( #[$crate::compile[all(
            nota(Ord $(, $no_trait)*),
            nota(PartialOrd $(, $no_trait)*),
            nota(Eq $(, $no_trait)*),
            nota(PartialEq $(, $no_trait)*)
        )]] )?
        impl ::core::cmp::Ord for $Set {
            fn cmp(&self, other: &Self) -> ::core::cmp::Ordering {
                self.bits.cmp(&other.bits)
            }
        }
        $( #[$crate::compile[nota(Hash $(, $no_trait)*)]] )?
        impl ::core::hash::Hash for $Set {
            fn hash<H: ::core::hash::Hasher>(&self, state: &mut H) {
                self.bits.hash(state)
            }
        }

        impl $crate::BitSized<{ $Set::_SET_BIT_SIZE }> for $Set {}
        impl $crate::ConstInit for $Set { const INIT: Self = Self::new(); }
        $( #[$crate::compile[nota(Default $(, $no_trait)*)]] )?
        impl Default for $Set { fn default() -> Self { Self::new() } }

        /* impl formatting traits */

        $crate::impl_trait! { fmt::Debug for
            $( #[$crate::compile[nota(Debug $(, $no_trait)*)]] )?
            /// Formats the set as a prefixed binary mask over its declared bit domain.
            $Set |self, f| write!(f, concat!(stringify!($Set),
                "(0b{:0w$b})"), self.bits, w = Self::_SET_BIT_WIDTH) }
        $crate::impl_trait! { fmt::Display for
            $( #[$crate::compile[nota(Display $(, $no_trait)*)]] )?
            /// Formats the set as a prefixed binary mask over its declared bit domain.
            $Set |self, f| write!(f, "0b{:0w$b}", self.bits, w = Self::_SET_BIT_WIDTH)
        }
        $crate::impl_trait! { fmt::Binary for
            $( #[$crate::compile[nota(Binary $(, $no_trait)*)]] )?
            /// Formats the set as a binary mask over its declared bit domain.
            $Set |self, f|
                if f.alternate() { write!(f, "0b{:0w$b}", self.bits, w = Self::_SET_BIT_WIDTH) }
                else { write!(f, "{:0w$b}", self.bits, w = Self::_SET_BIT_WIDTH) }
        }
        $crate::impl_trait! { fmt::Octal for
            $( #[$crate::compile[nota(Octal $(, $no_trait)*)]] )?
            /// Formats the set as an octal mask over its declared bit domain.
            $Set |self, f|
                if f.alternate() { write!(f, "0o{:0w$o}", self.bits, w = Self::_SET_OCTAL_WIDTH) }
                else { write!(f, "{:0w$o}", self.bits, w = Self::_SET_OCTAL_WIDTH) }
        }
        $crate::impl_trait! { fmt::LowerHex for
            $( #[$crate::compile[nota(LowerHex $(, $no_trait)*)]] )?
            /// Formats the set as a hexadecimal mask over its declared bit domain.
            $Set |self, f|
                if f.alternate() { write!(f, "0x{:0w$x}", self.bits, w = Self::_SET_HEX_WIDTH) }
                else { write!(f, "{:0w$x}", self.bits, w = Self::_SET_HEX_WIDTH) }
        }
        $crate::impl_trait! { fmt::UpperHex for
            $( #[$crate::compile[nota(UpperHex $(, $no_trait)*)]] )?
            /// Formats the set as a hexadecimal mask over its declared bit domain.
            $Set |self, f|
                if f.alternate() { write!(f, "0x{:0w$X}", self.bits, w = Self::_SET_HEX_WIDTH) }
                else { write!(f, "{:0w$X}", self.bits, w = Self::_SET_HEX_WIDTH) }
        }

        $( #[$crate::compile[nota(DebugExt $(, $no_trait)*)]] )?
        impl $crate::DebugExt for $Set where $Set: $crate::Debug {
            type Ctx = $crate::ReprMode;
            fn fmt_with(&self, f: &mut $crate::Formatter<'_>, ctx: &Self::Ctx)
                -> $crate::FmtResult<()> {
                match ctx {
                    $crate::ReprMode::Raw => $crate::Debug::fmt(self, f),
                    $crate::ReprMode::Named => { self._fmt_named(f) }
                    $crate::ReprMode::RawNamed => {
                        write!(f, concat!(stringify!($Set), "("))?;
                        write!(f, "0b{:0width$b}", self.bits, width = Self::_SET_BIT_WIDTH)?;
                        write!(f, "; ")?;
                        self._fmt_named_inner(f)?;
                        write!(f, ")")
                    }
                }
            }
        }
        impl $Set {
            fn _fmt_named(&self, f: &mut $crate::Formatter<'_>) -> $crate::FmtResult<()> {
                write!(f, concat!(stringify!($Set), "("))?;
                self._fmt_named_inner(f)?;
                write!(f, ")")
            }
            fn _fmt_named_inner(&self, f: &mut $crate::Formatter<'_>) -> $crate::FmtResult<()> {
                let mut first = true;
                $crate::paste! { $(
                    // for now, only show single-bit fields
                    if $crate::cif![all(none($($($end)?)+), xone($(some($start)),+))]
                        && self.contains(Self::$f)
                    {
                        if !first { write!(f, " | ")?; }
                        write!(f, stringify!($f))?;
                        first = false;
                    }
                )* }
                if first { write!(f, "empty")?; }
                Ok(())
            }
        }

        /* operator implementations */

        impl ::core::ops::BitOr for $Set {
            type Output = Self;
            fn bitor(self, rhs: Self) -> Self::Output { self.union(rhs) }
        }
        impl ::core::ops::BitOrAssign for $Set {
            fn bitor_assign(&mut self, rhs: Self) { self.insert(rhs); }
        }
        impl ::core::ops::BitAnd for $Set {
            type Output = Self;
            fn bitand(self, rhs: Self) -> Self::Output { self.intersection(rhs) }
        }
        impl ::core::ops::BitAndAssign for $Set {
            fn bitand_assign(&mut self, rhs: Self) { *self = self.intersection(rhs); }
        }
        impl ::core::ops::Sub for $Set {
            type Output = Self;
            fn sub(self, rhs: Self) -> Self::Output { self.difference(rhs) }
        }
        impl ::core::ops::SubAssign for $Set {
            fn sub_assign(&mut self, rhs: Self) { self.remove(rhs); }
        }
        impl ::core::ops::BitXor for $Set {
            type Output = Self;
            fn bitxor(self, rhs: Self) -> Self::Output { self.symmetric_difference(rhs) }
        }
        impl ::core::ops::BitXorAssign for $Set {
            fn bitxor_assign(&mut self, rhs: Self) { self.toggle(rhs); }
        }
        impl ::core::ops::Not for $Set {
            type Output = Self;
            fn not(self) -> Self::Output { Self::all().difference(self) }
        }
    };
    // reduces a comma-list of bits/ranges into one backing integer mask.
    (%mask $T:ty; $($start:tt $(..= $end:tt)?),+ $(,)?) => {{
        0 as $T $(| $crate::set!(%item $T; $start $(..= $end)?))+
    }};
    // single bit.
    (%item $T:ty; $bit:tt) => {
        $crate::Bitwise::<$T>::mask_range(($bit) as u32, ($bit) as u32).0
    };
    // inclusive bit range.
    (%item $T:ty; $start:tt ..= $end:tt) => {
        $crate::Bitwise::<$T>::mask_range(($start) as u32, ($end) as u32).0
    };
    // only allow implementions over unsigned integers
    (%guard_allowed_type $Set:ident, $T:ty) => { $crate::paste! {
        const [<__GUARD_ALLOWED_TYPE_ $Set:upper>]: () = {
            const fn __allowed_types<P: $crate::PrimUint>() {}
            __allowed_types::<$T>();
        };
    }};
    ($($tt:tt)*) => { compile_error! { concat![
        "set!: wrong syntax.\n\n",
        "Expected:\n",
        "    set! { $vis struct Name($ty) { CONST = bits; ... } }\n\n",
        "Examples of constant syntax:\n",
        "    SPACE = b' ';\n",
        "    HWS   = b' ', b'\\t';\n",
        "    DIGIT = b'0'..=b'9';\n",
        "    ALNUM = b'0'..=b'9', b'A'..=b'Z', b'a'..=b'z';",
        // "Input:\n",
        // "    ",
        // stringify!($($tt)*)
    ]}};
}
#[doc(inline)]
pub use set· as set;