descriptor 0.0.4

A simple to use struct descriptor
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
//! Easy pretty print your Rust struct into single element or list.
//!
//! # Simple Example
//! ```
//! use descriptor::{object_describe_to_string, table_describe_to_string, Descriptor};
//!
//! #[derive(Descriptor)]
//! struct User {
//!     name: String,
//!     age: i32,
//!     address: Address,
//! }
//!
//! #[derive(Descriptor)]
//! struct Address {
//!     street: String,
//!     town: String,
//! }
//!
//! let user1 = User{
//!     name: "Adrien".to_string(),
//!     age: 32,
//!     address: Address{
//!         street: "Main street".to_string(),
//!         town: "NY".to_string()
//!     }
//! };
//! let user2 = User{
//!     name: "Corentin".to_string(),
//!     age: 40,
//!     address: Address{
//!         street: "10 rue de la paix".to_string(),
//!         town: "Paris".to_string()
//!     }
//! };
//! let description = object_describe_to_string(&user1).unwrap();
//!
//! assert_eq!(r#"
//! Name:    Adrien
//! Age:     32
//! Address:
//!   Street: Main street
//!   Town:   NY
//! "#,  description);
//!
//! let table = table_describe_to_string(&vec![user1, user2]).unwrap();
//!
//! assert_eq!(r#"
//! NAME     AGE ADDRESS.STREET    ADDRESS.TOWN
//! Adrien   32  Main street       NY
//! Corentin 40  10 rue de la paix Paris
//! "#, format!("\n{}", table));
//! ```
//! <!-- toc -->
//! # Macro attributes
//! ## Struct attributes
//!
//! ### `#[descriptor(into = AnotherStruct)]`
//! The `into` parameter convert the struct into another before describe.
//!
//! The `From` or `Into` Trait should be implemented and `AnotherStruct` should implement the `Describe` trait.
//! ```
//! use descriptor::{Descriptor, object_describe_to_string};
//!
//! #[derive(Descriptor)]
//! pub struct ProgressDescribe {
//!     pub transfer: String,
//! }
//!
//! impl From<&Progress> for ProgressDescribe {
//!     fn from(progress: &Progress) -> Self {
//!         let bar_length = 20;
//!         let pad_l = ((progress.processed * bar_length) / progress.total.max(1)) as usize;
//!         let bar = format!(
//!             "[{:=>pad_l$}>{:>pad_r$}] {}/{}",
//!             "",
//!             "",
//!             progress.processed,
//!             progress.total,
//!             pad_l = pad_l,
//!             pad_r = bar_length as usize - pad_l
//!         );
//!
//!         Self {
//!             transfer: bar,
//!         }
//!     }
//! }
//!
//! #[derive(Descriptor)]
//! #[descriptor(into = ProgressDescribe)]
//! struct Progress {
//!     pub processed: u64,
//!     pub total: u64,
//! }
//!
//! let progress = Progress{
//!    processed: 20,
//!    total: 40,
//! };
//! let description = object_describe_to_string(&progress).unwrap();
//!
//! assert_eq!(r#"
//! Transfer: [==========>          ] 20/40
//! "#,  description);
//! ```
//!
//! ### `#[descriptor(extra_fields = ExtraStruct)]`
//!
//! Add fields from another struct into the description, useful for computed values without overriding real values.
//!
//! ```
//! use descriptor::{Descriptor, object_describe_to_string};
//!
//! #[derive(Descriptor)]
//! #[descriptor(extra_fields = AgeEntity)]
//! struct User {
//!     name: String,
//!     created_at: i32,
//! }
//!
//! #[derive(Descriptor)]
//! pub struct AgeEntity {
//!     pub age: String,
//! }
//!
//! impl From<&User> for AgeEntity {
//!     fn from(u: &User) -> Self {
//!         Self {
//!             age: format!("{} days ago", u.created_at),
//!         }
//!     }
//! }
//!
//! let progress = User{
//!    name: "Adrien".to_string(),
//!    created_at: 40,
//! };
//! let description = object_describe_to_string(&progress).unwrap();
//! assert_eq!(r#"
//! Name:       Adrien
//! Created At: 40
//! Age:        40 days ago
//! "#,  description);
//! ```
//!
//! ### `#[descriptor(default_headers = [""])]`
//!
//! Overrides default headers when using the table output.
//! ```
//! use descriptor::{Descriptor, table_describe_to_string};
//! #[derive(Descriptor, Clone)]
//! #[descriptor(default_headers = ["brand", "seat"])]
//! struct Car {
//!     brand: String,
//!     seat: i16,
//!     model: String,
//! }
//! let cars = vec![
//!     Car{brand: "Audi".to_string(), seat:4, model: "A3".to_string()},
//!     Car{brand: "Mercedes".to_string(), seat: 2, model: "GLC".to_string()}
//! ];
//!
//! let description = table_describe_to_string(&cars).unwrap();
//! assert_eq!(r#"
//! BRAND    SEAT
//! Audi     4
//! Mercedes 2
//! "#,  format!("\n{}", description));
//! ```
//!
//! ## Field attributes

