Skip to content

Commit

Permalink
Factor out byte array serialization to a new Formatter method
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Jul 11, 2023
1 parent 857b010 commit a1ca32a
Showing 1 changed file with 20 additions and 21 deletions.
41 changes: 20 additions & 21 deletions src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down Expand Up @@ -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<W>(&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]
Expand Down

0 comments on commit a1ca32a

Please sign in to comment.