Debian Codegraph @

src/utils.rs

raw symbols SCIP
1 use std::iter::Peekable;
2 use std::slice::Iter;
3
4 /// Helper method that returns None if test is true
5 #[inline]
6 #[must_use]
7 pub fn fail_if(test: bool) -> Option<()> {
8 if test {
9 None
10 } else {
11 Some(())
12 }
13 }
14
15 #[inline]
16 pub fn is_whitespace(c: u8) -> bool {
17 c == b'\t' || c == b' '
18 }
19
20 #[inline]
21 fn into_digit(c: u8) -> u64 {
22 u64::from(c - b'0')
23 }
24
25 pub(crate) trait IterExt {
26 #[must_use]
27 fn skip_spaces(&mut self) -> Option<u8>;
28 #[must_use]
29 fn parse_separator(&mut self, separator: u8) -> Option<u8>;
30 #[must_use]
31 fn parse_u64(&mut self) -> Option<u64>;
32 }
33
34 impl IterExt for Peekable<Iter<'_, u8>> {
35 /// Advances to the next non-blank byte, returning true if there is more data
36 fn skip_spaces(&mut self) -> Option<u8> {
37 loop {
38 match self.peek() {
39 None => return None,
40 Some(v) => {
41 if is_whitespace(**v) {
42 self.next();
43 } else {
44 return Some(**v);
45 }
46 }
47 }
48 }
49 }
50
51 /// Skip spaces, and ensure there is a given separator. Returns next non-space value
52 fn parse_separator(&mut self, separator: u8) -> Option<u8> {
53 if self.skip_spaces()? != separator {
54 return None;
55 }
56 self.next()?; // consume separator
57 self.skip_spaces()
58 }
59
60 /// Consume u64 value
61 fn parse_u64(&mut self) -> Option<u64> {
62 let mut res = match self.next() {
63 None => return None,
64 Some(v) => {
65 let c = *v;
66 if !c.is_ascii_digit() {
67 return None;
68 }
69 into_digit(*v)
70 }
71 };
72 loop {
73 match self.peek() {
74 None => return Some(res),
75 Some(v) => {
76 let next = **v;
77 if next.is_ascii_digit() {
78 res = res.checked_mul(10)?.checked_add(into_digit(next))?;
79 self.next();
80 } else {
81 return Some(res);
82 }
83 }
84 }
85 }
86 }
87 }