1/// A stream identifier, as described in [Section 5.1.1] of RFC 7540.
2///
3/// Streams are identified with an unsigned 31-bit integer. Streams
4/// initiated by a client MUST use odd-numbered stream identifiers; those
5/// initiated by the server MUST use even-numbered stream identifiers. A
6/// stream identifier of zero (0x0) is used for connection control
7/// messages; the stream identifier of zero cannot be used to establish a
8/// new stream.
9///
10/// [Section 5.1.1]: https://tools.ietf.org/html/rfc7540#section-5.1.1
11#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
12pub struct StreamId(u32);
1314#[derive(Debug, Copy, Clone)]
15pub struct StreamIdOverflow;
1617const STREAM_ID_MASK: u32 = 1 << 31;
1819impl StreamId {
20/// Stream ID 0.
21pub const ZERO: StreamId = StreamId(0);
2223/// The maximum allowed stream ID.
24pub const MAX: StreamId = StreamId(u32::MAX >> 1);
2526/// Parse the stream ID
27#[inline]
28pub fn parse(buf: &[u8]) -> (StreamId, bool) {
29let mut ubuf = [0; 4];
30 ubuf.copy_from_slice(&buf[0..4]);
31let unpacked = u32::from_be_bytes(ubuf);
32let flag = unpacked & STREAM_ID_MASK == STREAM_ID_MASK;
3334// Now clear the most significant bit, as that is reserved and MUST be
35 // ignored when received.
36(StreamId(unpacked & !STREAM_ID_MASK), flag)
37 }
3839/// Returns true if this stream ID corresponds to a stream that
40 /// was initiated by the client.
41pub fn is_client_initiated(&self) -> bool {
42let id = self.0;
43 id != 0 && id % 2 == 1
44}
4546/// Returns true if this stream ID corresponds to a stream that
47 /// was initiated by the server.
48pub fn is_server_initiated(&self) -> bool {
49let id = self.0;
50 id != 0 && id % 2 == 0
51}
5253/// Return a new `StreamId` for stream 0.
54#[inline]
55pub fn zero() -> StreamId {
56 StreamId::ZERO
57 }
5859/// Returns true if this stream ID is zero.
60pub fn is_zero(&self) -> bool {
61self.0 == 0
62}
6364/// Returns the next stream ID initiated by the same peer as this stream
65 /// ID, or an error if incrementing this stream ID would overflow the
66 /// maximum.
67pub fn next_id(&self) -> Result<StreamId, StreamIdOverflow> {
68let next = self.0 + 2;
69if next > StreamId::MAX.0 {
70Err(StreamIdOverflow)
71 } else {
72Ok(StreamId(next))
73 }
74 }
75}
7677impl From<u32> for StreamId {
78fn from(src: u32) -> Self {
79assert_eq!(src & STREAM_ID_MASK, 0, "invalid stream ID -- MSB is set");
80 StreamId(src)
81 }
82}
8384impl From<StreamId> for u32 {
85fn from(src: StreamId) -> Self {
86 src.0
87}
88}
8990impl PartialEq<u32> for StreamId {
91fn eq(&self, other: &u32) -> bool {
92self.0 == *other
93 }
94}