use rust_decimal::Decimal;
use crate::proto::longtrader::common::v1 as common;
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum DecimalConvertError {
#[error("decimal payload is empty: a value is carried by the containing field's presence")]
Empty,
#[error("`{value}` is not a base-10 decimal: {reason}")]
NotBase10 {
value: String,
reason: &'static str,
},
#[error("`{value}` is out of range for a decimal: {source}")]
OutOfRange {
value: String,
#[source]
source: rust_decimal::Error,
},
}
fn is_digits(s: &str) -> bool {
!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit())
}
fn grammar_violation(s: &str) -> Option<&'static str> {
if s.contains('_') {
return Some("digit separators are not accepted");
}
if s.contains(['e', 'E']) {
return Some("exponents are not accepted");
}
if s.starts_with('+') {
return Some("a leading `+` is not accepted");
}
let body = s.strip_prefix('-').unwrap_or(s);
let (whole, fraction) = match body.split_once('.') {
Some((whole, fraction)) => (whole, Some(fraction)),
None => (body, None),
};
if whole.is_empty() {
return Some("expected at least one digit before the decimal point");
}
if !is_digits(whole) {
return Some("expected only digits before the decimal point");
}
if let Some(fraction) = fraction {
if fraction.is_empty() {
return Some("expected at least one digit after the decimal point");
}
if !is_digits(fraction) {
return Some("expected only digits after the decimal point");
}
if fraction.len() > Decimal::MAX_SCALE as usize {
return Some("more fractional digits than a decimal can hold");
}
}
None
}
#[inline]
#[must_use]
pub fn decimal_to_common(value: Decimal) -> common::Decimal {
common::Decimal { value: value.to_string(), ..Default::default() }
}
pub fn common_to_decimal(value: &common::Decimal) -> Result<Decimal, DecimalConvertError> {
if value.value.trim().is_empty() {
return Err(DecimalConvertError::Empty);
}
if let Some(reason) = grammar_violation(&value.value) {
return Err(DecimalConvertError::NotBase10 { value: value.value.clone(), reason });
}
value
.value
.parse()
.map_err(|source| DecimalConvertError::OutOfRange { value: value.value.clone(), source })
}
#[cfg(test)]
mod tests {
use proptest::prelude::*;
use super::*;
fn assert_round_trip(value: Decimal) {
let encoded = decimal_to_common(value);
assert_eq!(encoded.value, value.to_string(), "the payload is the canonical rendering");
let decoded = common_to_decimal(&encoded).expect("this crate's own output must decode");
assert_eq!(decoded, value, "the round trip must be exact");
}
#[test]
fn a_value_is_carried_by_the_string_alone() {
assert_eq!(decimal_to_common(Decimal::new(12_345, 2)).value, "123.45");
assert_eq!(decimal_to_common(Decimal::ZERO).value, "0");
assert_eq!(decimal_to_common(Decimal::new(-7, 3)).value, "-0.007");
}
#[test]
fn the_full_decimal_range_round_trips_exactly() {
for value in [
Decimal::ZERO,
Decimal::ONE,
Decimal::NEGATIVE_ONE,
Decimal::new(-1, 8),
Decimal::MAX,
Decimal::MIN,
Decimal::from_i128_with_scale(1, 28),
"79228162514264337593543950335".parse::<Decimal>().expect("valid"),
"-79228162514264337593543950335".parse::<Decimal>().expect("valid"),
"0.0000000000000000000000000001".parse::<Decimal>().expect("valid"),
"1234567890123456789012345678".parse::<Decimal>().expect("valid"),
] {
assert_round_trip(value);
}
}
#[test]
fn a_wider_than_int64_mantissa_survives_unchanged() {
let widest = "79228162514264337593543950335".parse::<Decimal>().expect("valid");
assert!(widest.mantissa() > i128::from(i64::MAX), "this case must need more than 64 bits");
assert_round_trip(widest);
}
#[test]
fn the_scale_survives_the_round_trip() {
assert_round_trip(Decimal::new(1_100, 3));
assert_eq!(decimal_to_common(Decimal::new(1_100, 3)).value, "1.100");
}
#[test]
fn a_present_zero_is_a_value_and_not_an_absence() {
let zero = decimal_to_common(Decimal::ZERO);
assert_eq!(zero.value, "0");
assert_eq!(common_to_decimal(&zero).expect("zero decodes"), Decimal::ZERO);
}
#[test]
fn a_blank_payload_is_a_contract_violation_not_a_zero() {
for blank in ["", " ", "\t", "\n "] {
assert_eq!(
common_to_decimal(&common::Decimal {
value: blank.to_string(),
..Default::default()
}),
Err(DecimalConvertError::Empty),
"a payload of {blank:?} must be Empty, never zero"
);
}
}
#[test]
fn the_grammar_accepts_any_spelling_and_the_encoder_canonicalises() {
for (spelling, canonical) in
[("007", "7"), ("-0", "0"), ("1.500", "1.500"), ("0.000", "0.000"), ("00.5", "0.5")]
{
let wire = common::Decimal { value: spelling.to_string(), ..Default::default() };
let decoded = common_to_decimal(&wire)
.unwrap_or_else(|err| panic!("{spelling:?} should decode, got {err:?}"));
assert_eq!(
decimal_to_common(decoded).value,
canonical,
"{spelling:?} must canonicalise to {canonical:?}"
);
}
}
#[test]
fn an_unparsable_payload_is_rejected_and_echoed() {
let garbage = common::Decimal { value: "not-a-number".to_string(), ..Default::default() };
match common_to_decimal(&garbage) {
Err(DecimalConvertError::NotBase10 { value, reason }) => {
assert_eq!(value, "not-a-number", "the error must echo what actually arrived");
assert!(!reason.is_empty(), "the error must name the clause it broke");
}
other => panic!("expected Invalid, got {other:?}"),
}
}
#[test]
fn the_contract_grammar_is_stricter_than_the_rust_decimal_parser() {
for rejected in [
"1_000", "1e3", "1E3", ".5", "1.", "+1", " 1", "1 ", "1,000", "NaN", "inf", "--1", "0x10", "1", ] {
let wire = common::Decimal { value: rejected.to_string(), ..Default::default() };
assert!(
common_to_decimal(&wire).is_err(),
"{rejected:?} is outside the contract grammar and must be rejected"
);
}
for accepted in ["0", "-0", "1", "-1", "0.5", "-0.5", "1.000", "12345678901234567890"] {
let wire = common::Decimal { value: accepted.to_string(), ..Default::default() };
assert!(common_to_decimal(&wire).is_ok(), "{accepted:?} is in the contract grammar");
}
}
#[test]
fn anything_the_encoder_writes_is_accepted_by_the_decoder() {
for value in [
Decimal::new(i64::MAX, 0),
Decimal::new(i64::MIN, 28),
Decimal::from_i128_with_scale(-1, 28),
Decimal::new(1, 28),
] {
let encoded = decimal_to_common(value);
assert_eq!(common_to_decimal(&encoded).expect("encodable"), value);
}
}
proptest! {
#[test]
fn every_representable_decimal_survives_the_wire(
mantissa in proptest::num::i128::ANY,
scale in 0u32..=28,
) {
let Ok(value) = Decimal::try_from_i128_with_scale(mantissa, scale) else {
return Ok(());
};
let encoded = decimal_to_common(value);
prop_assert_eq!(&encoded.value, &value.to_string());
prop_assert_eq!(common_to_decimal(&encoded).unwrap_or(value), value);
}
#[test]
fn decoding_arbitrary_payloads_never_panics(payload in ".{0,40}") {
let wire = common::Decimal { value: payload, ..Default::default() };
match common_to_decimal(&wire) {
Ok(_) => {}
Err(DecimalConvertError::Empty) => {}
Err(DecimalConvertError::NotBase10 { value, .. })
| Err(DecimalConvertError::OutOfRange { value, .. })
=> prop_assert!(!value.is_empty()),
}
}
}
}