Skip to main content

mgrs_convert/
precision.rs

1//! The validated digit-pair count.
2//!
3//! Mechanism M3: invalid precision is unrepresentable. Every function that takes
4//! a precision takes this type, so the range check happens once, at the edge.
5
6#![deny(clippy::arithmetic_side_effects)]
7
8use crate::error::Error;
9
10/// Digit pairs in an MGRS reference, 0 through 11. Cell size is 10^(5-p) metres:
11/// 100 km at 0, 1 m at 5, 1 mm at 8, 1 um at 11.
12#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
13pub struct Precision(u8);
14
15impl Precision {
16    /// The finest supported precision, 11 digit pairs, a 1 um cell.
17    pub const MAX: Precision = Precision(11);
18
19    /// Five digit pairs, a 1 m cell. The overwhelmingly common case.
20    pub const ONE_METER: Precision = Precision(5);
21
22    /// Validates a digit-pair count. Values above 11 are rejected.
23    ///
24    /// ```
25    /// use mgrs_convert::{Error, Precision};
26    /// assert_eq!(Precision::new(5), Ok(Precision::ONE_METER));
27    /// assert_eq!(Precision::new(12), Err(Error::PrecisionOutOfRange { found: 12 }));
28    /// ```
29    pub fn new(digits: u8) -> Result<Precision, Error> {
30        if digits <= 11 {
31            Ok(Precision(digits))
32        } else {
33            Err(Error::PrecisionOutOfRange { found: digits })
34        }
35    }
36
37    /// The digit-pair count, 0 through 11.
38    pub fn get(self) -> u8 {
39        self.0
40    }
41}