1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright 2020-2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use core::ops::{Add, Deref, Sub};

use bee_common::packable::{Packable, Read, Write};

/// A wrapper around a `u32` that represents a milestone index.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MilestoneIndex(pub u32);

impl MilestoneIndex {
    /// Creates a new `MilestoneIndex`.
    pub fn new(value: u32) -> Self {
        Self(value)
    }
}

impl std::fmt::Display for MilestoneIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl Deref for MilestoneIndex {
    type Target = u32;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<u32> for MilestoneIndex {
    fn from(v: u32) -> Self {
        Self(v)
    }
}

impl Add for MilestoneIndex {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self(*self + *other)
    }
}

impl Add<u32> for MilestoneIndex {
    type Output = Self;

    fn add(self, other: u32) -> Self {
        Self(*self + other)
    }
}

impl Sub for MilestoneIndex {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        Self(*self - *other)
    }
}

impl Sub<u32> for MilestoneIndex {
    type Output = Self;

    fn sub(self, other: u32) -> Self {
        Self(*self - other)
    }
}

impl Packable for MilestoneIndex {
    type Error = std::io::Error;

    fn packed_len(&self) -> usize {
        self.0.packed_len()
    }

    fn pack<W: Write>(&self, writer: &mut W) -> Result<(), Self::Error> {
        self.0.pack(writer)
    }

    fn unpack_inner<R: Read + ?Sized, const CHECK: bool>(reader: &mut R) -> Result<Self, Self::Error> {
        Ok(Self::new(u32::unpack_inner::<R, CHECK>(reader)?))
    }
}