value_log/
coding.rs

1// Copyright (c) 2024-present, fjall-rs
2// This source code is licensed under both the Apache 2.0 and MIT License
3// (found in the LICENSE-* files in the repository)
4
5use std::io::{Read, Write};
6
7/// Error during serialization
8#[derive(Debug)]
9pub enum EncodeError {
10    /// I/O error
11    Io(std::io::Error),
12}
13
14impl std::fmt::Display for EncodeError {
15    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        write!(
17            f,
18            "EncodeError({})",
19            match self {
20                Self::Io(e) => e.to_string(),
21            }
22        )
23    }
24}
25
26impl From<std::io::Error> for EncodeError {
27    fn from(value: std::io::Error) -> Self {
28        Self::Io(value)
29    }
30}
31
32impl std::error::Error for EncodeError {
33    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
34        match self {
35            Self::Io(e) => Some(e),
36        }
37    }
38}
39
40/// Error during deserialization
41#[derive(Debug)]
42pub enum DecodeError {
43    /// I/O error
44    Io(std::io::Error),
45
46    Utf8(std::str::Utf8Error),
47
48    InvalidVersion,
49
50    /// Invalid enum tag
51    InvalidTag((&'static str, u8)),
52
53    InvalidTrailer,
54
55    /// Invalid block header
56    InvalidHeader(&'static str),
57}
58
59impl std::fmt::Display for DecodeError {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        write!(
62            f,
63            "DecodeError({})",
64            match self {
65                Self::Io(e) => e.to_string(),
66                e => format!("{e:?}"),
67            }
68        )
69    }
70}
71
72impl From<std::str::Utf8Error> for DecodeError {
73    fn from(value: std::str::Utf8Error) -> Self {
74        Self::Utf8(value)
75    }
76}
77
78impl From<std::io::Error> for DecodeError {
79    fn from(value: std::io::Error) -> Self {
80        Self::Io(value)
81    }
82}
83
84impl std::error::Error for DecodeError {
85    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
86        match self {
87            Self::Io(e) => Some(e),
88            _ => None,
89        }
90    }
91}
92
93/// Trait to serialize stuff
94pub trait Encode {
95    /// Serializes into writer.
96    fn encode_into<W: Write>(&self, writer: &mut W) -> Result<(), EncodeError>;
97
98    /// Serializes into vector.
99    #[allow(unused)]
100    fn encode_into_vec(&self) -> Vec<u8> {
101        let mut v = vec![];
102        self.encode_into(&mut v).expect("cannot fail");
103        v
104    }
105}
106
107/// Trait to deserialize stuff
108pub trait Decode {
109    /// Deserializes from reader.
110    fn decode_from<R: Read>(reader: &mut R) -> Result<Self, DecodeError>
111    where
112        Self: Sized;
113}