Skip to main content

deep_time/t_span/
formatting.rs

1use crate::TSpan;
2use core::fmt;
3
4fn write_fractional(subsec: u64, precision: usize, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5    if precision == 0 {
6        return Ok(());
7    }
8    let prec = precision.min(18); // attosecond precision (10^{-18} s)
9    let scale = 10u64.pow(18 - prec as u32);
10    let value = subsec / scale;
11    write!(f, ".{:0>width$}", value, width = prec)
12}
13
14impl fmt::Display for TSpan {
15    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16        let precision = f.precision().unwrap_or(9); // nanosecond precision — most useful default
17
18        if self.is_zero() {
19            // Special-case zero for cleanliness (no fractional part), but still respect flags
20            let sign = if f.sign_plus() { "+" } else { "" };
21            write!(f, "{sign}0")?;
22
23            if f.alternate() {
24                // # flag → raw internal representation (excellent for debugging)
25                write!(f, " [sec=0 subsec=0]")?;
26            }
27
28            f.write_str(" s")?;
29            return Ok(());
30        }
31
32        // Respect + sign when requested
33        if f.sign_plus() && self.sec >= 0 {
34            write!(f, "+")?;
35        }
36
37        write!(f, "{}", self.sec)?;
38        write_fractional(self.attos, precision, f)?;
39        f.write_str(" s")?;
40
41        if f.alternate() {
42            // # flag → raw internal representation (excellent for debugging)
43            write!(f, " [sec={} subsec={}]", self.sec, self.attos)?;
44        }
45
46        Ok(())
47    }
48}
49
50impl fmt::Debug for TSpan {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        let approx_sec_f = self.sec as f64 + (self.attos as f64 / 1e18_f64);
53
54        f.debug_struct("TSpan")
55            .field("sec", &self.sec)
56            .field("subsec", &self.attos)
57            .field("as_sec_f", &approx_sec_f)
58            .finish()
59    }
60}