pprint 0.3.6

Flexible and lightweight pretty printing library for Rust
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
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::io::Write;

use regex::Regex;

const BYTES_SIZE: usize = 24;

/// A Document that can be pretty printed
/// Represents the different ways wherein a doc can be printed
#[derive(Debug, Clone)]
#[allow(non_camel_case_types)]
pub enum Doc<'a> {
    Null,

    Char(u8),
    DoubleChar([u8; 2]),
    TripleChar([u8; 3]),
    QuadChar([u8; 4]),

    Bytes(Vec<u8>, usize),
    SmallBytes([u8; BYTES_SIZE], usize),

    String(Cow<'a, str>),

    i8(i8),
    i16(i16),
    i32(i32),
    i64(i64),
    i128(i128),
    isize(isize),
    u8(u8),
    u16(u16),
    u32(u32),
    u64(u64),
    u128(u128),
    usize(usize),

    f32(f32),
    f64(f64),

    DoubleDoc(Box<Doc<'a>>, Box<Doc<'a>>),
    TripleDoc(Box<Doc<'a>>, Box<Doc<'a>>, Box<Doc<'a>>),

    Concat(Vec<Doc<'a>>),

    Group(Box<Doc<'a>>),

    Indent(Box<Doc<'a>>),
    Dedent(Box<Doc<'a>>),

    Join(Box<(Doc<'a>, Vec<Doc<'a>>)>),
    SmartJoin(Box<(Doc<'a>, Vec<Doc<'a>>)>),
    LinearJoin(Box<(Doc<'a>, Vec<Doc<'a>>)>),

    IfBreak(Box<Doc<'a>>, Box<Doc<'a>>),

    Hardline,
    Softline,
    Mediumline,
    Line,
}

impl<'a> std::ops::Add for Doc<'a> {
    type Output = Doc<'a>;

    fn add(self, other: Doc<'a>) -> Doc<'a> {
        match (self, other) {
            // Skip Null operands — avoids polluting Concat vecs with
            // zero-width nodes that still incur traversal + cache overhead.
            (Doc::Null, other) => other,
            (s, Doc::Null) => s,
            (Doc::Concat(mut docs), other) => {
                docs.push(other);
                Doc::Concat(docs)
            }
            (s, Doc::Concat(mut docs)) => {
                // Prepend via a fresh Vec to avoid O(n) insert(0) shift.
                let mut new_docs = Vec::with_capacity(docs.len() + 1);
                new_docs.push(s);
                new_docs.append(&mut docs);
                Doc::Concat(new_docs)
            }
            (s, other) => Doc::Concat(vec![s, other]),
        }
    }
}

fn format_small_bytes<'a, T>(value: &T) -> Doc<'a>
where
    T: std::fmt::Display,
{
    let mut bytes = [0u8; BYTES_SIZE];
    let mut cursor = std::io::Cursor::new(&mut bytes[..]);

    write!(&mut cursor, "{}", value)
        .expect("format_small_bytes: value exceeded fixed stack buffer capacity");
    let len = cursor.position() as usize;

    if len == 1 {
        Doc::Char(bytes[0])
    } else if len == 2 {
        Doc::DoubleChar([bytes[0], bytes[1]])
    } else if len == 3 {
        Doc::TripleChar([bytes[0], bytes[1], bytes[2]])
    } else if len == 4 {
        Doc::QuadChar([bytes[0], bytes[1], bytes[2], bytes[3]])
    } else {
        Doc::SmallBytes(bytes, len)
    }
}

pub fn bytes<'a>(value: &[u8], len: usize) -> Doc<'a> {
    assert!(
        len <= value.len(),
        "bytes: requested length ({len}) exceeds input slice length ({})",
        value.len()
    );

    if len == 1 {
        Doc::Char(value[0])
    } else if len == 2 {
        Doc::DoubleChar([value[0], value[1]])
    } else if len == 3 {
        Doc::TripleChar([value[0], value[1], value[2]])
    } else if len == 4 {
        Doc::QuadChar([value[0], value[1], value[2], value[3]])
    } else if len <= BYTES_SIZE {
        let mut bytes = [0u8; BYTES_SIZE];
        bytes[..len].copy_from_slice(&value[..len]);

        Doc::SmallBytes(bytes, len)
    } else {
        Doc::Bytes(value[..len].into(), len)
    }
}

/// Group a document if it contains a line break.
/// A group is a document that is printed on a single line if it fits the page,
/// otherwise it's printed with line breaks.
pub fn group<'a>(doc: impl Into<Doc<'a>> + Clone) -> Doc<'a> {
    Doc::Group(Box::new(doc.into()))
}

/// Concatenate a vector of documents into a single document.
pub fn concat<'a>(docs: Vec<impl Into<Doc<'a>>>) -> Doc<'a> {
    let len = docs.len();
    let mut iter = docs.into_iter();
    match len {
        0 => Doc::Null,
        1 => iter.next().unwrap().into(),
        2 => Doc::DoubleDoc(
            Box::new(iter.next().unwrap().into()),
            Box::new(iter.next().unwrap().into()),
        ),
        3 => Doc::TripleDoc(
            Box::new(iter.next().unwrap().into()),
            Box::new(iter.next().unwrap().into()),
            Box::new(iter.next().unwrap().into()),
        ),
        _ => Doc::Concat(iter.map(Into::into).collect()),
    }
}

/// Enwrap a document with two other documents, `left` and `right`.
pub fn wrap<'a>(
    left: impl Into<Doc<'a>>,
    doc: impl Into<Doc<'a>>,
    right: impl Into<Doc<'a>>,
) -> Doc<'a> {
    Doc::TripleDoc(
        Box::new(left.into()),
        Box::new(doc.into()),
        Box::new(right.into()),
    )
}

