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
188    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
189    where
190        Self: Sized;
191
192    fn warn_on_err(self) -> LogErrorFuture<Self>
193    where
194        Self: Sized;
195    fn unwrap(self) -> UnwrapFuture<Self>
196    where
197        Self: Sized;
198}
199
200impl<F, T, E> TryFutureExt for F
201where
202    F: Future<Output = Result<T, E>>,
203    E: std::fmt::Debug,
204{
205    #[track_caller]
206    fn log_err(self) -> LogErrorFuture<Self>
207    where
208        Self: Sized,
209    {
210        let location = Location::caller();
211        LogErrorFuture(self, log::Level::Error, *location)
212    }
213
214    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
215    where
216        Self: Sized,
217    {
218        LogErrorFuture(self, log::Level::Error, location)
219    }
220
221    #[track_caller]
222    fn warn_on_err(self) -> LogErrorFuture<Self>
223    where
224        Self: Sized,
225    {
226        let location = Location::caller();
227        LogErrorFuture(self, log::Level::Warn, *location)
228    }
229
230    fn unwrap(self) -> UnwrapFuture<Self>
231    where
232        Self: Sized,
233    {
234        UnwrapFuture(self)
235    }
236}
237
238pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
239
240impl<F, T, E> Future for LogErrorFuture<F>
241where
242    F: Future<Output = Result<T, E>>,
243    E: std::fmt::Debug,
244{
245    type Output = Option<T>;
246
247    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
248        let level = self.1;
249        let location = self.2;
250        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
251        match inner.poll(cx) {
252            Poll::Ready(output) => Poll::Ready(match output {
253                Ok(output) => Some(output),
254                Err(error) => {
255                    log::log!(
256                        level,
257                        "{}:{}: {:?}",
258                        location.file(),
259                        location.line(),
260                        error
261                    );
262                    None
263                }
264            }),
265            Poll::Pending => Poll::Pending,
266        }
267    }
268}
269
270pub struct UnwrapFuture<F>(F);
271
272impl<F, T, E> Future for UnwrapFuture<F>
273where
274    F: Future<Output = Result<T, E>>,
275    E: std::fmt::Debug,
276{
277    type Output = T;
278
279    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
280        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
281        match inner.poll(cx) {
282            Poll::Ready(result) => Poll::Ready(result.unwrap()),
283            Poll::Pending => Poll::Pending,
284        }
285    }
286}
287
288pub struct Deferred<F: FnOnce()>(Option<F>);
289
290impl<F: FnOnce()> Deferred<F> {
291    /// Drop without running the deferred function.
292    pub fn cancel(mut self) {
293        self.0.take();
294    }
295}
296
297impl<F: FnOnce()> Drop for Deferred<F> {
298    fn drop(&mut self) {
299        if let Some(f) = self.0.take() {
300            f()
301        }
302    }
303}
304
305/// Run the given function when the returned value is dropped (unless it's cancelled).
306pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
307    Deferred(Some(f))
308}
309
310pub struct RandomCharIter<T: Rng> {
311    rng: T,
312    simple_text: bool,
313}
314
315impl<T: Rng> RandomCharIter<T> {
316    pub fn new(rng: T) -> Self {
317        Self {
318            rng,
319            simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
320        }
321    }
322
323    pub fn with_simple_text(mut self) -> Self {
324        self.simple_text = true;
325        self
326    }
327}
328
329impl<T: Rng> Iterator for RandomCharIter<T> {
330    type Item = char;
331
332    fn next(&mut self) -> Option<Self::Item> {
333        if self.simple_text {
334            return if self.rng.gen_range(0..100) < 5 {
335                Some('\n')
336            } else {
337                Some(self.rng.gen_range(b'a'..b'z' + 1).into())
338            };
339        }
340
341        match self.rng.gen_range(0..100) {
342            // whitespace
343            0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
344            // two-byte greek letters
345            20..=32 => char::from_u32(self.rng.gen_range(('α' as u32)..('ω' as u32 + 1))),
346            // // three-byte characters
347            33..=45 => ['✋', '✅', '❌', '❎', '⭐']
348                .choose(&mut self.rng)
349                .copied(),
350            // // four-byte characters
351            46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
352            // ascii letters
353            _ => Some(self.rng.gen_range(b'a'..b'z' + 1).into()),
354        }
355    }
356}
357
358/// Get an embedded file as a string.
359pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
360    match A::get(path).unwrap().data {
361        Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
362        Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
363    }
364}
365
366// copy unstable standard feature option unzip
367// https://github.com/rust-lang/rust/issues/87800
368// Remove when this ship in Rust 1.66 or 1.67
369pub fn unzip_option<T, U>(option: Option<(T, U)>) -> (Option<T>, Option<U>) {
370    match option {
371        Some((a, b)) => (Some(a), Some(b)),
372        None => (None, None),
373    }
374}
375
376/// Evaluates to an immediately invoked function expression. Good for using the ? operator
377/// in functions which do not return an Option or Result
378#[macro_export]
379macro_rules! maybe {
380    ($block:block) => {
381        (|| $block)()
382    };
383}
384
385/// Evaluates to an immediately invoked function expression. Good for using the ? operator
386/// in functions which do not return an Option or Result, but async.
387#[macro_export]
388macro_rules! async_maybe {
389    ($block:block) => {
390        (|| async move { $block })()
391    };
392}
393
394pub trait RangeExt<T> {
395    fn sorted(&self) -> Self;
396    fn to_inclusive(&self) -> RangeInclusive<T>;
397    fn overlaps(&self, other: &Range<T>) -> bool;
398    fn contains_inclusive(&self, other: &Range<T>) -> bool;
399}
400
401impl<T: Ord + Clone> RangeExt<T> for Range<T> {
402    fn sorted(&self) -> Self {
403        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
404    }
405
406    fn to_inclusive(&self) -> RangeInclusive<T> {
407        self.start.clone()..=self.end.clone()
408    }
409
410    fn overlaps(&self, other: &Range<T>) -> bool {
411        self.start < other.end && other.start < self.end
412    }
413
414    fn contains_inclusive(&self, other: &Range<T>) -> bool {
415        self.start <= other.start && other.end <= self.end
416    }
417}
418
419impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
420    fn sorted(&self) -> Self {
421        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
422    }
423
424    fn to_inclusive(&self) -> RangeInclusive<T> {
425        self.clone()
426    }
427
428    fn overlaps(&self, other: &Range<T>) -> bool {
429        self.start() < &other.end && &other.start <= self.end()
430    }
431
432    fn contains_inclusive(&self, other: &Range<T>) -> bool {
433        self.start() <= &other.start && &other.end <= self.end()
434    }
435}
436
437static GPUI_LOADED: AtomicU32 = AtomicU32::new(0);
438
439pub fn gpui2_loaded() {
440    if GPUI_LOADED.fetch_add(2, std::sync::atomic::Ordering::SeqCst) != 0 {
441        panic!("=========\nYou are loading both GPUI1 and GPUI2 in the same build!\nFix Your Dependencies with cargo tree!\n=========")
442    }
443}
444
445pub fn gpui1_loaded() {
446    if GPUI_LOADED.fetch_add(1, std::sync::atomic::Ordering::SeqCst) != 0 {
447        panic!("=========\nYou are loading both GPUI1 and GPUI2 in the same build!\nFix Your Dependencies with cargo tree!\n=========")
448    }
449}
450
451#[cfg(test)]
452mod tests {
453    use super::*;
454
455    #[test]
456    fn test_extend_sorted() {
457        let mut vec = vec![];
458
459        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
460        assert_eq!(vec, &[21, 17, 13, 8, 1]);
461
462        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
463        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
464
465        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
466        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
467    }
468
469    #[test]
470    fn test_iife() {
471        fn option_returning_function() -> Option<()> {
472            None
473        }
474
475        let foo = maybe!({
476            option_returning_function()?;
477            Some(())
478        });
479
480        assert_eq!(foo, None);
481    }
482
483    #[test]
484    fn test_trancate_and_trailoff() {
485        assert_eq!(truncate_and_trailoff("", 5), "");
486        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
487        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
488        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
489    }
490}