reifydb_type/value/constraint/
scale.rs

1// Copyright (c) reifydb.com 2025
2// This file is licensed under the AGPL-3.0-or-later, see license.md file
3
4use std::fmt::{Display, Formatter};
5
6use serde::{Deserialize, Serialize};
7
8use super::precision::Precision;
9use crate::{Error, OwnedFragment, error::diagnostic::number::decimal_scale_exceeds_precision, return_error};
10
11/// Scale for a decimal type (decimal places)
12#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
13#[repr(transparent)]
14pub struct Scale(u8);
15
16impl Scale {
17	/// Create a new Scale value
18	pub fn new(scale: u8) -> Self {
19		Self(scale)
20	}
21
22	/// Create a new Scale value with validation against precision
23	pub fn try_new_with_precision(scale: u8, precision: Precision) -> Result<Self, Error> {
24		if scale > precision.value() {
25			return_error!(decimal_scale_exceeds_precision(OwnedFragment::None, scale, precision.value()));
26		}
27		Ok(Self(scale))
28	}
29
30	/// Get the scale value
31	pub fn value(self) -> u8 {
32		self.0
33	}
34
35	/// Maximum scale (255 - maximum u8 value)
36	pub const MAX: Self = Self(255);
37
38	/// Minimum scale (0)
39	pub const MIN: Self = Self(0);
40}
41
42impl Display for Scale {
43	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
44		self.0.fmt(f)
45	}
46}
47
48impl From<Scale> for u8 {
49	fn from(scale: Scale) -> Self {
50		scale.0
51	}
52}
53
54impl From<u8> for Scale {
55	fn from(value: u8) -> Self {
56		Self::new(value)
57	}
58}