Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(mercury): implement From and TryInto traits for Flags #737

Merged
merged 4 commits into from
Dec 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 27 additions & 20 deletions mercury/src/internal/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,38 +60,45 @@ pub struct Flags {
pub stage: u8, // 2-bit during merge
pub name_length: u16, // 12-bit
}
// TODO From Trait
impl Flags {
pub fn new(name_len: u16) -> Self {
Flags {
assume_valid: true,
extended: false,
stage: 0,
name_length: name_len,
}
}

pub fn from_u16(flags: u16) -> Self {
impl From<u16> for Flags {
fn from(flags: u16) -> Self {
Flags {
assume_valid: flags & 0x8000 != 0,
extended: flags & 0x4000 != 0,
stage: ((flags & 0x3000) >> 12) as u8,
name_length: flags & 0xFFF,
}
}
}

pub fn to_u16(&self) -> u16 {
impl TryInto<u16> for &Flags {
type Error = &'static str;
fn try_into(self) -> Result<u16, Self::Error> {
let mut flags = 0u16;
if self.assume_valid {
flags |= 0x8000;
flags |= 0x8000; // 16
}
if self.extended {
flags |= 0x4000;
flags |= 0x4000; // 15
}
flags |= (self.stage as u16) << 12; // 13-14
if self.name_length > 0xFFF {
return Err("Name length is too long");
}
flags |= self.name_length; // 0-11
Ok(flags)
}
}

impl Flags {
pub fn new(name_len: u16) -> Self {
Flags {
assume_valid: true,
extended: false,
stage: 0,
name_length: name_len,
}
flags |= (self.stage as u16) << 12;
assert!(self.name_length <= 0xFFF, "Name length is too long");
flags |= self.name_length;
flags
}
}

Expand Down Expand Up @@ -240,7 +247,7 @@ impl Index {
gid: file.read_u32::<BigEndian>()?,
size: file.read_u32::<BigEndian>()?,
hash: utils::read_sha1(file)?,
flags: Flags::from_u16(file.read_u16::<BigEndian>()?),
flags: Flags::from(file.read_u16::<BigEndian>()?),
name: String::new(),
};
let name_len = entry.flags.name_length as usize;
Expand Down Expand Up @@ -308,7 +315,7 @@ impl Index {
entry_bytes.write_u32::<BigEndian>(entry.gid)?;
entry_bytes.write_u32::<BigEndian>(entry.size)?;
entry_bytes.write_all(&entry.hash.0)?;
entry_bytes.write_u16::<BigEndian>(entry.flags.to_u16())?;
entry_bytes.write_u16::<BigEndian>((&entry.flags).try_into().unwrap())?;
entry_bytes.write_all(entry.name.as_bytes())?;
let padding = 8 - ((22 + entry.name.len()) % 8);
entry_bytes.write_all(&vec![0; padding])?;
Expand Down
Loading