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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
//! A module which contains [Colors] trait and its blanket implementations.

use crate::{ansi::ANSIFmt, config::Position};

/// A trait which represents map of colors.
pub trait Colors {
    /// Color implementation.
    type Color: ANSIFmt;

    /// Returns a color for a given position.
    fn get_color(&self, pos: (usize, usize)) -> Option<&Self::Color>;

    /// Verifies whether a map is empty or not.
    fn is_empty(&self) -> bool;
}

impl<C> Colors for &'_ C
where
    C: Colors,
{
    type Color = C::Color;

    fn get_color(&self, pos: Position) -> Option<&Self::Color> {
        C::get_color(self, pos)
    }

    fn is_empty(&self) -> bool {
        C::is_empty(self)
    }
}

#[cfg(feature = "std")]
impl<C> Colors for std::collections::HashMap<Position, C>
where
    C: ANSIFmt,
{
    type Color = C;

    fn get_color(&self, pos: Position) -> Option<&Self::Color> {
        self.get(&pos)
    }

    fn is_empty(&self) -> bool {
        std::collections::HashMap::is_empty(self)
    }
}

#[cfg(feature = "std")]
impl<C> Colors for std::collections::BTreeMap<Position, C>
where
    C: ANSIFmt,
{
    type Color = C;

    fn get_color(&self, pos: Position) -> Option<&Self::Color> {
        self.get(&pos)
    }

    fn is_empty(&self) -> bool {
        std::collections::BTreeMap::is_empty(self)
    }
}

#[cfg(feature = "std")]
impl<C> Colors for crate::config::spanned::EntityMap<Option<C>>
where
    C: ANSIFmt,
{
    type Color = C;

    fn get_color(&self, pos: Position) -> Option<&Self::Color> {
        self.get(pos.into()).as_ref()
    }

    fn is_empty(&self) -> bool {
        crate::config::spanned::EntityMap::is_empty(self)
            && self.get(crate::config::Entity::Global).is_none()
    }
}

/// The structure represents empty [`Colors`] map.
#[derive(Debug, Default, Clone)]
pub struct NoColors;

impl Colors for NoColors {
    type Color = EmptyColor;

    fn get_color(&self, _: Position) -> Option<&Self::Color> {
        None
    }

    fn is_empty(&self) -> bool {
        true
    }
}

/// A color which is actually has not value.
#[derive(Debug)]
pub struct EmptyColor;

impl ANSIFmt for EmptyColor {
    fn fmt_ansi_prefix<W: core::fmt::Write>(&self, _: &mut W) -> core::fmt::Result {
        Ok(())
    }

    fn fmt_ansi_suffix<W: core::fmt::Write>(&self, _: &mut W) -> core::fmt::Result {
        Ok(())
    }
}