1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use std::io::{self, Read};
use encoding_rs_io::{DecodeReaderBytes, DecodeReaderBytesBuilder};
use crate::charsets::Charset;
#[derive(Debug)]
pub struct TextReader<R>(DecodeReaderBytes<R, Vec<u8>>);
impl<R> TextReader<R>
where
R: Read,
{
pub fn new(inner: R, charset: Charset) -> Self {
Self(DecodeReaderBytesBuilder::new().encoding(Some(charset)).build(inner))
}
}
impl<R> Read for TextReader<R>
where
R: Read,
{
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.0.read(buf)
}
}
#[test]
fn test_stream_decoder_utf8() {
let mut reader = TextReader::new("québec".as_bytes(), crate::charsets::UTF_8);
let mut text = String::new();
assert_eq!(reader.read_to_string(&mut text).ok(), Some(7));
assert_eq!(text, "québec");
}
#[test]
fn test_stream_decoder_latin1() {
let mut reader = TextReader::new(&b"qu\xC9bec"[..], crate::charsets::WINDOWS_1252);
let mut text = String::new();
assert_eq!(reader.read_to_string(&mut text).ok(), Some(7));
assert_eq!(text, "quÉbec");
}
#[test]
fn test_string_reader_large_buffer_latin1() {
let buf = vec![201; 10_000];
let mut reader = TextReader::new(&buf[..], crate::charsets::WINDOWS_1252);
let mut text = String::new();
assert_eq!(20_000, reader.read_to_string(&mut text).unwrap());
assert_eq!(text.len(), 20_000);
for c in text.chars() {
assert_eq!(c, 'É');
}
}