Skip to content

Commit

Permalink
Merge pull request #349 from MomoLangenstein/compact-arrays
Browse files Browse the repository at this point in the history
Add compact arrays (#299) and pretty inline separators
  • Loading branch information
torkleyy authored Dec 18, 2021
2 parents 521e639 + 58ad74d commit 61a8b5d
Show file tree
Hide file tree
Showing 5 changed files with 131 additions and 30 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- 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
90 changes: 66 additions & 24 deletions src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ pub struct PrettyConfig {
pub new_line: String,
/// Indentation string
pub indentor: String,
/// Separator string
pub separator: String,
// Whether to emit struct names
pub struct_names: bool,
/// Separate tuple members with indentation
Expand All @@ -87,6 +89,8 @@ pub struct PrettyConfig {
/// Enable extensions. Only configures 'implicit_some',
/// 'unwrap_newtypes', and 'unwrap_variant_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 @@ -128,6 +132,15 @@ 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`
Expand Down Expand Up @@ -170,6 +183,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 All @@ -190,11 +220,13 @@ impl Default for PrettyConfig {
String::from("\r\n")
},
indentor: String::from(" "),
separator: String::from(" "),
struct_names: false,
separate_tuple_members: false,
enumerate_arrays: false,
extensions: Extensions::empty(),
decimal_floats: false,
compact_arrays: false,
_future_proof: (),
}
}
Expand Down Expand Up @@ -263,13 +295,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 @@ -282,6 +307,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.default_extensions
| self
Expand Down Expand Up @@ -422,6 +453,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 @@ -563,7 +595,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 @@ -721,12 +755,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 @@ -744,13 +783,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 @@ -775,14 +817,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 @@ -866,6 +904,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 @@ -879,8 +919,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 @@ -920,15 +960,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 61a8b5d

Please sign in to comment.