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
//! This module contains useful structures that can be used as meaning of bitflag
//!
//!

use core::fmt;

/// Simple structure for basic and alternate string view
/// 
/// This struct may be used in most cases of crate using. 
/// We can rewrite [6502 status register example](super#example-status-register-of-mos-technology-6502)
/// using this struct
/// ```
/// # use std::{array, fmt, slice, ops::Deref};
/// # use bitfield_layout::{Layout, BitFieldLayout, DualView};
/// 
/// struct StatusRegister(u8);
/// impl StatusRegister {
///     const LAYOUT: [DualView<'static>; 8] = [
///         DualView(
///             "Carry flag",
///             "Enables numbers larger than a single word to be added/subtracted by
///             carrying a binary digit from a less significant word to the least
///             significant bit of a more significant word as needed."
///         ),
///         DualView(
///             "Zero flag",
///             "Indicates that the result of an arithmetic or logical operation
///             (or, sometimes, a load) was zero."
///         ),
///         DualView(
///             "Interrupt flag",
///             "Indicates whether interrupts are enabled or masked."
///         ),
///         DualView(
///             "Decimal flag",
///             "Indicates that a bit carry was produced between the nibbles as a
///             result of the last arithmetic operation."
///         ),
///         DualView(
///             "Break flag",
///             "It can be examined as a value stored on the stack."
///         ),
///         DualView("Unused", "Unused"),
///         DualView(
///             "Overflow flag",
///             "Indicates that the signed result of an operation is too large to
///             fit in the register width using two's complement representation."
///         ),
///         DualView(
///             "Negative flag",
///             "Indicates that the result of a mathematical operation is negative."
///         ),
///     ];
/// }
/// impl Layout for StatusRegister {
///     type Layout = slice::Iter<'static, DualView<'static>>;
///     fn layout() -> Self::Layout { StatusRegister::LAYOUT.iter() }
/// }
/// impl BitFieldLayout for StatusRegister {
///     type Value = u8;
///     fn get(&self) -> Self::Value { self.0 }
///     fn set(&mut self, new: Self::Value) { self.0 = new; }
/// }
/// ```
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)]
pub struct DualView<'a>(pub &'a str, pub &'a str);
impl<'a> fmt::Display for DualView<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = if f.alternate() { self.1 } else { self.0 };
        write!(f, "{}", s)
    }
}

/// Complex enumeration for several types of bit (flag)
///
/// This enum variants may be used to show difference beetween meaningful and reserved flags.
/// ```
/// # use core::{slice,array};
/// # use pretty_assertions::assert_eq;
/// # use bitfield_layout::{Layout, BitFieldLayout, FlagType, layout};
///
/// // Bitfield type definition
/// struct Light(u8);
/// impl Light {
///     const LAYOUT: [FlagType<'static>; 8] = [
///         FlagType::Significant("Red", "Red is the color at the long wavelength end"),
///         FlagType::Significant("Blue", "Blue is one of the three primary colours of pigments"),
///         FlagType::Significant("Green", "Green is the color between blue and yellow"),
///         FlagType::Reserved("Invisible"),
///         FlagType::ShouldBe0,
///         FlagType::ShouldBe1,
///         FlagType::Unknown,
///         FlagType::Undefined,
///     ];
/// }
/// // Implementation
/// impl Layout for Light {
///     type Layout = slice::Iter<'static, FlagType<'static>>;
///     fn layout() -> Self::Layout { Light::LAYOUT.iter() }
/// }
/// impl BitFieldLayout for Light {
///     type Value = u8;
///     fn get(&self) -> Self::Value { self.0 }
///     fn set(&mut self, new: Self::Value) { self.0 = new; }
/// }
///
/// // Value assignment
/// let white = Light(0b00100111);
///
/// let result = white.flags()
///     .enumerate()
///     .find(|(n, f)| n == &5 && f.is_set == true)
///     .map(|(_, f)| *f.value);
/// let sample = Some(FlagType::ShouldBe1);
///
/// assert_eq!(sample, result);
/// ```
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)]
pub enum FlagType<'a> {
    /// Has two strings - one for meaning, other for long description
    Significant(&'a str, &'a str),
    /// Reserved bit (flag) may has different types of reservation. Ex: OEM and Future using 
    Reserved(&'a str),
    /// Should always be set
    ShouldBe0,
    /// Should always be unset
    ShouldBe1,
    /// Unknown for current specification
    Unknown,
    /// Undefined in current specification
    Undefined,
}
impl<'a> fmt::Display for FlagType<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match (self, f.alternate()) {
            (Self::Significant(s, _), false) => write!(f, "{}", s),
            (Self::Significant(_, s), true) => write!(f, "{}", s),
            (Self::Reserved(s), _) => write!(f, "{}", s),
            (Self::ShouldBe0, _) => write!(f, "Should be 0"),
            (Self::ShouldBe1, _) => write!(f, "Should be 1"),
            (Self::Unknown, _) => write!(f, "Unknown"),
            (Self::Undefined, _) => write!(f, "Undefined"),
        }
    }
}




