dup_crypto/
utils.rs

1//  Copyright (C) 2020 Éloïs SANCHEZ.
2//
3// This program is free software: you can redistribute it and/or modify
4// it under the terms of the GNU Affero General Public License as
5// published by the Free Software Foundation, either version 3 of the
6// License, or (at your option) any later version.
7//
8// This program is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11// GNU Affero General Public License for more details.
12//
13// You should have received a copy of the GNU Affero General Public License
14// along with this program.  If not, see <https://www.gnu.org/licenses/>.
15
16//! Common utils
17
18use thiserror::Error;
19
20#[derive(Clone, Copy, Debug, Error)]
21/// U31Error
22#[error("Integer must less than 2^31")]
23pub struct U31Error;
24
25#[derive(Clone, Copy, Debug, Eq, PartialEq)]
26/// Unsigned 31 bits integer
27pub struct U31(u32);
28
29impl U31 {
30    /// New U31 from u32
31    pub fn new(u32_: u32) -> Result<Self, U31Error> {
32        if u32_ < 0x80000000 {
33            Ok(Self(u32_))
34        } else {
35            Err(U31Error)
36        }
37    }
38    #[inline(always)]
39    /// Into u32
40    pub fn into_u32(self) -> u32 {
41        self.0
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn test_u31() {
51        assert!(U31::new(0).is_ok());
52        assert!(U31::new(u32::MAX).is_err());
53        assert!(U31::new(0x80_00_00_00).is_err());
54        assert!(U31::new(0x7F_FF_FF_FF).is_ok());
55    }
56}