ansi_color_codec/
decoder.rs

1use crate::pair_decoder::PairDecoder;
2use crate::parser::Parser;
3
4/// Gives the ability to decode bytes from ANSI background colors.
5pub trait Decoder {
6    /// A type to parse color codes.
7    type Parser;
8    /// A type to decode color codes.
9    type Decoder;
10
11    /// Parse bytes into color codes.
12    fn parse(self) -> Self::Parser;
13
14    /// Decode color codes to bytes.
15    fn decode(self) -> Self::Decoder;
16}
17
18impl<T> Decoder for T {
19    type Parser = Parser<T>;
20    type Decoder = PairDecoder<Parser<T>>;
21
22    /// Parse ANSI color codes from a byte iterator.
23    fn parse(self) -> Self::Parser {
24        self.into()
25    }
26
27    /// Return an iterator that decodes all bytes interpreted as a sequence of ANSI background
28    /// colors to raw bytes.
29    ///
30    /// # Examples
31    ///
32    /// ```
33    /// use ansi_color_codec::Codec;
34    ///
35    /// let text = String::from("Hello world.");
36    /// let code: String = text
37    ///     .bytes()
38    ///     .encode()
39    ///     .map(|color| color.to_string())
40    ///     .collect();
41    /// let decoded: String = code
42    ///     .bytes()
43    ///     .decode()
44    ///     .filter_map(|result| result.map(|byte| byte as char).ok())
45    ///     .collect();
46    /// assert_eq!(text, decoded);
47    /// ```
48    fn decode(self) -> Self::Decoder {
49        <Self as Decoder>::parse(self).into()
50    }
51}