1use std::u32;
23/// A stream identifier, as described in [Section 5.1.1] of RFC 7540.
4///
5/// Streams are identified with an unsigned 31-bit integer. Streams
6/// initiated by a client MUST use odd-numbered stream identifiers; those
7/// initiated by the server MUST use even-numbered stream identifiers. A
8/// stream identifier of zero (0x0) is used for connection control
9/// messages; the stream identifier of zero cannot be used to establish a
10/// new stream.
11///
12/// [Section 5.1.1]: https://tools.ietf.org/html/rfc7540#section-5.1.1
13#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
14pub struct StreamId(u32);
1516#[derive(Debug, Copy, Clone)]
17pub struct StreamIdOverflow;
1819const STREAM_ID_MASK: u32 = 1 << 31;
2021impl StreamId {
22/// Stream ID 0.
23pub const ZERO: StreamId = StreamId(0);
2425/// The maximum allowed stream ID.
26pub const MAX: StreamId = StreamId(u32::MAX >> 1);
2728/// Parse the stream ID
29#[inline]
30pub fn parse(buf: &[u8]) -> (StreamId, bool) {
31let mut ubuf = [0; 4];
32 ubuf.copy_from_slice(&buf[0..4]);
33let unpacked = u32::from_be_bytes(ubuf);
34let flag = unpacked & STREAM_ID_MASK == STREAM_ID_MASK;
3536// Now clear the most significant bit, as that is reserved and MUST be
37 // ignored when received.
38(StreamId(unpacked & !STREAM_ID_MASK), flag)
39 }
4041/// Returns true if this stream ID corresponds to a stream that
42 /// was initiated by the client.
43pub fn is_client_initiated(&self) -> bool {
44let id = self.0;
45 id != 0 && id % 2 == 1
46}
4748/// Returns true if this stream ID corresponds to a stream that
49 /// was initiated by the server.
50pub fn is_server_initiated(&self) -> bool {
51let id = self.0;
52 id != 0 && id % 2 == 0
53}
5455/// Return a new `StreamId` for stream 0.
56#[inline]
57pub fn zero() -> StreamId {
58 StreamId::ZERO
59 }
6061/// Returns true if this stream ID is zero.
62pub fn is_zero(&self) -> bool {
63self.0 == 0
64}
6566/// Returns the next stream ID initiated by the same peer as this stream
67 /// ID, or an error if incrementing this stream ID would overflow the
68 /// maximum.
69pub fn next_id(&self) -> Result<StreamId, StreamIdOverflow> {
70let next = self.0 + 2;
71if next > StreamId::MAX.0 {
72Err(StreamIdOverflow)
73 } else {
74Ok(StreamId(next))
75 }
76 }
77}
7879impl From<u32> for StreamId {
80fn from(src: u32) -> Self {
81assert_eq!(src & STREAM_ID_MASK, 0, "invalid stream ID -- MSB is set");
82 StreamId(src)
83 }
84}
8586impl From<StreamId> for u32 {
87fn from(src: StreamId) -> Self {
88 src.0
89}
90}
9192impl PartialEq<u32> for StreamId {
93fn eq(&self, other: &u32) -> bool {
94self.0 == *other
95 }
96}