//! #### `#[descriptor(flatten)]`
//! Flatten a struct into another.
//!
//! ```
//! use descriptor::{Descriptor, object_describe_to_string};
//!
//! #[derive(Descriptor)]
//! struct User {
//!     name: String,
//!     age: i32,
//!     #[descriptor(flatten)]
//!     address: Address
//! }
//!
//! #[derive(Descriptor)]
//! struct Address {
//!     street: String,
//!     town: String,
//! }
//!
//! let foo = User{
//!     name: "Adrien".to_string(),
//!     age: 32,
//!     address: Address{
//!         street: "Main street".to_string(),
//!         town: "NY".to_string()
//!     }
//! };
//! let description = object_describe_to_string(&foo).unwrap();
//!
//! assert_eq!(r#"
//! Name:    Adrien
//! Age:     32
//! Street:  Main street
//! Town:    NY
//! "#,  description);
//! ```
//!
//! ### `#[descriptor(map = func)]`
//! Takes a transformation function as parameter, called before generating the field.
//!
//! Return value of the functions should not be a struct, use `into` parameter for this use case.
//!
//! ```
//! use descriptor::{Descriptor, object_describe_to_string};
//!
//! fn age_to_string(val: &i32) -> String {
//!   format!("{} years", val)
//! }
//!
//! #[derive(Descriptor)]
//! struct User {
//!     name: String,
//!     #[descriptor(map = age_to_string)]
//!     age: i32,
//! }
//! let foo = User{
//!     name: "Adrien".to_string(),
//!     age: 32,
//! };
//! let description = object_describe_to_string(&foo).unwrap();
//! assert_eq!(r#"
//! Name: Adrien
//! Age:  32 years
//! "#,  description);
//! ```
//! `map` parameter can be used with `resolve_option` parameter.
//!
//! If the field is an Option, it extract it before calling the transformation function.
//!
//! ```
//! use descriptor::{Descriptor, object_describe_to_string};
//!
//! fn age_to_string(val: &i32) -> String {
//!   format!("{} years", val)
//! }
//!
//! #[derive(Descriptor)]
//! struct User {
//!     name: String,
//!     #[descriptor(map = age_to_string, resolve_option)]
//!     age: Option<i32>,
//! }
//! let foo = User{
//!     name: "Adrien".to_string(),
//!     age: Option::Some(32),
//! };
//! let description = object_describe_to_string(&foo).unwrap();
//! assert_eq!(r#"
//! Name: Adrien
//! Age:  32 years
//! "#,  description);
//! ```
//! ### `#[descriptor(into)]`
//!
//! Act like `into` parameter in struct level,
//!
//! `into` parameter can be used with `map` parameter in field level.
//!
//! Sometimes, it's impossible to implement `Into` and `From` for some struct,
//! you can use a public method from the struct
//! ```
//! use descriptor::{Descriptor, object_describe_to_string};
//! #[derive(Descriptor)]
//! struct Download {
//!     pub filename: String,
//!     #[descriptor(into = String, map = Progress::to_string)]
//!     pub progress: Progress,
//! }
//!
//! #[derive(Descriptor)]
//! struct Progress {
//!     pub processed: u64,
//!     pub total: u64,
//! }
//! impl Progress {
//!     fn to_string(&self) -> String {
//!         format!("{}/{}", self.processed, self.total)
//!     }
//! }
//! let download = Download{
//!     filename: "debian-11.iso".to_string(),
//!     progress: Progress{ processed: 2, total: 4},
//! };
//!
//! let description = object_describe_to_string(&download).unwrap();
//! assert_eq!(r#"
//! Filename: debian-11.iso
//! Progress: 2/4
//! "#,  description);
//! ```
//! ### `#[descriptor(output_table)]`
//!
//! Output a table-like output inside the description.
//! ```
//! use descriptor::{Descriptor, object_describe_to_string};
//! #[derive(Descriptor, Clone)]
//! struct Car {
//!     name: String,
//!     seat: i16,
//! }
//!
//! #[derive(Descriptor)]
//! struct User {
//!     name: String,
//!     cars: Vec<Car>,
//!     #[descriptor(output_table)]
//!     cars_list: Vec<Car>,
//! }
//!
//! let cars = vec![Car{name: "Audi".to_string(), seat:4}, Car{name: "Mercedes".to_string(), seat: 2}];
//!
//! let user = User{
//!     name: "Adrien".to_string(),
//!     cars: cars.clone(),
//!     cars_list: cars.clone(),
//! };
//! let description = object_describe_to_string(&user).unwrap();
//! assert_eq!(r#"
//! Name:      Adrien
//! Cars:
//! - Name: Audi
//!   Seat: 4
//! - Name: Mercedes
//!   Seat: 2
//! Cars List:
//!   NAME       SEAT
//!   Audi       4
//!   Mercedes   2
//! "#,  description);
//! ```
//! ### `#[descriptor(skip)]`
//!
//! - `#[descriptor(skip)]`: Skip this field from description and default headers in table
//! - `#[descriptor(skip_description)]`: Skip this field only from description
//! - `#[descriptor(skip_header)]`:  Skip this field from default headers
//!
//! ```
//! use descriptor::{Descriptor, object_describe_to_string, table_describe_to_string, table_describe_with_header_to_string, object_describe};
//! #[derive(Descriptor, Clone)]
//! struct Car {
//!     brand: String,
//!     #[descriptor(skip_header)]
//!     seat: i16,
//!     #[descriptor(skip_description)]
//!     model: String,
//!     #[descriptor(skip)]
//!     serial: String,
//! }
//! let  car = Car{brand: "Audi".to_string(), seat:4, model: "A3".to_string(), serial: "SN".to_string()};
//!
//! let cars = vec![
//!     car.clone(),
//!     Car{brand: "Mercedes".to_string(), seat: 2, model: "GLC".to_string(), serial: "WD".to_string()}
//! ];
//!
//! let description = object_describe_to_string(&car).unwrap();
//! assert_eq!(r#"
//! Brand: Audi
//! Seat:  4
//! "#,  format!("{}", description));
//!
//! let table = table_describe_to_string(&cars).unwrap();
//! assert_eq!(r#"
//! BRAND    MODEL
//! Audi     A3
//! Mercedes GLC
//! "#,  format!("\n{}", table));
//!
//! let table = table_describe_with_header_to_string(&cars,&vec!["seat".to_string()] ).unwrap();
//! assert_eq!(r#"
//! SEAT
//! 4
//! 2
//! "#,  format!("\n{}", table));
//! ```
//! ### `#[descriptor(rename_header)]`
//!
//! Rename the auto-generated name for table header
//!
//! ```
//! use descriptor::{Descriptor, object_describe_to_string, table_describe_to_string, table_describe_with_header_to_string, object_describe};
//! #[derive(Descriptor)]
//! struct Car {
//!     #[descriptor(rename_header="Marque")]
//!     brand: String,
//!     #[descriptor(rename_header="Siege")]
//!     seat: i16,
//! }
//!
//! let cars = vec![
//!     Car{brand: "Audi".to_string(), seat:4},
//!     Car{brand: "Mercedes".to_string(), seat: 2}
//! ];
//!
//! let table = table_describe_to_string(&cars).unwrap();
//! assert_eq!(r#"
//! Marque   Siege
//! Audi     4
//! Mercedes 2
//! "#,  format!("\n{}", table));
//! ```
//!
//! ## Enum parameters
//! ### `#[descriptor(rename_description = "Renamed")]`
//!
//! Rename the value for enums.
//!
//! ```
//! use descriptor::{object_describe_to_string, Descriptor};
//! #[derive(Descriptor)]
//! struct User {
//!     name: String,
//!     role: Role,
//! }
//! #[derive(Descriptor)]
//! enum Role {
//!     Admin,
//!     #[descriptor(rename_description = "User role")]
//!     User,
//! }
//!
//! let description = object_describe_to_string(&User {
//!    name: "Adrien".to_string(),
//!    role: Role::User,
//! }).unwrap();
//! assert_eq!(r#"
//! Name: Adrien
//! Role: User role
//! "#, description);
//! ```
//!
//!
use std::collections::HashMap;
use std::io;

