From 654be91de3768f7c01acb36ab82460765927493a Mon Sep 17 00:00:00 2001 From: Akshay Date: Mon, 1 Mar 2021 22:10:12 +0530 Subject: add decode logic --- src/decode.rs | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/encode.rs | 11 ++++++----- src/lib.rs | 8 ++++++++ 3 files changed, 64 insertions(+), 5 deletions(-) create mode 100644 src/decode.rs (limited to 'src') diff --git a/src/decode.rs b/src/decode.rs new file mode 100644 index 0000000..59dae97 --- /dev/null +++ b/src/decode.rs @@ -0,0 +1,50 @@ +use std::io::{self, Cursor, Read}; + +use bitvec::prelude::*; +use byteorder::{LittleEndian, ReadBytesExt}; + +use crate::{FileHeader, Image, ImageInfoHeader}; + +pub fn decode_image(obi_data: &mut Cursor>) -> io::Result { + // file header + let version = obi_data.read_u16::()?; + let file_size = obi_data.read_u32::()?; + let data_offset = obi_data.read_u32::()?; + let file_header = FileHeader { + version, + file_size, + data_offset, + }; + + // image info header + let width = obi_data.read_u32::()?; + let height = obi_data.read_u32::()?; + let compression_type = obi_data.read_u32::()?; + let post_compression_size = obi_data.read_u32::()?; + let image_info_header = ImageInfoHeader { + width, + height, + compression_type, + post_compression_size, + }; + + // pixmap data + let mut data_bytes = vec![]; + obi_data.read_to_end(&mut data_bytes)?; + let data = data_bytes + .iter() + .map(|&b| { + BitVec::::from_element(b) + .into_iter() + .map(|e| e as bool) + .collect::>() + }) + .flatten() + .collect::>(); + + return Ok(Image { + file_header, + image_info_header, + data, + }); +} diff --git a/src/encode.rs b/src/encode.rs index 24d3792..e5760a8 100644 --- a/src/encode.rs +++ b/src/encode.rs @@ -1,7 +1,6 @@ use std::io; -use bitvec::prelude::*; -use bitvec::slice::BitSlice; +use bitvec::{prelude::*, vec::BitVec}; use byteorder::{LittleEndian, WriteBytesExt}; use crate::Image; @@ -25,9 +24,11 @@ pub fn encode_image(obi_image: Image) -> io::Result> { // pixmap data let pixmap = obi_image.data; for byte in pixmap.chunks(8) { - let bits_as_u8 = byte.iter().map(|&e| e as u8).collect::>(); - let slice = BitSlice::::from_slice(&bits_as_u8).unwrap(); - obi_data.write_u8(slice.load::())?; + let mut bv = BitVec::::new(); + for &b in byte { + bv.push(b); + } + obi_data.write_u8(bv.load::())?; } return Ok(obi_data); diff --git a/src/lib.rs b/src/lib.rs index 61ca7a8..cd7923c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,7 @@ #![allow(unreachable_patterns)] #![allow(non_snake_case)] +pub mod decode; pub mod encode; #[non_exhaustive] @@ -107,4 +108,11 @@ mod tests { let file_header_size = size_of::(); assert_eq!(16, file_header_size); } + + #[test] + fn encode_decode() { + let img = Image::new(100, 80); + let encoded = encode::encode_image(img).unwrap(); + assert_eq!(encoded.len(), 1026); + } } -- cgit v1.2.3