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 compact arrays (#299) and pretty inline separators #349

Merged
merged 3 commits into from
Dec 18, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
96 changes: 69 additions & 27 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 @@ -291,12 +316,16 @@ impl<W: io::Write> Serializer<W> {
}

fn start_indent(&mut self) -> Result<()> {
self.start_indent_if(|_| true)
}

fn start_indent_if(&mut self, condition: impl Fn(&PrettyConfig) -> bool) -> Result<()> {
torkleyy marked this conversation as resolved.
Show resolved Hide resolved
if let Some((ref config, ref mut pretty)) = self.pretty {
pretty.indent += 1;
if pretty.indent <= config.depth_limit {
let is_empty = self.is_empty.unwrap_or(false);

if !is_empty {
if !is_empty && condition(config) {
self.output.write_all(config.new_line.as_bytes())?;
}
}
Expand All @@ -305,8 +334,12 @@ impl<W: io::Write> Serializer<W> {
}

fn indent(&mut self) -> io::Result<()> {
self.indent_if(|_| true)
}

fn indent_if(&mut self, condition: impl Fn(&PrettyConfig) -> bool) -> io::Result<()> {
if let Some((ref config, ref pretty)) = self.pretty {
if pretty.indent <= config.depth_limit {
if pretty.indent <= config.depth_limit && condition(config) {
for _ in 0..pretty.indent {
self.output.write_all(config.indentor.as_bytes())?;
}
Expand All @@ -316,11 +349,15 @@ impl<W: io::Write> Serializer<W> {
}

fn end_indent(&mut self) -> io::Result<()> {
self.end_indent_if(|_| true)
}

fn end_indent_if(&mut self, condition: impl Fn(&PrettyConfig) -> bool) -> io::Result<()> {
if let Some((ref config, ref mut pretty)) = self.pretty {
if pretty.indent <= config.depth_limit {
let is_empty = self.is_empty.unwrap_or(false);

if !is_empty {
if !is_empty && condition(config) {
for _ in 1..pretty.indent {
self.output.write_all(config.indentor.as_bytes())?;
}
Expand Down Expand Up @@ -422,6 +459,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 +601,7 @@ impl<'a, W: io::Write> ser::Serializer for &'a mut Serializer<W> {
self.is_empty = Some(len == 0);
}

self.start_indent()?;
self.start_indent_if(|config| !config.compact_arrays)?;

if let Some((_, ref mut pretty)) = self.pretty {
pretty.sequence_index.push(0);
Expand Down Expand Up @@ -721,12 +759,15 @@ 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()?;

self.ser.indent_if(|config| !config.compact_arrays)?;

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 +785,14 @@ 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()?;

self.ser.end_indent_if(|config| !config.compact_arrays)?;

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
21 changes: 21 additions & 0 deletions tests/240_array_pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,25 @@ 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(),
"[(),(),()]"
);
}
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