Skip to content

Commit 97a5bfd

Browse files
authored
optimize: replace manual repetition loops with slice fill in decompressor (#428)
In \`read_dynamic_huffman_header\`, the loops used to repeat symbol lengths (codes 16, 17, and 18) were doing per-element assignments and bounds checks. Replacing these with \`slice::fill\` is more idiomatic and performant, as it allows the compiler to optimize the fill operation and avoids unnecessary branching. Safety is maintained by using \`min\` to clamp the fill length to the remaining number of symbols.
1 parent 04905e8 commit 97a5bfd

1 file changed

Lines changed: 9 additions & 18 deletions

File tree

src/decompress/mod.rs

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -458,38 +458,29 @@ impl Decompressor {
458458
let rep_count = 3 + ((self.bitbuf & 3) as usize);
459459
self.bitbuf >>= 2;
460460
self.bitsleft -= 2;
461-
for _ in 0..rep_count {
462-
if i < total_syms {
463-
self.lens[i] = rep_val;
464-
i += 1;
465-
}
466-
}
461+
let fill_len = min(rep_count, total_syms - i);
462+
self.lens[i..i + fill_len].fill(rep_val);
463+
i += fill_len;
467464
} else if presym == 17 {
468465
if self.bitsleft < 3 {
469466
return DecompressResult::ShortInput;
470467
}
471468
let rep_count = 3 + ((self.bitbuf & 7) as usize);
472469
self.bitbuf >>= 3;
473470
self.bitsleft -= 3;
474-
for _ in 0..rep_count {
475-
if i < total_syms {
476-
self.lens[i] = 0;
477-
i += 1;
478-
}
479-
}
471+
let fill_len = min(rep_count, total_syms - i);
472+
self.lens[i..i + fill_len].fill(0);
473+
i += fill_len;
480474
} else {
481475
if self.bitsleft < 7 {
482476
return DecompressResult::ShortInput;
483477
}
484478
let rep_count = 11 + ((self.bitbuf & 0x7F) as usize);
485479
self.bitbuf >>= 7;
486480
self.bitsleft -= 7;
487-
for _ in 0..rep_count {
488-
if i < total_syms {
489-
self.lens[i] = 0;
490-
i += 1;
491-
}
492-
}
481+
let fill_len = min(rep_count, total_syms - i);
482+
self.lens[i..i + fill_len].fill(0);
483+
i += fill_len;
493484
}
494485
}
495486
if i != total_syms {

0 commit comments

Comments
 (0)