literator 0.2.0

Efficient conversion of iterators to human-readable strings
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
#![doc = include_str!("../README.md")]
#![no_std]
#![forbid(unsafe_code, missing_docs)]

use core::fmt::{Display, Formatter};

pub mod block;
pub mod decorate;
pub mod fmt;
pub mod join;

use block::*;
use decorate::*;
use fmt::*;
use join::*;

/// Iterator extension trait for efficient `Display`/`Debug`.
///
/// See [crate-level documentation](index.html) for more information.
pub trait Literator: Iterator {
    /// Wrap the iterator in an object implementing `Display`/`Debug` that
    /// prints each item separated by a delimiter.
    ///
    /// This does not allocate, but does consumes the iterator when
    /// `Display::fmt()`, `Debug::fmt()`, or another formatting trait is used.
    /// Subsequent uses of the same [`Join`] object will print the empty string.
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::Literator;
    /// let items = ["Foo", "Bar"];
    /// let joined = items.iter().join(", ").to_string();
    /// assert_eq!(joined, "Foo, Bar");
    ///
    /// // Formatting options are forwarded.
    /// let joined = format!("{:04x}", [10, 20, 30].iter().join(", "));
    /// assert_eq!(joined, "000a, 0014, 001e");
    ///
    /// let floats = format!("{:0.02}", [1.0, 2.0].iter().join(" "));
    /// assert_eq!(floats, "1.00 2.00");
    /// ```
    fn join<D>(self, delim: D) -> Join<Self, D>
    where
        Self: Sized,
        D: Display,
    {
        Join::new(self, delim)
    }

    /// Concatenate all items into a single string, using each item's `Display`
    /// or `Debug` implementation.
    ///
    /// This is equivalent to [`.join(Empty)`](Literator::join).
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::{Literator, fmt::Uppercase};
    /// let chars = ['a', 'b', 'c'];
    /// assert_eq!(
    ///     chars.iter().map(Uppercase).concat().to_string(),
    ///     "ABC",
    /// );
    /// ```
    fn concat(self) -> Join<Self, Empty>
    where
        Self: Sized,
    {
        self.join(Empty)
    }

    /// Join the items using `delim` between the first N-1 elements, and
    /// `last_delim` between the next-to-last and last items.
    ///
    /// This is the same as
    /// [`oxford_join_custom()`](Literator::oxford_join_custom), but without the
    /// special case for exactly two elements.
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::Literator;
    /// let recipients = ["God", "Alice and Bob", "Charlie"];
    /// assert_eq!(
    ///     recipients.iter().conjunctive_join_custom(", ", ", and ").to_string(),
    ///     "God, Alice and Bob, and Charlie"
    /// );
    /// ```
    fn conjunctive_join_custom<Delim, LastDelim>(
        self,
        delim: Delim,
        last_delim: LastDelim,
    ) -> ConjunctiveJoin<Self, Delim, LastDelim>
    where
        Self: Sized,
        Delim: Display,
        LastDelim: Display,
    {
        ConjunctiveJoin::new(self, delim, last_delim)
    }

    /// Join the items separated by `", "` between each item, except `" and "`
    /// (no comma) between the next-to-last and last items.
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::Literator;
    /// let fruits = ["apples", "oranges", "bananas"];
    /// assert_eq!(
    ///     fruits.iter().join_and().to_string(),
    ///     "apples, oranges and bananas",
    /// );
    /// ```
    fn join_and(self) -> ConjunctiveJoin<Self>
    where
        Self: Sized,
    {
        self.conjunctive_join_custom(", ", " and ")
    }

    /// Join the items separated by `", "` between each item, except `" or "`
    /// (no comma) between the next-to-last and last items.
    fn join_or(self) -> ConjunctiveJoin<Self>
    where
        Self: Sized,
    {
        self.conjunctive_join_custom(", ", " or ")
    }

    /// Join the items separated by `", "` between each item, except `", and "`
    /// (with comma) between the next-to-last and last items.
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::Literator;
    /// let fruits = ["apples", "oranges", "bananas"];
    /// assert_eq!(
    ///     fruits.iter().join_comma_and().to_string(),
    ///     "apples, oranges, and bananas",
    /// );
    /// ```
    fn join_comma_and(self) -> ConjunctiveJoin<Self>
    where
        Self: Sized,
    {
        self.conjunctive_join_custom(", ", ", and ")
    }

