reifydb_type/value/constraint/
precision.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 crate::{Error, error::diagnostic::number::decimal_precision_invalid, return_error};
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_error!(decimal_precision_invalid(precision));
29		}
30		Ok(Self(precision))
31	}
32
33	/// Get the precision value
34	pub fn value(self) -> u8 {
35		self.0
36	}
37
38	/// Maximum precision (255 - maximum u8 value)
39	pub const MAX: Self = Self(255);
40
41	/// Minimum precision (1)
42	pub const MIN: Self = Self(1);
43}
44
45impl Display for Precision {
46	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
47		self.0.fmt(f)
48	}
49}
50
51impl From<Precision> for u8 {
52	fn from(precision: Precision) -> Self {
53		precision.0
54	}
55}
56
57impl From<u8> for Precision {
58	fn from(value: u8) -> Self {
59		Self::new(value)
60	}
61}