Skip to main content

proto_types/common/
decimal.rs

1use crate::{String, ToString, common::Decimal};
2
3impl Decimal {
4	#[must_use]
5	#[inline]
6	pub const fn new(value: String) -> Self {
7		Self { value }
8	}
9}
10
11impl Display for Decimal {
12	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
13		write!(f, "{}", self.value)
14	}
15}
16
17use core::{fmt::Display, str::FromStr};
18
19use rust_decimal::Decimal as RustDecimal;
20use thiserror::Error;
21
22/// Errors that can occur during the creation, conversion or validation of a [`Decimal`].
23#[derive(Debug, Error, PartialEq, Eq, Clone)]
24#[non_exhaustive]
25pub enum DecimalError {
26	#[error("Invalid decimal format: {0}")]
27	InvalidFormat(String),
28}
29
30impl TryFrom<Decimal> for RustDecimal {
31	type Error = DecimalError;
32	fn try_from(value: Decimal) -> Result<Self, Self::Error> {
33		Self::from_str(&value.value).map_err(|e| DecimalError::InvalidFormat(e.to_string()))
34	}
35}
36
37impl From<RustDecimal> for Decimal {
38	fn from(value: RustDecimal) -> Self {
39		Self {
40			value: value.to_string(),
41		}
42	}
43}