Skip to content

Commit

Permalink
Merge pull request toml-rs#467 from epage/value
Browse files Browse the repository at this point in the history
fix(ser)!: Clarify its `toml_edit`'s serializer is for `Value`
  • Loading branch information
epage authored Jan 19, 2023
2 parents 05e87e3 + 29b7576 commit 359f507
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 89 deletions.
4 changes: 2 additions & 2 deletions crates/toml_edit/src/easy/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
//!
//! This means that you can use Serde to deserialize/serialize the
//! [`Value`] type as well as the [`Datetime`][crate::Datetime] type in this crate. You can also
//! use the [`Deserializer`], [`Serializer`], or [`Value`] type itself to act as
//! use the [`Deserializer`], [`ValueSerializer`], or [`Value`] type itself to act as
//! a deserializer/serializer for arbitrary types.
//!
//! An example of deserializing with TOML is:
Expand Down Expand Up @@ -146,7 +146,7 @@ pub use crate::toml;
#[doc(no_inline)]
pub use de::{from_document, from_slice, from_str, Deserializer};
#[doc(no_inline)]
pub use ser::{to_document, to_string, to_string_pretty, to_vec, Serializer};
pub use ser::{to_document, to_string, to_string_pretty, to_vec, ValueSerializer};
pub use serde_spanned::Spanned;
#[doc(no_inline)]
pub use value::Value;
10 changes: 5 additions & 5 deletions crates/toml_edit/src/easy/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use std::str::FromStr;

use serde::de::IntoDeserializer as _;
use serde::Deserialize as _;
use serde::Serialize as _;