    /// Join the items separated by `", "` between each item, except `", or "`
    /// (with comma) between the next-to-last and last items.
    fn join_comma_or(self) -> ConjunctiveJoin<Self>
    where
        Self: Sized,
    {
        self.conjunctive_join_custom(", ", ", or ")
    }

    /// Join items using serial comma ("Oxford comma", "Harvard comma").
    ///
    /// Turns this iterator into an object that implements `Display` and/or
    /// `Debug`. All formatting options are forwarded to each item.
    ///
    /// - Items are formatted using `Debug` or `Display` based on whether the
    ///   returned object is formatted using `Debug` or `Display`.
    /// - When the iterator is empty (N=0), nothing is printed.
    /// - When the iterator has exactly one element (N=1), no separators are
    ///   emitted.
    /// - When the iterator has exactly two elements (N=2), the `{exactly_two}`
    ///   conjunction is the only separator (typically `" and "`, no comma).
    /// - When the iterator has three or more elements (N>=3), `{first_n}` is
    ///   written between all elements, except that `{final_delim_conjunction}`
    ///   is emitted between the next-to-last and last element, and
    ///   `exactly_two_conjunction` is unused.
    ///
    /// Note: This function does not add any spaces around the
    /// delimiters/conjunctions, which is why it takes three arguments.
    ///
    /// To get a standard Oxford list, you would call this as
    /// `iter.oxford_join_custom(", ", " and ", ", and ")`, which is what
    /// [`oxford_join_and()`](Literator::oxford_join_and) does.
    fn oxford_join_custom<Delim, ExactlyTwo, Final>(
        self,
        first_n: Delim,
        exactly_two_conjunction: ExactlyTwo,
        final_delim_conjunction: Final,
    ) -> OxfordJoin<Self, Delim, ExactlyTwo, Final>
    where
        Self: Sized,
        Delim: Display,
        ExactlyTwo: Display,
        Final: Display,
    {
        OxfordJoin::new(
            self,
            first_n,
            exactly_two_conjunction,
            final_delim_conjunction,
        )
    }

    /// Oxford join with commas and English "and".
    ///
    /// See also [`Literator::oxford_join_custom()`].
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::Literator;
    /// let items = ["Parsley", "Sage", "Rosemary", "Thyme"];
    /// let line = items.iter().oxford_join_and().to_string();
    /// assert_eq!(line, "Parsley, Sage, Rosemary, and Thyme");
    ///
    /// let just_two = ["Pride", "Prejudice"];
    /// let title = just_two.iter().oxford_join_and().to_string();
    /// assert_eq!(title, "Pride and Prejudice");
    /// ```
    fn oxford_join_and(self) -> OxfordJoin<Self>
    where
        Self: Sized,
    {
        self.oxford_join_custom(", ", " and ", ", and ")
    }

    /// Oxford join with commas and English "or".
    ///
    /// See also [`Literator::oxford_join_custom()`].
    fn oxford_join_or(self) -> OxfordJoin<Self>
    where
        Self: Sized,
    {
        self.oxford_join_custom(", ", " or ", ", or ")
    }

    /// Oxford join with semicolons and English "and".
    ///
    /// See also [`Literator::oxford_join_custom()`].
    fn oxford_join_semicolon_and(self) -> OxfordJoin<Self>
    where
        Self: Sized,
    {
        self.oxford_join_custom("; ", "; and ", "; and ")
    }

    /// Oxford join with semicolons and English "or".
    ///
    /// See also [`Literator::oxford_join_custom()`].
    fn oxford_join_semicolon_or(self) -> OxfordJoin<Self>
    where
        Self: Sized,
    {
        self.oxford_join_custom("; ", "; or ", "; or ")
    }

