Skip to content

Commit db418ad

Browse files
committed
improved replace_lump that actually improves filesize
1 parent b6cdc4c commit db418ad

File tree

2 files changed

+22
-19
lines changed

2 files changed

+22
-19
lines changed

src/bin/bsp.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
154154
io::copy(&mut slice, &mut lump_writer)?;
155155

156156
// replace bsp entity lump with a stripped one
157-
bsp.replace_lump(LumpIndex::LUMP_ENTITIES, &new_slice);
157+
bsp.replace_lump(LumpIndex::LUMP_ENTITIES, new_slice);
158158

159159
let lump_file = File::create(t.output)?;
160160
let mut lump_writer = BufWriter::new(lump_file);

src/bsp/buffered_bsp.rs

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,27 +20,30 @@ impl BufferedBSP {
2020
[(lump.off - BSP_HEADER_LEN) as usize..(lump.off + lump.len - BSP_HEADER_LEN) as usize]
2121
}
2222

23-
pub fn replace_lump(&mut self, lump_index: LumpIndex, new_lump: &[u8]) {
23+
pub fn replace_lump(&mut self, lump_index: LumpIndex, new_lump: Vec<u8>) {
2424
let mut lump = &mut self.header.lumps[lump_index as usize];
25-
assert!(
26-
new_lump.len() < lump.len as usize,
27-
"new lump must be smaller than old lump due to how we replace it"
28-
);
29-
30-
// zero old slice
31-
let old_slice = &mut self.data_without_header
32-
[(lump.off - BSP_HEADER_LEN) as usize..(lump.off + lump.len - BSP_HEADER_LEN) as usize];
33-
for i in old_slice {
34-
*i = 0;
35-
}
25+
let new_lump_len = new_lump.len() as u32;
26+
let lump_len_diff = (new_lump_len as i32) - (lump.len as i32);
27+
28+
// replace range in data
29+
self.data_without_header
30+
.splice(
31+
(lump.off - BSP_HEADER_LEN) as usize
32+
..(lump.off + lump.len - BSP_HEADER_LEN) as usize,
33+
new_lump,
34+
)
35+
.count();
3636

37-
// set new slice
38-
self.data_without_header[(lump.off - BSP_HEADER_LEN) as usize
39-
..(lump.off - BSP_HEADER_LEN) as usize + new_lump.len()]
40-
.copy_from_slice(new_lump);
37+
// set new lump length in header
38+
lump.len = new_lump_len;
4139

42-
// set length in header
43-
lump.len = new_lump.len() as u32;
40+
// fix offset of all lumps with offsets higher than this lump's offset
41+
let lump_off = lump.off;
42+
for mut some_lump in &mut self.header.lumps {
43+
if some_lump.off > lump_off {
44+
some_lump.off = (some_lump.off as i32 + lump_len_diff) as u32;
45+
}
46+
}
4447
}
4548

4649
pub fn write<W: Write>(&self, writer: &mut W) -> Result<(), Box<dyn std::error::Error>> {

0 commit comments

Comments
 (0)