interplane-mv
INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.
Brought by drakestapleton
interplane-mv / rust / crates / interplane-core / src / macros.rs
| 1 | /// A string enum that keeps unknown values as `Unknown(String)`. |
| 2 | macro_rules! string_enum { |
| 3 | ($(#[$m:meta])* $name:ident { $($var:ident => $s:literal),+ $(,)? }) => { |
| 4 | $(#[$m])* |
| 5 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 6 | pub enum $name { |
| 7 | $($var,)+ |
| 8 | /// A value this implementation does not know. |
| 9 | Unknown(String), |
| 10 | } |
| 11 | impl $name { |
| 12 | /// The wire string. |
| 13 | pub fn as_str(&self) -> &str { |
| 14 | match self { $(Self::$var => $s,)+ Self::Unknown(s) => s } |
| 15 | } |
| 16 | /// Parse a wire string; unknown strings become `Unknown`. |
| 17 | pub fn parse(s: &str) -> Self { |
| 18 | match s { $($s => Self::$var,)+ other => Self::Unknown(other.to_string()) } |
| 19 | } |
| 20 | /// True unless this is `Unknown`. |
| 21 | pub fn is_known(&self) -> bool { !matches!(self, Self::Unknown(_)) } |
| 22 | } |
| 23 | impl std::fmt::Display for $name { |
| 24 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) } |
| 25 | } |
| 26 | impl serde::Serialize for $name { |
| 27 | fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { s.serialize_str(self.as_str()) } |
| 28 | } |
| 29 | impl<'de> serde::Deserialize<'de> for $name { |
| 30 | fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> { |
| 31 | let s = <String as serde::Deserialize>::deserialize(d)?; |
| 32 | Ok(Self::parse(&s)) |
| 33 | } |
| 34 | } |
| 35 | }; |
| 36 | } |
| 37 | |
| 38 | /// A unit type that serializes to a constant `kind` string and refuses any other. |
| 39 | macro_rules! const_kind { |
| 40 | ($(#[$m:meta])* $name:ident, $lit:literal) => { |
| 41 | $(#[$m])* |
| 42 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 43 | pub struct $name; |
| 44 | impl serde::Serialize for $name { |
| 45 | fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { s.serialize_str($lit) } |
| 46 | } |
| 47 | impl<'de> serde::Deserialize<'de> for $name { |
| 48 | fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> { |
| 49 | let s = <String as serde::Deserialize>::deserialize(d)?; |
| 50 | if s == $lit { Ok($name) } else { |
| 51 | Err(serde::de::Error::custom(format!("expected kind {:?}, got {:?}", $lit, s))) |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | }; |
| 56 | } |