use crate::{
packet::number::{packet_number::PacketNumber, packet_number_len::PacketNumberLen},
varint::VarInt,
};
#[cfg(any(test, feature = "generator"))]
use bolero_generator::prelude::*;
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(any(test, feature = "generator"), derive(TypeGenerator))]
#[repr(u8)]
pub enum PacketNumberSpace {
#[default]
Initial = 1,
Handshake = 2,
ApplicationData = 3,
}
impl PacketNumberSpace {
#[inline]
pub fn is_initial(self) -> bool {
matches!(self, Self::Initial)
}
#[inline]
pub fn is_handshake(self) -> bool {
matches!(self, Self::Handshake)
}
#[inline]
pub fn is_application_data(self) -> bool {
matches!(self, Self::ApplicationData)
}
#[inline]
pub const fn new_packet_number(self, value: VarInt) -> PacketNumber {
PacketNumber::from_varint(value, self)
}
#[inline]
pub fn new_packet_number_len(self, tag: u8) -> PacketNumberLen {
PacketNumberLen::from_packet_tag(tag, self)
}
#[inline(always)]
pub(crate) fn assert_eq(self, other: Self) {
debug_assert_eq!(
self, other,
"PacketNumbers cannot be compared across packet spaces"
);
}
#[inline]
pub(crate) const fn as_tag(self) -> u8 {
self as u8
}
#[inline]
pub(crate) fn from_tag(tag: u8) -> Self {
match tag {
1 => Self::Initial,
2 => Self::Handshake,
3 => Self::ApplicationData,
_ if cfg!(debug_assertions) => panic!("invalid tag for PacketNumberSpace"),
_ => Self::Initial,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trip_test() {
let spaces = [
PacketNumberSpace::Initial,
PacketNumberSpace::Handshake,
PacketNumberSpace::ApplicationData,
];
for space in spaces.iter().cloned() {
assert_eq!(PacketNumberSpace::from_tag(space.as_tag()), space);
}
}
}