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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
use crate::{invalid_input, BitId, Error, Result};
use std::{fmt, str};

/// Value bits and mask
pub type Bits = u64;

/// Maximum number of values which can be get or set per time
pub const MAX_VALUES: usize = core::mem::size_of::<Bits>() * 8;

/// Maximum number of bits which can be get or set per time
pub const MAX_BITS: BitId = MAX_VALUES as _;

/// Default values representation
pub type Values = Masked<Bits>;

/// Something that can be used to get GPIO line values
pub trait AsValues {
    //// Number of bits
    fn bits(&self) -> BitId;

    /// Get the value of specific bit identified by offset
    ///
    /// If bit is out of range (0..bits) or not masked then None should be returned.
    fn get(&self, id: BitId) -> Option<bool>;

    /// Copy values to another variable
    fn copy_into<T: AsValuesMut>(&self, other: &mut T) {
        for id in 0..self.bits().min(other.bits()) {
            other.set(id, self.get(id));
        }
    }

    /// Convert to another representation
    fn convert<T: AsValuesMut + Default>(&self) -> T {
        let mut other = T::default();
        self.copy_into(&mut other);
        other
    }
}

/// Something that can be used to get and set GPIO line values
pub trait AsValuesMut: AsValues {
    /// Set the value of specific bit identified by offset
    ///
    /// If bit if out of range (0..bits) then nothing should be set.
    fn set(&mut self, id: BitId, val: Option<bool>);

    /// Change the value of specific bit identified by offset
    ///
    /// If bit if out of range (0..bits) then nothing will be changed.
    fn with(mut self, id: BitId, val: Option<bool>) -> Self
    where
        Self: Sized,
    {
        self.set(id, val);
        self
    }

    /// Copy values to another variable
    fn copy_from<T: AsValues>(&mut self, other: &T) {
        for id in 0..self.bits().min(other.bits()) {
            self.set(id, other.get(id));
        }
    }

    /// Fill values in range
    fn fill<R: Iterator<Item = BitId>>(&mut self, range: R, val: Option<bool>) {
        for id in range {
            self.set(id, val);
        }
    }

    /// Truncate mask
    fn truncate(&mut self, len: BitId) {
        for id in len..self.bits() {
            self.set(id, None);
        }
    }
}

impl<T: AsValues> AsValues for &T {
    fn bits(&self) -> BitId {
        (**self).bits()
    }

    fn get(&self, id: BitId) -> Option<bool> {
        (**self).get(id)
    }
}

impl<T: AsValues> AsValues for &mut T {
    fn bits(&self) -> BitId {
        (**self).bits()
    }

    fn get(&self, id: BitId) -> Option<bool> {
        (**self).get(id)
    }
}

impl<T: AsValuesMut> AsValuesMut for &mut T {
    fn set(&mut self, id: BitId, val: Option<bool>) {
        (**self).set(id, val)
    }
}

/// Line values with mask
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[repr(C)]
pub struct Masked<Bits> {
    /// Logic values of lines
    pub bits: Bits,

    /// Mask of lines to get or set
    pub mask: Bits,
}

