use std::{
collections::HashMap,
sync::{Arc, OnceLock},
};
use crate::handler::{ContainerHandler, FormatSpec, DETECT_LEN};
fn normalize(format: &str) -> String {
format.trim().trim_start_matches('.').to_ascii_lowercase()
}
#[derive(Debug, Default, Clone)]
pub struct HandlerRegistry {
by_format: HashMap<String, Arc<dyn ContainerHandler>>,
ordered: Vec<Arc<dyn ContainerHandler>>,
}
impl HandlerRegistry {
pub fn new() -> Self {
Self::default()
}
pub fn builtin() -> Arc<Self> {
static BUILTIN: OnceLock<Arc<HandlerRegistry>> = OnceLock::new();
Arc::clone(BUILTIN.get_or_init(|| {
let mut registry = Self::new();
crate::containers::register_builtin(&mut registry);
Arc::new(registry)
}))
}
pub fn with_builtin() -> Self {
Self::builtin().as_ref().clone()
}
pub fn with_handler(mut self, handler: impl ContainerHandler + 'static) -> Self {
self.add_handler(handler);
self
}
pub fn with_handlers(
mut self,
handlers: impl IntoIterator<Item = Arc<dyn ContainerHandler>>,
) -> Self {
self.extend(handlers);
self
}
pub fn extend_from(&mut self, other: &HandlerRegistry) {
self.extend(other.ordered.iter().cloned());
}
pub fn add_handler(&mut self, handler: impl ContainerHandler + 'static) {
self.add_arc(Arc::new(handler));
}
pub fn add_arc(&mut self, handler: Arc<dyn ContainerHandler>) {
for spec in handler.formats() {
for f in spec.format_strings() {
self.by_format.insert(normalize(f), handler.clone());
}
}
self.ordered.retain(|h| !Arc::ptr_eq(h, &handler));
self.ordered.push(handler);
}
pub fn handlers(&self) -> impl Iterator<Item = &Arc<dyn ContainerHandler>> {
self.ordered.iter()
}
pub fn handler(&self, format: &str) -> Option<&Arc<dyn ContainerHandler>> {
self.by_format.get(&normalize(format))
}
pub fn container_for(&self, format: &str) -> Option<&'static str> {
Some(self.handler(format)?.id())
}
pub fn format_for(&self, format: &str) -> Option<&FormatSpec> {
let key = normalize(format);
self.by_format
.get(&key)?
.formats()
.iter()
.find(|spec| spec.format_strings().any(|f| normalize(f) == key))
}
pub fn media_type_for(&self, format: &str) -> Option<&'static str> {
self.format_for(format).map(|spec| spec.media_type)
}
pub fn extension_for(&self, format: &str) -> Option<&'static str> {
self.format_for(format).map(|spec| spec.extension)
}
pub fn detect(&self, header: &[u8]) -> Option<&Arc<dyn ContainerHandler>> {
let header = &header[..header.len().min(DETECT_LEN)];
self.ordered.iter().rev().find(|h| h.detect(header))
}
pub fn formats(&self) -> Vec<String> {
let mut v: Vec<String> = self.by_format.keys().cloned().collect();
v.sort();
v
}
}
impl Extend<Arc<dyn ContainerHandler>> for HandlerRegistry {
fn extend<I: IntoIterator<Item = Arc<dyn ContainerHandler>>>(&mut self, handlers: I) {
for handler in handlers {
self.add_arc(handler);
}
}
}
#[cfg(test)]
mod tests {
use std::{borrow::Cow, io::Cursor};
use super::*;
use crate::{
container_api::{BoxFuture, ContainerHandler, ReadSeek, StructureBuilder},
io::Io,
segment::SegmentKind,
Error, Name, Result, Sink, Structure, Updates,
};
#[derive(Debug)]
struct Toy;
impl ContainerHandler for Toy {
fn id(&self) -> &'static str {
"toy"
}
fn formats(&self) -> &[FormatSpec] {
const F: &[FormatSpec] = &[FormatSpec::new("application/x-toy", "toy")];
F
}
fn detect(&self, header: &[u8]) -> bool {
header.starts_with(b"TOY!")
}
fn parse_async(self: Arc<Self>, mut io: Io) -> BoxFuture<'static, Result<Structure>> {
Box::pin(async move {
let data = io.read_vec(0, io.len() as usize).await?;
let mut b = StructureBuilder::new(self, "application/x-toy", data.len() as u64);
b.push_span(SegmentKind::Preamble, Name::FourCC(*b"TOY!"), 4, 0, 0)?;
let mut at = 4usize;
let mut idx = 0u64;
while at < data.len() {
let len = data[at] as usize;
if at + 1 + len > data.len() {
return Err(Error::InvalidFormat("toy record overruns".into()));
}
b.push_span(SegmentKind::Other, Name::Id(idx), 1, len as u64, 0)?;
at += 1 + len;
idx += 1;
}
b.finish()
})
}
fn write(
&self,
_: &Structure,
_: &mut dyn ReadSeek,
_: &mut dyn std::io::Write,
_: &Updates,
_: &mut dyn Sink,
) -> Result<Structure> {
Err(Error::UnsupportedFormat)
}
fn box_name(&self, name: Name) -> Option<Cow<'static, str>> {
match name {
Name::Id(n) => Some(Cow::Owned(format!("rec{n}"))),
Name::FourCC(cc) => Some(Cow::Owned(String::from_utf8_lossy(&cc).into_owned())),
_ => None,
}
}
}
fn toy_bytes() -> Vec<u8> {
let mut v = b"TOY!".to_vec();
v.extend([3, 1, 2, 3]);
v.extend([0]);
v.extend([2, 9, 9]);
v
}
#[test]
fn custom_handler_parses_names_and_tiles() {
let reg = HandlerRegistry::new().with_handler(Toy);
let bytes = toy_bytes();
let s = Structure::parse(®, &mut Cursor::new(bytes.clone()), Some("TOY")).unwrap();
assert_eq!(s.total_size(), bytes.len() as u64);
assert_eq!(s.media_type(), "application/x-toy");
let mut names = Vec::new();
let mut next = 0;
s.elements(|_, e| {
assert_eq!(e.range().offset(), next);
next = e.range().end();
names.push(s.box_name(e.name()).map(|n| n.into_owned()));
Ok(())
})
.unwrap();
assert_eq!(next, bytes.len() as u64);
assert_eq!(
names,
[
Some("TOY!".to_string()),
Some("rec0".to_string()),
Some("rec1".to_string()),
Some("rec2".to_string())
]
);
}
#[test]
fn detects_by_content_and_by_format_string() {
let reg = HandlerRegistry::new().with_handler(Toy);
assert!(reg.detect(b"TOY!....").is_some());
assert!(reg.detect(b"nope").is_none());
assert!(reg.handler(" .Toy ").is_some());
assert!(reg.handler("APPLICATION/X-TOY").is_some());
assert_eq!(reg.container_for("application/x-toy"), Some("toy"));
let s = Structure::parse(®, &mut Cursor::new(toy_bytes()), None).unwrap();
assert_eq!(s.container_id(), "toy");
assert!(matches!(
Structure::parse(®, &mut Cursor::new(toy_bytes()), Some("xyz")),
Err(Error::UnsupportedFormat)
));
}
#[test]
fn later_registration_wins_and_composition_copies_handlers() {
#[derive(Debug)]
struct Toy2;
impl ContainerHandler for Toy2 {
fn id(&self) -> &'static str {
"toy2"
}
fn formats(&self) -> &[FormatSpec] {
const F: &[FormatSpec] = &[FormatSpec::new("application/x-toy2", "toy")];
F
}
fn parse_async(self: Arc<Self>, _: Io) -> BoxFuture<'static, Result<Structure>> {
Box::pin(async { Err(Error::InvalidFormat("toy2".into())) })
}
fn write(
&self,
_: &Structure,
_: &mut dyn ReadSeek,
_: &mut dyn std::io::Write,
_: &Updates,
_: &mut dyn Sink,
) -> Result<Structure> {
Err(Error::UnsupportedFormat)
}
}
let base = HandlerRegistry::new().with_handler(Toy);
let mut over = HandlerRegistry::new();
over.extend_from(&base);
over.add_handler(Toy2);
assert!(matches!(
Structure::parse(&over, &mut Cursor::new(toy_bytes()), Some("toy")),
Err(Error::InvalidFormat(_))
));
assert!(Structure::parse(
&over,
&mut Cursor::new(toy_bytes()),
Some("application/x-toy")
)
.is_ok());
assert_eq!(over.container_for("toy"), Some("toy2"));
assert_eq!(base.container_for("toy"), Some("toy"));
assert!(Structure::parse(&base, &mut Cursor::new(toy_bytes()), Some("toy")).is_ok());
let mut under = HandlerRegistry::new().with_handler(Toy2);
under.extend_from(&base);
assert_eq!(under.container_for("toy"), Some("toy"));
let toy = Arc::clone(base.handler("toy").unwrap());
let again = over.clone().with_handlers([toy]);
assert_eq!(again.container_for("toy"), Some("toy"));
let ids: Vec<_> = again.handlers().map(|h| h.id()).collect();
assert_eq!(ids, ["toy2", "toy"]);
assert_eq!(again.formats(), over.formats());
}
}