use convert_case::{Case, Casing};
#[doc(hidden)]
pub use descriptor_derive::{self, *};

#[derive(Clone, Default)]
pub struct Context {
    pub offset: usize,
    pub pad: usize,
    pub upper_pad: usize,
    pub is_array: bool,
    pub title_size: usize,
}

impl Context {
    pub fn pad(&self, upper_pad: usize) -> Self {
        Self {
            offset: self.offset,
            upper_pad: self.upper_pad.max(upper_pad),
            pad: 0,
            title_size: 0,
            is_array: false,
        }
    }

    pub fn indent(&self, pad: usize, title_size: usize) -> Self {
        Self {
            offset: self.offset + 2,
            pad: pad.max(self.upper_pad),
            upper_pad: 0,
            title_size,
            is_array: false,
        }
    }

    pub fn array(&self) -> Self {
        Self {
            offset: self.offset,
            pad: self.pad,
            title_size: 0,
            upper_pad: 0,
            is_array: true,
        }
    }

    pub fn indent_and_table(&self) -> Self {
        Self {
            offset: self.offset + 2,
            pad: 0,
            upper_pad: 0,
            title_size: 0,
            is_array: true,
        }
    }

    pub fn describe_table<T, W>(&self, data: &[T], writer: &mut W) -> io::Result<()>
    where
        T: Describe,
        W: io::Write,
    {
        writeln!(writer)?;
        Describer::describe_list_internal(data, &[], writer, self.indent_and_table())
    }

