fray 0.1.2

A type-safe and ergonomic Rust library for working with bitfields.
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
use crate::{BitContainer, BitContainerFor};

mod fields;
pub use fields::{Field, FieldType};
pub mod bitorder;
use bitorder::BitOrder;
mod private;

/// Provides all the convenience methods for interacting with a **bitfield structure**.
///
/// This trait is:
/// - **sealed** (cannot be implemented manually),
/// - intended to be obtained via the `bitfield` macro,
/// - the main API end-users will work with.
///
/// # Core methods
///
/// - [`new`](Self::new):
///   Construct a new instance with an empty [`BitContainer`].
///
/// - [`into_inner`](Self::into_inner):
///   Consume `self` and return the underlying raw **inner value**
///   ([`BitFieldImpl::Container::Inner`](BitContainer::Inner)).
///
/// - [`get`](Self::get) / [`try_get`](Self::try_get):
///   Read the value of a field.
///
/// - [`set`](Self::set) / [`try_set`](Self::try_set):
///   Write the value of a field.
///
/// - [`with`](Self::with) / [`try_with`](Self::try_with):
///   Write the value of a field and return `&mut Self` for chaining.
///
/// # How it works
///
/// Internally, the macro implements [`BitFieldImpl`] for your type, and
/// [`BitField`] is automatically implemented via a generic blanket impl
/// over all types that implement [`BitFieldImpl`].
pub trait BitField: private::Sealed + BitFieldImpl {
    ///   Consume `self` and return the underlying raw **inner value**
    ///   ([`BitField::Container::Inner`](BitContainer::Inner)).
    #[inline]
    fn into_inner(self) -> <Self::Container as BitContainer>::Inner {
        self.into().into_inner()
    }

    /// Construct a new instance with an empty [`BitContainer`].
    #[inline]
    fn new() -> Self {
        Self::Container::empty().into()
    }

    #[doc(hidden)]
    #[inline]
    fn _set<F>(&mut self, value: F::BitsType, _: private::Token)
    where
        F: Field<Self>,
        Self::Container: BitContainerFor<F::BitsType>,
    {
        debug_assert!(F::OFFSET + F::SIZE <= Self::Container::SIZE);
        self.as_mut().store(value, F::OFFSET, F::SIZE);
    }

    #[doc(hidden)]
    #[inline]
    fn _get<F>(&self, _: private::Token) -> F::BitsType
    where
        F: Field<Self>,
        Self::Container: BitContainerFor<F::BitsType>,
    {
        debug_assert!(F::OFFSET + F::SIZE <= Self::Container::SIZE);
        self.as_ref().retrieve(F::OFFSET, F::SIZE)
    }

    /// Read the value of field `F`. Returns `F::Type` directly.
    ///
    /// Requires an infallible conversion from `F::BitsType` to `F::Type`.
    #[inline]
    fn get<F>(&self) -> F::Type
    where
        F: Field<Self>,
        Self::Container: BitContainerFor<F::BitsType>,
        F::BitsType: Into<F::Type>,
    {
        self._get::<F>(private::Token).into()
    }

    /// Read the value of field `F`.
    ///
    /// Returns a `Result` containing:
    /// - `F::Type` if the conversion succeeds,
    /// - an error (`TryInto<F::Type>::Error`) if it fails.
    #[inline]
    fn try_get<F>(&self) -> Result<F::Type, <F::BitsType as TryInto<F::Type>>::Error>
    where
        F: Field<Self>,
        Self::Container: BitContainerFor<F::BitsType>,
        F::BitsType: TryInto<F::Type>,
    {
        self._get::<F>(private::Token).try_into()
    }

    /// Write the value of field `F`.
    ///
    /// Requires an infallible conversion from `F::Type` to `F::BitsType`.
    #[inline]
    fn set<F>(&mut self, value: F::Type)
    where
        F: Field<Self>,
        Self::Container: BitContainerFor<F::BitsType>,
        F::Type: Into<F::BitsType>,
    {
        self._set::<F>(value.into(), private::Token);
    }

    /// Write the value of field `F`.
    ///
    /// Returns a `Result` containing:
    /// - `()` if the conversion succeeds,
    /// - an error (`TryInto<F::BitsType>::Error`) if it fails.
    #[inline]
    fn try_set<F>(&mut self, value: F::Type) -> Result<(), <F::Type as TryInto<F::BitsType>>::Error>
    where
        F: Field<Self>,
        Self::Container: BitContainerFor<F::BitsType>,
        F::Type: TryInto<F::BitsType>,
    {
        self._set::<F>(value.try_into()?, private::Token);
        Ok(())
    }

    /// Write the value of field `F` and return `&mut Self` for chaining.
    ///
    /// Requires an infallible conversion from `F::Type` to `F::BitsType`.
    #[inline]
    fn with<F>(&mut self, value: F::Type) -> &mut Self
    where
        F: Field<Self>,
        Self::Container: BitContainerFor<F::BitsType>,
        F::Type: Into<F::BitsType>,
    {
        self.set::<F>(value);
        self
    }

