Skip to main content

superh/
fmt.rs

1use alloc::string::String;
2
3use crate::{FormatIns, Ins, Options};
4
5pub trait FormatValue {
6    fn write<F>(&self, formatter: &mut F) -> core::fmt::Result
7    where
8        F: FormatIns + ?Sized;
9}
10
11// ── Formatter wrapping core::fmt::Formatter ──────────────────────────────────
12
13pub struct Formatter<'a, 'b> {
14    pub options: &'a Options,
15    pub formatter: &'a mut core::fmt::Formatter<'b>,
16}
17
18impl core::fmt::Write for Formatter<'_, '_> {
19    fn write_str(&mut self, s: &str) -> core::fmt::Result {
20        self.formatter.write_str(s)
21    }
22}
23
24impl FormatIns for Formatter<'_, '_> {
25    fn options(&self) -> &Options {
26        self.options
27    }
28}
29
30// ── DisplayIns — returned by Ins::display() ───────────────────────────────────
31
32pub struct DisplayIns<'a> {
33    ins: &'a Ins,
34    options: &'a Options,
35}
36
37impl Ins {
38    pub fn display<'a>(&'a self, options: &'a Options) -> DisplayIns<'a> {
39        DisplayIns { ins: self, options }
40    }
41}
42
43impl core::fmt::Display for DisplayIns<'_> {
44    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
45        let mut formatter = Formatter { options: self.options, formatter: f };
46        formatter.write_ins(self.ins)
47    }
48}
49
50// ── StringFormatter — accumulates into an alloc::String ──────────────────────
51
52pub struct StringFormatter<'a> {
53    pub options: &'a Options,
54    string: String,
55}
56
57impl<'a> StringFormatter<'a> {
58    pub fn new(options: &'a Options) -> Self {
59        Self { options, string: String::new() }
60    }
61
62    pub fn into_string(self) -> String {
63        self.string
64    }
65}
66
67impl core::fmt::Write for StringFormatter<'_> {
68    fn write_str(&mut self, s: &str) -> core::fmt::Result {
69        self.string.push_str(s);
70        Ok(())
71    }
72}
73
74impl FormatIns for StringFormatter<'_> {
75    fn options(&self) -> &Options {
76        self.options
77    }
78}