| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
use std::convert::Into; |
| 8 |
use types::*; |
| 9 |
|
| 10 |
|
| 11 |
#[derive(Clone, Copy)] |
| 12 |
pub struct ErrorEncoding; |
| 13 |
|
| 14 |
impl Encoding for ErrorEncoding { |
| 15 |
fn name(&self) -> &'static str { "error" } |
| 16 |
fn raw_encoder(&self) -> Box<RawEncoder> { ErrorEncoder::new() } |
| 17 |
fn raw_decoder(&self) -> Box<RawDecoder> { ErrorDecoder::new() } |
| 18 |
} |
| 19 |
|
| 20 |
|
| 21 |
#[derive(Clone, Copy)] |
| 22 |
pub struct ErrorEncoder; |
| 23 |
|
| 24 |
impl ErrorEncoder { |
| 25 |
pub fn new() -> Box<RawEncoder> { Box::new(ErrorEncoder) } |
| 26 |
} |
| 27 |
|
| 28 |
impl RawEncoder for ErrorEncoder { |
| 29 |
fn from_self(&self) -> Box<RawEncoder> { ErrorEncoder::new() } |
| 30 |
|
| 31 |
fn raw_feed(&mut self, input: &str, _output: &mut ByteWriter) -> (usize, Option<CodecError>) { |
| 32 |
if let Some(ch) = input.chars().next() { |
| 33 |
(0, Some(CodecError { upto: ch.len_utf8() as isize, |
| 34 |
cause: "unrepresentable character".into() })) |
| 35 |
} else { |
| 36 |
(0, None) |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
fn raw_finish(&mut self, _output: &mut ByteWriter) -> Option<CodecError> { |
| 41 |
None |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
#[derive(Clone, Copy)] |
| 47 |
pub struct ErrorDecoder; |
| 48 |
|
| 49 |
impl ErrorDecoder { |
| 50 |
pub fn new() -> Box<RawDecoder> { Box::new(ErrorDecoder) } |
| 51 |
} |
| 52 |
|
| 53 |
impl RawDecoder for ErrorDecoder { |
| 54 |
fn from_self(&self) -> Box<RawDecoder> { ErrorDecoder::new() } |
| 55 |
|
| 56 |
fn raw_feed(&mut self, |
| 57 |
input: &[u8], _output: &mut StringWriter) -> (usize, Option<CodecError>) { |
| 58 |
if input.len() > 0 { |
| 59 |
(0, Some(CodecError { upto: 1, cause: "invalid sequence".into() })) |
| 60 |
} else { |
| 61 |
(0, None) |
| 62 |
} |
| 63 |
} |
| 64 |
|
| 65 |
fn raw_finish(&mut self, _output: &mut StringWriter) -> Option<CodecError> { |
| 66 |
None |
| 67 |
} |
| 68 |
} |
| 69 |
|
| 70 |
#[cfg(test)] |
| 71 |
mod tests { |
| 72 |
use super::ErrorEncoding; |
| 73 |
use types::*; |
| 74 |
|
| 75 |
#[test] |
| 76 |
fn test_encoder() { |
| 77 |
let mut e = ErrorEncoding.raw_encoder(); |
| 78 |
assert_feed_err!(e, "", "A", "", []); |
| 79 |
assert_feed_err!(e, "", "B", "C", []); |
| 80 |
assert_feed_ok!(e, "", "", []); |
| 81 |
assert_feed_err!(e, "", "\u{a0}", "", []); |
| 82 |
assert_finish_ok!(e, []); |
| 83 |
} |
| 84 |
|
| 85 |
#[test] |
| 86 |
fn test_decoder() { |
| 87 |
let mut d = ErrorEncoding.raw_decoder(); |
| 88 |
assert_feed_err!(d, [], [0x41], [], ""); |
| 89 |
assert_feed_err!(d, [], [0x42], [0x43], ""); |
| 90 |
assert_feed_ok!(d, [], [], ""); |
| 91 |
assert_feed_err!(d, [], [0xa0], [], ""); |
| 92 |
assert_finish_ok!(d, ""); |
| 93 |
} |
| 94 |
} |