Skip to content

Commit

Permalink
refactor: use core::error::Error (#66)
Browse files Browse the repository at this point in the history
* refactor: use core::error::Error

* fix nit

* add missing From<String> impl
  • Loading branch information
niklasad1 authored Nov 11, 2024
1 parent 7f0214f commit 55b8904
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 53 deletions.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ homepage = "https://www.parity.io/"
description = "Encode and decode values of arbitrary shapes to SCALE bytes"
keywords = ["parity", "scale", "encoding", "decoding"]
include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE"]
rust-version = "1.81.0"

[features]
default = ["std", "serde", "from-string", "parser-ss58"]
Expand Down Expand Up @@ -39,7 +40,7 @@ either = { version = "1.6.1", default-features = false }
yap = { version = "0.11.0", optional = true }
base58 = { version = "0.2.0", optional = true }
blake2 = { version = "0.10.6", optional = true, default_features = false }
derive_more = { version = "1.0.0", default-features = false, features = ["display", "from"] }
thiserror = { version = "2.0.0", default-features = false }
scale-type-resolver = "0.2.0"

[dev-dependencies]
Expand Down
3 changes: 1 addition & 2 deletions src/scale_impls/tracing_decoder/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,7 @@ impl<Ctx: core::fmt::Debug> core::fmt::Display for TraceDecodingError<Value<Ctx>
}
}

#[cfg(feature = "std")]
impl<Ctx: core::fmt::Debug> std::error::Error for TraceDecodingError<Value<Ctx>> {}
impl<Ctx: core::fmt::Debug> core::error::Error for TraceDecodingError<Value<Ctx>> {}

