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

Add provisional metadata ser in named field pos #544

Merged
merged 20 commits into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from 14 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 CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Breaking: Enforce that ron always writes valid UTF-8 ([#488](https://github.com/ron-rs/ron/pull/488))
- Add convenient `Value::from` impls ([#498](https://github.com/ron-rs/ron/pull/498))
- Add new extension `explicit_struct_names` which requires that struct names are included during deserialization ([#522](https://github.com/ron-rs/ron/pull/522))
- Add new metadata serialization support in named field position via `PrettyConfig` ([#544](https://github.com/ron-rs/ron/pull/544))
juntyr marked this conversation as resolved.
Show resolved Hide resolved
- Breaking: Change `PrettyConfig` so that `new_line`, `indentor` and `separator` are all `Cow<'static, str>` instead of `String` ([#546](https://github.com/ron-rs/ron/pull/546))

### Format Changes
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub mod de;
pub mod ser;

pub mod error;
pub mod meta;
pub mod value;

pub mod extensions;
Expand Down
274 changes: 274 additions & 0 deletions src/meta.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,274 @@
use std::collections::HashMap;

use serde_derive::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct Meta {
voidentente marked this conversation as resolved.
Show resolved Hide resolved
fields: Fields,
}

impl Meta {
/// Get a reference to the named field position metadata.
#[must_use]
pub fn fields(&self) -> &Fields {
&self.fields
}

/// Get a mutable reference to the named field position metadata.
pub fn fields_mut(&mut self) -> &mut Fields {
&mut self.fields
}
}

/// The metadata and inner [Fields] of a field.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct Field {
meta: String,
fields: Option<Fields>,
}

impl Field {
/// Create a new empty field metadata.
#[must_use]
pub const fn empty() -> Self {
Self {
meta: String::new(),
fields: None,
}
}

/// Create a new field metadata.
pub fn new(meta: impl Into<String>, fields: Option<Fields>) -> Self {
Self {
meta: meta.into(),
fields,
}
}

/// Get the metadata of this field.
#[must_use]
pub fn meta(&self) -> &str {
voidentente marked this conversation as resolved.
Show resolved Hide resolved
&self.meta
}

/// Set the metadata of this field.
///
/// ```
/// # use ron::meta::Field;
///
/// let mut field = Field::empty();
///
/// assert_eq!(field.meta(), "");
///
/// field.with_meta("some meta");
///
/// assert_eq!(field.meta(), "some meta");
/// ```
pub fn with_meta(&mut self, meta: impl Into<String>) -> &mut Self {
self.meta = meta.into();
self
}

/// Return whether the Field has metadata.
///
/// ```
/// # use ron::meta::Field;
///
/// let mut field = Field::empty();
///
/// assert!(!field.has_meta());
///
/// field.with_meta("some");
///
/// assert!(field.has_meta());
/// ```
#[must_use]
pub fn has_meta(&self) -> bool {
!self.meta.is_empty()
}

/// Get a reference to the inner fields of this field, if it has any.
#[must_use]
pub fn fields(&self) -> Option<&Fields> {
self.fields.as_ref()
}

/// Get a mutable reference to the inner fields of this field, if it has any.
pub fn fields_mut(&mut self) -> Option<&mut Fields> {
self.fields.as_mut()
}

/// Return whether this field has inner fields.
///
/// ```
/// # use ron::meta::{Field, Fields};
///
/// let mut field = Field::empty();
///
/// assert!(!field.has_fields());
///
/// field.with_fields(Some(Fields::default()));
///
/// assert!(field.has_fields());
/// ```
#[must_use]
pub fn has_fields(&self) -> bool {
self.fields.is_some()
}

/// Set the inner fields of this field.
///
/// ```
/// # use ron::meta::{Field, Fields};
///
/// let mut field = Field::empty();
///
/// assert!(!field.has_fields());
///
/// field.with_fields(Some(Fields::default()));
///
/// assert!(field.has_fields());
///
/// field.with_fields(None);
///
/// assert!(!field.has_fields());
/// ```
pub fn with_fields(&mut self, fields: Option<Fields>) -> &mut Self {
self.fields = fields;
self
}

/// Ergonomic shortcut for building some inner fields.
///
/// ```
/// # use ron::meta::Field;
///
/// let mut field = Field::empty();
///
/// field.build_fields(|fields| {
/// fields.field("inner field");
/// });
///
/// assert_eq!(field.fields().map(|fields| fields.contains("inner field")), Some(true));
/// ```
pub fn build_fields(&mut self, builder: impl FnOnce(&mut Fields)) -> &mut Self {
let mut fields = Fields::default();
builder(&mut fields);
self.with_fields(Some(fields));
self
}
}

/// Mapping of names to [Field]s.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct Fields {
fields: HashMap<String, Field>,
}

impl Fields {
/// Return a new, empty metadata field map.
#[must_use]
pub fn new() -> Self {
Self::default()
}

/// Return whether this field map contains no fields.
///
/// ```
/// # use ron::meta::{Fields, Field};
///
/// let mut fields = Fields::default();
///
/// assert!(fields.is_empty());
///
/// fields.insert("", Field::empty());
///
/// assert!(!fields.is_empty());
/// ```
#[must_use]
pub fn is_empty(&self) -> bool {
self.fields.is_empty()
}

/// Return whether this field map contains a field with the given name.
///
/// ```
/// # use ron::meta::{Fields, Field};
///
/// let fields: Fields = [("a thing", Field::empty())].into_iter().collect();
///
/// assert!(fields.contains("a thing"));
/// assert!(!fields.contains("not a thing"));
/// ```
pub fn contains(&self, name: impl AsRef<str>) -> bool {
self.fields.contains_key(name.as_ref())
}

/// Get a reference to the field with the provided `name`, if it exists.
///
/// ```
/// # use ron::meta::{Fields, Field};
///
/// let fields: Fields = [("a thing", Field::empty())].into_iter().collect();
///
/// assert!(fields.get("a thing").is_some());
/// assert!(fields.get("not a thing").is_none());
/// ```
pub fn get(&self, name: impl AsRef<str>) -> Option<&Field> {
self.fields.get(name.as_ref())
}

/// Get a mutable reference to the field with the provided `name`, if it exists.
///
/// ```
/// # use ron::meta::{Fields, Field};
///
/// let mut fields: Fields = [("a thing", Field::empty())].into_iter().collect();
///
/// assert!(fields.get_mut("a thing").is_some());
/// assert!(fields.get_mut("not a thing").is_none());
/// ```
pub fn get_mut(&mut self, name: impl AsRef<str>) -> Option<&mut Field> {
self.fields.get_mut(name.as_ref())
}

/// Insert a field with the given name into the map.
///
/// ```
/// # use ron::meta::{Fields, Field};
///
/// let mut fields = Fields::default();
///
/// assert!(fields.insert("field", Field::empty()).is_none());
/// assert!(fields.insert("field", Field::empty()).is_some());
/// ```
pub fn insert(&mut self, name: impl Into<String>, field: Field) -> Option<Field> {
self.fields.insert(name.into(), field)
}

/// Get a mutable reference to the field with the provided `name`,
/// inserting an empty [`Field`] if it didn't exist.
///
/// ```
/// # use ron::meta::Fields;
///
/// let mut fields = Fields::default();
///
/// assert!(!fields.contains("thing"));
///
/// fields.field("thing");
///
/// assert!(fields.contains("thing"));
/// ```
pub fn field(&mut self, name: impl Into<String>) -> &mut Field {
self.fields.entry(name.into()).or_insert_with(Field::empty)
}
}

impl<K: Into<String>> FromIterator<(K, Field)> for Fields {
fn from_iter<T: IntoIterator<Item = (K, Field)>>(iter: T) -> Self {
Self {
fields: iter.into_iter().map(|(k, v)| (k.into(), v)).collect(),
}
}
}
35 changes: 35 additions & 0 deletions src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use unicode_ident::is_xid_continue;
use crate::{
error::{Error, Result},
extensions::Extensions,
meta::{Field, Meta},
options::Options,
parse::{is_ident_first_char, is_ident_raw_char, is_whitespace_char, LargeSInt, LargeUInt},
};
Expand Down Expand Up @@ -109,6 +110,8 @@ pub struct PrettyConfig {
pub compact_maps: bool,
/// Enable explicit number type suffixes like `1u16`
pub number_suffixes: bool,
/// Additional metadata to serialize
juntyr marked this conversation as resolved.
Show resolved Hide resolved
pub meta: Meta,
}

impl PrettyConfig {
Expand Down Expand Up @@ -359,6 +362,7 @@ impl Default for PrettyConfig {
compact_structs: false,
compact_maps: false,
number_suffixes: false,
meta: Meta::default(),
}
}
}
Expand All @@ -376,6 +380,7 @@ pub struct Serializer<W: fmt::Write> {
recursion_limit: Option<usize>,
// Tracks the number of opened implicit `Some`s, set to 0 on backtracking
implicit_some_depth: usize,
field_memory: Vec<&'static str>,
}

impl<W: fmt::Write> Serializer<W> {
Expand Down Expand Up @@ -428,6 +433,7 @@ impl<W: fmt::Write> Serializer<W> {
newtype_variant: false,
recursion_limit: options.recursion_limit,
implicit_some_depth: 0,
field_memory: Vec::new(),
})
}

Expand Down Expand Up @@ -1313,6 +1319,8 @@ impl<'a, W: fmt::Write> ser::SerializeStruct for Compound<'a, W> {
where
T: ?Sized + Serialize,
{
self.ser.field_memory.push(key);

if let State::First = self.state {
self.state = State::Rest;
} else {
Expand All @@ -1329,6 +1337,30 @@ impl<'a, W: fmt::Write> ser::SerializeStruct for Compound<'a, W> {

if !self.ser.compact_structs() {
self.ser.indent()?;

if let Some((ref config, _)) = self.ser.pretty {
let mut iter = self.ser.field_memory.iter();

let init = iter.next().and_then(|name| config.meta.fields().get(name));
let field = iter
voidentente marked this conversation as resolved.
Show resolved Hide resolved
.try_fold(init, |field, name| {
field.and_then(Field::fields).map(|fields| fields.get(name))
})
.flatten();

if let Some(field) = field {
let lines: Vec<_> = field
.meta()
.lines()
.map(|line| format!("/// {line}\n"))
.collect();

for line in lines {
self.ser.output.write_str(&line)?;
self.ser.indent()?;
}
}
}
}

self.ser.write_identifier(key)?;
Expand All @@ -1340,6 +1372,8 @@ impl<'a, W: fmt::Write> ser::SerializeStruct for Compound<'a, W> {

guard_recursion! { self.ser => value.serialize(&mut *self.ser)? };

self.ser.field_memory.pop();

Ok(())
}

Expand All @@ -1360,6 +1394,7 @@ impl<'a, W: fmt::Write> ser::SerializeStruct for Compound<'a, W> {
if !self.newtype_variant {
self.ser.output.write_char(')')?;
}

Ok(())
}
}
Expand Down
Loading