/// An error which may occur during encoding or decoding.
#[derive(Debug, PartialEq)]
pub enum Error {
    /// Not enough memory in the buffer for the attempted read or write operation.
    OutOfMemory,

    /// The value being decoded does not fit into the value range of the destination memory location.
    OutOfRange,

    /// An attempt was made to decode a reserved marker value.
    BadMarker,

    /// The decoded marker was not expected, possibly indicating a type mismatch during deserialization.
    Unexpected,

    /// The user data is not properly encoded, e.g. string data contains characters outside of the ASCII range.
    BadEncoding,

    /// One should report an issue if one ever encounters this error variant.
    Internal,
}

#[cfg(feature = "serde")]
impl core::fmt::Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Error::OutOfMemory => f.write_str("out of memory"),
            Error::OutOfRange => f.write_str("value out of range"),
            Error::BadMarker => f.write_str("bad marker"),
            Error::Unexpected => f.write_str("unexpected marker or length"),
            Error::BadEncoding => f.write_str("bad data/utf8 encoding"),
            Error::Internal => f.write_str("internal error"),
        }
    }
}

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

#[cfg(feature = "serde")]
impl serde::ser::Error for Error {
    fn custom<T>(_msg: T) -> Self
    where
        T: core::fmt::Display,
    {
        Self::Internal
    }
}

#[cfg(feature = "serde")]
impl serde::de::Error for Error {
    fn custom<T>(_msg: T) -> Self
    where
        T: core::fmt::Display,
    {
        Self::Internal
    }
}
