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
#![no_std]
#![doc = include_str!("../README.md")]
extern crate alloc;

use core::fmt::{Display, Write};

/// Configurable Display implementation for slices and Vecs.
pub trait SliceDisplay<'a, T: Display> {
    #[must_use = "this does not display the slice, \
                  it returns an object that can be displayed"]
    fn display(&'a self) -> SliceDisplayImpl<'a, T>;
}

/// Helper struct for printing Vecs and slices.
#[derive(Clone, Copy)]
pub struct SliceDisplayImpl<'a, T: Display> {
    slice: &'a [T],
    terminators: (char, char),
    delimiter: char,
    should_space: bool,
}

impl<'a, T: Display> SliceDisplayImpl<'a, T> {
    /// Configures the terminators to be used for the display.
    ///
    /// # Example
    ///
    /// ```rust
    /// use slicedisplay::SliceDisplay;
    ///
    /// let hello: Vec<_> = "Hello".chars().collect();
    ///
    /// assert_eq!(hello.display().terminator('{', '}').to_string(), "{H, e, l, l, o}");
    /// ```
    pub fn terminator(self, beginning: char, ending: char) -> Self {
        Self {
            terminators: (beginning, ending),
            ..self
        }
    }

    /// Configures the delimiter to be used for the display.
    ///
    /// # Example
    ///
    /// ```rust
    /// use slicedisplay::SliceDisplay;
    ///
    /// let hello: Vec<_> = "Hello".chars().collect();
    ///
    /// assert_eq!(hello.display().delimiter(';').to_string(), "[H; e; l; l; o]");
    /// ```
    pub fn delimiter(self, delimiter: char) -> Self {
        Self { delimiter, ..self }
    }

    /// Sets whether additional spacing should be added between elements.
    ///
    /// True by default.
    ///
    /// # Example
    ///
    /// ```rust
    /// use slicedisplay::SliceDisplay;
    ///
    /// let hello: Vec<_> = "Hello".chars().collect();
    ///
    /// assert_eq!(hello.display().delimiter(';').to_string(), "[H; e; l; l; o]");
    /// assert_eq!(hello.display().delimiter(';').should_space(false).to_string(), "[H;e;l;l;o]");
    /// ```
    pub fn should_space(self, should_space: bool) -> Self {
        Self {
            should_space,
            ..self
        }
    }
}

impl<T: Display, A> SliceDisplay<'_, T> for A
where
    A: AsRef<[T]>,
{
    fn display(&self) -> SliceDisplayImpl<'_, T> {
        SliceDisplayImpl {
            slice: self.as_ref(),
            terminators: ('[', ']'),
            delimiter: ',',
            should_space: true,
        }
    }
}

impl<'a, T: Display> Display for SliceDisplayImpl<'a, T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let (beginning, ending) = self.terminators;
        let delimiter = self.delimiter;
        let spacing = if self.should_space { " " } else { "" };

        f.write_char(beginning)?;
        if let Some((last, elems)) = self.slice.split_last() {
            for elem in elems {
                write!(f, "{elem}{delimiter}{spacing}")?;
            }
            write!(f, "{last}")?;
        }

        f.write_char(ending)
    }
}

#[cfg(test)]
mod tests {
    use alloc::{string::ToString, vec::Vec};

    use crate::SliceDisplay;

    extern crate alloc;

    #[test]
    fn slice_display_empty() {
        // Slighly redundant in order to ensure that we can
        // call Display on any AsRef<T>
        let empty: Vec<u8> = Vec::new();
        let empty_array: [u8; 0] = [];
        let empty_slice: &[u8] = &[];

        assert_eq!(empty.display().to_string(), "[]");
        assert_eq!(empty_array.display().to_string(), "[]");
        assert_eq!(empty_slice.display().to_string(), "[]");
    }

    #[test]
    fn slice_display_single() {
        let single = [1];
        assert_eq!(single.display().to_string(), "[1]");
    }

    #[test]
    fn slice_display_multiple() {
        let numbers = [1, 2, 3, 4, 5];
        assert_eq!(numbers.display().to_string(), "[1, 2, 3, 4, 5]");
    }

    #[test]
    fn slice_display_custom_delimiter() {
        let numbers = [1, 2, 3, 4, 5];
        assert_eq!(
            numbers.display().delimiter(';').to_string(),
            "[1; 2; 3; 4; 5]"
        );
        assert_eq!(
            numbers
                .display()
                .delimiter('-')
                .should_space(false)
                .to_string(),
            "[1-2-3-4-5]"
        );
    }

    #[test]
    fn slice_display_custom_terminators() {
        let numbers = [1, 2, 3, 4, 5];
        assert_eq!(
            numbers.display().terminator('{', '}').to_string(),
            "{1, 2, 3, 4, 5}"
        );
        assert_eq!(
            numbers
                .display()
                .terminator('{', '}')
                .should_space(false)
                .delimiter(';')
                .to_string(),
            "{1;2;3;4;5}"
        );
    }
}