Skip to main content

gpui/
util.rs

1use crate::{BackgroundExecutor, Task};
2use std::{
3    future::Future,
4    pin::Pin,
5    sync::atomic::{AtomicUsize, Ordering::SeqCst},
6    task,
7    time::Duration,
8};
9
10/// `Deref` to one field of a struct, and `DerefMut` too when the field is marked `mut`.
11macro_rules! impl_deref {
12    ([$($generics:tt)*] $ty:ty => mut $field:tt: $target:ty) => {
13        impl<$($generics)*> ::std::ops::Deref for $ty {
14            type Target = $target;
15            fn deref(&self) -> &$target {
16                &self.$field
17            }
18        }
19        impl<$($generics)*> ::std::ops::DerefMut for $ty {
20            fn deref_mut(&mut self) -> &mut $target {
21                &mut self.$field
22            }
23        }
24    };
25    ([$($generics:tt)*] $ty:ty => $field:tt: $target:ty) => {
26        impl<$($generics)*> ::std::ops::Deref for $ty {
27            type Target = $target;
28            fn deref(&self) -> &$target {
29                &self.$field
30            }
31        }
32    };
33}
34pub(crate) use impl_deref;
35
36/// A helper trait for building complex objects with imperative conditionals in a fluent style.
37pub trait FluentBuilder {
38    /// Imperatively modify self with the given closure.
39    fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
40    where
41        Self: Sized,
42    {
43        f(self)
44    }
45
46    /// Conditionally modify self with the given closure.
47    fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
48    where
49        Self: Sized,
50    {
51        self.map(|this| if condition { then(this) } else { this })
52    }
53
54    /// Conditionally modify self with the given closure.
55    fn when_else(
56        self,
57        condition: bool,
58        then: impl FnOnce(Self) -> Self,
59        else_fn: impl FnOnce(Self) -> Self,
60    ) -> Self
61    where
62        Self: Sized,
63    {
64        self.map(|this| if condition { then(this) } else { else_fn(this) })
65    }
66
67    /// Conditionally unwrap and modify self with the given closure, if the given option is Some.
68    fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
69    where
70        Self: Sized,
71    {
72        self.map(|this| {
73            if let Some(value) = option {
74                then(this, value)
75            } else {
76                this
77            }
78        })
79    }
80    /// Conditionally unwrap and modify self with the given closure, if the given option is None.
81    fn when_none<T>(self, option: &Option<T>, then: impl FnOnce(Self) -> Self) -> Self
82    where
83        Self: Sized,
84    {
85        self.map(|this| if option.is_some() { this } else { then(this) })
86    }
87}
88
89/// Extensions for Future types that provide additional combinators and utilities.
90pub trait FutureExt {
91    /// Requires a Future to complete before the specified duration has elapsed.
92    /// Similar to tokio::timeout.
93    fn with_timeout(self, timeout: Duration, executor: &BackgroundExecutor) -> WithTimeout<Self>
94    where
95        Self: Sized;
96}
97
98impl<T: Future> FutureExt for T {
99    fn with_timeout(self, timeout: Duration, executor: &BackgroundExecutor) -> WithTimeout<Self>
100    where
101        Self: Sized,
102    {
103        WithTimeout {
104            future: self,
105            timer: executor.timer(timeout),
106        }
107    }
108}
109
110pin_project_lite::pin_project! {
111    pub struct WithTimeout<T> {
112        #[pin]
113        future: T,
114        #[pin]
115        timer: Task<()>,
116    }
117}
118
119#[derive(Debug, thiserror::Error)]
120#[error("Timed out before future resolved")]
121/// Error returned by with_timeout when the timeout duration elapsed before the future resolved
122pub struct Timeout;
123
124impl<T: Future> Future for WithTimeout<T> {
125    type Output = Result<T::Output, Timeout>;
126
127    fn poll(self: Pin<&mut Self>, cx: &mut task::Context) -> task::Poll<Self::Output> {
128        let this = self.project();
129
130        if let task::Poll::Ready(output) = this.future.poll(cx) {
131            task::Poll::Ready(Ok(output))
132        } else if this.timer.poll(cx).is_ready() {
133            task::Poll::Ready(Err(Timeout))
134        } else {
135            task::Poll::Pending
136        }
137    }
138}
139
140/// Increment the given atomic counter if it is not zero.
141/// Return the new value of the counter.
142pub(crate) fn atomic_incr_if_not_zero(counter: &AtomicUsize) -> usize {
143    let mut loaded = counter.load(SeqCst);
144    loop {
145        if loaded == 0 {
146            return 0;
147        }
148        match counter.compare_exchange_weak(loaded, loaded + 1, SeqCst, SeqCst) {
149            Ok(x) => return x + 1,
150            Err(actual) => loaded = actual,
151        }
152    }
153}
154
155/// Rounds to the nearest integer with 0.5 ties toward zero.
156#[inline]
157pub(crate) fn round_half_toward_zero(value: f32) -> f32 {
158    (value.abs() - 0.5).ceil().copysign(value)
159}
160
161#[inline]
162pub(crate) fn round_half_toward_zero_f64(value: f64) -> f64 {
163    (value.abs() - 0.5).ceil().copysign(value)
164}
165
166#[inline]
167pub(crate) fn round_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
168    round_half_toward_zero(logical * scale_factor)
169}
170
171#[inline]
172pub(crate) fn round_stroke_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
173    if logical == 0.0 {
174        0.0
175    } else {
176        round_to_device_pixel(logical.max(0.0), scale_factor).max(1.0)
177    }
178}
179
180#[inline]
181pub(crate) fn floor_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
182    (logical * scale_factor).floor()
183}
184
185#[inline]
186pub(crate) fn ceil_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
187    (logical * scale_factor).ceil()
188}
189
190#[cfg(test)]
191mod tests {
192    use crate::TestAppContext;
193
194    use super::*;
195
196    #[test]
197    fn test_round_half_toward_zero() {
198        // Midpoint ties go toward zero
199        assert_eq!(round_half_toward_zero(0.5), 0.0);
200        assert_eq!(round_half_toward_zero(1.5), 1.0);
201        assert_eq!(round_half_toward_zero(2.5), 2.0);
202        assert_eq!(round_half_toward_zero(-0.5), 0.0);
203        assert_eq!(round_half_toward_zero(-1.5), -1.0);
204        assert_eq!(round_half_toward_zero(-2.5), -2.0);
205
206        // Non-midpoint values round to nearest
207        assert_eq!(round_half_toward_zero(1.5001), 2.0);
208        assert_eq!(round_half_toward_zero(1.4999), 1.0);
209        assert_eq!(round_half_toward_zero(-1.5001), -2.0);
210        assert_eq!(round_half_toward_zero(-1.4999), -1.0);
211
212        // Integers are unchanged
213        assert_eq!(round_half_toward_zero(0.0), 0.0);
214        assert_eq!(round_half_toward_zero(3.0), 3.0);
215        assert_eq!(round_half_toward_zero(-3.0), -3.0);
216    }
217
218    #[test]
219    fn test_device_pixel_helpers() {
220        // Snap uses half-toward-zero: 1.0 * 1.5 = 1.5 ties toward 1.0.
221        assert_eq!(round_to_device_pixel(1.0, 1.5), 1.0);
222        // Below the tie rounds down, above rounds up.
223        assert_eq!(round_to_device_pixel(0.3, 2.0), 1.0);
224        assert_eq!(round_to_device_pixel(1.4, 1.0), 1.0);
225        assert_eq!(round_to_device_pixel(1.6, 1.0), 2.0);
226
227        // Stroke uses snap, but clamps non-zero input up to at least 1dp.
228        assert_eq!(round_stroke_to_device_pixel(0.0, 1.0), 0.0);
229        assert_eq!(round_stroke_to_device_pixel(0.4, 1.0), 1.0);
230        assert_eq!(round_stroke_to_device_pixel(0.5, 1.0), 1.0);
231        assert_eq!(round_stroke_to_device_pixel(1.0, 1.5), 1.0);
232        assert_eq!(round_stroke_to_device_pixel(1.6, 1.0), 2.0);
233
234        // Cover's near edge floors, far edge ceils. Together they form a strict superset.
235        assert_eq!(floor_to_device_pixel(0.3, 2.0), 0.0);
236        assert_eq!(ceil_to_device_pixel(0.3, 2.0), 1.0);
237        assert_eq!(floor_to_device_pixel(2.1, 1.0), 2.0);
238        assert_eq!(ceil_to_device_pixel(2.1, 1.0), 3.0);
239
240        // Integer device-pixel inputs are stable under all three.
241        assert_eq!(round_to_device_pixel(2.0, 2.0), 4.0);
242        assert_eq!(floor_to_device_pixel(2.0, 2.0), 4.0);
243        assert_eq!(ceil_to_device_pixel(2.0, 2.0), 4.0);
244    }
245
246    #[test]
247    fn test_round_half_toward_zero_f64() {
248        assert_eq!(round_half_toward_zero_f64(0.5), 0.0);
249        assert_eq!(round_half_toward_zero_f64(-0.5), 0.0);
250        assert_eq!(round_half_toward_zero_f64(1.5), 1.0);
251        assert_eq!(round_half_toward_zero_f64(-1.5), -1.0);
252        assert_eq!(round_half_toward_zero_f64(2.5001), 3.0);
253    }
254
255    #[gpui::test]
256    async fn test_with_timeout(cx: &mut TestAppContext) {
257        Task::ready(())
258            .with_timeout(Duration::from_secs(1), &cx.executor())
259            .await
260            .expect("Timeout should be noop");
261
262        let long_duration = Duration::from_secs(6000);
263        let short_duration = Duration::from_secs(1);
264        cx.executor()
265            .timer(long_duration)
266            .with_timeout(short_duration, &cx.executor())
267            .await
268            .expect_err("timeout should have triggered");
269
270        let fut = cx
271            .executor()
272            .timer(long_duration)
273            .with_timeout(short_duration, &cx.executor());
274        cx.executor().advance_clock(short_duration * 2);
275        futures::FutureExt::now_or_never(fut)
276            .unwrap_or_else(|| panic!("timeout should have triggered"))
277            .expect_err("timeout");
278    }
279}