Skip to content

Commit 42dbd00

Browse files
authored
Merge pull request #1039 from dtolnay/writebytearray
Add Formatter::write_byte_array
2 parents 3ddda75 + a1ca32a commit 42dbd00

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

src/ser.rs

+21-6
Original file line numberDiff line numberDiff line change
@@ -189,12 +189,9 @@ where
189189

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

200197
#[inline]
@@ -1770,6 +1767,24 @@ pub trait Formatter {
17701767
writer.write_all(s)
17711768
}
17721769

1770+
/// Writes the representation of a byte array. Formatters can choose whether
1771+
/// to represent bytes as a JSON array of integers (the default), or some
1772+
/// JSON string encoding like hex or base64.
1773+
fn write_byte_array<W>(&mut self, writer: &mut W, value: &[u8]) -> io::Result<()>
1774+
where
1775+
W: ?Sized + io::Write,
1776+
{
1777+
tri!(self.begin_array(writer));
1778+
let mut first = true;
1779+
for byte in value {
1780+
tri!(self.begin_array_value(writer, first));
1781+
tri!(self.write_u8(writer, *byte));
1782+
tri!(self.end_array_value(writer));
1783+
first = false;
1784+
}
1785+
self.end_array(writer)
1786+
}
1787+
17731788
/// Called before every array. Writes a `[` to the specified
17741789
/// writer.
17751790
#[inline]

0 commit comments

Comments
 (0)