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