reifydb_type/value/constraint/
precision.rs1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
15#[repr(transparent)]
16pub struct Precision(u8);
17
18impl Precision {
19 pub fn new(precision: u8) -> Self {
24 assert!(precision > 0, "Precision must be at least 1, got {}", precision);
25 Self(precision)
26 }
27
28 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 pub fn value(self) -> u8 {
38 self.0
39 }
40
41 pub const MAX: Self = Self(255);
43
44 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}