use crate::error::{Error, ErrorCode, Result}; use crate::map::Map; use crate::number::Number; use crate::value::{to_value, Value}; use alloc::borrow::ToOwned; use alloc::string::{String, ToString}; use alloc::vec::Vec; use core::fmt::Display; use core::result; use serde::ser::{Impossible, Serialize}; impl Serialize for Value { #[inline] fn serialize(&self, serializer: S) -> result::Result where S: ::serde::Serializer, { match self { Value::Null => serializer.serialize_unit(), Value::Bool(b) => serializer.serialize_bool(*b), Value::Number(n) => n.serialize(serializer), Value::String(s) => serializer.serialize_str(s), Value::Array(v) => v.serialize(serializer), #[cfg(any(feature = "std", feature = "alloc"))] Value::Object(m) => { use serde::ser::SerializeMap; let mut map = tri!(serializer.serialize_map(Some(m.len()))); for (k, v) in m { tri!(map.serialize_entry(k, v)); } map.end() } } } } /// Serializer whose output is a `Value`. /// /// This is the serializer that backs [`serde_json::to_value`][crate::to_value]. /// Unlike the main serde_json serializer which goes from some serializable /// value of type `T` to JSON text, this one goes from `T` to /// `serde_json::Value`. /// /// The `to_value` function is implementable as: /// /// ``` /// use serde::Serialize; /// use serde_json::{Error, Value}; /// /// pub fn to_value(input: T) -> Result /// where /// T: Serialize, /// { /// input.serialize(serde_json::value::Serializer) /// } /// ``` pub struct Serializer; impl serde::Serializer for Serializer { type Ok = Value; type Error = Error; type SerializeSeq = SerializeVec; type SerializeTuple = SerializeVec; type SerializeTupleStruct = SerializeVec; type SerializeTupleVariant = SerializeTupleVariant; type SerializeMap = SerializeMap; type SerializeStruct = SerializeMap; type SerializeStructVariant = SerializeStructVariant; #[inline] fn serialize_bool(self, value: bool) -> Result { Ok(Value::Bool(value)) } #[inline] fn serialize_i8(self, value: i8) -> Result { self.serialize_i64(value as i64) } #[inline] fn serialize_i16(self, value: i16) -> Result { self.serialize_i64(value as i64) } #[inline] fn serialize_i32(self, value: i32) -> Result { self.serialize_i64(value as i64) } fn serialize_i64(self, value: i64) -> Result { Ok(Value::Number(value.into())) } #[cfg(feature = "arbitrary_precision")] fn serialize_i128(self, value: i128) -> Result { Ok(Value::Number(value.into())) } #[inline] fn serialize_u8(self, value: u8) -> Result { self.serialize_u64(value as u64) } #[inline] fn serialize_u16(self, value: u16) -> Result { self.serialize_u64(value as u64) } #[inline] fn serialize_u32(self, value: u32) -> Result { self.serialize_u64(value as u64) } #[inline] fn serialize_u64(self, value: u64) -> Result { Ok(Value::Number(value.into())) } #[cfg(feature = "arbitrary_precision")] fn serialize_u128(self, value: u128) -> Result { Ok(Value::Number(value.into())) } #[inline] fn serialize_f32(self, value: f32) -> Result { self.serialize_f64(value as f64) } #[inline] fn serialize_f64(self, value: f64) -> Result { Ok(Number::from_f64(value).map_or(Value::Null, Value::Number)) } #[inline] fn serialize_char(self, value: char) -> Result { let mut s = String::new(); s.push(value); Ok(Value::String(s)) } #[inline] fn serialize_str(self, value: &str) -> Result { Ok(Value::String(value.to_owned())) } fn serialize_bytes(self, value: &[u8]) -> Result { let vec = value.iter().map(|&b| Value::Number(b.into())).collect(); Ok(Value::Array(vec)) } #[inline] fn serialize_unit(self) -> Result { Ok(Value::Null) } #[inline] fn serialize_unit_struct(self, _name: &'static str) -> Result { self.serialize_unit() } #[inline] fn serialize_unit_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, ) -> Result { self.serialize_str(variant) } #[inline] fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> Result where T: ?Sized + Serialize, { value.serialize(self) } fn serialize_newtype_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, value: &T, ) -> Result where T: ?Sized + Serialize, { let mut values = Map::new(); values.insert(String::from(variant), tri!(to_value(value))); Ok(Value::Object(values)) } #[inline] fn serialize_none(self) -> Result { self.serialize_unit() } #[inline] fn serialize_some(self, value: &T) -> Result where T: ?Sized + Serialize, { value.serialize(self) } fn serialize_seq(self, len: Option) -> Result { Ok(SerializeVec { vec: Vec::with_capacity(len.unwrap_or(0)), }) } fn serialize_tuple(self, len: usize) -> Result { self.serialize_seq(Some(len)) } fn serialize_tuple_struct( self, _name: &'static str, len: usize, ) -> Result { self.serialize_seq(Some(len)) } fn serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, len: usize, ) -> Result { Ok(SerializeTupleVariant { name: String::from(variant), vec: Vec::with_capacity(len), }) } fn serialize_map(self, _len: Option) -> Result { Ok(SerializeMap::Map { map: Map::new(), next_key: None, }) } fn serialize_struct(self, name: &'static str, len: usize) -> Result { match name { #[cfg(feature = "arbitrary_precision")] crate::number::TOKEN => Ok(SerializeMap::Number { out_value: None }), #[cfg(feature = "raw_value")] crate::raw::TOKEN => Ok(SerializeMap::RawValue { out_value: None }), _ => self.serialize_map(Some(len)), } } fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, _len: usize, ) -> Result { Ok(SerializeStructVariant { name: String::from(variant), map: Map::new(), }) } fn collect_str(self, value: &T) -> Result where T: ?Sized + Display, { Ok(Value::String(value.to_string())) } } pub struct SerializeVec { vec: Vec, } pub struct SerializeTupleVariant { name: String, vec: Vec, } pub enum SerializeMap { Map { map: Map, next_key: Option, }, #[cfg(feature = "arbitrary_precision")] Number { out_value: Option }, #[cfg(feature = "raw_value")] RawValue { out_value: Option }, } pub struct SerializeStructVariant { name: String, map: Map, } impl serde::ser::SerializeSeq for SerializeVec { type Ok = Value; type Error = Error; fn serialize_element(&mut self, value: &T) -> Result<()> where T: ?Sized + Serialize, { self.vec.push(tri!(to_value(value))); Ok(()) } fn end(self) -> Result { Ok(Value::Array(self.vec)) } } impl serde::ser::SerializeTuple for SerializeVec { type Ok = Value; type Error = Error; fn serialize_element(&mut self, value: &T) -> Result<()> where T: ?Sized + Serialize, { serde::ser::SerializeSeq::serialize_element(self, value) } fn end(self) -> Result { serde::ser::SerializeSeq::end(self) } } impl serde::ser::SerializeTupleStruct for SerializeVec { type Ok = Value; type Error = Error; fn serialize_field(&mut self, value: &T) -> Result<()> where T: ?Sized + Serialize, { serde::ser::SerializeSeq::serialize_element(self, value) } fn end(self) -> Result { serde::ser::SerializeSeq::end(self) } } impl serde::ser::SerializeTupleVariant for SerializeTupleVariant { type Ok = Value; type Error = Error; fn serialize_field(&mut self, value: &T) -> Result<()> where T: ?Sized + Serialize, { self.vec.push(tri!(to_value(value))); Ok(()) } fn end(self) -> Result { let mut object = Map::new(); object.insert(self.name, Value::Array(self.vec)); Ok(Value::Object(object)) } } impl serde::ser::SerializeMap for SerializeMap { type Ok = Value; type Error = Error; fn serialize_key(&mut self, key: &T) -> Result<()> where T: ?Sized + Serialize, { match self { SerializeMap::Map { next_key, .. } => { *next_key = Some(tri!(key.serialize(MapKeySerializer))); Ok(()) } #[cfg(feature = "arbitrary_precision")] SerializeMap::Number { .. } => unreachable!(), #[cfg(feature = "raw_value")] SerializeMap::RawValue { .. } => unreachable!(), } } fn serialize_value(&mut self, value: &T) -> Result<()> where T: ?Sized + Serialize, { match self { SerializeMap::Map { map, next_key } => { let key = next_key.take(); // Panic because this indicates a bug in the program rather than an // expected failure. let key = key.expect("serialize_value called before serialize_key"); map.insert(key, tri!(to_value(value))); Ok(()) } #[cfg(feature = "arbitrary_precision")] SerializeMap::Number { .. } => unreachable!(), #[cfg(feature = "raw_value")] SerializeMap::RawValue { .. } => unreachable!(), } } fn end(self) -> Result { match self { SerializeMap::Map { map, .. } => Ok(Value::Object(map)), #[cfg(feature = "arbitrary_precision")] SerializeMap::Number { .. } => unreachable!(), #[cfg(feature = "raw_value")] SerializeMap::RawValue { .. } => unreachable!(), } } } struct MapKeySerializer; fn key_must_be_a_string() -> Error { Error::syntax(ErrorCode::KeyMustBeAString, 0, 0) } impl serde::Serializer for MapKeySerializer { type Ok = String; type Error = Error; type SerializeSeq = Impossible; type SerializeTuple = Impossible; type SerializeTupleStruct = Impossible; type SerializeTupleVariant = Impossible; type SerializeMap = Impossible; type SerializeStruct = Impossible; type SerializeStructVariant = Impossible; #[inline] fn serialize_unit_variant( self, _name: &'static str, _variant_index: u32, variant: &'static str, ) -> Result { Ok(variant.to_owned()) } #[inline] fn serialize_newtype_struct(self, _name: &'static str, value: &T) -> Result where T: ?Sized + Serialize, { value.serialize(self) } fn serialize_bool(self, _value: bool) -> Result { Err(key_must_be_a_string()) } fn serialize_i8(self, value: i8) -> Result { Ok(value.to_string()) } fn serialize_i16(self, value: i16) -> Result { Ok(value.to_string()) } fn serialize_i32(self, value: i32) -> Result { Ok(value.to_string()) } fn serialize_i64(self, value: i64) -> Result { Ok(value.to_string()) } fn serialize_u8(self, value: u8) -> Result { Ok(value.to_string()) } fn serialize_u16(self, value: u16) -> Result { Ok(value.to_string()) } fn serialize_u32(self, value: u32) -> Result { Ok(value.to_string()) } fn serialize_u64(self, value: u64) -> Result { Ok(value.to_string()) } fn serialize_f32(self, _value: f32) -> Result { Err(key_must_be_a_string()) } fn serialize_f64(self, _value: f64) -> Result { Err(key_must_be_a_string()) } #[inline] fn serialize_char(self, value: char) -> Result { Ok({ let mut s = String::new(); s.push(value); s }) } #[inline] fn serialize_str(self, value: &str) -> Result { Ok(value.to_owned()) } fn serialize_bytes(self, _value: &[u8]) -> Result { Err(key_must_be_a_string()) } fn serialize_unit(self) -> Result { Err(key_must_be_a_string()) } fn serialize_unit_struct(self, _name: &'static str) -> Result { Err(key_must_be_a_string()) } fn serialize_newtype_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _value: &T, ) -> Result where T: ?Sized + Serialize, { Err(key_must_be_a_string()) } fn serialize_none(self) -> Result { Err(key_must_be_a_string()) } fn serialize_some(self, _value: &T) -> Result where T: ?Sized + Serialize, { Err(key_must_be_a_string()) } fn serialize_seq(self, _len: Option) -> Result { Err(key_must_be_a_string()) } fn serialize_tuple(self, _len: usize) -> Result { Err(key_must_be_a_string()) } fn serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result { Err(key_must_be_a_string()) } fn serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result { Err(key_must_be_a_string()) } fn serialize_map(self, _len: Option) -> Result { Err(key_must_be_a_string()) } fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { Err(key_must_be_a_string()) } fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result { Err(key_must_be_a_string()) } fn collect_str(self, value: &T) -> Result where T: ?Sized + Display, { Ok(value.to_string()) } } impl serde::ser::SerializeStruct for SerializeMap { type Ok = Value; type Error = Error; fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<()> where T: ?Sized + Serialize, { match self { SerializeMap::Map { .. } => serde::ser::SerializeMap::serialize_entry(self, key, value), #[cfg(feature = "arbitrary_precision")] SerializeMap::Number { out_value } => { if key == crate::number::TOKEN { *out_value = Some(value.serialize(NumberValueEmitter)?); Ok(()) } else { Err(invalid_number()) } } #[cfg(feature = "raw_value")] SerializeMap::RawValue { out_value } => { if key == crate::raw::TOKEN { *out_value = Some(value.serialize(RawValueEmitter)?); Ok(()) } else { Err(invalid_raw_value()) } } } } fn end(self) -> Result { match self { SerializeMap::Map { .. } => serde::ser::SerializeMap::end(self), #[cfg(feature = "arbitrary_precision")] SerializeMap::Number { out_value, .. } => { Ok(out_value.expect("number value was not emitted")) } #[cfg(feature = "raw_value")] SerializeMap::RawValue { out_value, .. } => { Ok(out_value.expect("raw value was not emitted")) } } } } impl serde::ser::SerializeStructVariant for SerializeStructVariant { type Ok = Value; type Error = Error; fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<()> where T: ?Sized + Serialize, { self.map.insert(String::from(key), tri!(to_value(value))); Ok(()) } fn end(self) -> Result { let mut object = Map::new(); object.insert(self.name, Value::Object(self.map)); Ok(Value::Object(object)) } } #[cfg(feature = "arbitrary_precision")] struct NumberValueEmitter; #[cfg(feature = "arbitrary_precision")] fn invalid_number() -> Error { Error::syntax(ErrorCode::InvalidNumber, 0, 0) } #[cfg(feature = "arbitrary_precision")] impl serde::ser::Serializer for NumberValueEmitter { type Ok = Value; type Error = Error; type SerializeSeq = Impossible; type SerializeTuple = Impossible; type SerializeTupleStruct = Impossible; type SerializeTupleVariant = Impossible; type SerializeMap = Impossible; type SerializeStruct = Impossible; type SerializeStructVariant = Impossible; fn serialize_bool(self, _v: bool) -> Result { Err(invalid_number()) } fn serialize_i8(self, _v: i8) -> Result { Err(invalid_number()) } fn serialize_i16(self, _v: i16) -> Result { Err(invalid_number()) } fn serialize_i32(self, _v: i32) -> Result { Err(invalid_number()) } fn serialize_i64(self, _v: i64) -> Result { Err(invalid_number()) } fn serialize_u8(self, _v: u8) -> Result { Err(invalid_number()) } fn serialize_u16(self, _v: u16) -> Result { Err(invalid_number()) } fn serialize_u32(self, _v: u32) -> Result { Err(invalid_number()) } fn serialize_u64(self, _v: u64) -> Result { Err(invalid_number()) } fn serialize_f32(self, _v: f32) -> Result { Err(invalid_number()) } fn serialize_f64(self, _v: f64) -> Result { Err(invalid_number()) } fn serialize_char(self, _v: char) -> Result { Err(invalid_number()) } fn serialize_str(self, value: &str) -> Result { let n = tri!(value.to_owned().parse()); Ok(Value::Number(n)) } fn serialize_bytes(self, _value: &[u8]) -> Result { Err(invalid_number()) } fn serialize_none(self) -> Result { Err(invalid_number()) } fn serialize_some(self, _value: &T) -> Result where T: ?Sized + Serialize, { Err(invalid_number()) } fn serialize_unit(self) -> Result { Err(invalid_number()) } fn serialize_unit_struct(self, _name: &'static str) -> Result { Err(invalid_number()) } fn serialize_unit_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, ) -> Result { Err(invalid_number()) } fn serialize_newtype_struct(self, _name: &'static str, _value: &T) -> Result where T: ?Sized + Serialize, { Err(invalid_number()) } fn serialize_newtype_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _value: &T, ) -> Result where T: ?Sized + Serialize, { Err(invalid_number()) } fn serialize_seq(self, _len: Option) -> Result { Err(invalid_number()) } fn serialize_tuple(self, _len: usize) -> Result { Err(invalid_number()) } fn serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result { Err(invalid_number()) } fn serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result { Err(invalid_number()) } fn serialize_map(self, _len: Option) -> Result { Err(invalid_number()) } fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { Err(invalid_number()) } fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result { Err(invalid_number()) } } #[cfg(feature = "raw_value")] struct RawValueEmitter; #[cfg(feature = "raw_value")] fn invalid_raw_value() -> Error { Error::syntax(ErrorCode::ExpectedSomeValue, 0, 0) } #[cfg(feature = "raw_value")] impl serde::ser::Serializer for RawValueEmitter { type Ok = Value; type Error = Error; type SerializeSeq = Impossible; type SerializeTuple = Impossible; type SerializeTupleStruct = Impossible; type SerializeTupleVariant = Impossible; type SerializeMap = Impossible; type SerializeStruct = Impossible; type SerializeStructVariant = Impossible; fn serialize_bool(self, _v: bool) -> Result { Err(invalid_raw_value()) } fn serialize_i8(self, _v: i8) -> Result { Err(invalid_raw_value()) } fn serialize_i16(self, _v: i16) -> Result { Err(invalid_raw_value()) } fn serialize_i32(self, _v: i32) -> Result { Err(invalid_raw_value()) } fn serialize_i64(self, _v: i64) -> Result { Err(invalid_raw_value()) } fn serialize_u8(self, _v: u8) -> Result { Err(invalid_raw_value()) } fn serialize_u16(self, _v: u16) -> Result { Err(invalid_raw_value()) } fn serialize_u32(self, _v: u32) -> Result { Err(invalid_raw_value()) } fn serialize_u64(self, _v: u64) -> Result { Err(invalid_raw_value()) } fn serialize_f32(self, _v: f32) -> Result { Err(invalid_raw_value()) } fn serialize_f64(self, _v: f64) -> Result { Err(invalid_raw_value()) } fn serialize_char(self, _v: char) -> Result { Err(invalid_raw_value()) } fn serialize_str(self, value: &str) -> Result { crate::from_str(value) } fn serialize_bytes(self, _value: &[u8]) -> Result { Err(invalid_raw_value()) } fn serialize_none(self) -> Result { Err(invalid_raw_value()) } fn serialize_some(self, _value: &T) -> Result where T: ?Sized + Serialize, { Err(invalid_raw_value()) } fn serialize_unit(self) -> Result { Err(invalid_raw_value()) } fn serialize_unit_struct(self, _name: &'static str) -> Result { Err(invalid_raw_value()) } fn serialize_unit_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, ) -> Result { Err(invalid_raw_value()) } fn serialize_newtype_struct(self, _name: &'static str, _value: &T) -> Result where T: ?Sized + Serialize, { Err(invalid_raw_value()) } fn serialize_newtype_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _value: &T, ) -> Result where T: ?Sized + Serialize, { Err(invalid_raw_value()) } fn serialize_seq(self, _len: Option) -> Result { Err(invalid_raw_value()) } fn serialize_tuple(self, _len: usize) -> Result { Err(invalid_raw_value()) } fn serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result { Err(invalid_raw_value()) } fn serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result { Err(invalid_raw_value()) } fn serialize_map(self, _len: Option) -> Result { Err(invalid_raw_value()) } fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { Err(invalid_raw_value()) } fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result { Err(invalid_raw_value()) } fn collect_str(self, value: &T) -> Result where T: ?Sized + Display, { self.serialize_str(&value.to_string()) } }