/// Join a vector of documents on a separator.
pub fn join<'a>(sep: impl Into<Doc<'a>> + Clone, docs: Vec<impl Into<Doc<'a>> + Clone>) -> Doc<'a> {
    Doc::Join(Box::new((sep.into(), docs.iter().map(Doc::from).collect())))
}

/// Join a vector of documents on a separator if the result fits the page,
/// hence the name "smart join", otherwise join them on a line break.
///
/// Implemented using the algorithm described in:
/// src/utils.rs
pub fn smart_join<'a>(
    sep: impl Into<Doc<'a>> + Clone,
    docs: Vec<impl Into<Doc<'a>> + Clone>,
) -> Doc<'a> {
    Doc::SmartJoin(Box::new((sep.into(), docs.iter().map(Doc::from).collect())))
}

/// Join a vector of documents with a linear scan: break when the line would overflow.
/// No text justification pre-pass — each break decision is made inline.
pub fn linear_join<'a>(
    sep: impl Into<Doc<'a>> + Clone,
    docs: Vec<impl Into<Doc<'a>> + Clone>,
) -> Doc<'a> {
    Doc::LinearJoin(Box::new((sep.into(), docs.iter().map(Doc::from).collect())))
}

/// Indent a document by one level.
pub fn indent<'a>(doc: impl Into<Doc<'a>>) -> Doc<'a> {
    Doc::Indent(Box::new(doc.into()))
}

/// Dedent a document by one level.
pub fn dedent<'a>(doc: impl Into<Doc<'a>>) -> Doc<'a> {
    Doc::Dedent(Box::new(doc.into()))
}

/// An absolute line break, i.e. a line break that is always printed.
pub fn hardline<'a>() -> Doc<'a> {
    Doc::Hardline
}

/// A line break, i.e. a line break that is only printed if the document does not fit the page.
pub fn softline<'a>() -> Doc<'a> {
    Doc::Softline
}

/// If the first document fits the page, print it, otherwise print the second document.
pub fn if_break<'a>(doc: Doc<'a>, other: Doc<'a>) -> Doc<'a> {
    Doc::IfBreak(Box::new(doc), Box::new(other))
}

pub trait Group {
    fn group(self) -> Self;
}

impl Group for Doc<'_> {
    fn group(self) -> Self {
        group(self)
    }
}

pub trait Indent {
    fn indent(self) -> Self;
}

impl Indent for Doc<'_> {
    fn indent(self) -> Self {
        indent(self)
    }
}

pub trait Dedent {
    fn dedent(self) -> Self;
}

impl Dedent for Doc<'_> {
    fn dedent(self) -> Self {
        dedent(self)
    }
}

pub trait Join<'a> {
    fn join(self, sep: impl Into<Doc<'a>> + Clone) -> Doc<'a>;
}

impl<'a> Join<'a> for Vec<Doc<'a>> {
    fn join(self, sep: impl Into<Doc<'a>> + Clone) -> Doc<'a> {
        join(sep, self)
    }
}

pub trait SmartJoin<'a> {
    fn smart_join(self, sep: impl Into<Doc<'a>> + Clone) -> Doc<'a>;
}

impl<'a> SmartJoin<'a> for Vec<Doc<'a>> {
    fn smart_join(self, sep: impl Into<Doc<'a>> + Clone) -> Doc<'a> {
        smart_join(sep, self)
    }
}

pub trait LinearJoin<'a> {
    fn linear_join(self, sep: impl Into<Doc<'a>> + Clone) -> Doc<'a>;
}

impl<'a> LinearJoin<'a> for Vec<Doc<'a>> {
    fn linear_join(self, sep: impl Into<Doc<'a>> + Clone) -> Doc<'a> {
        linear_join(sep, self)
    }
}

pub trait Wrap<'a> {
    fn wrap(self, left: impl Into<Doc<'a>> + Clone, right: impl Into<Doc<'a>> + Clone) -> Doc<'a>;
}

impl<'a> Wrap<'a> for Doc<'a> {
    fn wrap(self, left: impl Into<Doc<'a>> + Clone, right: impl Into<Doc<'a>> + Clone) -> Doc<'a> {
        wrap(left, self, right)
    }
}

