qpprint 0.4.0

Simple console printing/formatting.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
use std::{
  borrow::Cow,
  fmt,
  iter::{self, zip}
};

use unicode_width::UnicodeWidthStr;

use yansi::Painted;

pub use super::Align;


#[allow(clippy::type_complexity)]
pub struct Column<CM, CDM> {
  title: String,
  min_width: Option<usize>,
  max_width: Option<usize>,
  trunc_len: usize,
  trunc_ch: char,
  renderer: Box<dyn Fn(Option<&CM>, &CellData<CDM>) -> String>,
  stylize:
    Option<Box<dyn Fn(Option<&CM>, &CellData<CDM>, &str) -> Painted<String>>>,
  title_align: Align,
  cell_align: Align,
  colmeta: Option<CM>
}

impl<CM, CDM> Column<CM, CDM> {
  #[allow(clippy::needless_pass_by_value)]
  pub fn new(
    heading: impl ToString,
    renderer: impl Fn(Option<&CM>, &CellData<CDM>) -> String + 'static
  ) -> Self {
    Self {
      title: heading.to_string(),
      min_width: None,
      max_width: None,
      trunc_len: 0,
      trunc_ch: '',
      renderer: Box::new(renderer),
      stylize: None,
      title_align: Align::Center,
      cell_align: Align::Left,
      colmeta: None
    }
  }

  #[must_use]
  pub fn min_width(mut self, min: usize) -> Self {
    self.min_width_ref(min);
    self
  }

  /// # Panics
  /// Panics if a maximum width has been configured for the `Column` and `min`
  /// is less than the maximum width.
  pub fn min_width_ref(&mut self, min: usize) -> &mut Self {
    // Make sure that min width is not greater than max width
    if let Some(max) = self.max_width {
      assert!(min <= max);
    }
    self.min_width = Some(min);
    self
  }

  #[must_use]
  pub fn max_width(mut self, max: usize) -> Self {
    self.max_width_ref(max);
    self
  }

  /// # Panics
  /// `max` must not be less than a previously configured `min` width.
  pub fn max_width_ref(&mut self, max: usize) -> &mut Self {
    // Make sure that max width is not less than min width
    if let Some(min) = self.min_width {
      assert!(max >= min);
    }
    self.max_width = Some(max);
    self
  }

  #[must_use]
  pub const fn trunc_style(mut self, len: usize, ch: char) -> Self {
    self.trunc_style_ref(len, ch);
    self
  }

  pub const fn trunc_style_ref(&mut self, len: usize, ch: char) -> &mut Self {
    self.trunc_len = len;
    self.trunc_ch = ch;
    self
  }

  #[must_use]
  pub fn stylize(
    mut self,
    f: impl Fn(Option<&CM>, &CellData<CDM>, &str) -> Painted<String> + 'static
  ) -> Self {
    self.stylize = Some(Box::new(f));
    self
  }

  #[must_use]
  pub const fn title_align(mut self, align: Align) -> Self {
    self.title_align_ref(align);
    self
  }

  pub const fn title_align_ref(&mut self, align: Align) -> &mut Self {
    self.title_align = align;
    self
  }

  #[must_use]
  pub const fn cell_align(mut self, align: Align) -> Self {
    self.cell_align_ref(align);
    self
  }

  pub const fn cell_align_ref(&mut self, align: Align) -> &mut Self {
    self.cell_align = align;
    self
  }

  #[must_use]
  pub fn meta(mut self, m: CM) -> Self {
    self.colmeta = Some(m);
    self
  }

  pub fn meta_r(&mut self, m: CM) -> &mut Self {
    self.colmeta = Some(m);
    self
  }
}


pub enum CellValue {
  Str(String),
  U64(u64)
}

impl From<String> for CellValue {
  fn from(val: String) -> Self {
    Self::Str(val)
  }
}

impl From<&str> for CellValue {
  fn from(val: &str) -> Self {
    Self::Str(val.to_string())
  }
}

impl From<u64> for CellValue {
  fn from(val: u64) -> Self {
    Self::U64(val)
  }
}

impl fmt::Display for CellValue {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match self {
      Self::Str(s) => write!(f, "{s}"),
      Self::U64(v) => write!(f, "{v}")
    }
  }
}


pub struct CellData<CDM> {
  pub val: CellValue,
  pub meta: Option<CDM>
}

impl<CDM> CellData<CDM> {
  #[must_use]
  pub fn str(val: impl Into<String>) -> Self {
    Self {
      val: CellValue::Str(val.into()),
      meta: None
    }
  }

  #[must_use]
  pub const fn u64(val: u64) -> Self {
    Self {
      val: CellValue::U64(val),
      meta: None
    }
  }

  #[must_use]
  pub fn meta(mut self, md: CDM) -> Self {
    self.meta = Some(md);
    self
  }
}

