Skip to content

Commit

Permalink
Optionally always include float decimals
Browse files Browse the repository at this point in the history
  • Loading branch information
cart committed May 26, 2020
1 parent 42b0f62 commit 2ea9937
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Next
- Added `decimal_floats` PrettyConfig option, which always includes decimals in floats (`1.0` vs `1`) ([#237](https://github.com/ron-rs/ron/pull/237))

## [0.6.0] - 2020-05-21
### Additions
Expand Down
31 changes: 31 additions & 0 deletions src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ pub struct PrettyConfig {
/// Enumerate array items in comments
#[serde(default = "default_enumerate_arrays")]
pub enumerate_arrays: bool,
/// Always include the decimal in floats
#[serde(default = "default_decimal_floats")]
pub decimal_floats: bool,
/// Enable extensions. Only configures 'implicit_some' for now.
pub extensions: Extensions,
/// Private field to ensure adding a field is non-breaking.
Expand Down Expand Up @@ -141,6 +144,17 @@ impl PrettyConfig {
self
}

/// Configures whether floats should always include a decimal.
/// When false `1.0` will serialize as `1`
/// When true `1.0` will serialize as `1.0`
///
/// Default: `false`
pub fn with_decimal_floats(mut self, decimal_floats: bool) -> Self {
self.decimal_floats = decimal_floats;

self
}

/// Configures extensions
///
/// Default: Extensions::empty()
Expand All @@ -164,6 +178,10 @@ fn default_new_line() -> String {
new_line
}

fn default_decimal_floats() -> bool {
false
}

fn default_indentor() -> String {
" ".to_string()
}
Expand All @@ -185,6 +203,7 @@ impl Default for PrettyConfig {
separate_tuple_members: default_separate_tuple_members(),
enumerate_arrays: default_enumerate_arrays(),
extensions: Extensions::default(),
decimal_floats: default_decimal_floats(),
_future_proof: (),
}
}
Expand Down Expand Up @@ -241,6 +260,12 @@ impl<W: io::Write> Serializer<W> {
.map_or(false, |&(ref config, _)| config.separate_tuple_members)
}

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

fn extensions(&self) -> Extensions {
self.pretty
.as_ref()
Expand Down Expand Up @@ -363,11 +388,17 @@ impl<'a, W: io::Write> ser::Serializer for &'a mut Serializer<W> {

fn serialize_f32(self, v: f32) -> Result<()> {
write!(self.output, "{}", v)?;
if self.decimal_floats() && (v - v.floor()).abs() < f32::EPSILON {
write!(self.output, ".0")?;
}
Ok(())
}

fn serialize_f64(self, v: f64) -> Result<()> {
write!(self.output, "{}", v)?;
if self.decimal_floats() && (v - v.floor()).abs() < f64::EPSILON {
write!(self.output, ".0")?;
}
Ok(())
}

Expand Down
24 changes: 23 additions & 1 deletion tests/floats.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,30 @@
use ron::de::from_str;
use ron::{
de::from_str,
ser::{to_string_pretty, PrettyConfig},
};

#[test]
fn test_inf_and_nan() {
assert_eq!(from_str("inf"), Ok(std::f64::INFINITY));
assert_eq!(from_str("-inf"), Ok(std::f64::NEG_INFINITY));
assert_eq!(from_str::<f64>("NaN").map(|n| n.is_nan()), Ok(true))
}

#[test]
fn decimal_floats() {
let pretty = PrettyConfig::new().with_decimal_floats(false);
let without_decimal = to_string_pretty(&1.0, pretty).unwrap();
assert_eq!(without_decimal, "1");

let pretty = PrettyConfig::new().with_decimal_floats(false);
let without_decimal = to_string_pretty(&1.1, pretty).unwrap();
assert_eq!(without_decimal, "1.1");

let pretty = PrettyConfig::new().with_decimal_floats(true);
let with_decimal = to_string_pretty(&1.0, pretty).unwrap();
assert_eq!(with_decimal, "1.0");

let pretty = PrettyConfig::new().with_decimal_floats(true);
let with_decimal = to_string_pretty(&1.1, pretty).unwrap();
assert_eq!(with_decimal, "1.1");
}

0 comments on commit 2ea9937

Please sign in to comment.