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::{self, Display, Formatter};
5
6use serde::{Deserialize, Serialize};
7
8use crate::error::{Error, TypeError};
9
10/// Precision for a decimal type (minimum 1 total digit)
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
12#[repr(transparent)]
13pub struct Precision(u8);
14
15impl Precision {
16	/// Create a new Precision value
17	///
18	/// # Panics
19	/// Panics if precision is 0
20	pub fn new(precision: u8) -> Self {
21		assert!(precision > 0, "Precision must be at least 1, got {}", precision);
22		Self(precision)
23	}
24
25	/// Create a new Precision value, returning an error if invalid
26	pub fn try_new(precision: u8) -> Result<Self, Error> {
27		if precision == 0 {
28			return Err(TypeError::DecimalPrecisionInvalid {
29				precision,
30			}
31			.into());
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<'_>) -> 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}