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. 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 {
122 type Ok;
123
124 fn log_err(self) -> Option<Self::Ok>;
125 fn warn_on_err(self) -> Option<Self::Ok>;
126}
127
128impl<T, E> ResultExt for Result<T, E>
129where
130 E: std::fmt::Debug,
131{
132 type Ok = T;
133
134 #[track_caller]
135 fn log_err(self) -> Option<T> {
136 match self {
137 Ok(value) => Some(value),
138 Err(error) => {
139 let caller = Location::caller();
140 log::error!("{}:{}: {:?}", caller.file(), caller.line(), error);
141 None
142 }
143 }
144 }
145
146 fn warn_on_err(self) -> Option<T> {
147 match self {
148 Ok(value) => Some(value),
149 Err(error) => {
150 log::warn!("{:?}", error);
151 None
152 }
153 }
154 }
155}
156
157pub trait TryFutureExt {
158 fn log_err(self) -> LogErrorFuture<Self>
159 where
160 Self: Sized;
161 fn warn_on_err(self) -> LogErrorFuture<Self>
162 where
163 Self: Sized;
164 fn unwrap(self) -> UnwrapFuture<Self>
165 where
166 Self: Sized;
167}
168
169impl<F, T, E> TryFutureExt for F
170where
171 F: Future<Output = Result<T, E>>,
172 E: std::fmt::Debug,
173{
174 fn log_err(self) -> LogErrorFuture<Self>
175 where
176 Self: Sized,
177 {
178 LogErrorFuture(self, log::Level::Error)
179 }
180
181 fn warn_on_err(self) -> LogErrorFuture<Self>
182 where
183 Self: Sized,
184 {
185 LogErrorFuture(self, log::Level::Warn)
186 }
187
188 fn unwrap(self) -> UnwrapFuture<Self>
189 where
190 Self: Sized,
191 {
192 UnwrapFuture(self)
193 }
194}
195
196pub struct LogErrorFuture<F>(F, log::Level);
197
198impl<F, T, E> Future for LogErrorFuture<F>
199where
200 F: Future<Output = Result<T, E>>,
201 E: std::fmt::Debug,
202{
203 type Output = Option<T>;
204
205 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
206 let level = self.1;
207 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
208 match inner.poll(cx) {
209 Poll::Ready(output) => Poll::Ready(match output {
210 Ok(output) => Some(output),
211 Err(error) => {
212 log::log!(level, "{:?}", error);
213 None
214 }
215 }),
216 Poll::Pending => Poll::Pending,
217 }
218 }
219}
220
221pub struct UnwrapFuture<F>(F);
222
223impl<F, T, E> Future for UnwrapFuture<F>
224where
225 F: Future<Output = Result<T, E>>,
226 E: std::fmt::Debug,
227{
228 type Output = T;
229
230 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
231 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
232 match inner.poll(cx) {
233 Poll::Ready(result) => Poll::Ready(result.unwrap()),
234 Poll::Pending => Poll::Pending,
235 }
236 }
237}
238
239struct Defer<F: FnOnce()>(Option<F>);
240
241impl<F: FnOnce()> Drop for Defer<F> {
242 fn drop(&mut self) {
243 if let Some(f) = self.0.take() {
244 f()
245 }
246 }
247}
248
249pub fn defer<F: FnOnce()>(f: F) -> impl Drop {
250 Defer(Some(f))
251}
252
253pub struct RandomCharIter<T: Rng>(T);
254
255impl<T: Rng> RandomCharIter<T> {
256 pub fn new(rng: T) -> Self {
257 Self(rng)
258 }
259}
260
261impl<T: Rng> Iterator for RandomCharIter<T> {
262 type Item = char;
263
264 fn next(&mut self) -> Option<Self::Item> {
265 if std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()) {
266 return if self.0.gen_range(0..100) < 5 {
267 Some('\n')
268 } else {
269 Some(self.0.gen_range(b'a'..b'z' + 1).into())
270 };
271 }
272
273 match self.0.gen_range(0..100) {
274 // whitespace
275 0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.0).copied(),
276 // two-byte greek letters
277 20..=32 => char::from_u32(self.0.gen_range(('α' as u32)..('ω' as u32 + 1))),
278 // // three-byte characters
279 33..=45 => ['✋', '✅', '❌', '❎', '⭐'].choose(&mut self.0).copied(),
280 // // four-byte characters
281 46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.0).copied(),
282 // ascii letters
283 _ => Some(self.0.gen_range(b'a'..b'z' + 1).into()),
284 }
285 }
286}
287
288/// Get an embedded file as a string.
289pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
290 match A::get(path).unwrap().data {
291 Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
292 Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
293 }
294}
295
296// copy unstable standard feature option unzip
297// https://github.com/rust-lang/rust/issues/87800
298// Remove when this ship in Rust 1.66 or 1.67
299pub fn unzip_option<T, U>(option: Option<(T, U)>) -> (Option<T>, Option<U>) {
300 match option {
301 Some((a, b)) => (Some(a), Some(b)),
302 None => (None, None),
303 }
304}
305
306/// Immediately invoked function expression. Good for using the ? operator
307/// in functions which do not return an Option or Result
308#[macro_export]
309macro_rules! iife {
310 ($block:block) => {
311 (|| $block)()
312 };
313}
314
315/// Async Immediately invoked function expression. Good for using the ? operator
316/// in functions which do not return an Option or Result. Async version of above
317#[macro_export]
318macro_rules! async_iife {
319 ($block:block) => {
320 (|| async move { $block })()
321 };
322}
323
324pub trait RangeExt<T> {
325 fn sorted(&self) -> Self;
326 fn to_inclusive(&self) -> RangeInclusive<T>;
327 fn overlaps(&self, other: &Range<T>) -> bool;
328 fn contains_inclusive(&self, other: &Range<T>) -> bool;
329}
330
331impl<T: Ord + Clone> RangeExt<T> for Range<T> {
332 fn sorted(&self) -> Self {
333 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
334 }
335
336 fn to_inclusive(&self) -> RangeInclusive<T> {
337 self.start.clone()..=self.end.clone()
338 }
339
340 fn overlaps(&self, other: &Range<T>) -> bool {
341 self.start < other.end && other.start < self.end
342 }
343
344 fn contains_inclusive(&self, other: &Range<T>) -> bool {
345 self.start <= other.start && other.end <= self.end
346 }
347}
348
349impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
350 fn sorted(&self) -> Self {
351 cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
352 }
353
354 fn to_inclusive(&self) -> RangeInclusive<T> {
355 self.clone()
356 }
357
358 fn overlaps(&self, other: &Range<T>) -> bool {
359 self.start() < &other.end && &other.start <= self.end()
360 }
361
362 fn contains_inclusive(&self, other: &Range<T>) -> bool {
363 self.start() <= &other.start && &other.end <= self.end()
364 }
365}
366
367#[cfg(test)]
368mod tests {
369 use super::*;
370
371 #[test]
372 fn test_extend_sorted() {
373 let mut vec = vec![];
374
375 extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
376 assert_eq!(vec, &[21, 17, 13, 8, 1]);
377
378 extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
379 assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
380
381 extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
382 assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
383 }
384
385 #[test]
386 fn test_iife() {
387 fn option_returning_function() -> Option<()> {
388 None
389 }
390
391 let foo = iife!({
392 option_returning_function()?;
393 Some(())
394 });
395
396 assert_eq!(foo, None);
397 }
398
399 #[test]
400 fn test_trancate_and_trailoff() {
401 assert_eq!(truncate_and_trailoff("", 5), "");
402 assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
403 assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
404 assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
405 }
406}