macro_rules! as_values {
    ($($type:ty,)*) => {
        $(
            impl AsValues for $type {
                fn bits(&self) -> BitId {
                    (core::mem::size_of::<$type>() * 8) as _
                }

                fn get(&self, id: BitId) -> Option<bool> {
                    if id >= (core::mem::size_of::<$type>() * 8) as _ {
                        return None;
                    }

                    Some(self & (1 << id) != 0)
                }
            }

            impl AsValuesMut for $type {
                fn set(&mut self, id: BitId, val: Option<bool>) {
                    if id >= (core::mem::size_of::<$type>() * 8) as _ {
                        return;
                    }

                    let mask = (1 as $type) << id;

                    if let Some(true) = val {
                        *self |= mask;
                    } else {
                        *self &= !mask;
                    }
                }
            }

            impl AsValues for Masked<$type> {
                fn bits(&self) -> BitId {
                    (core::mem::size_of::<$type>() * 8) as _
                }

                fn get(&self, id: BitId) -> Option<bool> {
                    if id >= (core::mem::size_of::<$type>() * 8) as _ {
                        return None;
                    }

                    let mask = (1 as $type) << id;

                    if self.mask & mask == 0 {
                        return None;
                    }

                    Some(self.bits & mask != 0)
                }
            }

            impl AsValuesMut for Masked<$type> {
                fn set(&mut self, id: BitId, val: Option<bool>) {
                    if id >= (core::mem::size_of::<$type>() * 8) as _ {
                        return;
                    }

                    let mask = (1 as $type) << id;

                    if let Some(val) = val {
                        self.mask |= mask;

                        if val {
                            self.bits |= mask;
                        } else {
                            self.bits &= !mask;
                        }
                    } else {
                        let mask = !mask;

                        self.mask &= mask;
                        self.bits &= mask;
                    }
                }
            }

            impl From<$type> for Masked<$type> {
                fn from(bits: $type) -> Self {
                    Self {
                        bits: bits as _,
                        mask: <$type>::MAX as _,
                    }
                }
            }

            impl From<Masked<$type>> for $type {
                fn from(values: Masked<$type>) -> Self {
                    (values.bits & values.mask) as _
                }
            }

            impl fmt::Binary for Masked<$type> {
                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                    use fmt::Write;

                    let max = (core::mem::size_of::<$type>() * 8) as BitId;
                    let len = (max - (self.mask & self.bits).leading_zeros() as BitId).max(1);
                    let fill = f.width().map(|width| {
                        let width = if f.alternate() {
                            width - 2
                        } else {
                            width
                        };
                        if width > len as _ {
                            width - len as usize
                        } else {
                            0
                        }
                    }).unwrap_or(0);
                    let (fill_before, fill_after) = match f.align() {
                        Some(fmt::Alignment::Left) => (0, fill),
                        Some(fmt::Alignment::Right) | None => (fill, 0),
                        Some(fmt::Alignment::Center) => (fill - fill / 2, fill / 2),
                    };
                    let fill_char = f.fill();
                    if f.alternate() {
                        f.write_str("0b")?;
                    }
                    for _ in 0..fill_before {
                        f.write_char(fill_char)?;
                    }
                    for i in (0..len).rev() {
                        f.write_char(match self.get(i) {
                            Some(true) => '1',
                            Some(false) => '0',
                            None => 'x',
                        })?;
                    }
                    for _ in 0..fill_after {
                        f.write_char(fill_char)?;
                    }
                    Ok(())
                }
            }

            impl fmt::Display for Masked<$type> {
                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                    fmt::Binary::fmt(self, f)
                }
            }

            impl str::FromStr for Masked<$type> {
                type Err = Error;

                fn from_str(s: &str) -> Result<Self> {
                    let s = s.strip_prefix("0b").unwrap_or(s);
                    let mut i = s.len() as BitId;
                    if i > (core::mem::size_of::<$type>() * 8) as _ {
                        return Err(invalid_input("Too many line values"));
                    }
                    let mut r = Self::default();
                    for c in s.chars() {
                        i -= 1;
                        match c {
                            '1' => {
                                let b = 1 << i;
                                r.bits |= b;
                                r.mask |= b;
                            }
                            '0' => {
                                let b = 1 << i;
                                r.mask |= b;
                            }
                            'x' => {}
                            _ => return Err(invalid_input("Unexpected char in line value")),
                        }
                    }
                    Ok(r)
                }
            }

        )*
    };
}

as_values! {
    u8,
    u16,
    u32,
    u64,
}

impl AsValues for [bool] {
    fn bits(&self) -> BitId {
        self.len() as _
    }

    fn get(&self, id: BitId) -> Option<bool> {
        if id >= self.len() as _ {
            return None;
        }

        Some(self[id as usize])
    }
}

impl AsValuesMut for [bool] {
    fn set(&mut self, id: BitId, val: Option<bool>) {
        if id >= self.len() as _ {
            return;
        }

        if let Some(val) = val {
            self[id as usize] = val;
        }
    }
}

impl AsValues for Vec<bool> {
    fn bits(&self) -> BitId {
        self.len() as _
    }

    fn get(&self, id: BitId) -> Option<bool> {
        if id >= self.len() as _ {
            return None;
        }

        Some(self[id as usize])
    }
}

impl AsValuesMut for Vec<bool> {
    fn set(&mut self, id: BitId, val: Option<bool>) {
        if id >= self.len() as _ {
            return;
        }

        if let Some(val) = val {
            self[id as usize] = val;
        }
    }
}

impl<const LEN: usize> AsValues for [bool; LEN] {
    fn bits(&self) -> BitId {
        LEN as _
    }

    fn get(&self, id: BitId) -> Option<bool> {
        if id >= LEN as _ {
            return None;
        }

        Some(self[id as usize])
    }
}

impl<const LEN: usize> AsValuesMut for [bool; LEN] {
    fn set(&mut self, id: BitId, val: Option<bool>) {
        if id >= LEN as _ {
            return;
        }

        if let Some(val) = val {
            self[id as usize] = val;
        }
    }
}

