pub struct MtfDecoder {
symbols: [u8; 256],
}
impl MtfDecoder {
pub fn new() -> Self {
let mut symbols = [0u8; 256];
for (i, s) in symbols.iter_mut().enumerate() {
*s = i as u8;
}
Self { symbols }
}
pub fn with_symbols(symbols: [u8; 256]) -> Self {
Self { symbols }
}
#[inline(always)]
pub fn decode(&mut self, n: u8) -> u8 {
let idx = n as usize;
let b = self.symbols[idx];
if idx == 0 {
return b;
}
if idx == 1 {
self.symbols[1] = self.symbols[0];
self.symbols[0] = b;
return b;
}
self.symbols.copy_within(..idx, 1);
self.symbols[0] = b;
b
}
#[inline]
pub fn first(&self) -> u8 {
self.symbols[0]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic_mtf() {
let mut mtf = MtfDecoder::new();
assert_eq!(mtf.decode(5), 5);
assert_eq!(mtf.first(), 5);
assert_eq!(mtf.decode(0), 5); assert_eq!(mtf.decode(1), 0); }
}