Skip to content

Commit

Permalink
Removed duplicate of serde::de::Unexpected from ron error API
Browse files Browse the repository at this point in the history
  • Loading branch information
juntyr committed Aug 15, 2022
1 parent 61d8164 commit 9890bc7
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 116 deletions.
151 changes: 44 additions & 107 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::{error::Error as StdError, fmt, io, str::Utf8Error, string::FromUtf8Err

/// This type represents all possible errors that can occur when
/// serializing or deserializing RON data.
#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SpannedError {
pub code: Error,
pub position: Position,
Expand All @@ -12,7 +12,7 @@ pub struct SpannedError {
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub type SpannedResult<T> = std::result::Result<T, SpannedError>;

#[derive(Clone, Debug, PartialEq)]
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
Io(String),
Expand Down Expand Up @@ -59,13 +59,9 @@ pub enum Error {
Utf8Error(Utf8Error),
TrailingCharacters,

ExpectedDifferentType {
expected: String,
found: UnexpectedSerdeTypeValue,
},
InvalidValueForType {
expected: String,
found: UnexpectedSerdeTypeValue,
found: String,
},
ExpectedDifferentLength {
expected: String,
Expand Down Expand Up @@ -148,16 +144,6 @@ impl fmt::Display for Error {
}
Error::UnexpectedByte(ref byte) => write!(f, "Unexpected byte {:?}", byte),
Error::TrailingCharacters => f.write_str("Non-whitespace trailing characters"),
Error::ExpectedDifferentType {
ref expected,
ref found,
} => {
write!(
f,
"Expected a value of type {} but found {} instead",
expected, found
)
}
Error::InvalidValueForType {
ref expected,
ref found,
Expand Down Expand Up @@ -244,7 +230,7 @@ impl fmt::Display for Error {
}
}

#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Position {
pub line: usize,
pub col: usize,
Expand All @@ -271,17 +257,52 @@ impl de::Error for Error {

#[cold]
fn invalid_type(unexp: de::Unexpected, exp: &dyn de::Expected) -> Self {
Error::ExpectedDifferentType {
expected: exp.to_string(),
found: unexp.into(),
}
// Invalid type and invalid value are merged given their similarity in ron
Self::invalid_value(unexp, exp)
}

#[cold]
fn invalid_value(unexp: de::Unexpected, exp: &dyn de::Expected) -> Self {
struct UnexpectedSerdeTypeValue<'a>(de::Unexpected<'a>);

impl<'a> fmt::Display for UnexpectedSerdeTypeValue<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use de::Unexpected::*;

match self.0 {
Bool(b) => write!(f, "the boolean `{}`", b),
Unsigned(i) => write!(f, "the unsigned integer `{}`", i),
Signed(i) => write!(f, "the signed integer `{}`", i),
Float(n) => write!(f, "the floating point number `{}`", n),
Char(c) => write!(f, "the UTF-8 character `{}`", c),
Str(s) => write!(f, "the string {:?}", s),
Bytes(b) => {
f.write_str("the bytes b\"")?;

for b in b {
write!(f, "\\x{:02x}", b)?;
}

f.write_str("\"")
}
Unit => write!(f, "a unit value"),
Option => write!(f, "an optional value"),
NewtypeStruct => write!(f, "a newtype struct"),
Seq => write!(f, "a sequence"),
Map => write!(f, "a map"),
Enum => write!(f, "an enum"),
UnitVariant => write!(f, "a unit variant"),
NewtypeVariant => write!(f, "a newtype variant"),
TupleVariant => write!(f, "a tuple variant"),
StructVariant => write!(f, "a struct variant"),
Other(other) => f.write_str(other),
}
}
}

Error::InvalidValueForType {
expected: exp.to_string(),
found: unexp.into(),
found: UnexpectedSerdeTypeValue(unexp).to_string(),
}
}

Expand Down Expand Up @@ -358,90 +379,6 @@ impl From<SpannedError> for Error {
}
}

#[derive(Clone, Debug, PartialEq)]
pub enum UnexpectedSerdeTypeValue {
Bool(bool),
Unsigned(u64),
Signed(i64),
Float(f64),
Char(char),
Str(String),
Bytes(Vec<u8>),
Unit,
Option,
NewtypeStruct,
Seq,
Map,
Enum,
UnitVariant,
NewtypeVariant,
TupleVariant,
StructVariant,
Other(String),
}

impl<'a> From<de::Unexpected<'a>> for UnexpectedSerdeTypeValue {
fn from(unexpected: de::Unexpected<'a>) -> Self {
use de::Unexpected::*;

match unexpected {
Bool(b) => Self::Bool(b),
Unsigned(u) => Self::Unsigned(u),
Signed(s) => Self::Signed(s),
Float(f) => Self::Float(f),
Char(c) => Self::Char(c),
Str(s) => Self::Str(s.to_owned()),
Bytes(b) => Self::Bytes(b.to_owned()),
Unit => Self::Unit,
Option => Self::Option,
NewtypeStruct => Self::NewtypeStruct,
Seq => Self::Seq,
Map => Self::Map,
Enum => Self::Enum,
UnitVariant => Self::UnitVariant,
NewtypeVariant => Self::NewtypeVariant,
TupleVariant => Self::TupleVariant,
StructVariant => Self::StructVariant,
Other(o) => Self::Other(o.to_owned()),
}
}
}

impl fmt::Display for UnexpectedSerdeTypeValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use self::UnexpectedSerdeTypeValue::*;

match *self {
Bool(b) => write!(f, "the boolean `{}`", b),
Unsigned(i) => write!(f, "the integer `{}`", i),
Signed(i) => write!(f, "the integer `{}`", i),
Float(n) => write!(f, "the floating point number `{}`", n),
Char(c) => write!(f, "the UTF-8 character `{}`", c),
Str(ref s) => write!(f, "the string {:?}", s),
Bytes(ref b) => {
f.write_str("the bytes b\"")?;

for b in b {
write!(f, "\\x{:02x}", b)?;
}

f.write_str("\"")
}
Unit => write!(f, "a unit value"),
Option => write!(f, "an optional value"),
NewtypeStruct => write!(f, "a newtype struct"),
Seq => write!(f, "a sequence"),
Map => write!(f, "a map"),
Enum => write!(f, "an enum"),
UnitVariant => write!(f, "a unit variant"),
NewtypeVariant => write!(f, "a newtype variant"),
TupleVariant => write!(f, "a tuple variant"),
StructVariant => write!(f, "a struct variant"),
Other(ref other) => f.write_str(other),
}
}
}

