Skip to main content

Decimal

Struct Decimal 

Source
pub struct Decimal { /* private fields */ }
Expand description

An arbitrary precision decimal number stored as sortable bytes.

The internal byte representation is designed to be lexicographically sortable, meaning that comparing the bytes directly yields the same result as comparing the numerical values. This enables efficient range queries in databases.

§Storage Efficiency

The encoding uses:

  • 1 byte for the sign
  • Variable bytes for the exponent (typically 1-3 bytes)
  • 4 bits per decimal digit (BCD encoding, 2 digits per byte)

Implementations§

Source§

impl Decimal

Source

pub fn with_precision_scale( s: &str, precision: Option<u32>, scale: Option<i32>, ) -> Result<Self, DecimalError>

Creates a new Decimal with precision and scale constraints.

Values that exceed the constraints are truncated/rounded to fit. This is compatible with SQL NUMERIC(precision, scale) semantics.

  • precision: Maximum total number of significant digits (None = unlimited)
  • scale: Digits after decimal point; negative values round to left of decimal
§PostgreSQL Compatibility

Supports negative scale (rounds to powers of 10):

  • scale = -3 rounds to nearest 1000
  • NUMERIC(2, -3) allows values like -99000 to 99000
§Examples
use decimal_bytes::Decimal;

// NUMERIC(5, 2) - up to 5 digits total, 2 after decimal
let d = Decimal::with_precision_scale("123.456", Some(5), Some(2)).unwrap();
assert_eq!(d.to_string(), "123.46"); // Rounded to 2 decimal places

// NUMERIC(2, -3) - rounds to nearest 1000, max 2 significant digits
let d = Decimal::with_precision_scale("12345", Some(2), Some(-3)).unwrap();
assert_eq!(d.to_string(), "12000"); // Rounded to nearest 1000
Source

pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecimalError>

Creates a Decimal from raw bytes.

The bytes must be a valid encoding produced by as_bytes(). Returns an error if the bytes are invalid.

§Examples
use decimal_bytes::Decimal;
use std::str::FromStr;

let original = Decimal::from_str("123.456").unwrap();
let bytes = original.as_bytes();
let restored = Decimal::from_bytes(bytes).unwrap();
assert_eq!(original, restored);
Source

pub fn from_bytes_unchecked(bytes: Vec<u8>) -> Self

Creates a Decimal from raw bytes without validation.

§Safety

The caller must ensure the bytes are a valid encoding. Using invalid bytes may cause panics or incorrect results.

Source

pub fn as_bytes(&self) -> &[u8]

Returns the raw byte representation.

These bytes are lexicographically sortable - comparing them directly yields the same result as comparing the numerical values.

Source

pub fn into_bytes(self) -> Vec<u8>

Consumes the Decimal and returns the underlying bytes.

Source

pub fn is_zero(&self) -> bool

Returns true if this decimal represents zero.

Source

pub fn is_negative(&self) -> bool

Returns true if this decimal is negative.

Source

pub fn is_positive(&self) -> bool

Returns true if this decimal is positive (and not zero).

Source

pub fn is_pos_infinity(&self) -> bool

Returns true if this decimal represents positive infinity.

Source

pub fn is_neg_infinity(&self) -> bool

Returns true if this decimal represents negative infinity.

Source

pub fn is_infinity(&self) -> bool

Returns true if this decimal represents positive or negative infinity.

Source

pub fn is_nan(&self) -> bool

Returns true if this decimal represents NaN (Not a Number).

Source

pub fn is_special(&self) -> bool

Returns true if this decimal is a special value (Infinity or NaN).

Source

pub fn is_finite(&self) -> bool

Returns true if this decimal is a finite number (not Infinity or NaN).

Source

pub fn byte_len(&self) -> usize

Returns the number of bytes used to store this decimal.

Source

pub fn infinity() -> Self

Creates positive infinity.

Infinity is greater than all finite numbers but less than NaN. Two positive infinities are equal to each other.

§Example
use decimal_bytes::Decimal;
use std::str::FromStr;

let inf = Decimal::infinity();
let big = Decimal::from_str("999999999999").unwrap();
assert!(inf > big);
assert_eq!(inf, Decimal::infinity());
Source

pub fn neg_infinity() -> Self

Creates negative infinity.

Negative infinity is less than all finite numbers and positive infinity. Two negative infinities are equal to each other.

§Example
use decimal_bytes::Decimal;
use std::str::FromStr;

let neg_inf = Decimal::neg_infinity();
let small = Decimal::from_str("-999999999999").unwrap();
assert!(neg_inf < small);
assert_eq!(neg_inf, Decimal::neg_infinity());
Source

pub fn nan() -> Self

Creates NaN (Not a Number).

§PostgreSQL Semantics

Unlike IEEE 754 floating-point where NaN != NaN, this follows PostgreSQL semantics where:

  • NaN == NaN is true
  • NaN is the greatest value (greater than positive infinity)
  • All NaN values are equal regardless of how they were created

This makes NaN usable in sorting, indexing, and deduplication.

§Example
use decimal_bytes::Decimal;
use std::str::FromStr;

let nan1 = Decimal::nan();
let nan2 = Decimal::from_str("NaN").unwrap();
let inf = Decimal::infinity();

// NaN equals itself (PostgreSQL behavior)
assert_eq!(nan1, nan2);

// NaN is greater than everything
assert!(nan1 > inf);

Trait Implementations§

Source§

impl Clone for Decimal

Source§

fn clone(&self) -> Decimal

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for Decimal

Source§

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

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

impl Default for Decimal

Source§

fn default() -> Self

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

impl<'de> Deserialize<'de> for Decimal

Source§

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

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Decimal

Source§

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

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

impl From<i128> for Decimal

Source§

fn from(val: i128) -> Self

Converts to this type from the input type.
Source§

impl From<i16> for Decimal

Source§

fn from(val: i16) -> Self

Converts to this type from the input type.
Source§

impl From<i32> for Decimal

Source§

fn from(val: i32) -> Self

Converts to this type from the input type.
Source§

impl From<i64> for Decimal

Source§

fn from(val: i64) -> Self

Converts to this type from the input type.
Source§

impl From<i8> for Decimal

Source§

fn from(val: i8) -> Self

Converts to this type from the input type.
Source§

impl From<u128> for Decimal

Source§

fn from(val: u128) -> Self

Converts to this type from the input type.
Source§

impl From<u16> for Decimal

Source§

fn from(val: u16) -> Self

Converts to this type from the input type.
Source§

impl From<u32> for Decimal

Source§

fn from(val: u32) -> Self

Converts to this type from the input type.
Source§

impl From<u64> for Decimal

Source§

fn from(val: u64) -> Self

Converts to this type from the input type.
Source§

impl From<u8> for Decimal

Source§

fn from(val: u8) -> Self

Converts to this type from the input type.
Source§

impl FromStr for Decimal

Source§

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

Creates a new Decimal from a string representation.

§Examples
use decimal_bytes::Decimal;
use std::str::FromStr;

let d = Decimal::from_str("123.456").unwrap();
let d = Decimal::from_str("-0.001").unwrap();
let d = Decimal::from_str("1e10").unwrap();
// Or use parse:
let d: Decimal = "42.5".parse().unwrap();
Source§

type Err = DecimalError

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

impl Hash for Decimal

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 Ord for Decimal

Source§

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

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

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

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

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

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

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

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

impl PartialEq for Decimal

Source§

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

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PartialOrd for Decimal

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 · 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 · 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 · 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 · 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 Serialize for Decimal

Source§

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

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for Decimal

Auto Trait Implementations§

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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,