b32_rs/src/decode.rs

104 lines
3 KiB
Rust

use super::*;
use std::io::{self, ErrorKind, Read, Write};
#[derive(Debug)]
pub enum DecoderError {
IO(io::Error),
IllegalChar,
}
impl From<io::Error> for DecoderError {
fn from(value: io::Error) -> Self {
Self::IO(value)
}
}
pub struct Decoder<R: Read, W: Write> {
reader: R,
writer: W,
alphabet: B32Alphabet,
ignore_whitespace: bool
}
impl<R: Read, W: Write> Decoder<R, W> {
pub fn new(reader: R, writer: W, alphabet: Option<B32Alphabet>, ignore_whitespace: bool) -> Self {
Self {
reader,
writer,
alphabet: alphabet.unwrap_or_default(),
ignore_whitespace,
}
}
pub fn decode(mut self) -> Result<W, DecoderError> {
let mut byte_reader = self.reader.bytes();
'outer: loop {
let mut in_buf = [0_u8; 8];
let mut out_buf = [0_u8; 5];
let mut num: u64 = 0;
let mut n_bytes = 0;
while n_bytes < 8 {
match byte_reader.next() {
Some(Ok(b)) => {
if self.ignore_whitespace && b.is_ascii_whitespace() {
continue;
} else if b == b'\n' || b == b'\r' {
continue;
} else {
in_buf[n_bytes] = b;
n_bytes += 1;
}
}
Some(Err(e)) if e.kind() == ErrorKind::UnexpectedEof => break,
Some(Err(e)) if e.kind() == ErrorKind::Interrupted => continue,
Some(Err(e)) => return Err(e.into()),
None => break,
}
}
for c in &in_buf {
num <<= 5;
if !matches!(self.alphabet.pad(), Some(ch) if ch == *c) {
let idx = self.alphabet.idx(*c).ok_or(DecoderError::IllegalChar)?;
num |= idx as u64;
}
}
for i in (0..5).rev() {
let b = (num & 0xff) as u8;
out_buf[i] = b;
num >>= 8;
}
for c in &out_buf {
if *c == b'\0' {
break 'outer;
} else {
self.writer.write_all(&[*c])?;
}
}
}
self.writer.flush()?;
Ok(self.writer)
}
}
#[cfg(test)]
mod tests {
use super::*;
static HELLO: &'static str = "Hello, World!";
static ENCODED: &'static str = "JBSWY3DPFQQFO33SNRSCC===";
#[test]
fn get_idx() {
let idx = B32_RFC4648_ALPHABET.idx(b'S').unwrap();
assert_eq!(idx, 18);
}
#[test]
fn hello() {
let reader = ENCODED.as_bytes();
let writer = Vec::<u8>::new();
let decoder = Decoder::new(reader, writer, None, false);
let output = decoder.decode().unwrap();
assert_eq!(HELLO.as_bytes(), output);
}
}