1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//! Contains the Error and Result type used by the deserializer.
use std::fmt::Display;

/// Various errors that can occur during deserialization.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error(String);

/// Convenience type for Result.
pub type Result<T> = std::result::Result<T, Error>;

impl std::error::Error for Error {}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl serde::de::Error for Error {
    fn custom<T: Display>(msg: T) -> Self {
        Error(msg.to_string())
    }
}

// TODO: Separate error types for ser and de?
impl serde::ser::Error for Error {
    fn custom<T>(msg: T) -> Self
    where
        T: Display,
    {
        Error(msg.to_string())
    }
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Error(format!("io error: {}", e))
    }
}

impl Error {
    pub(crate) fn invalid_tag(tag: u8) -> Error {
        Error(format!("invalid nbt tag value: {}", tag))
    }

    pub(crate) fn no_root_compound() -> Error {
        Error("invalid nbt: no root compound".to_owned())
    }

    pub(crate) fn nonunicode_string(data: &[u8]) -> Error {
        Error(format!(
            "invalid nbt string: nonunicode: {}",
            String::from_utf8_lossy(data)
        ))
    }

    pub(crate) fn unexpected_eof() -> Error {
        Error("eof: unexpectedly ran out of input".to_owned())
    }

    pub(crate) fn array_as_seq() -> Error {
        Error("expected NBT Array, found seq: use ByteArray, IntArray or LongArray types".into())
    }

    pub(crate) fn array_as_other() -> Error {
        Error("expected NBT Array: use ByteArray, IntArray or LongArray types".into())
    }

    pub(crate) fn bespoke(msg: String) -> Error {
        Error(msg)
    }
}