encoding/codec/
error.rs

1// This is a part of rust-encoding.
2// Copyright (c) 2013-2015, Kang Seonghoon.
3// See README.md and LICENSE.txt for details.
4
5//! A placeholder encoding that returns encoder/decoder error for every case.
6
7use std::convert::Into;
8use types::*;
9
10/// An encoding that returns encoder/decoder error for every case.
11#[derive(Clone, Copy)]
12pub struct ErrorEncoding;
13
14impl 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/// An encoder that always returns error.
21#[derive(Clone, Copy)]
22pub struct ErrorEncoder;
23
24impl ErrorEncoder {
25    pub fn new() -> Box<RawEncoder> { Box::new(ErrorEncoder) }
26}
27
28impl 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/// A decoder that always returns error.
46#[derive(Clone, Copy)]
47pub struct ErrorDecoder;
48
49impl ErrorDecoder {
50    pub fn new() -> Box<RawDecoder> { Box::new(ErrorDecoder) }
51}
52
53impl 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)]
71mod 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}