icydb_base/validator/
decimal.rs

1use crate::{core::traits::Validator, prelude::*};
2use std::convert::TryInto;
3
4///
5/// MaxDecimalPlaces
6///
7
8#[validator]
9pub struct MaxDecimalPlaces {
10    target: u32,
11}
12
13impl MaxDecimalPlaces {
14    /// Create a new validator with the given maximum number of decimal places.
15    pub fn new<N>(target: N) -> Self
16    where
17        N: TryInto<u32>,
18        N::Error: std::fmt::Debug,
19    {
20        Self {
21            target: target.try_into().expect("invalid number of decimal places"),
22        }
23    }
24}
25
26impl Validator<Decimal> for MaxDecimalPlaces {
27    fn validate(&self, n: &Decimal) -> Result<(), String> {
28        if n.scale() <= self.target {
29            Ok(())
30        } else {
31            let plural = if self.target == 1 { "" } else { "s" };
32
33            Err(format!(
34                "{n} must not have more than {} decimal place{}",
35                self.target, plural
36            ))
37        }
38    }
39}