Skip to main content

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