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