Debian Codegraph @

third_party/rust/sfv/src/parser.rs

raw
1 use crate::utils;
2 use crate::{
3 BareItem, Decimal, Dictionary, FromStr, InnerList, Item, List, ListEntry, Num, Parameters,
4 SFVResult,
5 };
6 use std::iter::Peekable;
7 use std::str::{from_utf8, Chars};
8
9 /// Implements parsing logic for each structured field value type.
10 pub trait ParseValue {
11 /// This method should not be used for parsing input into structured field value.
12 /// Use `Parser::parse_item`, `Parser::parse_list` or `Parsers::parse_dictionary` for that.
13 fn parse(input_chars: &mut Peekable<Chars>) -> SFVResult<Self>
14 where
15 Self: Sized;
16 }
17
18 /// If structured field value of List or Dictionary type is split into multiple lines,
19 /// allows to parse more lines and merge them into already existing structure field value.
20 pub trait ParseMore {
21 /// If structured field value is split across lines,
22 /// parses and merges next line into a single structured field value.
23 /// # Examples
24 /// ```
25 /// # use sfv::{Parser, SerializeValue, ParseMore};
26 ///
27 /// let mut list_field = Parser::parse_list("11, (12 13)".as_bytes()).unwrap();
28 /// list_field.parse_more("\"foo\", \"bar\"".as_bytes()).unwrap();
29 ///
30 /// assert_eq!(list_field.serialize_value().unwrap(), "11, (12 13), \"foo\", \"bar\"");
31 fn parse_more(&mut self, input_bytes: &[u8]) -> SFVResult<()>
32 where
33 Self: Sized;
34 }
35
36 impl ParseValue for Item {
37 fn parse(input_chars: &mut Peekable<Chars>) -> SFVResult<Item> {
38 // https://httpwg.org/specs/rfc8941.html#parse-item
39 let bare_item = Parser::parse_bare_item(input_chars)?;
40 let params = Parser::parse_parameters(input_chars)?;
41
42 Ok(Item { bare_item, params })
43 }
44 }
45
46 impl ParseValue for List {
47 fn parse(input_chars: &mut Peekable<Chars>) -> SFVResult<List> {
48 // https://httpwg.org/specs/rfc8941.html#parse-list
49 // List represents an array of (item_or_inner_list, parameters)
50
51 let mut members = vec![];
52
53 while input_chars.peek().is_some() {
54 members.push(Parser::parse_list_entry(input_chars)?);
55
56 utils::consume_ows_chars(input_chars);
57
58 if input_chars.peek().is_none() {
59 return Ok(members);
60 }
61
62 if let Some(c) = input_chars.next() {
63 if c != ',' {
64 return Err("parse_list: trailing characters after list member");
65 }
66 }
67
68 utils::consume_ows_chars(input_chars);
69
70 if input_chars.peek().is_none() {
71 return Err("parse_list: trailing comma");
72 }
73 }
74
75 Ok(members)
76 }
77 }
78
79 impl ParseValue for Dictionary {
80 fn parse(input_chars: &mut Peekable<Chars>) -> SFVResult<Dictionary> {
81 let mut dict = Dictionary::new();
82
83 while input_chars.peek().is_some() {
84 let this_key = Parser::parse_key(input_chars)?;
85
86 if let Some('=') = input_chars.peek() {
87 input_chars.next();
88 let member = Parser::parse_list_entry(input_chars)?;
89 dict.insert(this_key, member);
90 } else {
91 let value = true;
92 let params = Parser::parse_parameters(input_chars)?;
93 let member = Item {
94 bare_item: BareItem::Boolean(value),
95 params,
96 };
97 dict.insert(this_key, member.into());
98 }
99
100 utils::consume_ows_chars(input_chars);
101
102 if input_chars.peek().is_none() {
103 return Ok(dict);
104 }
105
106 if let Some(c) = input_chars.next() {
107 if c != ',' {
108 return Err("parse_dict: trailing characters after dictionary member");
109 }
110 }
111
112 utils::consume_ows_chars(input_chars);
113
114 if input_chars.peek().is_none() {
115 return Err("parse_dict: trailing comma");
116 }
117 }
118 Ok(dict)
119 }
120 }
121
122 impl ParseMore for List {
123 fn parse_more(&mut self, input_bytes: &[u8]) -> SFVResult<()> {
124 let parsed_list = Parser::parse_list(input_bytes)?;
125 self.extend(parsed_list);
126 Ok(())
127 }
128 }
129
130 impl ParseMore for Dictionary {
131 fn parse_more(&mut self, input_bytes: &[u8]) -> SFVResult<()> {
132 let parsed_dict = Parser::parse_dictionary(input_bytes)?;
133 self.extend(parsed_dict);
134 Ok(())
135 }
136 }
137
138 /// Exposes methods for parsing input into structured field value.
139 pub struct Parser;
140
141 impl Parser {
142 /// Parses input into structured field value of Dictionary type
143 pub fn parse_dictionary(input_bytes: &[u8]) -> SFVResult<Dictionary> {
144 Self::parse::<Dictionary>(input_bytes)
145 }
146
147 /// Parses input into structured field value of List type
148 pub fn parse_list(input_bytes: &[u8]) -> SFVResult<List> {
149 Self::parse::<List>(input_bytes)
150 }
151
152 /// Parses input into structured field value of Item type
153 pub fn parse_item(input_bytes: &[u8]) -> SFVResult<Item> {
154 Self::parse::<Item>(input_bytes)
155 }
156
157 // Generic parse method for checking input before parsing
158 // and handling trailing text error
159 fn parse<T: ParseValue>(input_bytes: &[u8]) -> SFVResult<T> {
160 // https://httpwg.org/specs/rfc8941.html#text-parse
161 if !input_bytes.is_ascii() {
162 return Err("parse: non-ascii characters in input");
163 }
164
165 let mut input_chars = from_utf8(input_bytes)
166 .map_err(|_| "parse: conversion from bytes to str failed")?
167 .chars()
168 .peekable();
169 utils::consume_sp_chars(&mut input_chars);
170
171 let output = T::parse(&mut input_chars)?;
172
173 utils::consume_sp_chars(&mut input_chars);
174
175 if input_chars.next().is_some() {
176 return Err("parse: trailing characters after parsed value");
177 };
178 Ok(output)
179 }
180
181 fn parse_list_entry(input_chars: &mut Peekable<Chars>) -> SFVResult<ListEntry> {
182 // https://httpwg.org/specs/rfc8941.html#parse-item-or-list
183 // ListEntry represents a tuple (item_or_inner_list, parameters)
184
185 match input_chars.peek() {
186 Some('(') => {
187 let parsed = Self::parse_inner_list(input_chars)?;
188 Ok(ListEntry::InnerList(parsed))
189 }
190 _ => {
191 let parsed = Item::parse(input_chars)?;
192 Ok(ListEntry::Item(parsed))
193 }
194 }
195 }
196
197 pub(crate) fn parse_inner_list(input_chars: &mut Peekable<Chars>) -> SFVResult<InnerList> {
198 // https://httpwg.org/specs/rfc8941.html#parse-innerlist
199
200 if Some('(') != input_chars.next() {
201 return Err("parse_inner_list: input does not start with '('");
202 }
203
204 let mut inner_list = Vec::new();
205 while input_chars.peek().is_some() {
206 utils::consume_sp_chars(input_chars);
207
208 if Some(&')') == input_chars.peek() {
209 input_chars.next();
210 let params = Self::parse_parameters(input_chars)?;
211 return Ok(InnerList {
212 items: inner_list,
213 params,
214 });
215 }
216
217 let parsed_item = Item::parse(input_chars)?;
218 inner_list.push(parsed_item);
219
220 if let Some(c) = input_chars.peek() {
221 if c != &' ' && c != &')' {
222 return Err("parse_inner_list: bad delimitation");
223 }
224 }
225 }
226
227 Err("parse_inner_list: the end of the inner list was not found")
228 }
229
230 pub(crate) fn parse_bare_item(input_chars: &mut Peekable<Chars>) -> SFVResult<BareItem> {
231 // https://httpwg.org/specs/rfc8941.html#parse-bare-item
232 if input_chars.peek().is_none() {
233 return Err("parse_bare_item: empty item");
234 }
235
236 match input_chars.peek() {
237 Some(&'?') => Ok(BareItem::Boolean(Self::parse_bool(input_chars)?)),
238 Some(&'"') => Ok(BareItem::String(Self::parse_string(input_chars)?)),
239 Some(&':') => Ok(BareItem::ByteSeq(Self::parse_byte_sequence(input_chars)?)),
240 Some(&c) if c == '*' || c.is_ascii_alphabetic() => {
241 Ok(BareItem::Token(Self::parse_token(input_chars)?))
242 }
243 Some(&c) if c == '-' || c.is_ascii_digit() => match Self::parse_number(input_chars)? {
244 Num::Decimal(val) => Ok(BareItem::Decimal(val)),
245 Num::Integer(val) => Ok(BareItem::Integer(val)),
246 },
247 _ => Err("parse_bare_item: item type can't be identified"),
248 }
249 }
250
251 pub(crate) fn parse_bool(input_chars: &mut Peekable<Chars>) -> SFVResult<bool> {
252 // https://httpwg.org/specs/rfc8941.html#parse-boolean
253
254 if input_chars.next() != Some('?') {
255 return Err("parse_bool: first character is not '?'");
256 }
257
258 match input_chars.next() {
259 Some('0') => Ok(false),
260 Some('1') => Ok(true),
261 _ => Err("parse_bool: invalid variant"),
262 }
263 }
264
265 pub(crate) fn parse_string(input_chars: &mut Peekable<Chars>) -> SFVResult<String> {
266 // https://httpwg.org/specs/rfc8941.html#parse-string
267
268 if input_chars.next() != Some('\"') {
269 return Err("parse_string: first character is not '\"'");
270 }
271
272 let mut output_string = String::from("");
273 while let Some(curr_char) = input_chars.next() {
274 match curr_char {
275 '\"' => return Ok(output_string),
276 '\x7f' | '\x00'..='\x1f' => return Err("parse_string: not a visible character"),
277 '\\' => match input_chars.next() {
278 Some(c) if c == '\\' || c == '\"' => {
279 output_string.push(c);
280 }
281 None => return Err("parse_string: last input character is '\\'"),
282 _ => return Err("parse_string: disallowed character after '\\'"),
283 },
284 _ => output_string.push(curr_char),
285 }
286 }
287 Err("parse_string: no closing '\"'")
288 }
289
290 pub(crate) fn parse_token(input_chars: &mut Peekable<Chars>) -> SFVResult<String> {
291 // https://httpwg.org/specs/rfc8941.html#parse-token
292
293 if let Some(first_char) = input_chars.peek() {
294 if !first_char.is_ascii_alphabetic() && first_char != &'*' {
295 return Err("parse_token: first character is not ALPHA or '*'");
296 }
297 } else {
298 return Err("parse_token: empty input string");
299 }
300
301 let mut output_string = String::from("");
302 while let Some(curr_char) = input_chars.peek() {
303 if !utils::is_tchar(*curr_char) && curr_char != &':' && curr_char != &'/' {
304 return Ok(output_string);
305 }
306
307 match input_chars.next() {
308 Some(c) => output_string.push(c),
309 None => return Err("parse_token: end of the string"),
310 }
311 }
312 Ok(output_string)
313 }
314
315 pub(crate) fn parse_byte_sequence(input_chars: &mut Peekable<Chars>) -> SFVResult<Vec<u8>> {
316 // https://httpwg.org/specs/rfc8941.html#parse-binary
317
318 if input_chars.next() != Some(':') {
319 return Err("parse_byte_seq: first char is not ':'");
320 }
321
322 if !input_chars.clone().any(|c| c == ':') {
323 return Err("parse_byte_seq: no closing ':'");
324 }
325
326 let b64_content = input_chars.take_while(|c| c != &':').collect::<String>();
327 if !b64_content.chars().all(utils::is_allowed_b64_content) {
328 return Err("parse_byte_seq: invalid char in byte sequence");
329 }
330 match utils::base64()?.decode(b64_content.as_bytes()) {
331 Ok(content) => Ok(content),
332 Err(_) => Err("parse_byte_seq: decoding error"),
333 }
334 }
335
336 pub(crate) fn parse_number(input_chars: &mut Peekable<Chars>) -> SFVResult<Num> {
337 // https://httpwg.org/specs/rfc8941.html#parse-number
338
339 let mut sign = 1;
340 if let Some('-') = input_chars.peek() {
341 sign = -1;
342 input_chars.next();
343 }
344
345 match input_chars.peek() {
346 Some(c) if !c.is_ascii_digit() => {
347 return Err("parse_number: input number does not start with a digit")
348 }
349 None => return Err("parse_number: input number lacks a digit"),
350 _ => (),
351 }
352
353 // Get number from input as a string and identify whether it's a decimal or integer
354 let (is_integer, input_number) = Self::extract_digits(input_chars)?;
355
356 // Parse input_number from string into integer
357 if is_integer {
358 let output_number = input_number
359 .parse::<i64>()
360 .map_err(|_err| "parse_number: parsing i64 failed")?
361 * sign;
362
363 let (min_int, max_int) = (-999_999_999_999_999_i64, 999_999_999_999_999_i64);
364 if !(min_int <= output_number && output_number <= max_int) {
365 return Err("parse_number: integer number is out of range");
366 }
367
368 return Ok(Num::Integer(output_number));
369 }
370
371 // Parse input_number from string into decimal
372 let chars_after_dot = input_number
373 .find('.')
374 .map(|dot_pos| input_number.len() - dot_pos - 1);
375
376 match chars_after_dot {
377 Some(0) => Err("parse_number: decimal ends with '.'"),
378 Some(1..=3) => {
379 let mut output_number = Decimal::from_str(&input_number)
380 .map_err(|_err| "parse_number: parsing f64 failed")?;
381
382 if sign == -1 {
383 output_number.set_sign_negative(true)
384 }
385
386 Ok(Num::Decimal(output_number))
387 }
388 _ => Err("parse_number: invalid decimal fraction length"),
389 }
390 }
391
392 fn extract_digits(input_chars: &mut Peekable<Chars>) -> SFVResult<(bool, String)> {
393 let mut is_integer = true;
394 let mut input_number = String::from("");
395 while let Some(curr_char) = input_chars.peek() {
396 if curr_char.is_ascii_digit() {
397 input_number.push(*curr_char);
398 input_chars.next();
399 } else if curr_char == &'.' && is_integer {
400 if input_number.len() > 12 {
401 return Err(
402 "parse_number: decimal too long, illegal position for decimal point",
403 );
404 }
405 input_number.push(*curr_char);
406 is_integer = false;
407 input_chars.next();
408 } else {
409 break;
410 }
411
412 if is_integer && input_number.len() > 15 {
413 return Err("parse_number: integer too long, length > 15");
414 }
415
416 if !is_integer && input_number.len() > 16 {
417 return Err("parse_number: decimal too long, length > 16");
418 }
419 }
420 Ok((is_integer, input_number))
421 }
422
423 pub(crate) fn parse_parameters(input_chars: &mut Peekable<Chars>) -> SFVResult<Parameters> {
424 // https://httpwg.org/specs/rfc8941.html#parse-param
425
426 let mut params = Parameters::new();
427
428 while let Some(curr_char) = input_chars.peek() {
429 if curr_char == &';' {
430 input_chars.next();
431 } else {
432 break;
433 }
434
435 utils::consume_sp_chars(input_chars);
436
437 let param_name = Self::parse_key(input_chars)?;
438 let param_value = match input_chars.peek() {
439 Some('=') => {
440 input_chars.next();
441 Self::parse_bare_item(input_chars)?
442 }
443 _ => BareItem::Boolean(true),
444 };
445 params.insert(param_name, param_value);
446 }
447
448 // If parameters already contains a name param_name (comparing character-for-character), overwrite its value.
449 // Note that when duplicate Parameter keys are encountered, this has the effect of ignoring all but the last instance.
450 Ok(params)
451 }
452
453 pub(crate) fn parse_key(input_chars: &mut Peekable<Chars>) -> SFVResult<String> {
454 match input_chars.peek() {
455 Some(c) if c == &'*' || c.is_ascii_lowercase() => (),
456 _ => return Err("parse_key: first character is not lcalpha or '*'"),
457 }
458
459 let mut output = String::new();
460 while let Some(curr_char) = input_chars.peek() {
461 if !curr_char.is_ascii_lowercase()
462 && !curr_char.is_ascii_digit()
463 && !"_-*.".contains(*curr_char)
464 {
465 return Ok(output);
466 }
467
468 output.push(*curr_char);
469 input_chars.next();
470 }
471 Ok(output)
472 }
473 }