    pub fn write_title<W>(&self, writer: &mut W, field: &str, first_field: bool) -> io::Result<()>
    where
        W: io::Write,
    {
        writeln!(writer)?;
        let offset = if first_field && self.is_array {
            write!(writer, "{:<offset$}- ", "", offset = self.offset - 2)?;
            0
        } else {
            self.offset
        };

        write!(
            writer,
            "{:<offset$}{}",
            "",
            format!("{}:", field),
            offset = offset
        )
    }

    pub fn write_value<W>(&self, writer: &mut W, field: String) -> io::Result<()>
    where
        W: io::Write,
    {
        if self.is_array {
            writeln!(writer)?;
            write!(
                writer,
                "{:<offset$}- {}",
                "",
                field,
                offset = self.offset - 2
            )
        } else {
            write!(
                writer,
                "{:>pad$}{}",
                "",
                field,
                pad = self.pad - self.title_size
            )
        }
    }
}

#[doc(hidden)]
pub fn get_keys(field_name: &str) -> (&str, &str) {
    match field_name.split_once(".") {
        None => (field_name, ""),
        Some((field_name, child)) => (field_name, child),
    }
}

pub trait Describe {
    // Method that take a field name and should return a String value of the field.
    // This method extract keys with dot in order to call the to_field method for children
    fn to_field(&self, field_name: &str) -> String;

