pub struct Decimal { /* private fields */ }Expand description
An exact base-10 decimal: mantissa × 10⁻ˢᶜᵃˡᵉ.
This is what every OCPP number is carried in. The schemas say "type": "number" and the
obvious reading of that is f64; it is the wrong one, for three reasons that all cost
money:
- Resolution is a claim. A meter reporting
2935.600kWh is stating three decimals of accuracy. As anf64,2935.600and2935.6are the same value and the claim is gone. ADecimalkeeps the scale the station sent, so the value decodes, prints and re-encodes as2935.600. OCMF says the same of its own readings: the representation “must not be transformed … thus potentially the number of valid digits” (Tab. 7,RV). - Energy is a subtraction. OCPP defines a session’s energy as the difference of two
register readings, and in
f6410.1 - 0.1is10.000000000000002. - The 2.1 Tariff and Cost block is money.
use ocpp_kit::decimal;
use ocpp_kit::types::Decimal;
let register: Decimal = "2935.600".parse().unwrap();
assert_eq!(register.scale(), 3);
assert_eq!(register.to_string(), "2935.600");
// The difference OCPP defines a session's energy as, exactly.
assert_eq!(decimal!(20.2) - decimal!(10.1), decimal!(10.1));Literals are written with decimal!, which parses the source text at
compile time; integers convert with From. There is deliberately no From<f64> — a
number that has been through a float has already lost what this type exists to keep — and
the conversions that do exist are named to_f64_lossy and
from_f64_lossy so a signature says what it costs. Nothing else
in this crate calls either, and cargo xtask no-floats fails the build if an f32 or
f64 reaches any public signature.
§What exactly is preserved
The fraction digits — the resolution claim — and therefore the positional spelling:
2935.600 in, 2935.600 out; 5 in, 5 out, not 5.0. What is not preserved is a
spelling that carries no information a decimal number has: exponent notation is
normalized (1.5e3 re-encodes as 1500), as are a leading + and leading zeros. Where
the exact bytes are load-bearing — a signed OCMF or EDL record — they are not a JSON
number at all, and metering carries those untouched.
§Range
The mantissa is an i64 and the scale is at most MAX_SCALE (18), so
a value carries up to 19 significant digits — a register in Wh with three decimals up to
10¹⁵ Wh. Text with more precision than that is rounded half to even by
from_ascii; text whose integer part does not fit is refused.
§Equality
PartialEq and Ord compare numerically, so 2.50 == 2.5 — that is what a comparison
between two readings should answer, and Hash agrees with it. The scale is still there
and still round-trips; eq_exact compares it too when the spelling is
what matters.
§Arithmetic
Addition, subtraction and multiplication are exact, at the scale the operands imply, and
the operators panic on overflow exactly as the integer ones do; the checked_ forms
return None instead. Division has no exact answer in base ten, so
checked_div takes the scale to round at rather than guessing one.
A change of unit prefix is checked_pow10, which moves the point
and so cannot round at all.
§Wire format
Serialize and Deserialize speak serde_json’s raw-value protocol, which is how the
source token reaches this type instead of the f64 a JSON parser would otherwise round it
to. Any other data format falls back to the ordinary numeric path and is lossy in the way
that format is lossy. OCPP-J is JSON, so this is the format that matters.
§Handing the value to another decimal type
A billing platform generally has a decimal type of its own. The conversion is exact in either direction, so this crate depends on none of them:
let exact = rust_decimal::Decimal::new(reading.mantissa(), u32::from(reading.scale()));
let back = ocpp_kit::types::Decimal::new(
i64::try_from(exact.mantissa()).unwrap(),
u8::try_from(exact.scale()).unwrap(),
);Anything that parses decimal text — bigdecimal, a database NUMERIC — takes
to_string(), which is the value at its own scale and never in exponent form.
Implementations§
Source§impl Decimal
impl Decimal
Sourcepub const fn try_new(mantissa: i64, scale: u8) -> Option<Self>
pub const fn try_new(mantissa: i64, scale: u8) -> Option<Self>
mantissa × 10⁻ˢᶜᵃˡᵉ, or None when scale exceeds MAX_SCALE.
Sourcepub const fn scale(self) -> u8
pub const fn scale(self) -> u8
How many digits follow the decimal point.
This is the resolution the value was written with, and it is preserved: a station that
sent 2935.600 gets 3 here, and 2935.600 back on the wire.
Sourcepub const fn eq_exact(self, other: Self) -> bool
pub const fn eq_exact(self, other: Self) -> bool
Whether two values have both the same number and the same scale — 2.50 and 2.5
are equal but not identical.
Sourcepub const fn normalized(self) -> Self
pub const fn normalized(self) -> Self
The same number with every trailing zero removed: 2.500 becomes 2.5.
Sourcepub const fn rescale(self, scale: u8) -> Option<Self>
pub const fn rescale(self, scale: u8) -> Option<Self>
The same number written at scale, or None when that would lose a digit or
overflow.
Exact by construction: it never rounds. Use round_to to round.
Sourcepub const fn round_to(self, scale: u8) -> Option<Self>
pub const fn round_to(self, scale: u8) -> Option<Self>
The value rounded to scale, half to even, or None on overflow or an out-of-range
scale.
Sourcepub const fn checked_add(self, rhs: Self) -> Option<Self>
pub const fn checked_add(self, rhs: Self) -> Option<Self>
The sum, at the larger of the two scales, or None on overflow.
Sourcepub const fn checked_sub(self, rhs: Self) -> Option<Self>
pub const fn checked_sub(self, rhs: Self) -> Option<Self>
The difference, at the larger of the two scales, or None on overflow.
This is the operation OCPP defines a session’s energy as, and the reason this type
exists: 20.2 - 10.1 is 10.1, not 10.100000000000001.
Sourcepub const fn checked_mul(self, rhs: Self) -> Option<Self>
pub const fn checked_mul(self, rhs: Self) -> Option<Self>
The product, at the sum of the two scales, or None when that does not fit.
Sourcepub const fn checked_div(self, rhs: Self, scale: u8) -> Option<Self>
pub const fn checked_div(self, rhs: Self, scale: u8) -> Option<Self>
The quotient at scale, rounded half to even, or None when rhs is zero or the
result does not fit.
Division is the one operation that has no exact answer in base ten — 1 / 3 does not
terminate — so the scale to round at is a parameter rather than a guess.
Sourcepub const fn checked_pow10(self, exp: i32) -> Option<Self>
pub const fn checked_pow10(self, exp: i32) -> Option<Self>
The value multiplied by 10^exp, exactly, or None when it does not fit.
A shift of the decimal point, which is all a change of unit prefix is: kWh to Wh is
pow10(3), and the 2.x unitOfMeasure.multiplier is exactly this operation. Unlike a
multiplication by a literal 1000.0 it cannot introduce a rounding error, because it
only moves the point.
Sourcepub const fn checked_abs(self) -> Option<Self>
pub const fn checked_abs(self) -> Option<Self>
The absolute value, or None for a mantissa of i64::MIN.
Sourcepub const fn checked_neg(self) -> Option<Self>
pub const fn checked_neg(self) -> Option<Self>
The negation, or None for a mantissa of i64::MIN.
Sourcepub const fn from_ascii(bytes: &[u8]) -> Result<Self, ParseDecimalError>
pub const fn from_ascii(bytes: &[u8]) -> Result<Self, ParseDecimalError>
Parses a decimal from ASCII, exactly.
Accepts everything JSON’s number production allows — an optional sign, digits, an
optional fraction, an optional e/E exponent — plus a leading +, leading zeros
and surrounding whitespace, none of which JSON permits but stations send anyway. The
scale of the result is the number of fraction digits written, so 2935.600 parses to
scale 3 and prints back identically.
§Errors
ParseDecimalError::Invalid when the text is not a number at all, and
ParseDecimalError::Overflow when its integer part needs more than 19 digits.
Excess fraction digits are rounded half to even rather than refused, because
refusing a value the schema calls valid is worse than rounding at the nineteenth
significant digit.
Sourcepub const fn from_literal(text: &str) -> Self
pub const fn from_literal(text: &str) -> Self
Parses a Rust numeric literal, panicking instead of returning an error.
This is what decimal! expands to, so the panic is a compile error
rather than a runtime one. It differs from from_ascii in
accepting Rust’s _ digit separators — decimal!(11_000) is how the number would be
written anywhere else in the source, and JSON never contains one, so the leniency
costs the wire path nothing.
§Panics
If the text is not a decimal number.
Sourcepub fn to_f64_lossy(self) -> f64
pub fn to_f64_lossy(self) -> f64
The value as an f64, correctly rounded.
Named for what it costs: past 15 significant digits the result is not the number this
Decimal holds, and no arithmetic done on it afterwards is exact. Nothing in this
crate calls it.
Sourcepub fn from_f64_lossy(value: f64) -> Option<Self>
pub fn from_f64_lossy(value: f64) -> Option<Self>
The decimal an f64 is nearest to, or None for an infinity, a NaN, or a magnitude
out of range.
Named for what it costs: the f64 0.1 is not one tenth, and this returns the
shortest decimal that reads back as the same f64 — 0.1 — rather than the value it
actually holds. That is the friendly answer, and it is still a guess about what the
number was before it became a float. Parse the text instead when there is text.
Trait Implementations§
Source§impl AddAssign for Decimal
impl AddAssign for Decimal
Source§fn add_assign(&mut self, rhs: Decimal)
fn add_assign(&mut self, rhs: Decimal)
+= operation. Read moreimpl Copy for Decimal
Source§impl<'de> Deserialize<'de> for Decimal
impl<'de> Deserialize<'de> for Decimal
Source§fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
Source§impl Div for Decimal
impl Div for Decimal
Source§fn div(self, rhs: Decimal) -> Decimal
fn div(self, rhs: Decimal) -> Decimal
Division at Decimal::MAX_SCALE, rounded half to even.
§Panics
On division by zero or overflow. Decimal::checked_div takes the scale to round at
and returns None instead, which is what production code should use.
impl Eq for Decimal
Source§impl Ord for Decimal
impl Ord for Decimal
1.21.0 (const: unstable) · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
1.21.0 (const: unstable) · Source§fn min(self, other: Self) -> Selfwhere
Self: Sized,
fn min(self, other: Self) -> Selfwhere
Self: Sized,
Source§impl PartialOrd for Decimal
impl PartialOrd for Decimal
Source§impl SubAssign for Decimal
impl SubAssign for Decimal
Source§fn sub_assign(&mut self, rhs: Decimal)
fn sub_assign(&mut self, rhs: Decimal)
-= operation. Read moreSource§impl Validate for Decimal
impl Validate for Decimal
Source§fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations)
fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations)
Nothing to check: unlike an f64, a Decimal cannot hold a value JSON has no
spelling for. Range constraints are emitted per field by the code generator.