use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub enum JwsAlgorithm {
#[default]
HS256,
HS384,
HS512,
ES256,
ES384,
RS256,
RS384,
RS512,
PS256,
PS384,
PS512,
EdDSA,
}
impl JwsAlgorithm {
pub const fn as_str(&self) -> &'static str {
match self {
Self::HS256 => "HS256",
Self::HS384 => "HS384",
Self::HS512 => "HS512",
Self::ES256 => "ES256",
Self::ES384 => "ES384",
Self::RS256 => "RS256",
Self::RS384 => "RS384",
Self::RS512 => "RS512",
Self::PS256 => "PS256",
Self::PS384 => "PS384",
Self::PS512 => "PS512",
Self::EdDSA => "EdDSA",
}
}
pub const fn is_symmetric(&self) -> bool {
matches!(self, Self::HS256 | Self::HS384 | Self::HS512)
}
}
impl Display for JwsAlgorithm {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
const ALL: [JwsAlgorithm; 12] = [
JwsAlgorithm::HS256,
JwsAlgorithm::HS384,
JwsAlgorithm::HS512,
JwsAlgorithm::ES256,
JwsAlgorithm::ES384,
JwsAlgorithm::RS256,
JwsAlgorithm::RS384,
JwsAlgorithm::RS512,
JwsAlgorithm::PS256,
JwsAlgorithm::PS384,
JwsAlgorithm::PS512,
JwsAlgorithm::EdDSA,
];
#[test]
fn it_defaults_to_hs256() {
assert_eq!(JwsAlgorithm::default(), JwsAlgorithm::HS256);
}
#[test]
fn it_renders_the_registered_alg_names() {
for alg in ALL {
assert_eq!(alg.to_string(), alg.as_str());
assert_eq!(format!("{alg:?}"), alg.as_str());
}
assert_eq!(JwsAlgorithm::EdDSA.as_str(), "EdDSA");
}
#[test]
fn it_separates_symmetric_from_asymmetric() {
for alg in ALL {
assert_eq!(alg.is_symmetric(), alg.as_str().starts_with("HS"));
}
}
}