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