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
use crate::Error;
use bee_common::packable::{Packable, Read, Write};
use core::str::FromStr;
pub const MESSAGE_ID_LENGTH: usize = 32;
#[derive(Clone, Copy, Eq, Hash, PartialEq, Ord, PartialOrd)]
pub struct MessageId([u8; MESSAGE_ID_LENGTH]);
impl MessageId {
pub fn new(bytes: [u8; MESSAGE_ID_LENGTH]) -> Self {
bytes.into()
}
pub fn null() -> Self {
Self([0u8; MESSAGE_ID_LENGTH])
}
}
#[cfg(feature = "serde")]
string_serde_impl!(MessageId);
impl From<[u8; MESSAGE_ID_LENGTH]> for MessageId {
fn from(bytes: [u8; MESSAGE_ID_LENGTH]) -> Self {
Self(bytes)
}
}
impl FromStr for MessageId {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let bytes: [u8; MESSAGE_ID_LENGTH] = hex::decode(s)
.map_err(|_| Self::Err::InvalidHexadecimalChar(s.to_owned()))?
.try_into()
.map_err(|_| Self::Err::InvalidHexadecimalLength(MESSAGE_ID_LENGTH * 2, s.len()))?;
Ok(MessageId::from(bytes))
}
}
impl AsRef<[u8]> for MessageId {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl core::fmt::Display for MessageId {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "{}", hex::encode(self.0))
}
}
impl core::fmt::Debug for MessageId {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "MessageId({})", self)
}
}
impl Packable for MessageId {
type Error = Error;
fn packed_len(&self) -> usize {
MESSAGE_ID_LENGTH
}
fn pack<W: Write>(&self, writer: &mut W) -> Result<(), Self::Error> {
self.0.pack(writer)?;
Ok(())
}
fn unpack_inner<R: Read + ?Sized, const CHECK: bool>(reader: &mut R) -> Result<Self, Self::Error> {
Ok(Self::new(<[u8; MESSAGE_ID_LENGTH]>::unpack_inner::<R, CHECK>(reader)?))
}
}