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