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
use core::fmt;
pub const SYMBOL_CODE_CHARS: [u8; 26] = *b"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
pub const SYMBOL_CODE_MAX_LEN: usize = 7;
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum ParseSymbolCodeError {
TooLong,
BadChar(u8),
}
impl fmt::Display for ParseSymbolCodeError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Self::TooLong => {
write!(f, "symbol is too long, must be 7 chars or less")
}
Self::BadChar(c) => write!(
f,
"symbol contains invalid character '{}'",
char::from(c)
),
}
}
}
#[inline]
pub fn symbol_code_from_bytes<I>(iter: I) -> Result<u64, ParseSymbolCodeError>
where
I: DoubleEndedIterator<Item = u8> + ExactSizeIterator,
{
let mut value = 0_u64;
for (i, c) in iter.enumerate().rev() {
if i == SYMBOL_CODE_MAX_LEN {
return Err(ParseSymbolCodeError::TooLong);
} else if c < b'A' || c > b'Z' {
return Err(ParseSymbolCodeError::BadChar(c));
} else {
value <<= 8;
value |= u64::from(c);
}
}
Ok(value)
}
#[inline]
#[must_use]
#[allow(clippy::cast_possible_truncation)]
pub fn symbol_code_to_bytes(value: u64) -> [u8; SYMBOL_CODE_MAX_LEN] {
let mut chars = [b' '; SYMBOL_CODE_MAX_LEN];
let mut v = value;
for c in &mut chars {
if v == 0 {
break;
}
*c = (v & 0xFF) as u8;
v >>= 8;
}
chars
}
#[cfg(test)]
mod tests {
use super::{symbol_code_from_bytes, symbol_code_to_bytes};
use core::str;
use proptest::prelude::*;
#[test]
fn from_bytes_to_bytes() {
proptest!(|(input in "[A-Z]{0,7}")| {
let value = symbol_code_from_bytes(input.bytes()).unwrap();
let bytes = symbol_code_to_bytes(value);
let string = str::from_utf8(&bytes).unwrap();
prop_assert_eq!(string, format!("{:<7}", input));
});
}
#[test]
fn from_bytes_too_long() {
proptest!(|(input in "[A-Z]{8}")| {
if symbol_code_from_bytes(input.bytes()).is_ok() {
panic!("Should've gotten TooLong error with input '{}'", input);
};
});
}
#[test]
fn to_bytes_doesnt_crash() {
proptest!(|(input in 0_u64..)| {
let _ = symbol_code_to_bytes(input);
});
}
}