Skip to main content

m5stack_core/io/
console_line.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Console line formatting, hardware-free so it is host-tested.
3//!
4//! A log record is formatted into a fixed [`LINE_CAP`] buffer, which the caller
5//! owns, before it enters the ring. `heapless::String` refuses a `push_str` that
6//! does not fit WHOLE, so formatting straight into it dropped an over-long
7//! argument without a trace: `[csv-hdr] ` arrived with nothing after it.
8//! [`format_into`] cuts at the last character that fits and says so with
9//! [`TRUNC_MARK`]. Records longer than one line go through
10//! `console::send_record`, which has no line buffer at all.
11
12use core::fmt::{self, Write as _};
13
14use heapless::String;
15
16/// Per-line format buffer for the log path.
17pub const LINE_CAP: usize = 352;
18/// Ends a line [`format_into`] had to cut. ASCII, so it renders anywhere.
19pub const TRUNC_MARK: &str = " [CONSOLE-TRUNC]";
20/// Longest `[SSSSS.mmm LEVEL] ` header: a u64 second count is 20 digits.
21pub const HEADER_CAP: usize = 40;
22
23/// Writes into a `String` up to `limit` bytes, whole characters only, and
24/// records whether anything was left out.
25struct Bounded<'a, const N: usize> {
26    out: &'a mut String<N>,
27    limit: usize,
28    cut: bool,
29}
30
31impl<const N: usize> fmt::Write for Bounded<'_, N> {
32    fn write_str(&mut self, s: &str) -> fmt::Result {
33        for c in s.chars() {
34            if self.out.len() + c.len_utf8() > self.limit || self.out.push(c).is_err() {
35                self.cut = true;
36                // Stops the formatter: nothing after this point can be kept.
37                return Err(fmt::Error);
38            }
39        }
40        Ok(())
41    }
42}
43
44/// `[SSSSS.mmm LEVEL] `, the header every console line starts with.
45pub fn header(secs: u64, millis: u64, level: &str) -> String<HEADER_CAP> {
46    let mut h: String<HEADER_CAP> = String::new();
47    // Cannot fail: HEADER_CAP covers the widest u64 and a 5-char level.
48    let _ = write!(h, "[{:05}.{:03} {:<5}] ", secs, millis % 1000, level);
49    h
50}
51
52/// One CRLF-terminated line into `line`, replacing what it held: header, then
53/// `args` as far as they fit. A cut line ends in [`TRUNC_MARK`], so a missing
54/// tail is visible, never silent. In place, so the caller decides where the
55/// line lives: no line buffer is ever on the stack of the code that logs.
56pub fn format_into(
57    line: &mut String<LINE_CAP>,
58    secs: u64,
59    millis: u64,
60    level: &str,
61    args: fmt::Arguments<'_>,
62) {
63    line.clear();
64    let mut w = Bounded {
65        out: line,
66        limit: LINE_CAP - TRUNC_MARK.len() - 2,
67        cut: false,
68    };
69    // The header always fits: LINE_CAP leaves room for HEADER_CAP.
70    let ok = write!(w, "[{:05}.{:03} {:<5}] ", secs, millis % 1000, level).is_ok()
71        && w.write_fmt(args).is_ok();
72    // An error without a cut is a `Display` impl failing; its output is just
73    // as incomplete, so it is marked the same way.
74    if !ok {
75        let _ = line.push_str(TRUNC_MARK); // room reserved by `limit`
76    }
77    let _ = line.push_str("\r\n"); // room reserved by `limit`
78}
79
80#[cfg(test)]
81mod tests {
82    extern crate std;
83    use std::string::String as StdString;
84
85    use super::*;
86
87    fn format_line(
88        secs: u64,
89        millis: u64,
90        level: &str,
91        args: fmt::Arguments<'_>,
92    ) -> String<LINE_CAP> {
93        let mut line = String::new();
94        format_into(&mut line, secs, millis, level, args);
95        line
96    }
97
98    #[test]
99    fn the_header_matches_header() {
100        let l = format_line(98765, 4321, "DEBUG", format_args!(""));
101        assert_eq!(
102            l.strip_suffix("\r\n").unwrap(),
103            header(98765, 4321, "DEBUG").as_str()
104        );
105    }
106
107    #[test]
108    fn a_previous_line_is_replaced() {
109        let mut line = String::new();
110        format_into(
111            &mut line,
112            1,
113            0,
114            "INFO ",
115            format_args!("{}", "x".repeat(200)),
116        );
117        format_into(&mut line, 2, 0, "INFO ", format_args!("short"));
118        assert_eq!(line.as_str(), "[00002.000 INFO ] short\r\n");
119    }
120
121    #[test]
122    fn a_short_line_is_carried_exactly() {
123        let l = format_line(12, 3456, "INFO ", format_args!("[mode] {}", "Idle"));
124        assert_eq!(l.as_str(), "[00012.456 INFO ] [mode] Idle\r\n");
125    }
126
127    /// The defect: `{}` of a 400 B string vanished and left `[csv-hdr] `.
128    #[test]
129    fn an_over_long_argument_is_cut_and_marked_not_dropped() {
130        let long: StdString = "Timestamp;Mode;".repeat(30);
131        let l = format_line(1, 0, "INFO ", format_args!("[csv-hdr] {}", long));
132        assert!(l.len() <= LINE_CAP);
133        assert!(l.ends_with(" [CONSOLE-TRUNC]\r\n"), "{l}");
134        let body = l.strip_prefix("[00001.000 INFO ] [csv-hdr] ").unwrap();
135        assert!(
136            body.len() > 250,
137            "the part that fits is kept: {} B",
138            body.len()
139        );
140        assert!(long.starts_with(body.strip_suffix(" [CONSOLE-TRUNC]\r\n").unwrap()));
141    }
142
143    #[test]
144    fn a_cut_never_splits_a_character() {
145        let long: StdString = "°".repeat(400);
146        let l = format_line(1, 0, "INFO ", format_args!("{}", long));
147        let body = l.strip_suffix(" [CONSOLE-TRUNC]\r\n").unwrap();
148        assert!(body.ends_with('°'));
149    }
150
151    #[test]
152    fn a_line_that_exactly_fits_is_not_marked() {
153        let room = LINE_CAP - TRUNC_MARK.len() - 2 - header(1, 0, "INFO ").len();
154        let fits: StdString = "x".repeat(room);
155        let l = format_line(1, 0, "INFO ", format_args!("{}", fits));
156        assert!(!l.contains("[CONSOLE-TRUNC]"));
157        let over: StdString = "x".repeat(room + 1);
158        let l = format_line(1, 0, "INFO ", format_args!("{}", over));
159        assert!(l.ends_with(" [CONSOLE-TRUNC]\r\n"));
160    }
161
162    #[test]
163    fn a_failing_display_is_marked() {
164        struct Broken;
165        impl fmt::Display for Broken {
166            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167                f.write_str("half")?;
168                Err(fmt::Error)
169            }
170        }
171        let l = format_line(1, 0, "WARN ", format_args!("{}", Broken));
172        assert_eq!(l.as_str(), "[00001.000 WARN ] half [CONSOLE-TRUNC]\r\n");
173    }
174
175    #[test]
176    fn the_header_holds_the_widest_second_count() {
177        let h = header(u64::MAX, 999, "DEBUG");
178        assert!(h.ends_with("999 DEBUG] "), "{h}");
179    }
180}