use crate::analyzers::Annotation;
use crate::output::OutputBackend;
use std::io::Write;
pub struct Table;
impl OutputBackend for Table {
fn render(&self, anns: &[Annotation], w: &mut dyn Write) -> std::io::Result<()> {
let kind_w = kind_width(anns);
let label_w = label_width(anns);
writeln!(
w,
"{:<18} {:<kind_w$} label",
"vaddr",
"kind",
kind_w = kind_w
)?;
writeln!(
w,
"{} {} {}",
repeat('-', 18),
repeat('-', kind_w),
repeat('-', label_w)
)?;
for a in anns {
writeln!(
w,
"0x{:<16x} {:<kind_w$} {}",
a.vaddr,
kind_str(&a.kind),
one_line(&a.label, label_w),
kind_w = kind_w
)?;
if let Some(c) = &a.comment {
for line in textwrap(c, label_w) {
writeln!(w, " {:<kind_w$} │ {}", "", line, kind_w = kind_w)?;
}
}
}
Ok(())
}
}
const fn kind_str(k: &crate::analyzers::AnnotationKind) -> &'static str {
use crate::analyzers::AnnotationKind::{PanicSite, String as KString, Symbol};
match k {
KString => "string",
Symbol => "symbol",
PanicSite => "panic",
}
}
fn kind_width(anns: &[Annotation]) -> usize {
let mut w = "kind".len();
for a in anns {
w = w.max(kind_str(&a.kind).len());
}
w
}
fn label_width(anns: &[Annotation]) -> usize {
let mut w = "label".len();
for a in anns {
let chars = visible_text(&a.label).chars().count().min(120);
w = w.max(chars);
}
w
}
fn one_line(s: &str, max: usize) -> String {
let one = visible_text(s);
if one.chars().count() <= max {
one
} else {
let target = max.saturating_sub(1);
let mut t = String::new();
let mut len = 0usize;
for ch in s.chars() {
let token = visible_char(ch);
let token_len = token.chars().count();
if len.saturating_add(token_len) > target {
break;
}
t.push_str(&token);
len = len.saturating_add(token_len);
}
t.push('…');
t
}
}
fn textwrap(s: &str, width: usize) -> Vec<String> {
if s.is_empty() {
return Vec::new();
}
let mut lines = Vec::new();
let mut cur = String::new();
let mut cur_len = 0usize;
for ch in s.chars() {
let token = visible_char(ch);
let token_len = token.chars().count();
if cur_len > 0 && cur_len.saturating_add(token_len) > width {
lines.push(std::mem::take(&mut cur));
cur_len = 0;
}
cur.push_str(&token);
cur_len = cur_len.saturating_add(token_len);
}
if !cur.is_empty() {
lines.push(cur);
}
lines
}
fn visible_text(s: &str) -> String {
let mut visible = String::with_capacity(s.len());
for ch in s.chars() {
visible.push_str(&visible_char(ch));
}
visible
}
fn visible_char(ch: char) -> String {
match ch {
'\n' => "\\n".into(),
'\r' => "\\r".into(),
'\t' => "\\t".into(),
c if matches!(u32::from(c), 0x00..=0x1f | 0x7f..=0x9f) => {
format!("\\x{:02x}", u32::from(c))
}
c if is_terminal_format_control(c) => format!("\\u{{{:04x}}}", u32::from(c)),
c => c.into(),
}
}
const fn is_terminal_format_control(ch: char) -> bool {
matches!(
ch,
'\u{061c}'
| '\u{200e}'
| '\u{200f}'
| '\u{202a}'..='\u{202e}'
| '\u{2066}'..='\u{2069}'
| '\u{feff}'
)
}
fn repeat(c: char, n: usize) -> String {
std::iter::repeat_n(c, n).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::analyzers::{Annotation, AnnotationKind};
use std::cmp;
fn render_bytes(anns: &[Annotation]) -> Vec<u8> {
let mut buf = Vec::new();
Table.render(anns, &mut buf).unwrap();
buf
}
fn render_string(anns: &[Annotation]) -> String {
String::from_utf8(render_bytes(anns)).unwrap()
}
#[test]
fn renders_address_kind_label() {
let anns = vec![Annotation {
vaddr: 0x0040_1000,
kind: AnnotationKind::String,
label: "hello".into(),
comment: None,
}];
let s = render_string(&anns);
assert!(s.contains("0x401000"));
assert!(s.contains("string"));
assert!(s.contains("hello"));
}
#[test]
fn repeat_emits_exactly_n_chars() {
assert_eq!(repeat('-', 0), "");
assert_eq!(repeat('-', 1), "-");
assert_eq!(repeat('-', 5), "-----");
assert_eq!(repeat('-', 18).chars().count(), 18);
assert_eq!(repeat('-', 120).chars().count(), 120);
assert_eq!(repeat('a', 3), "aaa");
}
#[test]
fn one_line_passes_through_short_strings() {
assert_eq!(one_line("abc", 10), "abc");
assert_eq!(one_line("", 10), "");
}
#[test]
fn one_line_truncates_with_ellipsis_on_overflow() {
let out = one_line(&"x".repeat(50), 10);
assert_eq!(out.chars().count(), 10);
assert!(out.ends_with('…'));
assert_eq!(&out[..9], &"x".repeat(9));
}
#[test]
fn one_line_truncates_at_max_zero() {
assert_eq!(one_line("hello", 0), "…");
}
#[test]
fn one_line_escapes_control_chars() {
assert_eq!(one_line("a\nb", 100), "a\\nb");
assert_eq!(one_line("a\rb", 100), "a\\rb");
assert_eq!(one_line("a\tb", 100), "a\\tb");
assert_eq!(one_line("\n\t\r", 100), "\\n\\t\\r");
assert_eq!(
one_line("\0\u{0007}\u{001b}\u{007f}\u{0085}\u{009f}", 100),
"\\x00\\x07\\x1b\\x7f\\x85\\x9f"
);
}
#[test]
fn one_line_escapes_bidi_and_default_ignorable_controls() {
let input = "\u{061c}\u{200e}\u{200f}\u{202a}\u{202b}\u{202c}\u{202d}\u{202e}\u{2066}\u{2067}\u{2068}\u{2069}\u{feff}";
assert_eq!(
one_line(input, 200),
"\\u{061c}\\u{200e}\\u{200f}\\u{202a}\\u{202b}\\u{202c}\\u{202d}\\u{202e}\\u{2066}\\u{2067}\\u{2068}\\u{2069}\\u{feff}"
);
}
#[test]
fn one_line_does_not_split_escape_at_truncation_boundary() {
let input = format!("{}\u{202e}{}", "a".repeat(110), "b".repeat(20));
let output = one_line(&input, 120);
assert!(output.contains("\\u{202e}"));
assert!(output.ends_with('…'));
assert!(!output.contains('\u{202e}'));
}
#[test]
fn textwrap_visibly_escapes_newline_and_controls() {
assert_eq!(textwrap("ab\ncd", 80), vec!["ab\\ncd"]);
assert_eq!(textwrap("\u{001b}\u{0085}", 80), vec!["\\x1b\\x85"]);
assert_eq!(textwrap("\u{202e}\u{2066}", 80), vec!["\\u{202e}\\u{2066}"]);
}
#[test]
fn textwrap_chops_at_width_char_count() {
assert_eq!(textwrap("abcdef", 2), vec!["ab", "cd", "ef"]);
assert_eq!(textwrap("abcdef", 3), vec!["abc", "def"]);
assert_eq!(textwrap("abcde", 3), vec!["abc", "de"]);
}
#[test]
fn textwrap_does_not_wrap_when_token_exactly_fills_width() {
assert_eq!(textwrap("abcd", 4), vec!["abcd"]);
assert_eq!(textwrap("ab\tc", 5), vec!["ab\\tc"]);
assert_eq!(textwrap("a", 0), vec!["a"]);
assert!(!textwrap("a", 0).iter().any(String::is_empty));
}
#[test]
fn textwrap_handles_empty_input() {
assert!(textwrap("", 80).is_empty());
}
#[test]
fn kind_width_picks_max_kind_label() {
let anns = vec![
Annotation {
vaddr: 1,
kind: AnnotationKind::String,
label: "x".into(),
comment: None,
},
Annotation {
vaddr: 2,
kind: AnnotationKind::Symbol,
label: "y".into(),
comment: None,
},
];
assert_eq!(kind_width(&anns), 6);
}
#[test]
fn label_width_picks_max_label_up_to_cap() {
let anns = vec![
Annotation {
vaddr: 1,
kind: AnnotationKind::String,
label: "short".into(),
comment: None,
},
Annotation {
vaddr: 2,
kind: AnnotationKind::String,
label: "a".repeat(500),
comment: None,
},
];
assert_eq!(label_width(&anns), 120);
}
#[test]
fn render_contains_no_terminal_or_format_controls_from_annotations() {
let anns = vec![Annotation {
vaddr: 1,
kind: AnnotationKind::String,
label: "bell\u{0007}esc\u{001b}del\u{007f}c1\u{0085}bidi\u{202e}".into(),
comment: Some("nul\0line\nend\u{009f}isolate\u{2066}bom\u{feff}".into()),
}];
let rendered = render_string(&anns);
assert!(rendered.contains("bell\\x07esc\\x1bdel\\x7fc1\\x85bidi\\u{202e}"));
assert!(rendered.contains("nul\\x00line\\nend\\x9fisolate"));
assert!(rendered.contains("\\u{2066}"));
assert!(rendered.contains("\\u{feff}"));
assert!(!rendered.chars().any(|ch| {
matches!(u32::from(ch), 0x00..=0x09 | 0x0b..=0x1f | 0x7f..=0x9f)
|| is_terminal_format_control(ch)
}));
}
fn render_reference(anns: &[Annotation]) -> String {
use std::fmt::Write as _;
let kind_w = kind_width(anns);
let label_w = label_width(anns);
let mut s = String::new();
let _ = writeln!(
s,
"{:<18} {:<kind_w$} label",
"vaddr",
"kind",
kind_w = kind_w
);
let _ = writeln!(
s,
"{} {} {}",
repeat('-', 18),
repeat('-', kind_w),
repeat('-', label_w)
);
for a in anns {
let _ = writeln!(
s,
"0x{:<16x} {:<kind_w$} {}",
a.vaddr,
kind_str(&a.kind),
one_line(&a.label, label_w),
kind_w = kind_w
);
if let Some(c) = &a.comment {
for line in textwrap(c, label_w) {
let _ = writeln!(s, " {:<kind_w$} │ {}", "", line, kind_w = kind_w);
}
}
}
s
}
#[test]
fn byte_exact_no_comments() {
let anns = vec![
Annotation {
vaddr: 0x0040_1000,
kind: AnnotationKind::String,
label: "alpha".into(),
comment: None,
},
Annotation {
vaddr: 0x0040_2000,
kind: AnnotationKind::PanicSite,
label: "src/main.rs:7".into(),
comment: None,
},
];
assert_eq!(render_string(&anns), render_reference(&anns));
}
#[test]
fn byte_exact_with_wrapped_comment() {
let anns = vec![Annotation {
vaddr: 0x0040_1000,
kind: AnnotationKind::Symbol,
label: "core::fmt::write".into(),
comment: Some("recovered &str slice at offset 0x401000, len=18, valid utf-8".into()),
}];
assert_eq!(render_string(&anns), render_reference(&anns));
}
#[test]
fn byte_exact_truncated_label() {
let long = "L".repeat(130);
let anns = vec![Annotation {
vaddr: 0x1000,
kind: AnnotationKind::String,
label: long.clone(),
comment: None,
}];
assert_eq!(render_string(&anns), render_reference(&anns));
let out = render_string(&anns);
let mut truncated = String::with_capacity(120);
truncated.push_str(&"L".repeat(cmp::min(120, long.len()) - 1));
truncated.push('…');
assert!(out.contains(&truncated), "missing: {truncated} in {out:?}");
}
#[test]
fn byte_exact_empty() {
assert_eq!(render_string(&[]), render_reference(&[]));
}
#[test]
fn byte_exact_all_three_kinds() {
let anns = vec![
Annotation {
vaddr: 0x0040_0000,
kind: AnnotationKind::String,
label: "string_data".into(),
comment: Some("note for string".into()),
},
Annotation {
vaddr: 0x0040_0010,
kind: AnnotationKind::Symbol,
label: "_ZN3std2io5Write9write_fmt".into(),
comment: None,
},
Annotation {
vaddr: 0x0040_0020,
kind: AnnotationKind::PanicSite,
label: "src/main.rs:42:5".into(),
comment: Some("called from thread main".into()),
},
];
assert_eq!(render_string(&anns), render_reference(&anns));
}
}