util.rs

  1pub mod arc_cow;
  2pub mod channel;
  3pub mod fs;
  4pub mod github;
  5pub mod http;
  6pub mod paths;
  7#[cfg(any(test, feature = "test-support"))]
  8pub mod test;
  9
 10use std::{
 11    borrow::Cow,
 12    cmp::{self, Ordering},
 13    ops::{AddAssign, Range, RangeInclusive},
 14    panic::Location,
 15    pin::Pin,
 16    sync::atomic::AtomicU32,
 17    task::{Context, Poll},
 18};
 19
 20pub use backtrace::Backtrace;
 21use futures::Future;
 22use rand::{seq::SliceRandom, Rng};
 23
 24pub use take_until::*;
 25
 26#[macro_export]
 27macro_rules! debug_panic {
 28    ( $($fmt_arg:tt)* ) => {
 29        if cfg!(debug_assertions) {
 30            panic!( $($fmt_arg)* );
 31        } else {
 32            let backtrace = $crate::Backtrace::new();
 33            log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace);
 34        }
 35    };
 36}
 37
 38pub fn truncate(s: &str, max_chars: usize) -> &str {
 39    match s.char_indices().nth(max_chars) {
 40        None => s,
 41        Some((idx, _)) => &s[..idx],
 42    }
 43}
 44
 45/// Removes characters from the end of the string if it's length is greater than `max_chars` and
 46/// appends "..." to the string. Returns string unchanged if it's length is smaller than max_chars.
 47pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
 48    debug_assert!(max_chars >= 5);
 49
 50    let truncation_ix = s.char_indices().map(|(i, _)| i).nth(max_chars);
 51    match truncation_ix {
 52        Some(length) => s[..length].to_string() + "",
 53        None => s.to_string(),
 54    }
 55}
 56
 57/// Removes characters from the front of the string if it's length is greater than `max_chars` and
 58/// prepends the string with "...". Returns string unchanged if it's length is smaller than max_chars.
 59pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String {
 60    debug_assert!(max_chars >= 5);
 61
 62    let truncation_ix = s.char_indices().map(|(i, _)| i).nth_back(max_chars);
 63    match truncation_ix {
 64        Some(length) => "".to_string() + &s[length..],
 65        None => s.to_string(),
 66    }
 67}
 68
 69pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
 70    let prev = *value;
 71    *value += T::from(1);
 72    prev
 73}
 74
 75/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
 76/// enforcing a maximum length. This also de-duplicates items. Sort the items according to the given callback. Before calling this,
 77/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
 78pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
 79where
 80    I: IntoIterator<Item = T>,
 81    F: FnMut(&T, &T) -> Ordering,
 82{
 83    let mut start_index = 0;
 84    for new_item in new_items {
 85        if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
 86            let index = start_index + i;
 87            if vec.len() < limit {
 88                vec.insert(index, new_item);
 89            } else if index < vec.len() {
 90                vec.pop();
 91                vec.insert(index, new_item);
 92            }
 93            start_index = index;
 94        }
 95    }
 96}
 97
 98pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
 99    use serde_json::Value;
