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