use core::fmt::{self, Write as _};
pub(crate) const DISPLAY_MAX_MEMBERS: usize = 16;
const DISPLAY_MAX_NAME_CHARS: usize = 64;
const _: () = assert!(DISPLAY_MAX_MEMBERS <= 64);
const _: () = assert!(DISPLAY_MAX_NAME_CHARS <= 256);
pub(crate) struct Dims<'a, T>(pub &'a [T]);
impl<T: fmt::Display> fmt::Display for Dims<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, dim) in self.0.iter().enumerate() {
if i > 0 {
f.write_str("x")?;
}
write!(f, "{dim}")?;
}
Ok(())
}
}
pub(crate) struct QuotedBytes<'a>(pub &'a [u8]);
impl fmt::Display for QuotedBytes<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("\"")?;
for &byte in self.0 {
if byte == b'"' || byte == b'\\' {
write!(f, "\\{}", byte as char)?;
} else if byte.is_ascii_graphic() || byte == b' ' {
write!(f, "{}", byte as char)?;
} else {
write!(f, "\\x{byte:02x}")?;
}
}
f.write_str("\"")
}
}
pub(crate) struct EscapedName<'a>(pub &'a str);
impl fmt::Display for EscapedName<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut escaped = self.0.escape_debug();
for ch in escaped.by_ref().take(DISPLAY_MAX_NAME_CHARS) {
f.write_char(ch)?;
}
if escaped.next().is_some() {
f.write_str("…")?;
}
Ok(())
}
}
pub(crate) fn write_elided(f: &mut fmt::Formatter<'_>, elided: usize) -> fmt::Result {
if elided > 0 {
write!(f, ", … {elided} more")?;
}
Ok(())
}
#[cfg(all(test, feature = "std"))]
mod tests {
use super::*;
#[test]
fn a_shape_is_spelled_the_same_way_everywhere() {
assert_eq!(Dims(&[4]).to_string(), "4");
assert_eq!(Dims(&[2, 3]).to_string(), "2x3");
assert_eq!(Dims::<u64>(&[]).to_string(), "");
}
#[test]
fn an_escaped_name_cannot_carry_a_control_character() {
assert_eq!(EscapedName("x").to_string(), "x");
assert_eq!(EscapedName("température").to_string(), "température");
for hostile in ["a\nb", "a\rb", "a\tb", "a\u{0}b", "a\u{1b}[31mb"] {
let shown = EscapedName(hostile).to_string();
assert!(
!shown.chars().any(char::is_control),
"{hostile:?} -> {shown}"
);
}
}
#[test]
fn a_long_name_is_truncated() {
let long = "n".repeat(DISPLAY_MAX_NAME_CHARS * 4);
let shown = EscapedName(&long).to_string();
assert_eq!(shown.chars().count(), DISPLAY_MAX_NAME_CHARS + 1);
assert!(shown.ends_with('…'), "{shown}");
let at_cap = "n".repeat(DISPLAY_MAX_NAME_CHARS);
assert_eq!(EscapedName(&at_cap).to_string(), at_cap);
}
#[test]
fn an_elided_tail_appears_only_when_something_was_dropped() {
assert_eq!(fmt_elided(0), "");
assert_eq!(fmt_elided(5), ", … 5 more");
}
fn fmt_elided(elided: usize) -> String {
struct Tail(usize);
impl fmt::Display for Tail {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write_elided(f, self.0)
}
}
Tail(elided).to_string()
}
}