1#[cfg(any(test, feature = "test-support"))]
2pub mod test;
3
4use futures::Future;
5use rand::{seq::SliceRandom, Rng};
6use std::{
7 cmp::Ordering,
8 ops::AddAssign,
9 pin::Pin,
10 task::{Context, Poll},
11};
12
13pub fn truncate(s: &str, max_chars: usize) -> &str {
14 match s.char_indices().nth(max_chars) {
15 None => s,
16 Some((idx, _)) => &s[..idx],
17 }
18}
19
20pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String {
21 debug_assert!(max_chars >= 5);
22
23 if s.len() > max_chars {
24 format!("{}…", truncate(&s, max_chars.saturating_sub(3)))
25 } else {
26 s.to_string()
27 }
28}
29
30pub fn post_inc<T: From<u8> + AddAssign<T> + Copy>(value: &mut T) -> T {
31 let prev = *value;
32 *value += T::from(1);
33 prev
34}
35
36/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and
37/// enforcing a maximum length. Sort the items according to the given callback. Before calling this,
38/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator.
39pub fn extend_sorted<T, I, F>(vec: &mut Vec<T>, new_items: I, limit: usize, mut cmp: F)
40where
41 I: IntoIterator<Item = T>,
42 F: FnMut(&T, &T) -> Ordering,
43{
44 let mut start_index = 0;
45 for new_item in new_items {
46 if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) {
47 let index = start_index + i;
48 if vec.len() < limit {
49 vec.insert(index, new_item);
50 } else if index < vec.len() {
51 vec.pop();
52 vec.insert(index, new_item);
53 }
54 start_index = index;
55 }
56 }
57}
58
59pub trait ResultExt {
60 type Ok;
61
62 fn log_err(self) -> Option<Self::Ok>;
63 fn warn_on_err(self) -> Option<Self::Ok>;
64}
65
66impl<T, E> ResultExt for Result<T, E>
67where
68 E: std::fmt::Debug,
69{
70 type Ok = T;
71
72 fn log_err(self) -> Option<T> {
73 match self {
74 Ok(value) => Some(value),
75 Err(error) => {
76 log::error!("{:?}", error);
77 None
78 }
79 }
80 }
81
82 fn warn_on_err(self) -> Option<T> {
83 match self {
84 Ok(value) => Some(value),
85 Err(error) => {
86 log::warn!("{:?}", error);
87 None
88 }
89 }
90 }
91}
92
93pub trait TryFutureExt {
94 fn log_err(self) -> LogErrorFuture<Self>
95 where
96 Self: Sized;
97 fn warn_on_err(self) -> LogErrorFuture<Self>
98 where
99 Self: Sized;
100}
101
102impl<F, T> TryFutureExt for F
103where
104 F: Future<Output = anyhow::Result<T>>,
105{
106 fn log_err(self) -> LogErrorFuture<Self>
107 where
108 Self: Sized,
109 {
110 LogErrorFuture(self, log::Level::Error)
111 }
112
113 fn warn_on_err(self) -> LogErrorFuture<Self>
114 where
115 Self: Sized,
116 {
117 LogErrorFuture(self, log::Level::Warn)
118 }
119}
120
121pub struct LogErrorFuture<F>(F, log::Level);
122
123impl<F, T> Future for LogErrorFuture<F>
124where
125 F: Future<Output = anyhow::Result<T>>,
126{
127 type Output = Option<T>;
128
129 fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
130 let level = self.1;
131 let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) };
132 match inner.poll(cx) {
133 Poll::Ready(output) => Poll::Ready(match output {
134 Ok(output) => Some(output),
135 Err(error) => {
136 log::log!(level, "{:?}", error);
137 None
138 }
139 }),
140 Poll::Pending => Poll::Pending,
141 }
142 }
143}
144
145struct Defer<F: FnOnce()>(Option<F>);
146
147impl<F: FnOnce()> Drop for Defer<F> {
148 fn drop(&mut self) {
149 if let Some(f) = self.0.take() {
150 f()
151 }
152 }
153}
154
155pub fn defer<F: FnOnce()>(f: F) -> impl Drop {
156 Defer(Some(f))
157}
158
159pub struct RandomCharIter<T: Rng>(T);
160
161impl<T: Rng> RandomCharIter<T> {
162 pub fn new(rng: T) -> Self {
163 Self(rng)
164 }
165}
166
167impl<T: Rng> Iterator for RandomCharIter<T> {
168 type Item = char;
169
170 fn next(&mut self) -> Option<Self::Item> {
171 if std::env::var("SIMPLE_TEXT").map_or(false, |v| !v.is_empty()) {
172 return if self.0.gen_range(0..100) < 5 {
173 Some('\n')
174 } else {
175 Some(self.0.gen_range(b'a'..b'z' + 1).into())
176 };
177 }
178
179 match self.0.gen_range(0..100) {
180 // whitespace
181 0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.0).copied(),
182 // two-byte greek letters
183 20..=32 => char::from_u32(self.0.gen_range(('α' as u32)..('ω' as u32 + 1))),
184 // // three-byte characters
185 33..=45 => ['✋', '✅', '❌', '❎', '⭐'].choose(&mut self.0).copied(),
186 // // four-byte characters
187 46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.0).copied(),
188 // ascii letters
189 _ => Some(self.0.gen_range(b'a'..b'z' + 1).into()),
190 }
191 }
192}
193
194#[cfg(test)]
195mod tests {
196 use super::*;
197
198 #[test]
199 fn test_extend_sorted() {
200 let mut vec = vec![];
201
202 extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a));
203 assert_eq!(vec, &[21, 17, 13, 8, 1]);
204
205 extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a));
206 assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]);
207
208 extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a));
209 assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
210 }
211}