Skip to main content

Quantity

Struct Quantity 

Source
pub struct Quantity<const SCALE: u32>(/* private fields */);
Expand description

A decimal quantity stored as an i64 count of 10^-SCALE units. SCALE is at most 9, checked at compile time. Adding and subtracting return a Result; there are no panicking operators.

use renox::money::Rounding;
use renox::quantity::Quantity;

let a = Quantity::<3>::parse_exact("1.250").unwrap();
let b = Quantity::<3>::parse_exact("0.750").unwrap();
assert_eq!(a.checked_add(b).unwrap().to_string(), "2.000");
assert_eq!(a.mul_decimal("1.15", Rounding::HalfUp).unwrap().to_string(), "1.438");
assert!(b < a);

Implementations§

Source§

impl<const SCALE: u32> Quantity<SCALE>

Source

pub const ZERO: Self

The zero quantity.

Source

pub const fn from_raw(raw: i64) -> Self

The quantity of raw units of 10^-SCALE (2500 is 2.500 for Quantity<3>).

use renox::quantity::Quantity;

assert_eq!(Quantity::<3>::from_raw(2500).to_string(), "2.500");
Source

pub const fn raw(self) -> i64

The value in units of 10^-SCALE.

use renox::quantity::Quantity;

assert_eq!(Quantity::<2>::from_raw(-150).raw(), -150);
Source

pub fn parse(text: &str, rounding: Rounding) -> Result<Self, QuantityError>

Reads a decimal such as "2.5" or "-0.125" with . as the decimal point. Digits beyond the scale are rounded with rounding (Down is toward zero, Up away from zero). Empty text, signs other than a leading - or +, exponents and separators are Invalid; a value that does not fit is Overflow.

use renox::money::Rounding;
use renox::quantity::Quantity;

let q = |t, r| Quantity::<3>::parse(t, r).unwrap().to_string();
assert_eq!(q("2.5", Rounding::HalfEven), "2.500");
assert_eq!(q("0.0005", Rounding::HalfUp), "0.001");
assert_eq!(q("0.0005", Rounding::HalfEven), "0.000");
assert_eq!(q("-0.0005", Rounding::Up), "-0.001");
assert_eq!(q("0.0009", Rounding::Down), "0.000");
assert!(Quantity::<3>::parse("1e3", Rounding::Down).is_err());
Source

pub fn parse_exact(text: &str) -> Result<Self, QuantityError>

Reads a decimal and fails with Inexact if digits beyond the scale are not all zero; nothing is rounded.

use renox::quantity::{Quantity, QuantityError};

assert_eq!(Quantity::<3>::parse_exact("12.50").unwrap().raw(), 12_500);
assert_eq!(Quantity::<3>::parse_exact("1.2000").unwrap().raw(), 1_200);
assert_eq!(Quantity::<3>::parse_exact("1.0001").unwrap_err(), QuantityError::Inexact);
Source

pub fn parse_half_even(text: &str) -> Result<Self, QuantityError>

Like Quantity::parse with HalfEven (banker’s rounding). It is a convenience, not a default: parse always asks for a rounding.

use renox::quantity::Quantity;

assert_eq!(Quantity::<0>::parse_half_even("2.5").unwrap().raw(), 2);
assert_eq!(Quantity::<0>::parse_half_even("3.5").unwrap().raw(), 4);
Source

pub fn checked_add(self, other: Self) -> Result<Self, QuantityError>

The sum, or Overflow past the i64 limits.

use renox::quantity::Quantity;

let one = Quantity::<3>::from_raw(1000);
assert_eq!(one.checked_add(one).unwrap().raw(), 2000);
assert!(Quantity::<3>::from_raw(i64::MAX).checked_add(one).is_err());
Source

pub fn checked_sub(self, other: Self) -> Result<Self, QuantityError>

The difference, or Overflow past the i64 limits.

use renox::quantity::Quantity;

let one = Quantity::<3>::from_raw(1000);
assert_eq!(one.checked_sub(Quantity::from_raw(1500)).unwrap().raw(), -500);
Source

pub fn checked_neg(self) -> Result<Self, QuantityError>

The negated quantity, or Overflow for the smallest i64.

use renox::quantity::Quantity;

assert_eq!(Quantity::<3>::from_raw(5).checked_neg().unwrap().raw(), -5);
assert!(Quantity::<3>::from_raw(i64::MIN).checked_neg().is_err());
Source

pub fn mul_ratio( self, num: i64, den: i64, rounding: Rounding, ) -> Result<Self, QuantityError>

The quantity times num / den, rounded to the scale with rounding. A zero den is DivisionByZero.

use renox::money::Rounding;
use renox::quantity::Quantity;

let q = Quantity::<3>::from_raw(1000);
assert_eq!(q.mul_ratio(1, 3, Rounding::Down).unwrap().raw(), 333);
assert_eq!(q.mul_ratio(1, 3, Rounding::Up).unwrap().raw(), 334);
Source

pub fn mul_decimal( self, factor: &str, rounding: Rounding, ) -> Result<Self, QuantityError>

The quantity times an exact decimal factor such as "1.15", rounded with rounding. The factor has at most 18 decimals and no exponent; anything else is Invalid.

