Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not discard error messages when using std #157

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions source/postcard/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,16 @@ pub enum Error {
DeserializeBadEncoding,
/// Bad CRC while deserializing
DeserializeBadCrc,
#[cfg(feature = "use-std")]
/// Serde Serialization Error
SerdeSerCustom(String),
#[cfg(not(feature = "use-std"))]
/// Serde Serialization Error
SerdeSerCustom,
#[cfg(feature = "use-std")]
/// Serde Deserialization Error
SerdeDeCustom(String),
#[cfg(not(feature = "use-std"))]
/// Serde Deserialization Error
SerdeDeCustom,
/// Error while processing `collect_str` during serialization
Expand Down Expand Up @@ -63,7 +71,13 @@ impl Display for Error {
DeserializeBadEnum => "Found an enum discriminant that was > u32::max_value()",
DeserializeBadEncoding => "The original data was not well encoded",
DeserializeBadCrc => "Bad CRC while deserializing",
#[cfg(feature = "use-std")]
SerdeSerCustom(s) => s,
#[cfg(feature = "use-std")]
SerdeDeCustom(s) => s,
#[cfg(not(feature = "use-std"))]
SerdeSerCustom => "Serde Serialization Error",
#[cfg(not(feature = "use-std"))]
SerdeDeCustom => "Serde Deserialization Error",
CollectStrError => "Error while processing `collect_str` during serialization",
}
Expand All @@ -74,6 +88,19 @@ impl Display for Error {
/// This is the Result type used by Postcard.
pub type Result<T> = ::core::result::Result<T, Error>;

#[cfg(feature = "use-std")]
impl serde::ser::Error for Error {
fn custom<T>(msg: T) -> Self
where
T: Display,
{
// We must convert the parameter immediately to a string, because we cannot guarantee
// that T lives long enough to be used later.
Error::SerdeSerCustom(msg.to_string())
}
}

#[cfg(not(feature = "use-std"))]
impl serde::ser::Error for Error {
fn custom<T>(_msg: T) -> Self
where
Expand All @@ -83,6 +110,17 @@ impl serde::ser::Error for Error {
}
}

#[cfg(feature = "use-std")]
impl serde::de::Error for Error {
fn custom<T>(msg: T) -> Self
where
T: Display,
{
Error::SerdeDeCustom(msg.to_string())
}
}

#[cfg(not(feature = "use-std"))]
impl serde::de::Error for Error {
fn custom<T>(_msg: T) -> Self
where
Expand Down