Skip to main content

mdcat/render/
observer.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5//! Observer hook.
6//!
7//! [`push_tty_with_observer`](crate::push_tty_with_observer) calls
8//! `on_event(byte_offset, event)` before each pulldown-cmark event.
9//! The default [`NoopObserver`] compiles away.
10
11use pulldown_cmark::Event;
12
13/// Observer invoked on every event the render state machine processes.
14///
15/// Implementations typically accumulate a side-table mapping output byte
16/// offsets to structural events. The default [`NoopObserver`] discards
17/// every call and compiles away under the optimiser.
18pub trait RenderObserver {
19    /// Called immediately before the event is rendered.
20    ///
21    /// `byte_offset` is the number of bytes written to the output so far.
22    /// Observers must not mutate the event; they receive it by shared
23    /// reference.
24    fn on_event(&mut self, byte_offset: u64, event: &Event<'_>);
25}
26
27/// Observer that ignores every event.
28///
29/// Used by [`push_tty`](crate::push_tty) to avoid paying for the hook when
30/// structural information is not needed.
31#[derive(Debug, Default, Copy, Clone)]
32pub struct NoopObserver;
33
34impl RenderObserver for NoopObserver {
35    #[inline]
36    fn on_event(&mut self, _byte_offset: u64, _event: &Event<'_>) {}
37}
38
39impl<O: RenderObserver + ?Sized> RenderObserver for &mut O {
40    fn on_event(&mut self, byte_offset: u64, event: &Event<'_>) {
41        (**self).on_event(byte_offset, event);
42    }
43}