Skip to main content

moq_lite/coding/
version.rs

1use crate::coding::*;
2
3use std::{fmt, ops::Deref};
4
5/// A version number negotiated during the setup.
6#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
7pub struct Version(pub u64);
8
9impl From<u64> for Version {
10	fn from(v: u64) -> Self {
11		Self(v)
12	}
13}
14
15impl From<Version> for u64 {
16	fn from(v: Version) -> Self {
17		v.0
18	}
19}
20
21impl<V: Copy> Decode<V> for Version
22where
23	u64: Decode<V>,
24{
25	/// Decode the version number.
26	fn decode<R: bytes::Buf>(r: &mut R, version: V) -> Result<Self, DecodeError> {
27		let v = u64::decode(r, version)?;
28		Ok(Self(v))
29	}
30}
31
32impl<V: Copy> Encode<V> for Version
33where
34	u64: Encode<V>,
35{
36	fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) -> Result<(), EncodeError> {
37		self.0.encode(w, version)
38	}
39}
40
41impl fmt::Debug for Version {
42	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43		self.0.fmt(f)
44	}
45}
46
47/// A list of versions in preferred order.
48#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
49pub struct Versions(Vec<Version>);
50
51impl<V: Copy> Decode<V> for Versions
52where
53	u64: Decode<V>,
54{
55	/// Decode the version list.
56	fn decode<R: bytes::Buf>(r: &mut R, version: V) -> Result<Self, DecodeError> {
57		let count = u64::decode(r, version)?;
58		let mut vs = Vec::new();
59
60		for _ in 0..count {
61			let v = Version::decode(r, version)?;
62			vs.push(v);
63		}
64
65		Ok(Self(vs))
66	}
67}
68
69impl<V: Copy> Encode<V> for Versions
70where
71	u64: Encode<V>,
72{
73	/// Encode the version list.
74	fn encode<W: bytes::BufMut>(&self, w: &mut W, version: V) -> Result<(), EncodeError> {
75		(self.0.len() as u64).encode(w, version)?;
76
77		for v in &self.0 {
78			v.encode(w, version)?;
79		}
80		Ok(())
81	}
82}
83
84impl Deref for Versions {
85	type Target = Vec<Version>;
86
87	fn deref(&self) -> &Self::Target {
88		&self.0
89	}
90}
91
92impl From<Vec<Version>> for Versions {
93	fn from(vs: Vec<Version>) -> Self {
94		Self(vs)
95	}
96}
97
98impl<const N: usize> From<[Version; N]> for Versions {
99	fn from(vs: [Version; N]) -> Self {
100		Self(vs.to_vec())
101	}
102}
103
104impl fmt::Debug for Versions {
105	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106		f.debug_list().entries(self.0.iter()).finish()
107	}
108}