Skip to main content

scale_serialization/
error.rs

1use crate::prelude::*;
2use core::fmt;
3
4/// Errors produced during SCALE encoding, decoding, or type resolution.
5#[derive(Debug)]
6pub enum Error {
7    /// End of input reached unexpectedly
8    Eof,
9    /// Type ID not found in registry
10    TypeNotFound(u32),
11    /// Variant index not found
12    InvalidVariant(u8),
13    /// Invalid UTF-8 in string data
14    InvalidUtf8,
15    /// Invalid unicode codepoint
16    InvalidChar(u32),
17    /// Bad input data
18    BadInput(String),
19    /// Unsupported type for operation
20    BadType(String),
21    /// Serialization/deserialization error
22    Ser(String),
23    /// Serializing from type to target not supported
24    NotSupported(&'static str, String),
25}
26
27impl fmt::Display for Error {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match self {
30            Error::Eof => write!(f, "unexpected end of input"),
31            Error::TypeNotFound(id) => write!(f, "type {id} not found in registry"),
32            Error::InvalidVariant(idx) => write!(f, "invalid variant index {idx}"),
33            Error::InvalidUtf8 => write!(f, "invalid UTF-8"),
34            Error::InvalidChar(code) => write!(f, "invalid char codepoint {code:#x}"),
35            Error::BadInput(msg) => write!(f, "bad input: {msg}"),
36            Error::BadType(msg) => write!(f, "unexpected type: {msg}"),
37            Error::Ser(msg) => write!(f, "{msg}"),
38            Error::NotSupported(from, to) => {
39                write!(f, "serializing {from} as {to} is not supported")
40            }
41        }
42    }
43}
44
45impl core::error::Error for Error {}
46
47impl From<fmt::Error> for Error {
48    fn from(_: fmt::Error) -> Self {
49        Error::Ser("format error".into())
50    }
51}
52
53impl serde::ser::Error for Error {
54    fn custom<T: fmt::Display>(msg: T) -> Self {
55        Error::Ser(msg.to_string())
56    }
57}