Skip to content

Commit

Permalink
change version format
Browse files Browse the repository at this point in the history
  • Loading branch information
marvin-j97 committed Aug 29, 2024
1 parent 68b164e commit 7640e50
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 17 deletions.
28 changes: 11 additions & 17 deletions src/version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// This source code is licensed under both the Apache 2.0 and MIT License
// (found in the LICENSE-* files in the repository)

use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use byteorder::WriteBytesExt;

/// Disk format version
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
Expand All @@ -13,21 +13,21 @@ pub enum Version {

impl std::fmt::Display for Version {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", u16::from(*self))
write!(f, "{}", u8::from(*self))
}
}

impl From<Version> for u16 {
impl From<Version> for u8 {
fn from(value: Version) -> Self {
match value {
Version::V1 => 1,
}
}
}

impl TryFrom<u16> for Version {
impl TryFrom<u8> for Version {
type Error = ();
fn try_from(value: u16) -> Result<Self, Self::Error> {
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
1 => Ok(Self::V1),
_ => Err(()),
Expand All @@ -48,14 +48,8 @@ impl Version {
let first_three = bytes.get(0..3)?;

if first_three == MAGIC_BYTES {
let next_two = bytes.get(3..5)?;

let mut bytes = [0; 2];
bytes.copy_from_slice(next_two);
let mut bytes: &[u8] = &bytes;

let value = bytes.read_u16::<BigEndian>().ok()?;
let version = Self::try_from(value).ok()?;
let version = *bytes.get(3)?;
let version = Self::try_from(version).ok()?;

Some(version)
} else {
Expand All @@ -68,7 +62,7 @@ impl Version {
writer: &mut W,
) -> std::io::Result<usize> {
writer.write_all(&MAGIC_BYTES)?;
writer.write_u16::<BigEndian>(u16::from(self))?;
writer.write_u8(u8::from(self))?;
Ok(5)
}
}
Expand All @@ -83,21 +77,21 @@ mod tests {
pub fn version_serialize() -> crate::Result<()> {
let mut bytes = vec![];
Version::V1.write_file_header(&mut bytes)?;
assert_eq!(bytes, &[b'V', b'L', b'G', 0, 1]);
assert_eq!(bytes, &[b'V', b'L', b'G', 1]);
Ok(())
}

#[test]
#[allow(clippy::expect_used)]
pub fn version_deserialize_success() {
let version = Version::parse_file_header(&[b'V', b'L', b'G', 0, 1]);
let version = Version::parse_file_header(&[b'V', b'L', b'G', 1]);
assert_eq!(version, Some(Version::V1));
}

#[test]
#[allow(clippy::expect_used)]
pub fn version_deserialize_fail() {
let version = Version::parse_file_header(&[b'F', b'J', b'X', 0, 1]);
let version = Version::parse_file_header(&[b'F', b'J', b'X', 1]);
assert!(version.is_none());
}

Expand Down
Binary file modified test_fixture/v1_vlog/.vlog
Binary file not shown.
Binary file modified test_fixture/v1_vlog_corrupt/.vlog
Binary file not shown.

0 comments on commit 7640e50

Please sign in to comment.