Skip to content

Commit

Permalink
Bubble up I/O errors in decode_stream
Browse files Browse the repository at this point in the history
  • Loading branch information
qsantos committed Jun 19, 2024
1 parent 883e986 commit 3cae425
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
14 changes: 10 additions & 4 deletions src/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,12 +212,16 @@ pub fn decode_string(input: &[u8], char_decode: fn(u8) -> char) -> String {
/// ripmors::decode_stream(&mut stdin, &mut stdout, ripmors::to_standard);
/// }
/// ```
pub fn decode_stream(input: &mut impl Read, output: &mut impl Write, char_decode: fn(u8) -> char) {
pub fn decode_stream(
input: &mut impl Read,
output: &mut impl Write,
char_decode: fn(u8) -> char,
) -> Result<(), std::io::Error> {
let mut input_buf = vec![0u8; 1 << 15];
let mut bytes_available = 0;
let mut output_buf = Vec::with_capacity(1 << 15);
loop {
let bytes_read = input.read(&mut input_buf[bytes_available..]).unwrap();
let bytes_read = input.read(&mut input_buf[bytes_available..])?;
if bytes_read == 0 {
break;
}
Expand All @@ -228,7 +232,7 @@ pub fn decode_stream(input: &mut impl Read, output: &mut impl Write, char_decode
// flush buffer
if !output_buf.is_empty() {
let decoded: String = output_buf.iter().collect();
output.write_all(decoded.as_bytes()).unwrap();
output.write_all(decoded.as_bytes())?;
output_buf.clear();
}

Expand All @@ -240,9 +244,11 @@ pub fn decode_stream(input: &mut impl Read, output: &mut impl Write, char_decode
decode_buffer_end(&input_buf[..bytes_available], char_decode, &mut output_buf);
if !output_buf.is_empty() {
let decoded: String = output_buf.iter().collect();
output.write_all(decoded.as_bytes()).unwrap();
output.write_all(decoded.as_bytes())?;
}
}

Ok(())
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ fn main() {
DecodeVariant::Hebrew => to_hebrew,
DecodeVariant::Arabic => to_arabic,
};
decode_stream(&mut stdin, &mut stdout, char_decode);
decode_stream(&mut stdin, &mut stdout, char_decode).unwrap();
} else if args.encode == Some(EncodeVariant::Ascii) {
encode_stream_ascii(&mut stdin, &mut stdout).unwrap();
} else {
Expand Down
2 changes: 1 addition & 1 deletion tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,6 @@ fn test_encode_stream_unicode() {
fn test_decode_stream() {
let mut f = std::fs::File::open("2-encoded.txt").unwrap();
let mut writer = BufWriter::new(Vec::new());
decode_stream(&mut f, &mut writer, to_standard);
decode_stream(&mut f, &mut writer, to_standard).unwrap();
compare_output_to_oracle(writer, "3-decoded.txt");
}

0 comments on commit 3cae425

Please sign in to comment.