Debian Codegraph @

rust/hg-core/src/config/values.rs

raw
1 //! Parsing functions for various type of configuration values.
2 //!
3 //! Returning `None` indicates a syntax error. Using a `Result` would be more
4 //! correct but would take more boilerplate for converting between error types,
5 //! compared to using `.ok()` on inner results of various error types to
6 //! convert them all to options. The `Config::get_parse` method later converts
7 //! those options to results with `ConfigValueParseError`, which contains
8 //! details about where the value came from (but omits details of what’s
9 //! invalid inside the value).
10
11 use crate::utils::strings::SliceExt;
12
13 pub(super) fn parse_bool(v: &[u8]) -> Option<bool> {
14 match v.to_ascii_lowercase().as_slice() {
15 b"1" | b"yes" | b"true" | b"on" | b"always" => Some(true),
16 b"0" | b"no" | b"false" | b"off" | b"never" => Some(false),
17 _ => None,
18 }
19 }
20
21 pub(super) fn parse_byte_size(value: &[u8]) -> Option<u64> {
22 let value = std::str::from_utf8(value).ok()?.to_ascii_lowercase();
23 const UNITS: &[(&str, u64)] = &[
24 ("g", 1 << 30),
25 ("gb", 1 << 30),
26 ("m", 1 << 20),
27 ("mb", 1 << 20),
28 ("k", 1 << 10),
29 ("kb", 1 << 10),
30 ("b", 1 << 0), // Needs to be last
31 ];
32 for &(unit, multiplier) in UNITS {
33 if let Some(value) = value.strip_suffix(unit) {
34 let float: f64 = value.trim().parse().ok()?;
35 if float >= 0.0 {
36 return Some((float * multiplier as f64).round() as u64);
37 } else {
38 return None;
39 }
40 }
41 }
42 value.parse().ok()
43 }
44
45 // Note: keep behavior in sync with the Python one.
46 // Note: this could return `Vec<Cow<[u8]>>` instead and borrow `input` when
47 // possible (when there’s no backslash-escapes) but this is probably not worth
48 // the complexity as config is presumably not accessed inside
49 // performance-sensitive loops.
50
51 /// Parse a config value as a list of sub-values.
52 ///
53 /// Ported from `parselist` in `mercurial/utils/stringutil.py`
54 pub(super) fn parse_list(input: &[u8]) -> Vec<Vec<u8>> {
55 // Port of Python’s `value.lstrip(b' ,\n')`
56 // TODO: is this really what we want?
57 let input =
58 input.trim_start_matches(|b| b == b' ' || b == b',' || b == b'\n');
59 parse_list_without_trim_start(input)
60 }
61
62 fn parse_list_without_trim_start(input: &[u8]) -> Vec<Vec<u8>> {
63 // Start of port of Python’s `_configlist`
64 let input = input.trim_end_matches(|b| b == b' ' || b == b',');
65 if input.is_empty() {
66 return Vec::new();
67 }
68
69 // Just to make “a string” less confusable with “a list of strings”.
70 type ByteString = Vec<u8>;
71
72 // These correspond to Python’s…
73 let mut mode = ParserMode::Plain; // `parser`
74 let mut values = Vec::new(); // `parts[:-1]`
75 let mut next_value = ByteString::new(); // `parts[-1]`
76 let mut offset = 0; // `offset`
77
78 // Setting `parser` to `None` is instead handled by returning immediately
79 enum ParserMode {
80 Plain,
81 Quoted,
82 }
83
84 loop {
85 match mode {
86 ParserMode::Plain => {
87 // Start of port of Python’s `_parse_plain`
88 let mut whitespace = false;
89 while let Some(&byte) = input.get(offset) {
90 if is_space(byte) || byte == b',' {
91 whitespace = true;
92 offset += 1;
93 } else {
94 break;
95 }
96 }
97 if let Some(&byte) = input.get(offset) {
98 if whitespace {
99 values.push(std::mem::take(&mut next_value))
100 }
101 if byte == b'"' && next_value.is_empty() {
102 mode = ParserMode::Quoted;
103 } else {
104 if byte == b'"' && next_value.ends_with(b"\\") {
105 next_value.pop();
106 }
107 next_value.push(byte);
108 }
109 offset += 1;
110 } else {
111 values.push(next_value);
112 return values;
113 }
114 }
115 ParserMode::Quoted => {
116 // Start of port of Python’s `_parse_quote`
117 if let Some(&byte) = input.get(offset) {
118 if byte == b'"' {
119 // The input contains a quoted zero-length value `""`
120 debug_assert_eq!(next_value, b"");
121 values.push(std::mem::take(&mut next_value));
122 offset += 1;
123 while let Some(&byte) = input.get(offset) {
124 if is_space(byte) || byte == b',' {
125 offset += 1;
126 } else {
127 break;
128 }
129 }
130 mode = ParserMode::Plain;
131 continue;
132 }
133 }
134
135 while let Some(&byte) = input.get(offset) {
136 if byte == b'"' {
137 break;
138 }
139 if byte == b'\\' && input.get(offset + 1) == Some(&b'"') {
140 next_value.push(b'"');
141 offset += 2;
142 } else {
143 next_value.push(byte);
144 offset += 1;
145 }
146 }
147
148 if offset >= input.len() {
149 // We didn’t find a closing double-quote,
150 // so treat the opening one as part of an unquoted value
151 // instead of delimiting the start of a quoted value.
152
153 // `next_value` may have had some backslash-escapes
154 // unescaped. TODO: shouldn’t we use a slice of `input`
155 // instead?
156 let mut real_values =
157 parse_list_without_trim_start(&next_value);
158
159 if let Some(first) = real_values.first_mut() {
160 first.insert(0, b'"');
161 // Drop `next_value`
162 values.extend(real_values)
163 } else {
164 next_value.push(b'"');
165 values.push(next_value);
166 }
167 return values;
168 }
169
170 // We’re not at the end of the input, which means the `while`
171 // loop above ended at at double quote. Skip
172 // over that.
173 offset += 1;
174
175 while let Some(&byte) = input.get(offset) {
176 if byte == b' ' || byte == b',' {
177 offset += 1;
178 } else {
179 break;
180 }
181 }
182
183 if offset >= input.len() {
184 values.push(next_value);
185 return values;
186 }
187
188 if offset + 1 == input.len() && input[offset] == b'"' {
189 next_value.push(b'"');
190 offset += 1;
191 } else {
192 values.push(std::mem::take(&mut next_value));
193 }
194
195 mode = ParserMode::Plain;
196 }
197 }
198 }
199
200 // https://docs.python.org/3/library/stdtypes.html?#bytes.isspace
201 fn is_space(byte: u8) -> bool {
202 matches!(byte, b' ' | b'\t' | b'\n' | b'\r' | b'\x0b' | b'\x0c')
203 }
204 }
205
206 #[test]
207 fn test_parse_list() {
208 // Make `assert_eq` error messages nicer
209 fn as_strings(values: &[Vec<u8>]) -> Vec<String> {
210 values
211 .iter()
212 .map(|v| std::str::from_utf8(v.as_ref()).unwrap().to_owned())
213 .collect()
214 }
215 macro_rules! assert_parse_list {
216 ( $input: expr => [ $( $output: expr ),* ] ) => {
217 assert_eq!(
218 as_strings(&parse_list($input)),
219 as_strings(&[ $( Vec::from(&$output[..]) ),* ]),
220 );
221 }
222 }
223
224 // Keep these Rust tests in sync with the Python ones in
225 // `tests/test-config-parselist.py`
226 assert_parse_list!(b"" => []);
227 assert_parse_list!(b"," => []);
228 assert_parse_list!(b"A" => [b"A"]);
229 assert_parse_list!(b"B,B" => [b"B", b"B"]);
230 assert_parse_list!(b", C, ,C," => [b"C", b"C"]);
231 assert_parse_list!(b"\"" => [b"\""]);
232 assert_parse_list!(b"\"\"" => [b"", b""]);
233 assert_parse_list!(b"D,\"" => [b"D", b"\""]);
234 assert_parse_list!(b"E,\"\"" => [b"E", b"", b""]);
235 assert_parse_list!(b"\"F,F\"" => [b"F,F"]);
236 assert_parse_list!(b"\"G,G" => [b"\"G", b"G"]);
237 assert_parse_list!(b"\"H \\\",\\\"H" => [b"\"H", b",", b"H"]);
238 assert_parse_list!(b"I,I\"" => [b"I", b"I\""]);
239 assert_parse_list!(b"J,\"J" => [b"J", b"\"J"]);
240 assert_parse_list!(b"K K" => [b"K", b"K"]);
241 assert_parse_list!(b"\"K\" K" => [b"K", b"K"]);
242 assert_parse_list!(b"L\tL" => [b"L", b"L"]);
243 assert_parse_list!(b"\"L\"\tL" => [b"L", b"", b"L"]);
244 assert_parse_list!(b"M\x0bM" => [b"M", b"M"]);
245 assert_parse_list!(b"\"M\"\x0bM" => [b"M", b"", b"M"]);
246 assert_parse_list!(b"\"N\" , ,\"" => [b"N\""]);
247 assert_parse_list!(b"\" ,O, " => [b"\"", b"O"]);
248 }
249
250 #[test]
251 fn test_parse_byte_size() {
252 assert_eq!(parse_byte_size(b""), None);
253 assert_eq!(parse_byte_size(b"b"), None);
254
255 assert_eq!(parse_byte_size(b"12"), Some(12));
256 assert_eq!(parse_byte_size(b"12b"), Some(12));
257 assert_eq!(parse_byte_size(b"12 b"), Some(12));
258 assert_eq!(parse_byte_size(b"12.1 b"), Some(12));
259 assert_eq!(parse_byte_size(b"1.1 K"), Some(1126));
260 assert_eq!(parse_byte_size(b"1.1 kB"), Some(1126));
261
262 assert_eq!(parse_byte_size(b"-12 b"), None);
263 assert_eq!(parse_byte_size(b"-0.1 b"), None);
264 assert_eq!(parse_byte_size(b"0.1 b"), Some(0));
265 assert_eq!(parse_byte_size(b"12.1 b"), Some(12));
266 }