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