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
44pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
45 debug_assert!(max_chars >= 5);
46
47 let truncation_ix = s.char_indices().map(|(i, _)| i).nth(max_chars);
48 match truncation_ix {
49 Some(length) => s[..length].to_string() + "…",
50 None => s.to_string(),
51 }
52}
53
54pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
55 let prev = *value;
56 *value += T::from(1);
57 prev
58}
59
60/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
61/// enforcing a maximum length. This also de-duplicates items. Sort the items according to the given callback. Before calling this,
62/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
63pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
64where
65 I: IntoIterator<Item = T>,
66 F: FnMut(&T, &T) -> Ordering,
67{
68 let mut start_index = 0;
69 for new_item in new_items {
70 if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
71 let index = start_index + i;
72 if vec.len() < limit {
73 vec.insert(index, new_item);
74 } else if index < vec.len() {
75 vec.pop();
76 vec.insert(index, new_item);
77 }
78 start_index = index;
79 }
80 }
81}
82
83pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
84 use serde_json::Value;
85
86 match (source, target) {
87 (Value::Object(source), Value::Object(target)) => {
88 for (key, value) in source {
89 if let Some(target) = target.get_mut(&key) {
90 merge_json_value_into(value, target);
91 } else {
92 target.insert(key.clone(), value);
93 }
94 }
95 }
96
97 (source, target) => *target = source,
98 }
99}
100
101pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
102 use serde_json::Value;
103 if let Value::Object(source_object) = source {
104 let target_object = if let Value::Object(target) = target {
105 target
106 } else {
107 *target = Value::Object(Default::default());
108 target.as_object_mut().unwrap()
109 };
110 for (key, value) in source_object {
111 if let Some(target) = target_object.get_mut(&key) {
112 merge_non_null_json_value_into(value, target);
113 } else if !value.is_null() {
114 target_object.insert(key.clone(), value);
115 }
116 }
117 } else if !source.is_null() {
118 *target = source
119 }
120}
121
122pub trait ResultExt<E> {
123 type Ok;
124
125 fn log_err(self) -> Option<Self::Ok>;
126 fn warn_on_err(self) -> Option<Self::Ok>;
127 fn inspect_error(self, func: impl FnOnce(&E)) -> Self;
128}
129
130impl<T, E> ResultExt<E> for Result<T, E>
131where
132 E: std::fmt::Debug,
133{
134 type Ok = T;
135
136 #[track_caller]
137 fn log_err(self) -> Option<T> {
138 match self {
139 Ok(value) => Some(value),
140 Err(error) => {
141 let caller = Location::caller();
142 log::error!("{}:{}: {:?}", caller.file(), caller.line(), error);
143 None
144 }
145 }
146 }
147
148 fn warn_on_err(self) -> Option<T> {
149 match self {
150 Ok(value) => Some(value),
151 Err(error) => {
152 log::warn!("{:?}", error);
153 None
154 }
155 }
156 }
157
158 /// https://doc.rust-lang.org/std/result/enum.Result.html#method.inspect_err
159 fn inspect_error(self, func: impl FnOnce(&E)) -> Self {
160 if let Err(err) = &self {
161 func(err);
162 }
163
164 self
165 }
166}
167
168pub trait TryFutureExt {
169 fn log_err(self) -> LogErrorFuture<Self>
170 where
171 Self: Sized;
172 fn warn_on_err(self) -> LogErrorFuture<Self>
173 where
174 Self: Sized;
175 fn unwrap(self) -> UnwrapFuture<Self>
176 where
177 Self: Sized;
178}
179
180impl<F, T, E> TryFutureExt for F
181where
182 F: Future<Output = Result<T, E>>,
183 E: std::fmt::Debug,
184{
185 fn log_err(self) -> LogErrorFuture<Self>
186 where
187 Self: Sized,
188 {
189 LogErrorFuture(self, log::Level::Error)
190 }
191
192 fn warn_on_err(self) -> LogErrorFuture<Self>
193 where
194 Self: Sized,
195 {
196 LogErrorFuture(self, log::Level::Warn)
197 }
198
199 fn unwrap(self) -> UnwrapFuture<Self>
200 where
201 Self: Sized,
202 {
203 UnwrapFuture(self)
204 }
205}
206
207pub struct LogErrorFuture<F>(F, log::Level);
208
209impl<F, T, E> Future for LogErrorFuture<F>
210where
211 F: Future<Output = Result<T, E>>,
212 E: std::fmt::Debug,
213{
214 type Output = Option<T>;
215
216 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
217 let level = self.1;
218 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
219 match inner.poll(cx) {
220 Poll::Ready(output) => Poll::Ready(match output {
221 Ok(output) => Some(output),
222 Err(error) => {
223 log::log!(level, "{:?}", error);
224 None
225 }
226 }),
227 Poll::Pending => Poll::Pending,
228 }
229 }
230}
231
232pub struct UnwrapFuture<F>(F);
233
234impl<F, T, E> Future for UnwrapFuture<F>
235where
236 F: Future<Output = Result<T, E>>,
237 E: std::fmt::Debug,
238{
239 type Output = T;
240
241 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
242 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
243 match inner.poll(cx) {
244 Poll::Ready(result) => Poll::Ready(result.unwrap()),
245 Poll::Pending => Poll::Pending,
246 }
247 }
248}
249
250pub struct Deferred<F: FnOnce()>(Option<F>);
251
252impl<F: FnOnce()> Deferred<F> {
253 /// Drop without running the deferred function.
254 pub fn cancel(mut self) {
255 self.0.take();
256 }
257}
258
259impl<F: FnOnce()> Drop for Deferred<F> {
260 fn drop(&mut self) {
261 if let Some(f) = self.0.take() {
262 f()
263 }
264 }
265}
266
267/// Run the given function when the returned value is dropped (unless it's cancelled).
268pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
269 Deferred(Some(f))
270}
271
272pub struct RandomCharIter<T: Rng> {
273 rng: T,
274 simple_text: bool,
275}
276
277impl<T: Rng> RandomCharIter<T> {
278 pub fn new(rng: T) -> Self {
279 Self {
280 rng,
281 simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
282 }
283 }
284
285 pub fn with_simple_text(mut self) -> Self {
286 self.simple_text = true;
287 self
288 }
289}
290
291impl<T: Rng> Iterator for RandomCharIter<T> {
292 type Item = char;
293
294 fn next(&mut self) -> Option<Self::Item> {
295 if self.simple_text {
296 return if self.rng.gen_range(0..100) < 5 {
297 Some('\n')
298 } else {
299 Some(self.rng.gen_range(b'a'..b'z' + 1).into())
300 };
301 }
302
303 match self.rng.gen_range(0..100) {
304 // whitespace
305 0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
306 // two-byte greek letters
307 20..=32 => char::from_u32(self.rng.gen_range(('α' as u32)..('ω' as u32 + 1))),
308 // // three-byte characters
309 33..=45 => ['✋', '✅', '❌', '❎', '⭐']
310 .choose(&mut self.rng)
311 .copied(),
312 // // four-byte characters
313 46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
314 // ascii letters
315 _ => Some(self.rng.gen_range(b'a'..b'z' + 1).into()),
316 }
317 }
318}
319
320/// Get an embedded file as a string.
321pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
322 match A::get(path).unwrap().data {
323 Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
324 Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
325 }
326}
327
328// copy unstable standard feature option unzip
329// https://github.com/rust-lang/rust/issues/87800
330// Remove when this ship in Rust 1.66 or 1.67
331pub fn unzip_option<T, U>(option: Option<(T, U)>) -> (Option<T>, Option<U>) {
332 match option {
333 Some((a, b)) => (Some(a), Some(b)),
334 None => (None, None),
335 }
336}
337
338/// Immediately invoked function expression. Good for using the ? operator
339/// in functions which do not return an Option or Result
340#[macro_export]
341macro_rules! iife {
342 ($block:block) => {
343 (|| $block)()
344 };
345}
346
347/// Async Immediately invoked function expression. Good for using the ? operator
348/// in functions which do not return an Option or Result. Async version of above
349#[macro_export]
350macro_rules! async_iife {
351 ($block:block) => {
352 (|| async move { $block })()
353 };
354}
355
356pub trait RangeExt<T> {
357 fn sorted(&self) -> Self;
358 fn to_inclusive(&self) -> RangeInclusive<T>;
359 fn overlaps(&self, other: &Range<T>) -> bool;
360 fn contains_inclusive(&self, other: &Range<T>) -> bool;
361}
362
363impl<T: Ord + Clone> RangeExt<T> for Range<T> {
364 fn sorted(&self) -> Self {
365 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
366 }
367
368 fn to_inclusive(&self) -> RangeInclusive<T> {
369 self.start.clone()..=self.end.clone()
370 }
371
372 fn overlaps(&self, other: &Range<T>) -> bool {
373 self.start < other.end && other.start < self.end
374 }
375
376 fn contains_inclusive(&self, other: &Range<T>) -> bool {
377 self.start <= other.start && other.end <= self.end
378 }
379}
380
381impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
382 fn sorted(&self) -> Self {
383 cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
384 }
385
386 fn to_inclusive(&self) -> RangeInclusive<T> {
387 self.clone()
388 }
389
390 fn overlaps(&self, other: &Range<T>) -> bool {
391 self.start() < &other.end && &other.start <= self.end()
392 }
393
394 fn contains_inclusive(&self, other: &Range<T>) -> bool {
395 self.start() <= &other.start && &other.end <= self.end()
396 }
397}
398
399#[cfg(test)]
400mod tests {
401 use super::*;
402
403 #[test]
404 fn test_extend_sorted() {
405 let mut vec = vec![];
406
407 extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
408 assert_eq!(vec, &[21, 17, 13, 8, 1]);
409
410 extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
411 assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
412
413 extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
414 assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
415 }
416
417 #[test]
418 fn test_iife() {
419 fn option_returning_function() -> Option<()> {
420 None
421 }
422
423 let foo = iife!({
424 option_returning_function()?;
425 Some(())
426 });
427
428 assert_eq!(foo, None);
429 }
430
431 #[test]
432 fn test_trancate_and_trailoff() {
433 assert_eq!(truncate_and_trailoff("", 5), "");
434 assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
435 assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
436 assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
437 }
438}