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
use std::convert::TryFrom;

use crate::proto::{
    coding::{Decode, Encode},
    stream::{InvalidStreamId, StreamId},
    varint::VarInt,
};

/// Identifies a WebTransport session
///
/// The session id is the same as the stream id of the CONNECT request.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct SessionId(u64);
impl SessionId {
    pub(crate) fn from_varint(id: VarInt) -> SessionId {
        Self(id.0)
    }

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

impl TryFrom<u64> for SessionId {
    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 Encode for SessionId {
    fn encode<B: bytes::BufMut>(&self, buf: &mut B) {
        VarInt::from_u64(self.0).unwrap().encode(buf);
    }
}

impl Decode for SessionId {
    fn decode<B: bytes::Buf>(buf: &mut B) -> crate::proto::coding::Result<Self> {
        Ok(Self(VarInt::decode(buf)?.into_inner()))
    }
}

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