commit 661819f911f8bc90be28a11278c9163b81074b4a
parent 1af72be4554dbeb5be73eb2e5fcab853faf05b5f
Author: triesap <tyson@radroots.org>
Date: Thu, 22 Oct 2026 15:34:43 +0000
domain: validate exact quantities and selected option amounts
- Add explicit dimension-preserving SI conversions with precision and range checks.
- Keep fixed, estimated and unspecified content descriptors distinct and redacted.
- Share checked increment rules across option construction and selected amounts.
- Verify boundary cases, feature portability, public API and unchanged coverage gates.
Diffstat:
7 files changed, 527 insertions(+), 3 deletions(-)
diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt
@@ -65,10 +65,13 @@ pub fn radroots_domain::listing::ListingId::deserialize<D: serde_core::de::Deser
pub struct radroots_domain::listing::ListingOption
impl radroots_domain::listing::ListingOption
pub const fn radroots_domain::listing::ListingOption::id(&self) -> radroots_domain::ListingOptionId
+pub const fn radroots_domain::listing::ListingOption::increment(&self) -> radroots_domain::PositiveDecimal
pub fn radroots_domain::listing::ListingOption::label(&self) -> &str
+pub const fn radroots_domain::listing::ListingOption::minimum(&self) -> radroots_domain::PositiveDecimal
pub const fn radroots_domain::listing::ListingOption::price(&self) -> radroots_domain::listing::Price
pub fn radroots_domain::listing::ListingOption::quote_required(radroots_domain::ListingOptionId, &str, radroots_domain::listing::SaleUnit, radroots_domain::PositiveDecimal, radroots_domain::PositiveDecimal, radroots_domain::listing::Supply, radroots_domain::listing::LeadSeconds) -> core::result::Result<Self, radroots_domain::listing::ListingError>
pub const fn radroots_domain::listing::ListingOption::unit(&self) -> &radroots_domain::listing::SaleUnit
+pub fn radroots_domain::listing::ListingOption::validate_amount(&self, radroots_domain::PositiveDecimal) -> core::result::Result<(), radroots_domain::listing::ListingError>
impl core::fmt::Debug for radroots_domain::listing::ListingOption
pub fn radroots_domain::listing::ListingOption::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct radroots_domain::listing::ListingTerms
@@ -119,6 +122,8 @@ pub radroots_domain::AmountError::MustBePositive
pub radroots_domain::AmountError::NegativeResult
pub radroots_domain::AmountError::NonCanonical
pub radroots_domain::AmountError::ScaleOutOfRange
+impl core::convert::From<radroots_domain::AmountError> for radroots_domain::QuantityError
+pub fn radroots_domain::QuantityError::from(radroots_domain::AmountError) -> Self
impl core::error::Error for radroots_domain::AmountError
impl core::fmt::Display for radroots_domain::AmountError
pub fn radroots_domain::AmountError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
@@ -129,6 +134,16 @@ pub radroots_domain::ChatRelation::Reply
pub radroots_domain::ChatRelation::Reply::parent: radroots_domain::MessageId
impl core::fmt::Debug for radroots_domain::ChatRelation
pub fn radroots_domain::ChatRelation::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
+pub enum radroots_domain::ContentMeasure
+pub radroots_domain::ContentMeasure::Estimated
+pub radroots_domain::ContentMeasure::Estimated::quantity: radroots_domain::Quantity
+pub radroots_domain::ContentMeasure::Fixed
+pub radroots_domain::ContentMeasure::Fixed::quantity: radroots_domain::Quantity
+pub radroots_domain::ContentMeasure::Unspecified
+impl radroots_domain::ContentMeasure
+pub const fn radroots_domain::ContentMeasure::fixed_quantity(self) -> core::option::Option<radroots_domain::Quantity>
+impl core::fmt::Debug for radroots_domain::ContentMeasure
+pub fn radroots_domain::ContentMeasure::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
#[non_exhaustive] pub enum radroots_domain::ContextError
pub radroots_domain::ContextError::InconsistentCoverage
pub radroots_domain::ContextError::InvalidInteger
@@ -190,6 +205,19 @@ impl core::error::Error for radroots_domain::PricingError
pub fn radroots_domain::PricingError::source(&self) -> core::option::Option<&(dyn core::error::Error + 'static)>
impl core::fmt::Display for radroots_domain::PricingError
pub fn radroots_domain::PricingError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
+#[non_exhaustive] pub enum radroots_domain::QuantityError
+pub radroots_domain::QuantityError::Amount(radroots_domain::AmountError)
+pub radroots_domain::QuantityError::ArithmeticOutOfRange
+pub radroots_domain::QuantityError::FractionalCount
+pub radroots_domain::QuantityError::IncompatibleDimension
+pub radroots_domain::QuantityError::PrecisionLoss
+pub radroots_domain::QuantityError::UnitMismatch
+impl core::convert::From<radroots_domain::AmountError> for radroots_domain::QuantityError
+pub fn radroots_domain::QuantityError::from(radroots_domain::AmountError) -> Self
+impl core::error::Error for radroots_domain::QuantityError
+pub fn radroots_domain::QuantityError::source(&self) -> core::option::Option<&(dyn core::error::Error + 'static)>
+impl core::fmt::Display for radroots_domain::QuantityError
+pub fn radroots_domain::QuantityError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct radroots_domain::ActorRef
impl radroots_domain::ActorRef
pub const fn radroots_domain::ActorRef::grant_id(self) -> core::option::Option<radroots_domain::GrantId>
@@ -566,6 +594,16 @@ pub const fn radroots_domain::PriceTier::new(radroots_domain::Decimal, radroots_
pub const fn radroots_domain::PriceTier::rate(self) -> radroots_domain::Money
impl core::fmt::Debug for radroots_domain::PriceTier
pub fn radroots_domain::PriceTier::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
+pub struct radroots_domain::Quantity
+impl radroots_domain::Quantity
+pub const fn radroots_domain::Quantity::amount(self) -> radroots_domain::Decimal
+pub fn radroots_domain::Quantity::checked_add(self, Self) -> core::result::Result<Self, radroots_domain::QuantityError>
+pub fn radroots_domain::Quantity::checked_sub(self, Self) -> core::result::Result<Self, radroots_domain::QuantityError>
+pub fn radroots_domain::Quantity::convert(self, radroots_domain::listing::MeasurementUnit) -> core::result::Result<Self, radroots_domain::QuantityError>
+pub fn radroots_domain::Quantity::new(radroots_domain::Decimal, radroots_domain::listing::MeasurementUnit) -> core::result::Result<Self, radroots_domain::QuantityError>
+pub const fn radroots_domain::Quantity::unit(self) -> radroots_domain::listing::MeasurementUnit
+impl core::fmt::Debug for radroots_domain::Quantity
+pub fn radroots_domain::Quantity::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct radroots_domain::RecordId(_)
impl radroots_domain::RecordId
pub const fn radroots_domain::RecordId::as_bytes(&self) -> &[u8; 32]
diff --git a/crates/domain/README.md b/crates/domain/README.md
@@ -32,6 +32,15 @@ and performs no implicit physical conversion. Complete option/terms admission,
fixed-price listing authoring, agreement installation and command effects remain
separate requirements; calculation values establish no authorization or stock.
+`Quantity` uses the existing measurement identity and exact decimal bounds.
+Conversions between g/kg and mL/L are explicit and reject precision loss;
+arithmetic requires matching units. `each` counts remain integral. Standalone
+`ContentMeasure` descriptors distinguish fixed, estimated and unspecified
+contents; estimates do not provide fixed conversions or stock backing. Existing
+sale options validate selected amounts against their minimum, increment and
+integral package/count rules. Advertised supply establishes no quantity ceiling
+or actual availability. Complete listing/term integration remains separate.
+
Order, thread, workspace, executor and operation IDs have distinct Rust types.
Each stores 32 bytes and uses exactly 64 lowercase hexadecimal characters in
strings and JSON. Byte/string construction validates representation; generation
diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs
@@ -15,6 +15,7 @@ pub mod listing;
mod message;
mod money;
mod pricing;
+mod quantity;
/// The identity-owned validated participant key; no second key type is defined.
pub use radroots_identity::PublicKey;
@@ -40,3 +41,4 @@ pub use pricing::{
DiscountBps, FixedPrice, LinePrice, MAX_PRICED_LINES, PRICING_PROFILE, PriceTier, PricingError,
checked_order_total,
};
+pub use quantity::{ContentMeasure, Quantity, QuantityError};
diff --git a/crates/domain/src/listing.rs b/crates/domain/src/listing.rs
@@ -325,9 +325,7 @@ impl ListingOption {
text(label, 120, false)?;
let inc = increment.amount();
let min = minimum.amount();
- let scale = inc.scale().max(min.scale());
- let align = |v: Decimal| v.coefficient() * 10_u64.pow(u32::from(scale - v.scale()));
- if !align(min).is_multiple_of(align(inc))
+ if !exact_multiple(min, inc)
|| (unit.integral()
&& (inc.scale() != 0
|| min.scale() != 0
@@ -354,6 +352,26 @@ impl ListingOption {
pub const fn unit(&self) -> &SaleUnit {
&self.unit
}
+ /// Returns the exact positive purchase increment.
+ pub const fn increment(&self) -> PositiveDecimal {
+ self.increment
+ }
+ /// Returns the exact positive advertised minimum.
+ pub const fn minimum(&self) -> PositiveDecimal {
+ self.minimum
+ }
+ /// Checks minimum, increment and integral count rules without claiming stock.
+ /// Advertised supply is an estimate, not an implicit quantity ceiling.
+ pub fn validate_amount(&self, amount: PositiveDecimal) -> Result<(), ListingError> {
+ let amount = amount.amount();
+ if amount < self.minimum.amount()
+ || !exact_multiple(amount, self.increment.amount())
+ || (self.unit.integral() && amount.scale() != 0)
+ {
+ return Err(ListingError::InvalidQuantity);
+ }
+ Ok(())
+ }
/// Returns the validated price mode, without inventing a quoted amount.
pub const fn price(&self) -> Price {
self.price
@@ -369,6 +387,15 @@ impl fmt::Debug for ListingOption {
}
}
+fn exact_multiple(value: Decimal, increment: Decimal) -> bool {
+ let scale = value.scale().max(increment.scale());
+ let align = |amount: Decimal| {
+ i128::from(amount.coefficient())
+ .checked_mul(10_i128.checked_pow(u32::from(scale - amount.scale()))?)
+ };
+ align(value).and_then(|value| value.checked_rem(align(increment)?)) == Some(0)
+}
+
/// Public fulfillment mode, without exact private destination or time window.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
diff --git a/crates/domain/src/quantity.rs b/crates/domain/src/quantity.rs
@@ -0,0 +1,177 @@
+use crate::{AmountError, Decimal, listing::MeasurementUnit};
+use core::fmt;
+
+/// Validated declared physical amount; this establishes no stock authority.
+#[derive(Clone, Copy, Eq, PartialEq)]
+#[cfg_attr(feature = "serde", derive(serde::Serialize))]
+pub struct Quantity {
+ amount: Decimal,
+ unit: MeasurementUnit,
+}
+
+impl Quantity {
+ /// Admits exact values, including explicit zero; each counts are integral.
+ pub fn new(amount: Decimal, unit: MeasurementUnit) -> Result<Self, QuantityError> {
+ if unit == MeasurementUnit::Each && amount.scale() != 0 {
+ return Err(QuantityError::FractionalCount);
+ }
+ Ok(Self { amount, unit })
+ }
+
+ /// Returns the exact normalized nonnegative amount.
+ pub const fn amount(self) -> Decimal {
+ self.amount
+ }
+
+ /// Returns the single existing measurement identity.
+ pub const fn unit(self) -> MeasurementUnit {
+ self.unit
+ }
+
+ /// Explicitly converts g/kg or mL/L without rounding or inferred dimensions.
+ pub fn convert(self, target: MeasurementUnit) -> Result<Self, QuantityError> {
+ if self.unit == target {
+ return Ok(self);
+ }
+ let multiply = match (self.unit, target) {
+ (MeasurementUnit::Kilogram, MeasurementUnit::Gram)
+ | (MeasurementUnit::Litre, MeasurementUnit::Millilitre) => true,
+ (MeasurementUnit::Gram, MeasurementUnit::Kilogram)
+ | (MeasurementUnit::Millilitre, MeasurementUnit::Litre) => false,
+ _ => return Err(QuantityError::IncompatibleDimension),
+ };
+ let mut coefficient = i128::from(self.amount.coefficient());
+ let mut scale = self.amount.scale();
+ if multiply && scale < 3 {
+ let factor = 10_i128
+ .checked_pow(u32::from(3 - scale))
+ .ok_or(QuantityError::ArithmeticOutOfRange)?;
+ coefficient = coefficient
+ .checked_mul(factor)
+ .ok_or(QuantityError::ArithmeticOutOfRange)?;
+ scale = 0;
+ } else if multiply {
+ scale -= 3;
+ } else {
+ scale = scale
+ .checked_add(3)
+ .ok_or(QuantityError::ArithmeticOutOfRange)?;
+ }
+ while scale > 0 && coefficient.checked_rem(10) == Some(0) {
+ coefficient = coefficient
+ .checked_div(10)
+ .ok_or(QuantityError::ArithmeticOutOfRange)?;
+ scale -= 1;
+ }
+ if scale > Decimal::MAX_SCALE {
+ return Err(QuantityError::PrecisionLoss);
+ }
+ let coefficient =
+ u64::try_from(coefficient).map_err(|_| QuantityError::ArithmeticOutOfRange)?;
+ Self::new(Decimal::from_parts(coefficient, scale)?, target)
+ }
+
+ /// Adds matching units exactly; even compatible units require conversion.
+ pub fn checked_add(self, other: Self) -> Result<Self, QuantityError> {
+ if self.unit != other.unit {
+ return Err(QuantityError::UnitMismatch);
+ }
+ Self::new(self.amount.checked_add(other.amount)?, self.unit)
+ }
+
+ /// Subtracts matching units exactly; negative results remain errors.
+ pub fn checked_sub(self, other: Self) -> Result<Self, QuantityError> {
+ if self.unit != other.unit {
+ return Err(QuantityError::UnitMismatch);
+ }
+ Self::new(self.amount.checked_sub(other.amount)?, self.unit)
+ }
+}
+
+/// Declared package-content data, without physical backing or stock permission.
+/// Estimated contents may inform display but never supply a fixed conversion.
+#[derive(Clone, Copy, Eq, PartialEq)]
+#[cfg_attr(feature = "serde", derive(serde::Serialize))]
+#[cfg_attr(feature = "serde", serde(tag = "type", rename_all = "snake_case"))]
+pub enum ContentMeasure {
+ /// Explicit declared fixed quantity; authorization is established elsewhere.
+ Fixed {
+ /// Exact declared content and measurement unit.
+ quantity: Quantity,
+ },
+ /// Display estimate, explicitly distinct from a guaranteed conversion.
+ Estimated {
+ /// Exact representation of the declared estimate.
+ quantity: Quantity,
+ },
+ /// No quantity or universal physical conversion is implied.
+ Unspecified,
+}
+
+impl ContentMeasure {
+ /// Returns only explicitly fixed metadata; estimates never become fixed.
+ pub const fn fixed_quantity(self) -> Option<Quantity> {
+ match self {
+ Self::Fixed { quantity } => Some(quantity),
+ Self::Estimated { .. } | Self::Unspecified => None,
+ }
+ }
+}
+
+/// Input-free physical-value admission or exact-conversion failure.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+#[non_exhaustive]
+pub enum QuantityError {
+ /// Each counts cannot have a fractional normalized amount.
+ FractionalCount,
+ /// Arithmetic operands have different explicit units.
+ UnitMismatch,
+ /// No supported dimension-preserving conversion exists.
+ IncompatibleDimension,
+ /// The exact converted value would exceed the supported fractional scale.
+ PrecisionLoss,
+ /// A checked conversion intermediate cannot be represented.
+ ArithmeticOutOfRange,
+ /// Exact decimal admission/arithmetic failed.
+ Amount(AmountError),
+}
+
+impl From<AmountError> for QuantityError {
+ fn from(value: AmountError) -> Self {
+ Self::Amount(value)
+ }
+}
+
+impl fmt::Display for QuantityError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(match self {
+ Self::FractionalCount => "fractional each count",
+ Self::UnitMismatch => "physical quantity units differ",
+ Self::IncompatibleDimension => "incompatible physical measurement dimensions",
+ Self::PrecisionLoss => "exact conversion exceeds supported precision",
+ Self::ArithmeticOutOfRange => "quantity arithmetic exceeds supported bounds",
+ Self::Amount(error) => return error.fmt(f),
+ })
+ }
+}
+
+impl core::error::Error for QuantityError {
+ fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
+ match self {
+ Self::Amount(error) => Some(error),
+ _ => None,
+ }
+ }
+}
+
+impl fmt::Debug for Quantity {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("Quantity(<redacted>)")
+ }
+}
+
+impl fmt::Debug for ContentMeasure {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("ContentMeasure(<redacted>)")
+ }
+}
diff --git a/crates/domain/tests/listing.rs b/crates/domain/tests/listing.rs
@@ -265,6 +265,78 @@ fn exact_increments_and_units_never_invent_fractional_packages_or_conversion() {
}
#[test]
+fn selected_amounts_validate_minimum_and_increment_without_using_advertised_stock() {
+ let measured = option(
+ 1,
+ SaleUnit::measured(MeasurementUnit::Kilogram),
+ "0.25",
+ "0.5",
+ "0",
+ )
+ .unwrap();
+ assert_eq!(measured.minimum().to_string(), "0.5");
+ assert_eq!(measured.increment().to_string(), "0.25");
+ for amount in ["0.5", "0.75", "10.25", "999999999999"] {
+ measured.validate_amount(amount.parse().unwrap()).unwrap();
+ }
+ for amount in ["0.25", "0.6", "0.500001"] {
+ assert_eq!(
+ measured.validate_amount(amount.parse().unwrap()),
+ Err(ListingError::InvalidQuantity)
+ );
+ }
+ for unit in [
+ SaleUnit::measured(MeasurementUnit::Each),
+ SaleUnit::package_unspecified("bag").unwrap(),
+ ] {
+ let value = option(2, unit, "2", "4", "0").unwrap();
+ for amount in ["4", "6", "100"] {
+ value.validate_amount(amount.parse().unwrap()).unwrap();
+ }
+ for amount in ["1", "3", "4.5", "5"] {
+ assert_eq!(
+ value.validate_amount(amount.parse().unwrap()),
+ Err(ListingError::InvalidQuantity)
+ );
+ }
+ }
+}
+
+#[test]
+fn selected_amounts_preserve_extreme_exact_scales_and_shared_constructor_rules() {
+ let tiny = option(
+ 1,
+ SaleUnit::measured(MeasurementUnit::Gram),
+ "0.000001",
+ "0.000002",
+ "0",
+ )
+ .unwrap();
+ for amount in ["0.000002", "1", "999999999999"] {
+ tiny.validate_amount(amount.parse().unwrap()).unwrap();
+ }
+ assert_eq!(
+ tiny.validate_amount("0.000001".parse().unwrap()),
+ Err(ListingError::InvalidQuantity)
+ );
+ let large = option(
+ 2,
+ SaleUnit::measured(MeasurementUnit::Litre),
+ "999999999999",
+ "999999999999",
+ "0",
+ )
+ .unwrap();
+ large
+ .validate_amount("999999999999".parse().unwrap())
+ .unwrap();
+ assert_eq!(
+ large.validate_amount("1".parse().unwrap()),
+ Err(ListingError::InvalidQuantity)
+ );
+}
+
+#[test]
fn bounded_unique_options_preserve_exact_default_without_fallback() {
let make = |n| {
option(
diff --git a/crates/domain/tests/quantity.rs b/crates/domain/tests/quantity.rs
@@ -0,0 +1,199 @@
+use radroots_domain::listing::MeasurementUnit::{self, Each, Gram, Kilogram, Litre, Millilitre};
+use radroots_domain::{AmountError, ContentMeasure, Decimal, Quantity, QuantityError};
+use std::error::Error;
+
+fn quantity(amount: &str, unit: MeasurementUnit) -> Quantity {
+ Quantity::new(amount.parse().unwrap(), unit).unwrap()
+}
+
+#[test]
+fn explicit_si_conversions_match_independent_canonical_examples_in_both_dimensions() {
+ for (source, target) in [(Gram, Kilogram), (Millilitre, Litre)] {
+ for (small, large) in [
+ ("0", "0"),
+ ("1", "0.001"),
+ ("1000", "1"),
+ ("1250", "1.25"),
+ ("0.001", "0.000001"),
+ ("999999999999", "999999999.999"),
+ ] {
+ let small = quantity(small, source);
+ let large = quantity(large, target);
+ assert_eq!(small.convert(target).unwrap(), large);
+ assert_eq!(large.convert(source).unwrap(), small);
+ assert_eq!(small.convert(source).unwrap(), small);
+ assert_eq!(large.convert(target).unwrap(), large);
+ }
+ }
+ assert_eq!(
+ quantity("0.000001", Kilogram).convert(Gram).unwrap(),
+ quantity("0.001", Gram)
+ );
+ assert_eq!(
+ quantity("0.000001", Litre).convert(Millilitre).unwrap(),
+ quantity("0.001", Millilitre)
+ );
+}
+
+#[test]
+fn exact_conversions_refuse_rounding_and_normalized_amount_overflow() {
+ for (source, target) in [(Gram, Kilogram), (Millilitre, Litre)] {
+ for amount in ["0.000001", "0.00001", "0.0001", "1.000001"] {
+ assert_eq!(
+ quantity(amount, source).convert(target),
+ Err(QuantityError::PrecisionLoss)
+ );
+ }
+ assert_eq!(
+ quantity("999999999999", target).convert(source),
+ Err(QuantityError::Amount(AmountError::CoefficientOutOfRange))
+ );
+ // The exact largest output remains representable after conversion.
+ assert_eq!(
+ quantity("999999999.999", target)
+ .convert(source)
+ .unwrap()
+ .amount(),
+ Decimal::MAX
+ );
+ }
+}
+
+#[test]
+fn every_unit_pair_preserves_explicit_dimensions_even_for_zero() {
+ let units = [Gram, Kilogram, Millilitre, Litre, Each];
+ for source in units {
+ for target in units {
+ let compatible = source == target
+ || matches!(
+ (source, target),
+ (Gram, Kilogram) | (Kilogram, Gram) | (Millilitre, Litre) | (Litre, Millilitre)
+ );
+ for amount in ["0", "1"] {
+ let result = quantity(amount, source).convert(target);
+ if compatible {
+ let converted = result.unwrap();
+ assert_eq!(converted.unit(), target);
+ assert_eq!(converted.convert(source).unwrap(), quantity(amount, source));
+ } else {
+ assert_eq!(result, Err(QuantityError::IncompatibleDimension));
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn each_counts_use_semantic_normalization_but_cannot_be_fractional() {
+ for amount in ["0", "1", "999999999999"] {
+ let value = quantity(amount, Each);
+ assert_eq!(value.amount().to_string(), amount);
+ assert_eq!(value.unit(), Each);
+ }
+ assert_eq!(
+ Quantity::new(Decimal::from_parts(10, 1).unwrap(), Each).unwrap(),
+ quantity("1", Each)
+ );
+ for amount in ["0.000001", "0.5", "1.5"] {
+ assert_eq!(
+ Quantity::new(amount.parse().unwrap(), Each),
+ Err(QuantityError::FractionalCount)
+ );
+ for unit in [Gram, Kilogram, Millilitre, Litre] {
+ assert!(Quantity::new(amount.parse().unwrap(), unit).is_ok());
+ }
+ }
+}
+
+#[test]
+fn arithmetic_requires_matching_units_and_keeps_decimal_bounds_exact() {
+ let one = quantity("1", Kilogram);
+ let quarter = quantity("250", Gram);
+ assert_eq!(one.checked_add(quarter), Err(QuantityError::UnitMismatch));
+ assert_eq!(one.checked_sub(quarter), Err(QuantityError::UnitMismatch));
+ let quarter = quarter.convert(Kilogram).unwrap();
+ assert_eq!(
+ one.checked_add(quarter).unwrap(),
+ quantity("1.25", Kilogram)
+ );
+ assert_eq!(
+ one.checked_sub(quarter).unwrap(),
+ quantity("0.75", Kilogram)
+ );
+ assert_eq!(one.checked_sub(one).unwrap(), quantity("0", Kilogram));
+ assert_eq!(
+ quarter.checked_sub(one),
+ Err(QuantityError::Amount(AmountError::NegativeResult))
+ );
+ assert_eq!(
+ quantity("999999999999", Each).checked_add(quantity("1", Each)),
+ Err(QuantityError::Amount(AmountError::CoefficientOutOfRange))
+ );
+}
+
+#[test]
+fn fixed_estimated_and_unspecified_contents_never_collapse_into_one_claim() {
+ let amount = quantity("1.25", Kilogram);
+ let fixed = ContentMeasure::Fixed { quantity: amount };
+ let estimated = ContentMeasure::Estimated { quantity: amount };
+ assert_ne!(fixed, estimated);
+ assert_eq!(fixed.fixed_quantity(), Some(amount));
+ assert_eq!(estimated.fixed_quantity(), None);
+ assert_eq!(ContentMeasure::Unspecified.fixed_quantity(), None);
+ let explicit_zero = ContentMeasure::Fixed {
+ quantity: quantity("0", Gram),
+ };
+ assert_ne!(explicit_zero, ContentMeasure::Unspecified);
+}
+
+#[test]
+fn diagnostics_redact_physical_values_and_preserve_typed_fixed_failures() {
+ let value = quantity("928174615", Kilogram);
+ for debug in [
+ format!("{value:?}"),
+ format!("{:?}", ContentMeasure::Fixed { quantity: value }),
+ format!("{:?}", ContentMeasure::Estimated { quantity: value }),
+ ] {
+ assert!(!debug.contains("928174615"));
+ assert!(!debug.contains("Kilogram"));
+ }
+ for error in [
+ QuantityError::FractionalCount,
+ QuantityError::UnitMismatch,
+ QuantityError::IncompatibleDimension,
+ QuantityError::PrecisionLoss,
+ QuantityError::ArithmeticOutOfRange,
+ AmountError::CoefficientOutOfRange.into(),
+ ] {
+ assert!(!error.to_string().is_empty());
+ assert!(!error.to_string().contains("928174615"));
+ }
+ assert!(QuantityError::PrecisionLoss.source().is_none());
+ assert!(
+ QuantityError::Amount(AmountError::NegativeResult)
+ .source()
+ .is_some()
+ );
+}
+
+#[cfg(feature = "serde")]
+#[test]
+fn serialization_preserves_exact_strings_units_and_explicit_content_alternatives() {
+ let value = quantity("0.000001", Kilogram);
+ assert_eq!(
+ serde_json::to_value(value).unwrap(),
+ serde_json::json!({"amount":"0.000001","unit":"kg"})
+ );
+ assert_eq!(
+ serde_json::to_value(ContentMeasure::Fixed { quantity: value }).unwrap(),
+ serde_json::json!({"type":"fixed","quantity":{"amount":"0.000001","unit":"kg"}})
+ );
+ assert_eq!(
+ serde_json::to_value(ContentMeasure::Estimated { quantity: value }).unwrap(),
+ serde_json::json!({"type":"estimated","quantity":{"amount":"0.000001","unit":"kg"}})
+ );
+ assert_eq!(
+ serde_json::to_value(ContentMeasure::Unspecified).unwrap(),
+ serde_json::json!({"type":"unspecified"})
+ );
+}