pub use crate::easy::datetime::*;
use crate::easy::map::Entry;
Expand Down Expand Up @@ -51,8 +52,7 @@ impl Value {
where
T: serde::ser::Serialize,
{
let item = super::ser::to_item(&value)?;
let value = item.into_value().expect("`to_item` only generates values");
let value = value.serialize(super::ValueSerializer::new())?;
let value = value.into_deserializer();
let target = Self::deserialize(value)?;
Ok(target)
Expand All @@ -71,8 +71,7 @@ impl Value {
where
T: serde::de::DeserializeOwned,
{
let item = super::ser::to_item(&self)?;
let value = item.into_value().expect("`to_item` only generates values");
let value = (&self).serialize(super::ValueSerializer::new())?;
let value = value.into_deserializer();
let target = T::deserialize(value)?;
Ok(target)
Expand Down Expand Up @@ -243,7 +242,8 @@ impl std::fmt::Display for Value {
| Value::Float(..)
| Value::Boolean(..)
| Value::Datetime(..)
| Value::Array(..) => crate::ser::to_item(self)
| Value::Array(..) => self
.serialize(super::ValueSerializer::new())
.map_err(|_| std::fmt::Error)?
.fmt(f),
Value::Table(_) => crate::ser::to_string_pretty(self)
Expand Down
28 changes: 13 additions & 15 deletions crates/toml_edit/src/ser/array.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use super::Error;

#[doc(hidden)]
pub struct SerializeItemArray {
pub struct SerializeValueArray {
values: Vec<crate::Item>,
}

impl SerializeItemArray {
impl SerializeValueArray {
pub(crate) fn new() -> Self {
Self { values: Vec::new() }
}
Expand All @@ -17,28 +17,26 @@ impl SerializeItemArray {
}
}

impl serde::ser::SerializeSeq for SerializeItemArray {
type Ok = crate::Item;
impl serde::ser::SerializeSeq for SerializeValueArray {
type Ok = crate::Value;
type Error = Error;

fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
where
T: serde::ser::Serialize,
{
let value = value.serialize(super::ItemSerializer {})?;
self.values.push(value);
let value = value.serialize(super::ValueSerializer {})?;
self.values.push(crate::Item::Value(value));
Ok(())
}

fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(crate::Item::Value(crate::Value::Array(
crate::Array::with_vec(self.values),
)))
Ok(crate::Value::Array(crate::Array::with_vec(self.values)))
}
}

impl serde::ser::SerializeTuple for SerializeItemArray {
type Ok = crate::Item;
impl serde::ser::SerializeTuple for SerializeValueArray {
type Ok = crate::Value;
type Error = Error;

fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
Expand All @@ -53,8 +51,8 @@ impl serde::ser::SerializeTuple for SerializeItemArray {
}
}

impl serde::ser::SerializeTupleVariant for SerializeItemArray {
type Ok = crate::Item;
impl serde::ser::SerializeTupleVariant for SerializeValueArray {
type Ok = crate::Value;
type Error = Error;

fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
Expand All @@ -69,8 +67,8 @@ impl serde::ser::SerializeTupleVariant for SerializeItemArray {
}
}

impl serde::ser::SerializeTupleStruct for SerializeItemArray {
type Ok = crate::Item;
impl serde::ser::SerializeTupleStruct for SerializeValueArray {
type Ok = crate::Value;
type Error = Error;

fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Error>
Expand Down
21 changes: 5 additions & 16 deletions crates/toml_edit/src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@
//! This module contains all the Serde support for serializing Rust structures into TOML.
mod array;
mod item;
mod key;
mod pretty;
mod table;
mod value;

pub(crate) use array::*;
pub(crate) use item::*;
pub(crate) use key::*;
pub(crate) use table::*;

Expand Down Expand Up @@ -145,7 +144,7 @@ where
/// Serialize the given data structure as a "pretty" String of TOML.
///
/// This is identical to `to_string` except the output string has a more
/// "pretty" output. See `Serializer::pretty` for more details.
/// "pretty" output. See `ValueSerializer::pretty` for more details.
pub fn to_string_pretty<T: ?Sized>(value: &T) -> Result<String, Error>
where
T: serde::ser::Serialize,
Expand All @@ -162,22 +161,12 @@ pub fn to_document<T: ?Sized>(value: &T) -> Result<crate::Document, Error>
where
T: serde::ser::Serialize,
{
let item = to_item(value)?;
let value = value.serialize(ValueSerializer::new())?;
let item = crate::Item::Value(value);
let root = item
.into_table()
.map_err(|_| ErrorKind::UnsupportedType(None))?;
Ok(root.into())
}

/// Serialize the given data structure into a TOML data structure
///
/// This would allow custom formatting to be applied, mixing with format preserving edits, etc.
pub fn to_item<T: ?Sized>(value: &T) -> Result<crate::Item, Error>
where
T: serde::ser::Serialize,
{
let item = value.serialize(Serializer::new())?;
Ok(item)
}

pub use item::ItemSerializer as Serializer;
pub use value::ValueSerializer;
64 changes: 31 additions & 33 deletions crates/toml_edit/src/ser/table.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use super::{Error, ErrorKind, KeySerializer};

#[doc(hidden)]
pub struct SerializeItemTable {
pub struct SerializeValueTable {
inner: SerializeKeyValuePairs,
}

impl SerializeItemTable {
impl SerializeValueTable {
pub(crate) fn new() -> Self {
Self {
inner: SerializeKeyValuePairs::new(),
Expand All @@ -19,8 +19,8 @@ impl SerializeItemTable {
}
}

impl serde::ser::SerializeMap for SerializeItemTable {
type Ok = crate::Item;
impl serde::ser::SerializeMap for SerializeValueTable {
type Ok = crate::Value;
type Error = Error;

fn serialize_key<T: ?Sized>(&mut self, input: &T) -> Result<(), Self::Error>
Expand All @@ -38,16 +38,14 @@ impl serde::ser::SerializeMap for SerializeItemTable {
}

fn end(self) -> Result<Self::Ok, Self::Error> {
self.inner.end().map(|items| {
crate::Item::Value(crate::Value::InlineTable(crate::InlineTable::with_pairs(
items,
)))
})
self.inner
.end()
.map(|items| crate::Value::InlineTable(crate::InlineTable::with_pairs(items)))
}
}

impl serde::ser::SerializeStruct for SerializeItemTable {
type Ok = crate::Item;
impl serde::ser::SerializeStruct for SerializeValueTable {
type Ok = crate::Value;
type Error = Error;

fn serialize_field<T: ?Sized>(
Expand All @@ -62,11 +60,9 @@ impl serde::ser::SerializeStruct for SerializeItemTable {
}

fn end(self) -> Result<Self::Ok, Self::Error> {
self.inner.end().map(|items| {
crate::Item::Value(crate::Value::InlineTable(crate::InlineTable::with_pairs(
items,
)))
})
self.inner
.end()
.map(|items| crate::Value::InlineTable(crate::InlineTable::with_pairs(items)))
}
}

Expand Down Expand Up @@ -107,20 +103,21 @@ impl serde::ser::SerializeMap for SerializeKeyValuePairs {
where
T: serde::ser::Serialize,
{
let res = value.serialize(super::ItemSerializer {});
let item = match res {
Ok(item) => item,
let res = value.serialize(super::ValueSerializer {});
match res {
Ok(item) => {
let key = self.key.take().unwrap();
let kv = crate::table::TableKeyValue::new(
crate::Key::new(&key),
crate::Item::Value(item),
);
self.items.insert(key, kv);
}
Err(e) => {
if e.kind != ErrorKind::UnsupportedNone {
return Err(e);
}
crate::Item::None
}
};
if !item.is_none() {
let key = self.key.take().unwrap();
let kv = crate::table::TableKeyValue::new(crate::Key::new(&key), item);
self.items.insert(key, kv);
}
Ok(())
}
Expand All @@ -142,20 +139,21 @@ impl serde::ser::SerializeStruct for SerializeKeyValuePairs {
where
T: serde::ser::Serialize,
{
let res = value.serialize(super::ItemSerializer {});
let item = match res {
Ok(item) => item,
let res = value.serialize(super::ValueSerializer {});
match res {
Ok(item) => {
let kv = crate::table::TableKeyValue::new(
crate::Key::new(key),
crate::Item::Value(item),
);
self.items.insert(crate::InternalString::from(key), kv);
}
Err(e) => {
if e.kind != ErrorKind::UnsupportedNone {
return Err(e);
}
crate::Item::None
}
};
if !item.is_none() {
let kv = crate::table::TableKeyValue::new(crate::Key::new(key), item);
self.items.insert(crate::InternalString::from(key), kv);
}
Ok(())
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,28 @@ use super::{Error, ErrorKind};
/// which is passed in when creating the serializer itself.
#[derive(Default)]
#[non_exhaustive]
pub struct ItemSerializer {}
pub struct ValueSerializer {}

impl ItemSerializer {
impl ValueSerializer {
/// Creates a new serializer generate a TOML document.
pub fn new() -> Self {
Self {}
}
}

impl serde::ser::Serializer for ItemSerializer {
type Ok = crate::Item;
impl serde::ser::Serializer for ValueSerializer {
type Ok = crate::Value;
type Error = Error;
type SerializeSeq = super::SerializeItemArray;
type SerializeTuple = super::SerializeItemArray;
type SerializeTupleStruct = super::SerializeItemArray;
type SerializeTupleVariant = super::SerializeItemArray;
type SerializeMap = super::SerializeItemTable;
type SerializeStruct = super::SerializeItemTable;
type SerializeSeq = super::SerializeValueArray;
type SerializeTuple = super::SerializeValueArray;
type SerializeTupleStruct = super::SerializeValueArray;
type SerializeTupleVariant = super::SerializeValueArray;
type SerializeMap = super::SerializeValueTable;
type SerializeStruct = super::SerializeValueTable;
type SerializeStructVariant = serde::ser::Impossible<Self::Ok, Self::Error>;

fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
Ok(crate::Item::Value(v.into()))
Ok(v.into())
}

fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
Expand All @@ -48,7 +48,7 @@ impl serde::ser::Serializer for ItemSerializer {
}

fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
Ok(crate::Item::Value(v.into()))
Ok(v.into())
}

fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
Expand All @@ -72,7 +72,7 @@ impl serde::ser::Serializer for ItemSerializer {
}

fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
Ok(crate::Item::Value(v.into()))
Ok(v.into())
}

fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
Expand All @@ -81,7 +81,7 @@ impl serde::ser::Serializer for ItemSerializer {
}

fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
Ok(crate::Item::Value(v.into()))
Ok(v.into())
}

fn serialize_bytes(self, value: &[u8]) -> Result<Self::Ok, Self::Error> {
Expand Down Expand Up @@ -143,8 +143,8 @@ impl serde::ser::Serializer for ItemSerializer {

fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
let serializer = match len {
Some(len) => super::SerializeItemArray::with_capacity(len),
None => super::SerializeItemArray::new(),
Some(len) => super::SerializeValueArray::with_capacity(len),
None => super::SerializeValueArray::new(),
};
Ok(serializer)
}
Expand Down Expand Up @@ -173,8 +173,8 @@ impl serde::ser::Serializer for ItemSerializer {

fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
let serializer = match len {
Some(len) => super::SerializeItemTable::with_capacity(len),
None => super::SerializeItemTable::new(),
Some(len) => super::SerializeValueTable::with_capacity(len),
None => super::SerializeValueTable::new(),
};
Ok(serializer)
}
Expand Down

0 comments on commit 359f507

Please sign in to comment.