Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
kariy committed Oct 16, 2024
1 parent 2857767 commit 43013c7
Showing 1 changed file with 22 additions and 6 deletions.
28 changes: 22 additions & 6 deletions crates/katana/primitives/src/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,19 @@ impl ProtocolVersion {
/// Parses a version string in the format `x.y.z.w` where x, y, z, w are u8 numbers.
/// The string can have fewer than 4 segments; missing segments are filled with zeros.
pub fn parse(version: &str) -> Result<Self, ParseVersionError> {
if version.is_empty() {
return Err(ParseVersionError::InvalidFormat);
}

let segments = version.split('.').collect::<Vec<&str>>();

if segments.is_empty() || segments.len() > 4 {
if segments.len() > 4 {
return Err(ParseVersionError::InvalidFormat);
}

let mut buffer = [0u8; 4];
for (buf, seg) in buffer.iter_mut().zip(segments) {
*buf = seg.parse::<u8>()?;
*buf = if seg.is_empty() { 0 } else { seg.parse::<u8>()? };
}

Ok(Self::new(buffer))
Expand Down Expand Up @@ -115,7 +119,9 @@ mod tests {
#[test]
fn parse_version_missing_parts() {
let version = "1.9.0";
assert!(ProtocolVersion::parse(version).is_err());
let parsed = ProtocolVersion::parse(version).unwrap();
assert_eq!(parsed.segments, [1, 9, 0, 0]);
assert_eq!("1.9.0", parsed.to_string());
}

#[test]
Expand All @@ -125,17 +131,27 @@ mod tests {
}

#[test]
fn parse_version_missing_digit_should_fail() {
fn parse_version_missing_digit_default_zero() {
let version = "1...";
assert!(ProtocolVersion::parse(version).is_err());
let parsed = ProtocolVersion::parse(version).unwrap();
assert_eq!(parsed.segments, [1, 0, 0, 0]);
assert_eq!("1.0.0", parsed.to_string());
}

#[test]
fn parse_version_many_parts_should_succeed() {
let version = "1.2.3.4";
let parsed = ProtocolVersion::parse(version).unwrap();
assert_eq!(parsed.segments, [1, 2, 3, 4]);
assert_eq!(String::from("1.2.3.4"), parsed.to_string());
assert_eq!("1.2.3.4", parsed.to_string());
}

#[test]
fn parse_invalid_formats() {
let version = "";
assert!(ProtocolVersion::parse(version).is_err());
let version = "1.2.3.4.5";
assert!(ProtocolVersion::parse(version).is_err());
}

#[cfg(feature = "serde")]
Expand Down

0 comments on commit 43013c7

Please sign in to comment.