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