ansi_color_codec/
encoder.rs

1use core::iter::FlatMap;
2
3use crate::code_pair::CodePair;
4
5/// Gives the ability to encode bytes to ANSI background colors.
6pub trait Encoder {
7    /// Type to encode bytes into ANSI color codes.
8    type Encoder;
9
10    /// Encode bytes into ANSI colors.
11    fn encode(self) -> Self::Encoder;
12}
13
14impl<T> Encoder for T
15where
16    T: Iterator<Item = u8>,
17{
18    type Encoder = FlatMap<T, CodePair, fn(u8) -> CodePair>;
19
20    /// Return an iterator that encodes all bytes as ANSI background colors.
21    ///
22    /// # Examples
23    ///
24    /// ```
25    /// use ansi_color_codec::Codec;
26    ///
27    /// let text = String::from("Hello world.");
28    /// let reference: Vec<u8> = vec![
29    ///     27, 91, 52, 52, 109, 32, 27, 91, 49, 48, 48, 109, 32, 27, 91, 52, 54, 109, 32, 27, 91,
30    ///     52, 53, 109, 32, 27, 91, 52, 54, 109, 32, 27, 91, 49, 48, 52, 109, 32, 27, 91, 52, 54,
31    ///     109, 32, 27, 91, 49, 48, 52, 109, 32, 27, 91, 52, 54, 109, 32, 27, 91, 49, 48, 55, 109,
32    ///     32, 27, 91, 52, 50, 109, 32, 27, 91, 52, 48, 109, 32, 27, 91, 52, 55, 109, 32, 27, 91,
33    ///     52, 55, 109, 32, 27, 91, 52, 54, 109, 32, 27, 91, 49, 48, 55, 109, 32, 27, 91, 52, 55,
34    ///     109, 32, 27, 91, 52, 50, 109, 32, 27, 91, 52, 54, 109, 32, 27, 91, 49, 48, 52, 109, 32,
35    ///     27, 91, 52, 54, 109, 32, 27, 91, 52, 52, 109, 32, 27, 91, 52, 50, 109, 32, 27, 91, 49,
36    ///     48, 54, 109, 32,
37    /// ];
38    /// let code: Vec<u8> = text
39    ///     .bytes()
40    ///     .encode()
41    ///     .flat_map(|color| color.to_string().into_bytes())
42    ///     .collect();
43    /// assert_eq!(code, reference);
44    /// ```
45    fn encode(self) -> Self::Encoder {
46        self.flat_map(CodePair::from)
47    }
48}