impl<CDM> From<String> for CellData<CDM> {
  fn from(val: String) -> Self {
    Self {
      val: CellValue::from(val),
      meta: None
    }
  }
}

impl<CDM> From<&str> for CellData<CDM> {
  fn from(val: &str) -> Self {
    Self {
      val: CellValue::from(val),
      meta: None
    }
  }
}

impl<CDM> From<u64> for CellData<CDM> {
  fn from(val: u64) -> Self {
    Self {
      val: CellValue::from(val),
      meta: None
    }
  }
}

impl<CDM> fmt::Display for CellData<CDM> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    match &self.val {
      CellValue::Str(s) => write!(f, "{s}"),
      CellValue::U64(v) => write!(f, "{v}")
    }
  }
}


// Rename to TableData?
pub struct Data<CDM> {
  num_cols: usize,
  cells: Vec<Vec<CellData<CDM>>>
}

impl<CDM> Data<CDM> {
  #[must_use]
  pub const fn new(cols: usize) -> Self {
    Self {
      num_cols: cols,
      cells: Vec::new()
    }
  }

  /// # Panics
  /// The row length must equal to the number of columns.
  pub fn add_row(&mut self, row: Vec<CellData<CDM>>) {
    assert_eq!(row.len(), self.num_cols);
    self.cells.push(row);
  }
}

pub trait CellRender {
  fn stringify();

  fn print();
}


pub struct Renderer<'a, CM, CDM> {
  show_header: bool,
  header_underline: Option<char>,
  col_spacing: usize,
  cols: &'a [Column<CM, CDM>],
  data: &'a [Vec<CellData<CDM>>]
}

impl<'a, CM, CDM> Renderer<'a, CM, CDM> {
  #[must_use]
  pub fn new(cols: &'a [Column<CM, CDM>], data: &'a Data<CDM>) -> Self {
    Self {
      show_header: false,
      header_underline: None,
      col_spacing: 2,
      cols,
      data: &data.cells
    }
  }

  #[must_use]
  pub const fn header(mut self, underline: Option<char>) -> Self {
    self.header_ref(underline);
    self
  }

  pub const fn header_ref(&mut self, underline: Option<char>) -> &mut Self {
    self.show_header = true;
    self.header_underline = underline;
    self
  }

  #[must_use]
  pub const fn column_spacing(mut self, n: usize) -> Self {
    self.column_spacing_ref(n);
    self
  }

  pub const fn column_spacing_ref(&mut self, n: usize) -> &mut Self {
    self.col_spacing = n;
    self
  }

  pub fn print(&self) {
    println!("{self}");
  }
}

/// Calculate the width (in units of number of terminal character cells) of a
/// unicode string.
///
/// Apparently this is not an exact science.  It should work well enough as
/// long as no one tries to be too creative.
#[inline]
fn strlen(s: &str) -> usize {
  //c.title.chars().count()
  s.width()
}

impl<CM, CDM> fmt::Display for Renderer<'_, CM, CDM> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    //
    // Iterate over cells and generate a new rendered table.
    // Every cell here is a String
    //
    let mut rendered: Vec<Vec<String>> = Vec::with_capacity(self.data.len());

    //
    // Used to keep track of auto-detected column widths.
    //
    // If the renderer is configured to show a header, then initialize to the
    // column titles.  Otherwise initialize to 0.
    //
    // If a column min and/or max widths have been configured, the column
    // widths will be clamped later.
    //
    let mut col_widths: Vec<usize> = if self.show_header {
      self.cols.iter().map(|c| strlen(&c.title)).collect()
    } else {
      vec![0; self.cols.len()]
    };

    //
    // Convert table of CellValues into a table of Strings.
    //
    // In the process, keep increasing the column widths as needed
    //
    for row in self.data {
      let mut rrow = Vec::with_capacity(self.cols.len());
      /*
      for (icol, (col, cell)) in zip(self.cols, row).enumerate() {
        let cell_str = (col.renderer)(cell);

        // ToDo: Cut down to size if cell_str.len() exceeds column's max_width

        //if cell_str.len() > col_width {}

        col_widths[icol] = std::cmp::max(col_widths[icol], cell_str.len());
        rrow.push(cell_str);
      }
      */

      for (cw, (col, cell)) in
        col_widths.iter_mut().zip(iter::zip(self.cols, row))
      {
        let cell_str = (col.renderer)(col.colmeta.as_ref(), cell);

        // ToDo: Cut down to size if cell_str.len() exceeds column's max_width

        //if cell_str.len() > col_width {}

        *cw = std::cmp::max(*cw, strlen(&cell_str));
        rrow.push(cell_str);
      }

      rendered.push(rrow);
    }

    //
    // If columns have a minimum and/or maximum width configured, then apply
    // these limits to col_widths
    //
    let col_widths: Vec<usize> = zip(col_widths, self.cols)
      .map(|(cw, col)| clamp_width(cw, col.min_width, col.max_width))
      .collect();

    let colspace = " ".repeat(self.col_spacing);

    let mut fields = Vec::with_capacity(self.cols.len());

    if self.show_header {
      //
      // Print column headers
      //
      for (col, cw) in std::iter::zip(self.cols, &col_widths) {
        let title = trunc_str(&col.title, *cw, col.trunc_len, col.trunc_ch);

        let cc = format_cell(&title, *cw, col.title_align);
        fields.push(cc);
      }
      writeln!(f, "{}", fields.join(&colspace))?;


      //
      // Print heading underline
      //
      if let Some(ch) = self.header_underline {
        fields.clear();
        for cw in &col_widths {
          //let line = iter::repeat(ch).take(*cw).collect::<String>();
          let line = std::iter::repeat_n(ch, *cw).collect::<String>();
          fields.push(line);
        }
        writeln!(f, "{}", fields.join(&colspace))?;
      }
    }


    //
    // At this point `rendered` is a table of String's
    //
    for (cvs, row) in iter::zip(self.data, rendered) {
      fields.clear();

      for ((col, cw), (cv, cell)) in
        iter::zip(iter::zip(self.cols, &col_widths), iter::zip(cvs, row))
      {
        let cell = trunc_str(&cell, *cw, col.trunc_len, col.trunc_ch);

        if let Some(ref stylize) = col.stylize {
          let cell = stylize(col.colmeta.as_ref(), cv, &cell);
          let cc = format_painted_cell(&cell, *cw, col.cell_align);
          fields.push(cc);
        } else {
          let cc = format_cell(&cell, *cw, col.cell_align);
          fields.push(cc);
        }
      }

      writeln!(f, "{}", fields.join(&colspace))?;
    }
    Ok(())
  }
}