    /// Produce an iterator where each item's `Display`/`Debug` implementation
    /// is overridden by `with`.
    ///
    /// This is essentially short-hand for `.map(|item| fmt::from_fn(move |f|
    /// ...))`. See [fmt::from_fn()].
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::{Literator, fmt::Capitalize};
    /// let hex_numbers = [10, 20, 30]
    ///     .iter()
    ///     .format_each_with(|n, f| write!(f, "{n:#04x}"))
    ///     .oxford_join_and()
    ///     .to_string();
    /// assert_eq!(hex_numbers, "0x0a, 0x14, and 0x1e");
    ///
    /// // Capitalize the first item
    /// let items = ["apples", "oranges", "pears"];
    /// assert_eq!(
    ///     items
    ///         .iter()
    ///         .enumerate()
    ///         .format_each_with(|(index, thing), f| if *index == 0 {
    ///             write!(f, "{}", Capitalize(thing))
    ///         } else {
    ///             write!(f, "{thing}")
    ///         })
    ///         .oxford_join_and()
    ///         .to_string(),
    ///     "Apples, oranges, and pears",
    /// );
    /// ```
    fn format_each_with<F>(self, with: F) -> impl Iterator<Item = FormatWith<Self::Item, F>>
    where
        Self: Sized,
        F: Fn(&Self::Item, &mut Formatter) -> core::fmt::Result + Clone,
    {
        self.map(move |item| FormatWith {
            item,
            with: with.clone(),
        })
    }

    /// Capitalize the first item in the list.
    ///
    /// Due to current limitations in the standard library, this only works for
    /// `Display`, not other formatting traits.
    ///
    /// To capitalize all items, use [`.map(Capitalize)`](Capitalize) instead.
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::Literator;
    /// let items = ["apples", "oranges", "pears"];
    /// assert_eq!(
    ///     items
    ///         .iter()
    ///         .capitalize_first()
    ///         .oxford_join_and()
    ///         .to_string(),
    ///     "Apples, oranges, and pears",
    /// );
    /// ```
    fn capitalize_first(self) -> impl Iterator<Item: Display>
    where
        Self: Sized,
        Self::Item: Display,
    {
        self.enumerate().format_each_with(|(index, thing), f| {
            if *index == 0 {
                write!(f, "{}", Capitalize(thing))
            } else {
                thing.fmt(f)
            }
        })
    }

    /// Produce an iterator where each item's `Display`/`Debug` implementation
    /// writes a custom prefix before the item.
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::Literator;
    /// let numbers = 1..=5;
    /// let even_list = numbers
    ///     .into_iter()
    ///     .prefix_each_with(|n, f| if *n % 2 == 0 { write!(f, "* ") } else { Ok (()) })
    ///     .join('\n')
    ///     .to_string();
    /// assert_eq!(even_list,
    /// "1
    /// * 2
    /// 3
    /// * 4
    /// 5");
    /// ```
    fn prefix_each_with<F>(self, with: F) -> impl Iterator<Item = PrefixWith<Self::Item, F>>
    where
        F: Fn(&Self::Item, &mut Formatter) -> core::fmt::Result + Clone,
        Self: Sized,
    {
        self.map(move |item| PrefixWith {
            item,
            with: with.clone(),
        })
    }

    /// Produce an iterator where each item's `Display`/`Debug` implementation
    /// writes a custom suffix after the item.
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::Literator;
    /// let numbers = 1..=10;
    /// let even_list = numbers
    ///     .into_iter()
    ///     .suffix_each_with(|n, f| if *n % 2 == 0 { write!(f, " *") } else { Ok (()) })
    ///     .join('\n')
    ///     .to_string();
    /// assert_eq!(even_list, "1\n2 *\n3\n4 *\n5\n6 *\n7\n8 *\n9\n10 *");
    /// ```
    fn suffix_each_with<F>(self, with: F) -> impl Iterator<Item = SuffixWith<Self::Item, F>>
    where
        F: Fn(&Self::Item, &mut Formatter) -> core::fmt::Result + Clone,
        Self: Sized,
    {
        self.map(move |item| SuffixWith {
            item,
            with: with.clone(),
        })
    }

    /// Produce an iterator where each item's `Display`/`Debug` implementation
    /// writes `prefix` before the item.
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::Literator;
    /// let items = ["Milk", "Eggs", "Tampons"];
    /// let shopping_list = items.iter().prefix_each("- ").join('\n').to_string();
    /// assert_eq!(shopping_list, "- Milk\n- Eggs\n- Tampons");
    /// ```
    fn prefix_each<P>(self, prefix: P) -> impl Iterator<Item = Prefix<Self::Item, P>>
    where
        P: Display + Clone,
        Self: Sized,
    {
        self.map(move |item| Prefix {
            item,
            prefix: prefix.clone(),
        })
    }

