Skip to main content

icydb_model/base/validator/
decimal.rs

1//! Module: base::validator::decimal
2//!
3//! Responsibility: base validator definitions.
4//! Does not own: normalization policy, persistence, or schema mutation semantics.
5//! Boundary: reports typed visitor issues for facade schema values.
6
7use crate::{prelude::*, visitor::Validator};
8
9///
10/// MaxDecimalPlaces
11///
12/// Enforces an upper bound on fractional precision for `Decimal` values.
13/// Values with a larger scale than `target` are rejected.
14///
15
16#[validator]
17pub struct MaxDecimalPlaces {
18    target: u32,
19    invalid_configuration: bool,
20}
21
22impl MaxDecimalPlaces {
23    /// Configure a precision limit; failed conversion reports an issue on validation.
24    pub fn new(target: impl TryInto<u32>) -> Self {
25        let target = target.try_into().ok();
26        Self {
27            target: target.unwrap_or_default(),
28            invalid_configuration: target.is_none(),
29        }
30    }
31}
32
33impl Validator<Decimal> for MaxDecimalPlaces {
34    fn validate(&self, n: &Decimal, ctx: &mut dyn VisitorContext) {
35        if self.invalid_configuration {
36            ctx.issue("maximum decimal places cannot be represented as u32".to_string());
37            return;
38        }
39        if n.scale() > self.target {
40            ctx.issue(format!(
41                "decimal scale {} must be at most {}",
42                n.scale(),
43                self.target
44            ));
45        }
46    }
47}