Skip to content

Commit

Permalink
Do not allocate buffer size before necessary
Browse files Browse the repository at this point in the history
  • Loading branch information
dragly committed Dec 19, 2019
1 parent 1b500e1 commit 35eef9d
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/decode/lzbuffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,25 @@ where
pub fn from_stream(stream: &'a mut W, dict_size: usize) -> Self {
info!("Dict size in LZ buffer: {}", dict_size);
Self {
stream,
buf: vec![0; dict_size],
stream: stream,
buf: Vec::new(),
dict_size,
cursor: 0,
len: 0,
}
}

fn get(&self, index: usize) -> u8 {
match self.buf.get(index) {
Some(x) => *x,
None => 0
}
}

fn get_mut(&mut self, index: usize) -> &mut u8 {
self.buf.resize(index + 1, 0);
self.buf.get_mut(index).unwrap()
}
}

impl<'a, W> LZBuffer for LZCircularBuffer<'a, W>
Expand All @@ -160,7 +172,7 @@ where
if self.len == 0 {
lit
} else {
self.buf[(self.dict_size + self.cursor - 1) % self.dict_size]
self.get((self.dict_size + self.cursor - 1) % self.dict_size)
}
}

Expand All @@ -180,12 +192,12 @@ where
}

let offset = (self.dict_size + self.cursor - dist) % self.dict_size;
Ok(self.buf[offset])
Ok(self.get(offset))
}

// Append a literal
fn append_literal(&mut self, lit: u8) -> io::Result<()> {
self.buf[self.cursor] = lit;
*self.get_mut(self.cursor) = lit;
self.cursor += 1;
self.len += 1;

Expand Down Expand Up @@ -216,7 +228,7 @@ where

let mut offset = (self.dict_size + self.cursor - dist) % self.dict_size;
for _ in 0..len {
let x = self.buf[offset];
let x = self.get(offset);
self.append_literal(x)?;
offset += 1;
if offset == self.dict_size {
Expand Down

0 comments on commit 35eef9d

Please sign in to comment.