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