sbat/error.rs
1// Copyright 2023 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use ascii::AsciiChar;
10use core::fmt::{self, Display, Formatter};
11
12/// SBAT parse error.
13#[derive(Clone, Debug, Eq, PartialEq)]
14pub enum ParseError {
15 /// CSV field is not ASCII. According to the SBAT spec, all fields
16 /// must be ASCII.
17 InvalidAscii,
18
19 /// CSV field contains a special character. The characters allowed
20 /// are alphabetic, numeric, and [`ALLOWED_SPECIAL_CHARS`]. This is
21 /// to keep parsing simple. In particular, double-quote and escape
22 /// characters are not allowed, so a field cannot contain a comma.
23 ///
24 /// [`ALLOWED_SPECIAL_CHARS`]: crate::ALLOWED_SPECIAL_CHARS
25 SpecialChar(AsciiChar),
26
27 /// CSV field is not a valid [`Generation`] number.
28 ///
29 /// [`Generation`]: crate::Generation
30 InvalidGeneration,
31
32 /// CSV record has too few fields.
33 TooFewFields,
34}
35
36impl Display for ParseError {
37 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
38 match self {
39 Self::InvalidAscii => write!(f, "CSV field is not ASCII"),
40 Self::SpecialChar(c) => {
41 write!(
42 f,
43 "CSV field contains special character: {:#04x}",
44 c.as_byte()
45 )
46 }
47 Self::InvalidGeneration => {
48 write!(f, "invalid generation, must be a positive integer")
49 }
50 Self::TooFewFields => {
51 write!(f, "a CSV record does not have enough fields")
52 }
53 }
54 }
55}
56
57impl core::error::Error for ParseError {}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62
63 #[test]
64 fn test_error_display() {
65 assert_eq!(
66 format!("{}", ParseError::SpecialChar(AsciiChar::Null)),
67 "CSV field contains special character: 0x00"
68 );
69
70 // For the rest, don't bother testing the specific error
71 // messages, just ensure nothing panics.
72 let _ = format!("{}", ParseError::InvalidAscii);
73 let _ = format!("{}", ParseError::InvalidGeneration);
74 let _ = format!("{}", ParseError::TooFewFields);
75 }
76}