use crate::error::UrnaError;
use sha2::{Digest, Sha256};
use super::SECTION_ENCODING_RAW;
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
pub struct SectionEntry {
pub section_id: u32,
pub encoding: u32,
pub offset: u64,
pub size: u64,
pub checksum: [u8; 8],
}
impl SectionEntry {
pub fn new(section_id: u32, offset: u64, size: u64) -> Self {
Self {
section_id,
encoding: SECTION_ENCODING_RAW,
offset,
size,
checksum: [0; 8],
}
}
pub fn as_bytes(&self) -> &[u8] {
bytemuck::bytes_of(self)
}
pub fn as_bytes_mut(&mut self) -> &mut [u8] {
bytemuck::bytes_of_mut(self)
}
pub fn compute_checksum(&mut self, data: &[u8]) {
let hash = Sha256::digest(data);
self.checksum.copy_from_slice(&hash[..8]);
}
pub fn validate_checksum(&self, data: &[u8]) -> crate::Result<()> {
let hash = Sha256::digest(data);
if hash[..8] != self.checksum[..] {
return Err(UrnaError::SectionChecksumMismatch(self.section_id));
}
Ok(())
}
}