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