lib.rs

  1// FluentBuilder
  2// pub use gpui_util::{FutureExt, Timeout, arc_cow::ArcCow};
  3
  4use std::{
  5    env,
  6    ops::AddAssign,
  7    panic::Location,
  8    pin::Pin,
  9    sync::OnceLock,
 10    task::{Context, Poll},
 11    time::Instant,
 12};
 13
 14pub mod arc_cow;
 15
 16pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
 17    let prev = *value;
 18    *value += T::from(1);
 19    prev
 20}
 21
 22pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
 23    static ZED_MEASUREMENTS: OnceLock<bool> = OnceLock::new();
 24    let zed_measurements = ZED_MEASUREMENTS.get_or_init(|| {
 25        env::var("ZED_MEASUREMENTS")
 26            .map(|measurements| measurements == "1" || measurements == "true")
 27            .unwrap_or(false)
 28    });
 29
 30    if *zed_measurements {
 31        let start = Instant::now();
 32        let result = f();
 33        let elapsed = start.elapsed();
 34        eprintln!("{}: {:?}", label, elapsed);
 35        result
 36    } else {
 37        f()
 38    }
 39}
 40
 41#[macro_export]
 42macro_rules! debug_panic {
 43    ( $($fmt_arg:tt)* ) => {
 44        if cfg!(debug_assertions) {
 45            panic!( $($fmt_arg)* );
 46        } else {
 47            let backtrace = std::backtrace::Backtrace::capture();
 48            log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace);
 49        }
 50    };
 51}
 52
 53#[track_caller]
 54pub fn some_or_debug_panic<T>(option: Option<T>) -> Option<T> {
 55    #[cfg(debug_assertions)]
 56    if option.is_none() {
 57        panic!("Unexpected None");
 58    }
 59    option
 60}
 61
 62/// Expands to an immediately-invoked function expression. Good for using the ? operator
 63/// in functions which do not return an Option or Result.
 64///
 65/// Accepts a normal block, an async block, or an async move block.
 66#[macro_export]
 67macro_rules! maybe {
 68    ($block:block) => {
 69        (|| $block)()
 70    };
 71    (async $block:block) => {
 72        (async || $block)()
 73    };
 74    (async move $block:block) => {
 75        (async move || $block)()
 76    };
 77}
 78pub trait ResultExt<E> {
 79    type Ok;
 80
 81    fn log_err(self) -> Option<Self::Ok>;
 82    /// Assert that this result should never be an error in development or tests.
 83    fn debug_assert_ok(self, reason: &str) -> Self;
 84    fn warn_on_err(self) -> Option<Self::Ok>;
 85    fn log_with_level(self, level: log::Level) -> Option<Self::Ok>;
 86    fn anyhow(self) -> anyhow::Result<Self::Ok>
 87    where
 88        E: Into<anyhow::Error>;
 89}
 90
 91impl<T, E> ResultExt<E> for Result<T, E>
 92where
 93    E: std::fmt::Debug,
 94{
 95    type Ok = T;
 96
 97    #[track_caller]
 98    fn log_err(self) -> Option<T> {
 99        self.log_with_level(log::Level::Error)
100    }
101
102    #[track_caller]
103    fn debug_assert_ok(self, reason: &str) -> Self {
104        if let Err(error) = &self {
105            debug_panic!("{reason} - {error:?}");
106        }
107        self
108    }
109
110    #[track_caller]
111    fn warn_on_err(self) -> Option<T> {
112        self.log_with_level(log::Level::Warn)
113    }
114
115    #[track_caller]
116    fn log_with_level(self, level: log::Level) -> Option<T> {
117        match self {
118            Ok(value) => Some(value),
119            Err(error) => {
120                log_error_with_caller(*Location::caller(), error, level);
121                None
122            }
123        }
124    }
125
126    fn anyhow(self) -> anyhow::Result<T>
127    where
128        E: Into<anyhow::Error>,
129    {
130        self.map_err(Into::into)
131    }
132}
133
134fn log_error_with_caller<E>(caller: core::panic::Location<'_>, error: E, level: log::Level)
135where
136    E: std::fmt::Debug,
137{
138    #[cfg(not(windows))]
139    let file = caller.file();
140    #[cfg(windows)]
141    let file = caller.file().replace('\\', "/");
142    // In this codebase all crates reside in a `crates` directory,
143    // so discard the prefix up to that segment to find the crate name
144    let file = file.split_once("crates/");
145    let target = file.as_ref().and_then(|(_, s)| s.split_once("/src/"));
146
147    let module_path = target.map(|(krate, module)| {
148        if module.starts_with(krate) {
149            module.trim_end_matches(".rs").replace('/', "::")
150        } else {
151            krate.to_owned() + "::" + &module.trim_end_matches(".rs").replace('/', "::")
152        }
153    });
154    let file = file.map(|(_, file)| format!("crates/{file}"));
155    log::logger().log(
156        &log::Record::builder()
157            .target(module_path.as_deref().unwrap_or(""))
158            .module_path(file.as_deref())
159            .args(format_args!("{:?}", error))
160            .file(Some(caller.file()))
161            .line(Some(caller.line()))
162            .level(level)
163            .build(),
164    );
165}
166
167pub fn log_err<E: std::fmt::Debug>(error: &E) {
168    log_error_with_caller(*Location::caller(), error, log::Level::Error);
169}
170
171pub trait TryFutureExt {
172    fn log_err(self) -> LogErrorFuture<Self>
173    where
174        Self: Sized;
175
176    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
177    where
178        Self: Sized;
179
180    fn warn_on_err(self) -> LogErrorFuture<Self>
181    where
182        Self: Sized;
183    fn unwrap(self) -> UnwrapFuture<Self>
184    where
185        Self: Sized;
186}
187
188impl<F, T, E> TryFutureExt for F
189where
190    F: Future<Output = Result<T, E>>,
191    E: std::fmt::Debug,
192{
193    #[track_caller]
194    fn log_err(self) -> LogErrorFuture<Self>
195    where
196        Self: Sized,
197    {
198        let location = Location::caller();
199        LogErrorFuture(self, log::Level::Error, *location)
200    }
201
202    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
203    where
204        Self: Sized,
205    {
206        LogErrorFuture(self, log::Level::Error, location)
207    }
208
209    #[track_caller]
210    fn warn_on_err(self) -> LogErrorFuture<Self>
211    where
212        Self: Sized,
213    {
214        let location = Location::caller();
215        LogErrorFuture(self, log::Level::Warn, *location)
216    }
217
218    fn unwrap(self) -> UnwrapFuture<Self>
219    where
220        Self: Sized,
221    {
222        UnwrapFuture(self)
223    }
224}
225
226#[must_use]
227pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
228
229impl<F, T, E> Future for LogErrorFuture<F>
230where
231    F: Future<Output = Result<T, E>>,
232    E: std::fmt::Debug,
233{
234    type Output = Option<T>;
235
236    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
237        let level = self.1;
238        let location = self.2;
239        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
240        match inner.poll(cx) {
241            Poll::Ready(output) => Poll::Ready(match output {
242                Ok(output) => Some(output),
243                Err(error) => {
244                    log_error_with_caller(location, error, level);
245                    None
246                }
247            }),
248            Poll::Pending => Poll::Pending,
249        }
250    }
251}
252
253pub struct UnwrapFuture<F>(F);
254
255impl<F, T, E> Future for UnwrapFuture<F>
256where
257    F: Future<Output = Result<T, E>>,
258    E: std::fmt::Debug,
259{
260    type Output = T;
261
262    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
263        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
264        match inner.poll(cx) {
265            Poll::Ready(result) => Poll::Ready(result.unwrap()),
266            Poll::Pending => Poll::Pending,
267        }
268    }
269}
270
271pub struct Deferred<F: FnOnce()>(Option<F>);
272
273impl<F: FnOnce()> Deferred<F> {
274    /// Drop without running the deferred function.
275    pub fn abort(mut self) {
276        self.0.take();
277    }
278}
279
280impl<F: FnOnce()> Drop for Deferred<F> {
281    fn drop(&mut self) {
282        if let Some(f) = self.0.take() {
283            f()
284        }
285    }
286}
287
288/// Run the given function when the returned value is dropped (unless it's cancelled).
289#[must_use]
290pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
291    Deferred(Some(f))
292}