    /// Write the value of field `F`.
    ///
    /// Returns a `Result` containing:
    /// - `&mut Self` if the conversion succeeds allowing chaning,
    /// - an error (`TryInto<F::BitsType>::Error`) if it fails.
    #[inline]
    fn try_with<F>(
        &mut self,
        value: F::Type,
    ) -> Result<&mut Self, <F::Type as TryInto<F::BitsType>>::Error>
    where
        F: Field<Self>,
        Self::Container: BitContainerFor<F::BitsType>,
        F::Type: TryInto<F::BitsType>,
    {
        self.try_set::<F>(value)?;
        Ok(self)
    }
}

impl<T: BitFieldImpl + private::Sealed> BitField for T {}

/// Internal trait required by [`BitField`].
///
/// `BitFieldImpl` is **not meant to be implemented manually**.
/// It is automatically implemented by the `bitfield` macro.
///
/// # Usage
///
/// End-users generally do **not** interact with `BitFieldImpl` directly.
/// Instead, they use the convenience methods provided by [`BitField`].
pub trait BitFieldImpl
where
    Self::Container: Into<Self>,
    Self: Into<Self::Container>,
    Self: AsRef<Self::Container>,
    Self: AsMut<Self::Container>,
{
    /// The underlying storage type for the bitfield.
    ///
    /// This type defines where the raw bits are stored.
    /// It must implement [`BitContainer`].
    type Container: BitContainer;

    /// Indicates the bit numbering order used by the bitfield.
    ///
    /// This associated type has no functional impact; it exists purely for
    /// **semantic clarity**.
    ///
    /// Set automatically by the [`bitorder`](crate::bitfield) attribute
    /// (`LSB0` by default).
    type BitOrder: BitOrder;
}

impl<T: BitFieldImpl> private::Sealed for T {}

#[cfg(test)]
mod tests {
    use crate::iterable::BitIterableContainer;

    use super::*;

    #[allow(dead_code)]
    #[allow(clippy::upper_case_acronyms)]
    #[allow(missing_debug_implementations)]
    mod dns_flags {
        use core::fmt::Debug;

        use super::*;
        use crate::{bitorder::LSB0, iterable::BitIterableContainer};

        // https://datatracker.ietf.org/doc/html/rfc1035#section-4.1.1
        // #[bitfield(repr(u16), bitorder(msb0))]
        // pub struct DNSFlags {
        //     QR: bool,
        //     OPCODE: OpCode,
        //     AA: bool,
        //     TC: bool,
        //     RD: bool,
        //     RA: bool,
        //     #[bits(3)]
        //     _z: (),
        //     RCODE: Rcode,
        // }
        pub mod fields {
            macro_rules! create_field {
                ($name:ident, $bf:ty, $t: ty, $bit_t:ty, $offset:expr) => {
                    pub enum $name {}

                    impl crate::Field<$bf> for $name {
                        type Type = $t;
                        type BitsType = $bit_t;
                        const OFFSET: usize = $offset;
                    }
                };
            }
            create_field!(QR, super::DNSFlags, bool, bool, 0);
            create_field!(OPCODE, super::DNSFlags, super::OpCode, u8, 1);
            create_field!(AA, super::DNSFlags, bool, bool, 5);
            create_field!(TC, super::DNSFlags, bool, bool, 6);
            create_field!(RD, super::DNSFlags, bool, bool, 7);
            create_field!(RA, super::DNSFlags, bool, bool, 8);
            // offset = 8 + 1 (RA size) + 3 (zeroes)
            create_field!(RCODE, super::DNSFlags, super::Rcode, u8, 12);
        }

        #[repr(u8)]
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        pub enum OpCode {
            Query = 0,
            IQuery = 1,
            Status = 2,
        }
        impl FieldType for OpCode {
            const SIZE: usize = 4;

            type BitsType = u8;
        }
        impl TryFrom<u8> for OpCode {
            type Error = ();

            fn try_from(value: u8) -> Result<Self, Self::Error> {
                Ok(match value {
                    0 => Self::Query,
                    1 => Self::IQuery,
                    2 => Self::Status,
                    _ => return Err(()),
                })
            }
        }

        impl From<OpCode> for u8 {
            fn from(value: OpCode) -> Self {
                value as u8
            }
        }

        #[repr(u8)]
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        pub enum Rcode {
            NoError = 0,
            FormatError = 1,
            ServerFailure = 2,
            NameError = 3,
            NotImplemented = 4,
            Refused = 5,
        }
        impl FieldType for Rcode {
            const SIZE: usize = 4;

            type BitsType = u8;
        }

        impl TryFrom<u8> for Rcode {
            type Error = ();

            fn try_from(value: u8) -> Result<Self, Self::Error> {
                Ok(match value {
                    0 => Self::NoError,
                    1 => Self::FormatError,
                    2 => Self::ServerFailure,
                    3 => Self::NameError,
                    4 => Self::NotImplemented,
                    5 => Self::Refused,
                    _ => return Err(()),
                })
            }
        }

        #[derive(Clone, Copy)]
        pub struct DNSFlags(BitIterableContainer<u16>);

