1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
use bytes::{Buf, BufMut};
use std::{
    convert::TryFrom,
    fmt::{self, Display},
    ops::Add,
};

use crate::webtransport::SessionId;

use super::{
    coding::{BufExt, BufMutExt, Decode, Encode, UnexpectedEnd},
    varint::VarInt,
};

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct StreamType(u64);

macro_rules! stream_types {
    {$($name:ident = $val:expr,)*} => {
        impl StreamType {
            $(pub const $name: StreamType = StreamType($val);)*
        }
    }
}

stream_types! {
    CONTROL = 0x00,
    PUSH = 0x01,
    ENCODER = 0x02,
    DECODER = 0x03,
    WEBTRANSPORT_BIDI = 0x41,
    WEBTRANSPORT_UNI = 0x54,
}

impl StreamType {
    pub const MAX_ENCODED_SIZE: usize = VarInt::MAX_SIZE;

    pub fn value(&self) -> u64 {
        self.0
    }
    /// returns a StreamType type with random number of the 0x1f * N + 0x21
    /// format within the range of the Varint implementation
    pub fn grease() -> Self {
        StreamType(fastrand::u64(0..0x210842108421083) * 0x1f + 0x21)
    }
}

impl Decode for StreamType {
    fn decode<B: Buf>(buf: &mut B) -> Result<Self, UnexpectedEnd> {
        Ok(StreamType(buf.get_var()?))
    }
}

impl Encode for StreamType {
    fn encode<W: BufMut>(&self, buf: &mut W) {
        buf.write_var(self.0);
    }
}

impl fmt::Display for StreamType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            &StreamType::CONTROL => write!(f, "Control"),
            &StreamType::ENCODER => write!(f, "Encoder"),
            &StreamType::DECODER => write!(f, "Decoder"),
            &StreamType::WEBTRANSPORT_UNI => write!(f, "WebTransportUni"),
            x => write!(f, "StreamType({})", x.0),
        }
    }
}

/// Identifier for a stream
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct StreamId(#[cfg(not(test))] u64, #[cfg(test)] pub(crate) u64);

impl fmt::Display for StreamId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let initiator = match self.initiator() {
            Side::Client => "client",
            Side::Server => "server",
        };
        let dir = match self.dir() {
            Dir::Uni => "uni",
            Dir::Bi => "bi",
        };
        write!(
            f,
            "{} {}directional stream {}",
            initiator,
            dir,
            self.index()
        )
    }
}

impl StreamId {
    pub(crate) const FIRST_REQUEST: Self = Self::new(0, Dir::Bi, Side::Client);

    /// Is this a client-initiated request?
    pub fn is_request(&self) -> bool {
        self.dir() == Dir::Bi && self.initiator() == Side::Client
    }

    /// Is this a server push?
    pub fn is_push(&self) -> bool {
        self.dir() == Dir::Uni && self.initiator() == Side::Server
    }

    /// Which side of a connection initiated the stream
    pub(crate) fn initiator(self) -> Side {
        if self.0 & 0x1 == 0 {
            Side::Client
        } else {
            Side::Server
        }
    }

    /// Create a new StreamId
    const fn new(index: u64, dir: Dir, initiator: Side) -> Self {
        StreamId((index) << 2 | (dir as u64) << 1 | initiator as u64)
    }

    /// Distinguishes streams of the same initiator and directionality
    pub fn index(self) -> u64 {
        self.0 >> 2
    }

    /// Which directions data flows in
    fn dir(self) -> Dir {
        if self.0 & 0x2 == 0 {
            Dir::Bi
        } else {
            Dir::Uni
        }
    }

    pub(crate) fn into_inner(self) -> u64 {
        self.0
    }
}

impl TryFrom<u64> for StreamId {
    type Error = InvalidStreamId;
    fn try_from(v: u64) -> Result<Self, Self::Error> {
        if v > VarInt::MAX.0 {
            return Err(InvalidStreamId(v));
        }
        Ok(Self(v))
    }
}

impl From<VarInt> for StreamId {
    fn from(v: VarInt) -> Self {
        Self(v.0)
    }
}

impl From<StreamId> for VarInt {
    fn from(v: StreamId) -> Self {
        Self(v.0)
    }
}

/// Invalid StreamId, for example because it's too large
#[derive(Debug, PartialEq)]
pub struct InvalidStreamId(pub(crate) u64);

impl Display for InvalidStreamId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid stream id: {:x}", self.0)
    }
}

impl Encode for StreamId {
    fn encode<B: bytes::BufMut>(&self, buf: &mut B) {
        VarInt::from_u64(self.0).unwrap().encode(buf);
    }
}

impl Add<usize> for StreamId {
    type Output = StreamId;

    #[allow(clippy::suspicious_arithmetic_impl)]
    fn add(self, rhs: usize) -> Self::Output {
        let index = u64::min(
            u64::saturating_add(self.index(), rhs as u64),
            VarInt::MAX.0 >> 2,
        );
        Self::new(index, self.dir(), self.initiator())
    }
}

impl From<SessionId> for StreamId {
    fn from(value: SessionId) -> Self {
        Self(value.into_inner())
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Side {
    /// The initiator of a connection
    Client = 0,
    /// The acceptor of a connection
    Server = 1,
}

/// Whether a stream communicates data in both directions or only from the initiator
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
enum Dir {
    /// Data flows in both directions
    Bi = 0,
    /// Data flows only from the stream's initiator
    Uni = 1,
}