Skip to main content

docspec_core/
traits.rs

1//! Core traits for event sources, sinks, and asset providers.
2
3use alloc::borrow::Cow;
4use std::io;
5use std::io::Write;
6
7/// Provides access to binary assets referenced in the event stream.
8///
9/// Readers register assets as they are encountered. Writers call [`AssetProvider::stream_to`]
10/// on demand — bytes stream through, never buffer. Assets must remain accessible until
11/// the `EndDocument` event is processed.
12pub trait AssetProvider: Send + Sync {
13    /// Returns the MIME content type for the given asset ID, or `None` if the asset is not found.
14    fn content_type(&self, asset_id: &str) -> Option<Cow<'_, str>>;
15
16    /// Streams the asset bytes to the given writer.
17    ///
18    /// Returns `Some(Ok(bytes_written))` on success, `Some(Err(_))` on write error,
19    /// or `None` if the asset is not found.
20    fn stream_to(&self, asset_id: &str, writer: &mut dyn Write) -> Option<io::Result<u64>>;
21}
22
23/// Consumes a stream of [`crate::Event`]s to produce output.
24///
25/// Writers implement this trait to translate document events into a target
26/// format. Call [`EventSink::handle_event`] for each event in order, then
27/// call [`EventSink::finish`] to flush output and signal completion.
28///
29/// `finish` consumes `self` to prevent reuse after the stream has ended.
30pub trait EventSink {
31    /// Flush any buffered output and finalize the document.
32    ///
33    /// Consumes `self` to prevent further use after the stream ends.
34    ///
35    /// # Errors
36    ///
37    /// Returns an error if flushing or finalization fails.
38    fn finish(self) -> crate::Result<()>;
39
40    /// Process one event from the stream.
41    ///
42    /// Events must arrive in valid document order. Writers may assume the
43    /// stream is well-formed per the rules in EVENTS.md.
44    ///
45    /// # Errors
46    ///
47    /// Returns an error if the sink cannot process the event (write failure,
48    /// invalid format, resource exhaustion).
49    fn handle_event(&mut self, event: crate::Event) -> crate::Result<()>;
50}
51
52/// Produces a stream of [`crate::Event`]s from a document source.
53///
54/// The pull-based design gives the consumer control: only fetch events when
55/// ready to process them. This provides natural backpressure and constant
56/// memory usage regardless of document size.
57///
58/// Return `Ok(None)` to signal the end of the stream. Return `Err` for fatal
59/// errors that prevent further reading.
60pub trait EventSource {
61    /// Returns the next event from the stream, or `None` if the stream has ended.
62    ///
63    /// # Errors
64    ///
65    /// Returns an error if the source encounters a fatal problem (malformed
66    /// input, truncated stream, I/O failure). After an error, the stream is
67    /// considered terminated.
68    fn next_event(&mut self) -> crate::Result<Option<crate::Event>>;
69}