Skip to content

Commit 62ee109

Browse files
robin-nitrokeysosthene-nitrokey
authored andcommitted
Handle bytes identifier as UTF-8 strings
Previously, we visited either strings or bytes so that the visitor had to handle both cases. With this change, we always visit strings so that the bytes visitor function can be optimized out. This significantly reduces binary size.
1 parent 327f723 commit 62ee109

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

src/de.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -804,9 +804,16 @@ impl<'de, 'a> de::Deserializer<'de> for &'a mut Deserializer<'de> {
804804
{
805805
let major = self.peek_major()?;
806806
match major {
807-
MAJOR_STR => self.deserialize_str(visitor),
807+
MAJOR_BYTES | MAJOR_STR => {
808+
// Rust identifiers are always valid UTF-8 so we can assume that bytes are
809+
// UTF-8-encoded strings. This has the benefit that we only need a mapping from
810+
// strings to fields (and the mapping from bytes to fields can be optimized out).
811+
let length = self.raw_deserialize_u32(major)? as usize;
812+
let bytes: &'de [u8] = self.try_take_n(length)?;
813+
let string_slice = core::str::from_utf8(bytes).map_err(|_| Error::DeserializeBadUtf8)?;
814+
visitor.visit_borrowed_str(string_slice)
815+
}
808816
MAJOR_POSINT => self.deserialize_u64(visitor),
809-
MAJOR_BYTES => self.deserialize_bytes(visitor),
810817
_ => Err(Error::DeserializeBadMajor),
811818
}
812819
}

0 commit comments

Comments
 (0)