util.rs

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