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
10pub trait FluentBuilder {
24 fn map<U>(self, f: impl FnOnce(Self) -> U) -> U
27 where
28 Self: Sized,
29 {
30 f(self)
31 }
32
33 fn when(self, condition: bool, then: impl FnOnce(Self) -> Self) -> Self
36 where
37 Self: Sized,
38 {
39 self.map(|this| if condition { then(this) } else { this })
40 }
41
42 fn when_else(
45 self,
46 condition: bool,
47 then: impl FnOnce(Self) -> Self,
48 else_fn: impl FnOnce(Self) -> Self,
49 ) -> Self
50 where
51 Self: Sized,
52 {
53 self.map(|this| if condition { then(this) } else { else_fn(this) })
54 }
55
56 fn when_some<T>(self, option: Option<T>, then: impl FnOnce(Self, T) -> Self) -> Self
59 where
60 Self: Sized,
61 {
62 self.map(|this| {
63 if let Some(value) = option {
64 then(this, value)
65 } else {
66 this
67 }
68 })
69 }
70 fn when_none<T>(self, option: &Option<T>, then: impl FnOnce(Self) -> Self) -> Self
73 where
74 Self: Sized,
75 {
76 self.map(|this| if option.is_some() { this } else { then(this) })
77 }
78}
79
80pub trait FutureExt {
82 fn with_timeout(self, timeout: Duration, executor: &BackgroundExecutor) -> WithTimeout<Self>
101 where
102 Self: Sized;
103}
104
105impl<T: Future> FutureExt for T {
106 fn with_timeout(self, timeout: Duration, executor: &BackgroundExecutor) -> WithTimeout<Self>
107 where
108 Self: Sized,
109 {
110 WithTimeout {
111 future: self,
112 timer: executor.timer(timeout),
113 }
114 }
115}
116
117pub trait TextRangeExt {
119 fn contains_range(&self, range: &std::ops::Range<usize>) -> bool;
121}
122
123impl TextRangeExt for str {
124 fn contains_range(&self, range: &std::ops::Range<usize>) -> bool {
125 self.get(range.clone()).is_some()
126 }
127}
128
129#[pin_project::pin_project]
132pub struct WithTimeout<T> {
133 #[pin]
134 future: T,
135 #[pin]
136 timer: Task<()>,
137}
138
139#[derive(Debug, thiserror::Error)]
142#[error("Timed out before future resolved")]
143pub struct Timeout;
144
145impl<T: Future> Future for WithTimeout<T> {
146 type Output = Result<T::Output, Timeout>;
147
148 fn poll(self: Pin<&mut Self>, cx: &mut task::Context) -> task::Poll<Self::Output> {
149 let this = self.project();
150
151 if let task::Poll::Ready(output) = this.future.poll(cx) {
152 task::Poll::Ready(Ok(output))
153 } else if this.timer.poll(cx).is_ready() {
154 task::Poll::Ready(Err(Timeout))
155 } else {
156 task::Poll::Pending
157 }
158 }
159}
160
161pub(crate) fn atomic_incr_if_not_zero(counter: &AtomicUsize) -> usize {
164 let mut loaded = counter.load(SeqCst);
165 loop {
166 if loaded == 0 {
167 return 0;
168 }
169 match counter.compare_exchange_weak(loaded, loaded + 1, SeqCst, SeqCst) {
170 Ok(x) => return x + 1,
171 Err(actual) => loaded = actual,
172 }
173 }
174}
175
176#[inline]
178pub(crate) fn round_half_toward_zero(value: f32) -> f32 {
179 (value.abs() - 0.5).ceil().copysign(value)
180}
181
182#[inline]
183pub(crate) fn round_half_toward_zero_f64(value: f64) -> f64 {
184 (value.abs() - 0.5).ceil().copysign(value)
185}
186
187#[inline]
188pub(crate) fn round_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
189 round_half_toward_zero(logical * scale_factor)
190}
191
192#[inline]
193pub(crate) fn round_stroke_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
194 if logical == 0.0 {
195 0.0
196 } else {
197 round_to_device_pixel(logical.max(0.0), scale_factor).max(1.0)
198 }
199}
200
201#[inline]
202pub(crate) fn floor_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
203 (logical * scale_factor).floor()
204}
205
206#[inline]
207pub(crate) fn ceil_to_device_pixel(logical: f32, scale_factor: f32) -> f32 {
208 (logical * scale_factor).ceil()
209}
210
211#[cfg(test)]
212mod tests {
213 use crate::TestAppContext;
214
215 use super::*;
216
217 #[test]
218 fn test_round_half_toward_zero() {
219 assert_eq!(round_half_toward_zero(0.5), 0.0);
221 assert_eq!(round_half_toward_zero(1.5), 1.0);
222 assert_eq!(round_half_toward_zero(2.5), 2.0);
223 assert_eq!(round_half_toward_zero(-0.5), 0.0);
224 assert_eq!(round_half_toward_zero(-1.5), -1.0);
225 assert_eq!(round_half_toward_zero(-2.5), -2.0);
226
227 assert_eq!(round_half_toward_zero(1.5001), 2.0);
229 assert_eq!(round_half_toward_zero(1.4999), 1.0);
230 assert_eq!(round_half_toward_zero(-1.5001), -2.0);
231 assert_eq!(round_half_toward_zero(-1.4999), -1.0);
232
233 assert_eq!(round_half_toward_zero(0.0), 0.0);
235 assert_eq!(round_half_toward_zero(3.0), 3.0);
236 assert_eq!(round_half_toward_zero(-3.0), -3.0);
237 }
238
239 #[test]
240 fn test_device_pixel_helpers() {
241 assert_eq!(round_to_device_pixel(1.0, 1.5), 1.0);
243 assert_eq!(round_to_device_pixel(0.3, 2.0), 1.0);
245 assert_eq!(round_to_device_pixel(1.4, 1.0), 1.0);
246 assert_eq!(round_to_device_pixel(1.6, 1.0), 2.0);
247
248 assert_eq!(round_stroke_to_device_pixel(0.0, 1.0), 0.0);
250 assert_eq!(round_stroke_to_device_pixel(0.4, 1.0), 1.0);
251 assert_eq!(round_stroke_to_device_pixel(0.5, 1.0), 1.0);
252 assert_eq!(round_stroke_to_device_pixel(1.0, 1.5), 1.0);
253 assert_eq!(round_stroke_to_device_pixel(1.6, 1.0), 2.0);
254
255 assert_eq!(floor_to_device_pixel(0.3, 2.0), 0.0);
257 assert_eq!(ceil_to_device_pixel(0.3, 2.0), 1.0);
258 assert_eq!(floor_to_device_pixel(2.1, 1.0), 2.0);
259 assert_eq!(ceil_to_device_pixel(2.1, 1.0), 3.0);
260
261 assert_eq!(round_to_device_pixel(2.0, 2.0), 4.0);
263 assert_eq!(floor_to_device_pixel(2.0, 2.0), 4.0);
264 assert_eq!(ceil_to_device_pixel(2.0, 2.0), 4.0);
265 }
266
267 #[test]
268 fn test_round_half_toward_zero_f64() {
269 assert_eq!(round_half_toward_zero_f64(0.5), 0.0);
270 assert_eq!(round_half_toward_zero_f64(-0.5), 0.0);
271 assert_eq!(round_half_toward_zero_f64(1.5), 1.0);
272 assert_eq!(round_half_toward_zero_f64(-1.5), -1.0);
273 assert_eq!(round_half_toward_zero_f64(2.5001), 3.0);
274 }
275
276 #[gpui::test]
277 async fn test_with_timeout(cx: &mut TestAppContext) {
278 Task::ready(())
279 .with_timeout(Duration::from_secs(1), &cx.executor())
280 .await
281 .expect("Timeout should be noop");
282
283 let long_duration = Duration::from_secs(6000);
284 let short_duration = Duration::from_secs(1);
285 cx.executor()
286 .timer(long_duration)
287 .with_timeout(short_duration, &cx.executor())
288 .await
289 .expect_err("timeout should have triggered");
290
291 let fut = cx
292 .executor()
293 .timer(long_duration)
294 .with_timeout(short_duration, &cx.executor());
295 cx.executor().advance_clock(short_duration * 2);
296 futures::FutureExt::now_or_never(fut)
297 .unwrap_or_else(|| panic!("timeout should have triggered"))
298 .expect_err("timeout");
299 }
300}