[bencode/de] Improved syntax error messages

This commit is contained in:
Fabian 2024-08-11 21:00:51 +02:00
parent 00e84033b4
commit 6eb7f08388
2 changed files with 16 additions and 11 deletions

View File

@ -85,11 +85,13 @@ impl <'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
where
V: Visitor<'de>
{
match self.peek_byte()? as char {
let b = self.peek_byte()? as char;
match b {
'i' => self.deserialize_i64(visitor),
'l' => self.deserialize_seq(visitor),
'd' => self.deserialize_map(visitor),
_ => Err(Error::Syntax),
'0'..='9' => self.deserialize_str(visitor),
_ => Err(Error::Syntax(format!("any: invalid start char: {}", b))),
}
}
@ -278,14 +280,15 @@ impl <'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
where
V: Visitor<'de>
{
match self.peek_byte()? as char{
let b = self.peek_byte()? as char;
match b {
'l' => self.deserialize_seq(visitor),
'0'..='9' => {
let str = self.parse_byte_string()?;
let ba = ByteAccess::new(self, str);
visitor.visit_seq(ba)
},
_ => Err(Error::Syntax),
_ => Err(Error::Syntax(format!("tuple: invalid start char: {}", b))),
}
}
@ -397,12 +400,13 @@ impl<'a, 'de> SeqAccess<'de> for RegularAccess<'a, 'de> {
where
T: DeserializeSeed<'de>
{
match self.de.peek_byte()? as char {
let b = self.de.peek_byte()? as char;
match b {
'd' | 'i' | 'l' | '0'..='9' => {
seed.deserialize(&mut *self.de).map(Some)
},
'e' => Ok(None),
_ => Err(Error::Syntax)
_ => Err(Error::Syntax(format!("seq: next_element: invalid start/end char: {}", b)))
}
}
}
@ -427,11 +431,12 @@ impl<'a, 'de> MapAccess<'de> for RegularAccess<'a, 'de> {
where
V: DeserializeSeed<'de>
{
match self.de.peek_byte()? as char {
let b = self.de.peek_byte()? as char;
match b {
'd' | 'i' | 'l' | '0'..='9' => {
seed.deserialize(&mut *self.de)
},
_ => Err(Error::Syntax)
_ => Err(Error::Syntax(format!("map: next_value: invalid start char: {}", b)))
}
}
}

View File

@ -9,7 +9,7 @@ pub enum Error {
WontImplement,
Eof,
Syntax,
Syntax(String),
InvalidUtf8,
ExpectedBytes,
ExpectedBytesSep,
@ -48,8 +48,8 @@ impl Display for Error {
Error::Message(msg) => formatter.write_str(msg),
Error::WontImplement => formatter.write_str("there is no reasonable way to (de)serialize this type"),
Error::Eof => formatter.write_str("unexpected end of input"),
Error::Syntax => formatter.write_str("syntax error"),
Error::InvalidUtf8 => formatter.write_str("could not decoded as UTF-8"),
Error::Syntax(msg) => formatter.write_fmt(format_args!("syntax error: {}", msg)),
Error::InvalidUtf8 => formatter.write_str("could not decode as UTF-8"),
Error::ExpectedBytes => formatter.write_str("expected byte string start char: any number"),
Error::ExpectedBytesSep => formatter.write_str("expected byte separator char: ':'"),
Error::ExpectedInteger => formatter.write_str("expected integer start char 'i'"),