tm1637_embedded_hal/
str.rs

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
//! [`str`] parsing utilities.

use core::str::Bytes;

use crate::mappings::{from_ascii_byte, SegmentBits};

/// Parse a string to it's corresponding 7-segment display bits.
///
/// Dots are ignored unless they appear after a character. The dot is then or'd with the character.
///
/// # Example
///
/// ```rust
/// use tm1637_embedded_hal::{str::StrParser, mappings::{DigitBits, LoCharBits, SegmentBits, UpCharBits}};
///
/// let input = "..oH.3..45..............6.7";
/// let mut parser = StrParser::new(input);
///
/// assert_eq!(7, parser.len());
/// assert_eq!(LoCharBits::LoO as u8, parser.next().unwrap());
/// assert_eq!(UpCharBits::UpH as u8 | SegmentBits::Dot as u8, parser.next().unwrap());
/// assert_eq!(DigitBits::Seven as u8, parser.next_back().unwrap());
/// assert_eq!(4, parser.len());
/// ```
///
#[derive(Debug, Clone)]
pub struct StrParser<'a> {
    bytes: Bytes<'a>,
    current: Option<u8>,
    /// While reading backwards, we need to know if we have read a dot.
    ///
    /// - `0`: No dot has been read.
    /// - `SegmentBits::Dot as u8`: A dot has been read.
    ///
    /// We or this value with the found digit on the next call to `next_back`.
    or: u8,
    size: usize,
}

#[cfg(feature = "defmt")]
impl defmt::Format for StrParser<'_> {
    fn format(&self, fmt: defmt::Formatter) {
        defmt::write!(fmt, "StrParser {{ .. }}")
    }
}

impl<'a> StrParser<'a> {
    /// Create a new [`StrParser`] from a &[`str`].
    pub fn new(str: &'a str) -> Self {
        Self {
            bytes: str.bytes(),
            current: None,
            or: 0,
            size: str.bytes().filter(|byte| *byte != b'.').count(),
        }
    }
}

impl<'a> From<&'a str> for StrParser<'a> {
    fn from(value: &'a str) -> Self {
        Self::new(value)
    }
}

impl Iterator for StrParser<'_> {
    type Item = u8;
    fn next(&mut self) -> Option<Self::Item> {
        if self.size == 0 {
            return None;
        }

        loop {
            match self.bytes.next() {
                Some(byte) => match byte {
                    b'.' => match self.current.take() {
                        Some(current) => {
                            self.size -= 1;

                            return Some(from_ascii_byte(current) | SegmentBits::Dot as u8);
                        }
                        None => continue,
                    },
                    byte => match self.current.replace(byte) {
                        Some(current) => {
                            self.size -= 1;

                            return Some(from_ascii_byte(current));
                        }
                        None => self.current = Some(byte),
                    },
                },
                None => match self.current.take().map(from_ascii_byte) {
                    Some(current) => {
                        self.size -= 1;

                        return Some(current);
                    }
                    None => return None,
                },
            }
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.size, Some(self.size))
    }
}

impl ExactSizeIterator for StrParser<'_> {}

impl DoubleEndedIterator for StrParser<'_> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.size == 0 {
            return None;
        }

        loop {
            match self.bytes.next_back() {
                Some(byte) => match byte {
                    b'.' => {
                        self.or = SegmentBits::Dot as u8;

                        continue;
                    }
                    byte => {
                        let byte = from_ascii_byte(byte) | self.or;

                        self.or = 0;
                        self.size -= 1;

                        return Some(byte);
                    }
                },
                None => return None,
            }
        }
    }
}

#[cfg(test)]
mod tests {
    extern crate std;
    use std::vec;
    use std::vec::Vec;

    use crate::mappings::{DigitBits, UpCharBits};

    use super::*;

