diff options
| author | Laurenz <laurmaedje@gmail.com> | 2021-02-03 21:30:36 +0100 |
|---|---|---|
| committer | Laurenz <laurmaedje@gmail.com> | 2021-02-03 21:34:49 +0100 |
| commit | d86a5e8a1f469dd79abf3137dba77a71fae2a774 (patch) | |
| tree | fc7ab35d999322b9d124e41ab80948df23965d26 /src/pretty.rs | |
| parent | 6fcef9973be4253e5b377251dd9d1921f9738fc1 (diff) | |
Tidy up raw blocks 🧹
- Better trimming (only trim at the end if necessary)
- Fixed block-level layouting
- Improved pretty printing
- Flip inline variable to block
- Flip inline variable to display for math formulas
Diffstat (limited to 'src/pretty.rs')
| -rw-r--r-- | src/pretty.rs | 71 |
1 files changed, 70 insertions, 1 deletions
diff --git a/src/pretty.rs b/src/pretty.rs index f1c3cfb7..0123e9a7 100644 --- a/src/pretty.rs +++ b/src/pretty.rs @@ -2,10 +2,13 @@ use std::fmt::{Arguments, Result, Write}; +use crate::color::{Color, RgbaColor}; +use crate::geom::{Angle, Length, Linear, Relative}; + /// Pretty print an item and return the resulting string. pub fn pretty<T>(item: &T) -> String where - T: Pretty, + T: Pretty + ?Sized, { let mut p = Printer::new(); item.pretty(&mut p); @@ -29,6 +32,11 @@ impl Printer { Self { buf: String::new() } } + /// Push a character into the buffer. + pub fn push(&mut self, c: char) { + self.buf.push(c); + } + /// Push a string into the buffer. pub fn push_str(&mut self, string: &str) { self.buf.push_str(string); @@ -67,3 +75,64 @@ impl Write for Printer { Ok(()) } } + +impl Pretty for i64 { + fn pretty(&self, p: &mut Printer) { + p.push_str(itoa::Buffer::new().format(*self)); + } +} + +impl Pretty for f64 { + fn pretty(&self, p: &mut Printer) { + p.push_str(ryu::Buffer::new().format(*self)); + } +} + +impl Pretty for str { + fn pretty(&self, p: &mut Printer) { + p.push('"'); + for c in self.chars() { + match c { + '\\' => p.push_str(r"\\"), + '"' => p.push_str(r#"\""#), + '\n' => p.push_str(r"\n"), + '\r' => p.push_str(r"\r"), + '\t' => p.push_str(r"\t"), + _ => p.push(c), + } + } + p.push('"'); + } +} + +macro_rules! impl_pretty_display { + ($($type:ty),* $(,)?) => { + $(impl Pretty for $type { + fn pretty(&self, p: &mut Printer) { + write!(p, "{}", self).unwrap(); + } + })* + }; +} + +impl_pretty_display! { + bool, + Length, + Angle, + Relative, + Linear, + RgbaColor, + Color, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_pretty_print_str() { + assert_eq!(pretty("\n"), r#""\n""#); + assert_eq!(pretty("\\"), r#""\\""#); + assert_eq!(pretty("\""), r#""\"""#); + } +} |
