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