1use std::{
7 collections::HashMap,
8 fmt::{Display, Write},
9};
10
11pub struct Table {
13 header: Box<[Box<dyn Display>]>,
15 body: HashMap<(usize, usize), Box<dyn Display>>,
16 nrows: usize,
17}
18
19impl Table {
20 pub fn new<I>(header: I, nrows: usize) -> Self
21 where
22 I: IntoIterator<Item: Display + 'static>,
23 {
24 fn as_dyn_display<T: Display + 'static>(x: T) -> Box<dyn Display> {
25 Box::new(x)
26 }
27
28 let header: Box<[_]> = header.into_iter().map(as_dyn_display).collect();
29 Self {
30 header,
31 body: HashMap::new(),
32 nrows,
33 }
34 }
35
36 pub fn nrows(&self) -> usize {
37 self.nrows
38 }
39
40 pub fn ncols(&self) -> usize {
41 self.header.len()
42 }
43
44 pub fn insert<T>(&mut self, item: T, row: usize, col: usize) -> bool
45 where
46 T: Display + 'static,
47 {
48 self.check_bounds(row, col);
49 self.body.insert((row, col), Box::new(item)).is_some()
50 }
51
52 pub fn get(&self, row: usize, col: usize) -> Option<&dyn Display> {
53 self.check_bounds(row, col);
54 self.body.get(&(row, col)).map(|x| &**x)
55 }
56
57 pub fn row(&mut self, row: usize) -> Row<'_> {
58 self.check_bounds(row, 0);
59 Row::new(self, row)
60 }
61
62 #[expect(clippy::panic, reason = "table interfaces are bounds checked")]
63 fn check_bounds(&self, row: usize, col: usize) {
64 if row >= self.nrows() {
65 panic!("row {} is out of bounds (max {})", row, self.nrows());
66 }
67 if col >= self.ncols() {
68 panic!("col {} is out of bounds (max {})", col, self.ncols());
69 }
70 }
71}
72
73pub struct Row<'a> {
74 table: &'a mut Table,
75 row: usize,
76}
77
78impl<'a> Row<'a> {
79 fn new(table: &'a mut Table, row: usize) -> Self {
81 Self { table, row }
82 }
83
84 pub fn insert<T>(&mut self, item: T, col: usize) -> bool
86 where
87 T: Display + 'static,
88 {
89 self.table.insert(item, self.row, col)
90 }
91}
92
93impl Display for Table {
94 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95 const SEP: &str = ", ";
96
97 struct Count(usize);
99
100 impl Write for Count {
101 fn write_str(&mut self, s: &str) -> std::fmt::Result {
102 self.0 += s.len();
103 Ok(())
104 }
105 }
106
107 fn formatted_size<T>(x: &T) -> usize
108 where
109 T: Display + ?Sized,
110 {
111 let mut buf = Count(0);
112 match write!(&mut buf, "{}", x) {
113 Ok(()) => buf.0,
115 Err(_) => 0,
116 }
117 }
118
119 let mut widths: Vec<usize> = self.header.iter().map(formatted_size).collect();
120 for row in 0..self.nrows() {
121 for (col, width) in widths.iter_mut().enumerate() {
122 if let Some(v) = self.body.get(&(row, col)) {
123 *width = (*width).max(formatted_size(v))
124 }
125 }
126 }
127
128 let header_width: usize = widths.iter().sum::<usize>() + (widths.len() - 1) * SEP.len();
129
130 let mut buf = String::new();
131 std::iter::zip(widths.iter(), self.header.iter())
133 .enumerate()
134 .try_for_each(|(col, (width, head))| {
135 buf.clear();
136 write!(buf, "{}", head)?;
137 write!(f, "{:>width$}", buf)?;
138 if col + 1 != self.ncols() {
139 write!(f, "{}", SEP)?;
140 }
141 Ok(())
142 })?;
143
144 write!(f, "\n{:=>header_width$}\n", "")?;
146
147 for row in 0..self.nrows() {
149 for (col, width) in widths.iter_mut().enumerate() {
150 match self.body.get(&(row, col)) {
151 Some(v) => {
152 buf.clear();
153 write!(buf, "{}", v)?;
154 write!(f, "{:>width$}", buf)?;
155 }
156 None => write!(f, "{:>width$}", "")?,
157 }
158 if col + 1 != self.ncols() {
159 write!(f, "{}", SEP)?;
160 } else {
161 writeln!(f)?;
162 }
163 }
164 }
165 Ok(())
166 }
167}
168
169pub(crate) struct Banner<'a>(&'a str);
174
175impl<'a> Banner<'a> {
176 pub(crate) fn new(message: &'a str) -> Self {
177 Self(message)
178 }
179}
180
181impl std::fmt::Display for Banner<'_> {
182 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183 let st = format!("# {} #", self.0);
184 let len = st.len();
185 writeln!(f, "{:#>len$}", "")?;
186 writeln!(f, "{}", st)?;
187 writeln!(f, "{:#>len$}", "")?;
188 Ok(())
189 }
190}
191
192#[derive(Debug, Clone, Copy)]
209pub struct Indent<'a> {
210 string: &'a str,
211 spaces: usize,
212}
213
214impl<'a> Indent<'a> {
215 pub fn new(string: &'a str, spaces: usize) -> Self {
217 Self { string, spaces }
218 }
219}
220
221impl std::fmt::Display for Indent<'_> {
222 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223 let spaces = self.spaces;
224
225 let mut first = true;
229 self.string.lines().try_for_each(|ln| {
230 if first {
231 first = false;
232 write!(f, "{: >spaces$}{}", "", ln)
233 } else {
234 write!(f, "\n{: >spaces$}{}", "", ln)
235 }
236 })
237 }
238}
239
240pub struct Delimit<'a, I> {
273 itr: std::cell::Cell<Option<I>>,
274 delimiter: &'a str,
275 last: &'a str,
276 pair: Option<&'a str>,
277}
278
279impl<'a, I> Delimit<'a, I> {
280 pub fn new(itr: impl IntoIterator<IntoIter = I>, delimiter: &'a str) -> Self {
286 Self {
287 itr: std::cell::Cell::new(Some(itr.into_iter())),
288 delimiter,
289 last: delimiter,
290 pair: None,
291 }
292 }
293
294 pub fn with_last(mut self, last: &'a str) -> Self {
296 self.last = last;
297 self
298 }
299
300 pub fn with_pair(mut self, pair: &'a str) -> Self {
302 self.pair = Some(pair);
303 self
304 }
305}
306
307impl<I> std::fmt::Display for Delimit<'_, I>
308where
309 I: Iterator<Item: std::fmt::Display>,
310{
311 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
312 let Some(mut itr) = self.itr.take() else {
313 return write!(f, "<missing>");
314 };
315
316 let mut count = 0;
317 let mut current = if let Some(item) = itr.next() {
318 item
319 } else {
320 return Ok(());
322 };
323
324 loop {
325 match itr.next() {
326 None => {
327 let delimiter = if count == 0 {
334 ""
335 } else if count == 1 {
336 self.pair.unwrap_or(self.last)
337 } else {
338 self.last
339 };
340
341 return write!(f, "{}{}", delimiter, current);
342 }
343 Some(next) => {
344 let delimiter = if count == 0 { "" } else { self.delimiter };
346
347 write!(f, "{}{}", delimiter, current)?;
348 count += 1;
349 current = next;
350 }
351 }
352 }
353 }
354}
355
356#[derive(Debug, Clone, Copy)]
371pub struct Quote<T>(pub T);
372
373impl<T> std::fmt::Display for Quote<T>
374where
375 T: std::fmt::Display,
376{
377 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
378 write!(f, "\"{}\"", self.0)
379 }
380}
381
382enum MaybeLazy<'a> {
387 Lazy(&'a dyn std::fmt::Display),
388 Eager(String),
389}
390
391impl std::fmt::Display for MaybeLazy<'_> {
392 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
393 match self {
394 Self::Lazy(lazy) => write!(f, "{}", lazy),
395 Self::Eager(s) => f.write_str(s),
396 }
397 }
398}
399
400impl std::fmt::Debug for MaybeLazy<'_> {
401 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
402 struct AsDisplay<'a>(&'a dyn std::fmt::Display);
403 impl std::fmt::Debug for AsDisplay<'_> {
404 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
405 self.0.fmt(f)
406 }
407 }
408
409 match self {
410 Self::Lazy(o) => {
411 let as_display = AsDisplay(o);
412 f.debug_tuple("MaybeLazy::Lazy").field(&as_display).finish()
413 }
414 Self::Eager(s) => f.debug_tuple("MaybeLazy::Eager").field(s).finish(),
415 }
416 }
417}
418
419#[derive(Debug, Default)]
461pub struct KeyValue<'a> {
462 kv: Vec<(&'a str, MaybeLazy<'a>)>,
463 max_key_length: usize,
464}
465
466impl<'a> KeyValue<'a> {
467 pub fn new() -> Self {
469 Self {
470 kv: Vec::new(),
471 max_key_length: 0,
472 }
473 }
474
475 pub fn push(&mut self, key: &'a str, value: &'a dyn std::fmt::Display) {
477 self.max_key_length = self.max_key_length.max(key.len());
478 self.kv.push((key, MaybeLazy::Lazy(value)))
479 }
480
481 pub fn push_eager<D>(&mut self, key: &'a str, value: D)
483 where
484 D: std::fmt::Display,
485 {
486 self.max_key_length = self.max_key_length.max(key.len());
487 self.kv.push((key, MaybeLazy::Eager(value.to_string())))
488 }
489}
490
491impl std::fmt::Display for KeyValue<'_> {
492 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
493 let width = self.max_key_length;
494 let mut prefix = "";
495 for (k, v) in self.kv.iter() {
496 let rendered = v.to_string();
497 if rendered.contains('\n') {
498 write!(f, "{}{}:\n{}", prefix, k, Indent::new(&rendered, 2))?
499 } else {
500 let pad = (width + 1).saturating_sub(k.len());
503 write!(f, "{}{}:{:pad$}{rendered}", prefix, k, "")?;
504 }
505 prefix = "\n";
506 }
507 Ok(())
508 }
509}
510
511#[cfg(test)]
516mod tests {
517 use super::*;
518
519 #[test]
520 fn test_banner() {
521 let b = Banner::new("hello world");
522 let s = b.to_string();
523
524 let expected = "###############\n\
525 # hello world #\n\
526 ###############\n";
527
528 assert_eq!(s, expected);
529
530 let b = Banner::new("");
531 let s = b.to_string();
532
533 let expected = "####\n\
534 # #\n\
535 ####\n";
536
537 assert_eq!(s, expected);
538
539 let b = Banner::new("foo");
540 let s = b.to_string();
541
542 let expected = "#######\n\
543 # foo #\n\
544 #######\n";
545
546 assert_eq!(s, expected);
547 }
548
549 #[test]
550 fn test_format() {
551 {
553 let headers = ["h 0"];
554 let mut table = Table::new(headers, 3);
555 table.insert("a", 0, 0);
556 table.insert("hello world", 1, 0);
557 table.insert(62, 2, 0);
558
559 let s = table.to_string();
560 let expected = r#"
561 h 0
562===========
563 a
564hello world
565 62
566"#;
567 assert_eq!(s, expected.strip_prefix('\n').unwrap());
568 }
569
570 {
572 let headers = ["a really really long header", "h1"];
573 let mut table = Table::new(headers, 3);
574 table.insert("a", 0, 0);
575 table.insert("b", 0, 1);
576
577 table.insert("hello world", 1, 0);
578 table.insert("hello world version 2", 1, 1);
579
580 table.insert(7, 2, 0);
581 table.insert("bar", 2, 1);
582
583 let s = table.to_string();
584 let expected = r#"
585a really really long header, h1
586====================================================
587 a, b
588 hello world, hello world version 2
589 7, bar
590"#;
591 assert_eq!(s, expected.strip_prefix('\n').unwrap());
592 }
593 }
594
595 #[test]
596 fn test_row_api() {
597 let mut table = Table::new(["a", "b", "c"], 2);
598 let mut row = table.row(0);
599 row.insert(1, 0);
600 row.insert("long", 1);
601 row.insert("s", 2);
602
603 let mut row = table.row(1);
604 row.insert("string", 0);
605 row.insert(2, 1);
606 row.insert(3, 2);
607
608 let s = table.to_string();
609
610 let expected = r#"
611 a, b, c
612===================
613 1, long, s
614string, 2, 3
615"#;
616 assert_eq!(s, expected.strip_prefix('\n').unwrap());
617 }
618
619 #[test]
620 fn missing_values() {
621 let mut table = Table::new(["a", "loong", "c"], 1);
622 let mut row = table.row(0);
623 row.insert("string", 0);
624 row.insert("string", 2);
625
626 let s = table.to_string();
627 let expected = r#"
628 a, loong, c
629=========================
630string, , string
631"#;
632 assert_eq!(s, expected.strip_prefix('\n').unwrap());
633 }
634
635 #[test]
636 #[should_panic(expected = "row 3 is out of bounds (max 2)")]
637 fn test_panic_row() {
638 let mut table = Table::new([1, 2, 3], 2);
639 let _ = table.row(3);
640 }
641
642 #[test]
643 #[should_panic(expected = "col 3 is out of bounds (max 2)")]
644 fn test_panic_col() {
645 let mut table = Table::new([1, 2], 1);
646 let mut row = table.row(0);
647 row.insert(1, 3);
648 }
649
650 #[test]
651 fn test_indent_single_line() {
652 let s = Indent::new("hello", 4).to_string();
653 assert_eq!(s, " hello");
654 }
655
656 #[test]
657 fn test_indent_multi_line() {
658 let s = Indent::new("hello\nworld\nfoo", 2).to_string();
659 assert_eq!(s, " hello\n world\n foo");
660 }
661
662 #[test]
663 fn test_indent_zero_spaces() {
664 let s = Indent::new("hello\nworld", 0).to_string();
665 assert_eq!(s, "hello\nworld");
666 }
667
668 #[test]
669 fn test_indent_empty_string() {
670 let s = Indent::new("", 4).to_string();
671 assert_eq!(s, "");
672 }
673
674 #[test]
675 fn test_delimit_empty() {
676 let d = Delimit::new(std::iter::empty::<&str>(), ", ");
677 assert_eq!(d.to_string(), "");
678 }
679
680 #[test]
681 fn test_delimit_single_item() {
682 let d = Delimit::new(["a"], ", ").with_last(", and ");
683 assert_eq!(d.to_string(), "a");
684 }
685
686 #[test]
687 fn test_delimit_two_items_with_last() {
688 let d = Delimit::new(["a", "b"], ", ").with_last(", and ");
689 assert_eq!(d.to_string(), "a, and b");
690 }
691
692 #[test]
693 fn test_delimit_two_items_with_pair() {
694 let d = Delimit::new(["a", "b"], ", ")
695 .with_last(", and ")
696 .with_pair(" and ");
697 assert_eq!(d.to_string(), "a and b");
698 }
699
700 #[test]
701 fn test_delimit_three_items_with_last() {
702 let d = Delimit::new(["a", "b", "c"], ", ")
703 .with_last(", and ")
704 .with_pair(" and ");
705 assert_eq!(d.to_string(), "a, b, and c");
706 }
707
708 #[test]
709 fn test_delimit_without_last() {
710 let d = Delimit::new(["x", "y", "z"], " | ");
711 assert_eq!(d.to_string(), "x | y | z");
712 }
713
714 #[test]
715 fn test_delimit_second_display_prints_missing() {
716 let d = Delimit::new(["a", "b"], ", ");
717 assert_eq!(d.to_string(), "a, b");
718 assert_eq!(d.to_string(), "<missing>");
719 }
720
721 #[test]
722 fn test_quote() {
723 assert_eq!(Quote("hello").to_string(), "\"hello\"");
724 }
725
726 #[test]
727 fn test_quote_with_integer() {
728 assert_eq!(Quote(42).to_string(), "\"42\"");
729 }
730
731 #[test]
732 fn test_delimit_with_quote() {
733 let d = Delimit::new(["topk", "range"].iter().map(Quote), ", ")
734 .with_last(", and ")
735 .with_pair(" and ");
736 assert_eq!(d.to_string(), "\"topk\" and \"range\"");
737 }
738
739 fn process(x: &str) -> &str {
745 let x = x.strip_prefix('\n').unwrap_or(x);
746 x.strip_suffix('\n').unwrap_or(x)
747 }
748
749 #[test]
750 fn test_key_value_empty() {
751 let kv = KeyValue::new();
752 assert_eq!(kv.to_string(), "");
753 }
754
755 #[test]
756 fn test_key_value_single_pair() {
757 let mut kv = KeyValue::new();
758 kv.push("a", &1);
759 assert_eq!(kv.to_string(), "a: 1");
760 }
761
762 #[test]
763 fn test_key_value_aligns_values() {
764 let mut kv = KeyValue::new();
765 kv.push("a", &1);
766 kv.push("hello", &"world");
767 let expected = process(
768 r#"
769a: 1
770hello: world
771"#,
772 );
773 assert_eq!(kv.to_string(), expected);
774 }
775
776 #[test]
777 fn test_key_value_push_eager() {
778 let mut kv = KeyValue::new();
779 kv.push_eager("a", 1);
780 kv.push_eager("hello", "world");
781
782 let expected = process(
783 r#"
784a: 1
785hello: world
786"#,
787 );
788
789 assert_eq!(kv.to_string(), expected);
790 }
791
792 #[test]
793 fn test_key_value_multiline_value_is_indented() {
794 let mut inner = KeyValue::new();
795 inner.push("x", &1);
796 inner.push("yy", &2);
797 let inner = inner.to_string();
798
799 let mut kv = KeyValue::new();
800 kv.push("name", &"example");
801 kv.push("nested", &inner);
802 kv.push("another line", &1);
803
804 let expected = process(
805 r#"
806name: example
807nested:
808 x: 1
809 yy: 2
810another line: 1
811"#,
812 );
813
814 assert_eq!(kv.to_string(), expected);
815 }
816
817 #[test]
818 fn maybe_lazy_debug() {
819 let x = MaybeLazy::Lazy(&1);
820 let dbg = format!("{:?}", x);
821 assert_eq!(dbg, "MaybeLazy::Lazy(1)");
822
823 let x = MaybeLazy::Eager("hello".into());
824 let dbg = format!("{:?}", x);
825 assert_eq!(dbg, "MaybeLazy::Eager(\"hello\")");
826 }
827}