powerfmt/
ext.rs

1//! Extension traits.
2
3use core::fmt::{Alignment, Arguments, Formatter, Result, Write};
4
5mod sealed {
6    pub trait Sealed {}
7
8    impl Sealed for core::fmt::Formatter<'_> {}
9}
10
11/// An extension trait for [`core::fmt::Formatter`].
12pub trait FormatterExt: sealed::Sealed {
13    /// Writes the given arguments to the formatter, padding them with the given width. If `width`
14    /// is incorrect, the resulting output will not be the requested width.
15    fn pad_with_width(&mut self, width: usize, args: Arguments<'_>) -> Result;
16}
17
18impl FormatterExt for Formatter<'_> {
19    fn pad_with_width(&mut self, args_width: usize, args: Arguments<'_>) -> Result {
20        let Some(final_width) = self.width() else {
21            // The caller has not requested a width. Write the arguments as-is.
22            return self.write_fmt(args);
23        };
24        let Some(fill_width @ 1..) = final_width.checked_sub(args_width) else {
25            // No padding will be present. Write the arguments as-is.
26            return self.write_fmt(args);
27        };
28
29        let alignment = self.align().unwrap_or(Alignment::Left);
30        let fill = self.fill();
31
32        let left_fill_width = match alignment {
33            Alignment::Left => 0,
34            Alignment::Right => fill_width,
35            Alignment::Center => fill_width / 2,
36        };
37        let right_fill_width = match alignment {
38            Alignment::Left => fill_width,
39            Alignment::Right => 0,
40            // When the fill is not even on both sides, the extra fill goes on the right.
41            Alignment::Center => (fill_width + 1) / 2,
42        };
43
44        for _ in 0..left_fill_width {
45            self.write_char(fill)?;
46        }
47        self.write_fmt(args)?;
48        for _ in 0..right_fill_width {
49            self.write_char(fill)?;
50        }
51
52        Ok(())
53    }
54}