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