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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
use crate::att::{AttError, ErrorCode};
use crate::{bytes::*, Error};
use core::{fmt, ops::RangeInclusive};
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Handle(u16);
impl Handle {
pub const NULL: Self = Handle(0x0000);
pub fn as_u16(&self) -> u16 {
self.0
}
pub fn from_raw(raw: u16) -> Self {
Handle(raw)
}
}
impl fmt::Debug for Handle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:#06X}", self.0)
}
}
impl FromBytes<'_> for Handle {
fn from_bytes(bytes: &mut ByteReader<'_>) -> Result<Self, Error> {
Ok(Handle(bytes.read_u16_le()?))
}
}
impl ToBytes for Handle {
fn to_bytes(&self, writer: &mut ByteWriter<'_>) -> Result<(), Error> {
writer.write_u16_le(self.as_u16())?;
Ok(())
}
}
#[derive(Debug, Copy, Clone)]
pub struct RawHandleRange {
start: Handle,
end: Handle,
}
impl RawHandleRange {
pub fn check(&self) -> Result<HandleRange, AttError> {
if self.start.0 > self.end.0 || self.start.0 == 0 {
Err(AttError::new(ErrorCode::InvalidHandle, self.start))
} else {
Ok(HandleRange(self.start..=self.end))
}
}
}
impl FromBytes<'_> for RawHandleRange {
fn from_bytes(bytes: &mut ByteReader<'_>) -> Result<Self, Error> {
Ok(Self {
start: Handle::from_bytes(bytes)?,
end: Handle::from_bytes(bytes)?,
})
}
}
impl ToBytes for RawHandleRange {
fn to_bytes(&self, writer: &mut ByteWriter<'_>) -> Result<(), Error> {
writer.write_u16_le(self.start.as_u16())?;
writer.write_u16_le(self.end.as_u16())?;
Ok(())
}
}
#[derive(Debug)]
pub struct HandleRange(RangeInclusive<Handle>);
impl HandleRange {
pub fn new(from: Handle, to: Handle) -> Self {
HandleRange(from..=to)
}
pub fn contains(&self, handle: Handle) -> bool {
self.0.start().0 <= handle.as_u16() && self.0.end().0 >= handle.as_u16()
}
pub fn start(&self) -> Handle {
*self.0.start()
}
pub fn end(&self) -> Handle {
*self.0.end()
}
}