Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Display, Eq, Hash for Sig #95

Merged
merged 1 commit into from
Oct 26, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion oqs/src/sig.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ macro_rules! implement_sigs {
/// They may not all be enabled
///
/// Optional support for `serde` if that feature is enabled.
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[allow(missing_docs)]
pub enum Algorithm {
Expand Down Expand Up @@ -77,6 +77,15 @@ macro_rules! implement_sigs {
assert!(!Algorithm::$sig.is_enabled())
}
}

#[cfg(not(feature = "no_std"))]
#[test]
fn test_display() {
// Just make sure the Display impl does not panic or crash.
let name = Algorithm::$sig.to_string();
// ... And actually contains something.
assert!(!name.is_empty());
}
}
)*
)
Expand Down Expand Up @@ -160,6 +169,16 @@ impl Algorithm {
pub fn to_id(self) -> *const libc::c_char {
algorithm_to_id(self)
}

/// Returns the algorithm's name as a static Rust string.
///
/// This is the same as the `to_id`, but as a safe Rust string.
#[cfg(not(feature = "no_std"))]
pub fn name(&self) -> &'static str {
// SAFETY: The id from ffi must be a proper null terminated C string
let id = unsafe { CStr::from_ptr(self.to_id()) };
id.to_str().expect("OQS algorithm names must be UTF-8")
}
}

/// Signature scheme
Expand Down Expand Up @@ -188,6 +207,13 @@ impl Drop for Sig {
}
}

#[cfg(not(feature = "no_std"))]
impl std::fmt::Display for Algorithm {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.name().fmt(f)
}
}

impl core::convert::TryFrom<Algorithm> for Sig {
type Error = crate::Error;
fn try_from(alg: Algorithm) -> Result<Sig> {
Expand Down