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 rand::{seq::SliceRandom, Rng};
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] != "" {
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
520pub struct RandomCharIter<T: Rng> {
521 rng: T,
522 simple_text: bool,
523}
524
525impl<T: Rng> RandomCharIter<T> {
526 pub fn new(rng: T) -> Self {
527 Self {
528 rng,
529 simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
530 }
531 }
532
533 pub fn with_simple_text(mut self) -> Self {
534 self.simple_text = true;
535 self
536 }
537}
538
539impl<T: Rng> Iterator for RandomCharIter<T> {
540 type Item = char;
541
542 fn next(&mut self) -> Option<Self::Item> {
543 if self.simple_text {
544 return if self.rng.gen_range(0..100) < 5 {
545 Some('\n')
546 } else {
547 Some(self.rng.gen_range(b'a'..b'z' + 1).into())
548 };
549 }
550
551 match self.rng.gen_range(0..100) {
552 // whitespace
553 0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
554 // two-byte greek letters
555 20..=32 => char::from_u32(self.rng.gen_range(('α' as u32)..('ω' as u32 + 1))),
556 // // three-byte characters
557 33..=45 => ['✋', '✅', '❌', '❎', '⭐']
558 .choose(&mut self.rng)
559 .copied(),
560 // // four-byte characters
561 46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
562 // ascii letters
563 _ => Some(self.rng.gen_range(b'a'..b'z' + 1).into()),
564 }
565 }
566}
567
568/// Get an embedded file as a string.
569pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
570 match A::get(path).unwrap().data {
571 Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
572 Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
573 }
574}
575
576/// Expands to an immediately-invoked function expression. Good for using the ? operator
577/// in functions which do not return an Option or Result.
578///
579/// Accepts a normal block, an async block, or an async move block.
580#[macro_export]
581macro_rules! maybe {
582 ($block:block) => {
583 (|| $block)()
584 };
585 (async $block:block) => {
586 (|| async $block)()
587 };
588 (async move $block:block) => {
589 (|| async move $block)()
590 };
591}
592
593pub trait RangeExt<T> {
594 fn sorted(&self) -> Self;
595 fn to_inclusive(&self) -> RangeInclusive<T>;
596 fn overlaps(&self, other: &Range<T>) -> bool;
597 fn contains_inclusive(&self, other: &Range<T>) -> bool;
598}
599
600impl<T: Ord + Clone> RangeExt<T> for Range<T> {
601 fn sorted(&self) -> Self {
602 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
603 }
604
605 fn to_inclusive(&self) -> RangeInclusive<T> {
606 self.start.clone()..=self.end.clone()
607 }
608
609 fn overlaps(&self, other: &Range<T>) -> bool {
610 self.start < other.end && other.start < self.end
611 }
612
613 fn contains_inclusive(&self, other: &Range<T>) -> bool {
614 self.start <= other.start && other.end <= self.end
615 }
616}
617
618impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
619 fn sorted(&self) -> Self {
620 cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
621 }
622
623 fn to_inclusive(&self) -> RangeInclusive<T> {
624 self.clone()
625 }
626
627 fn overlaps(&self, other: &Range<T>) -> bool {
628 self.start() < &other.end && &other.start <= self.end()
629 }
630
631 fn contains_inclusive(&self, other: &Range<T>) -> bool {
632 self.start() <= &other.start && &other.end <= self.end()
633 }
634}
635
636/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
637/// case-insensitive.
638///
639/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
640/// into `1-abc, 2, 10, 11-def, .., 21-abc`
641#[derive(Debug, PartialEq, Eq)]
642pub struct NumericPrefixWithSuffix<'a>(i32, &'a str);
643
644impl<'a> NumericPrefixWithSuffix<'a> {
645 pub fn from_numeric_prefixed_str(str: &'a str) -> Option<Self> {
646 let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
647 let (prefix, remainder) = str.split_at(i);
648
649 match prefix.parse::<i32>() {
650 Ok(prefix) => Some(NumericPrefixWithSuffix(prefix, remainder)),
651 Err(_) => None,
652 }
653 }
654}
655
656impl Ord for NumericPrefixWithSuffix<'_> {
657 fn cmp(&self, other: &Self) -> Ordering {
658 let NumericPrefixWithSuffix(num_a, remainder_a) = self;
659 let NumericPrefixWithSuffix(num_b, remainder_b) = other;
660 num_a
661 .cmp(num_b)
662 .then_with(|| UniCase::new(remainder_a).cmp(&UniCase::new(remainder_b)))
663 }
664}
665
666impl<'a> PartialOrd for NumericPrefixWithSuffix<'a> {
667 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
668 Some(self.cmp(other))
669 }
670}
671
672fn emoji_regex() -> &'static Regex {
673 static EMOJI_REGEX: OnceLock<Regex> = OnceLock::new();
674 EMOJI_REGEX.get_or_init(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap())
675}
676
677/// Returns true if the given string consists of emojis only.
678/// E.g. "👨👩👧👧👋" will return true, but "👋!" will return false.
679pub fn word_consists_of_emojis(s: &str) -> bool {
680 let mut prev_end = 0;
681 for capture in emoji_regex().find_iter(s) {
682 if capture.start() != prev_end {
683 return false;
684 }
685 prev_end = capture.end();
686 }
687 prev_end == s.len()
688}
689
690#[cfg(test)]
691mod tests {
692 use super::*;
693
694 #[test]
695 fn test_extend_sorted() {
696 let mut vec = vec![];
697
698 extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
699 assert_eq!(vec, &[21, 17, 13, 8, 1]);
700
701 extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
702 assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
703
704 extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
705 assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
706 }
707
708 #[test]
709 fn test_iife() {
710 fn option_returning_function() -> Option<()> {
711 None
712 }
713
714 let foo = maybe!({
715 option_returning_function()?;
716 Some(())
717 });
718
719 assert_eq!(foo, None);
720 }
721
722 #[test]
723 fn test_trancate_and_trailoff() {
724 assert_eq!(truncate_and_trailoff("", 5), "");
725 assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
726 assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
727 assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
728 }
729
730 #[test]
731 fn test_numeric_prefix_str_method() {
732 let target = "1a";
733 assert_eq!(
734 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
735 Some(NumericPrefixWithSuffix(1, "a"))
736 );
737
738 let target = "12ab";
739 assert_eq!(
740 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
741 Some(NumericPrefixWithSuffix(12, "ab"))
742 );
743
744 let target = "12_ab";
745 assert_eq!(
746 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
747 Some(NumericPrefixWithSuffix(12, "_ab"))
748 );
749
750 let target = "1_2ab";
751 assert_eq!(
752 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
753 Some(NumericPrefixWithSuffix(1, "_2ab"))
754 );
755
756 let target = "1.2";
757 assert_eq!(
758 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
759 Some(NumericPrefixWithSuffix(1, ".2"))
760 );
761
762 let target = "1.2_a";
763 assert_eq!(
764 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
765 Some(NumericPrefixWithSuffix(1, ".2_a"))
766 );
767
768 let target = "12.2_a";
769 assert_eq!(
770 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
771 Some(NumericPrefixWithSuffix(12, ".2_a"))
772 );
773
774 let target = "12a.2_a";
775 assert_eq!(
776 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
777 Some(NumericPrefixWithSuffix(12, "a.2_a"))
778 );
779 }
780
781 #[test]
782 fn test_numeric_prefix_with_suffix() {
783 let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
784 sorted.sort_by_key(|s| {
785 NumericPrefixWithSuffix::from_numeric_prefixed_str(s).unwrap_or_else(|| {
786 panic!("Cannot convert string `{s}` into NumericPrefixWithSuffix")
787 })
788 });
789 assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
790
791 for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~™£"] {
792 assert_eq!(
793 NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
794 None,
795 "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
796 )
797 }
798 }
799
800 #[test]
801 fn test_word_consists_of_emojis() {
802 let words_to_test = vec![
803 ("👨👩👧👧👋🥒", true),
804 ("👋", true),
805 ("!👋", false),
806 ("👋!", false),
807 ("👋 ", false),
808 (" 👋", false),
809 ("Test", false),
810 ];
811
812 for (text, expected_result) in words_to_test {
813 assert_eq!(word_consists_of_emojis(text), expected_result);
814 }
815 }
816
817 #[test]
818 fn test_truncate_lines_and_trailoff() {
819 let text = r#"Line 1
820Line 2
821Line 3"#;
822
823 assert_eq!(
824 truncate_lines_and_trailoff(text, 2),
825 r#"Line 1
826…"#
827 );
828
829 assert_eq!(
830 truncate_lines_and_trailoff(text, 3),
831 r#"Line 1
832Line 2
833…"#
834 );
835
836 assert_eq!(
837 truncate_lines_and_trailoff(text, 4),
838 r#"Line 1
839Line 2
840Line 3"#
841 );
842 }
843}