Skip to main content

amaru_protocols/protocol_messages/
version_number.rs

1// Copyright 2025 PRAGMA
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use amaru_kernel::cbor;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
18pub struct VersionNumber(u64);
19
20impl From<u64> for VersionNumber {
21    fn from(value: u64) -> Self {
22        Self(value)
23    }
24}
25
26impl From<VersionNumber> for u64 {
27    fn from(value: VersionNumber) -> Self {
28        value.0
29    }
30}
31
32impl AsRef<VersionNumber> for VersionNumber {
33    fn as_ref(&self) -> &VersionNumber {
34        self
35    }
36}
37
38impl VersionNumber {
39    pub const V11: VersionNumber = VersionNumber::new(11);
40    pub const V12: VersionNumber = VersionNumber::new(12);
41    pub const V13: VersionNumber = VersionNumber::new(13);
42    pub const V14: VersionNumber = VersionNumber::new(14);
43
44    pub const fn new(value: u64) -> Self {
45        Self(value)
46    }
47
48    pub const fn as_u64(self) -> u64 {
49        self.0
50    }
51
52    pub const fn has_query_and_peer_sharing(self) -> bool {
53        self.0 >= 11
54    }
55}
56
57impl<C> cbor::Encode<C> for VersionNumber {
58    fn encode<W: cbor::encode::Write>(
59        &self,
60        e: &mut cbor::Encoder<W>,
61        ctx: &mut C,
62    ) -> Result<(), cbor::encode::Error<W::Error>> {
63        self.0.encode(e, ctx)
64    }
65}
66
67impl<'b, C> cbor::Decode<'b, C> for VersionNumber {
68    fn decode(d: &mut cbor::Decoder<'b>, ctx: &mut C) -> Result<Self, cbor::decode::Error> {
69        u64::decode(d, ctx).map(VersionNumber)
70    }
71}
72
73#[cfg(test)]
74pub(crate) mod tests {
75    use amaru_kernel::prop_cbor_roundtrip;
76    use proptest::{
77        prelude::{Just, Strategy},
78        prop_oneof,
79    };
80
81    use crate::protocol_messages::version_number::VersionNumber;
82
83    prop_cbor_roundtrip!(VersionNumber, any_version_number());
84
85    pub fn any_version_number() -> impl Strategy<Value = VersionNumber> {
86        prop_oneof![
87            1 => Just(VersionNumber::V11),
88            1 => Just(VersionNumber::V12),
89            1 => Just(VersionNumber::V13),
90            1 => Just(VersionNumber::V14),
91        ]
92    }
93}