Skip to main content

diskann_benchmark_runner/utils/
fmt.rs

1/*
2 * Copyright (c) Microsoft Corporation.
3 * Licensed under the MIT license.
4 */
5
6use std::{
7    collections::HashMap,
8    fmt::{Display, Write},
9};
10
11/// A 2-d table for formatting properly spaced values in a table.
12pub struct Table {
13    // The number of columns is implicitly described by the number of entries in `header`.
14    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    // A **private** constructor assuming that `row` is inbounds.
80    fn new(table: &'a mut Table, row: usize) -> Self {
81        Self { table, row }
82    }
83
84    /// Insert a value into the specified column of this row.
85    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        // Compute the maximum width of each column.
98        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                // Return the number of bytes "written",
114                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        // Print the header.
132        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        // Banner
145        write!(f, "\n{:=>header_width$}\n", "")?;
146
147        // Write out each row.
148        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
169////////////
170// Banner //
171////////////
172
173pub(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////////////
193// Indent //
194////////////
195
196/// Indents each line of a string by a fixed number of spaces.
197///
198/// Each line is prefixed with `spaces` spaces.
199///
200/// # Examples
201///
202/// ```
203/// use diskann_benchmark_runner::utils::fmt::Indent;
204///
205/// let indented = Indent::new("hello\nworld", 4).to_string();
206/// assert_eq!(indented, "    hello\n    world");
207/// ```
208#[derive(Debug, Clone, Copy)]
209pub struct Indent<'a> {
210    string: &'a str,
211    spaces: usize,
212}
213
214impl<'a> Indent<'a> {
215    /// Create a new [`Indent`] that will prefix each line of `string` with `spaces` spaces.
216    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        // We don't know ahead of time how many lines there are. To avoid appending a
226        // newline at the end of the last print, we instead add a newline to line `N-1` when
227        // writing out line `N`.
228        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
240/////////////
241// Delimit //
242/////////////
243
244/// Formats an iterator with a delimiter between items and optional overrides for
245/// the final delimiter and pair formatting.
246///
247/// This is a single-use wrapper: the iterator is consumed on the first call to [`Display::fmt`].
248/// Subsequent calls will print `<missing>`.
249///
250/// Use [`Delimit::with_last`] to change the delimiter before the final item
251/// (e.g., `", and "`), which is useful for natural-language lists like
252/// `"a, b, and c"`.
253///
254/// Use [`Delimit::with_pair`] to change formatting when there are only two items.
255///
256/// # Examples
257///
258/// ```
259/// use diskann_benchmark_runner::utils::fmt::Delimit;
260///
261/// let d = Delimit::new(["a", "b", "c"], ", ").with_last(", and ");
262/// assert_eq!(d.to_string(), "a, b, and c");
263///
264/// let d = Delimit::new(["a", "b"], ", ").with_last(", and ");
265/// assert_eq!(d.to_string(), "a, and b");
266///
267/// let d = Delimit::new(["a", "b"], ", ")
268///     .with_last(", and ")
269///     .with_pair(" and ");
270/// assert_eq!(d.to_string(), "a and b");
271/// ```
272pub 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    /// Create a new [`Delimit`] from an iterable and a delimiter.
281    ///
282    /// By default, the same delimiter is used between every item. Use
283    /// [`Self::with_last`] and [`Self::with_pair`] to opt into special handling
284    /// before the final item or for pairs.
285    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    /// Use `last` before the final item when formatting three or more items.
295    pub fn with_last(mut self, last: &'a str) -> Self {
296        self.last = last;
297        self
298    }
299
300    /// Use `pair` when formatting exactly two items.
301    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            // Empty iterator
321            return Ok(());
322        };
323
324        loop {
325            match itr.next() {
326                None => {
327                    // "current" is the last item. If it is also the first, we write it
328                    // directly.
329                    //
330                    // Otherwise, we check if we've just emitted a single item so far and
331                    // use `pair` if available. Otherwise, we try `last` and finally
332                    // `delimiter`.
333                    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                    // There is at least one item next. We print "current" and move on.
345                    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///////////
357// Quote //
358///////////
359
360/// Wraps a value in double quotes when displayed.
361///
362/// # Examples
363///
364/// ```
365/// use diskann_benchmark_runner::utils::fmt::Quote;
366///
367/// assert_eq!(Quote("hello").to_string(), "\"hello\"");
368/// assert_eq!(Quote(42).to_string(), "\"42\"");
369/// ```
370#[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
382///////////
383// Tests //
384///////////
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389
390    #[test]
391    fn test_banner() {
392        let b = Banner::new("hello world");
393        let s = b.to_string();
394
395        let expected = "###############\n\
396                        # hello world #\n\
397                        ###############\n";
398
399        assert_eq!(s, expected);
400
401        let b = Banner::new("");
402        let s = b.to_string();
403
404        let expected = "####\n\
405                        #  #\n\
406                        ####\n";
407
408        assert_eq!(s, expected);
409
410        let b = Banner::new("foo");
411        let s = b.to_string();
412
413        let expected = "#######\n\
414                        # foo #\n\
415                        #######\n";
416
417        assert_eq!(s, expected);
418    }
419
420    #[test]
421    fn test_format() {
422        // One column
423        {
424            let headers = ["h 0"];
425            let mut table = Table::new(headers, 3);
426            table.insert("a", 0, 0);
427            table.insert("hello world", 1, 0);
428            table.insert(62, 2, 0);
429
430            let s = table.to_string();
431            let expected = r#"
432        h 0
433===========
434          a
435hello world
436         62
437"#;
438            assert_eq!(s, expected.strip_prefix('\n').unwrap());
439        }
440
441        // Two columns
442        {
443            let headers = ["a really really long header", "h1"];
444            let mut table = Table::new(headers, 3);
445            table.insert("a", 0, 0);
446            table.insert("b", 0, 1);
447
448            table.insert("hello world", 1, 0);
449            table.insert("hello world version 2", 1, 1);
450
451            table.insert(7, 2, 0);
452            table.insert("bar", 2, 1);
453
454            let s = table.to_string();
455            let expected = r#"
456a really really long header,                      h1
457====================================================
458                          a,                       b
459                hello world,   hello world version 2
460                          7,                     bar
461"#;
462            assert_eq!(s, expected.strip_prefix('\n').unwrap());
463        }
464    }
465
466    #[test]
467    fn test_row_api() {
468        let mut table = Table::new(["a", "b", "c"], 2);
469        let mut row = table.row(0);
470        row.insert(1, 0);
471        row.insert("long", 1);
472        row.insert("s", 2);
473
474        let mut row = table.row(1);
475        row.insert("string", 0);
476        row.insert(2, 1);
477        row.insert(3, 2);
478
479        let s = table.to_string();
480
481        let expected = r#"
482     a,      b,   c
483===================
484     1,   long,   s
485string,      2,   3
486"#;
487        assert_eq!(s, expected.strip_prefix('\n').unwrap());
488    }
489
490    #[test]
491    fn missing_values() {
492        let mut table = Table::new(["a", "loong", "c"], 1);
493        let mut row = table.row(0);
494        row.insert("string", 0);
495        row.insert("string", 2);
496
497        let s = table.to_string();
498        let expected = r#"
499     a,   loong,        c
500=========================
501string,        ,   string
502"#;
503        assert_eq!(s, expected.strip_prefix('\n').unwrap());
504    }
505
506    #[test]
507    #[should_panic(expected = "row 3 is out of bounds (max 2)")]
508    fn test_panic_row() {
509        let mut table = Table::new([1, 2, 3], 2);
510        let _ = table.row(3);
511    }
512
513    #[test]
514    #[should_panic(expected = "col 3 is out of bounds (max 2)")]
515    fn test_panic_col() {
516        let mut table = Table::new([1, 2], 1);
517        let mut row = table.row(0);
518        row.insert(1, 3);
519    }
520
521    #[test]
522    fn test_indent_single_line() {
523        let s = Indent::new("hello", 4).to_string();
524        assert_eq!(s, "    hello");
525    }
526
527    #[test]
528    fn test_indent_multi_line() {
529        let s = Indent::new("hello\nworld\nfoo", 2).to_string();
530        assert_eq!(s, "  hello\n  world\n  foo");
531    }
532
533    #[test]
534    fn test_indent_zero_spaces() {
535        let s = Indent::new("hello\nworld", 0).to_string();
536        assert_eq!(s, "hello\nworld");
537    }
538
539    #[test]
540    fn test_indent_empty_string() {
541        let s = Indent::new("", 4).to_string();
542        assert_eq!(s, "");
543    }
544
545    #[test]
546    fn test_delimit_empty() {
547        let d = Delimit::new(std::iter::empty::<&str>(), ", ");
548        assert_eq!(d.to_string(), "");
549    }
550
551    #[test]
552    fn test_delimit_single_item() {
553        let d = Delimit::new(["a"], ", ").with_last(", and ");
554        assert_eq!(d.to_string(), "a");
555    }
556
557    #[test]
558    fn test_delimit_two_items_with_last() {
559        let d = Delimit::new(["a", "b"], ", ").with_last(", and ");
560        assert_eq!(d.to_string(), "a, and b");
561    }
562
563    #[test]
564    fn test_delimit_two_items_with_pair() {
565        let d = Delimit::new(["a", "b"], ", ")
566            .with_last(", and ")
567            .with_pair(" and ");
568        assert_eq!(d.to_string(), "a and b");
569    }
570
571    #[test]
572    fn test_delimit_three_items_with_last() {
573        let d = Delimit::new(["a", "b", "c"], ", ")
574            .with_last(", and ")
575            .with_pair(" and ");
576        assert_eq!(d.to_string(), "a, b, and c");
577    }
578
579    #[test]
580    fn test_delimit_without_last() {
581        let d = Delimit::new(["x", "y", "z"], " | ");
582        assert_eq!(d.to_string(), "x | y | z");
583    }
584
585    #[test]
586    fn test_delimit_second_display_prints_missing() {
587        let d = Delimit::new(["a", "b"], ", ");
588        assert_eq!(d.to_string(), "a, b");
589        assert_eq!(d.to_string(), "<missing>");
590    }
591
592    #[test]
593    fn test_quote() {
594        assert_eq!(Quote("hello").to_string(), "\"hello\"");
595    }
596
597    #[test]
598    fn test_quote_with_integer() {
599        assert_eq!(Quote(42).to_string(), "\"42\"");
600    }
601
602    #[test]
603    fn test_delimit_with_quote() {
604        let d = Delimit::new(["topk", "range"].iter().map(Quote), ", ")
605            .with_last(", and ")
606            .with_pair(" and ");
607        assert_eq!(d.to_string(), "\"topk\" and \"range\"");
608    }
609}