use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ProtocolVersion(pub u32);
impl ProtocolVersion {
pub const fn new(version: u32) -> Self {
Self(version)
}
pub const fn get(self) -> u32 {
self.0
}
}
impl From<u32> for ProtocolVersion {
fn from(value: u32) -> Self {
Self(value)
}
}
impl std::fmt::Display for ProtocolVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
pub const CURRENT_VERSION: ProtocolVersion = ProtocolVersion(1);
const _: () = assert!(CURRENT_VERSION.0 >= 1, "CURRENT_VERSION must be >= 1");
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SupportedVersions {
min: ProtocolVersion,
max: ProtocolVersion,
}
impl SupportedVersions {
pub const fn current() -> Self {
let max = CURRENT_VERSION.0;
let min = if max > 1 { max - 1 } else { 1 };
Self {
min: ProtocolVersion(min),
max: ProtocolVersion(max),
}
}
pub const fn new(
min: ProtocolVersion,
max: ProtocolVersion,
) -> Result<Self, SupportedVersionsError> {
if min.0 < 1 {
return Err(SupportedVersionsError::MinVersionZero);
}
if min.0 > max.0 {
return Err(SupportedVersionsError::InvertedRange);
}
if max.0 > CURRENT_VERSION.0 {
return Err(SupportedVersionsError::MaxAboveCurrent);
}
Ok(Self { min, max })
}
pub const fn min(self) -> ProtocolVersion {
self.min
}
pub const fn max(self) -> ProtocolVersion {
self.max
}
pub const fn contains(self, version: ProtocolVersion) -> bool {
version.0 >= self.min.0 && version.0 <= self.max.0
}
}
impl Default for SupportedVersions {
fn default() -> Self {
Self::current()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum SupportedVersionsError {
#[error("supported-version range floor must be >= 1 (version 0 does not exist)")]
MinVersionZero,
#[error("supported-version range is inverted: min must not exceed max")]
InvertedRange,
#[error("supported-version range max must not exceed the current protocol version")]
MaxAboveCurrent,
}
#[cfg(test)]
#[path = "version_tests.rs"]
mod tests;