use core::fmt::Write as _;
pub const LOG_TIMESTAMP_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.3f%:z";
pub const LOG_STAMP_BYTES: usize = 30;
#[track_caller]
pub fn stamp_into(buf: &mut String) {
let start = buf.len();
let _ = write!(
buf,
"{} ",
chrono::Local::now().format(LOG_TIMESTAMP_FORMAT)
);
debug_assert_eq!(
buf.len() - start,
LOG_STAMP_BYTES,
"the stamp's width is fixed and readers strip it by count"
);
}
#[must_use]
pub fn strip(line: &str) -> &str {
let Some((stamp, rest)) = line.split_at_checked(LOG_STAMP_BYTES) else {
return line;
};
let Some(stamp) = stamp.strip_suffix(' ') else {
return line;
};
if chrono::DateTime::parse_from_rfc3339(stamp).is_ok() {
rest
} else {
line
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_stamped_line_comes_back_the_way_it_went_in() {
let mut written = String::new();
stamp_into(&mut written);
written.push_str("the sheep said this");
assert_eq!(written.len(), LOG_STAMP_BYTES + "the sheep said this".len());
assert_eq!(strip(&written), "the sheep said this");
}
#[test]
fn an_unstamped_line_is_left_exactly_as_it_is() {
for line in [
"",
"short",
"an old line from before shep stamped anything at all",
"2026-99-99T99:99:99.999+99:99 nonsense in the shape of a stamp",
"############################# looks like a prefix, parses as nothing",
] {
assert_eq!(strip(line), line, "{line:?} carries no stamp to strip");
}
}
#[test]
fn a_line_split_mid_character_is_returned_whole() {
let line = format!("{}x", "é".repeat(LOG_STAMP_BYTES));
assert_eq!(strip(&line), line);
}
}