ntex_h2/frame/
stream_id.rs1#[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 CON: StreamId = StreamId(0);
22
23 pub const CLIENT: StreamId = StreamId(1);
25
26 pub const MAX: StreamId = StreamId(u32::MAX >> 1);
28
29 #[inline]
31 pub fn parse(buf: &[u8]) -> (StreamId, bool) {
32 let mut ubuf = [0; 4];
33 ubuf.copy_from_slice(&buf[0..4]);
34 let unpacked = u32::from_be_bytes(ubuf);
35 let flag = unpacked & STREAM_ID_MASK == STREAM_ID_MASK;
36
37 (StreamId(unpacked & !STREAM_ID_MASK), flag)
40 }
41
42 pub const fn is_client_initiated(&self) -> bool {
45 let id = self.0;
46 id != 0 && id % 2 == 1
47 }
48
49 pub const fn is_server_initiated(&self) -> bool {
52 let id = self.0;
53 id != 0 && id % 2 == 0
54 }
55
56 #[inline]
58 pub const fn zero() -> StreamId {
59 StreamId::CON
60 }
61
62 pub const fn is_zero(&self) -> bool {
64 self.0 == 0
65 }
66
67 pub const fn next_id(&self) -> Result<StreamId, StreamIdOverflow> {
71 let next = self.0 + 2;
72 if next > StreamId::MAX.0 {
73 Err(StreamIdOverflow)
74 } else {
75 Ok(StreamId(next))
76 }
77 }
78}
79
80impl From<u32> for StreamId {
81 fn from(src: u32) -> Self {
82 assert_eq!(src & STREAM_ID_MASK, 0, "invalid stream ID -- MSB is set");
83 StreamId(src)
84 }
85}
86
87impl From<StreamId> for u32 {
88 fn from(src: StreamId) -> Self {
89 src.0
90 }
91}
92
93impl PartialEq<u32> for StreamId {
94 fn eq(&self, other: &u32) -> bool {
95 self.0 == *other
96 }
97}