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