1use serde::{Deserialize, Serialize};
6use std::{fmt, io::Read};
7use thiserror::Error;
8use tls_codec::{
9 Deserialize as TlsDeserializeTrait, DeserializeBytes, Error, Serialize as TlsSerializeTrait,
10 Size,
11};
12
13#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
25#[repr(u16)]
26#[allow(missing_docs)]
27pub enum ProtocolVersion {
28 Mls10 = 1,
29 Other(u16),
30}
31
32impl Default for ProtocolVersion {
34 fn default() -> Self {
35 ProtocolVersion::Mls10
36 }
37}
38
39impl From<u16> for ProtocolVersion {
40 fn from(v: u16) -> Self {
42 match v {
43 1 => ProtocolVersion::Mls10,
44 _ => ProtocolVersion::Other(v),
45 }
46 }
47}
48
49impl TlsSerializeTrait for ProtocolVersion {
50 fn tls_serialize<W: std::io::Write>(&self, writer: &mut W) -> Result<usize, tls_codec::Error> {
51 match self {
52 ProtocolVersion::Mls10 => {
53 let v = 1u16;
54 v.tls_serialize(writer)
55 }
56 ProtocolVersion::Other(1) => Err(tls_codec::Error::EncodingError(
58 "Other(1) is encoded as 0x0001, which decodes as Mls10".to_string(),
59 )),
60 ProtocolVersion::Other(v) => v.tls_serialize(writer),
61 }
62 }
63}
64
65impl TlsDeserializeTrait for ProtocolVersion {
66 fn tls_deserialize<R: Read>(bytes: &mut R) -> Result<Self, Error>
67 where
68 Self: Sized,
69 {
70 u16::tls_deserialize(bytes).map(ProtocolVersion::from)
71 }
72}
73
74impl DeserializeBytes for ProtocolVersion {
75 fn tls_deserialize_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error>
76 where
77 Self: Sized,
78 {
79 let (v, bytes) = u16::tls_deserialize_bytes(bytes)?;
80 Ok((ProtocolVersion::from(v), bytes))
81 }
82}
83
84impl Size for ProtocolVersion {
85 fn tls_serialized_len(&self) -> usize {
86 2
87 }
88}
89
90impl fmt::Display for ProtocolVersion {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 match &self {
93 ProtocolVersion::Mls10 => write!(f, "MLS 1.0"),
94 ProtocolVersion::Other(v) => write!(f, "Other version: {v}"),
95 }
96 }
97}
98
99#[derive(Error, Debug, PartialEq, Eq, Clone)]
101pub enum VersionError {
102 #[error("Unsupported MLS version.")]
104 UnsupportedMlsVersion,
105}