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