75 lines
2.6 KiB
Rust
75 lines
2.6 KiB
Rust
use std::fmt;
|
|
|
|
use crate::dec::debug;
|
|
|
|
/// The type of errors returned by helper functions on `Term`
|
|
#[derive(Debug, Clone)]
|
|
pub enum TypeError {
|
|
/// The term could not be decoded in the given type
|
|
WrongType(&'static str),
|
|
/// The term is not an array of the requested length
|
|
WrongLength(usize, usize),
|
|
/// The dictionnary is missing a key
|
|
MissingKey(String),
|
|
/// The dictionnary contains an invalid key
|
|
UnexpectedKey(String),
|
|
/// The underlying raw string contains garbage (should not happen in theory)
|
|
Garbage,
|
|
}
|
|
|
|
impl From<std::str::Utf8Error> for TypeError {
|
|
fn from(_x: std::str::Utf8Error) -> TypeError {
|
|
TypeError::Garbage
|
|
}
|
|
}
|
|
|
|
impl std::fmt::Display for TypeError {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
match self {
|
|
TypeError::WrongType(t) => write!(f, "Not a {}", t),
|
|
TypeError::WrongLength(n, m) => write!(f, "Expected {} items, got {}", m, n),
|
|
TypeError::MissingKey(k) => write!(f, "Missing key `{}` in dict", k),
|
|
TypeError::UnexpectedKey(k) => write!(f, "Spurrious/unexpected key `{}` in dict", k),
|
|
TypeError::Garbage => write!(f, "Garbage in underlying data"),
|
|
}
|
|
}
|
|
}
|
|
|
|
// ----
|
|
|
|
/// The error kind returned by the `decode` function.
|
|
#[derive(Eq, PartialEq)]
|
|
pub enum DecodeError<'a> {
|
|
/// Indicates that there is trailing garbage at the end of the decoded string
|
|
Garbage(&'a [u8]),
|
|
/// Indicates that the entered string does not represent a complete nettext term
|
|
IncompleteInput,
|
|
/// Indicates a syntax error in the decoded term
|
|
NomError(&'a [u8], nom::error::ErrorKind),
|
|
}
|
|
|
|
impl<'a> std::fmt::Display for DecodeError<'a> {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
|
|
match self {
|
|
DecodeError::Garbage(g) => write!(f, "Garbage: `{}`", debug(g)),
|
|
DecodeError::IncompleteInput => write!(f, "Incomplete input"),
|
|
DecodeError::NomError(s, e) => write!(f, "Nom: {:?}, at: `{}`", e, debug(s)),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl<'a> std::fmt::Debug for DecodeError<'a> {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
|
|
std::fmt::Display::fmt(self, f)
|
|
}
|
|
}
|
|
|
|
impl<'a> From<nom::Err<nom::error::Error<&'a [u8]>>> for DecodeError<'a> {
|
|
fn from(e: nom::Err<nom::error::Error<&'a [u8]>>) -> DecodeError<'a> {
|
|
match e {
|
|
nom::Err::Incomplete(_) => DecodeError::IncompleteInput,
|
|
nom::Err::Error(e) | nom::Err::Failure(e) => DecodeError::NomError(e.input, e.code),
|
|
}
|
|
}
|
|
}
|