toad_msg/msg/id.rs
1use toad_cursor::Cursor;
2
3use super::MessageParseError;
4use crate::from_bytes::TryConsumeBytes;
5#[allow(unused_imports)]
6use crate::Token;
7
8/// # Message ID
9///
10/// 16-bit unsigned integer in network byte order. Used to
11/// detect message duplication and to match messages of type
12/// Acknowledgement/Reset to messages of type Confirmable/Non-
13/// confirmable. The rules for generating a Message ID and matching
14/// messages are defined in RFC7252 Section 4
15///
16/// For a little more context and the difference between [`Id`] and [`Token`], see [`Token`].
17///
18/// See [RFC7252 - Message Details](https://datatracker.ietf.org/doc/html/rfc7252#section-3) for context
19#[derive(Copy, Clone, Hash, PartialEq, PartialOrd, Debug, Eq, Ord)]
20pub struct Id(pub u16);
21
22impl Id {
23 /// Create an Id from a big-endian 2-byte unsigned int
24 pub fn from_be_bytes(bs: [u8; 2]) -> Self {
25 Self(u16::from_be_bytes(bs))
26 }
27}
28
29impl<Bytes: AsRef<[u8]>> TryConsumeBytes<Bytes> for Id {
30 type Error = MessageParseError;
31
32 fn try_consume_bytes(bytes: &mut Cursor<Bytes>) -> Result<Self, Self::Error> {
33 match bytes.take_exact(2) {
34 | Some(&[a, b]) => Ok(Id::from_be_bytes([a, b])),
35 | _ => Err(MessageParseError::eof()),
36 }
37 }
38}