util.rs

 1#[cfg(any(test, feature = "test-support"))]
 2use std::time::Duration;
 3
 4#[cfg(any(test, feature = "test-support"))]
 5use futures::Future;
 6
 7#[cfg(any(test, feature = "test-support"))]
 8use smol::future::FutureExt;
 9
10pub use util::*;
11
12/// A helper trait for building complex objects with imperative conditionals in a fluent style.
13pub trait FluentBuilder {
14    /// Imperatively modify self with the given closure.
15    fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
16    where
17        Self: Sized,
18    {
19        f(self)
20    }
21
22    /// Conditionally modify self with the given closure.
23    fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
24    where
25        Self: Sized,
26    {
27        self.map(|this| if condition { then(this) } else { this })
28    }
29
30    /// Conditionally unwrap and modify self with the given closure, if the given option is Some.
31    fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
32    where
33        Self: Sized,
34    {
35        self.map(|this| {
36            if let Some(value) = option {
37                then(this, value)
38            } else {
39                this
40            }
41        })
42    }
43}
44
45#[cfg(any(test, feature = "test-support"))]
46pub async fn timeout<F, T>(timeout: Duration, f: F) -> Result<T, ()>
47where
48    F: Future<Output = T>,
49{
50    let timer = async {
51        smol::Timer::after(timeout).await;
52        Err(())
53    };
54    let future = async move { Ok(f.await) };
55    timer.race(future).await
56}
57
58#[cfg(any(test, feature = "test-support"))]
59pub struct CwdBacktrace<'a>(pub &'a backtrace::Backtrace);
60
61#[cfg(any(test, feature = "test-support"))]
62impl<'a> std::fmt::Debug for CwdBacktrace<'a> {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        use backtrace::{BacktraceFmt, BytesOrWideString};
65
66        let cwd = std::env::current_dir().unwrap();
67        let cwd = cwd.parent().unwrap();
68        let mut print_path = |fmt: &mut std::fmt::Formatter<'_>, path: BytesOrWideString<'_>| {
69            std::fmt::Display::fmt(&path, fmt)
70        };
71        let mut fmt = BacktraceFmt::new(f, backtrace::PrintFmt::Full, &mut print_path);
72        for frame in self.0.frames() {
73            let mut formatted_frame = fmt.frame();
74            if frame
75                .symbols()
76                .iter()
77                .any(|s| s.filename().map_or(false, |f| f.starts_with(cwd)))
78            {
79                formatted_frame.backtrace_frame(frame)?;
80            }
81        }
82        fmt.finish()
83    }
84}