use renox::money::Rounding;
use renox::quantity::Quantity;

let q = Quantity::<3>::from_raw(2000);
assert_eq!(q.mul_decimal("1.15", Rounding::HalfUp).unwrap().raw(), 2300);
assert_eq!(q.mul_decimal("-0.0005", Rounding::HalfUp).unwrap().raw(), -1);
assert!(q.mul_decimal("1e3", Rounding::HalfUp).is_err());
Source

pub fn rescale<const TO: u32>( self, rounding: Rounding, ) -> Result<Quantity<TO>, QuantityError>

The same value at another scale. Going to a finer scale is exact (or Overflow); going coarser rounds with rounding.

use renox::money::Rounding;
use renox::quantity::Quantity;

let q = Quantity::<3>::from_raw(2505);
assert_eq!(q.rescale::<2>(Rounding::HalfUp).unwrap().raw(), 251);
assert_eq!(q.rescale::<2>(Rounding::Down).unwrap().raw(), 250);
assert_eq!(q.rescale::<4>(Rounding::Down).unwrap().raw(), 25_050);

Trait Implementations§

Source§

impl<const SCALE: u32> Clone for Quantity<SCALE>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<const S: u32> ColumnType for Quantity<S>

A Quantity is one BIGINT column; the scale is in the Rust type only.

Source§

const KIND: ColumnKind = ColumnKind::BigInt

The kind of column this type is stored in.
Source§

impl<const SCALE: u32> Copy for Quantity<SCALE>

Source§

impl<const SCALE: u32> Debug for Quantity<SCALE>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'r, const S: u32> Decode<'r, Postgres> for Quantity<S>

Source§

fn decode( value: <Postgres as Database>::ValueRef<'r>, ) -> Result<Self, BoxDynError>

Decode a new value of this type using a raw value from the database.
Source§

impl<'r, const S: u32> Decode<'r, Sqlite> for Quantity<S>

Source§

fn decode( value: <Sqlite as Database>::ValueRef<'r>, ) -> Result<Self, BoxDynError>

Decode a new value of this type using a raw value from the database.
Source§

impl<'de, const SCALE: u32> Deserialize<'de> for Quantity<SCALE>

Source§

fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>

Accepts a decimal string, or a JSON number when it is exactly representable at the scale (its shortest decimal form is read).

Source§

impl<const SCALE: u32> Display for Quantity<SCALE>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

The exact decimal with all SCALE digits (2.500), . as the decimal point and no grouping.

Source§

impl<const SCALE: u32> Eq for Quantity<SCALE>

Source§

impl<const SCALE: u32> Hash for Quantity<SCALE>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<const S: u32> Number for Quantity<S>

The sum of a Quantity column stays a Quantity of the same scale.

Source§

impl<const SCALE: u32> Ord for Quantity<SCALE>

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl<const SCALE: u32> PartialEq for Quantity<SCALE>

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<const SCALE: u32> PartialOrd for Quantity<SCALE>

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<const SCALE: u32> Serialize for Quantity<SCALE>

Source§

fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

A decimal string such as "2.500", so JSON never loses precision.

Source§

impl<const SCALE: u32> StructuralPartialEq for Quantity<SCALE>

Source§

impl<const S: u32> ToDbValue for Quantity<S>

The scaled integer, stored as BIGINT: exact on both databases. The scale lives in the Rust type, not in the schema.

Source§

fn to_db_value(&self) -> DbValue

The value to bind for self.
Source§

impl<const S: u32> Type<Postgres> for Quantity<S>

Source§

fn type_info() -> <Postgres as Database>::TypeInfo

Returns the canonical SQL type for this Rust type. Read more
Source§

fn compatible(ty: &<Postgres as Database>::TypeInfo) -> bool

Determines if this Rust type is compatible with the given SQL type. Read more
Source§

impl<const S: u32> Type<Sqlite> for Quantity<S>

Source§

fn type_info() -> <Sqlite as Database>::TypeInfo

Returns the canonical SQL type for this Rust type. Read more
Source§

fn compatible(ty: &<Sqlite as Database>::TypeInfo) -> bool

Determines if this Rust type is compatible with the given SQL type. Read more

Auto Trait Implementations§

§

impl<const SCALE: u32> Freeze for Quantity<SCALE>

§

impl<const SCALE: u32> RefUnwindSafe for Quantity<SCALE>

§

impl<const SCALE: u32> Send for Quantity<SCALE>

§

impl<const SCALE: u32> Sync for Quantity<SCALE>

§

impl<const SCALE: u32> Unpin for Quantity<SCALE>

§

impl<const SCALE: u32> UnsafeUnpin for Quantity<SCALE>

§

impl<const SCALE: u32> UnwindSafe for Quantity<SCALE>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
Source§

impl<T> Comparable<T> for T
where T: ToDbValue,

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> Fake for T

Source§

fn fake<U>(&self) -> U
where Self: FakeBase<U>,

Source§

fn fake_with_rng<U, R>(&self, rng: &mut R) -> U
where R: RngExt + ?Sized, Self: FakeBase<U>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromDb for T
where T: for<'r> Decode<'r, Sqlite> + Type<Sqlite> + Postgres,

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more