1#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
12pub struct StreamId(u32);
13
14#[derive(Debug, Copy, Clone)]
15pub struct StreamIdOverflow;
16
17const STREAM_ID_MASK: u32 = 1 << 31;
18
19impl StreamId {
20 pub const ZERO: StreamId = StreamId(0);
22
23 pub const MAX: StreamId = StreamId(u32::MAX >> 1);
25
26 #[inline]
28 pub fn parse(buf: &[u8]) -> (StreamId, bool) {
29 let mut ubuf = [0; 4];
30 ubuf.copy_from_slice(&buf[0..4]);
31 let unpacked = u32::from_be_bytes(ubuf);
32 let flag = unpacked & STREAM_ID_MASK == STREAM_ID_MASK;
33
34 (StreamId(unpacked & !STREAM_ID_MASK), flag)
37 }
38
39 pub fn is_client_initiated(&self) -> bool {
42 let id = self.0;
43 id != 0 && id % 2 == 1
44 }
45
46 pub fn is_server_initiated(&self) -> bool {
49 let id = self.0;
50 id != 0 && id % 2 == 0
51 }
52
53 #[inline]
55 pub fn zero() -> StreamId {
56 StreamId::ZERO
57 }
58
59 pub fn is_zero(&self) -> bool {
61 self.0 == 0
62 }
63
64 pub fn next_id(&self) -> Result<StreamId, StreamIdOverflow> {
68 let next = self.0 + 2;
69 if next > StreamId::MAX.0 {
70 Err(StreamIdOverflow)
71 } else {
72 Ok(StreamId(next))
73 }
74 }
75}
76
77impl From<u32> for StreamId {
78 fn from(src: u32) -> Self {
79 assert_eq!(src & STREAM_ID_MASK, 0, "invalid stream ID -- MSB is set");
80 StreamId(src)
81 }
82}
83
84impl From<StreamId> for u32 {
85 fn from(src: StreamId) -> Self {
86 src.0
87 }
88}
89
90impl PartialEq<u32> for StreamId {
91 fn eq(&self, other: &u32) -> bool {
92 self.0 == *other
93 }
94}