#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UnknownVariant {
enum_name: &'static str,
value: String,
allowed: &'static [&'static str],
}
impl UnknownVariant {
#[must_use]
pub fn new(enum_name: &'static str, value: impl Into<String>, allowed: &'static [&'static str]) -> Self {
Self { enum_name, value: value.into(), allowed }
}
#[must_use]
pub fn value(&self) -> &str {
&self.value
}
#[must_use]
pub const fn enum_name(&self) -> &'static str {
self.enum_name
}
#[must_use]
pub const fn allowed(&self) -> &'static [&'static str] {
self.allowed
}
}
impl core::fmt::Display for UnknownVariant {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{:?} is not a valid {}; expected one of ", self.value, self.enum_name)?;
for (i, a) in self.allowed.iter().enumerate() {
if i > 0 {
f.write_str(", ")?;
}
write!(f, "{a}")?;
}
Ok(())
}
}
impl std::error::Error for UnknownVariant {}
#[macro_export]
macro_rules! oicp_enum {
(
$(#[$meta:meta])*
$vis:vis enum $name:ident {
$(
$(#[$vmeta:meta])*
$variant:ident = $wire:literal
),* $(,)?
}
) => {
$(#[$meta])*
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
$vis enum $name {
$(
$(#[$vmeta])*
#[doc = concat!("\n\nWire value: `", $wire, "`")]
$variant,
)*
}
#[allow(dead_code)]
impl $name {
pub const ALL: &'static [Self] = &[ $( Self::$variant ),* ];
pub const ALL_WIRE: &'static [&'static str] = &[ $( $wire ),* ];
#[must_use]
pub const fn as_str(&self) -> &'static str {
match self { $( Self::$variant => $wire, )* }
}
#[must_use]
pub fn from_str_ignore_case(s: &str) -> Option<Self> {
$( if s.eq_ignore_ascii_case($wire) { return Some(Self::$variant); } )*
None
}
}
impl core::fmt::Display for $name {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
impl core::str::FromStr for $name {
type Err = $crate::types::UnknownVariant;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
$( $wire => Ok(Self::$variant), )*
other => Err($crate::types::UnknownVariant::new(
stringify!($name), other, Self::ALL_WIRE,
)),
}
}
}
impl $crate::types::Validate for $name {
fn validate_in(&self, _v: &mut $crate::types::Validator) {}
}
impl serde::Serialize for $name {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.as_str())
}
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V;
impl serde::de::Visitor<'_> for V {
type Value = $name;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "one of the {} values of {}", $name::ALL_WIRE.len(), stringify!($name))
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<$name, E> {
<$name as core::str::FromStr>::from_str(v).map_err(E::custom)
}
}
d.deserialize_str(V)
}
}
#[cfg(feature = "schema")]
impl schemars::JsonSchema for $name {
fn schema_name() -> std::borrow::Cow<'static, str> { stringify!($name).into() }
fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({ "type": "string", "enum": Self::ALL_WIRE })
}
}
};
}
#[macro_export]
macro_rules! oicp_open_enum {
(
$(#[$meta:meta])*
$vis:vis enum $name:ident {
$(
$(#[$vmeta:meta])*
$variant:ident = $wire:literal
),* $(,)?
}
) => {
$(#[$meta])*
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
$vis enum $name {
$(
$(#[$vmeta])*
#[doc = concat!("\n\nWire value: `", $wire, "`")]
$variant,
)*
Custom(String),
}
#[allow(dead_code)]
impl $name {
pub const ALL: &'static [Self] = &[ $( Self::$variant ),* ];
pub const ALL_WIRE: &'static [&'static str] = &[ $( $wire ),* ];
#[must_use]
pub fn as_str(&self) -> &str {
match self {
$( Self::$variant => $wire, )*
Self::Custom(s) => s.as_str(),
}
}
#[must_use]
pub fn is_known(&self) -> bool {
!matches!(self, Self::Custom(_))
}
#[must_use]
pub fn from_str_ignore_case(s: &str) -> Self {
$( if s.eq_ignore_ascii_case($wire) { return Self::$variant; } )*
Self::Custom(s.to_owned())
}
}
impl core::fmt::Display for $name {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
impl core::str::FromStr for $name {
type Err = core::convert::Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s {
$( $wire => Self::$variant, )*
other => Self::Custom(other.to_owned()),
})
}
}
impl From<&str> for $name {
fn from(s: &str) -> Self {
match s {
$( $wire => Self::$variant, )*
other => Self::Custom(other.to_owned()),
}
}
}
impl $crate::types::Validate for $name {
fn validate_in(&self, v: &mut $crate::types::Validator) {
if let Self::Custom(value) = self {
v.report(
$crate::types::ViolationCode::PatternMismatch,
format!(
"{value:?} is not one of the {} values OICP 2.3 documents for {}; \
it is preserved, but a peer that has not agreed on it will not \
understand it",
Self::ALL_WIRE.len(), stringify!($name),
),
);
}
}
}
impl serde::Serialize for $name {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.as_str())
}
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V;
impl serde::de::Visitor<'_> for V {
type Value = $name;
fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "a {} value", stringify!($name))
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<$name, E> {
Ok($name::from(v))
}
}
d.deserialize_str(V)
}
}
#[cfg(feature = "schema")]
impl schemars::JsonSchema for $name {
fn schema_name() -> std::borrow::Cow<'static, str> { stringify!($name).into() }
fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({ "type": "string", "examples": Self::ALL_WIRE })
}
}
};
}
#[cfg(test)]
mod tests {
use crate::types::Validate;
oicp_open_enum! {
pub enum Sample {
Alpha = "Alpha",
Beta = "Beta",
}
}
oicp_enum! {
pub enum Closed {
Alpha = "Alpha",
}
}
#[test]
fn open_enum_preserves_unknown_values_byte_for_byte() {
let json = r#""SomethingHubjectAddedLater""#;
let value: Sample = serde_json::from_str(json).unwrap();
assert!(!value.is_known());
assert_eq!(serde_json::to_string(&value).unwrap(), json);
assert_eq!(value.validate().unwrap_err().len(), 1);
}
#[test]
fn open_enum_known_values_validate_clean() {
let value: Sample = serde_json::from_str(r#""Beta""#).unwrap();
assert_eq!(value, Sample::Beta);
assert!(value.validate().is_ok());
}
#[test]
fn closed_enum_rejects_unknown_values() {
assert!(serde_json::from_str::<Closed>(r#""Beta""#).is_err());
}
#[test]
fn case_insensitive_parsing_is_opt_in() {
assert_eq!(Sample::from_str_ignore_case("alpha"), Sample::Alpha);
assert_eq!(Sample::from("alpha"), Sample::Custom("alpha".into()));
}
}