use crate::prelude::*;
use super::section::SectionSchema;
use super::validate::{ValidationError, ValidationResult};
use alloc::collections::BTreeMap;
use spin::{Once, RwLock};
#[derive(Debug)]
pub struct SchemaRegistry {
schemas: RwLock<BTreeMap<String, SectionSchema>>,
}
impl SchemaRegistry {
pub fn new() -> Self {
Self {
schemas: RwLock::new(BTreeMap::new()),
}
}
pub fn global() -> &'static Self {
static INSTANCE: Once<SchemaRegistry> = Once::new();
INSTANCE.call_once(|| {
let registry = SchemaRegistry::new();
super::official::register_official_schemas(®istry);
registry
})
}
pub fn register(&self, schema: SectionSchema) {
let mut schemas = self.schemas.write();
schemas.insert(schema.name.clone(), schema);
}
pub fn get(&self, name: &str) -> ValidationResult<SectionSchema> {
let schemas = self.schemas.read();
schemas
.get(name)
.cloned()
.ok_or_else(|| ValidationError::UnknownSection {
name: name.to_string(),
})
}
pub fn list(&self) -> Vec<String> {
let schemas = self.schemas.read();
schemas.keys().cloned().collect()
}
}
impl Default for SchemaRegistry {
fn default() -> Self {
Self::new()
}
}
pub type UserRegistry = SchemaRegistry;