use std::collections::HashMap;
use compact_str::CompactString;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Extensions(HashMap<CompactString, ExtensionEntry>);
impl Extensions {
#[must_use]
pub fn new() -> Self {
Self(HashMap::new())
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
#[must_use]
pub fn get(&self, id: &str) -> Option<&ExtensionEntry> {
self.0.get(id)
}
pub fn insert(&mut self, id: impl Into<CompactString>, entry: ExtensionEntry) {
let _ = self.0.insert(id.into(), entry);
}
#[must_use]
pub fn remove(&mut self, id: &str) -> Option<ExtensionEntry> {
self.0.remove(id)
}
pub fn iter(&self) -> impl Iterator<Item = (&CompactString, &ExtensionEntry)> {
self.0.iter()
}
}
impl<K, V> FromIterator<(K, V)> for Extensions
where
K: Into<CompactString>,
V: Into<ExtensionEntry>,
{
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
Self(
iter.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect(),
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ExtensionEntry {
Structured {
info: Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
schema: Option<Value>,
},
Raw(Value),
}
impl ExtensionEntry {
#[must_use]
pub const fn info(info: Value) -> Self {
Self::Structured { info, schema: None }
}
#[must_use]
pub const fn with_schema(info: Value, schema: Value) -> Self {
Self::Structured {
info,
schema: Some(schema),
}
}
#[must_use]
pub const fn raw(value: Value) -> Self {
Self::Raw(value)
}
#[must_use]
pub const fn as_info(&self) -> Option<&Value> {
match self {
Self::Structured { info, .. } => Some(info),
Self::Raw(_) => None,
}
}
#[must_use]
pub const fn as_schema(&self) -> Option<&Value> {
match self {
Self::Structured { schema, .. } => schema.as_ref(),
Self::Raw(_) => None,
}
}
#[must_use]
pub fn to_value(&self) -> Value {
match self {
Self::Structured { info, schema } => {
let mut obj = serde_json::Map::new();
let _ = obj.insert("info".to_owned(), info.clone());
if let Some(schema) = schema {
let _ = obj.insert("schema".to_owned(), schema.clone());
}
Value::Object(obj)
}
Self::Raw(value) => value.clone(),
}
}
}
impl From<Value> for ExtensionEntry {
fn from(value: Value) -> Self {
Self::Raw(value)
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn extensions_empty_by_default() {
let ext = Extensions::new();
assert!(ext.is_empty());
assert_eq!(serde_json::to_value(&ext).unwrap(), json!({}));
}
#[test]
fn structured_entry_roundtrip() {
let mut ext = Extensions::new();
ext.insert(
"bazaar",
ExtensionEntry::with_schema(json!({"registered": true}), json!({"type": "object"})),
);
let encoded = serde_json::to_value(&ext).unwrap();
assert_eq!(encoded["bazaar"]["info"]["registered"], true);
assert_eq!(encoded["bazaar"]["schema"]["type"], "object");
let decoded: Extensions = serde_json::from_value(encoded).unwrap();
assert_eq!(decoded, ext);
}
#[test]
fn raw_entry_roundtrip() {
let mut ext = Extensions::new();
ext.insert("custom", ExtensionEntry::raw(json!([1, 2, 3])));
let encoded = serde_json::to_value(&ext).unwrap();
assert_eq!(encoded["custom"], json!([1, 2, 3]));
let decoded: Extensions = serde_json::from_value(encoded).unwrap();
assert_eq!(decoded, ext);
}
}