    // Return the default_headers for the structs
    fn default_headers() -> Vec<String> {
        Self::headers()
    }

    // Return the list of all headers for the struct
    fn headers() -> Vec<String> {
        vec![]
    }

    // Return another name for an header
    fn header_name(_: &str) -> Option<String> {
        None
    }

    fn struct_pad() -> usize {
        0
    }

    // Describe write the current description of the struct
    // The current version is used for scalar types
    fn describe<W>(&self, writer: &mut W, ctx: Context) -> io::Result<()>
    where
        W: io::Write,
    {
        ctx.write_value(writer, self.to_field(""))
    }
}

impl<V: Describe> Describe for HashMap<String, V> {
    fn to_field(&self, _: &str) -> String {
        "todo".to_string()
    }

    fn describe<W: io::Write>(&self, writer: &mut W, ctx: Context) -> io::Result<()> {
        if !self.is_empty() {
            let pad = &self.keys().map(|k| k.len()).max().unwrap_or_default() + 1;
            let mut keys = self.keys().collect::<Vec<_>>();
            keys.sort();
            for k in keys {
                ctx.write_title(writer, k, false)?;
                self[k].describe(writer, ctx.indent(pad, k.len()))?;
            }
        } else {
            ctx.write_value(writer, "~".to_string())?
        }
        Ok(())
    }
}

impl<T: Describe> Describe for Vec<T> {
    fn to_field(&self, field: &str) -> String {
        self.iter()
            .map(|x| x.to_field(field))
            .collect::<Vec<_>>()
            .join(",")
    }

    fn describe<W: io::Write>(&self, writer: &mut W, ctx: Context) -> io::Result<()> {
        if self.is_empty() {
            ctx.write_value(writer, "~".to_string())
        } else {
            for inner in self {
                inner.describe(writer, ctx.array())?;
            }
            Ok(())
        }
    }
}

impl<T: Describe> Describe for Option<T> {
    fn to_field(&self, field_name: &str) -> String {
        match self {
            None => "~".to_string(),
            Some(v) => v.to_field(field_name),
        }
    }

    fn headers() -> Vec<String> {
        T::headers()
    }

    fn header_name(header: &str) -> Option<String> {
        T::header_name(header)
    }

    fn describe<W: io::Write>(&self, writer: &mut W, ctx: Context) -> io::Result<()> {
        match self {
            None => ctx.write_value(writer, "~".to_string()),
            Some(v) => v.describe(writer, ctx),
        }
    }
}

pub struct Describer;

impl Describer {
    pub fn describe_object<W: io::Write, T>(
        data: &T,
        writer: &mut W,
        ctx: Context,
    ) -> io::Result<()>
    where
        T: Describe,
    {
        data.describe(writer, ctx)?;
        writeln!(writer)
    }

    pub fn describe_list<W: io::Write, T>(
        data: &[T],
        writer: &mut W,
        ctx: Context,
    ) -> io::Result<()>
    where
        T: Describe,
    {
        Self::describe_list_with_header(data, &[], writer, ctx)
    }

    pub fn describe_list_with_header<W: io::Write, T>(
        data: &[T],
        headers: &[String],
        writer: &mut W,
        ctx: Context,
    ) -> io::Result<()>
    where
        T: Describe,
    {
        Self::describe_list_internal(data, headers, writer, ctx)?;
        writeln!(writer)
    }

