Skip to main content

asset_io/
parse.rs

1// Copyright 2026 Adobe. All rights reserved.
2// This file is licensed to you under the Apache License,
3// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
4// or the MIT license (http://opensource.org/licenses/MIT),
5// at your option.
6
7//! Parsing: select a handler from a registry, then run its parser to build a
8//! [`Structure`].
9
10use std::{io::SeekFrom, sync::Arc};
11
12use crate::{
13    container_api::{ReadSeek, DETECT_LEN},
14    io::Io,
15    task::{block_on, Task},
16    Error, HandlerRegistry, Result, Structure,
17};
18
19impl Structure {
20    /// Parse a complete stream with blocking I/O.
21    ///
22    /// Content detection takes precedence. If no handler recognizes the content,
23    /// `Some(format)` selects a handler by extension or MIME type; with `None`,
24    /// parsing fails. Format selection does not validate the content; the selected
25    /// handler's parser does that.
26    ///
27    /// The stream's length is determined by seeking to its end. Offsets are relative
28    /// to the beginning of the stream, regardless of its initial position. The
29    /// stream may be repositioned on success or error.
30    pub fn parse(
31        registry: &HandlerRegistry,
32        src: &mut dyn ReadSeek,
33        format: Option<&str>,
34    ) -> Result<Structure> {
35        let total = src.seek(SeekFrom::End(0))?;
36        block_on(total, src, |mut io| async move {
37            Structure::parse_async(registry, &mut io, format).await
38        })
39    }
40
41    /// Parse a stream of `total` bytes as a caller-driven task.
42    ///
43    /// Format selection follows [`parse`](Self::parse). Selection and parsing
44    /// errors are returned when the task is driven, not when it is created. The
45    /// task borrows `registry` and `format`; to build a registry-independent task
46    /// for a known handler, use [`Task::new`] with
47    /// [`ContainerHandler::parse_async`](crate::container_api::ContainerHandler::parse_async).
48    pub fn parse_task<'a>(
49        registry: &'a HandlerRegistry,
50        total: u64,
51        format: Option<&'a str>,
52    ) -> Task<'a, Structure> {
53        Task::new(total, move |mut io| async move {
54            Structure::parse_async(registry, &mut io, format).await
55        })
56    }
57
58    /// Parse through `io` inside a larger sans-I/O computation.
59    ///
60    /// Format selection follows [`parse`](Self::parse). This does no I/O itself:
61    /// a [`Task`] driver supplies requested bytes. The selected handler takes an
62    /// owned [`Io::fork`], leaving `io` available after parsing. The fork has a
63    /// separate byte window, so detection bytes may be requested again by the
64    /// parser.
65    pub async fn parse_async(
66        registry: &HandlerRegistry,
67        io: &mut Io,
68        format: Option<&str>,
69    ) -> Result<Structure> {
70        let len = (DETECT_LEN as u64).min(io.len()) as usize;
71        let head = io.fetch(0, len).await?;
72        let detected = registry.detect(head);
73        let handler = match (detected, format) {
74            (Some(detected), Some(format)) => match registry.handler(format) {
75                Some(explicit) if explicit.id() == detected.id() => Arc::clone(explicit),
76                _ => Arc::clone(detected),
77            },
78            (Some(detected), None) => Arc::clone(detected),
79            (None, Some(format)) => {
80                Arc::clone(registry.handler(format).ok_or(Error::UnsupportedFormat)?)
81            }
82            (None, None) => return Err(Error::UnsupportedFormat),
83        };
84        handler.parse_async(io.fork()).await
85    }
86}
87
88#[cfg(test)]
89mod tests {
90    use std::{
91        io::{Cursor, Read, Seek},
92        sync::atomic::{AtomicUsize, Ordering},
93    };
94
95    use super::*;
96    use crate::{
97        container_api::{BoxFuture, ContainerHandler, FormatSpec, StructureBuilder},
98        task::Progress,
99        Name, SegmentKind,
100    };
101
102    #[derive(Debug)]
103    struct TestHandler {
104        id: &'static str,
105        format: &'static str,
106        detects: bool,
107        detections: Arc<AtomicUsize>,
108    }
109
110    impl ContainerHandler for TestHandler {
111        fn id(&self) -> &'static str {
112            self.id
113        }
114
115        fn formats(&self) -> &[FormatSpec] {
116            const TEST: &[FormatSpec] = &[FormatSpec::new("application/x-test", "test")];
117            const OTHER: &[FormatSpec] = &[FormatSpec::new("application/x-other", "other")];
118            match self.format {
119                "test" => TEST,
120                "other" => OTHER,
121                _ => unreachable!("test handler format"),
122            }
123        }
124
125        fn detect(&self, header: &[u8]) -> bool {
126            self.detections.fetch_add(1, Ordering::Relaxed);
127            self.detects && header.starts_with(b"TEST")
128        }
129
130        fn parse_async(self: Arc<Self>, mut io: Io) -> BoxFuture<'static, Result<Structure>> {
131            Box::pin(async move {
132                let mut head = [0; 4];
133                io.read_at(0, &mut head).await?;
134                if head != *b"TEST" {
135                    return Err(Error::InvalidFormat("expected TEST header".into()));
136                }
137                let mut builder = StructureBuilder::new(self, "application/x-test", io.len());
138                builder.push_span(
139                    SegmentKind::Other,
140                    Name::FourCC(*b"TEST"),
141                    4,
142                    io.len() - 4,
143                    0,
144                )?;
145                builder.finish()
146            })
147        }
148    }
149
150    fn handler(id: &'static str, format: &'static str, detects: bool) -> TestHandler {
151        TestHandler {
152            id,
153            format,
154            detects,
155            detections: Arc::new(AtomicUsize::new(0)),
156        }
157    }
158
159    fn drive<T>(mut task: Task<'_, T>, bytes: &[u8]) -> (Result<T>, usize) {
160        let mut requests = 0;
161        loop {
162            match task.resume() {
163                Ok(Progress::Read(mut req)) => {
164                    requests += 1;
165                    let start = (req.offset() as usize).min(bytes.len());
166                    let end = (start + req.window_len()).min(bytes.len());
167                    req.buffer().extend_from_slice(&bytes[start..end]);
168                }
169                Ok(Progress::Done(value)) => return (Ok(value), requests),
170                Err(error) => return (Err(error), requests),
171            }
172        }
173    }
174
175    #[test]
176    fn explicit_format_falls_back_when_content_is_not_detected() {
177        let h = handler("explicit", "test", false);
178        let detections = Arc::clone(&h.detections);
179        let registry = HandlerRegistry::new().with_handler(h);
180        for format in [" .TeSt ", "APPLICATION/X-TEST"] {
181            let mut src = Cursor::new(b"TESTpayload");
182            src.set_position(5);
183            let structure = Structure::parse(&registry, &mut src, Some(format)).unwrap();
184            assert_eq!(structure.container_id(), "explicit");
185            assert_eq!(structure.total_size(), 11);
186            let (structure, _) = drive(
187                Structure::parse_task(&registry, 11, Some(format)),
188                b"TESTpayload",
189            );
190            assert_eq!(structure.unwrap().container_id(), "explicit");
191        }
192        assert!(detections.load(Ordering::Relaxed) > 0);
193        assert!(matches!(
194            Structure::parse(&registry, &mut Cursor::new(b"TEST"), None),
195            Err(Error::UnsupportedFormat)
196        ));
197    }
198
199    #[test]
200    fn detection_and_format_selection_prefer_the_latest_registration() {
201        let base = HandlerRegistry::new().with_handler(handler("base", "test", true));
202        let mut registry = HandlerRegistry::new();
203        registry.extend_from(&base);
204        registry.add_handler(handler("first", "test", true));
205        registry.add_handler(handler("latest", "test", true));
206        for format in [None, Some("test")] {
207            let structure = Structure::parse(&registry, &mut Cursor::new(b"TEST"), format).unwrap();
208            assert_eq!(structure.container_id(), "latest");
209            let (structure, _) = drive(Structure::parse_task(&registry, 4, format), b"TEST");
210            assert_eq!(structure.unwrap().container_id(), "latest");
211        }
212        // The registry composed from is unchanged.
213        for format in [None, Some("test")] {
214            assert_eq!(
215                Structure::parse(&base, &mut Cursor::new(b"TEST"), format)
216                    .unwrap()
217                    .container_id(),
218                "base"
219            );
220        }
221    }
222
223    #[test]
224    fn content_detection_precedes_format_fallback() {
225        let h = handler("test", "test", true);
226        let detections = Arc::clone(&h.detections);
227        let registry = HandlerRegistry::new().with_handler(h);
228        for format in [Some("unknown"), Some("")] {
229            assert_eq!(
230                Structure::parse(&registry, &mut Cursor::new(b"TEST"), format)
231                    .unwrap()
232                    .container_id(),
233                "test"
234            );
235            let (result, requests) = drive(Structure::parse_task(&registry, 4, format), b"TEST");
236            assert_eq!(result.unwrap().container_id(), "test");
237            assert!(requests > 0);
238        }
239        let mismatch_registry = HandlerRegistry::new()
240            .with_handler(handler("fallback", "other", false))
241            .with_handler(handler("detected", "test", true));
242        assert_eq!(
243            Structure::parse(&mismatch_registry, &mut Cursor::new(b"TEST"), Some("other"))
244                .unwrap()
245                .container_id(),
246            "detected"
247        );
248        assert!(matches!(
249            Structure::parse(&registry, &mut Cursor::new(b"nope"), Some("unknown")),
250            Err(Error::UnsupportedFormat)
251        ));
252        let (result, _) = drive(
253            Structure::parse_task(&registry, 4, Some("unknown")),
254            b"nope",
255        );
256        assert!(matches!(result, Err(Error::UnsupportedFormat)));
257
258        assert!(matches!(
259            Structure::parse(&registry, &mut Cursor::new(b"nope"), Some("test")),
260            Err(Error::InvalidFormat(_))
261        ));
262        assert!(detections.load(Ordering::Relaxed) > 0);
263        for bytes in [b"".as_slice(), b"T", b"nope"] {
264            assert!(matches!(
265                Structure::parse(&registry, &mut Cursor::new(bytes), None),
266                Err(Error::UnsupportedFormat)
267            ));
268        }
269        let (result, _) = drive(Structure::parse_task(&registry, 4, Some("test")), b"T");
270        assert!(matches!(
271            result,
272            Err(Error::Io(error)) if error.kind() == std::io::ErrorKind::UnexpectedEof
273        ));
274    }
275
276    #[test]
277    fn async_parsing_composes_with_later_reads_in_the_same_task() {
278        let registry = HandlerRegistry::new().with_handler(handler("test", "test", true));
279        for format in [None, Some("test")] {
280            let registry = &registry;
281            let task = Task::new(11, |mut io| async move {
282                let structure = Structure::parse_async(registry, &mut io, format).await?;
283                let payload = io.read_vec(4, 7).await?;
284                Ok((structure, payload))
285            });
286            let (result, _) = drive(task, b"TESTpayload");
287            let (structure, payload) = result.unwrap();
288            assert_eq!(structure.container_id(), "test");
289            assert_eq!(payload, b"payload");
290        }
291    }
292
293    #[test]
294    fn blocking_parse_propagates_source_errors() {
295        struct Broken;
296        impl Read for Broken {
297            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
298                Err(std::io::Error::other("read failed"))
299            }
300        }
301        impl Seek for Broken {
302            fn seek(&mut self, _: SeekFrom) -> std::io::Result<u64> {
303                Ok(4)
304            }
305        }
306        let registry = HandlerRegistry::new().with_handler(handler("test", "test", true));
307        for format in [None, Some("test")] {
308            assert!(matches!(
309                Structure::parse(&registry, &mut Broken, format),
310                Err(Error::Io(error)) if error.to_string() == "read failed"
311            ));
312        }
313    }
314}