argon2/
version.rs

1// Copyright (c) 2017 Martijn Rijkeboer <[email protected]>
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use crate::error::Error;
10use crate::result::Result;
11use std::fmt;
12
13/// The Argon2 version.
14#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
15pub enum Version {
16    /// Version 0x10.
17    Version10 = 0x10,
18
19    /// Version 0x13 (Recommended).
20    Version13 = 0x13,
21}
22
23impl Version {
24    /// Gets the u32 representation of the version.
25    pub fn as_u32(&self) -> u32 {
26        *self as u32
27    }
28
29    /// Attempts to create a version from a string slice.
30    pub fn from_str(str: &str) -> Result<Version> {
31        match str {
32            "16" => Ok(Version::Version10),
33            "19" => Ok(Version::Version13),
34            _ => Err(Error::DecodingFail),
35        }
36    }
37
38    /// Attempts to create a version from an u32.
39    pub fn from_u32(val: u32) -> Result<Version> {
40        match val {
41            0x10 => Ok(Version::Version10),
42            0x13 => Ok(Version::Version13),
43            _ => Err(Error::IncorrectVersion),
44        }
45    }
46}
47
48impl Default for Version {
49    fn default() -> Version {
50        Version::Version13
51    }
52}
53
54impl fmt::Display for Version {
55    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56        write!(f, "{}", self.as_u32())
57    }
58}
59
60#[cfg(test)]
61mod tests {
62
63    use crate::error::Error;
64    use crate::version::Version;
65
66    #[test]
67    fn as_u32_returns_correct_u32() {
68        assert_eq!(Version::Version10.as_u32(), 0x10);
69        assert_eq!(Version::Version13.as_u32(), 0x13);
70    }
71
72    #[test]
73    fn default_returns_correct_version() {
74        assert_eq!(Version::default(), Version::Version13);
75    }
76
77    #[test]
78    fn display_returns_correct_string() {
79        assert_eq!(format!("{}", Version::Version10), "16");
80        assert_eq!(format!("{}", Version::Version13), "19");
81    }
82
83    #[test]
84    fn from_str_returns_correct_result() {
85        assert_eq!(Version::from_str("16"), Ok(Version::Version10));
86        assert_eq!(Version::from_str("19"), Ok(Version::Version13));
87        assert_eq!(Version::from_str("11"), Err(Error::DecodingFail));
88    }
89
90    #[test]
91    fn from_u32_returns_correct_result() {
92        assert_eq!(Version::from_u32(0x10), Ok(Version::Version10));
93        assert_eq!(Version::from_u32(0x13), Ok(Version::Version13));
94        assert_eq!(Version::from_u32(0), Err(Error::IncorrectVersion));
95    }
96}