Skip to main content

co_primitives/macros/
serde_string_enum.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2026 1io BRANDGUARDIAN GmbH
3
4/// Adds display and to_string implementation to serde enum types.
5#[macro_export]
6macro_rules! serde_string_enum {
7	($t: ident) => {
8		impl std::fmt::Display for $t {
9			fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10				write!(
11					f,
12					"{}",
13					serde_json::to_value(self)
14						.expect("$t to serialize")
15						.as_str()
16						.expect("$t to serialize to string")
17				)
18			}
19		}
20		impl TryFrom<String> for $t {
21			type Error = serde_json::error::Error;
22			fn try_from(value: String) -> Result<Self, Self::Error> {
23				serde_json::from_value(serde_json::Value::String(value))
24			}
25		}
26		impl TryFrom<&str> for $t {
27			type Error = serde_json::error::Error;
28			fn try_from(value: &str) -> Result<Self, Self::Error> {
29				serde_json::from_value(serde_json::Value::String(value.to_owned()))
30			}
31		}
32	};
33}