Skip to content

Commit 37748b3

Browse files
authored
Optimize GzipEncoder to not allocate for header and footer (#431)
Fixed #397 Signed-off-by: Jiahao XU <[email protected]>
1 parent 1627bfc commit 37748b3

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

crates/compression-codecs/src/gzip/encoder.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ use std::io;
55

66
#[derive(Debug)]
77
enum State {
8-
Header(PartialBuffer<Vec<u8>>),
8+
Header(PartialBuffer<[u8; 10]>),
99
Encoding,
10-
Footer(PartialBuffer<Vec<u8>>),
10+
Footer(PartialBuffer<[u8; 8]>),
1111
Done,
1212
}
1313

@@ -18,7 +18,7 @@ pub struct GzipEncoder {
1818
state: State,
1919
}
2020

21-
fn header(level: Compression) -> Vec<u8> {
21+
fn header(level: Compression) -> [u8; 10] {
2222
let level_byte = if level.level() >= Compression::best().level() {
2323
0x02
2424
} else if level.level() <= Compression::fast().level() {
@@ -27,7 +27,7 @@ fn header(level: Compression) -> Vec<u8> {
2727
0x00
2828
};
2929

30-
vec![0x1f, 0x8b, 0x08, 0, 0, 0, 0, 0, level_byte, 0xff]
30+
[0x1f, 0x8b, 0x08, 0, 0, 0, 0, 0, level_byte, 0xff]
3131
}
3232

3333
impl GzipEncoder {
@@ -39,11 +39,11 @@ impl GzipEncoder {
3939
}
4040
}
4141

42-
fn footer(&mut self) -> Vec<u8> {
43-
let mut output = Vec::with_capacity(8);
42+
fn footer(&mut self) -> [u8; 8] {
43+
let mut output = [0; 8];
4444

45-
output.extend(&self.crc.sum().to_le_bytes());
46-
output.extend(&self.crc.amount().to_le_bytes());
45+
output[..4].copy_from_slice(&self.crc.sum().to_le_bytes());
46+
output[4..].copy_from_slice(&self.crc.amount().to_le_bytes());
4747

4848
output
4949
}

0 commit comments

Comments
 (0)