Skip to main content

reifydb_type/value/constraint/
precision.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (c) 2025 ReifyDB
3
4use std::fmt::{Display, Formatter};
5
6use serde::{Deserialize, Serialize};
7
8use crate::{
9	error::{Error, diagnostic::number::decimal_precision_invalid},
10	return_error,
11};
12
13/// Precision for a decimal type (minimum 1 total digit)
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
15#[repr(transparent)]
16pub struct Precision(u8);
17
18impl Precision {
19	/// Create a new Precision value
20	///
21	/// # Panics
22	/// Panics if precision is 0
23	pub fn new(precision: u8) -> Self {
24		assert!(precision > 0, "Precision must be at least 1, got {}", precision);
25		Self(precision)
26	}
27
28	/// Create a new Precision value, returning an error if invalid
29	pub fn try_new(precision: u8) -> Result<Self, Error> {
30		if precision == 0 {
31			return_error!(decimal_precision_invalid(precision));
32		}
33		Ok(Self(precision))
34	}
35
36	/// Get the precision value
37	pub fn value(self) -> u8 {
38		self.0
39	}
40
41	/// Maximum precision (255 - maximum u8 value)
42	pub const MAX: Self = Self(255);
43
44	/// Minimum precision (1)
45	pub const MIN: Self = Self(1);
46}
47
48impl Display for Precision {
49	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
50		self.0.fmt(f)
51	}
52}
53
54impl From<Precision> for u8 {
55	fn from(precision: Precision) -> Self {
56		precision.0
57	}
58}
59
60impl From<u8> for Precision {
61	fn from(value: u8) -> Self {
62		Self::new(value)
63	}
64}