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