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