Skip to main content

fmty/
repeat.rs

1use core::fmt::*;
2
3pub(crate) mod types {
4    #[allow(unused)]
5    use super::*;
6
7    /// See [`repeat()`].
8    #[derive(Clone, Copy)]
9    pub struct Repeat<T> {
10        pub(super) value: T,
11        pub(super) n: usize,
12    }
13
14    /// See [`repeat_with()`].
15    #[derive(Clone, Copy)]
16    pub struct RepeatWith<F> {
17        // Although this could alias `Concat<iter::Take<iter::RepeatWith<F>>>`,
18        // it would not be able to implement `Copy` because `Take` doesn't.
19        pub(super) f: F,
20        pub(super) n: usize,
21    }
22}
23
24use types::*;
25
26/// Repeats a value `n` times.
27///
28/// This is a non-allocating alternative to
29/// [`[T]::repeat()`](https://doc.rust-lang.org/std/primitive.slice.html#method.repeat) or
30/// [`str::repeat()`](https://doc.rust-lang.org/std/primitive.str.html#method.repeat).
31///
32/// # Examples
33///
34/// ```
35/// let value = fmty::repeat("123", 3);
36/// assert_eq!(value.to_string(), "123123123");
37/// ```
38pub fn repeat<T>(value: T, n: usize) -> Repeat<T> {
39    Repeat { value, n }
40}
41
42/// Repeats `n` results of a closure.
43///
44/// # Examples
45///
46/// ```
47/// use std::cell::Cell;
48///
49/// let counter = Cell::new(1);
50///
51/// let value = fmty::repeat_with(3, || {
52///     let result = counter.get();
53///     counter.set(result + 1);
54///     result
55/// });
56///
57/// assert_eq!(value.to_string(), "123");
58/// ```
59pub fn repeat_with<F>(n: usize, f: F) -> RepeatWith<F> {
60    RepeatWith { n, f }
61}
62
63impl<T: Debug> Debug for Repeat<T> {
64    fn fmt(&self, f: &mut Formatter) -> Result {
65        for _ in 0..self.n {
66            write!(f, "{:?}", self.value)?;
67        }
68        Ok(())
69    }
70}
71
72impl<T: Display> Display for Repeat<T> {
73    fn fmt(&self, f: &mut Formatter) -> Result {
74        for _ in 0..self.n {
75            write!(f, "{}", self.value)?;
76        }
77        Ok(())
78    }
79}
80
81impl<F, R> Debug for RepeatWith<F>
82where
83    F: Fn() -> R,
84    R: Debug,
85{
86    fn fmt(&self, f: &mut Formatter) -> Result {
87        for _ in 0..self.n {
88            write!(f, "{:?}", (self.f)())?;
89        }
90        Ok(())
91    }
92}
93
94impl<F, R> Display for RepeatWith<F>
95where
96    F: Fn() -> R,
97    R: Display,
98{
99    fn fmt(&self, f: &mut Formatter) -> Result {
100        for _ in 0..self.n {
101            write!(f, "{}", (self.f)())?;
102        }
103        Ok(())
104    }
105}