        impl From<DNSFlags> for <<DNSFlags as BitFieldImpl>::Container as BitContainer>::Inner {
            fn from(value: DNSFlags) -> Self {
                value.into_inner()
            }
        }

        impl From<BitIterableContainer<u16>> for DNSFlags {
            fn from(value: BitIterableContainer<u16>) -> Self {
                Self(value)
            }
        }

        impl From<DNSFlags> for BitIterableContainer<u16> {
            fn from(value: DNSFlags) -> Self {
                value.0
            }
        }

        impl AsRef<BitIterableContainer<u16>> for DNSFlags {
            fn as_ref(&self) -> &BitIterableContainer<u16> {
                &self.0
            }
        }

        impl AsMut<BitIterableContainer<u16>> for DNSFlags {
            fn as_mut(&mut self) -> &mut BitIterableContainer<u16> {
                &mut self.0
            }
        }

        impl BitFieldImpl for DNSFlags {
            type Container = BitIterableContainer<u16>;
            type BitOrder = LSB0;
        }

        impl Debug for DNSFlags {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                use crate::debug::PrettyResult;
                f.debug_struct("DNSFlags")
                    .field("QR", &PrettyResult::from(&self.try_get::<QR>()))
                    .field("OPCODE", &PrettyResult::from(&self.try_get::<OPCODE>()))
                    .field("AA", &PrettyResult::from(&self.try_get::<AA>()))
                    .field("TC", &PrettyResult::from(&self.try_get::<TC>()))
                    .field("RD", &PrettyResult::from(&self.try_get::<RD>()))
                    .field("RA", &PrettyResult::from(&self.try_get::<RA>()))
                    .field("RCODE", &PrettyResult::from(&self.try_get::<RCODE>()))
                    .finish()
            }
        }
    }
    use dns_flags::{DNSFlags, OpCode, fields::*};

    #[test]
    fn set_bool_basic() {
        let mut dns_flags = DNSFlags::new();

        dns_flags.set::<QR>(true);
        assert_eq!(dns_flags.into_inner(), 0b1u16);

        dns_flags.set::<QR>(true);
        assert_eq!(dns_flags.into_inner(), 0b1u16);

        dns_flags.set::<QR>(false);
        assert_eq!(dns_flags.into_inner(), 0b0u16);

        dns_flags.set::<QR>(false);
        assert_eq!(dns_flags.into_inner(), 0b0u16);

        dns_flags.set::<RA>(true);
        assert_eq!(dns_flags.into_inner(), 0b1_0000_0000u16);

        dns_flags.set::<RA>(true);
        assert_eq!(dns_flags.into_inner(), 0b1_0000_0000u16);

        dns_flags.set::<RA>(false);
        assert_eq!(dns_flags.into_inner(), 0b0u16);

        dns_flags.set::<RA>(false);
        assert_eq!(dns_flags.into_inner(), 0b0u16);
    }

    #[test]
    fn set_bool_dont_overlap() {
        let mut dns_flags = DNSFlags::new();
        dns_flags.set::<TC>(true);
        dns_flags.set::<RD>(true);
        dns_flags.set::<RA>(true);
        assert_eq!(dns_flags.into_inner(), 0b1_1100_0000u16);

        dns_flags.set::<RD>(false);
        assert_eq!(dns_flags.into_inner(), 0b1_0100_0000u16);

        dns_flags.set::<RD>(true);
        assert_eq!(dns_flags.into_inner(), 0b1_1100_0000u16);
    }

    #[test]
    fn get_bool() {
        let dns_flags = DNSFlags::from(BitIterableContainer::from(0b1u16));
        assert!(dns_flags.get::<QR>());

        let dns_flags = DNSFlags::new();
        assert!(!dns_flags.get::<RA>());
        assert!(!dns_flags.get::<QR>());

        let dns_flags = DNSFlags::from(BitIterableContainer::from(0b1_0000_0000u16));
        assert!(dns_flags.get::<RA>());
    }

    #[test]
    fn set_custom_type() {
        let mut dns_flags = DNSFlags::new();

        dns_flags.set::<OPCODE>(OpCode::IQuery);
        assert_eq!(dns_flags.into_inner(), 0b10u16);

        dns_flags.set::<OPCODE>(OpCode::Status);
        assert_eq!(dns_flags.into_inner(), 0b100u16);

        dns_flags.set::<OPCODE>(OpCode::Query);
        assert_eq!(dns_flags.into_inner(), 0b0u16);
    }

    #[test]
    fn get_custom_type() {
        let dns_flags = DNSFlags::from(BitIterableContainer::from(0b10u16));
        assert_eq!(dns_flags.try_get::<OPCODE>(), Ok(OpCode::IQuery));

        let dns_flags = DNSFlags::from(BitIterableContainer::from(0b100u16));
        assert_eq!(dns_flags.try_get::<OPCODE>(), Ok(OpCode::Status));

        let dns_flags = DNSFlags::new();
        assert_eq!(dns_flags.try_get::<OPCODE>(), Ok(OpCode::Query));
    }
}