use byteorder::{LittleEndian, ReadBytesExt};
use std::io::{Cursor, Read};
use anyhow::{ensure, Result};
#[derive(Clone, Debug, thiserror::Error)]
#[error("FAT data has invalid size.")]
struct InvalidFatLen;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct AllocInfo {
pub start: u32,
pub end: u32,
}
impl AllocInfo {
pub fn new<R: Read>(reader: &mut R) -> Result<Self> {
Ok(Self {
start: reader.read_u32::<LittleEndian>()?,
end: reader.read_u32::<LittleEndian>()?,
})
}
pub fn len(&self) -> u32 {
self.end - self.start
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct FileAllocTable {
list: Vec<AllocInfo>,
}
impl FileAllocTable {
pub fn new(fat: &[u8]) -> Result<Self> {
ensure!(fat.len() % 8 == 0, InvalidFatLen);
let mut list = Vec::new();
let mut cursor = Cursor::new(fat);
let entries = fat.len() / 8;
for _ in 0..entries {
list.push(AllocInfo::new(&mut cursor)?);
}
Ok(Self {
list
})
}
pub fn get(&self, id: u16) -> Option<AllocInfo> {
if self.list.len() >= id as usize {
return Some(self.list[id as usize]);
}
None
}
}