Skip to main content

luct_core/
version.rs

1use crate::utils::codec::{CodecError, Decode, Encode};
2use serde::{Deserialize, Serialize};
3use std::{
4    fmt::Display,
5    io::{Read, Write},
6};
7
8/// The version of the protocol, that the log supports
9///
10/// - `V1` corresponds to RFC 6962
11/// - `V2` corresponds to RFC 9162
12///
13/// Currently, only [`Version::V1`] is supported
14///
15/// See RFC 6962 3.2
16#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
17pub enum Version {
18    #[default]
19    V1,
20}
21
22impl Serialize for Version {
23    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
24    where
25        S: serde::Serializer,
26    {
27        match self {
28            Version::V1 => serializer.serialize_u8(1),
29        }
30    }
31}
32
33impl<'de> Deserialize<'de> for Version {
34    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
35    where
36        D: serde::Deserializer<'de>,
37    {
38        let version: u8 = <u8>::deserialize(deserializer)?;
39        match version {
40            1 => Ok(Version::V1),
41            x => Err(serde::de::Error::custom(format!("Unsupported version {x}"))),
42        }
43    }
44}
45
46impl Display for Version {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        match self {
49            Version::V1 => write!(f, "V1"),
50        }
51    }
52}
53
54impl Encode for Version {
55    fn encode(&self, mut writer: impl Write) -> Result<(), CodecError> {
56        let discriminant = match self {
57            Version::V1 => 0,
58        };
59        Ok(writer.write_all(&[discriminant])?)
60    }
61}
62
63impl Decode for Version {
64    fn decode(mut reader: impl Read) -> Result<Self, CodecError> {
65        let mut buf = vec![0u8];
66        reader.read_exact(&mut buf)?;
67
68        match buf[0] {
69            0 => Ok(Version::V1),
70            x => Err(CodecError::UnknownVariant("Version", x as u64)),
71        }
72    }
73}