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