1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
}
}