Skip to content

Commit 4862ffb

Browse files
EcoFreshKaseAlexander Jablonowski
andauthored
feat: implement FromStr for Algorithm Enums (#292)
Signed-off-by: Alexander Jablonowski <[email protected]> Co-authored-by: Alexander Jablonowski <[email protected]>
1 parent 5927a86 commit 4862ffb

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

oqs/src/kem.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use alloc::vec::Vec;
66

77
use core::ptr::NonNull;
8+
use core::str::FromStr;
89

910
#[cfg(not(feature = "std"))]
1011
use cstr_core::CStr;
@@ -50,6 +51,19 @@ macro_rules! implement_kems {
5051
id as *const _ as *const libc::c_char
5152
}
5253

54+
impl FromStr for Algorithm {
55+
type Err = crate::Error;
56+
57+
fn from_str(s: &str) -> Result<Self> {
58+
$(
59+
if s == Algorithm::$kem.name() {
60+
return Ok(Algorithm::$kem);
61+
}
62+
)*
63+
Err(crate::Error::AlgorithmParsingError)
64+
}
65+
}
66+
5367
$(
5468
#[cfg(test)]
5569
#[allow(non_snake_case)]
@@ -139,6 +153,14 @@ macro_rules! implement_kems {
139153
assert!(!version.is_empty());
140154
}
141155
}
156+
157+
#[test]
158+
fn test_from_str() {
159+
let algorithm = Algorithm::$kem;
160+
let name = algorithm.name();
161+
let parsed = Algorithm::from_str(name).unwrap();
162+
assert_eq!(algorithm, parsed);
163+
}
142164
}
143165
)*
144166
)

oqs/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,8 @@ pub enum Error {
8989
ErrorExternalOpenSSL,
9090
/// Invalid length of a public object
9191
InvalidLength,
92+
/// Error while trying to parse string to an algorithm
93+
AlgorithmParsingError,
9294
}
9395
#[cfg(feature = "std")]
9496
impl std::error::Error for Error {}

oqs/src/sig.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use alloc::vec::Vec;
66

77
use core::ptr::{null, NonNull};
8+
use core::str::FromStr;
89

910
#[cfg(not(feature = "std"))]
1011
use cstr_core::CStr;
@@ -52,6 +53,19 @@ macro_rules! implement_sigs {
5253
id as *const _ as *const libc::c_char
5354
}
5455

56+
impl FromStr for Algorithm {
57+
type Err = crate::Error;
58+
59+
fn from_str(s: &str) -> Result<Self> {
60+
$(
61+
if s == Algorithm::$sig.name() {
62+
return Ok(Algorithm::$sig);
63+
}
64+
)*
65+
Err(crate::Error::AlgorithmParsingError)
66+
}
67+
}
68+
5569
$(
5670
#[cfg(test)]
5771
#[allow(non_snake_case)]
@@ -157,6 +171,13 @@ macro_rules! implement_sigs {
157171
assert!(!version.is_empty());
158172
}
159173
}
174+
175+
#[test]
176+
fn test_from_str() {
177+
let algorithm = Algorithm::$sig;
178+
let name = algorithm.name();
179+
let parsed = Algorithm::from_str(name).unwrap();
180+
assert_eq!(algorithm, parsed);}
160181
}
161182
)*
162183
)

0 commit comments

Comments
 (0)