aboutsummaryrefslogtreecommitdiff
path: root/src/serialize.rs
blob: 197b92c3b0699eebb3cebd746471756fb7366a81 (plain)
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
use alloc::{string::String, fmt};

pub enum SerializeErr {
    FailedJsonEncode(String),
    CannotSerialize(String),
}

impl fmt::Display for SerializeErr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use SerializeErr::*;
        match self {
            FailedJsonEncode(data) => {
                f.write_fmt(format_args!("failed to serialize json: {:?}", data))
            }
            CannotSerialize(message) => {
                f.write_fmt(format_args!("cannot serialize value, invalid representation: {:?}", message))
            }
        }
    }
}

impl fmt::Debug for SerializeErr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        <dyn fmt::Display>::fmt(self, f)
    }
}

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

pub type SerializeResult = Result<(), SerializeErr>;

pub trait Serialize: Sized {
    fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult;
}

pub trait Serializer: Sized {
    fn serialize_bytes(&mut self, data: &[u8]) -> SerializeResult;

    fn serialize_byte(&mut self, byte: u8) -> SerializeResult {
        self.serialize_bytes(&[byte])
    }

    fn serialize_other<S: Serialize>(&mut self, other: &S) -> SerializeResult {
        other.mc_serialize(self)
    }
}