lsm_tree/
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    /// Unsupported/outdated disk version
47    InvalidVersion,
48
49    /// Invalid enum tag
50    InvalidTag((&'static str, u8)),
51
52    /// Invalid block trailer
53    InvalidTrailer,
54
55    /// Invalid block header
56    InvalidHeader(&'static str),
57
58    /// UTF-8 error
59    Utf8(std::str::Utf8Error),
60}
61
62impl std::fmt::Display for DecodeError {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        write!(
65            f,
66            "DecodeError({})",
67            match self {
68                Self::Io(e) => e.to_string(),
69                e => format!("{e:?}"),
70            }
71        )
72    }
73}
74
75impl From<std::str::Utf8Error> for DecodeError {
76    fn from(value: std::str::Utf8Error) -> Self {
77        Self::Utf8(value)
78    }
79}
80
81impl From<std::io::Error> for DecodeError {
82    fn from(value: std::io::Error) -> Self {
83        Self::Io(value)
84    }
85}
86
87impl std::error::Error for DecodeError {
88    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
89        match self {
90            Self::Io(e) => Some(e),
91            _ => None,
92        }
93    }
94}
95
96/// Trait to serialize stuff
97pub trait Encode {
98    /// Serializes into writer.
99    fn encode_into<W: Write>(&self, writer: &mut W) -> Result<(), EncodeError>;
100
101    /// Serializes into vector.
102    #[allow(unused)]
103    fn encode_into_vec(&self) -> Vec<u8> {
104        let mut v = vec![];
105        self.encode_into(&mut v).expect("cannot fail");
106        v
107    }
108}
109
110/// Trait to deserialize stuff
111pub trait Decode {
112    /// Deserializes from reader.
113    fn decode_from<R: Read>(reader: &mut R) -> Result<Self, DecodeError>
114    where
115        Self: Sized;
116}