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    #[cfg(not(target_os = "windows"))]
382    let file = caller.file();
383    #[cfg(target_os = "windows")]
384    let file = caller.file().replace('\\', "/");
385    // In this codebase, the first segment of the file path is
386    // the 'crates' folder, followed by the crate name.
387    let target = file.split('/').nth(1);
388
389    log::logger().log(
390        &log::Record::builder()
391            .target(target.unwrap_or(""))
392            .module_path(target)
393            .args(format_args!("{:?}", error))
394            .file(Some(caller.file()))
395            .line(Some(caller.line()))
396            .level(level)
397            .build(),
398    );
399}
400
401pub trait TryFutureExt {
402    fn log_err(self) -> LogErrorFuture<Self>
403    where
404        Self: Sized;
405
406    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
407    where
408        Self: Sized;
409
410    fn warn_on_err(self) -> LogErrorFuture<Self>
411    where
412        Self: Sized;
413    fn unwrap(self) -> UnwrapFuture<Self>
414    where
415        Self: Sized;
416}
417
418impl<F, T, E> TryFutureExt for F
419where
420    F: Future<Output = Result<T, E>>,
421    E: std::fmt::Debug,
422{
423    #[track_caller]
424    fn log_err(self) -> LogErrorFuture<Self>
425    where
426        Self: Sized,
427    {
428        let location = Location::caller();
429        LogErrorFuture(self, log::Level::Error, *location)
430    }
431
432    fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
433    where
434        Self: Sized,
435    {
436        LogErrorFuture(self, log::Level::Error, location)
437    }
438
439    #[track_caller]
440    fn warn_on_err(self) -> LogErrorFuture<Self>
441    where
442        Self: Sized,
443    {
444        let location = Location::caller();
445        LogErrorFuture(self, log::Level::Warn, *location)
446    }
447
448    fn unwrap(self) -> UnwrapFuture<Self>
449    where
450        Self: Sized,
451    {
452        UnwrapFuture(self)
453    }
454}
455
456#[must_use]
457pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
458
459impl<F, T, E> Future for LogErrorFuture<F>
460where
461    F: Future<Output = Result<T, E>>,
462    E: std::fmt::Debug,
463{
464    type Output = Option<T>;
465
466    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
467        let level = self.1;
468        let location = self.2;
469        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
470        match inner.poll(cx) {
471            Poll::Ready(output) => Poll::Ready(match output {
472                Ok(output) => Some(output),
473                Err(error) => {
474                    log_error_with_caller(location, error, level);
475                    None
476                }
477            }),
478            Poll::Pending => Poll::Pending,
479        }
480    }
481}
482
483pub struct UnwrapFuture<F>(F);
484
485impl<F, T, E> Future for UnwrapFuture<F>
486where
487    F: Future<Output = Result<T, E>>,
488    E: std::fmt::Debug,
489{
490    type Output = T;
491
492    fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
493        let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
494        match inner.poll(cx) {
495            Poll::Ready(result) => Poll::Ready(result.unwrap()),
496            Poll::Pending => Poll::Pending,
497        }
498    }
499}
500
501pub struct Deferred<F: FnOnce()>(Option<F>);
502
503impl<F: FnOnce()> Deferred<F> {
504    /// Drop without running the deferred function.
505    pub fn abort(mut self) {
506        self.0.take();
507    }
508}
509
510impl<F: FnOnce()> Drop for Deferred<F> {
511    fn drop(&mut self) {
512        if let Some(f) = self.0.take() {
513            f()
514        }
515    }
516}
517
518/// Run the given function when the returned value is dropped (unless it's cancelled).
519#[must_use]
520pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
521    Deferred(Some(f))
522}
523
524#[cfg(any(test, feature = "test-support"))]
525mod rng {
526    use rand::{seq::SliceRandom, Rng};
527    pub struct RandomCharIter<T: Rng> {
528        rng: T,
529        simple_text: bool,
530    }
531
532    impl<T: Rng> RandomCharIter<T> {
533        pub fn new(rng: T) -> Self {
534            Self {
535                rng,
536                simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
537            }
538        }
539
540        pub fn with_simple_text(mut self) -> Self {
541            self.simple_text = true;
542            self
543        }
544    }
545
546    impl<T: Rng> Iterator for RandomCharIter<T> {
547        type Item = char;
548
549        fn next(&mut self) -> Option<Self::Item> {
550            if self.simple_text {
551                return if self.rng.gen_range(0..100) < 5 {
552                    Some('\n')
553                } else {
554                    Some(self.rng.gen_range(b'a'..b'z' + 1).into())
555                };
556            }
557
558            match self.rng.gen_range(0..100) {
559                // whitespace
560                0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
561                // two-byte greek letters
562                20..=32 => char::from_u32(self.rng.gen_range(('α' as u32)..('ω' as u32 + 1))),
563                // // three-byte characters
564                33..=45 => ['✋', '✅', '❌', '❎', '⭐']
565                    .choose(&mut self.rng)
566                    .copied(),
567                // // four-byte characters
568                46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
569                // ascii letters
570                _ => Some(self.rng.gen_range(b'a'..b'z' + 1).into()),
571            }
572        }
573    }
574}
575#[cfg(any(test, feature = "test-support"))]
576pub use rng::RandomCharIter;
577/// Get an embedded file as a string.
578pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
579    match A::get(path).unwrap().data {
580        Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
581        Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
582    }
583}
584
585/// Expands to an immediately-invoked function expression. Good for using the ? operator
586/// in functions which do not return an Option or Result.
587///
588/// Accepts a normal block, an async block, or an async move block.
589#[macro_export]
590macro_rules! maybe {
591    ($block:block) => {
592        (|| $block)()
593    };
594    (async $block:block) => {
595        (|| async $block)()
596    };
597    (async move $block:block) => {
598        (|| async move $block)()
599    };
600}
601
602pub trait RangeExt<T> {
603    fn sorted(&self) -> Self;
604    fn to_inclusive(&self) -> RangeInclusive<T>;
605    fn overlaps(&self, other: &Range<T>) -> bool;
606    fn contains_inclusive(&self, other: &Range<T>) -> bool;
607}
608
609impl<T: Ord + Clone> RangeExt<T> for Range<T> {
610    fn sorted(&self) -> Self {
611        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
612    }
613
614    fn to_inclusive(&self) -> RangeInclusive<T> {
615        self.start.clone()..=self.end.clone()
616    }
617
618    fn overlaps(&self, other: &Range<T>) -> bool {
619        self.start < other.end && other.start < self.end
620    }
621
622    fn contains_inclusive(&self, other: &Range<T>) -> bool {
623        self.start <= other.start && other.end <= self.end
624    }
625}
626
627impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
628    fn sorted(&self) -> Self {
629        cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
630    }
631
632    fn to_inclusive(&self) -> RangeInclusive<T> {
633        self.clone()
634    }
635
636    fn overlaps(&self, other: &Range<T>) -> bool {
637        self.start() < &other.end && &other.start <= self.end()
638    }
639
640    fn contains_inclusive(&self, other: &Range<T>) -> bool {
641        self.start() <= &other.start && &other.end <= self.end()
642    }
643}
644
645/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
646/// case-insensitive.
647///
648/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
649/// into `1-abc, 2, 10, 11-def, .., 21-abc`
650#[derive(Debug, PartialEq, Eq)]
651pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
652
653impl<'a> NumericPrefixWithSuffix<'a> {
654    pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
655        let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
656        let (prefix, remainder) = str.split_at(i);
657
658        let prefix = prefix.parse().ok();
659        Self(prefix, remainder)
660    }
661}
662
663/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
664/// to handle cases like "a" < "A" instead of "a" == "A".
665impl Ord for NumericPrefixWithSuffix<'_> {
666    fn cmp(&self, other: &Self) -> Ordering {
667        match (self.0, other.0) {
668            (None, None) => UniCase::new(self.1)
669                .cmp(&UniCase::new(other.1))
670                .then_with(|| self.1.cmp(other.1).reverse()),
671            (None, Some(_)) => Ordering::Greater,
672            (Some(_), None) => Ordering::Less,
673            (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
674                UniCase::new(self.1)
675                    .cmp(&UniCase::new(other.1))
676                    .then_with(|| self.1.cmp(other.1).reverse())
677            }),
678        }
679    }
680}
681
682impl<'a> PartialOrd for NumericPrefixWithSuffix<'a> {
683    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
684        Some(self.cmp(other))
685    }
686}
687
688fn emoji_regex() -> &'static Regex {
689    static EMOJI_REGEX: OnceLock<Regex> = OnceLock::new();
690    EMOJI_REGEX.get_or_init(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap())
691}
692
693/// Returns true if the given string consists of emojis only.
694/// E.g. "👨‍👩‍👧‍👧👋" will return true, but "👋!" will return false.
695pub fn word_consists_of_emojis(s: &str) -> bool {
696    let mut prev_end = 0;
697    for capture in emoji_regex().find_iter(s) {
698        if capture.start() != prev_end {
699            return false;
700        }
701        prev_end = capture.end();
702    }
703    prev_end == s.len()
704}
705
706#[cfg(test)]
707mod tests {
708    use super::*;
709
710    #[test]
711    fn test_extend_sorted() {
712        let mut vec = vec![];
713
714        extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
715        assert_eq!(vec, &[21, 17, 13, 8, 1]);
716
717        extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
718        assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
719
720        extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
721        assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
722    }
723
724    #[test]
725    fn test_iife() {
726        fn option_returning_function() -> Option<()> {
727            None
728        }
729
730        let foo = maybe!({
731            option_returning_function()?;
732            Some(())
733        });
734
735        assert_eq!(foo, None);
736    }
737
738    #[test]
739    fn test_truncate_and_trailoff() {
740        assert_eq!(truncate_and_trailoff("", 5), "");
741        assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
742        assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
743        assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
744    }
745
746    #[test]
747    fn test_numeric_prefix_str_method() {
748        let target = "1a";
749        assert_eq!(
750            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
751            NumericPrefixWithSuffix(Some(1), "a")
752        );
753
754        let target = "12ab";
755        assert_eq!(
756            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
757            NumericPrefixWithSuffix(Some(12), "ab")
758        );
759
760        let target = "12_ab";
761        assert_eq!(
762            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
763            NumericPrefixWithSuffix(Some(12), "_ab")
764        );
765
766        let target = "1_2ab";
767        assert_eq!(
768            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
769            NumericPrefixWithSuffix(Some(1), "_2ab")
770        );
771
772        let target = "1.2";
773        assert_eq!(
774            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
775            NumericPrefixWithSuffix(Some(1), ".2")
776        );
777
778        let target = "1.2_a";
779        assert_eq!(
780            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
781            NumericPrefixWithSuffix(Some(1), ".2_a")
782        );
783
784        let target = "12.2_a";
785        assert_eq!(
786            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
787            NumericPrefixWithSuffix(Some(12), ".2_a")
788        );
789
790        let target = "12a.2_a";
791        assert_eq!(
792            NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
793            NumericPrefixWithSuffix(Some(12), "a.2_a")
794        );
795    }
796
797    #[test]
798    fn test_numeric_prefix_with_suffix() {
799        let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
800        sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
801        assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
802
803        for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~™£"] {
804            assert_eq!(
805                NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
806                NumericPrefixWithSuffix(None, numeric_prefix_less),
807                "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
808            )
809        }
810    }
811
812    #[test]
813    fn test_word_consists_of_emojis() {
814        let words_to_test = vec![
815            ("👨‍👩‍👧‍👧👋🥒", true),
816            ("👋", true),
817            ("!👋", false),
818            ("👋!", false),
819            ("👋 ", false),
820            (" 👋", false),
821            ("Test", false),
822        ];
823
824        for (text, expected_result) in words_to_test {
825            assert_eq!(word_consists_of_emojis(text), expected_result);
826        }
827    }
828
829    #[test]
830    fn test_truncate_lines_and_trailoff() {
831        let text = r#"Line 1
832Line 2
833Line 3"#;
834
835        assert_eq!(
836            truncate_lines_and_trailoff(text, 2),
837            r#"Line 1
838…"#
839        );
840
841        assert_eq!(
842            truncate_lines_and_trailoff(text, 3),
843            r#"Line 1
844Line 2
845…"#
846        );
847
848        assert_eq!(
849            truncate_lines_and_trailoff(text, 4),
850            r#"Line 1
851Line 2
852Line 3"#
853        );
854    }
855}