quantity.rs (7512B)
1 use crate::{AmountError, Decimal, listing::MeasurementUnit}; 2 use core::fmt; 3 4 /// Validated declared physical amount; this establishes no stock authority. 5 #[derive(Clone, Copy, Eq, PartialEq)] 6 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 7 pub struct Quantity { 8 amount: Decimal, 9 unit: MeasurementUnit, 10 } 11 12 #[cfg(feature = "serde")] 13 impl<'de> serde::Deserialize<'de> for Quantity { 14 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { 15 #[derive(serde::Deserialize)] 16 #[serde(deny_unknown_fields)] 17 struct Wire { 18 amount: Decimal, 19 unit: MeasurementUnit, 20 } 21 struct Visitor; 22 impl<'de> serde::de::Visitor<'de> for Visitor { 23 type Value = Wire; 24 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 25 f.write_str("a closed exact quantity object") 26 } 27 fn visit_map<A: serde::de::MapAccess<'de>>(self, map: A) -> Result<Wire, A::Error> { 28 <Wire as serde::Deserialize>::deserialize( 29 serde::de::value::MapAccessDeserializer::new(map), 30 ) 31 } 32 } 33 let wire = deserializer.deserialize_map(Visitor)?; 34 Self::new(wire.amount, wire.unit).map_err(serde::de::Error::custom) 35 } 36 } 37 38 impl Quantity { 39 /// Admits exact values, including explicit zero; each counts are integral. 40 pub fn new(amount: Decimal, unit: MeasurementUnit) -> Result<Self, QuantityError> { 41 if unit == MeasurementUnit::Each && amount.scale() != 0 { 42 return Err(QuantityError::FractionalCount); 43 } 44 Ok(Self { amount, unit }) 45 } 46 47 /// Returns the exact normalized nonnegative amount. 48 pub const fn amount(self) -> Decimal { 49 self.amount 50 } 51 52 /// Returns the single existing measurement identity. 53 pub const fn unit(self) -> MeasurementUnit { 54 self.unit 55 } 56 57 /// Explicitly converts g/kg or mL/L without rounding or inferred dimensions. 58 pub fn convert(self, target: MeasurementUnit) -> Result<Self, QuantityError> { 59 if self.unit == target { 60 return Ok(self); 61 } 62 let multiply = match (self.unit, target) { 63 (MeasurementUnit::Kilogram, MeasurementUnit::Gram) 64 | (MeasurementUnit::Litre, MeasurementUnit::Millilitre) => true, 65 (MeasurementUnit::Gram, MeasurementUnit::Kilogram) 66 | (MeasurementUnit::Millilitre, MeasurementUnit::Litre) => false, 67 _ => return Err(QuantityError::IncompatibleDimension), 68 }; 69 let mut coefficient = i128::from(self.amount.coefficient()); 70 let mut scale = self.amount.scale(); 71 if multiply && scale < 3 { 72 let factor = 10_i128 73 .checked_pow(u32::from(3 - scale)) 74 .ok_or(QuantityError::ArithmeticOutOfRange)?; 75 coefficient = coefficient 76 .checked_mul(factor) 77 .ok_or(QuantityError::ArithmeticOutOfRange)?; 78 scale = 0; 79 } else if multiply { 80 scale -= 3; 81 } else { 82 scale = scale 83 .checked_add(3) 84 .ok_or(QuantityError::ArithmeticOutOfRange)?; 85 } 86 while scale > 0 && coefficient.checked_rem(10) == Some(0) { 87 coefficient = coefficient 88 .checked_div(10) 89 .ok_or(QuantityError::ArithmeticOutOfRange)?; 90 scale -= 1; 91 } 92 if scale > Decimal::MAX_SCALE { 93 return Err(QuantityError::PrecisionLoss); 94 } 95 let coefficient = 96 u64::try_from(coefficient).map_err(|_| QuantityError::ArithmeticOutOfRange)?; 97 Self::new(Decimal::from_parts(coefficient, scale)?, target) 98 } 99 100 /// Adds matching units exactly; even compatible units require conversion. 101 pub fn checked_add(self, other: Self) -> Result<Self, QuantityError> { 102 if self.unit != other.unit { 103 return Err(QuantityError::UnitMismatch); 104 } 105 Self::new(self.amount.checked_add(other.amount)?, self.unit) 106 } 107 108 /// Subtracts matching units exactly; negative results remain errors. 109 pub fn checked_sub(self, other: Self) -> Result<Self, QuantityError> { 110 if self.unit != other.unit { 111 return Err(QuantityError::UnitMismatch); 112 } 113 Self::new(self.amount.checked_sub(other.amount)?, self.unit) 114 } 115 } 116 117 /// Declared package-content data, without physical backing or stock permission. 118 /// Estimated contents may inform display but never supply a fixed conversion. 119 #[derive(Clone, Copy, Eq, PartialEq)] 120 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 121 #[cfg_attr(feature = "serde", serde(tag = "type", rename_all = "snake_case"))] 122 pub enum ContentMeasure { 123 /// Explicit declared fixed quantity; authorization is established elsewhere. 124 Fixed { 125 /// Exact declared content and measurement unit. 126 quantity: Quantity, 127 }, 128 /// Display estimate, explicitly distinct from a guaranteed conversion. 129 Estimated { 130 /// Exact representation of the declared estimate. 131 quantity: Quantity, 132 }, 133 /// No quantity or universal physical conversion is implied. 134 Unspecified, 135 } 136 137 impl ContentMeasure { 138 /// Returns only explicitly fixed metadata; estimates never become fixed. 139 pub const fn fixed_quantity(self) -> Option<Quantity> { 140 match self { 141 Self::Fixed { quantity } => Some(quantity), 142 Self::Estimated { .. } | Self::Unspecified => None, 143 } 144 } 145 } 146 147 /// Input-free physical-value admission or exact-conversion failure. 148 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 149 #[non_exhaustive] 150 pub enum QuantityError { 151 /// Each counts cannot have a fractional normalized amount. 152 FractionalCount, 153 /// Arithmetic operands have different explicit units. 154 UnitMismatch, 155 /// No supported dimension-preserving conversion exists. 156 IncompatibleDimension, 157 /// The exact converted value would exceed the supported fractional scale. 158 PrecisionLoss, 159 /// A checked conversion intermediate cannot be represented. 160 ArithmeticOutOfRange, 161 /// Exact decimal admission/arithmetic failed. 162 Amount(AmountError), 163 } 164 165 impl From<AmountError> for QuantityError { 166 fn from(value: AmountError) -> Self { 167 Self::Amount(value) 168 } 169 } 170 171 impl fmt::Display for QuantityError { 172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 173 f.write_str(match self { 174 Self::FractionalCount => "fractional each count", 175 Self::UnitMismatch => "physical quantity units differ", 176 Self::IncompatibleDimension => "incompatible physical measurement dimensions", 177 Self::PrecisionLoss => "exact conversion exceeds supported precision", 178 Self::ArithmeticOutOfRange => "quantity arithmetic exceeds supported bounds", 179 Self::Amount(error) => return error.fmt(f), 180 }) 181 } 182 } 183 184 impl core::error::Error for QuantityError { 185 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { 186 match self { 187 Self::Amount(error) => Some(error), 188 _ => None, 189 } 190 } 191 } 192 193 impl fmt::Debug for Quantity { 194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 195 f.write_str("Quantity(<redacted>)") 196 } 197 } 198 199 impl fmt::Debug for ContentMeasure { 200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 201 f.write_str("ContentMeasure(<redacted>)") 202 } 203 }