    #[test]
    fn no_dots() {
        let parser = StrParser::new("1234");
        let result: Vec<u8> = parser.collect();

        assert_eq!(
            vec![
                DigitBits::One as u8,
                DigitBits::Two as u8,
                DigitBits::Three as u8,
                DigitBits::Four as u8
            ],
            result
        );

        let parser = StrParser::new("HE.LLO");
        let result: Vec<u8> = parser.take(3).rev().collect();

        assert_eq!(
            vec![
                UpCharBits::UpH as u8,
                UpCharBits::UpE as u8 | SegmentBits::Dot as u8,
                UpCharBits::UpL as u8,
            ]
            .into_iter()
            .rev()
            .collect::<Vec<_>>(),
            result
        );
    }

    #[test]
    fn len() {
        let mut parser = StrParser::new("..12.3..45..............6.7");

        assert_eq!(7, parser.len());
        parser.next();
        assert_eq!(6, parser.len());
        parser.next();
        assert_eq!(5, parser.len());
        parser.next();
        assert_eq!(4, parser.len());
        parser.next();
        assert_eq!(3, parser.len());
        parser.next();
        assert_eq!(2, parser.len());
        parser.next();
        assert_eq!(1, parser.len());
        parser.next();
        assert_eq!(0, parser.len());
        assert_eq!(None, parser.next());
        assert_eq!(0, parser.len());
    }

    #[test]
    fn dots() {
        let parser = StrParser::new("..12.3..45..............6.7");
        let result: Vec<u8> = parser.collect();
        assert_eq!(
            vec![
                DigitBits::One as u8,
                DigitBits::Two as u8 | SegmentBits::Dot as u8,
                DigitBits::Three as u8 | SegmentBits::Dot as u8,
                DigitBits::Four as u8,
                DigitBits::Five as u8 | SegmentBits::Dot as u8,
                DigitBits::Six as u8 | SegmentBits::Dot as u8,
                DigitBits::Seven as u8
            ],
            result
        );
    }

    #[test]
    fn no_dots_rev() {
        let parser = StrParser::new("1234");
        let result: Vec<u8> = parser.rev().collect();
        let mut expected = vec![
            DigitBits::One as u8,
            DigitBits::Two as u8,
            DigitBits::Three as u8,
            DigitBits::Four as u8,
        ];
        expected.reverse();
        assert_eq!(expected, result);
    }

    #[test]
    fn dots_rev() {
        let parser = StrParser::new("..12.3..45..............6.7");
        let result: Vec<u8> = parser.rev().collect();
        let mut expected = vec![
            DigitBits::One as u8,
            DigitBits::Two as u8 | SegmentBits::Dot as u8,
            DigitBits::Three as u8 | SegmentBits::Dot as u8,
            DigitBits::Four as u8,
            DigitBits::Five as u8 | SegmentBits::Dot as u8,
            DigitBits::Six as u8 | SegmentBits::Dot as u8,
            DigitBits::Seven as u8,
        ];
        expected.reverse();
        assert_eq!(expected, result);
    }

    #[test]
    fn back_and_forth() {
        let mut parser = StrParser::new("..12.3..45..............6.7");

        assert_eq!(7, parser.len());

        assert_eq!(Some(DigitBits::One as u8), parser.next());
        assert_eq!(6, parser.len());

        assert_eq!(
            Some(DigitBits::Two as u8 | SegmentBits::Dot as u8),
            parser.next()
        );
        assert_eq!(5, parser.len());

        assert_eq!(Some(DigitBits::Seven as u8), parser.next_back());
        assert_eq!(4, parser.len());

        assert_eq!(
            Some(DigitBits::Three as u8 | SegmentBits::Dot as u8),
            parser.next()
        );
        assert_eq!(3, parser.len());

        assert_eq!(
            Some(DigitBits::Six as u8 | SegmentBits::Dot as u8),
            parser.next_back()
        );
        assert_eq!(2, parser.len());

        assert_eq!(Some(DigitBits::Four as u8), parser.next());
        assert_eq!(1, parser.len());

        assert_eq!(
            Some(DigitBits::Five as u8 | SegmentBits::Dot as u8),
            parser.next()
        );
        assert_eq!(0, parser.len());

        assert_eq!(None, parser.next_back());
        assert_eq!(None, parser.next());
        assert_eq!(0, parser.len());
    }
}