use core::fmt;
use core::str::FromStr;
use oxicode::de::{Decode, Decoder};
use oxicode::enc::{Encode, Encoder};
use semver::Version;
use serde::{Deserialize, Deserializer, Serialize};
use crate::error::codec_invalid;
pub const PROTOCOL_VERSION: u16 = 1;
pub const MIN_SUPPORTED_PROTOCOL: u16 = 1;
const _: () = assert!(
MIN_SUPPORTED_PROTOCOL <= PROTOCOL_VERSION,
"the oldest accepted protocol cannot be newer than the one we speak"
);
const _: () = assert!(
PROTOCOL_VERSION >= 1,
"protocol 0 is not a released version"
);
pub const ASTRS_VERSION_STR: &str = env!("CARGO_PKG_VERSION");
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ProtocolMismatch {
#[error("peer speaks protocol {peer}, below the minimum supported {minimum}")]
TooOld {
peer: u16,
minimum: u16,
},
}
pub const fn negotiate_protocol(peer: u16) -> Result<u16, ProtocolMismatch> {
if peer < MIN_SUPPORTED_PROTOCOL {
return Err(ProtocolMismatch::TooOld {
peer,
minimum: MIN_SUPPORTED_PROTOCOL,
});
}
Ok(if peer < PROTOCOL_VERSION {
peer
} else {
PROTOCOL_VERSION
})
}
#[must_use]
pub const fn supports_protocol(protocol: u16) -> bool {
protocol >= MIN_SUPPORTED_PROTOCOL && protocol <= PROTOCOL_VERSION
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct AstrsVersion(Version);
impl AstrsVersion {
#[must_use]
pub fn current() -> Self {
Self(Version::parse(ASTRS_VERSION_STR).unwrap_or_else(|_| Version::new(0, 0, 0)))
}
#[must_use]
pub const fn new(version: Version) -> Self {
Self(version)
}
#[must_use]
pub fn from_parts(major: u64, minor: u64, patch: u64) -> Self {
Self(Version::new(major, minor, patch))
}
pub fn parse(text: &str) -> Result<Self, semver::Error> {
Ok(Self(Version::parse(text)?))
}
#[must_use]
pub const fn as_version(&self) -> &Version {
&self.0
}
#[must_use]
pub fn into_version(self) -> Version {
self.0
}
#[must_use]
pub const fn major(&self) -> u64 {
self.0.major
}
#[must_use]
pub const fn minor(&self) -> u64 {
self.0.minor
}
#[must_use]
pub const fn patch(&self) -> u64 {
self.0.patch
}
#[must_use]
pub fn is_prerelease(&self) -> bool {
!self.0.pre.is_empty()
}
#[must_use]
pub fn is_compatible_with(&self, other: &Self) -> bool {
if self.major() != other.major() {
return false;
}
self.major() != 0 || self.minor() == other.minor()
}
}
impl fmt::Display for AstrsVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl fmt::Debug for AstrsVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "AstrsVersion({})", self.0)
}
}
impl Default for AstrsVersion {
fn default() -> Self {
Self::current()
}
}
impl FromStr for AstrsVersion {
type Err = semver::Error;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Self::parse(text)
}
}
impl From<Version> for AstrsVersion {
fn from(version: Version) -> Self {
Self(version)
}
}
impl From<AstrsVersion> for Version {
fn from(version: AstrsVersion) -> Self {
version.0
}
}
impl<'de> Deserialize<'de> for AstrsVersion {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(Self(Version::deserialize(deserializer)?))
}
}
impl Encode for AstrsVersion {
fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), oxicode::error::Error> {
self.0.to_string().encode(encoder)
}
}
impl<Context> Decode<Context> for AstrsVersion {
fn decode<D: Decoder<Context = Context>>(
decoder: &mut D,
) -> Result<Self, oxicode::error::Error> {
let text = String::decode(decoder)?;
if text.len() > MAX_VERSION_TEXT_LEN {
return Err(codec_invalid(format!(
"version string of {} bytes exceeds the {MAX_VERSION_TEXT_LEN}-byte limit",
text.len()
)));
}
Version::parse(&text)
.map(Self)
.map_err(|err| codec_invalid(format!("invalid semver `{text}`: {err}")))
}
}
pub const MAX_VERSION_TEXT_LEN: usize = 128;
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use crate::codec::{WireDecode, WireEncode};
#[test]
fn protocol_constants_are_coherent() {
assert!(supports_protocol(MIN_SUPPORTED_PROTOCOL));
assert!(supports_protocol(PROTOCOL_VERSION));
assert!(!supports_protocol(PROTOCOL_VERSION + 1));
}
#[test]
fn negotiation_meets_at_the_lower_version() {
assert_eq!(
negotiate_protocol(PROTOCOL_VERSION).unwrap(),
PROTOCOL_VERSION
);
assert_eq!(negotiate_protocol(u16::MAX).unwrap(), PROTOCOL_VERSION);
assert_eq!(
negotiate_protocol(MIN_SUPPORTED_PROTOCOL).unwrap(),
MIN_SUPPORTED_PROTOCOL
);
}
#[test]
fn negotiation_refuses_versions_below_the_floor() {
for peer in 0..MIN_SUPPORTED_PROTOCOL {
match negotiate_protocol(peer) {
Err(ProtocolMismatch::TooOld { peer: p, minimum }) => {
assert_eq!(p, peer);
assert_eq!(minimum, MIN_SUPPORTED_PROTOCOL);
}
other => panic!("protocol {peer} should be refused, got {other:?}"),
}
}
}
#[test]
fn support_predicate_matches_negotiation() {
for protocol in 0..=(PROTOCOL_VERSION + 3) {
let negotiable = negotiate_protocol(protocol)
.map(|agreed| agreed == protocol)
.unwrap_or(false);
assert_eq!(
supports_protocol(protocol),
negotiable,
"protocol {protocol}"
);
}
}
#[test]
fn current_matches_the_package_version() {
assert_eq!(AstrsVersion::current().to_string(), ASTRS_VERSION_STR);
assert_eq!(AstrsVersion::default(), AstrsVersion::current());
assert!(AstrsVersion::current() > AstrsVersion::from_parts(0, 0, 0));
}
#[test]
fn components_are_exposed() {
let version = AstrsVersion::parse("2.3.4-rc.1+meta").unwrap();
assert_eq!(version.major(), 2);
assert_eq!(version.minor(), 3);
assert_eq!(version.patch(), 4);
assert!(version.is_prerelease());
assert!(!AstrsVersion::from_parts(2, 3, 4).is_prerelease());
assert_eq!(version.as_version().major, 2);
assert_eq!(Version::from(version.clone()), version.into_version());
}
#[test]
fn compatibility_follows_cargo_semver_rules() {
let zero_one = AstrsVersion::from_parts(0, 1, 0);
assert!(zero_one.is_compatible_with(&AstrsVersion::from_parts(0, 1, 9)));
assert!(!zero_one.is_compatible_with(&AstrsVersion::from_parts(0, 2, 0)));
assert!(!zero_one.is_compatible_with(&AstrsVersion::from_parts(1, 1, 0)));
let one_two = AstrsVersion::from_parts(1, 2, 0);
assert!(one_two.is_compatible_with(&AstrsVersion::from_parts(1, 9, 9)));
assert!(!one_two.is_compatible_with(&AstrsVersion::from_parts(2, 0, 0)));
}
#[test]
fn codec_preserves_prerelease_and_build_metadata() {
for text in [
"0.1.0",
"0.1.0-rc.1",
"0.1.0+build.7",
"1.0.0-alpha.1+sha.abcdef",
"18446744073709551615.0.0",
] {
let version = AstrsVersion::parse(text).unwrap();
let bytes = version.encode_to_vec().unwrap();
let decoded = AstrsVersion::decode_exact(&bytes).unwrap();
assert_eq!(decoded, version);
assert_eq!(decoded.to_string(), text);
}
}
#[test]
fn decoding_rejects_a_non_semver_string() {
let hostile = "not.a.version".to_owned().encode_to_vec().unwrap();
assert!(AstrsVersion::decode_exact(&hostile).is_err());
}
#[test]
fn decoding_rejects_an_oversize_version_string() {
let hostile = format!("1.0.0+{}", "a".repeat(MAX_VERSION_TEXT_LEN))
.encode_to_vec()
.unwrap();
assert!(AstrsVersion::decode_exact(&hostile).is_err());
}
#[test]
fn ordering_follows_semver_precedence() {
let mut versions = [
AstrsVersion::parse("1.0.0").unwrap(),
AstrsVersion::parse("1.0.0-rc.1").unwrap(),
AstrsVersion::parse("0.9.0").unwrap(),
];
versions.sort();
assert_eq!(versions[0].to_string(), "0.9.0");
assert_eq!(versions[1].to_string(), "1.0.0-rc.1");
assert_eq!(versions[2].to_string(), "1.0.0");
}
#[test]
fn serde_uses_the_string_form() {
let version = AstrsVersion::parse("0.1.0-rc.2").unwrap();
let json = serde_json::to_string(&version).unwrap();
assert_eq!(json, "\"0.1.0-rc.2\"");
assert_eq!(
serde_json::from_str::<AstrsVersion>(&json).unwrap(),
version
);
}
#[test]
fn conversions_and_formatting() {
let version = AstrsVersion::from(Version::new(1, 2, 3));
assert_eq!(version, AstrsVersion::new(Version::new(1, 2, 3)));
assert_eq!("1.2.3".parse::<AstrsVersion>().unwrap(), version);
assert_eq!(format!("{version:?}"), "AstrsVersion(1.2.3)");
assert!(AstrsVersion::parse("nope").is_err());
}
}