ableos/ableos/src/relib/encoding/rle.rs

44 lines
1.0 KiB
Rust

pub fn encode(bytes: &[u8]) -> Vec<u8> {
let mut encoding = if bytes.first().is_none() {
return vec![];
} else {
vec![*bytes.first().unwrap()]
};
let mut occurrences = 1;
for byte in bytes.iter().skip(1) {
if byte == encoding.last().unwrap() && occurrences < 255 {
occurrences += 1;
} else {
encoding.extend(&[occurrences, *byte]);
occurrences = 1;
}
}
encoding.push(occurrences);
encoding
}
/// Read a run-length encoding and return its decoded contents.
///
/// * `bytes` - The bytes to be decoded.
pub fn decode(bytes: &[u8]) -> Vec<u8> {
let mut decoding = Vec::<u8>::new();
for (i, byte) in bytes.iter().enumerate() {
if i % 2 != 0 {
continue;
}
// Repeat bytes[i], bytes[i+1] times in a row.
// e.g.: "!!" equals to 33 times "!" ("!" value in ASCII).
for _j in 0..bytes[i + 1] {
decoding.push(*byte)
}
}
decoding
}