Ignore newlines when decoding

This commit is contained in:
Nathan Fisher 2025-01-05 12:17:42 -05:00
parent 0493911702
commit 841160d2d5

View file

@ -28,20 +28,33 @@ impl<R: Read, W: Write> Decoder<R, W> {
/// `Error::MissingPadding`
/// - `intError` should never be returned. If this error is recieved the code
/// is somehow broken. Please file a bug.
pub fn decode(&mut self) -> Result<(), Error> {
pub fn decode(mut self) -> Result<W, Error> {
let mut byte_reader = self.reader.bytes();
loop {
let mut in_buf = [0_u8; 4];
let mut out_buf = [0_u8; 3];
let mut num = 0_u32;
let mut n_bytes = 0;
loop {
n_bytes += match self.reader.read(&mut in_buf) {
Ok(n) => n,
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => return Err(e.into()),
};
while n_bytes < 4 {
if let Some(byte) = byte_reader.next() {
match byte {
Ok(b) => {
if b == b'\n' {
continue;
}
in_buf[n_bytes] = b;
n_bytes += 1;
}
Err(e) => match e.kind() {
ErrorKind::UnexpectedEof => break,
ErrorKind::Interrupted => continue,
_ => return Err(e.into()),
}
}
} else {
break;
}
}
match n_bytes {
0 => break,
4 => {}
@ -70,7 +83,7 @@ impl<R: Read, W: Write> Decoder<R, W> {
}
self.writer.write_all(&out_buf[0..olen])?;
}
Ok(())
Ok(self.writer)
}
}
@ -80,16 +93,19 @@ mod tests {
#[test]
fn decode() {
let mut decoder = Decoder::new("SGVsbG8sIFdvcmxk".as_bytes(), vec![], None);
decoder.decode().unwrap();
assert_eq!(String::from_utf8(decoder.writer).unwrap(), "Hello, World");
decoder = Decoder::new("SGVsbG8sIFdvcmxkIQ==".as_bytes(), vec![], None);
decoder.decode().unwrap();
assert_eq!(String::from_utf8(decoder.writer).unwrap(), "Hello, World!");
decoder = Decoder::new("SGVsbG8sIFdvcmxkIQo=".as_bytes(), vec![], None);
decoder.decode().unwrap();
let mut output = vec![];
let mut decoder = Decoder::new("SGVsbG8sIFdvcmxk".as_bytes(), output, None);
output = decoder.decode().unwrap();
assert_eq!(String::from_utf8(output.clone()).unwrap(), "Hello, World");
output.clear();
decoder = Decoder::new("SGVsbG8sIFdvcmxkIQ==".as_bytes(), output, None);
output = decoder.decode().unwrap();
assert_eq!(String::from_utf8(output.clone()).unwrap(), "Hello, World!");
output.clear();
decoder = Decoder::new("SGVsbG8sIFdvcmxkIQo=".as_bytes(), output, None);
output = decoder.decode().unwrap();
assert_eq!(
String::from_utf8(decoder.writer).unwrap(),
String::from_utf8(output).unwrap(),
"Hello, World!\n"
);
}