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

Allow noncompact CompactDecimal #2889

Merged
merged 10 commits into from
Dec 16, 2022
Merged
Show file tree
Hide file tree
Changes from 9 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
2 changes: 2 additions & 0 deletions ffi/diplomat/ffi_coverage/tests/missing_apis.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
fixed_decimal::CompactDecimal#Struct
fixed_decimal::CompactDecimal::exponent#FnInStruct
fixed_decimal::CompactDecimal::from_str#FnInStruct
fixed_decimal::CompactDecimal::into_significand#FnInStruct
fixed_decimal::CompactDecimal::write_to#FnInStruct
fixed_decimal::FixedInteger#Struct
fixed_decimal::FixedInteger::from_str#FnInStruct
Expand Down
86 changes: 63 additions & 23 deletions utils/fixed_decimal/src/compact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ use crate::FixedDecimal;

/// A struct containing a [`FixedDecimal`] significand together with an exponent, representing a
/// number written in compact notation (such as 1.2M).
/// This represents a _source number_ that uses compact decimal notation, as defined
/// This represents a _source number_, as defined
/// [in UTS #35](https://www.unicode.org/reports/tr35/tr35-numbers.html#Plural_rules_syntax).
/// The value exponent=0 represents a number in non-compact
/// notation (such as 1 200 000).
///
/// This is distinct from [`crate::ScientificDecimal`] because it does not represent leading 0s
/// nor a sign in the exponent, and behaves differently in pluralization.
Expand All @@ -23,6 +25,33 @@ pub struct CompactDecimal {
exponent: i16,
}

impl CompactDecimal {
/// Returns the significand of `self`.
/// ```
/// # use fixed_decimal::CompactDecimal;
/// # use fixed_decimal::FixedDecimal;
/// # use std::str::FromStr;
/// #
/// assert_eq!(CompactDecimal::from_str("+1.20c6").unwrap().into_significand(), FixedDecimal::from_str("+1.20").unwrap());
/// ```
pub fn into_significand(self) -> FixedDecimal {
self.significand
}

/// Returns the exponent of `self`.
/// ```
/// # use fixed_decimal::CompactDecimal;
/// # use fixed_decimal::FixedDecimal;
/// # use std::str::FromStr;
/// #
/// assert_eq!(CompactDecimal::from_str("+1.20c6").unwrap().exponent(), 6);
/// assert_eq!(CompactDecimal::from_str("1729").unwrap().exponent(), 0);
/// ```
pub fn exponent(&self) -> i16 {
self.exponent
}
}

/// Render the [`CompactDecimal`] in sampleValue syntax.
/// The letter c is used, rather than the deprecated e.
///
Expand All @@ -34,16 +63,24 @@ pub struct CompactDecimal {
/// # use writeable::assert_writeable_eq;
/// #
/// assert_writeable_eq!(CompactDecimal::from_str("+1.20c6").unwrap(), "+1.20c6");
/// assert_writeable_eq!(CompactDecimal::from_str("+1729").unwrap(), "+1729");
/// ```
impl writeable::Writeable for CompactDecimal {
fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
self.significand.write_to(sink)?;
sink.write_char('c')?;
self.exponent.write_to(sink)
if self.exponent != 0 {
sink.write_char('c')?;
self.exponent.write_to(sink)?;
}
Ok(())
}

fn writeable_length_hint(&self) -> writeable::LengthHint {
self.significand.writeable_length_hint() + 1 + self.exponent.writeable_length_hint()
let mut result = self.significand.writeable_length_hint();
if self.exponent != 0 {
result += self.exponent.writeable_length_hint() + 1;
}
return result;
}
}

Expand All @@ -65,22 +102,29 @@ impl TryFrom<&[u8]> for CompactDecimal {
}
let mut parts = input_str.split(|&c| c == b'c');
let significand = FixedDecimal::try_from(parts.next().ok_or(Error::Syntax)?)?;
let exponent_str =
core::str::from_utf8(parts.next().ok_or(Error::Syntax)?).map_err(|_| Error::Syntax)?;
if parts.next().is_some() {
return Err(Error::Syntax);
}
if exponent_str.is_empty()
|| exponent_str.bytes().next() == Some(b'0')
|| !exponent_str.bytes().all(|c| (b'0'..=b'9').contains(&c))
{
return Err(Error::Syntax);
match parts.next() {
None => Ok(CompactDecimal {
significand,
exponent: 0,
}),
Some(exponent_str) => {
let exponent_str = core::str::from_utf8(exponent_str).map_err(|_| Error::Syntax)?;
if parts.next().is_some() {
return Err(Error::Syntax);
}
if exponent_str.is_empty()
|| exponent_str.bytes().next() == Some(b'0')
|| !exponent_str.bytes().all(|c| (b'0'..=b'9').contains(&c))
{
return Err(Error::Syntax);
}
let exponent = exponent_str.parse().map_err(|_| Error::Limit)?;
Ok(CompactDecimal {
significand,
exponent,
})
}
}
let exponent = exponent_str.parse().map_err(|_| Error::Limit)?;
Ok(CompactDecimal {
significand,
exponent,
})
}
}

Expand All @@ -92,10 +136,6 @@ fn test_compact_syntax_error() {
pub expected_err: Option<Error>,
}
let cases = [
TestCase {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: probably add some testcases that ensure it works now

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They are in the doc tests (and they even caught a hint bug); the #[test] only covers errors.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah neat

input_str: "5",
expected_err: Some(Error::Syntax),
},
TestCase {
input_str: "-123e4",
expected_err: Some(Error::Syntax),
Expand Down
12 changes: 10 additions & 2 deletions utils/writeable/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,9 +329,17 @@ macro_rules! assert_writeable_eq {
assert_eq!(actual_str, $expected_str, $($arg)*);
assert_eq!(actual_str, $crate::Writeable::write_to_string(actual_writeable), $($arg)+);
let length_hint = $crate::Writeable::writeable_length_hint(actual_writeable);
assert!(length_hint.0 <= actual_str.len(), $($arg)*);
assert!(
length_hint.0 <= actual_str.len(),
"hint lower bound {} larger than actual length {}: {}",
length_hint.0, actual_str.len(), format!($($arg)*),
);
if let Some(upper) = length_hint.1 {
assert!(actual_str.len() <= upper, $($arg)*);
assert!(
actual_str.len() <= upper,
"hint upper bound {} smaller than actual length {}: {}",
length_hint.0, actual_str.len(), format!($($arg)*),
);
}
assert_eq!(actual_writeable.to_string(), $expected_str);
}};
Expand Down