proto_types/common/
decimal.rs

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