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