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
32/// Error during deserialization
33#[derive(Debug)]
34pub enum DecodeError {
35    /// I/O error
36    Io(std::io::Error),
37
38    Utf8(std::str::Utf8Error),
39
40    InvalidVersion,
41
42    /// Invalid enum tag
43    InvalidTag((&'static str, u8)),
44
45    /// Invalid block header
46    InvalidTrailer,
47
48    InvalidHeader(&'static str),
49}
50
51impl std::fmt::Display for DecodeError {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        write!(
54            f,
55            "DecodeError({})",
56            match self {
57                Self::Io(e) => e.to_string(),
58                e => format!("{e:?}"),
59            }
60        )
61    }
62}
63
64impl From<std::io::Error> for DecodeError {
65    fn from(value: std::io::Error) -> Self {
66        Self::Io(value)
67    }
68}
69
70impl From<std::str::Utf8Error> for DecodeError {
71    fn from(value: std::str::Utf8Error) -> Self {
72        Self::Utf8(value)
73    }
74}
75
76/// Trait to serialize stuff
77pub trait Encode {
78    /// Serializes into writer.
79    fn encode_into<W: Write>(&self, writer: &mut W) -> Result<(), EncodeError>;
80
81    /// Serializes into vector.
82    fn encode_into_vec(&self) -> Vec<u8> {
83        let mut v = vec![];
84
85        #[allow(clippy::expect_used)]
86        self.encode_into(&mut v).expect("cannot fail");
87
88        v
89    }
90}
91
92/// Trait to deserialize stuff
93pub trait Decode {
94    /// Deserializes from reader.
95    fn decode_from<R: Read>(reader: &mut R) -> Result<Self, DecodeError>
96    where
97        Self: Sized;
98}