Skip to main content

oak_pretty_print/
to_doc.rs

1use crate::Document;
2use alloc::{boxed::Box, string::String, vec::Vec};
3
4/// A trait for types that can be converted to a document for pretty printing.
5pub trait AsDocument {
6    /// Converts this type to a document for pretty printing.
7    fn as_document(&self) -> Document<'_>;
8}
9
10/// A trait for types that can be converted to a document value, potentially consuming the input.
11pub trait ToDocument<'a> {
12    /// Converts this type to a document value.
13    fn to_document(self) -> Document<'a>;
14}
15
16impl AsDocument for String {
17    fn as_document(&self) -> Document<'_> {
18        Document::Text(self.as_str().into())
19    }
20}
21
22impl AsDocument for str {
23    fn as_document(&self) -> Document<'_> {
24        Document::Text(self.into())
25    }
26}
27
28impl<'a> AsDocument for Document<'a> {
29    fn as_document(&self) -> Document<'_> {
30        self.clone()
31    }
32}
33
34impl<T: AsDocument> AsDocument for Vec<T> {
35    fn as_document(&self) -> Document<'_> {
36        Document::Concat(self.iter().map(|t| t.as_document()).collect())
37    }
38}
39
40impl<T: AsDocument> AsDocument for Option<T> {
41    fn as_document(&self) -> Document<'_> {
42        match self {
43            Some(t) => t.as_document(),
44            None => Document::Nil,
45        }
46    }
47}
48
49impl<T: AsDocument + ?Sized> AsDocument for &T {
50    fn as_document(&self) -> Document<'_> {
51        (**self).as_document()
52    }
53}
54
55impl<T: AsDocument + ?Sized> AsDocument for Box<T> {
56    fn as_document(&self) -> Document<'_> {
57        self.as_ref().as_document()
58    }
59}
60
61impl<'a> ToDocument<'a> for Document<'a> {
62    fn to_document(self) -> Document<'a> {
63        self
64    }
65}
66
67impl<'a, T: AsDocument + ?Sized> ToDocument<'a> for &'a T {
68    fn to_document(self) -> Document<'a> {
69        self.as_document()
70    }
71}
72
73impl<'a> ToDocument<'a> for String {
74    fn to_document(self) -> Document<'a> {
75        Document::Text(self.into())
76    }
77}