Skip to content
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

Correctly serialize non-string keys #41

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ keywords = ["json5", "parse", "parser", "serde", "json"]
edition = "2018"

[dependencies]
itoa = "1.0.1"
pest = "2.0"
pest_derive = "2.0"
serde = "1.0"
Expand Down
181 changes: 180 additions & 1 deletion src/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ impl<'a> ser::SerializeMap for &'a mut Serializer {
if !self.output.ends_with('{') {
self.output += ",";
}
key.serialize(&mut **self)
key.serialize(KeySerializer { base: &mut **self })
}

fn serialize_value<T>(&mut self, value: &T) -> Result<()>
Expand Down Expand Up @@ -372,3 +372,182 @@ fn escape(v: &str) -> String {
})
.collect()
}

struct KeySerializer<'a> {
base: &'a mut Serializer,
}

impl KeySerializer<'_> {
fn serialize_integer<I: itoa::Integer>(self, integer: I) -> Result<()> {
self.base.output.push('"');
self.base
.output
.push_str(itoa::Buffer::new().format(integer));
self.base.output.push('"');
Ok(())
}
}

fn key_not_string() -> Error {
ser::Error::custom("key must be a string")
}

impl ser::Serializer for KeySerializer<'_> {
type Ok = ();
type Error = Error;

fn serialize_str(self, v: &str) -> Result<()> {
self.base.serialize_str(v)
}

fn serialize_unit_variant(
self,
_name: &'static str,
_variant_index: u32,
variant: &'static str,
) -> Result<()> {
self.serialize_str(variant)
}

fn serialize_newtype_struct<T: Serialize + ?Sized>(
self,
_name: &'static str,
value: &T,
) -> Result<()> {
value.serialize(self)
}

type SerializeSeq = ser::Impossible<(), Error>;
type SerializeTuple = ser::Impossible<(), Error>;
type SerializeTupleStruct = ser::Impossible<(), Error>;
type SerializeTupleVariant = ser::Impossible<(), Error>;
type SerializeMap = ser::Impossible<(), Error>;
type SerializeStruct = ser::Impossible<(), Error>;
type SerializeStructVariant = ser::Impossible<(), Error>;

fn serialize_bool(self, _v: bool) -> Result<()> {
Err(key_not_string())
}

fn serialize_i8(self, v: i8) -> Result<()> {
self.serialize_integer(v)
}

fn serialize_i16(self, v: i16) -> Result<()> {
self.serialize_integer(v)
}

fn serialize_i32(self, v: i32) -> Result<()> {
self.serialize_integer(v)
}

fn serialize_i64(self, v: i64) -> Result<()> {
self.serialize_integer(v)
}

fn serialize_u8(self, v: u8) -> Result<()> {
self.serialize_integer(v)
}

fn serialize_u16(self, v: u16) -> Result<()> {
self.serialize_integer(v)
}

fn serialize_u32(self, v: u32) -> Result<()> {
self.serialize_integer(v)
}

fn serialize_u64(self, v: u64) -> Result<()> {
self.serialize_integer(v)
}

fn serialize_f32(self, _v: f32) -> Result<()> {
Err(key_not_string())
}

fn serialize_f64(self, _v: f64) -> Result<()> {
Err(key_not_string())
}

fn serialize_char(self, v: char) -> Result<()> {
self.serialize_str(v.encode_utf8(&mut [0; 4]))
}

fn serialize_bytes(self, _v: &[u8]) -> Result<()> {
Err(key_not_string())
}

fn serialize_unit(self) -> Result<()> {
Err(key_not_string())
}

fn serialize_unit_struct(self, _name: &'static str) -> Result<()> {
Err(key_not_string())
}

fn serialize_newtype_variant<T: ?Sized + Serialize>(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_value: &T,
) -> Result<()> {
Err(key_not_string())
}

fn serialize_none(self) -> Result<()> {
Err(key_not_string())
}

fn serialize_some<T: ?Sized + Serialize>(self, _value: &T) -> Result<()> {
Err(key_not_string())
}

fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> {
Err(key_not_string())
}

fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> {
Err(key_not_string())
}

fn serialize_tuple_struct(
self,
_name: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleStruct> {
Err(key_not_string())
}

fn serialize_tuple_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeTupleVariant> {
Err(key_not_string())
}

fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
Err(key_not_string())
}

fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
Err(key_not_string())
}

fn serialize_struct_variant(
self,
_name: &'static str,
_variant_index: u32,
_variant: &'static str,
_len: usize,
) -> Result<Self::SerializeStructVariant> {
Err(key_not_string())
}

fn collect_str<T: ?Sized + std::fmt::Display>(self, value: &T) -> Result<()> {
self.base.collect_str(value)
}
}
17 changes: 17 additions & 0 deletions tests/ser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,23 @@ fn serializes_map() {
serializes_to(outer, "{\"a\":{\"b\":true}}");
}

#[test]
fn serializes_map_integer_keys() {
let mut map = HashMap::new();
map.insert(5, ());
serializes_to(map, "{\"5\":null}");
}

#[test]
fn non_string_keys() {
let mut map = HashMap::new();
map.insert((), true);
assert_eq!(
json5::to_string(&map).unwrap_err().to_string(),
"key must be a string"
);
}

#[test]
fn serializes_struct() {
#[derive(Serialize, PartialEq, Debug)]
Expand Down