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