]> git.lizzy.rs Git - rust.git/blob - crates/stdx/src/lib.rs
Merge #7193
[rust.git] / crates / stdx / src / lib.rs
1 //! Missing batteries for standard libraries.
2 use std::{ops, process, time::Instant};
3
4 mod macros;
5 pub mod panic_context;
6
7 #[inline(always)]
8 pub fn is_ci() -> bool {
9     option_env!("CI").is_some()
10 }
11
12 #[must_use]
13 pub fn timeit(label: &'static str) -> impl Drop {
14     struct Guard {
15         label: &'static str,
16         start: Instant,
17     }
18
19     impl Drop for Guard {
20         fn drop(&mut self) {
21             eprintln!("{}: {:.2?}", self.label, self.start.elapsed())
22         }
23     }
24
25     Guard { label, start: Instant::now() }
26 }
27
28 fn to_snake_case<F: Fn(&char) -> char>(s: &str, change_case: F) -> String {
29     let mut buf = String::with_capacity(s.len());
30     let mut prev = false;
31     for c in s.chars() {
32         // `&& prev` is required to not insert `_` before the first symbol.
33         if c.is_ascii_uppercase() && prev {
34             // This check is required to not translate `Weird_Case` into `weird__case`.
35             if !buf.ends_with('_') {
36                 buf.push('_')
37             }
38         }
39         prev = true;
40
41         buf.push(change_case(&c));
42     }
43     buf
44 }
45
46 pub fn to_lower_snake_case(s: &str) -> String {
47     to_snake_case(s, char::to_ascii_lowercase)
48 }
49
50 pub fn to_upper_snake_case(s: &str) -> String {
51     to_snake_case(s, char::to_ascii_uppercase)
52 }
53
54 pub fn replace(buf: &mut String, from: char, to: &str) {
55     if !buf.contains(from) {
56         return;
57     }
58     // FIXME: do this in place.
59     *buf = buf.replace(from, to)
60 }
61
62 // https://github.com/rust-lang/rust/issues/74773
63 pub fn split_once(haystack: &str, delim: char) -> Option<(&str, &str)> {
64     let mut split = haystack.splitn(2, delim);
65     let prefix = split.next()?;
66     let suffix = split.next()?;
67     Some((prefix, suffix))
68 }
69 pub fn rsplit_once(haystack: &str, delim: char) -> Option<(&str, &str)> {
70     let mut split = haystack.rsplitn(2, delim);
71     let suffix = split.next()?;
72     let prefix = split.next()?;
73     Some((prefix, suffix))
74 }
75
76 pub fn trim_indent(mut text: &str) -> String {
77     if text.starts_with('\n') {
78         text = &text[1..];
79     }
80     let indent = text
81         .lines()
82         .filter(|it| !it.trim().is_empty())
83         .map(|it| it.len() - it.trim_start().len())
84         .min()
85         .unwrap_or(0);
86     lines_with_ends(text)
87         .map(
88             |line| {
89                 if line.len() <= indent {
90                     line.trim_start_matches(' ')
91                 } else {
92                     &line[indent..]
93                 }
94             },
95         )
96         .collect()
97 }
98
99 pub fn lines_with_ends(text: &str) -> LinesWithEnds {
100     LinesWithEnds { text }
101 }
102
103 pub struct LinesWithEnds<'a> {
104     text: &'a str,
105 }
106
107 impl<'a> Iterator for LinesWithEnds<'a> {
108     type Item = &'a str;
109     fn next(&mut self) -> Option<&'a str> {
110         if self.text.is_empty() {
111             return None;
112         }
113         let idx = self.text.find('\n').map_or(self.text.len(), |it| it + 1);
114         let (res, next) = self.text.split_at(idx);
115         self.text = next;
116         Some(res)
117     }
118 }
119
120 // https://github.com/rust-lang/rust/issues/73831
121 pub fn partition_point<T, P>(slice: &[T], mut pred: P) -> usize
122 where
123     P: FnMut(&T) -> bool,
124 {
125     let mut left = 0;
126     let mut right = slice.len();
127
128     while left != right {
129         let mid = left + (right - left) / 2;
130         // SAFETY:
131         // When left < right, left <= mid < right.
132         // Therefore left always increases and right always decreases,
133         // and either of them is selected.
134         // In both cases left <= right is satisfied.
135         // Therefore if left < right in a step,
136         // left <= right is satisfied in the next step.
137         // Therefore as long as left != right, 0 <= left < right <= len is satisfied
138         // and if this case 0 <= mid < len is satisfied too.
139         let value = unsafe { slice.get_unchecked(mid) };
140         if pred(value) {
141             left = mid + 1;
142         } else {
143             right = mid;
144         }
145     }
146
147     left
148 }
149
150 pub struct JodChild(pub process::Child);
151
152 impl ops::Deref for JodChild {
153     type Target = process::Child;
154     fn deref(&self) -> &process::Child {
155         &self.0
156     }
157 }
158
159 impl ops::DerefMut for JodChild {
160     fn deref_mut(&mut self) -> &mut process::Child {
161         &mut self.0
162     }
163 }
164
165 impl Drop for JodChild {
166     fn drop(&mut self) {
167         let _ = self.0.kill();
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 }