f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
//! Optional timing spans for profiling. With
//! the feature `timing`, a thread that called `arm` records how long each [`span`] takes, and
//! `take` hands the spans over. Without the feature, or on a thread that did not arm it,
//! [`span`] only runs its work.

/// Runs `work`, and records how long it took under `name` when the feature `timing` is on and
/// the thread armed the recording.
pub fn span<T>(name: &'static str, work: impl FnOnce() -> T) -> T {
    #[cfg(feature = "timing")]
    {
        recording::span(name, work)
    }
    #[cfg(not(feature = "timing"))]
    {
        let _ = name;
        work()
    }
}

#[cfg(feature = "timing")]
pub use recording::{arm, take};

#[cfg(feature = "timing")]
mod recording {
    use std::cell::{Cell, RefCell};
    use std::time::{Duration, Instant};

    thread_local! {
        static ARMED: Cell<bool> = const { Cell::new(false) };
        static SPANS: RefCell<Vec<(&'static str, Duration)>> = const { RefCell::new(Vec::new()) };
    }

    /// Makes the current thread record its spans from now on.
    pub fn arm() {
        ARMED.with(|armed| armed.set(true));
    }

    /// The spans that the current thread recorded since the last call, in the order in which
    /// they ended.
    #[must_use]
    pub fn take() -> Vec<(&'static str, Duration)> {
        SPANS.with(|spans| std::mem::take(&mut *spans.borrow_mut()))
    }

    pub(super) fn span<T>(name: &'static str, work: impl FnOnce() -> T) -> T {
        if !ARMED.with(Cell::get) {
            return work();
        }
        let start = Instant::now();
        let value = work();
        let elapsed = start.elapsed();
        SPANS.with(|spans| spans.borrow_mut().push((name, elapsed)));
        value
    }

    #[cfg(test)]
    mod tests {
        #[test]
        fn records_spans_only_on_an_armed_thread() {
            assert_eq!(super::span("before", || 1), 1);
            assert_eq!(super::take(), []);
            super::arm();
            assert_eq!(super::span("work", || 2), 2);
            let spans = super::take();
            assert_eq!(spans.len(), 1);
            assert_eq!(spans.first().map(|s| s.0), Some("work"));
            assert_eq!(super::take(), []);
        }
    }
}