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