Skip to content

Add Formatter::write_byte_array #1039

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions src/ser.rs
Original file line number Diff line number Diff line change
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