    /// Produce an iterator where each item's `Display`/`Debug` implementation
    /// writes `suffix` after the item.
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::Literator;
    /// let words = ["Fresh", "Innovative", "Placemaking", "Disposable duvets", "Growth hacking"];
    /// let message = words.iter().suffix_each('.').join(' ').to_string();
    /// assert_eq!(message, "Fresh. Innovative. Placemaking. Disposable duvets. Growth hacking.");
    /// ```
    fn suffix_each<S>(self, suffix: S) -> impl Iterator<Item = Suffix<Self::Item, S>>
    where
        S: Display + Clone,
        Self: Sized,
    {
        self.map(move |item| Suffix {
            item,
            suffix: suffix.clone(),
        })
    }

    /// Produce an iterator where each item's `Display`/`Debug` implementation
    /// writes `prefix` before and `suffix` after the item.
    ///
    /// This is shorthand for `.suffix_each(suffix).prefix_each(prefix)`.
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::Literator;
    /// let items = ["Foo", "Bar"];
    /// let list = items.iter().surround_each('(', ')').concat().to_string();
    /// assert_eq!(list, "(Foo)(Bar)");
    /// ```
    fn surround_each<P, S>(
        self,
        prefix: P,
        suffix: S,
    ) -> impl Iterator<Item = Prefix<Suffix<Self::Item, S>, P>>
    where
        P: Display + Clone,
        S: Display + Clone,
        Self: Sized,
    {
        self.suffix_each(suffix).prefix_each(prefix)
    }

    /// Print each item prefixed by indentation, where each level of indentation
    /// is 4 spaces, and suffix each item with a newline.
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::Literator;
    /// let numbers = format!("\n{}", [1, 2, 3].iter().prefix_each("- ").indent(1).concat());
    /// assert_eq!(numbers, "
    ///     - 1
    ///     - 2
    ///     - 3
    /// ");
    /// ```
    fn indent(
        self,
        level: usize,
    ) -> impl Iterator<Item = Prefix<Suffix<Self::Item, char>, Repeat<&'static str>>>
    where
        Self: Sized,
    {
        self.indent_custom(level, "    ", '\n')
    }

    /// Print each item with custom indentation.
    fn indent_custom<P, S>(
        self,
        level: usize,
        indentation: P,
        newline: S,
    ) -> impl Iterator<Item = Prefix<Suffix<Self::Item, S>, Repeat<P>>>
    where
        P: Display + Clone,
        S: Display + Clone,
        Self: Sized,
    {
        self.surround_each(repeat(indentation, level), newline)
    }

    /// Print items in a block surrounded by `open` and `close`, indented by `inner_level`.
    ///
    /// When there are zero items, the open and close tokens are printed without
    /// any spacing or newline.
    ///
    /// When there are one or more items: A newline is added after the open
    /// token, and each item is printed with default indentation (four spaces
    /// per level) on a separate line, and the closing delimiter is placed on a
    /// separate line with indentation corresponding to `inner_level-1`.
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::Literator;
    /// # use std::collections::BTreeMap;
    /// let empty: &[i32] = &[];
    /// assert_eq!(empty.iter().indented_block('{', '}', 1).to_string(), "{}");
    ///
    /// let two = &[1, 2];
    /// assert_eq!(format!("\n{}", two.iter().indented_block('{', '}', 1)), "
    /// {
    ///     1
    ///     2
    /// }");
    ///
    /// let map = BTreeMap::from_iter([("hello", 123), ("world", 456)]);
    /// assert_eq!(
    ///     format!("\n{}", map
    ///         .iter()
    ///         .format_each_with(|(key, value), f| write!(f, "{key}: {value},"))
    ///         .indented_block('{', '}', 1)),
    ///     "
    /// {
    ///     hello: 123,
    ///     world: 456,
    /// }");
    /// ```
    fn indented_block<Open, Close>(
        self,
        open: Open,
        close: Close,
        inner_level: usize,
    ) -> IndentedBlock<Self, Open, Close, &'static str, char>
    where
        Self: Sized,
        Open: Display,
        Close: Display,
    {
        self.indented_block_custom(open, close, inner_level, "    ", '\n')
    }

    /// Same as [`indented_block()`](Literator::indented_block), but with custom
    /// indentation and newline tokens.
    ///
    /// `indentation` is printed for each indentation level. `newline` is
    /// printed after each item, as well as after `open`.
    fn indented_block_custom<Open, Close, Indentation, Newline>(
        self,
        open: Open,
        close: Close,
        inner_level: usize,
        indentation: Indentation,
        newline: Newline,
    ) -> IndentedBlock<Self, Open, Close, Indentation, Newline>
    where
        Self: Sized,
        Open: Display,
        Close: Display,
        Indentation: Display,
        Newline: Display,
    {
        IndentedBlock::new(self, open, close, indentation, newline, inner_level)
    }