impl AsValues for [Option<bool>] {
    fn bits(&self) -> BitId {
        self.len() as _
    }

    fn get(&self, id: BitId) -> Option<bool> {
        if id >= self.len() as _ {
            return None;
        }

        self[id as usize]
    }
}

impl AsValuesMut for [Option<bool>] {
    fn set(&mut self, id: BitId, val: Option<bool>) {
        if id >= self.len() as _ {
            return;
        }

        self[id as usize] = val;
    }
}

impl AsValues for Vec<Option<bool>> {
    fn bits(&self) -> BitId {
        self.len() as _
    }

    fn get(&self, id: BitId) -> Option<bool> {
        if id >= self.len() as _ {
            return None;
        }

        self[id as usize]
    }
}

impl AsValuesMut for Vec<Option<bool>> {
    fn set(&mut self, id: BitId, val: Option<bool>) {
        if id >= self.len() as _ {
            return;
        }

        self[id as usize] = val;
    }
}

impl<const LEN: usize> AsValues for [Option<bool>; LEN] {
    fn bits(&self) -> BitId {
        LEN as _
    }

    fn get(&self, id: BitId) -> Option<bool> {
        if id >= LEN as _ {
            return None;
        }

        self[id as usize]
    }
}

impl<const LEN: usize> AsValuesMut for [Option<bool>; LEN] {
    fn set(&mut self, id: BitId, val: Option<bool>) {
        if id >= LEN as _ {
            return;
        }

        self[id as usize] = val;
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn format_masked() {
        assert_eq!(Masked::from(0b1000u8).to_string(), "1000");

        assert_eq!(
            Values {
                bits: 0b1000,
                mask: 0b1111,
            }
            .to_string(),
            "1000"
        );

        assert_eq!(
            Values {
                bits: 0b0011,
                mask: 0b0111,
            }
            .to_string(),
            "11"
        );

        assert_eq!(
            Values {
                bits: 0b0011,
                mask: 0b1111,
            }
            .to_string(),
            "11"
        );

        assert_eq!(
            Values {
                bits: 0b11000,
                mask: 0b00011,
            }
            .to_string(),
            "0"
        );

        assert_eq!(
            Values {
                bits: 0b100001,
                mask: 0b110011,
            }
            .to_string(),
            "10xx01"
        );
    }

    #[test]
    fn format_masked_advanced() {
        assert_eq!(format!("{:#}", Masked::from(0b1000u8)), "0b1000");

        assert_eq!(format!("{:#08b}", 0b1000u8), "0b001000");

        //assert_eq!(format!("{:#08b}", Masked::from(0b1000u8)), "0b001000");

        assert_eq!(format!("{:11}", Masked::from(0b1000u8)), "       1000");

        assert_eq!(format!("{:-<11}", Masked::from(0b1000u8)), "1000-------");

        assert_eq!(format!("{:->11}", Masked::from(0b1000u8)), "-------1000");

        assert_eq!(format!("{:-^11}", Masked::from(0b1000u8)), "----1000---");
    }

    #[test]
    fn parse_masked() {
        assert_eq!(
            "0110".parse::<Values>().unwrap(),
            Values {
                bits: 0b0110,
                mask: 0b1111,
            }
        );

        assert_eq!(
            "00110".parse::<Values>().unwrap(),
            Values {
                bits: 0b00110,
                mask: 0b11111,
            }
        );

        assert_eq!(
            "0b10101".parse::<Values>().unwrap(),
            Values {
                bits: 0b10101,
                mask: 0b11111,
            }
        );

        assert_eq!(
            "1x10x".parse::<Values>().unwrap(),
            Values {
                bits: 0b10100,
                mask: 0b10110,
            }
        );

        assert_eq!(
            "xx0x010".parse::<Values>().unwrap(),
            Values {
                bits: 0b00010,
                mask: 0b10111,
            }
        );

        assert_eq!(
            "0bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                .parse::<Values>()
                .unwrap(),
            Values::default()
        );

        assert_eq!(
            "0b1111111111111111111111111111111111111111111111111111111111111111"
                .parse::<Values>()
                .unwrap(),
            Values {
                bits: Bits::MAX,
                mask: Bits::MAX,
            }
        );

        assert_eq!(
            "0b0000000000000000000000000000000000000000000000000000000000000000"
                .parse::<Values>()
                .unwrap(),
            Values {
                bits: 0,
                mask: Bits::MAX,
            }
        );

        assert!(
            "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                .parse::<Values>()
                .is_err()
        );

        assert!("0b10xy".parse::<Values>().is_err());
    }
}