/// Fast defining of useful types
///
/// This macro helps to implement [crate::BitFieldLayout] trait and create associated const layout.
/// Macro may be used for following data types:
/// - [DualView](#dualview)
/// - [FlagType](#flagtype)
///
/// ## DualView
/// 
/// ```
/// # use core::{slice,array};
/// # use bitfield_layout::{Layout, BitFieldLayout, DualView, layout};
/// # fn main() {
///
/// // Data created by macro
/// let macro_data = {
///     layout!(
///         DualView;
///         struct Letters(u8);
///         "a",
///         "b" "B",
///         "c",
///         "d",
///         "e",
///         "f" "F",
///         "g" "G",
///         "h" "H",
///     );
///
///     Letters(42).flags()
/// };
/// // Expands to:
/// let manual_data = {
///     struct Letters(u8);
///     impl Letters {
///         const LAYOUT: [DualView<'static>; 8] = [
///             DualView("a", "a"),
///             DualView("b", "B"),
///             DualView("c", "c"),
///             DualView("d", "d"),
///             DualView("e", "e"),
///             DualView("f", "F"),
///             DualView("g", "G"),
///             DualView("h", "H"),
///         ];
///     }
///     
///     impl Layout for Letters {
///         type Layout = slice::Iter<'static, DualView<'static>>;
///         fn layout() -> Self::Layout { Letters::LAYOUT.iter() }
///     }
///     impl BitFieldLayout for Letters {
///         type Value = u8;
///         fn get(&self) -> Self::Value { self.0 }
///         fn set(&mut self, new: Self::Value) { self.0 = new; }
///     }
///
///     Letters(42).flags()
/// };
///
/// assert_eq!(macro_data.collect::<Vec<_>>(), manual_data.collect::<Vec<_>>());
/// # }
/// ```
///
/// ## FlagType
/// ```
/// # use core::{slice,array};
/// # use pretty_assertions::assert_eq;
/// # use bitfield_layout::{Layout, BitFieldLayout, FlagType, layout};
/// # fn main() {
/// let macro_data = {
///     layout!(
///         FlagType;
///         struct EightFlags(u8);
///         "Significant: meaning",
///         "Significant: meaning" "Significant: description",
///         "Reserved: 2 bits": 2,
///         "Reserved: shouldn't exists": 0,
///         ShouldBe0,
///         ShouldBe1,
///         Unknown,
///         Undefined,
///     );
///
///     EightFlags(73).flags()
/// };
/// // Expands to:
/// let manual_data = {
///     struct EightFlags(u8);
///     impl EightFlags {
///         const LAYOUT: [FlagType<'static>; 8] = [
///             FlagType::Significant("Significant: meaning", "Significant: meaning"),
///             FlagType::Significant("Significant: meaning", "Significant: description"),
///             FlagType::Reserved("Reserved: 2 bits"),
///             FlagType::Reserved("Reserved: 2 bits"),
///             FlagType::ShouldBe0,
///             FlagType::ShouldBe1,
///             FlagType::Unknown,
///             FlagType::Undefined,
///         ];
///     }
///     
///     impl Layout for EightFlags {
///         type Layout = slice::Iter<'static, FlagType<'static>>;
///         fn layout() -> Self::Layout { EightFlags::LAYOUT.iter() }
///     }
///     impl BitFieldLayout for EightFlags {
///         type Value = u8;
///         fn get(&self) -> Self::Value { self.0 }
///         fn set(&mut self, new: Self::Value) { self.0 = new; }
///     }
///
///     EightFlags(73).flags()
/// };
///
/// assert_eq!(macro_data.collect::<Vec<_>>(), manual_data.collect::<Vec<_>>());
/// # }
/// ```
#[macro_export]
macro_rules! layout  {
    // DualView
    (item = DualView; [] -> [$($output:tt)*]) => {
        [$($output)*]
    };
    (item = DualView; [$m:literal $d:literal, $($input:tt)*] -> [$($output:tt)*]) => {
        layout!(item = DualView; [$($input)*] -> [$($output)* DualView($m, $d),])
    };
    (item = DualView; [$m:literal, $($input:tt)*] -> [$($output:tt)*]) => {{
        layout!(item = DualView; [$($input)*] -> [$($output)* DualView($m, $m),])
    }};
    (DualView; $(#[$meta:meta])* $vis:vis $ident:ident $name:ident($value:tt); $($input:tt)*) => {
        $(#[$meta])*
        $vis $ident $name($value);
        impl $name {
            const LAYOUT: &'static [DualView<'static>] =
                &layout!(item = DualView; [$($input)*] -> []);
        }
        impl Layout for $name {
            type Layout = slice::Iter<'static, DualView<'static>>;
            fn layout() -> Self::Layout { $name::LAYOUT.iter() }
        }
        impl BitFieldLayout for $name {
            type Value = $value;
            fn get(&self) -> Self::Value { self.0 }
            fn set(&mut self, new: Self::Value) { self.0 = new; }
        }
    };

    // FlagType
    (item = FlagType; array = $a:expr; index = $i:expr;) => {{ $a }};
    (item = FlagType; array = $a:expr; index = $i:expr; Undefined, $($input:tt)*) => {{
        let mut result = layout!(item = FlagType; array = $a; index = $i + 1; $($input)*);
        result[$i] = FlagType::Undefined;
        result
    }};
    (item = FlagType; array = $a:expr; index = $i:expr; Unknown, $($input:tt)*) => {{
        let mut result = layout!(item = FlagType; array = $a; index = $i + 1; $($input)*);
        result[$i] = FlagType::Unknown;
        result
    }};
    (item = FlagType; array = $a:expr; index = $i:expr; ShouldBe1, $($input:tt)*) => {{
        let mut result = layout!(item = FlagType; array = $a; index = $i + 1; $($input)*);
        result[$i] = FlagType::ShouldBe1;
        result
    }};
    (item = FlagType; array = $a:expr; index = $i:expr; ShouldBe0, $($input:tt)*) => {{
        let mut result = layout!(item = FlagType; array = $a; index = $i + 1; $($input)*);
        result[$i] = FlagType::ShouldBe0;
        result
    }};
    (item = FlagType; array = $a:expr; index = $i:expr; $m:literal: $n:expr, $($input:tt)*) => {{
        let mut result = layout!(item = FlagType; array = $a; index = $i + $n; $($input)*);
        let mut i = $i;
        while i < $i + $n {
            result[i] = FlagType::Reserved($m);
            i += 1;
        }
        result
    }};
    (item = FlagType; array = $a:expr; index = $i:expr; $m:literal $d:literal, $($input:tt)*) => {{
        let mut result = layout!(item = FlagType; array = $a; index = $i + 1; $($input)*);
        result[$i] = FlagType::Significant($m, $d);
        result
    }};
    (item = FlagType; array = $a:expr; index = $i:expr; $m:literal, $($input:tt)*) => {{
        let mut result = layout!(item = FlagType; array = $a; index = $i + 1; $($input)*);
        result[$i] = FlagType::Significant($m, $m);
        result
    }};
    (FlagType; $(#[$meta:meta])* $vis:vis $ident:ident $name:ident($value:tt); $($input:tt)*) => {
        $(#[$meta])*
        $vis $ident $name($value);
        impl $name {
            const LAYOUT: [FlagType<'static>; { layout!(@count_bytes $value) * 8 }] =
                layout!(
                    item = FlagType;
                    array = [FlagType::Unknown; { layout!(@count_bytes $value) * 8 }];
                    index = 0;
                    $($input)*
                );
        }
        impl Layout for $name {
            type Layout = core::slice::Iter<'static, FlagType<'static>>;
            fn layout() -> Self::Layout { $name::LAYOUT.iter() }
        }
        impl BitFieldLayout for $name {
            type Value = $value;
            fn get(&self) -> Self::Value { self.0 }
            fn set(&mut self, new: Self::Value) { self.0 = new; }
        }
    };

    // Utils
    (@as_expr $expr:expr) => { $expr };
    (@as_ty $ty:ty) => { $ty };
    (@count_bytes u8) => { 1 };
    (@count_bytes u16) => { 2 };
    (@count_bytes u32) => { 4 };
    (@count_bytes u64) => { 8 };
    (@count_bytes u128) => { 16 };
    (@count_bytes [u8; $n:expr]) => { $n };
}



#[cfg(test)]
mod tests {
    use std::prelude::v1::*;
    use std::{slice,};

    use pretty_assertions::assert_eq;
    use crate::*;


    #[test]
    fn dual_view() {
        let result = DualView("a", "A");
        assert_eq!("a", format!("{}", result));
        assert_eq!("A", format!("{:#}", result));
    }

    #[test]
    fn flag_type() {
        let significant = FlagType::Significant("s", "S");
        let reserved = FlagType::Reserved("r");
        assert_eq!("s", format!("{}", significant));
        assert_eq!("S", format!("{:#}", significant));
        assert_eq!("r", format!("{:#}", reserved));
    }

    #[test]
    fn layout_macro_dual_view() {
        layout!(
            DualView;
            struct Letters(u8);
            "a",
            "b" "B",
            "c",
            "d",
            "e",
            "f" "F",
            "g" "G",
            "h" "H",
        );
        let l0 = Letters(0b00000000);
        let l1 = Letters(0b00100000);
        let result = l0.diff(l1).next().unwrap();
        let sample = either::Either::Right((5, &DualView("f", "F")));
        assert_eq!(sample, result);
        layout!(
            DualView;
            pub struct Triple([u8; 3]);
            "a",
            "b" "B",
            "c",
            "d",
            "e",
            "f" "F",
            "g" "G",
            "h" "H",
        );
    }

    #[test]
    fn layout_macro_flag_type() {
        layout!(
            FlagType;
            struct EightFlags(u8);
            "Significant: meaning",
            "Significant: meaning" "Significant: description",
            "Reserved: 2 bits": 2,
            "Reserved: shouldn't exists": 0,
            ShouldBe0,
            ShouldBe1,
            Unknown,
            Undefined,
        );
        let ef0 = EightFlags(0b00000000);
        let ef1 = EightFlags(0b00100000);
        let result = ef0.diff(ef1).next().unwrap();
        let sample = either::Either::Right((5, &FlagType::ShouldBe1));
        assert_eq!(sample, result);
    }
}