const SECTOR_SIZE: usize = 512;
const MINI_SECTOR_SIZE: usize = 64;
const MINI_STREAM_CUTOFF: usize = 4096;
const DIR_ENTRY_SIZE: usize = 128;
const ENTRIES_PER_DIR_SECTOR: usize = SECTOR_SIZE / DIR_ENTRY_SIZE; const FAT_ENTRIES_PER_SECTOR: usize = SECTOR_SIZE / 4; const HEADER_DIFAT_COUNT: usize = 109;
const DIFAT_ENTRIES_PER_SECTOR: usize = FAT_ENTRIES_PER_SECTOR - 1;
const ENDOFCHAIN: u32 = 0xFFFFFFFE;
const FREESECT: u32 = 0xFFFFFFFF;
const FATSECT: u32 = 0xFFFFFFFD;
const DIFSECT: u32 = 0xFFFFFFFC;
const NOSTREAM: u32 = 0xFFFFFFFF;
const CFB_SIGNATURE: [u8; 8] = [0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1];
struct DirEntry {
name: String,
obj_type: u8,
data: Vec<u8>,
parent: usize,
children: Vec<usize>,
left: u32,
right: u32,
child: u32,
color: u8,
start_sector: u32,
is_mini: bool,
clsid: [u8; 16],
}
impl DirEntry {
fn new(name: &str, obj_type: u8, parent: usize) -> Self {
match Self::try_new(name, obj_type, parent, &crate::storage::Unbounded) {
Ok(entry) => entry,
Err(never) => match never {},
}
}
fn try_new<S: crate::storage::Storage>(
name: &str,
obj_type: u8,
parent: usize,
storage: &S,
) -> Result<Self, S::Error> {
Ok(DirEntry {
name: storage.string(name)?,
obj_type,
data: Vec::new(),
parent,
children: Vec::new(),
left: NOSTREAM,
right: NOSTREAM,
child: NOSTREAM,
color: 1,
start_sector: if obj_type == 1 { 0 } else { ENDOFCHAIN },
is_mini: false,
clsid: [0u8; 16],
})
}
}
pub fn build_cfb(named_streams: &[(&str, &[u8])]) -> Result<Vec<u8>, String> {
build_cfb_with_root_clsid(named_streams, [0u8; 16])
}
pub fn build_cfb_with_root_clsid(
named_streams: &[(&str, &[u8])],
root_clsid: [u8; 16],
) -> Result<Vec<u8>, String> {
build_cfb_with_storage(
named_streams,
root_clsid,
&crate::storage::Unbounded,
usize::MAX,
)
}
pub(crate) fn build_cfb_with_storage<S: crate::storage::Storage>(
named_streams: &[(&str, &[u8])],
root_clsid: [u8; 16],
storage: &S,
maximum: usize,
) -> Result<Vec<u8>, String>
where
S::Error: std::fmt::Display,
{
storage.bytes(0).map_err(|error| error.to_string())?;
if maximum < 512 {
return Err("SERIALIZE_RESOURCE_LIMIT: CFB output byte limit".into());
}
let mut entries = try_build_entries(named_streams, storage)?;
entries[0].clsid = root_clsid;
try_build_tree(&mut entries, storage)?;
let mut mini_stream = Vec::new();
let mut mini_fat: Vec<u32> = Vec::new();
for entry in entries.iter_mut() {
if entry.obj_type == 2 && !entry.data.is_empty() && entry.data.len() < MINI_STREAM_CUTOFF {
entry.is_mini = true;
let start_mini = mini_fat.len();
entry.start_sector = start_mini as u32;
let num_mini = (entry.data.len() + MINI_SECTOR_SIZE - 1) / MINI_SECTOR_SIZE;
storage
.reserve(&mut mini_fat, num_mini)
.map_err(|error| error.to_string())?;
for i in 0..num_mini {
mini_fat.push(if i + 1 < num_mini {
(start_mini + i + 1) as u32
} else {
ENDOFCHAIN
});
}
let pad = (MINI_SECTOR_SIZE - (entry.data.len() % MINI_SECTOR_SIZE)) % MINI_SECTOR_SIZE;
storage
.reserve(&mut mini_stream, entry.data.len().saturating_add(pad))
.map_err(|error| error.to_string())?;
mini_stream.extend_from_slice(&entry.data);
mini_stream.resize(mini_stream.len() + pad, 0);
}
}
let mini_stream_size = mini_stream.len();
if !mini_stream.is_empty() {
entries[0].data = mini_stream;
}
let dir_sectors = (entries.len() + ENTRIES_PER_DIR_SECTOR - 1) / ENTRIES_PER_DIR_SECTOR;
let mut next_sector = dir_sectors as u32;
for entry in entries.iter_mut() {
if entry.obj_type == 2 && !entry.data.is_empty() && !entry.is_mini {
entry.start_sector = next_sector;
let num = (entry.data.len() + SECTOR_SIZE - 1) / SECTOR_SIZE;
next_sector += num as u32;
}
}
if mini_stream_size > 0 {
entries[0].start_sector = next_sector;
let num = (entries[0].data.len() + SECTOR_SIZE - 1) / SECTOR_SIZE;
next_sector += num as u32;
}
let mini_fat_start;
let mini_fat_sector_count;
if !mini_fat.is_empty() {
mini_fat_start = next_sector;
mini_fat_sector_count =
((mini_fat.len() + FAT_ENTRIES_PER_SECTOR - 1) / FAT_ENTRIES_PER_SECTOR) as u32;
next_sector += mini_fat_sector_count;
} else {
mini_fat_start = ENDOFCHAIN;
mini_fat_sector_count = 0;
}
let non_meta_sectors = next_sector; let mut fat_count = 1u32;
let mut difat_count = 0u32;
loop {
let total = non_meta_sectors + fat_count + difat_count;
let needed_fat =
(((total as usize) + FAT_ENTRIES_PER_SECTOR - 1) / FAT_ENTRIES_PER_SECTOR) as u32;
let needed_difat = if needed_fat as usize > HEADER_DIFAT_COUNT {
(((needed_fat as usize - HEADER_DIFAT_COUNT) + DIFAT_ENTRIES_PER_SECTOR - 1)
/ DIFAT_ENTRIES_PER_SECTOR) as u32
} else {
0
};
if needed_fat <= fat_count && needed_difat <= difat_count {
break;
}
fat_count = needed_fat.max(fat_count);
difat_count = needed_difat.max(difat_count);
}
let fat_start = non_meta_sectors;
let difat_start = fat_start + fat_count;
let total_sectors = non_meta_sectors + fat_count + difat_count;
let file_size = 512usize
.checked_add(
(total_sectors as usize)
.checked_mul(SECTOR_SIZE)
.ok_or("SERIALIZE_RESOURCE_LIMIT: CFB sector size")?,
)
.ok_or("SERIALIZE_RESOURCE_LIMIT: CFB file size")?;
if file_size > maximum {
return Err("SERIALIZE_RESOURCE_LIMIT: CFB output byte limit".into());
}
let mut fat = storage
.vec(total_sectors as usize)
.map_err(|error| error.to_string())?;
fat.resize(total_sectors as usize, FREESECT);
for i in 0..dir_sectors {
fat[i] = if i + 1 < dir_sectors {
(i + 1) as u32
} else {
ENDOFCHAIN
};
}
for entry in entries.iter() {
if entry.obj_type == 2 && !entry.data.is_empty() && !entry.is_mini {
let start = entry.start_sector as usize;
let num = (entry.data.len() + SECTOR_SIZE - 1) / SECTOR_SIZE;
for i in 0..num {
fat[start + i] = if i + 1 < num {
(start + i + 1) as u32
} else {
ENDOFCHAIN
};
}
}
}
if entries[0].start_sector != ENDOFCHAIN && !entries[0].data.is_empty() {
let start = entries[0].start_sector as usize;
let num = (entries[0].data.len() + SECTOR_SIZE - 1) / SECTOR_SIZE;
for i in 0..num {
fat[start + i] = if i + 1 < num {
(start + i + 1) as u32
} else {
ENDOFCHAIN
};
}
}
if mini_fat_start != ENDOFCHAIN {
let start = mini_fat_start as usize;
for i in 0..mini_fat_sector_count as usize {
fat[start + i] = if i + 1 < mini_fat_sector_count as usize {
(start + i + 1) as u32
} else {
ENDOFCHAIN
};
}
}
for i in 0..fat_count as usize {
fat[fat_start as usize + i] = FATSECT;
}
for i in 0..difat_count as usize {
fat[difat_start as usize + i] = DIFSECT;
}
let mut output = storage.vec(file_size).map_err(|error| error.to_string())?;
output.resize(file_size, 0);
write_header(
&mut output,
fat_count,
fat_start,
mini_fat_start,
mini_fat_sector_count,
difat_start,
difat_count,
);
for i in entries.len()..dir_sectors * ENTRIES_PER_DIR_SECTOR {
let sector_idx = i / ENTRIES_PER_DIR_SECTOR;
let entry_in_sector = i % ENTRIES_PER_DIR_SECTOR;
let offset = 512 + sector_idx * SECTOR_SIZE + entry_in_sector * DIR_ENTRY_SIZE;
output[offset + 68..offset + 72].copy_from_slice(&NOSTREAM.to_le_bytes());
output[offset + 72..offset + 76].copy_from_slice(&NOSTREAM.to_le_bytes());
output[offset + 76..offset + 80].copy_from_slice(&NOSTREAM.to_le_bytes());
}
for (i, entry) in entries.iter().enumerate() {
let sector_idx = i / ENTRIES_PER_DIR_SECTOR;
let entry_in_sector = i % ENTRIES_PER_DIR_SECTOR;
let offset = 512 + sector_idx * SECTOR_SIZE + entry_in_sector * DIR_ENTRY_SIZE;
write_dir_entry(&mut output, offset, entry);
}
for entry in &entries {
if entry.obj_type == 2 && !entry.data.is_empty() && !entry.is_mini {
let start_offset = 512 + entry.start_sector as usize * SECTOR_SIZE;
output[start_offset..start_offset + entry.data.len()].copy_from_slice(&entry.data);
}
}
if entries[0].start_sector != ENDOFCHAIN && !entries[0].data.is_empty() {
let start_offset = 512 + entries[0].start_sector as usize * SECTOR_SIZE;
output[start_offset..start_offset + entries[0].data.len()]
.copy_from_slice(&entries[0].data);
}
if mini_fat_start != ENDOFCHAIN {
for sector_idx in 0..mini_fat_sector_count as usize {
let sector_base = 512 + (mini_fat_start as usize + sector_idx) * SECTOR_SIZE;
for entry_idx in 0..FAT_ENTRIES_PER_SECTOR {
let offset = sector_base + entry_idx * 4;
output[offset..offset + 4].copy_from_slice(&FREESECT.to_le_bytes());
}
}
for (i, &mf) in mini_fat.iter().enumerate() {
let sector_idx = i / FAT_ENTRIES_PER_SECTOR;
let entry_in_sector = i % FAT_ENTRIES_PER_SECTOR;
let offset =
512 + (mini_fat_start as usize + sector_idx) * SECTOR_SIZE + entry_in_sector * 4;
output[offset..offset + 4].copy_from_slice(&mf.to_le_bytes());
}
}
for sector_idx in 0..fat_count as usize {
let sector_base = 512 + (fat_start as usize + sector_idx) * SECTOR_SIZE;
for entry_idx in 0..FAT_ENTRIES_PER_SECTOR {
let offset = sector_base + entry_idx * 4;
output[offset..offset + 4].copy_from_slice(&FREESECT.to_le_bytes());
}
}
for (i, &fat_entry) in fat.iter().enumerate() {
let fat_sector_idx = i / FAT_ENTRIES_PER_SECTOR;
let entry_in_sector = i % FAT_ENTRIES_PER_SECTOR;
let offset =
512 + (fat_start as usize + fat_sector_idx) * SECTOR_SIZE + entry_in_sector * 4;
output[offset..offset + 4].copy_from_slice(&fat_entry.to_le_bytes());
}
for d in 0..difat_count as usize {
let sector_base = 512 + (difat_start as usize + d) * SECTOR_SIZE;
for j in 0..DIFAT_ENTRIES_PER_SECTOR {
let fat_idx = HEADER_DIFAT_COUNT + d * DIFAT_ENTRIES_PER_SECTOR + j;
let value = if (fat_idx as u32) < fat_count {
fat_start + fat_idx as u32
} else {
FREESECT
};
let off = sector_base + j * 4;
output[off..off + 4].copy_from_slice(&value.to_le_bytes());
}
let next = if d + 1 < difat_count as usize {
difat_start + (d as u32) + 1
} else {
ENDOFCHAIN
};
let off = sector_base + DIFAT_ENTRIES_PER_SECTOR * 4;
output[off..off + 4].copy_from_slice(&next.to_le_bytes());
}
Ok(output)
}
fn build_entries(named_streams: &[(&str, &[u8])]) -> Result<Vec<DirEntry>, String> {
try_build_entries(named_streams, &crate::storage::Unbounded)
}
fn try_build_entries<S: crate::storage::Storage>(
named_streams: &[(&str, &[u8])],
storage: &S,
) -> Result<Vec<DirEntry>, String>
where
S::Error: std::fmt::Display,
{
let mut entries = Vec::new();
storage
.push(
&mut entries,
DirEntry::try_new("Root Entry", 5, 0, storage).map_err(|error| error.to_string())?,
)
.map_err(|error| error.to_string())?;
for &(path, data) in named_streams {
let normalized = storage
.chars(path.chars().map(|ch| if ch == '\\' { '/' } else { ch }))
.map_err(|error| error.to_string())?;
let parts = storage
.collect(normalized.split('/').filter(|s| !s.is_empty()))
.map_err(|error| error.to_string())?;
if parts.is_empty() {
return Err(format!("CFB 경로에 이름 세그먼트가 없다: {path:?}"));
}
let mut parent_idx = 0;
for (i, part) in parts.iter().enumerate() {
let is_last = i == parts.len() - 1;
let want_type = if is_last { 2u8 } else { 1u8 };
let existing = entries
.iter()
.enumerate()
.skip(1)
.find(|(_, e)| e.parent == parent_idx && e.name == *part)
.map(|(idx, _)| idx);
if let Some(idx) = existing {
if entries[idx].obj_type != want_type {
return Err(format!(
"CFB 경로 충돌: {path:?} 의 '{part}' 가 이미 {}(으)로 존재한다",
if entries[idx].obj_type == 1 {
"스토리지"
} else {
"스트림"
}
));
}
if is_last {
entries[idx].data = storage
.copy_slice(data)
.map_err(|error| error.to_string())?;
}
parent_idx = idx;
} else {
let new_idx = entries.len();
let mut entry = DirEntry::try_new(part, want_type, parent_idx, storage)
.map_err(|error| error.to_string())?;
if is_last {
entry.data = storage
.copy_slice(data)
.map_err(|error| error.to_string())?;
}
storage
.push(&mut entries[parent_idx].children, new_idx)
.map_err(|error| error.to_string())?;
storage
.push(&mut entries, entry)
.map_err(|error| error.to_string())?;
parent_idx = new_idx;
}
}
}
Ok(entries)
}
fn build_tree(entries: &mut Vec<DirEntry>, idx: usize) {
match try_build_tree_from(entries, idx, &crate::storage::Unbounded) {
Ok(()) => (),
Err(error) => unreachable!("{error}"),
}
}
fn try_build_tree<S: crate::storage::Storage>(
entries: &mut Vec<DirEntry>,
storage: &S,
) -> Result<(), String>
where
S::Error: std::fmt::Display,
{
try_build_tree_from(entries, 0, storage)
}
fn try_build_tree_from<S: crate::storage::Storage>(
entries: &mut Vec<DirEntry>,
first: usize,
storage: &S,
) -> Result<(), String>
where
S::Error: std::fmt::Display,
{
let mut keys = storage
.vec(entries.len())
.map_err(|error| error.to_string())?;
for entry in entries.iter() {
keys.push(
storage
.chars(entry.name.chars().flat_map(char::to_uppercase))
.map_err(|error| error.to_string())?,
);
}
let mut pending = storage
.collect([first])
.map_err(|error| error.to_string())?;
while let Some(idx) = pending.pop() {
let children = storage
.copy_slice(&entries[idx].children)
.map_err(|error| error.to_string())?;
if children.is_empty() {
entries[idx].child = NOSTREAM;
continue;
}
let mut sorted = storage
.copy_slice(&children)
.map_err(|error| error.to_string())?;
storage
.bytes(sorted.len().saturating_mul(std::mem::size_of::<usize>()))
.map_err(|error| error.to_string())?;
sorted.sort_by(|&a, &b| {
keys[a]
.len()
.cmp(&keys[b].len())
.then(keys[a].cmp(&keys[b]))
});
let root = build_balanced_tree(entries, &sorted);
entries[idx].child = root;
let max_depth = tree_max_depth(entries, root, 0);
color_deepest_nodes(entries, root, 0, max_depth);
for &child in children.iter().rev() {
if entries[child].obj_type == 1 {
storage
.push(&mut pending, child)
.map_err(|error| error.to_string())?;
}
}
}
Ok(())
}
fn tree_max_depth(entries: &[DirEntry], idx: u32, depth: usize) -> usize {
if idx == NOSTREAM {
return depth.saturating_sub(1);
}
let entry = &entries[idx as usize];
tree_max_depth(entries, entry.left, depth + 1).max(tree_max_depth(
entries,
entry.right,
depth + 1,
))
}
fn color_deepest_nodes(entries: &mut [DirEntry], idx: u32, depth: usize, max_depth: usize) {
if idx == NOSTREAM {
return;
}
let left = entries[idx as usize].left;
let right = entries[idx as usize].right;
entries[idx as usize].color = if depth > 0 && depth == max_depth {
0 } else {
1 };
color_deepest_nodes(entries, left, depth + 1, max_depth);
color_deepest_nodes(entries, right, depth + 1, max_depth);
}
fn build_balanced_tree(entries: &mut Vec<DirEntry>, sorted: &[usize]) -> u32 {
if sorted.is_empty() {
return NOSTREAM;
}
let mid = sorted.len() / 2;
let root = sorted[mid] as u32;
let left = build_balanced_tree(entries, &sorted[..mid]);
let right = if mid + 1 < sorted.len() {
build_balanced_tree(entries, &sorted[mid + 1..])
} else {
NOSTREAM
};
entries[root as usize].left = left;
entries[root as usize].right = right;
root
}
fn write_header(
output: &mut [u8],
fat_count: u32,
fat_start: u32,
mini_fat_start: u32,
mini_fat_sector_count: u32,
difat_start: u32,
difat_count: u32,
) {
output[0..8].copy_from_slice(&CFB_SIGNATURE);
output[24..26].copy_from_slice(&0x003Eu16.to_le_bytes());
output[26..28].copy_from_slice(&0x0003u16.to_le_bytes());
output[28..30].copy_from_slice(&0xFFFEu16.to_le_bytes());
output[30..32].copy_from_slice(&9u16.to_le_bytes());
output[32..34].copy_from_slice(&6u16.to_le_bytes());
output[44..48].copy_from_slice(&fat_count.to_le_bytes());
output[48..52].copy_from_slice(&0u32.to_le_bytes());
output[56..60].copy_from_slice(&(MINI_STREAM_CUTOFF as u32).to_le_bytes());
output[60..64].copy_from_slice(&mini_fat_start.to_le_bytes());
output[64..68].copy_from_slice(&mini_fat_sector_count.to_le_bytes());
let first_difat = if difat_count > 0 {
difat_start
} else {
ENDOFCHAIN
};
output[68..72].copy_from_slice(&first_difat.to_le_bytes());
output[72..76].copy_from_slice(&difat_count.to_le_bytes());
let header_difat_offset = 76;
for i in 0..HEADER_DIFAT_COUNT {
let offset = header_difat_offset + i * 4;
if (i as u32) < fat_count {
let sid = fat_start + i as u32;
output[offset..offset + 4].copy_from_slice(&sid.to_le_bytes());
} else {
output[offset..offset + 4].copy_from_slice(&FREESECT.to_le_bytes());
}
}
}
fn write_dir_entry(output: &mut [u8], offset: usize, entry: &DirEntry) {
let buf = &mut output[offset..offset + DIR_ENTRY_SIZE];
let mut name_utf16 = [0u16; 31];
let mut name_len = 0;
for unit in entry.name.encode_utf16().take(31) {
name_utf16[name_len] = unit;
name_len += 1;
}
for i in 0..name_len {
let pos = i * 2;
buf[pos..pos + 2].copy_from_slice(&name_utf16[i].to_le_bytes());
}
let null_pos = name_len * 2;
buf[null_pos..null_pos + 2].copy_from_slice(&0u16.to_le_bytes());
let name_byte_len = ((name_len + 1) * 2) as u16;
buf[64..66].copy_from_slice(&name_byte_len.to_le_bytes());
buf[66] = entry.obj_type;
buf[67] = entry.color;
buf[68..72].copy_from_slice(&entry.left.to_le_bytes());
buf[72..76].copy_from_slice(&entry.right.to_le_bytes());
buf[76..80].copy_from_slice(&entry.child.to_le_bytes());
buf[80..96].copy_from_slice(&entry.clsid);
if entry.obj_type == 5 || entry.obj_type == 1 {
let filetime: u64 = 0x01DA_5E8B_8000_0000;
let ft_bytes = filetime.to_le_bytes();
buf[100..108].copy_from_slice(&ft_bytes); buf[108..116].copy_from_slice(&ft_bytes); }
buf[116..120].copy_from_slice(&entry.start_sector.to_le_bytes());
let size = if entry.obj_type == 2 || entry.obj_type == 5 {
entry.data.len() as u32
} else {
0
};
buf[120..124].copy_from_slice(&size.to_le_bytes());
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_build_cfb_signature() {
let streams = vec![("/TestStream", b"Hello" as &[u8])];
let bytes = build_cfb(&streams).unwrap();
assert!(bytes.len() >= 512);
assert_eq!(&bytes[0..8], &CFB_SIGNATURE);
}
#[test]
fn test_build_cfb_empty() {
let streams: Vec<(&str, &[u8])> = Vec::new();
let bytes = build_cfb(&streams).unwrap();
assert_eq!(&bytes[0..8], &CFB_SIGNATURE);
}
#[test]
fn test_build_cfb_readable_by_cfb_crate() {
let fh = vec![0xAAu8; 256];
let di = vec![0xBBu8; 100];
let streams = vec![("/FileHeader", fh.as_slice()), ("/DocInfo", di.as_slice())];
let bytes = build_cfb(&streams).unwrap();
let cursor = std::io::Cursor::new(&bytes);
let mut cfb = cfb::CompoundFile::open(cursor).unwrap();
let mut fh_read = Vec::new();
std::io::Read::read_to_end(&mut cfb.open_stream("/FileHeader").unwrap(), &mut fh_read)
.unwrap();
assert_eq!(fh_read.len(), 256);
assert!(fh_read.iter().all(|&b| b == 0xAA));
let mut di_read = Vec::new();
std::io::Read::read_to_end(&mut cfb.open_stream("/DocInfo").unwrap(), &mut di_read)
.unwrap();
assert_eq!(di_read.len(), 100);
assert!(di_read.iter().all(|&b| b == 0xBB));
}
#[test]
fn test_build_cfb_with_storages() {
let d1 = vec![0x01u8; 256];
let d2 = vec![0x02u8; 500];
let d3 = vec![0x03u8; 2000];
let d4 = vec![0x04u8; 1500];
let streams = vec![
("/FileHeader", d1.as_slice()),
("/DocInfo", d2.as_slice()),
("/BodyText/Section0", d3.as_slice()),
("/BodyText/Section1", d4.as_slice()),
];
let bytes = build_cfb(&streams).unwrap();
let cursor = std::io::Cursor::new(&bytes);
let mut cfb = cfb::CompoundFile::open(cursor).unwrap();
let mut s0 = Vec::new();
std::io::Read::read_to_end(&mut cfb.open_stream("/BodyText/Section0").unwrap(), &mut s0)
.unwrap();
assert_eq!(s0.len(), 2000);
assert!(s0.iter().all(|&b| b == 0x03));
let mut s1 = Vec::new();
std::io::Read::read_to_end(&mut cfb.open_stream("/BodyText/Section1").unwrap(), &mut s1)
.unwrap();
assert_eq!(s1.len(), 1500);
assert!(s1.iter().all(|&b| b == 0x04));
}
#[test]
fn test_build_cfb_large_stream() {
let data = vec![0x55u8; 10240];
let streams = vec![("/BigStream", data.as_slice())];
let bytes = build_cfb(&streams).unwrap();
let cursor = std::io::Cursor::new(&bytes);
let mut cfb = cfb::CompoundFile::open(cursor).unwrap();
let mut read_data = Vec::new();
std::io::Read::read_to_end(&mut cfb.open_stream("/BigStream").unwrap(), &mut read_data)
.unwrap();
assert_eq!(read_data, data);
}
#[test]
fn test_build_cfb_mixed_sizes() {
let small = vec![0x11u8; 100];
let large = vec![0x22u8; 5000];
let streams = vec![("/Small", small.as_slice()), ("/Large", large.as_slice())];
let bytes = build_cfb(&streams).unwrap();
let cursor = std::io::Cursor::new(&bytes);
let mut cfb = cfb::CompoundFile::open(cursor).unwrap();
let mut s_read = Vec::new();
std::io::Read::read_to_end(&mut cfb.open_stream("/Small").unwrap(), &mut s_read).unwrap();
assert_eq!(s_read, small);
let mut l_read = Vec::new();
std::io::Read::read_to_end(&mut cfb.open_stream("/Large").unwrap(), &mut l_read).unwrap();
assert_eq!(l_read, large);
}
#[test]
fn test_build_cfb_difat_over_threshold() {
let n = 7_200_000usize;
let big: Vec<u8> = (0..n).map(|i| (i % 251) as u8).collect();
let bytes = {
let streams = vec![("/BinData/BIN0001", big.as_slice())];
build_cfb(&streams).unwrap()
};
drop(big);
let first_difat = u32::from_le_bytes(bytes[68..72].try_into().unwrap());
let num_difat = u32::from_le_bytes(bytes[72..76].try_into().unwrap());
assert!(num_difat > 0, "출력이 7.14MB를 넘는데 DIFAT 섹터가 0개");
assert_ne!(
first_difat, ENDOFCHAIN,
"DIFAT가 필요한데 first_difat가 ENDOFCHAIN"
);
let cursor = std::io::Cursor::new(&bytes);
let mut cfb = cfb::CompoundFile::open(cursor).unwrap();
let mut read_data = Vec::new();
std::io::Read::read_to_end(
&mut cfb.open_stream("/BinData/BIN0001").unwrap(),
&mut read_data,
)
.unwrap();
assert_eq!(read_data.len(), n);
assert!(
read_data
.iter()
.enumerate()
.all(|(i, &b)| b == (i % 251) as u8),
"라운드트립 데이터가 원본 패턴과 불일치"
);
}
fn read_stream(bytes: &[u8], path: &str) -> Vec<u8> {
let mut cfb = cfb::CompoundFile::open(std::io::Cursor::new(bytes)).expect("CFB 열기");
let mut out = Vec::new();
std::io::Read::read_to_end(&mut cfb.open_stream(path).expect("스트림 열기"), &mut out)
.expect("스트림 읽기");
out
}
#[test]
fn test_build_cfb_normalizes_backslash_path_separator() {
let data = vec![0x77u8; 300];
let back = build_cfb(&[("/BinData\\BIN0001.OLE", data.as_slice())]).unwrap();
let fwd = build_cfb(&[("/BinData/BIN0001.OLE", data.as_slice())]).unwrap();
assert_eq!(back, fwd, "구분자 표기가 출력 바이트를 바꾸면 안 된다");
assert_eq!(read_stream(&back, "/BinData/BIN0001.OLE"), data);
}
#[test]
fn test_build_cfb_collapses_empty_path_segments() {
let data = vec![0x11u8; 10];
let messy = build_cfb(&[("//A//B/", data.as_slice())]).unwrap();
let clean = build_cfb(&[("/A/B", data.as_slice())]).unwrap();
assert_eq!(
messy, clean,
"빈 세그먼트는 이름 없는 엔트리를 만들면 안 된다"
);
assert_eq!(read_stream(&messy, "/A/B"), data);
}
#[test]
fn test_build_cfb_rejects_degenerate_paths() {
let data = b"x" as &[u8];
assert!(build_cfb(&[("", data)]).is_err());
assert!(build_cfb(&[("/", data)]).is_err());
assert!(build_cfb(&[("\\", data)]).is_err());
assert!(build_cfb(&[("///", data)]).is_err());
}
#[test]
fn test_build_entries_does_not_clobber_root_entry() {
let data = vec![0xEEu8; 64];
let bytes = build_cfb(&[("/Root Entry", data.as_slice())]).unwrap();
assert_eq!(read_stream(&bytes, "/Root Entry"), data);
}
#[test]
fn test_build_cfb_rejects_storage_stream_conflict() {
let data = vec![0x22u8; 10];
assert!(build_cfb(&[("/A/B", data.as_slice()), ("/A", data.as_slice())]).is_err());
assert!(build_cfb(&[("/A", data.as_slice()), ("/A/B", data.as_slice())]).is_err());
}
#[test]
fn test_build_cfb_with_root_clsid_writes_dir_entry_offset_80() {
const CLSID: [u8; 16] = [
0x37, 0xa1, 0x3d, 0x4c, 0x90, 0xdc, 0xb9, 0x47, 0x9b, 0xed, 0x59, 0xda, 0xe3, 0x52,
0xa2, 0x80,
];
let data = vec![0x99u8; 32];
let bytes = build_cfb_with_root_clsid(&[("/Contents", data.as_slice())], CLSID).unwrap();
assert_eq!(&bytes[8..24], &[0u8; 16], "헤더 CLSID 는 0 이어야 한다");
assert_eq!(
&bytes[512 + 80..512 + 96],
&CLSID,
"루트 디렉터리 엔트리 +80"
);
assert_eq!(&bytes[512 + 128 + 80..512 + 128 + 96], &[0u8; 16]);
let via_crate = cfb::CompoundFile::open(std::io::Cursor::new(&bytes))
.unwrap()
.root_entry()
.clsid()
.to_bytes_le();
assert_eq!(via_crate, CLSID);
let zeroed = build_cfb(&[("/Contents", data.as_slice())]).unwrap();
assert_eq!(&zeroed[512 + 80..512 + 96], &[0u8; 16]);
}
}