Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
53 changes: 53 additions & 0 deletions tbf-parser/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1183,4 +1183,57 @@ impl TbfHeader {
_ => None,
}
}

/// Returns the checksum for TBF header according to the `parse_tbf_header` function
/// `new_flags` is the new value we want to set
pub fn compute_checksum(header: &[u8], new_flags: u32) -> Result<u32, TbfParseError> {
let mut checksum: u32 = 0;

let header_iter = header.chunks_exact(4);

// Iterate all chunks and XOR the chunks to compute the checksum.
for (i, chunk) in header_iter.enumerate() {
let word = if i == 2 {
new_flags
} else if i == 3 {
continue;
} else {
u32::from_le_bytes(chunk.try_into()?)
};
checksum ^= word;
}
Ok(checksum)
}

/// Sets the flag field and updates the checksum, it modifies the state accordingly
pub fn set_flags(&mut self, flags: u32, header: &[u8]) -> Result<(), TbfParseError> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Besides this function, I would create a

  • set_enabled
  • set_sticky

and anything else the flags can be. Just so that the end-user of this crate does not need to know which bit is the 'enabled' or 'sticky' bit

let new_checksum = Self::compute_checksum(header, flags)?;
match self {
TbfHeader::TbfHeaderV2(hd) => {
hd.base.flags = flags;
hd.base.checksum = new_checksum;
}
TbfHeader::Padding(base) => {
base.flags = flags;
base.checksum = new_checksum;
}
}

Ok(())
}

/// Returns a 16 byte array with the serialized base header (little-endian format)
pub fn serialize(&self) -> Result<[u8; 16], TbfParseError> {
let base = match self {
TbfHeader::TbfHeaderV2(hd) => &hd.base,
TbfHeader::Padding(base) => base,
};
let mut bytes = [0u8; 16];
bytes[0..2].copy_from_slice(&base.version.to_le_bytes());
bytes[2..4].copy_from_slice(&base.header_size.to_le_bytes());
bytes[4..8].copy_from_slice(&base.total_size.to_le_bytes());
bytes[8..12].copy_from_slice(&base.flags.to_le_bytes());
bytes[12..16].copy_from_slice(&base.checksum.to_le_bytes());
Ok(bytes)
}
}
Loading