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 it's length is greater than `max_chars` and
45/// appends "..." to the string. Returns string unchanged if it's 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 it's length is greater than `max_chars` and
57/// prepends the string with "...". Returns string unchanged if it's 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 fn warn_on_err(self) -> Option<Self::Ok>;
141 fn inspect_error(self, func: impl FnOnce(&E)) -> Self;
142}
143
144impl<T, E> ResultExt<E> for Result<T, E>
145where
146 E: std::fmt::Debug,
147{
148 type Ok = T;
149
150 #[track_caller]
151 fn log_err(self) -> Option<T> {
152 match self {
153 Ok(value) => Some(value),
154 Err(error) => {
155 let caller = Location::caller();
156 log::error!("{}:{}: {:?}", caller.file(), caller.line(), error);
157 None
158 }
159 }
160 }
161
162 fn warn_on_err(self) -> Option<T> {
163 match self {
164 Ok(value) => Some(value),
165 Err(error) => {
166 log::warn!("{:?}", error);
167 None
168 }
169 }
170 }
171
172 /// https://doc.rust-lang.org/std/result/enum.Result.html#method.inspect_err
173 fn inspect_error(self, func: impl FnOnce(&E)) -> Self {
174 if let Err(err) = &self {
175 func(err);
176 }
177
178 self
179 }
180}
181
182pub trait TryFutureExt {
183 fn log_err(self) -> LogErrorFuture<Self>
184 where
185 Self: Sized;
186
187 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
188 where
189 Self: Sized;
190
191 fn warn_on_err(self) -> LogErrorFuture<Self>
192 where
193 Self: Sized;
194 fn unwrap(self) -> UnwrapFuture<Self>
195 where
196 Self: Sized;
197}
198
199impl<F, T, E> TryFutureExt for F
200where
201 F: Future<Output = Result<T, E>>,
202 E: std::fmt::Debug,
203{
204 #[track_caller]
205 fn log_err(self) -> LogErrorFuture<Self>
206 where
207 Self: Sized,
208 {
209 let location = Location::caller();
210 LogErrorFuture(self, log::Level::Error, *location)
211 }
212
213 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
214 where
215 Self: Sized,
216 {
217 LogErrorFuture(self, log::Level::Error, location)
218 }
219
220 #[track_caller]
221 fn warn_on_err(self) -> LogErrorFuture<Self>
222 where
223 Self: Sized,
224 {
225 let location = Location::caller();
226 LogErrorFuture(self, log::Level::Warn, *location)
227 }
228
229 fn unwrap(self) -> UnwrapFuture<Self>
230 where
231 Self: Sized,
232 {
233 UnwrapFuture(self)
234 }
235}
236
237pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
238
239impl<F, T, E> Future for LogErrorFuture<F>
240where
241 F: Future<Output = Result<T, E>>,
242 E: std::fmt::Debug,
243{
244 type Output = Option<T>;
245
246 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
247 let level = self.1;
248 let location = self.2;
249 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
250 match inner.poll(cx) {
251 Poll::Ready(output) => Poll::Ready(match output {
252 Ok(output) => Some(output),
253 Err(error) => {
254 log::log!(
255 level,
256 "{}:{}: {:?}",
257 location.file(),
258 location.line(),
259 error
260 );
261 None
262 }
263 }),
264 Poll::Pending => Poll::Pending,
265 }
266 }
267}
268
269pub struct UnwrapFuture<F>(F);
270
271impl<F, T, E> Future for UnwrapFuture<F>
272where
273 F: Future<Output = Result<T, E>>,
274 E: std::fmt::Debug,
275{
276 type Output = T;
277
278 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
279 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
280 match inner.poll(cx) {
281 Poll::Ready(result) => Poll::Ready(result.unwrap()),
282 Poll::Pending => Poll::Pending,
283 }
284 }
285}
286
287pub struct Deferred<F: FnOnce()>(Option<F>);
288
289impl<F: FnOnce()> Deferred<F> {
290 /// Drop without running the deferred function.
291 pub fn cancel(mut self) {
292 self.0.take();
293 }
294}
295
296impl<F: FnOnce()> Drop for Deferred<F> {
297 fn drop(&mut self) {
298 if let Some(f) = self.0.take() {
299 f()
300 }
301 }
302}
303
304/// Run the given function when the returned value is dropped (unless it's cancelled).
305pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
306 Deferred(Some(f))
307}
308
309pub struct RandomCharIter<T: Rng> {
310 rng: T,
311 simple_text: bool,
312}
313
314impl<T: Rng> RandomCharIter<T> {
315 pub fn new(rng: T) -> Self {
316 Self {
317 rng,
318 simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
319 }
320 }
321
322 pub fn with_simple_text(mut self) -> Self {
323 self.simple_text = true;
324 self
325 }
326}
327
328impl<T: Rng> Iterator for RandomCharIter<T> {
329 type Item = char;
330
331 fn next(&mut self) -> Option<Self::Item> {
332 if self.simple_text {
333 return if self.rng.gen_range(0..100) < 5 {
334 Some('\n')
335 } else {
336 Some(self.rng.gen_range(b'a'..b'z' + 1).into())
337 };
338 }
339
340 match self.rng.gen_range(0..100) {
341 // whitespace
342 0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
343 // two-byte greek letters
344 20..=32 => char::from_u32(self.rng.gen_range(('α' as u32)..('ω' as u32 + 1))),
345 // // three-byte characters
346 33..=45 => ['✋', '✅', '❌', '❎', '⭐']
347 .choose(&mut self.rng)
348 .copied(),
349 // // four-byte characters
350 46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
351 // ascii letters
352 _ => Some(self.rng.gen_range(b'a'..b'z' + 1).into()),
353 }
354 }
355}
356
357/// Get an embedded file as a string.
358pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
359 match A::get(path).unwrap().data {
360 Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
361 Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
362 }
363}
364
365// copy unstable standard feature option unzip
366// https://github.com/rust-lang/rust/issues/87800
367// Remove when this ship in Rust 1.66 or 1.67
368pub fn unzip_option<T, U>(option: Option<(T, U)>) -> (Option<T>, Option<U>) {
369 match option {
370 Some((a, b)) => (Some(a), Some(b)),
371 None => (None, None),
372 }
373}
374
375/// Evaluates to an immediately invoked function expression. Good for using the ? operator
376/// in functions which do not return an Option or Result
377#[macro_export]
378macro_rules! maybe {
379 ($block:block) => {
380 (|| $block)()
381 };
382}
383
384/// Evaluates to an immediately invoked function expression. Good for using the ? operator
385/// in functions which do not return an Option or Result, but async.
386#[macro_export]
387macro_rules! async_maybe {
388 ($block:block) => {
389 (|| async move { $block })()
390 };
391}
392
393pub trait RangeExt<T> {
394 fn sorted(&self) -> Self;
395 fn to_inclusive(&self) -> RangeInclusive<T>;
396 fn overlaps(&self, other: &Range<T>) -> bool;
397 fn contains_inclusive(&self, other: &Range<T>) -> bool;
398}
399
400impl<T: Ord + Clone> RangeExt<T> for Range<T> {
401 fn sorted(&self) -> Self {
402 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
403 }
404
405 fn to_inclusive(&self) -> RangeInclusive<T> {
406 self.start.clone()..=self.end.clone()
407 }
408
409 fn overlaps(&self, other: &Range<T>) -> bool {
410 self.start < other.end && other.start < self.end
411 }
412
413 fn contains_inclusive(&self, other: &Range<T>) -> bool {
414 self.start <= other.start && other.end <= self.end
415 }
416}
417
418impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
419 fn sorted(&self) -> Self {
420 cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
421 }
422
423 fn to_inclusive(&self) -> RangeInclusive<T> {
424 self.clone()
425 }
426
427 fn overlaps(&self, other: &Range<T>) -> bool {
428 self.start() < &other.end && &other.start <= self.end()
429 }
430
431 fn contains_inclusive(&self, other: &Range<T>) -> bool {
432 self.start() <= &other.start && &other.end <= self.end()
433 }
434}
435
436#[cfg(test)]
437mod tests {
438 use super::*;
439
440 #[test]
441 fn test_extend_sorted() {
442 let mut vec = vec![];
443
444 extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
445 assert_eq!(vec, &[21, 17, 13, 8, 1]);
446
447 extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
448 assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
449
450 extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
451 assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
452 }
453
454 #[test]
455 fn test_iife() {
456 fn option_returning_function() -> Option<()> {
457 None
458 }
459
460 let foo = maybe!({
461 option_returning_function()?;
462 Some(())
463 });
464
465 assert_eq!(foo, None);
466 }
467
468 #[test]
469 fn test_trancate_and_trailoff() {
470 assert_eq!(truncate_and_trailoff("", 5), "");
471 assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
472 assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
473 assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
474 }
475}