impl<'a> From<&'a str> for Doc<'a> {
    fn from(s: &'a str) -> Doc<'a> {
        bytes(s.as_bytes(), s.len())
    }
}

impl<'a> From<String> for Doc<'a> {
    fn from(s: String) -> Doc<'a> {
        bytes(s.as_bytes(), s.len())
    }
}

impl<'a> From<bool> for Doc<'a> {
    fn from(b: bool) -> Doc<'a> {
        format_small_bytes(&b)
    }
}

macro_rules! impl_from_number_to_doc {
    ($($t:ident),*) => {
        $(
            impl<'a> From<$t> for Doc<'a> {
                fn from(value: $t) -> Self {
                    Doc::$t(value)
                }
            }
        )*
    };
}
impl_from_number_to_doc!(
    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64
);

impl<'a, T> From<Option<T>> for Doc<'a>
where
    T: Into<Doc<'a>>,
{
    fn from(opt: Option<T>) -> Doc<'a> {
        match opt {
            Some(value) => value.into(),
            None => panic!("Doc::from<Option<T>>: None is unsupported; handle None explicitly"),
        }
    }
}

impl<'a, T> From<&[T]> for Doc<'a>
where
    T: Into<Doc<'a>> + Clone,
{
    fn from(slice: &[T]) -> Doc<'a> {
        slice
            .iter()
            .map(|item| item.clone().into())
            .collect::<Vec<_>>()
            .into()
    }
}

impl From<()> for Doc<'_> {
    fn from(_: ()) -> Self {
        Doc::from("()")
    }
}

impl<'a, T> From<&T> for Doc<'a>
where
    T: Into<Doc<'a>> + Clone,
{
    fn from(value: &T) -> Self {
        value.clone().into()
    }
}

impl<'a, T> From<Box<T>> for Doc<'a>
where
    T: Into<Doc<'a>>,
{
    fn from(value: Box<T>) -> Self {
        (*value).into()
    }
}

impl<'a> From<Cow<'a, str>> for Doc<'a> {
    fn from(cow: Cow<'a, str>) -> Self {
        match cow {
            Cow::Borrowed(s) => s.into(),
            Cow::Owned(s) => s.into(),
        }
    }
}

impl<'a> From<Regex> for Doc<'a> {
    fn from(regex: Regex) -> Self {
        regex.as_str().to_owned().into()
    }
}

macro_rules! impl_from_tuple_to_doc {
    ($($t:ident),*) => {
        #[allow(non_snake_case)]
        impl<'a, $($t),*> From<($($t),*)> for Doc<'a>
        where
            $($t: Into<Doc<'a>>),*
        {
            fn from(tuple: ($($t),*)) -> Self {
                let ($($t),*) = tuple;

                vec![$($t.into()),*]
                    .join(", ")
                    .group()
                    .wrap("(", ")")
            }
        }
    };
}

impl_from_tuple_to_doc!(T1, T2);
impl_from_tuple_to_doc!(T1, T2, T3);
impl_from_tuple_to_doc!(T1, T2, T3, T4);
impl_from_tuple_to_doc!(T1, T2, T3, T4, T5);
impl_from_tuple_to_doc!(T1, T2, T3, T4, T5, T6);
impl_from_tuple_to_doc!(T1, T2, T3, T4, T5, T6, T7);
impl_from_tuple_to_doc!(T1, T2, T3, T4, T5, T6, T7, T8);
impl_from_tuple_to_doc!(T1, T2, T3, T4, T5, T6, T7, T8, T9);
impl_from_tuple_to_doc!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
impl_from_tuple_to_doc!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
impl_from_tuple_to_doc!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);

impl<'a, T> From<Vec<T>> for Doc<'a>
where
    T: Into<Doc<'a>> + 'a + Clone,
{
    fn from(vec: Vec<T>) -> Doc<'a> {
        if !vec.is_empty() {
            smart_join(Doc::from(", "), vec)
                .group()
                .wrap("[", "]")
                .indent()
        } else {
            Doc::from("[]")
        }
    }
}

impl<'a, K, V, R> From<HashMap<K, V, R>> for Doc<'a>
where
    K: Into<Doc<'a>>,
    V: Into<Doc<'a>>,
{
    fn from(map: HashMap<K, V, R>) -> Doc<'a> {
        let doc_vec: Vec<_> = map
            .into_iter()
            .map(|(key, value)| key.into() + Doc::from(": ") + value.into())
            .collect();

        if !doc_vec.is_empty() {
            doc_vec
                .join(Doc::from(", ") + Doc::Hardline)
                .group()
                .wrap("{", "}")
                .indent()
        } else {
            Doc::from("{}")
        }
    }
}

impl<'a, T> From<HashSet<T>> for Doc<'a>
where
    T: Into<Doc<'a>>,
{
    fn from(set: HashSet<T>) -> Self {
        let doc_vec: Vec<_> = set.into_iter().map(|item| item.into()).collect();

        if !doc_vec.is_empty() {
            doc_vec.join(", ").group().wrap("{", "}").indent()
        } else {
            Doc::from("{}")
        }
    }
}