lib.rs

  1pub mod channel;
  2pub mod paths;
  3#[cfg(any(test, feature = "test-support"))]
  4pub mod test;
  5
  6pub use backtrace::Backtrace;
  7use futures::Future;
  8use rand::{seq::SliceRandom, Rng};
  9use std::{
 10    cmp::Ordering,
 11    ops::AddAssign,
 12    path::Path,
 13    pin::Pin,
 14    task::{Context, Poll},
 15};
 16
 17#[derive(Debug, Default)]
 18pub struct StaffMode(pub bool);
 19
 20impl std::ops::Deref for StaffMode {
 21    type Target = bool;
 22
 23    fn deref(&self) -> &Self::Target {
 24        &self.0
 25    }
 26}
 27
 28#[macro_export]
 29macro_rules! debug_panic {
 30    ( $($fmt_arg:tt)* ) => {
 31        if cfg!(debug_assertions) {
 32            panic!( $($fmt_arg)* );
 33        } else {
 34            let backtrace = $crate::Backtrace::new();
 35            log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace);
 36        }
 37    };
 38}
 39
 40pub fn truncate(s: &str, max_chars: usize) -> &str {
 41    match s.char_indices().nth(max_chars) {
 42        None => s,
 43        Some((idx, _)) => &s[..idx],
 44    }
 45}
 46
 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
 57pub fn open<P: AsRef<Path>>(path: P) {
 58    let path_to_open = path.as_ref().to_string_lossy();
 59    #[cfg(target_os = "macos")]
 60    {
 61        std::process::Command::new("open")
 62            .arg(path_to_open.as_ref())
 63            .spawn()
 64            .log_err();
 65    }
 66}
 67
 68pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
 69    let prev = *value;
 70    *value += T::from(1);
 71    prev
 72}
 73
 74/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
 75/// enforcing a maximum length. Sort the items according to the given callback. Before calling this,
 76/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
 77pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
 78where
 79    I: IntoIterator<Item = T>,
 80    F: FnMut(&T, &T) -> Ordering,
 81{
 82    let mut start_index = 0;
 83    for new_item in new_items {
 84        if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
 85            let index = start_index + i;
 86            if vec.len() < limit {
 87                vec.insert(index, new_item);
 88            } else if index < vec.len() {
 89                vec.pop();
 90                vec.insert(index, new_item);
 91            }
 92            start_index = index;
 93        }
 94    }
 95}
 96
 97pub trait ResultExt {
 98    type Ok;
 99
100    fn log_err(self) -> Option<Self::Ok>;
101    fn warn_on_err(self) -> Option<Self::Ok>;
102}
103
104impl<T, E> ResultExt for Result<T, E>
105where
106    E: std::fmt::Debug,
107{
108    type Ok = T;
109
110    fn log_err(self) -> Option<T> {
111        match self {
112            Ok(value) => Some(value),
113            Err(error) => {
114                log::error!("{:?}", error);
115                None
116            }
117        }
118    }
119
120    fn warn_on_err(self) -> Option<T> {
121        match self {
122            Ok(value) => Some(value),
123            Err(error) => {
124                log::warn!("{:?}", error);
125                None
126            }
127        }
128    }
129}
130
131pub trait TryFutureExt {
132    fn log_err(self) -> LogErrorFuture<Self>
133    where
134        Self: Sized;
135    fn warn_on_err(self) -> LogErrorFuture<Self>
136    where
137        Self: Sized;
138}
139
140impl<F, T> TryFutureExt for F
141where
142    F: Future<Output = anyhow::Result<T>>,
143{
144    fn log_err(self) -> LogErrorFuture<Self>
145    where
146        Self: Sized,
147    {
148        LogErrorFuture(self, log::Level::Error)
149    }
150
151    fn warn_on_err(self) -> LogErrorFuture<Self>
152    where
153        Self: Sized,
154    {
155        LogErrorFuture(self, log::Level::Warn)
156    }
157}
158
159pub struct LogErrorFuture<F>(F, log::Level);
160
161impl<F, T> Future for LogErrorFuture<F>
162where
163    F: Future<Output = anyhow::Result<T>>,
164{
165    type Output = Option<T>;
166
167    fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
168        let level = self.1;
169        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
170        match inner.poll(cx) {
171            Poll::Ready(output) => Poll::Ready(match output {
172                Ok(output) => Some(output),
173                Err(error) => {
174                    log::log!(level, "{:?}", error);
175                    None
176                }
177            }),
178            Poll::Pending => Poll::Pending,
179        }
180    }
181}
182
183struct Defer<F: FnOnce()>(Option<F>);
184
185impl<F: FnOnce()> Drop for Defer<F> {
186    fn drop(&mut self) {
187        if let Some(f) = self.0.take() {
188            f()
189        }
190    }
191}
192
193pub fn defer<F: FnOnce()>(f: F) -> impl Drop {
194    Defer(Some(f))
195}
196
197pub struct RandomCharIter<T: Rng>(T);
198
199impl<T: Rng> RandomCharIter<T> {
200    pub fn new(rng: T) -> Self {
201        Self(rng)
202    }
203}
204
205impl<T: Rng> Iterator for RandomCharIter<T> {
206    type Item = char;
207
208    fn next(&mut self) -> Option<Self::Item> {
209        if std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()) {
210            return if self.0.gen_range(0..100) < 5 {
211                Some('\n')
212            } else {
213                Some(self.0.gen_range(b'a'..b'z' + 1).into())
214            };
215        }
216
217        match self.0.gen_range(0..100) {
218            // whitespace
219            0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.0).copied(),
220            // two-byte greek letters
221            20..=32 => char::from_u32(self.0.gen_range(('α' as u32)..('ω' as u32 + 1))),
222            // // three-byte characters
223            33..=45 => ['✋', '✅', '❌', '❎', '⭐'].choose(&mut self.0).copied(),
224            // // four-byte characters
225            46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.0).copied(),
226            // ascii letters
227            _ => Some(self.0.gen_range(b'a'..b'z' + 1).into()),
228        }
229    }
230}
231
232// copy unstable standard feature option unzip
233// https://github.com/rust-lang/rust/issues/87800
234// Remove when this ship in Rust 1.66 or 1.67
235pub fn unzip_option<T, U>(option: Option<(T, U)>) -> (Option<T>, Option<U>) {
236    match option {
237        Some((a, b)) => (Some(a), Some(b)),
238        None => (None, None),
239    }
240}
241
242/// Immediately invoked function expression. Good for using the ? operator
243/// in functions which do not return an Option or Result
244#[macro_export]
245macro_rules! iife {
246    ($block:block) => {
247        (|| $block)()
248    };
249}
250
251/// Async lImmediately invoked function expression. Good for using the ? operator
252/// in functions which do not return an Option or Result. Async version of above
253#[macro_export]
254macro_rules! async_iife {
255    ($block:block) => {
256        (|| async move { $block })()
257    };
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    #[test]
265    fn test_extend_sorted() {
266        let mut vec = vec![];
267
268        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
269        assert_eq!(vec, &[21, 17, 13, 8, 1]);
270
271        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
272        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
273
274        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
275        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
276    }
277
278    #[test]
279    fn test_iife() {
280        fn option_returning_function() -> Option<()> {
281            None
282        }
283
284        let foo = iife!({
285            option_returning_function()?;
286            Some(())
287        });
288
289        assert_eq!(foo, None);
290    }
291
292    #[test]
293    fn test_trancate_and_trailoff() {
294        assert_eq!(truncate_and_trailoff("", 5), "");
295        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
296        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
297        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
298    }
299}