1pub mod arc_cow;
2pub mod command;
3pub mod fs;
4pub mod paths;
5pub mod serde;
6#[cfg(any(test, feature = "test-support"))]
7pub mod test;
8
9use anyhow::Result;
10use futures::Future;
11use itertools::Either;
12use regex::Regex;
13use std::sync::{LazyLock, OnceLock};
14use std::{
15 borrow::Cow,
16 cmp::{self, Ordering},
17 env,
18 ops::{AddAssign, Range, RangeInclusive},
19 panic::Location,
20 pin::Pin,
21 task::{Context, Poll},
22 time::Instant,
23};
24use unicase::UniCase;
25
26#[cfg(unix)]
27use anyhow::{anyhow, Context as _};
28
29pub use take_until::*;
30
31#[macro_export]
32macro_rules! debug_panic {
33 ( $($fmt_arg:tt)* ) => {
34 if cfg!(debug_assertions) {
35 panic!( $($fmt_arg)* );
36 } else {
37 let backtrace = std::backtrace::Backtrace::capture();
38 log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace);
39 }
40 };
41}
42
43pub fn truncate(s: &str, max_chars: usize) -> &str {
44 match s.char_indices().nth(max_chars) {
45 None => s,
46 Some((idx, _)) => &s[..idx],
47 }
48}
49
50/// Removes characters from the end of the string if its length is greater than `max_chars` and
51/// appends "..." to the string. Returns string unchanged if its length is smaller than max_chars.
52pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
53 debug_assert!(max_chars >= 5);
54
55 // If the string's byte length is <= max_chars, walking the string can be skipped since the
56 // number of chars is <= the number of bytes.
57 if s.len() <= max_chars {
58 return s.to_string();
59 }
60 let truncation_ix = s.char_indices().map(|(i, _)| i).nth(max_chars);
61 match truncation_ix {
62 Some(index) => s[..index].to_string() + "…",
63 _ => s.to_string(),
64 }
65}
66
67/// Removes characters from the front of the string if its length is greater than `max_chars` and
68/// prepends the string with "...". Returns string unchanged if its length is smaller than max_chars.
69pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String {
70 debug_assert!(max_chars >= 5);
71
72 // If the string's byte length is <= max_chars, walking the string can be skipped since the
73 // number of chars is <= the number of bytes.
74 if s.len() <= max_chars {
75 return s.to_string();
76 }
77 let suffix_char_length = max_chars.saturating_sub(1);
78 let truncation_ix = s
79 .char_indices()
80 .map(|(i, _)| i)
81 .nth_back(suffix_char_length);
82 match truncation_ix {
83 Some(index) if index > 0 => "…".to_string() + &s[index..],
84 _ => s.to_string(),
85 }
86}
87
88/// Takes only `max_lines` from the string and, if there were more than `max_lines-1`, appends a
89/// a newline and "..." to the string, so that `max_lines` are returned.
90/// Returns string unchanged if its length is smaller than max_lines.
91pub fn truncate_lines_and_trailoff(s: &str, max_lines: usize) -> String {
92 let mut lines = s.lines().take(max_lines).collect::<Vec<_>>();
93 if lines.len() > max_lines - 1 {
94 lines.pop();
95 lines.join("\n") + "\n…"
96 } else {
97 lines.join("\n")
98 }
99}
100
101pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
102 let prev = *value;
103 *value += T::from(1);
104 prev
105}
106
107/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
108/// enforcing a maximum length. This also de-duplicates items. Sort the items according to the given callback. Before calling this,
109/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
110pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
111where
112 I: IntoIterator<Item = T>,
113 F: FnMut(&T, &T) -> Ordering,
114{
115 let mut start_index = 0;
116 for new_item in new_items {
117 if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
118 let index = start_index + i;
119 if vec.len() < limit {
120 vec.insert(index, new_item);
121 } else if index < vec.len() {
122 vec.pop();
123 vec.insert(index, new_item);
124 }
125 start_index = index;
126 }
127 }
128}
129
130pub fn truncate_to_bottom_n_sorted_by<T, F>(items: &mut Vec<T>, limit: usize, compare: &F)
131where
132 F: Fn(&T, &T) -> Ordering,
133{
134 if limit == 0 {
135 items.truncate(0);
136 }
137 if items.len() <= limit {
138 items.sort_by(compare);
139 return;
140 }
141 // When limit is near to items.len() it may be more efficient to sort the whole list and
142 // truncate, rather than always doing selection first as is done below. It's hard to analyze
143 // where the threshold for this should be since the quickselect style algorithm used by
144 // `select_nth_unstable_by` makes the prefix partially sorted, and so its work is not wasted -
145 // the expected number of comparisons needed by `sort_by` is less than it is for some arbitrary
146 // unsorted input.
147 items.select_nth_unstable_by(limit, compare);
148 items.truncate(limit);
149 items.sort_by(compare);
150}
151
152#[cfg(unix)]
153pub fn load_shell_from_passwd() -> Result<()> {
154 let buflen = match unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) } {
155 n if n < 0 => 1024,
156 n => n as usize,
157 };
158 let mut buffer = Vec::with_capacity(buflen);
159
160 let mut pwd: std::mem::MaybeUninit<libc::passwd> = std::mem::MaybeUninit::uninit();
161 let mut result: *mut libc::passwd = std::ptr::null_mut();
162
163 let uid = unsafe { libc::getuid() };
164 let status = unsafe {
165 libc::getpwuid_r(
166 uid,
167 pwd.as_mut_ptr(),
168 buffer.as_mut_ptr() as *mut libc::c_char,
169 buflen,
170 &mut result,
171 )
172 };
173 let entry = unsafe { pwd.assume_init() };
174
175 anyhow::ensure!(
176 status == 0,
177 "call to getpwuid_r failed. uid: {}, status: {}",
178 uid,
179 status
180 );
181 anyhow::ensure!(!result.is_null(), "passwd entry for uid {} not found", uid);
182 anyhow::ensure!(
183 entry.pw_uid == uid,
184 "passwd entry has different uid ({}) than getuid ({}) returned",
185 entry.pw_uid,
186 uid,
187 );
188
189 let shell = unsafe { std::ffi::CStr::from_ptr(entry.pw_shell).to_str().unwrap() };
190 if env::var("SHELL").map_or(true, |shell_env| shell_env != shell) {
191 log::info!(
192 "updating SHELL environment variable to value from passwd entry: {:?}",
193 shell,
194 );
195 env::set_var("SHELL", shell);
196 }
197
198 Ok(())
199}
200
201#[cfg(unix)]
202pub fn load_login_shell_environment() -> Result<()> {
203 let marker = "ZED_LOGIN_SHELL_START";
204 let shell = env::var("SHELL").context(
205 "SHELL environment variable is not assigned so we can't source login environment variables",
206 )?;
207
208 // If possible, we want to `cd` in the user's `$HOME` to trigger programs
209 // such as direnv, asdf, mise, ... to adjust the PATH. These tools often hook
210 // into shell's `cd` command (and hooks) to manipulate env.
211 // We do this so that we get the env a user would have when spawning a shell
212 // in home directory.
213 let shell_cmd_prefix = std::env::var_os("HOME")
214 .and_then(|home| home.into_string().ok())
215 .map(|home| format!("cd '{home}';"));
216
217 // The `exit 0` is the result of hours of debugging, trying to find out
218 // why running this command here, without `exit 0`, would mess
219 // up signal process for our process so that `ctrl-c` doesn't work
220 // anymore.
221 // We still don't know why `$SHELL -l -i -c '/usr/bin/env -0'` would
222 // do that, but it does, and `exit 0` helps.
223 let shell_cmd = format!(
224 "{}printf '%s' {marker}; /usr/bin/env; exit 0;",
225 shell_cmd_prefix.as_deref().unwrap_or("")
226 );
227
228 let output = std::process::Command::new(&shell)
229 .args(["-l", "-i", "-c", &shell_cmd])
230 .output()
231 .context("failed to spawn login shell to source login environment variables")?;
232 if !output.status.success() {
233 Err(anyhow!("login shell exited with error"))?;
234 }
235
236 let stdout = String::from_utf8_lossy(&output.stdout);
237
238 if let Some(env_output_start) = stdout.find(marker) {
239 let env_output = &stdout[env_output_start + marker.len()..];
240
241 parse_env_output(env_output, |key, value| env::set_var(key, value));
242
243 log::info!(
244 "set environment variables from shell:{}, path:{}",
245 shell,
246 env::var("PATH").unwrap_or_default(),
247 );
248 }
249
250 Ok(())
251}
252
253/// Parse the result of calling `usr/bin/env` with no arguments
254pub fn parse_env_output(env: &str, mut f: impl FnMut(String, String)) {
255 let mut current_key: Option<String> = None;
256 let mut current_value: Option<String> = None;
257
258 for line in env.split_terminator('\n') {
259 if let Some(separator_index) = line.find('=') {
260 if !line[..separator_index].is_empty() {
261 if let Some((key, value)) = Option::zip(current_key.take(), current_value.take()) {
262 f(key, value)
263 }
264 current_key = Some(line[..separator_index].to_string());
265 current_value = Some(line[separator_index + 1..].to_string());
266 continue;
267 };
268 }
269 if let Some(value) = current_value.as_mut() {
270 value.push('\n');
271 value.push_str(line);
272 }
273 }
274 if let Some((key, value)) = Option::zip(current_key.take(), current_value.take()) {
275 f(key, value)
276 }
277}
278
279pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
280 use serde_json::Value;
281
282 match (source, target) {
283 (Value::Object(source), Value::Object(target)) => {
284 for (key, value) in source {
285 if let Some(target) = target.get_mut(&key) {
286 merge_json_value_into(value, target);
287 } else {
288 target.insert(key.clone(), value);
289 }
290 }
291 }
292
293 (Value::Array(source), Value::Array(target)) => {
294 for value in source {
295 target.push(value);
296 }
297 }
298
299 (source, target) => *target = source,
300 }
301}
302
303pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
304 use serde_json::Value;
305 if let Value::Object(source_object) = source {
306 let target_object = if let Value::Object(target) = target {
307 target
308 } else {
309 *target = Value::Object(Default::default());
310 target.as_object_mut().unwrap()
311 };
312 for (key, value) in source_object {
313 if let Some(target) = target_object.get_mut(&key) {
314 merge_non_null_json_value_into(value, target);
315 } else if !value.is_null() {
316 target_object.insert(key.clone(), value);
317 }
318 }
319 } else if !source.is_null() {
320 *target = source
321 }
322}
323
324pub fn measure<R>(label: &str, f: impl FnOnce() -> R) -> R {
325 static ZED_MEASUREMENTS: OnceLock<bool> = OnceLock::new();
326 let zed_measurements = ZED_MEASUREMENTS.get_or_init(|| {
327 env::var("ZED_MEASUREMENTS")
328 .map(|measurements| measurements == "1" || measurements == "true")
329 .unwrap_or(false)
330 });
331
332 if *zed_measurements {
333 let start = Instant::now();
334 let result = f();
335 let elapsed = start.elapsed();
336 eprintln!("{}: {:?}", label, elapsed);
337 result
338 } else {
339 f()
340 }
341}
342
343pub fn iterate_expanded_and_wrapped_usize_range(
344 range: Range<usize>,
345 additional_before: usize,
346 additional_after: usize,
347 wrap_length: usize,
348) -> impl Iterator<Item = usize> {
349 let start_wraps = range.start < additional_before;
350 let end_wraps = wrap_length < range.end + additional_after;
351 if start_wraps && end_wraps {
352 Either::Left(0..wrap_length)
353 } else if start_wraps {
354 let wrapped_start = (range.start + wrap_length).saturating_sub(additional_before);
355 if wrapped_start <= range.end {
356 Either::Left(0..wrap_length)
357 } else {
358 Either::Right((0..range.end + additional_after).chain(wrapped_start..wrap_length))
359 }
360 } else if end_wraps {
361 let wrapped_end = range.end + additional_after - wrap_length;
362 if range.start <= wrapped_end {
363 Either::Left(0..wrap_length)
364 } else {
365 Either::Right((0..wrapped_end).chain(range.start - additional_before..wrap_length))
366 }
367 } else {
368 Either::Left((range.start - additional_before)..(range.end + additional_after))
369 }
370}
371
372pub trait ResultExt<E> {
373 type Ok;
374
375 fn log_err(self) -> Option<Self::Ok>;
376 /// Assert that this result should never be an error in development or tests.
377 fn debug_assert_ok(self, reason: &str) -> Self;
378 fn warn_on_err(self) -> Option<Self::Ok>;
379 fn anyhow(self) -> anyhow::Result<Self::Ok>
380 where
381 E: Into<anyhow::Error>;
382}
383
384impl<T, E> ResultExt<E> for Result<T, E>
385where
386 E: std::fmt::Debug,
387{
388 type Ok = T;
389
390 #[track_caller]
391 fn log_err(self) -> Option<T> {
392 match self {
393 Ok(value) => Some(value),
394 Err(error) => {
395 log_error_with_caller(*Location::caller(), error, log::Level::Error);
396 None
397 }
398 }
399 }
400
401 #[track_caller]
402 fn debug_assert_ok(self, reason: &str) -> Self {
403 if let Err(error) = &self {
404 debug_panic!("{reason} - {error:?}");
405 }
406 self
407 }
408
409 #[track_caller]
410 fn warn_on_err(self) -> Option<T> {
411 match self {
412 Ok(value) => Some(value),
413 Err(error) => {
414 log_error_with_caller(*Location::caller(), error, log::Level::Warn);
415 None
416 }
417 }
418 }
419
420 fn anyhow(self) -> anyhow::Result<T>
421 where
422 E: Into<anyhow::Error>,
423 {
424 self.map_err(Into::into)
425 }
426}
427
428fn log_error_with_caller<E>(caller: core::panic::Location<'_>, error: E, level: log::Level)
429where
430 E: std::fmt::Debug,
431{
432 #[cfg(not(target_os = "windows"))]
433 let file = caller.file();
434 #[cfg(target_os = "windows")]
435 let file = caller.file().replace('\\', "/");
436 // In this codebase, the first segment of the file path is
437 // the 'crates' folder, followed by the crate name.
438 let target = file.split('/').nth(1);
439
440 log::logger().log(
441 &log::Record::builder()
442 .target(target.unwrap_or(""))
443 .module_path(target)
444 .args(format_args!("{:?}", error))
445 .file(Some(caller.file()))
446 .line(Some(caller.line()))
447 .level(level)
448 .build(),
449 );
450}
451
452pub trait TryFutureExt {
453 fn log_err(self) -> LogErrorFuture<Self>
454 where
455 Self: Sized;
456
457 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
458 where
459 Self: Sized;
460
461 fn warn_on_err(self) -> LogErrorFuture<Self>
462 where
463 Self: Sized;
464 fn unwrap(self) -> UnwrapFuture<Self>
465 where
466 Self: Sized;
467}
468
469impl<F, T, E> TryFutureExt for F
470where
471 F: Future<Output = Result<T, E>>,
472 E: std::fmt::Debug,
473{
474 #[track_caller]
475 fn log_err(self) -> LogErrorFuture<Self>
476 where
477 Self: Sized,
478 {
479 let location = Location::caller();
480 LogErrorFuture(self, log::Level::Error, *location)
481 }
482
483 fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture<Self>
484 where
485 Self: Sized,
486 {
487 LogErrorFuture(self, log::Level::Error, location)
488 }
489
490 #[track_caller]
491 fn warn_on_err(self) -> LogErrorFuture<Self>
492 where
493 Self: Sized,
494 {
495 let location = Location::caller();
496 LogErrorFuture(self, log::Level::Warn, *location)
497 }
498
499 fn unwrap(self) -> UnwrapFuture<Self>
500 where
501 Self: Sized,
502 {
503 UnwrapFuture(self)
504 }
505}
506
507#[must_use]
508pub struct LogErrorFuture<F>(F, log::Level, core::panic::Location<'static>);
509
510impl<F, T, E> Future for LogErrorFuture<F>
511where
512 F: Future<Output = Result<T, E>>,
513 E: std::fmt::Debug,
514{
515 type Output = Option<T>;
516
517 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
518 let level = self.1;
519 let location = self.2;
520 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
521 match inner.poll(cx) {
522 Poll::Ready(output) => Poll::Ready(match output {
523 Ok(output) => Some(output),
524 Err(error) => {
525 log_error_with_caller(location, error, level);
526 None
527 }
528 }),
529 Poll::Pending => Poll::Pending,
530 }
531 }
532}
533
534pub struct UnwrapFuture<F>(F);
535
536impl<F, T, E> Future for UnwrapFuture<F>
537where
538 F: Future<Output = Result<T, E>>,
539 E: std::fmt::Debug,
540{
541 type Output = T;
542
543 fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
544 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
545 match inner.poll(cx) {
546 Poll::Ready(result) => Poll::Ready(result.unwrap()),
547 Poll::Pending => Poll::Pending,
548 }
549 }
550}
551
552pub struct Deferred<F: FnOnce()>(Option<F>);
553
554impl<F: FnOnce()> Deferred<F> {
555 /// Drop without running the deferred function.
556 pub fn abort(mut self) {
557 self.0.take();
558 }
559}
560
561impl<F: FnOnce()> Drop for Deferred<F> {
562 fn drop(&mut self) {
563 if let Some(f) = self.0.take() {
564 f()
565 }
566 }
567}
568
569/// Run the given function when the returned value is dropped (unless it's cancelled).
570#[must_use]
571pub fn defer<F: FnOnce()>(f: F) -> Deferred<F> {
572 Deferred(Some(f))
573}
574
575#[cfg(any(test, feature = "test-support"))]
576mod rng {
577 use rand::{seq::SliceRandom, Rng};
578 pub struct RandomCharIter<T: Rng> {
579 rng: T,
580 simple_text: bool,
581 }
582
583 impl<T: Rng> RandomCharIter<T> {
584 pub fn new(rng: T) -> Self {
585 Self {
586 rng,
587 simple_text: std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()),
588 }
589 }
590
591 pub fn with_simple_text(mut self) -> Self {
592 self.simple_text = true;
593 self
594 }
595 }
596
597 impl<T: Rng> Iterator for RandomCharIter<T> {
598 type Item = char;
599
600 fn next(&mut self) -> Option<Self::Item> {
601 if self.simple_text {
602 return if self.rng.gen_range(0..100) < 5 {
603 Some('\n')
604 } else {
605 Some(self.rng.gen_range(b'a'..b'z' + 1).into())
606 };
607 }
608
609 match self.rng.gen_range(0..100) {
610 // whitespace
611 0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(),
612 // two-byte greek letters
613 20..=32 => char::from_u32(self.rng.gen_range(('α' as u32)..('ω' as u32 + 1))),
614 // // three-byte characters
615 33..=45 => ['✋', '✅', '❌', '❎', '⭐']
616 .choose(&mut self.rng)
617 .copied(),
618 // // four-byte characters
619 46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(),
620 // ascii letters
621 _ => Some(self.rng.gen_range(b'a'..b'z' + 1).into()),
622 }
623 }
624 }
625}
626#[cfg(any(test, feature = "test-support"))]
627pub use rng::RandomCharIter;
628/// Get an embedded file as a string.
629pub fn asset_str<A: rust_embed::RustEmbed>(path: &str) -> Cow<'static, str> {
630 match A::get(path).unwrap().data {
631 Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()),
632 Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()),
633 }
634}
635
636/// Expands to an immediately-invoked function expression. Good for using the ? operator
637/// in functions which do not return an Option or Result.
638///
639/// Accepts a normal block, an async block, or an async move block.
640#[macro_export]
641macro_rules! maybe {
642 ($block:block) => {
643 (|| $block)()
644 };
645 (async $block:block) => {
646 (|| async $block)()
647 };
648 (async move $block:block) => {
649 (|| async move $block)()
650 };
651}
652
653pub trait RangeExt<T> {
654 fn sorted(&self) -> Self;
655 fn to_inclusive(&self) -> RangeInclusive<T>;
656 fn overlaps(&self, other: &Range<T>) -> bool;
657 fn contains_inclusive(&self, other: &Range<T>) -> bool;
658}
659
660impl<T: Ord + Clone> RangeExt<T> for Range<T> {
661 fn sorted(&self) -> Self {
662 cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
663 }
664
665 fn to_inclusive(&self) -> RangeInclusive<T> {
666 self.start.clone()..=self.end.clone()
667 }
668
669 fn overlaps(&self, other: &Range<T>) -> bool {
670 self.start < other.end && other.start < self.end
671 }
672
673 fn contains_inclusive(&self, other: &Range<T>) -> bool {
674 self.start <= other.start && other.end <= self.end
675 }
676}
677
678impl<T: Ord + Clone> RangeExt<T> for RangeInclusive<T> {
679 fn sorted(&self) -> Self {
680 cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone()
681 }
682
683 fn to_inclusive(&self) -> RangeInclusive<T> {
684 self.clone()
685 }
686
687 fn overlaps(&self, other: &Range<T>) -> bool {
688 self.start() < &other.end && &other.start <= self.end()
689 }
690
691 fn contains_inclusive(&self, other: &Range<T>) -> bool {
692 self.start() <= &other.start && &other.end <= self.end()
693 }
694}
695
696/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one,
697/// case-insensitive.
698///
699/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc`
700/// into `1-abc, 2, 10, 11-def, .., 21-abc`
701#[derive(Debug, PartialEq, Eq)]
702pub struct NumericPrefixWithSuffix<'a>(Option<u64>, &'a str);
703
704impl<'a> NumericPrefixWithSuffix<'a> {
705 pub fn from_numeric_prefixed_str(str: &'a str) -> Self {
706 let i = str.chars().take_while(|c| c.is_ascii_digit()).count();
707 let (prefix, remainder) = str.split_at(i);
708
709 let prefix = prefix.parse().ok();
710 Self(prefix, remainder)
711 }
712}
713
714/// When dealing with equality, we need to consider the case of the strings to achieve strict equality
715/// to handle cases like "a" < "A" instead of "a" == "A".
716impl Ord for NumericPrefixWithSuffix<'_> {
717 fn cmp(&self, other: &Self) -> Ordering {
718 match (self.0, other.0) {
719 (None, None) => UniCase::new(self.1)
720 .cmp(&UniCase::new(other.1))
721 .then_with(|| self.1.cmp(other.1).reverse()),
722 (None, Some(_)) => Ordering::Greater,
723 (Some(_), None) => Ordering::Less,
724 (Some(a), Some(b)) => a.cmp(&b).then_with(|| {
725 UniCase::new(self.1)
726 .cmp(&UniCase::new(other.1))
727 .then_with(|| self.1.cmp(other.1).reverse())
728 }),
729 }
730 }
731}
732
733impl<'a> PartialOrd for NumericPrefixWithSuffix<'a> {
734 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
735 Some(self.cmp(other))
736 }
737}
738
739fn emoji_regex() -> &'static Regex {
740 static EMOJI_REGEX: LazyLock<Regex> =
741 LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap());
742 &EMOJI_REGEX
743}
744
745/// Returns true if the given string consists of emojis only.
746/// E.g. "👨👩👧👧👋" will return true, but "👋!" will return false.
747pub fn word_consists_of_emojis(s: &str) -> bool {
748 let mut prev_end = 0;
749 for capture in emoji_regex().find_iter(s) {
750 if capture.start() != prev_end {
751 return false;
752 }
753 prev_end = capture.end();
754 }
755 prev_end == s.len()
756}
757
758#[cfg(test)]
759mod tests {
760 use super::*;
761
762 #[test]
763 fn test_extend_sorted() {
764 let mut vec = vec![];
765
766 extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
767 assert_eq!(vec, &[21, 17, 13, 8, 1]);
768
769 extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
770 assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
771
772 extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
773 assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
774 }
775
776 #[test]
777 fn test_truncate_to_bottom_n_sorted_by() {
778 let mut vec: Vec<u32> = vec![5, 2, 3, 4, 1];
779 truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp);
780 assert_eq!(vec, &[1, 2, 3, 4, 5]);
781
782 vec = vec![5, 2, 3, 4, 1];
783 truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp);
784 assert_eq!(vec, &[1, 2, 3, 4, 5]);
785
786 vec = vec![5, 2, 3, 4, 1];
787 truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp);
788 assert_eq!(vec, &[1, 2, 3, 4]);
789
790 vec = vec![5, 2, 3, 4, 1];
791 truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp);
792 assert_eq!(vec, &[1]);
793
794 vec = vec![5, 2, 3, 4, 1];
795 truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp);
796 assert!(vec.is_empty());
797 }
798
799 #[test]
800 fn test_iife() {
801 fn option_returning_function() -> Option<()> {
802 None
803 }
804
805 let foo = maybe!({
806 option_returning_function()?;
807 Some(())
808 });
809
810 assert_eq!(foo, None);
811 }
812
813 #[test]
814 fn test_truncate_and_trailoff() {
815 assert_eq!(truncate_and_trailoff("", 5), "");
816 assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa");
817 assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa");
818 assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaa…");
819 assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè");
820 assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè");
821 assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…");
822 }
823
824 #[test]
825 fn test_truncate_and_remove_front() {
826 assert_eq!(truncate_and_remove_front("", 5), "");
827 assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa");
828 assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa");
829 assert_eq!(truncate_and_remove_front("aaaaaa", 5), "…aaaaa");
830 assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè");
831 assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè");
832 assert_eq!(truncate_and_remove_front("èèèèèè", 5), "…èèèèè");
833 }
834
835 #[test]
836 fn test_numeric_prefix_str_method() {
837 let target = "1a";
838 assert_eq!(
839 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
840 NumericPrefixWithSuffix(Some(1), "a")
841 );
842
843 let target = "12ab";
844 assert_eq!(
845 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
846 NumericPrefixWithSuffix(Some(12), "ab")
847 );
848
849 let target = "12_ab";
850 assert_eq!(
851 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
852 NumericPrefixWithSuffix(Some(12), "_ab")
853 );
854
855 let target = "1_2ab";
856 assert_eq!(
857 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
858 NumericPrefixWithSuffix(Some(1), "_2ab")
859 );
860
861 let target = "1.2";
862 assert_eq!(
863 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
864 NumericPrefixWithSuffix(Some(1), ".2")
865 );
866
867 let target = "1.2_a";
868 assert_eq!(
869 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
870 NumericPrefixWithSuffix(Some(1), ".2_a")
871 );
872
873 let target = "12.2_a";
874 assert_eq!(
875 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
876 NumericPrefixWithSuffix(Some(12), ".2_a")
877 );
878
879 let target = "12a.2_a";
880 assert_eq!(
881 NumericPrefixWithSuffix::from_numeric_prefixed_str(target),
882 NumericPrefixWithSuffix(Some(12), "a.2_a")
883 );
884 }
885
886 #[test]
887 fn test_numeric_prefix_with_suffix() {
888 let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"];
889 sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s));
890 assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]);
891
892 for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~™£"] {
893 assert_eq!(
894 NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less),
895 NumericPrefixWithSuffix(None, numeric_prefix_less),
896 "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix"
897 )
898 }
899 }
900
901 #[test]
902 fn test_word_consists_of_emojis() {
903 let words_to_test = vec![
904 ("👨👩👧👧👋🥒", true),
905 ("👋", true),
906 ("!👋", false),
907 ("👋!", false),
908 ("👋 ", false),
909 (" 👋", false),
910 ("Test", false),
911 ];
912
913 for (text, expected_result) in words_to_test {
914 assert_eq!(word_consists_of_emojis(text), expected_result);
915 }
916 }
917
918 #[test]
919 fn test_truncate_lines_and_trailoff() {
920 let text = r#"Line 1
921Line 2
922Line 3"#;
923
924 assert_eq!(
925 truncate_lines_and_trailoff(text, 2),
926 r#"Line 1
927…"#
928 );
929
930 assert_eq!(
931 truncate_lines_and_trailoff(text, 3),
932 r#"Line 1
933Line 2
934…"#
935 );
936
937 assert_eq!(
938 truncate_lines_and_trailoff(text, 4),
939 r#"Line 1
940Line 2
941Line 3"#
942 );
943 }
944
945 #[test]
946 fn test_iterate_expanded_and_wrapped_usize_range() {
947 // Neither wrap
948 assert_eq!(
949 iterate_expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::<Vec<usize>>(),
950 (1..5).collect::<Vec<usize>>()
951 );
952 // Start wraps
953 assert_eq!(
954 iterate_expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::<Vec<usize>>(),
955 ((0..5).chain(7..8)).collect::<Vec<usize>>()
956 );
957 // Start wraps all the way around
958 assert_eq!(
959 iterate_expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::<Vec<usize>>(),
960 (0..8).collect::<Vec<usize>>()
961 );
962 // Start wraps all the way around and past 0
963 assert_eq!(
964 iterate_expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::<Vec<usize>>(),
965 (0..8).collect::<Vec<usize>>()
966 );
967 // End wraps
968 assert_eq!(
969 iterate_expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::<Vec<usize>>(),
970 (0..1).chain(2..8).collect::<Vec<usize>>()
971 );
972 // End wraps all the way around
973 assert_eq!(
974 iterate_expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::<Vec<usize>>(),
975 (0..8).collect::<Vec<usize>>()
976 );
977 // End wraps all the way around and past the end
978 assert_eq!(
979 iterate_expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::<Vec<usize>>(),
980 (0..8).collect::<Vec<usize>>()
981 );
982 // Both start and end wrap
983 assert_eq!(
984 iterate_expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::<Vec<usize>>(),
985 (0..8).collect::<Vec<usize>>()
986 );
987 }
988}