From e509adcac5bfac91ebc350e9c36b699328d47cb1 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Sun, 26 Apr 2015 09:29:06 -0700 Subject: [PATCH] Allow the pretty printer character to be changed This unfortunately loses the simd-ish whitespace printer, but since pretty printing shouldn't be on a hot path, this shouldn't really matter. Partially addresses #65. --- src/json/ser.rs | 48 +++++++++++++++++++++++++----------------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/src/json/ser.rs b/src/json/ser.rs index 23086cbd..2803ea86 100644 --- a/src/json/ser.rs +++ b/src/json/ser.rs @@ -295,16 +295,29 @@ impl Formatter for CompactFormatter { } } -pub struct PrettyFormatter { +pub struct PrettyFormatter<'a> { current_indent: usize, - indent: usize, + indent: &'a [u8], } -impl Formatter for PrettyFormatter { +impl<'a> PrettyFormatter<'a> { + fn new() -> Self { + PrettyFormatter::with_indent(b" ") + } + + fn with_indent(indent: &'a [u8]) -> Self { + PrettyFormatter { + current_indent: 0, + indent: indent, + } + } +} + +impl<'a> Formatter for PrettyFormatter<'a> { fn open(&mut self, writer: &mut W, ch: u8) -> io::Result<()> where W: io::Write, { - self.current_indent += self.indent; + self.current_indent += 1; writer.write_all(&[ch]) } @@ -317,7 +330,7 @@ impl Formatter for PrettyFormatter { try!(writer.write_all(b",\n")); } - spaces(writer, self.current_indent) + indent(writer, self.current_indent, self.indent) } fn colon(&mut self, writer: &mut W) -> io::Result<()> @@ -329,9 +342,9 @@ impl Formatter for PrettyFormatter { fn close(&mut self, writer: &mut W, ch: u8) -> io::Result<()> where W: io::Write, { - self.current_indent -= self.indent; + self.current_indent -= 1; try!(writer.write(b"\n")); - try!(spaces(writer, self.current_indent)); + try!(indent(writer, self.current_indent, self.indent)); writer.write_all(&[ch]) } @@ -439,10 +452,7 @@ pub fn to_writer_pretty(writer: &mut W, value: &T) -> io::Result<()> where W: io::Write, T: ser::Serialize, { - let mut ser = Serializer::new_with_formatter(writer, PrettyFormatter { - current_indent: 0, - indent: 2, - }); + let mut ser = Serializer::new_with_formatter(writer, PrettyFormatter::new()); try!(value.serialize(&mut ser)); Ok(()) } @@ -489,20 +499,12 @@ pub fn to_string_pretty(value: &T) -> Result String::from_utf8(vec) } -fn spaces(wr: &mut W, mut n: usize) -> io::Result<()> +fn indent(wr: &mut W, n: usize, s: &[u8]) -> io::Result<()> where W: io::Write, { - const LEN: usize = 16; - const BUF: &'static [u8; LEN] = &[b' '; 16]; - - while n >= LEN { - try!(wr.write_all(BUF)); - n -= LEN; + for _ in 0 .. n { + try!(wr.write_all(s)); } - if n > 0 { - wr.write_all(&BUF[..n]) - } else { - Ok(()) - } + Ok(()) }