]> git.lizzy.rs Git - rust.git/blob - crates/stdx/src/lib.rs
Merge #8902
[rust.git] / crates / stdx / src / lib.rs
1 //! Missing batteries for standard libraries.
2 use std::{cmp::Ordering, ops, time::Instant};
3
4 mod macros;
5 pub mod process;
6 pub mod panic_context;
7
8 pub use always_assert::{always, never};
9
10 #[inline(always)]
11 pub fn is_ci() -> bool {
12     option_env!("CI").is_some()
13 }
14
15 #[must_use]
16 pub fn timeit(label: &'static str) -> impl Drop {
17     let start = Instant::now();
18     defer(move || eprintln!("{}: {:.2?}", label, start.elapsed()))
19 }
20
21 /// Prints backtrace to stderr, useful for debugging.
22 #[cfg(feature = "backtrace")]
23 pub fn print_backtrace() {
24     let bt = backtrace::Backtrace::new();
25     eprintln!("{:?}", bt);
26 }
27 #[cfg(not(feature = "backtrace"))]
28 pub fn print_backtrace() {
29     eprintln!(
30         r#"Enable the backtrace feature.
31 Uncomment `default = [ "backtrace" ]` in `crates/stdx/Cargo.toml`.
32 "#
33     );
34 }
35
36 pub fn to_lower_snake_case(s: &str) -> String {
37     to_snake_case(s, char::to_ascii_lowercase)
38 }
39 pub fn to_upper_snake_case(s: &str) -> String {
40     to_snake_case(s, char::to_ascii_uppercase)
41 }
42 fn to_snake_case<F: Fn(&char) -> char>(s: &str, change_case: F) -> String {
43     let mut buf = String::with_capacity(s.len());
44     let mut prev = false;
45     for c in s.chars() {
46         // `&& prev` is required to not insert `_` before the first symbol.
47         if c.is_ascii_uppercase() && prev {
48             // This check is required to not translate `Weird_Case` into `weird__case`.
49             if !buf.ends_with('_') {
50                 buf.push('_')
51             }
52         }
53         prev = true;
54
55         buf.push(change_case(&c));
56     }
57     buf
58 }
59
60 pub fn replace(buf: &mut String, from: char, to: &str) {
61     if !buf.contains(from) {
62         return;
63     }
64     // FIXME: do this in place.
65     *buf = buf.replace(from, to)
66 }
67
68 pub fn trim_indent(mut text: &str) -> String {
69     if text.starts_with('\n') {
70         text = &text[1..];
71     }
72     let indent = text
73         .lines()
74         .filter(|it| !it.trim().is_empty())
75         .map(|it| it.len() - it.trim_start().len())
76         .min()
77         .unwrap_or(0);
78     text.split_inclusive('\n')
79         .map(
80             |line| {
81                 if line.len() <= indent {
82                     line.trim_start_matches(' ')
83                 } else {
84                     &line[indent..]
85                 }
86             },
87         )
88         .collect()
89 }
90
91 pub fn equal_range_by<T, F>(slice: &[T], mut key: F) -> ops::Range<usize>
92 where
93     F: FnMut(&T) -> Ordering,
94 {
95     let start = slice.partition_point(|it| key(it) == Ordering::Less);
96     let len = slice[start..].partition_point(|it| key(it) == Ordering::Equal);
97     start..start + len
98 }
99
100 #[must_use]
101 pub fn defer<F: FnOnce()>(f: F) -> impl Drop {
102     struct D<F: FnOnce()>(Option<F>);
103     impl<F: FnOnce()> Drop for D<F> {
104         fn drop(&mut self) {
105             if let Some(f) = self.0.take() {
106                 f()
107             }
108         }
109     }
110     D(Some(f))
111 }
112
113 #[repr(transparent)]
114 pub struct JodChild(pub std::process::Child);
115
116 impl ops::Deref for JodChild {
117     type Target = std::process::Child;
118     fn deref(&self) -> &std::process::Child {
119         &self.0
120     }
121 }
122
123 impl ops::DerefMut for JodChild {
124     fn deref_mut(&mut self) -> &mut std::process::Child {
125         &mut self.0
126     }
127 }
128
129 impl Drop for JodChild {
130     fn drop(&mut self) {
131         let _ = self.0.kill();
132         let _ = self.0.wait();
133     }
134 }
135
136 impl JodChild {
137     pub fn into_inner(self) -> std::process::Child {
138         // SAFETY: repr transparent
139         unsafe { std::mem::transmute::<JodChild, std::process::Child>(self) }
140     }
141 }
142
143 // feature: iter_order_by
144 // Iterator::eq_by
145 pub fn iter_eq_by<I, I2, F>(this: I2, other: I, mut eq: F) -> bool
146 where
147     I: IntoIterator,
148     I2: IntoIterator,
149     F: FnMut(I2::Item, I::Item) -> bool,
150 {
151     let mut other = other.into_iter();
152     let mut this = this.into_iter();
153
154     loop {
155         let x = match this.next() {
156             None => return other.next().is_none(),
157             Some(val) => val,
158         };
159
160         let y = match other.next() {
161             None => return false,
162             Some(val) => val,
163         };
164
165         if !eq(x, y) {
166             return false;
167         }
168     }
169 }
170
171 #[cfg(test)]
172 mod tests {
173     use super::*;
174
175     #[test]
176     fn test_trim_indent() {
177         assert_eq!(trim_indent(""), "");
178         assert_eq!(
179             trim_indent(
180                 "
181             hello
182             world
183 "
184             ),
185             "hello\nworld\n"
186         );
187         assert_eq!(
188             trim_indent(
189                 "
190             hello
191             world"
192             ),
193             "hello\nworld"
194         );
195         assert_eq!(trim_indent("    hello\n    world\n"), "hello\nworld\n");
196         assert_eq!(
197             trim_indent(
198                 "
199             fn main() {
200                 return 92;
201             }
202         "
203             ),
204             "fn main() {\n    return 92;\n}\n"
205         );
206     }
207 }