struct OneOf {
alts: &'static [&'static str],
none: &'static str,
Expand Down
4 changes: 2 additions & 2 deletions src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -656,11 +656,11 @@ impl<'a> Bytes<'a> {
}

pub fn peek(&self) -> Option<u8> {
self.bytes.get(0).cloned()
self.bytes.first().cloned()
}

pub fn peek_or_eof(&self) -> Result<u8> {
self.bytes.get(0).cloned().ok_or(Error::Eof)
self.bytes.first().cloned().ok_or(Error::Eof)
}

pub fn signed_integer<T>(&mut self) -> Result<T>
Expand Down
8 changes: 4 additions & 4 deletions tests/203_error_positions.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::num::NonZeroU32;

use ron::error::{Error, Position, SpannedError, UnexpectedSerdeTypeValue};
use ron::error::{Error, Position, SpannedError};
use serde::{
de::{Deserialize, Error as DeError, Unexpected},
Deserializer,
Expand All @@ -27,9 +27,9 @@ fn test_error_positions() {
assert_eq!(
ron::from_str::<TypeError>(" ()"),
Err(SpannedError {
code: Error::ExpectedDifferentType {
code: Error::InvalidValueForType {
expected: String::from("impossible"),
found: UnexpectedSerdeTypeValue::Unit,
found: String::from("a unit value"),
},
position: Position { line: 1, col: 3 },
})
Expand All @@ -40,7 +40,7 @@ fn test_error_positions() {
Err(SpannedError {
code: Error::InvalidValueForType {
expected: String::from("a nonzero u32"),
found: UnexpectedSerdeTypeValue::Unsigned(0),
found: String::from("the unsigned integer `0`"),
},
position: Position { line: 1, col: 28 },
})
Expand Down
4 changes: 2 additions & 2 deletions tests/359_deserialize_seed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ fn test_deserialize_seed() {
assert_eq!(
ron::Options::default().from_str_seed("'a'", Seed(42)),
Err(ron::error::SpannedError {
code: ron::Error::ExpectedDifferentType {
code: ron::Error::InvalidValueForType {
expected: String::from("an integer"),
found: ron::error::UnexpectedSerdeTypeValue::Str(String::from("a")),
found: String::from("the string \"a\""),
},
position: ron::error::Position { line: 1, col: 4 },
})
Expand Down
2 changes: 1 addition & 1 deletion tests/roundtrip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ fn roundtrip_pretty() {

#[test]
fn roundtrip_sep_tuple_members() {
#[derive(Debug, Deserialize, PartialEq, Serialize)]
#[derive(Debug, Deserialize, PartialEq, Eq, Serialize)]
pub enum FileOrMem {
File(String),
Memory,
Expand Down

0 comments on commit 9890bc7

Please sign in to comment.