fn format_cell(s: &str, cell_width: usize, align: Align) -> String {
  match align {
    Align::Left => {
      let pad = cell_width - strlen(s);
      format!("{s}{:pad$}", "")
    }
    Align::Center => {
      let pad = cell_width - strlen(s);
      let (lpad, rpad) = split_len(pad);
      format!("{:lpad$}{s}{:rpad$}", "", "")
    }
    Align::Right => {
      let pad = cell_width - strlen(s);
      format!("{:pad$}{s}", "")
    }
  }
}

fn format_painted_cell(
  s: &Painted<String>,
  cell_width: usize,
  align: Align
) -> String {
  match align {
    Align::Left => {
      let pad = cell_width - strlen(&s.value);
      format!("{s}{:pad$}", "")
    }
    Align::Center => {
      let pad = cell_width - strlen(&s.value);
      let (lpad, rpad) = split_len(pad);
      format!("{:lpad$}{s}{:rpad$}", "", "")
    }
    Align::Right => {
      let pad = cell_width - strlen(&s.value);
      format!("{:pad$}{s}", "")
    }
  }
}


#[inline]
const fn split_len(len: usize) -> (usize, usize) {
  let left = len / 2;
  let right = len - left;
  (left, right)
}


fn clamp_width(w: usize, min: Option<usize>, max: Option<usize>) -> usize {
  let w = min.map_or(w, |min| if w < min { min } else { w });
  max.map_or(w, |max| if w > max { max } else { w })
}

/// Given input string `s` and a cell's `width`, return a potentially truncated
/// string that is at most `width` long.
fn trunc_str(
  s: &str,
  width: usize,
  trunc_len: usize,
  trunc_ch: char
) -> Cow<'_, str> {
  let slen = strlen(s);
  if slen > width {
    let trunc = s[..width - trunc_len].to_string();
    let cont = std::iter::repeat_n(trunc_ch, trunc_len).collect::<String>();
    let s = format!("{trunc}{cont}");
    Cow::from(s)
  } else {
    Cow::from(s)
  }
}


#[cfg(test)]
mod tests {
  use super::{clamp_width, trunc_str};

  #[test]
  fn truncing() {
    assert_eq!(trunc_str("hello", 4, 1, '.').into_owned(), "hel.");
    assert_eq!(trunc_str("hello", 4, 2, '.').into_owned(), "he..");
  }

  #[test]
  fn clamping() {
    assert_eq!(clamp_width(0, None, None), 0);

    assert_eq!(clamp_width(0, Some(2), None), 2);
    assert_eq!(clamp_width(8, Some(2), None), 8);

    assert_eq!(clamp_width(0, None, Some(8)), 0);
    assert_eq!(clamp_width(10, None, Some(8)), 8);

    assert_eq!(clamp_width(0, Some(2), Some(8)), 2);
    assert_eq!(clamp_width(4, Some(2), Some(8)), 4);
    assert_eq!(clamp_width(10, Some(2), Some(8)), 8);
  }
}

// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :