Skip to main content

reifydb_type/value/constraint/
scale.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2025 ReifyDB
3
4use std::fmt::{self, Display, Formatter};
5
6use serde::{Deserialize, Serialize};
7
8use super::precision::Precision;
9use crate::{
10	error::{Error, TypeError},
11	fragment::Fragment,
12};
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
15#[repr(transparent)]
16pub struct Scale(u8);
17
18impl Scale {
19	pub fn new(scale: u8) -> Self {
20		Self(scale)
21	}
22
23	pub fn try_new_with_precision(scale: u8, precision: Precision) -> Result<Self, Error> {
24		if scale > precision.value() {
25			return Err(TypeError::DecimalScaleExceedsPrecision {
26				scale,
27				precision: precision.value(),
28				fragment: Fragment::None,
29			}
30			.into());
31		}
32		Ok(Self(scale))
33	}
34
35	pub fn value(self) -> u8 {
36		self.0
37	}
38
39	pub const MAX: Self = Self(255);
40
41	pub const MIN: Self = Self(0);
42}
43
44impl Display for Scale {
45	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
46		self.0.fmt(f)
47	}
48}
49
50impl From<Scale> for u8 {
51	fn from(scale: Scale) -> Self {
52		scale.0
53	}
54}
55
56impl From<u8> for Scale {
57	fn from(value: u8) -> Self {
58		Self::new(value)
59	}
60}