100
101    match (source, target) {
102        (Value::Object(source), Value::Object(target)) => {
103            for (key, value) in source {
104                if let Some(target) = target.get_mut(&key) {
105                    merge_json_value_into(value, target);
106                } else {
107                    target.insert(key.clone(), value);
108                }
109            }
110        }
111
112        (source, target) => *target = source,
113    }
114}
115
116pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
117    use serde_json::Value;
118    if let Value::Object(source_object) = source {
119        let target_object = if let Value::Object(target) = target {
120            target
121        } else {
122            *target = Value::Object(Default::default());
123            target.as_object_mut().unwrap()
124        };
125        for (key, value) in source_object {
126            if let Some(target) = target_object.get_mut(&key) {
127                merge_non_null_json_value_into(value, target);
128            } else if !value.is_null() {
129                target_object.insert(key.clone(), value);
130            }
131        }
132    } else if !source.is_null() {
133        *target = source
134    }
135}
136
137pub trait ResultExt<E> {
138    type Ok;
139
140    fn log_err(self) -> Option<Self::Ok>;
141    fn warn_on_err(self) -> Option<Self::Ok>;
142    fn inspect_error(self, func: impl FnOnce(&E)) -> Self;
143}
144
145impl<T, E> ResultExt<E> for Result<T, E>
146where
147    E: std::fmt::Debug,
148{
149    type Ok = T;
150
151    #[track_caller]
152    fn log_err(self) -> Option<T> {
153        match self {
154            Ok(value) => Some(value),
155            Err(error) => {
156                let caller = Location::caller();
157                log::error!("{}:{}: {:?}", caller.file(), caller.line(), error);
158                None
159            }
160        }
161    }
162
163    fn warn_on_err(self) -> Option<T> {
164        match self {
165            Ok(value) => Some(value),
166            Err(error) => {
167                log::warn!("{:?}", error);
168                None
169            }
170        }
171    }
172
173    /// https://doc.rust-lang.org/std/result/enum.Result.html#method.inspect_err
174    fn inspect_error(self, func: impl FnOnce(&E)) -> Self {
175        if let Err(err) = &self {
176            func(err);
177        }
178
179        self
180    }
181}
182
183pub trait TryFutureExt {
184    fn log_err(self) -> LogErrorFuture<Self>
185    where
186        Self: Sized;
187    fn warn_on_err(self) -> LogErrorFuture<Self>
188    where
189        Self: Sized;
190    fn unwrap(self) -> UnwrapFuture<Self>
191    where
192        Self: Sized;
193}
194
195impl<F, T, E> TryFutureExt for F
196where
197    F: Future<Output = Result<T, E>>,
198    E: std::fmt::Debug,
199{
200    fn log_err(self) -> LogErrorFuture<Self>
201    where
202        Self: Sized,
203    {
204        LogErrorFuture(self, log::Level::Error)
205    }
206
207    fn warn_on_err(self) -> LogErrorFuture<Self>
208    where
209        Self: Sized,
210    {
211        LogErrorFuture(self, log::Level::Warn)
212    }
213
214    fn unwrap(self) -> UnwrapFuture<Self>
215    where
216        Self: Sized,
217    {
218        UnwrapFuture(self)
219    }
220}
221
222pub struct LogErrorFuture<F>(F, log::Level);
223
224impl<F, T, E> Future for LogErrorFuture<F>
225where
226    F: Future<Output = Result<T, E>>,
227    E: std::fmt::Debug,
228{
229    type Output = Option<T>;
230
231    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
232        let level = self.1;
233        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
234        match inner.poll(cx) {
235            Poll::Ready(output) => Poll::Ready(match output {
236                Ok(output) => Some(output),
237                Err(error) => {
238                    log::log!(level, "{:?}", error);
239                    None
240                }
241            }),
242            Poll::Pending => Poll::Pending,
243        }
244    }
245}
246
247pub struct UnwrapFuture<F>(F);
248
249impl<F, T, E> Future for UnwrapFuture<F>
250where
251    F: Future<Output = Result<T, E>>,
252    E: std::fmt::Debug,
253{
254    type Output = T;
255
256    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
257        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
258        match inner.poll(cx) {
259            Poll::Ready(result) => Poll::Ready(result.unwrap()),
260            Poll::Pending => Poll::Pending,
261        }
262    }
263}
264
265pub struct Deferred<F: FnOnce()>(Option<F>);
266
267impl<F: FnOnce()> Deferred<F> {
268    /// Drop without running the deferred function.
269    pub fn cancel(mut self) {
270        self.0.take();
271    }
272}
273
274impl<F: FnOnce()> Drop for Deferred<F> {
275    fn drop(&mut self) {
276        if let Some(f) = self.0.take() {
277            f()
278        }
279    }
280}
281
282/// Run the given function when the returned value is dropped (unless it's cancelled).
283pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
284    Deferred(Some(f))
285}
286
287pub struct RandomCharIter<T: Rng> {
288    rng: T,
289    simple_text: bool,
290}
291
292impl<T: Rng> RandomCharIter<T> {
293    pub fn new(rng: T) -> Self {
294        Self {
295            rng,
296            simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
297        }
298    }
299
300    pub fn with_simple_text(mut self) -> Self {
301        self.simple_text = true;
302        self
303    }
304}
305
306impl<T: Rng> Iterator for RandomCharIter<T> {
307    type Item = char;
308
309    fn next(&mut self) -> Option<Self::Item> {
310        if self.simple_text {
311            return if self.rng.gen_range(0..100) < 5 {
312                Some('\n')
313            } else {
314                Some(self.rng.gen_range(b'a'..b'z' + 1).into())
315            };
316        }
317
318        match self.rng.gen_range(0..100) {
319            // whitespace
320            0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
321            // two-byte greek letters
322            20..=32 => char::from_u32(self.rng.gen_range(('α' as u32)..('ω' as u32 + 1))),
323            // // three-byte characters
324            33..=45 => ['✋', '✅', '❌', '❎', '⭐']
325                .choose(&mut self.rng)
326                .copied(),
327            // // four-byte characters
328            46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
329            // ascii letters
330            _ => Some(self.rng.gen_range(b'a'..b'z' + 1).into()),
331        }
332    }
333}
334
335/// Get an embedded file as a string.
336pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
337    match A::get(path).unwrap().data {
338        Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
339        Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
340    }
341}
342
343// copy unstable standard feature option unzip
344// https://github.com/rust-lang/rust/issues/87800
345// Remove when this ship in Rust 1.66 or 1.67
346pub fn unzip_option<T, U>(option: Option<(T, U)>) -> (Option<T>, Option<U>) {
347    match option {
348        Some((a, b)) => (Some(a), Some(b)),
349        None => (None, None),
350    }
351}
352
353/// Evaluates to an immediately invoked function expression. Good for using the ? operator
354/// in functions which do not return an Option or Result
355#[macro_export]
356macro_rules! maybe {
357    ($block:block) => {
358        (|| $block)()
359    };
360}
361
362/// Evaluates to an immediately invoked function expression. Good for using the ? operator
363/// in functions which do not return an Option or Result, but async.
364#[macro_export]
365macro_rules! async_maybe {
366    ($block:block) => {
367        (|| async move { $block })()
368    };
369}
370
371pub trait RangeExt<T> {
372    fn sorted(&self) -> Self;
373    fn to_inclusive(&self) -> RangeInclusive<T>;
374    fn overlaps(&self, other: &Range<T>) -> bool;
375    fn contains_inclusive(&self, other: &Range<T>) -> bool;
376}
377
378impl<T: Ord + Clone> RangeExt<T> for Range<T> {
379    fn sorted(&self) -> Self {
380        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
381    }
382
383    fn to_inclusive(&self) -> RangeInclusive<T> {
384        self.start.clone()..=self.end.clone()
385    }
386
387    fn overlaps(&self, other: &Range<T>) -> bool {
388        self.start < other.end && other.start < self.end
389    }
390
391    fn contains_inclusive(&self, other: &Range<T>) -> bool {
392        self.start <= other.start && other.end <= self.end
393    }
394}
395
396impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
397    fn sorted(&self) -> Self {
398        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
399    }
400
401    fn to_inclusive(&self) -> RangeInclusive<T> {
402        self.clone()
403    }
404
405    fn overlaps(&self, other: &Range<T>) -> bool {
406        self.start() < &other.end && &other.start <= self.end()
407    }
408
409    fn contains_inclusive(&self, other: &Range<T>) -> bool {
410        self.start() <= &other.start && &other.end <= self.end()
411    }
412}
413
414static GPUI_LOADED: AtomicU32 = AtomicU32::new(0);
415
416pub fn gpui2_loaded() {
417    if GPUI_LOADED.fetch_add(2, std::sync::atomic::Ordering::SeqCst) != 0 {
418        panic!("=========\nYou are loading both GPUI1 and GPUI2 in the same build!\nFix Your Dependencies with cargo tree!\n=========")
419    }
420}
421
422pub fn gpui1_loaded() {
423    if GPUI_LOADED.fetch_add(1, std::sync::atomic::Ordering::SeqCst) != 0 {
424        panic!("=========\nYou are loading both GPUI1 and GPUI2 in the same build!\nFix Your Dependencies with cargo tree!\n=========")
425    }
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431
432    #[test]
433    fn test_extend_sorted() {
434        let mut vec = vec![];
435
436        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
437        assert_eq!(vec, &[21, 17, 13, 8, 1]);
438
439        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
440        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
441
442        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
443        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
444    }
445
446    #[test]
447    fn test_iife() {
448        fn option_returning_function() -> Option<()> {
449            None
450        }
451
452        let foo = maybe!({
453            option_returning_function()?;
454            Some(())
455        });
456
457        assert_eq!(foo, None);
458    }
459
460    #[test]
461    fn test_trancate_and_trailoff() {
462        assert_eq!(truncate_and_trailoff("", 5), "");
463        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
464        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
465        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
466    }
467}