Skip to content

Commit

Permalink
Merge pull request ron-rs#349 from MomoLangenstein/compact-arrays
Browse files Browse the repository at this point in the history
Add compact arrays (ron-rs#299) and pretty inline separators
  • Loading branch information
torkleyy committed Jun 6, 2022
1 parent d44242b commit edddc94
Show file tree
Hide file tree
Showing 5 changed files with 144 additions and 30 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Fix issue [#338](https://github.com/ron-rs/ron/issues/338) value map roundtrip ([#341](https://github.com/ron-rs/ron/pull/341))
- Fix issue [#289](https://github.com/ron-rs/ron/issues/289) enumerate_arrays comments ([#344](https://github.com/ron-rs/ron/pull/344))
- Report struct name in expected struct error ([#342](https://github.com/ron-rs/ron/pull/342))
- Add `Options` builder to configure the RON serde roundtrip ([#343](https://github.com/ron-rs/ron/pull/343))
- Add `compact_arrays` ([#299](https://github.com/ron-rs/ron/pull/299)) and `separator` options to `PrettyConfig` ([#349](https://github.com/ron-rs/ron/pull/349))

## [0.7.0] - 2021-10-22

Expand Down
102 changes: 78 additions & 24 deletions src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ pub struct PrettyConfig {
/// Indentation string
#[serde(default = "default_indentor")]
pub indentor: String,
/// Separator string
pub separator: String,
// Whether to emit struct names
pub struct_names: bool,
/// Separate tuple members with indentation
#[serde(default = "default_separate_tuple_members")]
pub separate_tuple_members: bool,
Expand All @@ -97,6 +101,8 @@ pub struct PrettyConfig {
/// Enable extensions. Only configures 'implicit_some'
/// and 'unwrap_newtypes' for now.
pub extensions: Extensions,
/// Enable compact arrays
pub compact_arrays: bool,
/// Private field to ensure adding a field is non-breaking.
#[serde(skip)]
_future_proof: (),
Expand Down Expand Up @@ -138,6 +144,24 @@ impl PrettyConfig {
self
}

/// Configures the string sequence used to separate items inline.
///
/// Default: 1 space
pub fn separator(mut self, separator: String) -> Self {
self.separator = separator;

self
}

/// Configures whether to emit struct names.
///
/// Default: `false`
pub fn struct_names(mut self, struct_names: bool) -> Self {
self.struct_names = struct_names;

self
}

/// Configures whether tuples are single- or multi-line.
/// If set to `true`, tuples will have their fields indented and in new
/// lines. If set to `false`, tuples will be serialized without any
Expand Down Expand Up @@ -171,6 +195,23 @@ impl PrettyConfig {
self
}

/// Configures whether every array should be a single line (true) or a multi line one (false)
/// When false, `["a","b"]` (as well as any array) will serialize to
/// `
/// [
/// "a",
/// "b",
/// ]
/// `
/// When true, `["a","b"]` (as well as any array) will serialize to `["a","b"]`
///
/// Default: `false`
pub fn compact_arrays(mut self, compact_arrays: bool) -> Self {
self.compact_arrays = compact_arrays;

self
}

/// Configures extensions
///
/// Default: Extensions::empty()
Expand Down Expand Up @@ -220,6 +261,9 @@ impl Default for PrettyConfig {
enumerate_arrays: default_enumerate_arrays(),
extensions: Extensions::default(),
decimal_floats: default_decimal_floats(),
separator: String::from(" "),
struct_names: false,
compact_arrays: false,
_future_proof: (),
}
}
Expand Down Expand Up @@ -267,13 +311,6 @@ impl<W: io::Write> Serializer<W> {
})
}

fn is_pretty(&self) -> bool {
match self.pretty {
Some((ref config, ref pretty)) => pretty.indent <= config.depth_limit,
None => false,
}
}

fn separate_tuple_members(&self) -> bool {
self.pretty
.as_ref()
Expand All @@ -286,6 +323,12 @@ impl<W: io::Write> Serializer<W> {
.map_or(false, |&(ref config, _)| config.decimal_floats)
}

fn compact_arrays(&self) -> bool {
self.pretty
.as_ref()
.map_or(false, |&(ref config, _)| config.compact_arrays)
}

fn extensions(&self) -> Extensions {
self.pretty
.as_ref()
Expand Down Expand Up @@ -417,6 +460,7 @@ impl<'a, W: io::Write> ser::Serializer for &'a mut Serializer<W> {

fn serialize_f32(self, v: f32) -> Result<()> {
write!(self.output, "{}", v)?;
// TODO: use f32::EPSILON when minimum supported rust version is 1.43
#[allow(clippy::excessive_precision)]
pub const EPSILON: f32 = 1.192_092_90e-07_f32;
if self.decimal_floats() && (v - v.floor()).abs() < EPSILON {
Expand Down Expand Up @@ -544,7 +588,9 @@ impl<'a, W: io::Write> ser::Serializer for &'a mut Serializer<W> {
self.is_empty = Some(len == 0);
}

self.start_indent()?;
if !self.compact_arrays() {
self.start_indent()?;
}

if let Some((_, ref mut pretty)) = self.pretty {
pretty.sequence_index.push(0);
Expand Down Expand Up @@ -677,12 +723,17 @@ impl<'a, W: io::Write> ser::SerializeSeq for Compound<'a, W> {
} else {
self.ser.output.write_all(b",")?;
if let Some((ref config, ref mut pretty)) = self.ser.pretty {
if pretty.indent <= config.depth_limit {
if pretty.indent <= config.depth_limit && !config.compact_arrays {
self.ser.output.write_all(config.new_line.as_bytes())?;
} else {
self.ser.output.write_all(config.separator.as_bytes())?;
}
}
}
self.ser.indent()?;

if !self.ser.compact_arrays() {
self.ser.indent()?;
}

if let Some((ref mut config, ref mut pretty)) = self.ser.pretty {
if pretty.indent <= config.depth_limit && config.enumerate_arrays {
Expand All @@ -700,13 +751,16 @@ impl<'a, W: io::Write> ser::SerializeSeq for Compound<'a, W> {
fn end(self) -> Result<()> {
if let State::Rest = self.state {
if let Some((ref config, ref mut pretty)) = self.ser.pretty {
if pretty.indent <= config.depth_limit {
if pretty.indent <= config.depth_limit && !config.compact_arrays {
self.ser.output.write_all(b",")?;
self.ser.output.write_all(config.new_line.as_bytes())?;
}
}
}
self.ser.end_indent()?;

if !self.ser.compact_arrays() {
self.ser.end_indent()?;
}

if let Some((_, ref mut pretty)) = self.ser.pretty {
pretty.sequence_index.pop();
Expand All @@ -730,14 +784,10 @@ impl<'a, W: io::Write> ser::SerializeTuple for Compound<'a, W> {
} else {
self.ser.output.write_all(b",")?;
if let Some((ref config, ref pretty)) = self.ser.pretty {
if pretty.indent <= config.depth_limit {
self.ser
.output
.write_all(if self.ser.separate_tuple_members() {
config.new_line.as_bytes()
} else {
b" "
})?;
if pretty.indent <= config.depth_limit && self.ser.separate_tuple_members() {
self.ser.output.write_all(config.new_line.as_bytes())?;
} else {
self.ser.output.write_all(config.separator.as_bytes())?;
}
}
}
Expand Down Expand Up @@ -819,6 +869,8 @@ impl<'a, W: io::Write> ser::SerializeMap for Compound<'a, W> {
if let Some((ref config, ref pretty)) = self.ser.pretty {
if pretty.indent <= config.depth_limit {
self.ser.output.write_all(config.new_line.as_bytes())?;
} else {
self.ser.output.write_all(config.separator.as_bytes())?;
}
}
}
Expand All @@ -832,8 +884,8 @@ impl<'a, W: io::Write> ser::SerializeMap for Compound<'a, W> {
{
self.ser.output.write_all(b":")?;

if self.ser.is_pretty() {
self.ser.output.write_all(b" ")?;
if let Some((ref config, _)) = self.ser.pretty {
self.ser.output.write_all(config.separator.as_bytes())?;
}

value.serialize(&mut *self.ser)?;
Expand Down Expand Up @@ -872,15 +924,17 @@ impl<'a, W: io::Write> ser::SerializeStruct for Compound<'a, W> {
if let Some((ref config, ref pretty)) = self.ser.pretty {
if pretty.indent <= config.depth_limit {
self.ser.output.write_all(config.new_line.as_bytes())?;
} else {
self.ser.output.write_all(config.separator.as_bytes())?;
}
}
}
self.ser.indent()?;
self.ser.write_identifier(key)?;
self.ser.output.write_all(b":")?;

if self.ser.is_pretty() {
self.ser.output.write_all(b" ")?;
if let Some((ref config, _)) = self.ser.pretty {
self.ser.output.write_all(config.separator.as_bytes())?;
}

value.serialize(&mut *self.ser)?;
Expand Down
38 changes: 38 additions & 0 deletions tests/240_array_pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,42 @@ fn small_array() {
(),
]"
);
assert_eq!(
to_string_pretty(
&arr,
PrettyConfig::new()
.new_line("\n".to_string())
.compact_arrays(true)
)
.unwrap(),
"[(), (), ()]"
);
assert_eq!(
to_string_pretty(
&arr,
PrettyConfig::new()
.new_line("\n".to_string())
.compact_arrays(true)
.separator("".to_string())
)
.unwrap(),
"[(),(),()]"
);
assert_eq!(
to_string_pretty(
&vec![(1, 2), (3, 4)],
PrettyConfig::new()
.new_line("\n".to_string())
.separate_tuple_members(true)
.compact_arrays(true)
)
.unwrap(),
"[(
1,
2,
), (
3,
4,
)]"
);
}
20 changes: 20 additions & 0 deletions tests/289_enumerate_arrays.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ const EXPTECTED: &str = "[
/*[4]*/ None,
]";

const EXPTECTED_COMPACT: &str = "[/*[0]*/ None, /*[1]*/ Some([]), /*[2]*/ Some([/*[0]*/ 42]), \
/*[3]*/ Some([/*[0]*/ 4, /*[1]*/ 2]), /*[4]*/ None]";

#[test]
fn enumerate_arrays() {
let v: Vec<Option<Vec<u8>>> = vec![None, Some(vec![]), Some(vec![42]), Some(vec![4, 2]), None];
Expand All @@ -25,3 +28,20 @@ fn enumerate_arrays() {

assert_eq!(v, de)
}

#[test]
fn enumerate_compact_arrays() {
let v: Vec<Option<Vec<u8>>> = vec![None, Some(vec![]), Some(vec![42]), Some(vec![4, 2]), None];

let pretty = ron::ser::PrettyConfig::new()
.enumerate_arrays(true)
.compact_arrays(true);

let ser = ron::ser::to_string_pretty(&v, pretty).unwrap();

assert_eq!(ser, EXPTECTED_COMPACT);

let de: Vec<Option<Vec<u8>>> = ron::from_str(&ser).unwrap();

assert_eq!(v, de)
}
12 changes: 6 additions & 6 deletions tests/depth_limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ struct Nested {
}

const EXPECTED: &str = "(
float: (2.18,-1.1),
tuple: ((),false),
map: {8:'1'},
nested: (a:\"a\",b:'b'),
var: A(255,\"\"),
array: [(),(),()],
float: (2.18, -1.1),
tuple: ((), false),
map: {8: '1'},
nested: (a: \"a\", b: 'b'),
var: A(255, \"\"),
array: [(), (), ()],
)";

#[test]
Expand Down

0 comments on commit edddc94

Please sign in to comment.