From 931d256d62a1a20c8ba8a8b6726fb1d7167f1d68 Mon Sep 17 00:00:00 2001 From: Akshay Date: Sun, 4 Apr 2021 15:42:36 +0530 Subject: speed up pixmap drawing! --- src/utils.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) (limited to 'src/utils.rs') diff --git a/src/utils.rs b/src/utils.rs index bee5782..ab446f4 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -108,3 +108,36 @@ pub fn load_file>(path: P) -> Result { image.read_to_end(&mut buf)?; Ok(Image::decode(&mut (Cursor::new(buf))).unwrap()) // TODO: obi error } + +pub fn compress(scanline: &[T]) -> Vec<(T, usize)> { + let mut runs = vec![]; + if scanline.is_empty() { + return runs; + } + let mut idx = 0; + loop { + let first = &scanline[idx]; + let run_length = scanline[idx..] + .iter() + .take_while(|&item| item == first) + .count(); + + runs.push((first.clone(), run_length)); + + idx += run_length; + if idx > scanline.len() - 1 { + break; + } + } + runs +} + +#[cfg(test)] +mod tests { + use super::compress; + #[test] + fn compression() { + let sl = [1, 1, 1, 2, 2, 2]; + assert_eq!(compress(&sl), vec![(1, 3), (2, 3)]); + } +} -- cgit v1.2.3