    fn describe_list_internal<W: io::Write, T>(
        data: &[T],
        headers: &[String],
        writer: &mut W,
        ctx: Context,
    ) -> io::Result<()>
    where
        T: Describe,
    {
        // Compute headers to display
        let default_headers: Vec<String> =
            T::default_headers().iter().map(|x| x.to_string()).collect();
        let headers = if headers.is_empty() {
            default_headers.as_slice()
        } else {
            headers
        };

        // Compute rows
        let rows = data
            .iter()
            .map(|row| {
                headers
                    .iter()
                    .map(|x| {
                        let val = x.as_str();
                        row.to_field(val)
                    })
                    .collect::<Vec<_>>()
            })
            .collect::<Vec<_>>();

        let header_names = headers
            .iter()
            .map(|header| match T::header_name(header) {
                None => header.to_string().to_case(Case::UpperSnake),
                Some(header) => header,
            })
            .collect::<Vec<_>>();

        // Compute columns width
        let mut col_widths = header_names
            .iter()
            .map(|header| header.len())
            .collect::<Vec<_>>();
        for row in rows.iter() {
            for (idx, cell) in row.iter().enumerate() {
                col_widths[idx] = col_widths[idx].max(Self::compute_string_size(cell))
            }
        }

        let header_len = header_names.len();
        // Print header
        for (idx, cell) in header_names.into_iter().enumerate() {
            if idx > 0 {
                write!(writer, " ")?;
            }

            let space = if idx + 1 != header_len {
                format!("{:width$}", "", width = col_widths[idx] - cell.len())
            } else {
                format!("")
            };

            write!(
                writer,
                "{:<offset$}{}{}",
                "",
                cell.as_str(),
                space,
                offset = ctx.offset
            )?;
        }

        // Print rows
        if rows.is_empty() {
            writeln!(writer, "Empty list")?;
        }
        for row in rows {
            writeln!(writer)?;
            for (idx, cell) in row.into_iter().enumerate() {
                if idx > 0 {
                    writer.write_fmt(format_args!(" "))?;
                }
                let space = if idx + 1 != header_len {
                    format!(
                        "{:width$}",
                        "",
                        width = col_widths[idx] - Self::compute_string_size(&cell)
                    )
                } else {
                    format!("")
                };
                writer.write_fmt(format_args!(
                    "{:<offset$}{}{}",
                    "",
                    cell,
                    space,
                    offset = ctx.offset
                ))?;
            }
        }

        Ok(())
    }

    fn compute_string_size(str: &str) -> usize {
        String::from_utf8(strip_ansi_escapes::strip(str).unwrap())
            .unwrap_or_else(|_| str.to_string())
            .len()
    }
}

pub fn object_describe_to_string<T: Describe>(object: &T) -> io::Result<String> {
    let mut vec = Vec::with_capacity(128);
    Describer::describe_object(object, &mut vec, Context::default())?;
    let string = String::from_utf8(vec).unwrap();
    Ok(string)
}

pub fn object_describe<W: io::Write, T: Describe>(object: &T, writer: &mut W) -> io::Result<()> {
    Describer::describe_object(object, writer, Context::default())
}

pub fn table_describe_to_string<T: Describe>(data: &[T]) -> io::Result<String> {
    let mut vec = Vec::with_capacity(128);
    Describer::describe_list(data, &mut vec, Context::default())?;
    let string = String::from_utf8(vec).unwrap();
    Ok(string)
}

pub fn table_describe_with_header_to_string<T: Describe>(
    data: &[T],
    headers: &[String],
) -> io::Result<String> {
    let mut vec = Vec::with_capacity(128);
    Describer::describe_list_with_header(data, headers, &mut vec, Context::default())?;
    let string = String::from_utf8(vec).unwrap();
    Ok(string)
}

pub fn table_describe<W: io::Write, T: Describe>(
    data: &[T],
    headers: &[String],
    writer: &mut W,
) -> io::Result<()> {
    Describer::describe_list_with_header(data, headers, writer, Context::default())
}

#[doc(hidden)]
macro_rules! describe_macro_to_string {
    (
        $t: ty
    ) => {
        impl Describe for $t {
            fn to_field(&self, _: &str) -> String {
                self.to_string()
            }
        }
    };
}

describe_macro_to_string!(String);
describe_macro_to_string!(i32);
describe_macro_to_string!(i64);
describe_macro_to_string!(u32);
describe_macro_to_string!(u64);
describe_macro_to_string!(u16);
describe_macro_to_string!(i16);
describe_macro_to_string!(usize);
describe_macro_to_string!(bool);