use std::fmt;
use serde_json::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MetadataValueKind {
Null,
Bool,
Number,
String,
Array,
Object,
}
impl MetadataValueKind {
#[inline]
pub fn of(value: &Value) -> Self {
match value {
Value::Null => Self::Null,
Value::Bool(_) => Self::Bool,
Value::Number(_) => Self::Number,
Value::String(_) => Self::String,
Value::Array(_) => Self::Array,
Value::Object(_) => Self::Object,
}
}
}
impl From<&Value> for MetadataValueKind {
#[inline]
fn from(value: &Value) -> Self {
Self::of(value)
}
}
impl fmt::Display for MetadataValueKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let text = match self {
Self::Null => "null",
Self::Bool => "bool",
Self::Number => "number",
Self::String => "string",
Self::Array => "array",
Self::Object => "object",
};
f.write_str(text)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MetadataError {
MissingKey(String),
SerializationError {
key: String,
message: String,
},
DeserializationError {
key: String,
expected: &'static str,
actual: MetadataValueKind,
message: String,
},
}
impl MetadataError {
#[inline]
pub(crate) fn deserialization_error<T>(
key: &str,
value: &Value,
error: serde_json::Error,
) -> Self {
Self::DeserializationError {
key: key.to_string(),
expected: std::any::type_name::<T>(),
actual: MetadataValueKind::of(value),
message: error.to_string(),
}
}
#[inline]
pub(crate) fn serialization_error(key: String, error: serde_json::Error) -> Self {
Self::SerializationError {
key,
message: error.to_string(),
}
}
}
impl fmt::Display for MetadataError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingKey(key) => write!(f, "Metadata key not found: {key}"),
Self::SerializationError { key, message } => {
write!(f, "Failed to serialize metadata value for key '{key}': {message}")
}
Self::DeserializationError {
key,
expected,
actual,
message,
} => write!(
f,
"Failed to deserialize metadata key '{key}' as {expected} from JSON {actual}: {message}"
),
}
}
}
impl std::error::Error for MetadataError {}
pub type MetadataResult<T> = Result<T, MetadataError>;