asset-io 0.7.0

Streaming, container-agnostic access to media file structure and metadata (JUMBF, XMP)
Documentation
// Copyright 2026 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.

// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.

//! Registry of container handlers.
//!
//! Handlers are looked up by format string (a file extension or MIME type) or by
//! matching caller-supplied header bytes. [`HandlerRegistry::new`] is empty;
//! [`HandlerRegistry::builtin`] holds the handlers of the enabled container
//! features. Registries are composed by adding handlers: the last registered
//! wins, so a caller's handlers override built-in ones for the formats they
//! claim, and are tried first when detecting.
//!
//! A registry only resolves handlers and format metadata; it never reads or
//! parses a stream. Use [`Structure::parse`](crate::Structure::parse),
//! [`Structure::parse_async`](crate::Structure::parse_async) or
//! [`Structure::parse_task`](crate::Structure::parse_task) to select a handler and
//! run its parser.

use std::{
    collections::HashMap,
    sync::{Arc, OnceLock},
};

use crate::handler::{ContainerHandler, FormatSpec, DETECT_LEN};

/// Matching is case-insensitive and ignores surrounding whitespace and a leading dot.
fn normalize(format: &str) -> String {
    format.trim().trim_start_matches('.').to_ascii_lowercase()
}

/// Container handlers, keyed by the format strings they declare.
///
/// Registering a handler for a format string that is already claimed replaces the
/// earlier claim ("last registered wins"), and detection tries the most recently
/// registered handler first. Registering a handler again moves it to the end.
///
/// Compose registries by adding handlers, not by layering them:
///
/// ```
/// # use asset_io::HandlerRegistry;
/// // Every enabled built-in handler, then the caller's own, which take precedence.
/// let registry = HandlerRegistry::with_builtin().with_handlers(Vec::new());
/// # let _ = registry;
/// ```
///
/// A registry is a list of shared handlers, so cloning or extending one is cheap.
#[derive(Debug, Default, Clone)]
pub struct HandlerRegistry {
    by_format: HashMap<String, Arc<dyn ContainerHandler>>,
    /// Registration order, for detection (most recent first).
    ordered: Vec<Arc<dyn ContainerHandler>>,
}

impl HandlerRegistry {
    /// An empty registry.
    pub fn new() -> Self {
        Self::default()
    }

    /// The handlers of every enabled container feature, shared. Empty when no
    /// container feature is enabled.
    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)
        }))
    }

    /// An owned registry holding the [built-in](Self::builtin) handlers, to add
    /// more to.
    pub fn with_builtin() -> Self {
        Self::builtin().as_ref().clone()
    }

    /// Register `handler`, returning the registry for chaining.
    pub fn with_handler(mut self, handler: impl ContainerHandler + 'static) -> Self {
        self.add_handler(handler);
        self
    }

    /// Register each of `handlers` in order, returning the registry for chaining.
    /// A crate that provides several handlers can export them as one list for
    /// this.
    pub fn with_handlers(
        mut self,
        handlers: impl IntoIterator<Item = Arc<dyn ContainerHandler>>,
    ) -> Self {
        self.extend(handlers);
        self
    }

    /// Register every handler of `other`, in its registration order, so they take
    /// precedence over handlers registered here before.
    pub fn extend_from(&mut self, other: &HandlerRegistry) {
        self.extend(other.ordered.iter().cloned());
    }

    /// Register `handler` for every format string it declares.
    pub fn add_handler(&mut self, handler: impl ContainerHandler + 'static) {
        self.add_arc(Arc::new(handler));
    }

    /// Register an already shared 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);
    }

    /// Every registered handler, in registration order.
    /// These are [`crate::container_api::ContainerHandler`]s, available to
    /// compose registries and use container-specific hooks explicitly.
    pub fn handlers(&self) -> impl Iterator<Item = &Arc<dyn ContainerHandler>> {
        self.ordered.iter()
    }

    /// The handler for a format string (extension or MIME type).
    /// Advanced clients can call its [`compose`](ContainerHandler::compose)
    /// hook; ordinary clients use [`crate::Asset::write`].
    pub fn handler(&self, format: &str) -> Option<&Arc<dyn ContainerHandler>> {
        self.by_format.get(&normalize(format))
    }

    /// The [id](ContainerHandler::id) of the container for a format string. Two
    /// format strings are the same container iff their ids are equal.
    pub fn container_for(&self, format: &str) -> Option<&'static str> {
        Some(self.handler(format)?.id())
    }

    /// The format a format string names, from the handler that serves it.
    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))
    }

    /// The media type for a format string (extension or media type): `"heic"`
    /// gives `"image/heic"`, and an alias such as `"image/x-webp"` gives
    /// `"image/webp"`. `None` if no handler claims the format.
    pub fn media_type_for(&self, format: &str) -> Option<&'static str> {
        self.format_for(format).map(|spec| spec.media_type)
    }

    /// The preferred file extension for a format string (extension or media
    /// type): `"image/jpeg"` and `"jpeg"` both give `"jpg"`. `None` if no handler
    /// claims the format.
    pub fn extension_for(&self, format: &str) -> Option<&'static str> {
        self.format_for(format).map(|spec| spec.extension)
    }

    /// The handler that recognises `header` (the leading bytes of a stream).
    /// Handlers are tried most recently registered first.
    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))
    }

    /// Every format string this registry serves, sorted.
    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,
    };

    /// A made-up container: `TOY!` then records of `[len][len bytes]`.
    /// Records are named by index with `Name::Id`, shown as `rec<N>`.
    #[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,
            _: &Structure,
            _: crate::SegmentId,
            element: &crate::Segment,
        ) -> Option<Cow<'static, str>> {
            match element.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(&reg, &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(|id, e| {
            assert_eq!(e.range().offset(), next);
            next = e.range().end();
            names.push(s.box_name(id, e).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(&reg, &mut Cursor::new(toy_bytes()), None).unwrap();
        assert_eq!(s.container_id(), "toy");
        let s = Structure::parse(&reg, &mut Cursor::new(toy_bytes()), Some("xyz")).unwrap();
        assert_eq!(s.container_id(), "toy");
    }

    #[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);

        // Content detection takes precedence over a mismatched explicit format.
        assert!(matches!(
            Structure::parse(&over, &mut Cursor::new(toy_bytes()), Some("toy")),
            Ok(s) if s.container_id() == "toy"
        ));
        assert!(Structure::parse(
            &over,
            &mut Cursor::new(toy_bytes()),
            Some("application/x-toy")
        )
        .is_ok());
        assert_eq!(over.container_for("toy"), Some("toy2"));
        // The registry it was composed from is untouched.
        assert_eq!(base.container_for("toy"), Some("toy"));
        assert!(Structure::parse(&base, &mut Cursor::new(toy_bytes()), Some("toy")).is_ok());

        // Composing the other way round gives the other precedence.
        let mut under = HandlerRegistry::new().with_handler(Toy2);
        under.extend_from(&base);
        assert_eq!(under.container_for("toy"), Some("toy"));

        // Registering a handler again moves it last and reclaims its formats,
        // without listing it twice.
        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());
    }
}