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>(T);
273
274impl<T: Rng> RandomCharIter<T> {
275 pub fn new(rng: T) -> Self {
276 Self(rng)
277 }
278}
279
280impl<T: Rng> Iterator for RandomCharIter<T> {
281 type Item = char;
282
283 fn next(&mut self) -> Option<Self::Item> {
284 if std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()) {
285 return if self.0.gen_range(0..100) < 5 {
286 Some('\n')
287 } else {
288 Some(self.0.gen_range(b'a'..b'z' + 1).into())
289 };
290 }
291
292 match self.0.gen_range(0..100) {
293 // whitespace
294 0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.0).copied(),
295 // two-byte greek letters
296 20..=32 => char::from_u32(self.0.gen_range(('α' as u32)..('ω' as u32 + 1))),
297 // // three-byte characters
298 33..=45 => ['✋', '✅', '❌', '❎', '⭐'].choose(&mut self.0).copied(),
299 // // four-byte characters
300 46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.0).copied(),
301 // ascii letters
302 _ => Some(self.0.gen_range(b'a'..b'z' + 1).into()),
303 }
304 }
305}
306
307/// Get an embedded file as a string.
308pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
309 match A::get(path).unwrap().data {
310 Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
311 Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
312 }
313}
314
315// copy unstable standard feature option unzip
316// https://github.com/rust-lang/rust/issues/87800
317// Remove when this ship in Rust 1.66 or 1.67
318pub fn unzip_option<T, U>(option: Option<(T, U)>) -> (Option<T>, Option<U>) {
319 match option {
320 Some((a, b)) => (Some(a), Some(b)),
321 None => (None, None),
322 }
323}
324
325/// Immediately invoked function expression. Good for using the ? operator
326/// in functions which do not return an Option or Result
327#[macro_export]
328macro_rules! iife {
329 ($block:block) => {
330 (|| $block)()
331 };
332}
333
334/// Async Immediately invoked function expression. Good for using the ? operator
335/// in functions which do not return an Option or Result. Async version of above
336#[macro_export]
337macro_rules! async_iife {
338 ($block:block) => {
339 (|| async move { $block })()
340 };
341}
342
343pub trait RangeExt<T> {
344 fn sorted(&self) -> Self;
345 fn to_inclusive(&self) -> RangeInclusive<T>;
346 fn overlaps(&self, other: &Range<T>) -> bool;
347 fn contains_inclusive(&self, other: &Range<T>) -> bool;
348}
349
350impl<T: Ord + Clone> RangeExt<T> for Range<T> {
351 fn sorted(&self) -> Self {
352 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
353 }
354
355 fn to_inclusive(&self) -> RangeInclusive<T> {
356 self.start.clone()..=self.end.clone()
357 }
358
359 fn overlaps(&self, other: &Range<T>) -> bool {
360 self.start < other.end && other.start < self.end
361 }
362
363 fn contains_inclusive(&self, other: &Range<T>) -> bool {
364 self.start <= other.start && other.end <= self.end
365 }
366}
367
368impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
369 fn sorted(&self) -> Self {
370 cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
371 }
372
373 fn to_inclusive(&self) -> RangeInclusive<T> {
374 self.clone()
375 }
376
377 fn overlaps(&self, other: &Range<T>) -> bool {
378 self.start() < &other.end && &other.start <= self.end()
379 }
380
381 fn contains_inclusive(&self, other: &Range<T>) -> bool {
382 self.start() <= &other.start && &other.end <= self.end()
383 }
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389
390 #[test]
391 fn test_extend_sorted() {
392 let mut vec = vec![];
393
394 extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
395 assert_eq!(vec, &[21, 17, 13, 8, 1]);
396
397 extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
398 assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
399
400 extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
401 assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
402 }
403
404 #[test]
405 fn test_iife() {
406 fn option_returning_function() -> Option<()> {
407 None
408 }
409
410 let foo = iife!({
411 option_returning_function()?;
412 Some(())
413 });
414
415 assert_eq!(foo, None);
416 }
417
418 #[test]
419 fn test_trancate_and_trailoff() {
420 assert_eq!(truncate_and_trailoff("", 5), "");
421 assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
422 assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
423 assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
424 }
425}