    /// Print items in a block surrounded by `open` and `close`, where items are
    /// delimited by `delim`.
    ///
    /// When there are zero items, the open and close tokens are printed without
    /// any spacing, but when there are one or more items, a space is added
    /// after the opening token and before the closing token. This is what
    /// distinguishes `inline_block()` from simply using `join(delim)`
    /// surrounded by the open/close tokens.
    ///
    /// # Example
    ///
    /// ```
    /// # use literator::Literator;
    /// let empty: &[i32] = &[];
    /// assert_eq!(empty.iter().inline_block('[', ',', ']').to_string(), "[]");
    ///
    /// let one = &[1];
    /// assert_eq!(one.iter().inline_block('[', ',', ']').to_string(), "[ 1 ]");
    ///
    /// let two = &[1, 2];
    /// assert_eq!(two.iter().inline_block('[', ", ", ']').to_string(), "[ 1, 2 ]");
    /// ```
    fn inline_block<P, D, S>(self, open: P, delim: D, close: S) -> InlineBlock<Self, P, D, S>
    where
        Self: Sized,
        P: Display,
        D: Display,
        S: Display,
    {
        InlineBlock::new(self, open, delim, close)
    }
}

impl<I: Iterator> Literator for I {}

macro_rules! impl_fmt_trait {
    ($trait:ident) => {
        impl<D, I> core::fmt::$trait for Join<I, D>
        where
            I: Iterator<Item: core::fmt::$trait>,
            D: Display,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                self.do_fmt(f, core::fmt::$trait::fmt)
            }
        }

        impl<I, D, L> core::fmt::$trait for ConjunctiveJoin<I, D, L>
        where
            I: Iterator<Item: core::fmt::$trait>,
            D: Display,
            L: Display,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                self.do_fmt(f, core::fmt::$trait::fmt)
            }
        }

        impl<I, D1, D2, D3> core::fmt::$trait for OxfordJoin<I, D1, D2, D3>
        where
            I: Iterator<Item: core::fmt::$trait>,
            D1: Display,
            D2: Display,
            D3: Display,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                self.do_fmt(f, core::fmt::$trait::fmt)
            }
        }

        impl<I, Open, Delim, Close> core::fmt::$trait for InlineBlock<I, Open, Delim, Close>
        where
            I: Iterator<Item: core::fmt::$trait>,
            Open: Display,
            Delim: Display,
            Close: Display,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                self.do_fmt(f, core::fmt::$trait::fmt)
            }
        }

        impl<I, Open, Close, Indentation, Newline> core::fmt::$trait
            for IndentedBlock<I, Open, Close, Indentation, Newline>
        where
            I: Iterator<Item: core::fmt::$trait>,
            Open: Display,
            Close: Display,
            Indentation: Display,
            Newline: Display,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                self.do_fmt(f, core::fmt::$trait::fmt)
            }
        }

        impl<T: core::fmt::$trait, P: Display> core::fmt::$trait for Prefix<T, P> {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                write!(f, "{}", self.prefix)?;
                self.item.fmt(f)
            }
        }

        impl<T: core::fmt::$trait, S: Display> core::fmt::$trait for Suffix<T, S> {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                self.item.fmt(f)?;
                write!(f, "{}", self.suffix)
            }
        }

        impl<T, F> core::fmt::$trait for PrefixWith<T, F>
        where
            T: core::fmt::$trait,
            F: Fn(&T, &mut Formatter) -> core::fmt::Result,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                (self.with)(&self.item, f)?;
                self.item.fmt(f)
            }
        }

        impl<T, F> core::fmt::$trait for SuffixWith<T, F>
        where
            T: core::fmt::$trait,
            F: Fn(&T, &mut Formatter) -> core::fmt::Result,
        {
            fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
                self.item.fmt(f)?;
                (self.with)(&self.item, f)
            }
        }
    };
}

impl_fmt_trait!(Display);
impl_fmt_trait!(Debug);
impl_fmt_trait!(LowerHex);
impl_fmt_trait!(LowerExp);
impl_fmt_trait!(UpperHex);
impl_fmt_trait!(UpperExp);
impl_fmt_trait!(Octal);
impl_fmt_trait!(Pointer);
impl_fmt_trait!(Binary);