mcproto_rs/
serialize.rs

1use alloc::{string::String, fmt};
2
3pub enum SerializeErr {
4    FailedJsonEncode(String),
5    CannotSerialize(String),
6}
7
8impl fmt::Display for SerializeErr {
9    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10        use SerializeErr::*;
11        match self {
12            FailedJsonEncode(data) => {
13                f.write_fmt(format_args!("failed to serialize json: {:?}", data))
14            }
15            CannotSerialize(message) => {
16                f.write_fmt(format_args!("cannot serialize value, invalid representation: {:?}", message))
17            }
18        }
19    }
20}
21
22impl fmt::Debug for SerializeErr {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        <dyn fmt::Display>::fmt(self, f)
25    }
26}
27
28#[cfg(feature = "std")]
29impl std::error::Error for SerializeErr {}
30
31pub type SerializeResult = Result<(), SerializeErr>;
32
33pub trait Serialize: Sized {
34    fn mc_serialize<S: Serializer>(&self, to: &mut S) -> SerializeResult;
35}
36
37pub trait Serializer: Sized {
38    fn serialize_bytes(&mut self, data: &[u8]) -> SerializeResult;
39
40    fn serialize_byte(&mut self, byte: u8) -> SerializeResult {
41        self.serialize_bytes(&[byte])
42    }
43
44    fn serialize_other<S: Serialize>(&mut self, other: &S) -> SerializeResult {
45        other.mc_serialize(self)
46    }
47}