fmt_utils/std.rs
1use std::fmt;
2
3/// Note: only the Display impl is special; the Debug impl is just a `#[derive]`.
4/// Use <https://crates.io/crates/fmt_adapter> if this is an issue.
5///
6/// ```
7/// use fmt_utils::std::Separated;
8///
9/// assert_eq!(Separated { sep: ',', iter: &[] as &[char] }.to_string(), "");
10/// assert_eq!(Separated { sep: ',', iter: &['a'] }.to_string(), "a");
11/// assert_eq!(Separated { sep: ',', iter: &['a', 'b'] }.to_string(), "a,b");
12/// assert_eq!(Separated { sep: ',', iter: &['a', 'b', 'c'] }.to_string(), "a,b,c");
13/// ```
14#[derive(Copy, Clone, Debug)]
15pub struct Separated<Sep, Iter>
16where
17 Sep: fmt::Display,
18 Iter: Copy + IntoIterator,
19 Iter::Item: fmt::Display,
20{
21 pub sep: Sep,
22 pub iter: Iter,
23}
24
25impl<Sep, Iter> fmt::Display for Separated<Sep, Iter>
26where
27 Sep: fmt::Display,
28 Iter: Copy + IntoIterator,
29 Iter::Item: fmt::Display,
30{
31 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
32 let mut it = self.iter.into_iter();
33 if let Some(x) = it.next() {
34 write!(f, "{}", x)?;
35 for y in it {
36 write!(f, "{}{}", self.sep, y)?;
37 }
38 }
39 Ok(())
40 }
41}
42
43/// Note: only the Display impl is special; the Debug impl is just a `#[derive]`.
44/// Use <https://crates.io/crates/fmt_adapter> if this is an issue.
45///
46/// ```
47/// use fmt_utils::std::Repeated;
48///
49/// assert_eq!(Repeated { value: "", count: 0 }.to_string(), "");
50/// assert_eq!(Repeated { value: 'a', count: 0 }.to_string(), "");
51/// assert_eq!(Repeated { value: "ab", count: 0 }.to_string(), "");
52/// assert_eq!(Repeated { value: "", count: 1 }.to_string(), "");
53/// assert_eq!(Repeated { value: 'a', count: 1 }.to_string(), "a");
54/// assert_eq!(Repeated { value: "ab", count: 1 }.to_string(), "ab");
55/// assert_eq!(Repeated { value: "", count: 2 }.to_string(), "");
56/// assert_eq!(Repeated { value: 'a', count: 2 }.to_string(), "aa");
57/// assert_eq!(Repeated { value: "ab", count: 2 }.to_string(), "abab");
58/// ```
59#[derive(Copy, Clone, Debug)]
60pub struct Repeated<T>
61where
62 T: fmt::Display,
63{
64 pub value: T,
65 pub count: usize,
66}
67
68impl<T> fmt::Display for Repeated<T>
69where
70 T: fmt::Display,
71{
72 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
73 for _ in 0..self.count {
74 write!(f, "{}", self.value)?
75 }
76 Ok(())
77 }
78}