aboutsummaryrefslogtreecommitdiff
path: root/src/dependency_history.rs
blob: 4e36a7b93c62c15f0ffce7fc406f7901407b59d5 (plain)
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
//! Dependency history.

use std::any::type_name;
use std::collections::HashSet;
use std::fmt::{Debug, Display};

const BOLD_MODE: &str = "\x1b[1m";
const RESET_BOLD_MODE: &str = "\x1b[22m";

/// Dependency history interface.
///
/// **This trait is sealed and cannot be implemented for types outside this crate.**
pub trait IDependencyHistory: private::Sealed
{
    #[doc(hidden)]
    fn push<Dependency: 'static + ?Sized>(&mut self);

    #[doc(hidden)]
    fn contains<Dependency: 'static + ?Sized>(&self) -> bool;
}

/// Dependency history.
#[derive(Clone, Debug)]
pub struct DependencyHistory
{
    inner: Vec<&'static str>,
}

impl DependencyHistory
{
    #[must_use]
    pub(crate) fn new() -> Self
    {
        Self { inner: vec![] }
    }
}

impl IDependencyHistory for DependencyHistory
{
    #[doc(hidden)]
    fn push<Dependency: 'static + ?Sized>(&mut self)
    {
        self.inner.push(type_name::<Dependency>());
    }

    #[doc(hidden)]
    fn contains<Dependency: 'static + ?Sized>(&self) -> bool
    {
        self.inner.contains(&type_name::<Dependency>())
    }
}

impl Display for DependencyHistory
{
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
    {
        let mut found_items = HashSet::new();

        let opt_dupe_item = self.inner.iter().find(|item| {
            if found_items.contains(item) {
                return true;
            }

            found_items.insert(*item);

            false
        });

        for (index, item) in self.inner.iter().enumerate() {
            let mut item_is_dupe = false;

            if let Some(dupe_item) = opt_dupe_item {
                if *item == *dupe_item {
                    formatter
                        .write_fmt(format_args!("{BOLD_MODE}{item}{RESET_BOLD_MODE}"))?;

                    item_is_dupe = true;
                }
            }

            if !item_is_dupe {
                formatter.write_str(item)?;
            }

            if index != self.inner.len() - 1 {
                formatter.write_str(" -> ")?;
            }
        }

        if opt_dupe_item.is_some() {
            formatter.write_str(" -> ...")?;
        }

        Ok(())
    }
}

impl Default for DependencyHistory
{
    fn default() -> Self
    {
        Self::new()
    }
}

impl private::Sealed for DependencyHistory {}

pub(crate) mod private
{
    pub trait Sealed {}
}

#[cfg(test)]
mod tests
{
    use super::*;
    use crate::test_utils::subjects;

    #[test]
    fn can_push()
    {
        let mut dependency_history = DependencyHistory::new();

        dependency_history.push::<dyn subjects::INumber>();

        assert!(dependency_history
            .inner
            .contains(&type_name::<dyn subjects::INumber>()));
    }

    #[test]
    fn contains_works()
    {
        let mut dependency_history = DependencyHistory::new();

        dependency_history
            .inner
            .push(type_name::<dyn subjects::IUserManager>());

        assert!(dependency_history.contains::<dyn subjects::IUserManager>());

        assert!(!dependency_history.contains::<dyn subjects::INumber>());
    }

    #[test]
    fn display_works()
    {
        trait Ninja {}
        trait Katana {}
        trait Blade {}

        let mut dependency_history = DependencyHistory::new();

        dependency_history.inner.push(type_name::<dyn Ninja>());
        dependency_history.inner.push(type_name::<dyn Katana>());
        dependency_history.inner.push(type_name::<dyn Blade>());

        assert_eq!(
            dependency_history.to_string(),
            format!(
                "{} -> {} -> {}",
                type_name::<dyn Ninja>(),
                type_name::<dyn Katana>(),
                type_name::<dyn Blade>()
            )
        );

        dependency_history.inner.push(type_name::<dyn Katana>());

        assert_eq!(
            dependency_history.to_string(),
            format!(
                concat!(
                    "{} -> {bold_mode}{}{reset_bold_mode} -> {} -> ",
                    "{bold_mode}{}{reset_bold_mode} -> ...",
                ),
                type_name::<dyn Ninja>(),
                type_name::<dyn Katana>(),
                type_name::<dyn Blade>(),
                type_name::<dyn Katana>(),
                bold_mode = BOLD_MODE,
                reset_bold_mode = RESET_BOLD_MODE
            )
        );
    }
}