Skip to main content

Decimal

Struct Decimal 

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

A non-negative fixed-point decimal cost with K decimal places.

Stores an integer number of units of 10^-K in a u64, so Decimal::<2> counts hundredths. Arithmetic is exact integer arithmetic: sums never round and are independent of the summation order, which floats cannot promise. The scale is part of the type, so costs of different scales cannot be mixed by accident.

K ranges from 0 to 19; a larger K is rejected at compile time as soon as a constructor, Decimal::SCALE or formatting is used. The largest representable cost is u64::MAX / 10^K whole units plus the fraction; + overflows like u64 (see the Cost contract).

ⓘ
// 10^20 does not fit into u64.
let _ = search_core::Decimal::<20>::from_raw(1);

Default is zero and, being derived, skips that check; it is harmless because every operation that needs the scale performs it.

Display and Debug both print the decimal value with exactly K fraction digits; FromStr parses it back exactly, rejecting text that would round (see ParseDecimalError).

§Examples

use search_core::{Cost, Decimal};

type Cents = Decimal<2>;

let step = Cents::from_raw(125); // 1.25
let bonus = Cents::from_int(2).unwrap();

assert_eq!(step + bonus, Cents::from_raw(325));
assert_eq!((step + bonus).to_string(), "3.25");
assert!(Cents::ZERO < step);

Implementations§

Source§

impl<const K: u32> Decimal<K>

Source

pub const SCALE: u64

The number of raw units in one whole unit: 10^K.

Referencing it with K > 19 is a compile-time error, because 10^20 exceeds u64.

Source

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

Creates a cost from its raw number of 10^-K units.

Source

pub const fn from_int(whole: u64) -> Option<Self>

Creates the cost of whole full units, or None if whole * 10^K overflows u64.

Source

pub const fn raw(self) -> u64

The raw number of 10^-K units.

Trait Implementations§

Source§

impl<const K: u32> Add for Decimal<K>

Source§

type Output = Decimal<K>

The resulting type after applying the + operator.
Source§

fn add(self, other: Self) -> Self

Performs the + operation. Read more
Source§

impl<const K: u32> Clone for Decimal<K>

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 K: u32> Copy for Decimal<K>

Source§

impl<const K: u32> Cost for Decimal<K>

Source§

const ZERO: Self

The cost of the empty path, and the smallest value of the type.
Source§

fn saturating_add(self, other: Self) -> Self

Adds two costs, saturating at the largest value instead of overflowing. Read more
Source§

fn saturating_times(self, factor: u32) -> Self

Multiplies the cost by a small integer factor, saturating at the largest value. Read more
Source§

impl<const K: u32> CostExt for Decimal<K>

Source§

fn to_f64(self) -> f64

The raw unit count as a float: the value scaled by 10^K.

Priorities only compare quotients and differences of costs of one type, so the common factor 10^K cancels, and dividing it out would only add rounding.

Source§

fn saturating_sub(self, other: Self) -> Self

Subtracts other, saturating at Cost::ZERO. Read more
Source§

impl<const K: u32> Debug for Decimal<K>

Source§

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

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

impl<const K: u32> Default for Decimal<K>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<const K: u32> Display for Decimal<K>

Source§

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

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

impl<const K: u32> Eq for Decimal<K>

Source§

impl<const K: u32> ExactArith for Decimal<K>

Source§

type Exact = BigUint

The raw value, at scale 10^K.

Source§

fn exact(self) -> BigUint

The cost as an exact number.
Source§

impl<const K: u32> FromStr for Decimal<K>

Parses whole or whole.fraction, exactly.

Both parts are plain ASCII digits; leading zeros are fine. The fraction has 1 to K digits, trailing zeros included, so nothing is ever rounded: "1.25" is a Decimal<2> or Decimal<3> but not a Decimal<1>, and Decimal<0> takes integers only.

§Errors

§Examples

use search_core::{Decimal, ParseDecimalError};

assert_eq!("3.25".parse::<Decimal<2>>(), Ok(Decimal::from_raw(325)));
assert_eq!("3.2".parse::<Decimal<2>>(), Ok(Decimal::from_raw(320)));
assert_eq!("7".parse::<Decimal<2>>(), Ok(Decimal::from_raw(700)));
assert_eq!("3.25".parse::<Decimal<1>>(), Err(ParseDecimalError::TooManyFractionDigits));
assert_eq!("-1".parse::<Decimal<2>>(), Err(ParseDecimalError::InvalidDigit));
Source§

type Err = ParseDecimalError

The associated error which can be returned from parsing.
Source§

fn from_str(text: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl<const K: u32> Hash for Decimal<K>

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 K: u32> Ord for Decimal<K>

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 K: u32> PartialEq for Decimal<K>

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 K: u32> PartialOrd for Decimal<K>

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 K: u32> StructuralPartialEq for Decimal<K>

Source§

impl<const K: u32> WideMul for Decimal<K>

Source§

type Wide = u128

The product of the raw values, at scale 10^(2K).

Source§

fn wide_mul(self, other: Self) -> u128

Multiplies two costs into WideMul::Wide.
Source§

fn abs_diff(self, other: Self) -> Self

The distance |self - other|, exact for the integers and Decimal.

Auto Trait Implementations§

§

impl<const K: u32> Forget for Decimal<K>

§

impl<const K: u32> Freeze for Decimal<K>

§

impl<const K: u32> Move for Decimal<K>

§

impl<const K: u32> RefUnwindSafe for Decimal<K>

§

impl<const K: u32> Send for Decimal<K>

§

impl<const K: u32> Sync for Decimal<K>

§

impl<const K: u32> Unpin for Decimal<K>

§

impl<const K: u32> UnsafeUnpin for Decimal<K>

§

impl<const K: u32> UnwindSafe for Decimal<K>

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<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<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> 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.