impl<TypeId> From<DecodeError> for TraceDecodingError<TypeId> {
fn from(value: DecodeError) -> Self {
Expand Down
6 changes: 2 additions & 4 deletions src/serde_impls/deserializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,10 @@ use serde::{
/// Many internal serialization/deserialization errors are relayed
/// to this in string form, and so we use basic strings for custom
/// errors as well for simplicity.
#[derive(derive_more::Display, Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub struct DeserializerError(Cow<'static, str>);

#[cfg(feature = "std")]
impl std::error::Error for DeserializerError {}

impl DeserializerError {
fn from_string<S: Into<String>>(s: S) -> DeserializerError {
DeserializerError(Cow::Owned(s.into()))
Expand Down
10 changes: 4 additions & 6 deletions src/serde_impls/serializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,26 +30,24 @@ use serde::{
pub struct ValueSerializer;

/// An error that can occur when attempting to serialize a type into a [`Value`].
#[derive(derive_more::Display, Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SerializerError {
/// Some custom error string.
#[error("Custom error: {0}")]
Custom(String),
/// SCALE does not support floating point values, and so we'll hit this error if we try to
/// encode any floats.
#[display(
#[error(
"Floats do not have a SCALE compatible representation, and so cannot be serialized to Values"
)]
CannotSerializeFloats,
/// SCALE encoding is only designed to map from statically known structs to bytes. We use field names
/// to figure out this mapping between named composite types and structs, so we don't support encoding
/// maps with non-string keys into [`Value`]s.
#[display("Map keys must be strings or string-like")]
#[error("Map keys must be strings or string-like")]
MapKeyMustBeStringlike,
}

#[cfg(feature = "std")]
impl std::error::Error for SerializerError {}

impl serde::ser::Error for SerializerError {
fn custom<T>(msg: T) -> Self
where
Expand Down
9 changes: 3 additions & 6 deletions src/string_impls/custom_parsers/hex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,18 +92,15 @@ pub fn parse_hex(s: &mut &str) -> Option<Result<Value<()>, ParseError>> {
Some(Ok(Value::unnamed_composite(composite_values)))
}

#[derive(Debug, PartialEq, Clone, derive_more::Display)]
#[derive(Debug, PartialEq, Clone, thiserror::Error)]
#[allow(missing_docs)]
pub enum ParseHexError {
#[display("Invalid hex character: {_0}")]
#[error("Invalid hex character: {0}")]
InvalidChar(char),
#[display("Hex string is the wrong length; should be an even length")]
#[error("Hex string is the wrong length; should be an even length")]
WrongLength,
}

#[cfg(feature = "std")]
impl std::error::Error for ParseHexError {}

#[cfg(test)]
mod test {
use super::*;
Expand Down
73 changes: 39 additions & 34 deletions src/string_impls/from_string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,7 @@ pub struct ParseError {
pub err: ParseErrorKind,
}

#[cfg(feature = "std")]
impl std::error::Error for ParseError {}
impl core::error::Error for ParseError {}

impl ParseError {
/// Construct a new `ParseError` for tokens at the given location.
Expand Down Expand Up @@ -122,22 +121,22 @@ macro_rules! at_between {
}

/// Details about the error that occurred.
#[derive(Debug, derive_more::Display, derive_more::From, PartialEq, Eq)]
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
#[allow(missing_docs)]
pub enum ParseErrorKind {
#[display("Expected a value")]
#[error("Expected a value")]
ExpectedValue,
#[from]
Complex(ParseComplexError),
#[from]
Char(ParseCharError),
#[from]
String(ParseStringError),
#[from]
Number(ParseNumberError),
#[from]
BitSequence(ParseBitSequenceError),
#[from]
#[error(transparent)]
Complex(#[from] ParseComplexError),
#[error(transparent)]
Char(#[from] ParseCharError),
#[error(transparent)]
String(#[from] ParseStringError),
#[error(transparent)]
Number(#[from] ParseNumberError),
#[error(transparent)]
BitSequence(#[from] ParseBitSequenceError),
#[error("Custom error: {0}")]
Custom(String),
}
at_between!(ParseErrorKind);
Expand All @@ -155,60 +154,66 @@ impl ParseErrorKind {
}
}

#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)]
impl From<String> for ParseErrorKind {
fn from(s: String) -> Self {
ParseErrorKind::Custom(s)
}
}

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[allow(missing_docs)]
pub enum ParseComplexError {
#[display("The first character in a field name should be alphabetic")]
#[error("The first character in a field name should be alphabetic")]
InvalidStartingCharacterInIdent,
#[display(
#[error(
"Field name is not valid (it should begin with an alphabetical char and then consist only of alphanumeric chars)"
)]
InvalidFieldName,
#[display("Missing field separator; expected {_0}")]
#[error("Missing field separator; expected {0}")]
MissingFieldSeparator(char),
#[display("Missing closing '{_0}'")]
#[error("Missing closing '{0}'")]
ExpectedCloserToMatch(char, usize),
}
at_between!(ParseComplexError);

#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[allow(missing_docs)]
pub enum ParseCharError {
#[display("Expected a single character")]
#[error("Expected a single character")]
ExpectedValidCharacter,
#[display("Expected an escape code to follow the '\\'")]
#[error("Expected an escape code to follow the '\\'")]
ExpectedValidEscapeCode,
#[display("Expected a closing quote to match the opening quote at position {_0}")]
#[error("Expected a closing quote to match the opening quote at position {0}")]
ExpectedClosingQuoteToMatch(usize),
}
at_between!(ParseCharError);

#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[allow(missing_docs)]
pub enum ParseStringError {
#[display("Expected a closing quote to match the opening quote at position {_0}")]
#[error("Expected a closing quote to match the opening quote at position {0}")]
ExpectedClosingQuoteToMatch(usize),
#[display("Expected an escape code to follow the '\\'")]
#[error("Expected an escape code to follow the '\\'")]
ExpectedValidEscapeCode,
}
at_between!(ParseStringError);

#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[allow(missing_docs)]
pub enum ParseNumberError {
#[display("Expected one or more digits")]
#[error("Expected one or more digits")]
ExpectedDigit,
#[display("Failed to parse digits into an integer: {_0}")]
ParsingFailed(ParseIntError),
#[error("Failed to parse digits into an integer: {0}")]
ParsingFailed(#[from] ParseIntError),
}
at_between!(ParseNumberError);

#[derive(Debug, Clone, PartialEq, Eq, derive_more::Display)]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[allow(missing_docs)]
pub enum ParseBitSequenceError {
#[display("Expected a closing bracket ('>') to match the opening one at position {_0}")]
#[error("Expected a closing bracket ('>') to match the opening one at position {_0}")]
ExpectedClosingBracketToMatch(usize),
#[display("Invalid character; expecting a 0 or 1")]
#[error("Invalid character; expecting a 0 or 1")]
InvalidCharacter,
}
at_between!(ParseBitSequenceError);
Expand Down

0 comments on commit 55b8904

Please sign in to comment.