decaf377_fmd/
precision.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use core::fmt;

use crate::Error;

/// The maximum detection precision, chosen so that the message bits fit in 3 bytes.
pub(crate) const MAX_PRECISION: u8 = 24;

/// Represents the precision governing the false positive rate of detection.
///
/// This is usually measured in bits, where a precision of `n` bits yields false
/// positives with a rate of `2^-n`.
///
/// This type implements `TryFrom` for `u8`, `u32`, `u64`, and `i32`, which has the behavior of considering
/// the value as a number of bits, and converting if this number isn't too large.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Precision(u8);

impl Precision {
    pub const MAX: Precision = Precision(MAX_PRECISION);

    pub fn new(precision_bits: u8) -> Result<Self, Error> {
        if precision_bits > MAX_PRECISION {
            return Err(Error::PrecisionTooLarge(precision_bits.into()));
        }
        Ok(Self(precision_bits))
    }

    pub fn bits(&self) -> u8 {
        self.0
    }
}

impl Default for Precision {
    fn default() -> Self {
        Self(0)
    }
}

impl fmt::Display for Precision {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl TryFrom<u8> for Precision {
    type Error = Error;

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl TryFrom<u32> for Precision {
    type Error = Error;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        u8::try_from(value)
            .map_err(|_| Error::PrecisionTooLarge(value.into()))?
            .try_into()
    }
}

impl TryFrom<u64> for Precision {
    type Error = Error;

    fn try_from(value: u64) -> Result<Self, Self::Error> {
        u8::try_from(value)
            .map_err(|_| Error::PrecisionTooLarge(value))?
            .try_into()
    }
}

impl TryFrom<i32> for Precision {
    type Error = Error;

    fn try_from(value: i32) -> Result<Self, Self::Error> {
        u8::try_from(value)
            .map_err(|_| Error::PrecisionTooLarge(value as u64))?
            .try_into()
    }
}