Skip to content

Commit

Permalink
Merge pull request #1039 from dtolnay/writebytearray
Browse files Browse the repository at this point in the history
Add Formatter::write_byte_array
  • Loading branch information
dtolnay committed Jul 12, 2023
2 parents 3ddda75 + a1ca32a commit 42dbd00
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions src/ser.rs
Expand Up @@ -189,12 +189,9 @@ where

#[inline]
fn serialize_bytes(self, value: &[u8]) -> Result<()> {
use serde::ser::SerializeSeq;
let mut seq = tri!(self.serialize_seq(Some(value.len())));
for byte in value {
tri!(seq.serialize_element(byte));
}
seq.end()
self.formatter
.write_byte_array(&mut self.writer, value)
.map_err(Error::io)
}

#[inline]
Expand Down Expand Up @@ -1770,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 42dbd00

Please sign in to comment.