diff --git a/src/ser.rs b/src/ser.rs index 7657db9ca..6bb6fd761 100644 --- a/src/ser.rs +++ b/src/ser.rs @@ -187,29 +187,10 @@ where format_escaped_str(&mut self.writer, &mut self.formatter, value).map_err(Error::io) } + #[inline] fn serialize_bytes(self, value: &[u8]) -> Result<()> { - tri!(self - .formatter - .begin_array(&mut self.writer) - .map_err(Error::io)); - let mut first = true; - for byte in value { - tri!(self - .formatter - .begin_array_value(&mut self.writer, first) - .map_err(Error::io)); - tri!(self - .formatter - .write_u8(&mut self.writer, *byte) - .map_err(Error::io)); - tri!(self - .formatter - .end_array_value(&mut self.writer) - .map_err(Error::io)); - first = false; - } self.formatter - .end_array(&mut self.writer) + .write_byte_array(&mut self.writer, value) .map_err(Error::io) } @@ -1786,6 +1767,24 @@ pub trait Formatter { writer.write_all(s) } + /// Writes the representation of a byte array. Formatters can choose whether + /// to represent bytes as a JSON array of integers (the default), or some + /// JSON string encoding like hex or base64. + fn write_byte_array(&mut self, writer: &mut W, value: &[u8]) -> io::Result<()> + where + W: ?Sized + io::Write, + { + tri!(self.begin_array(writer)); + let mut first = true; + for byte in value { + tri!(self.begin_array_value(writer, first)); + tri!(self.write_u8(writer, *byte)); + tri!(self.end_array_value(writer)); + first = false; + } + self.end_array(writer) + } + /// Called before every array. Writes a `[` to the specified /// writer. #[inline]