Debian Codegraph @

rust/hg-core/src/utils.rs

raw
1 // utils module
2 //
3 // Copyright 2019 Raphaël Gomès <[email protected]>
4 //
5 // This software may be used and distributed according to the terms of the
6 // GNU General Public License version 2 or any later version.
7
8 //! Contains useful functions, traits, structs, etc. for use in core.
9
10 use std::borrow::Cow;
11 use std::cmp::Ordering;
12 use std::sync::Arc;
13
14 use im_rc::ordmap::DiffItem;
15 use im_rc::ordmap::OrdMap;
16 use itertools::EitherOrBoth;
17 use itertools::Itertools;
18
19 use crate::errors::HgBacktrace;
20 use crate::errors::HgError;
21 use crate::errors::IoErrorContext;
22
23 pub mod debug;
24 pub mod docket;
25 pub mod files;
26 pub mod hg_path;
27 pub mod path_auditor;
28 pub mod strings;
29
30 #[inline(always)]
31 pub fn u32_u(i: u32) -> usize {
32 // XXX I am tempted to just use `as usize` only in debug mode
33 i.try_into()
34 .expect("usize can't hold a u32, are you on a 16 bits computer ?")
35 }
36
37 #[inline(always)]
38 pub fn u_u32(i: usize) -> u32 {
39 i.try_into().expect("value too large for a u32")
40 }
41
42 #[inline(always)]
43 pub fn u_i32(i: usize) -> i32 {
44 i.try_into().expect("value too large for a i32")
45 }
46
47 #[inline(always)]
48 pub fn u16_u(i: u16) -> usize {
49 i as usize
50 }
51
52 #[inline(always)]
53 pub fn u_u16(i: usize) -> u16 {
54 i.try_into().expect("value too large for a u16")
55 }
56
57 pub fn current_dir() -> Result<std::path::PathBuf, HgError> {
58 std::env::current_dir().map_err(|error| HgError::IoError {
59 error,
60 context: IoErrorContext::CurrentDir,
61 backtrace: HgBacktrace::capture(),
62 })
63 }
64
65 pub fn current_exe() -> Result<std::path::PathBuf, HgError> {
66 std::env::current_exe().map_err(|error| HgError::IoError {
67 error,
68 context: IoErrorContext::CurrentExe,
69 backtrace: HgBacktrace::capture(),
70 })
71 }
72
73 pub(crate) enum MergeResult<V> {
74 Left,
75 Right,
76 New(V),
77 }
78
79 /// Return the union of the two given maps,
80 /// calling `merge(key, left_value, right_value)` to resolve keys that exist in
81 /// both.
82 ///
83 /// CC <https://github.com/bodil/im-rs/issues/166>
84 pub(crate) fn ordmap_union_with_merge<K, V>(
85 left: OrdMap<K, V>,
86 right: OrdMap<K, V>,
87 mut merge: impl FnMut(&K, &V, &V) -> MergeResult<V>,
88 ) -> OrdMap<K, V>
89 where
90 K: Clone + Ord,
91 V: Clone + PartialEq,
92 {
93 if left.ptr_eq(&right) {
94 // One of the two maps is an unmodified clone of the other
95 left
96 } else if left.len() / 2 > right.len() {
97 // When two maps have different sizes,
98 // their size difference is a lower bound on
99 // how many keys of the larger map are not also in the smaller map.
100 // This in turn is a lower bound on the number of differences in
101 // `OrdMap::diff` and the "amount of work" that would be done
102 // by `ordmap_union_with_merge_by_diff`.
103 //
104 // Here `left` is more than twice the size of `right`,
105 // so the number of differences is more than the total size of
106 // `right`. Therefore an algorithm based on iterating `right`
107 // is more efficient.
108 //
109 // This helps a lot when a tiny (or empty) map is merged
110 // with a large one.
111 ordmap_union_with_merge_by_iter(left, right, merge)
112 } else if left.len() < right.len() / 2 {
113 // Same as above but with `left` and `right` swapped
114 ordmap_union_with_merge_by_iter(right, left, |key, a, b| {
115 // Also swapped in `merge` arguments:
116 match merge(key, b, a) {
117 MergeResult::New(v) => MergeResult::New(v),
118 // … and swap back in `merge` result:
119 MergeResult::Left => MergeResult::Right,
120 MergeResult::Right => MergeResult::Left,
121 }
122 })
123 } else {
124 // For maps of similar size, use the algorithm based on `OrdMap::diff`
125 ordmap_union_with_merge_by_diff(left, right, merge)
126 }
127 }
128
129 /// Efficient if `right` is much smaller than `left`
130 fn ordmap_union_with_merge_by_iter<K, V>(
131 mut left: OrdMap<K, V>,
132 right: OrdMap<K, V>,
133 mut merge: impl FnMut(&K, &V, &V) -> MergeResult<V>,
134 ) -> OrdMap<K, V>
135 where
136 K: Clone + Ord,
137 V: Clone,
138 {
139 for (key, right_value) in right {
140 match left.get(&key) {
141 None => {
142 left.insert(key, right_value);
143 }
144 Some(left_value) => match merge(&key, left_value, &right_value) {
145 MergeResult::Left => {}
146 MergeResult::Right => {
147 left.insert(key, right_value);
148 }
149 MergeResult::New(new_value) => {
150 left.insert(key, new_value);
151 }
152 },
153 }
154 }
155 left
156 }
157
158 /// Fallback when both maps are of similar size
159 fn ordmap_union_with_merge_by_diff<K, V>(
160 mut left: OrdMap<K, V>,
161 mut right: OrdMap<K, V>,
162 mut merge: impl FnMut(&K, &V, &V) -> MergeResult<V>,
163 ) -> OrdMap<K, V>
164 where
165 K: Clone + Ord,
166 V: Clone + PartialEq,
167 {
168 // (key, value) pairs that would need to be inserted in either map
169 // in order to turn it into the union.
170 //
171 // TODO: if/when https://github.com/bodil/im-rs/pull/168 is accepted,
172 // change these from `Vec<(K, V)>` to `Vec<(&K, Cow<V>)>`
173 // with `left_updates` only borrowing from `right` and `right_updates` from
174 // `left`, and with `Cow::Owned` used for `MergeResult::New`.
175 //
176 // This would allow moving all `.clone()` calls to after we’ve decided
177 // which of `right_updates` or `left_updates` to use
178 // (value ones becoming `Cow::into_owned`),
179 // and avoid making clones we don’t end up using.
180 let mut left_updates = Vec::new();
181 let mut right_updates = Vec::new();
182
183 for difference in left.diff(&right) {
184 match difference {
185 DiffItem::Add(key, value) => {
186 left_updates.push((key.clone(), value.clone()))
187 }
188 DiffItem::Remove(key, value) => {
189 right_updates.push((key.clone(), value.clone()))
190 }
191 DiffItem::Update {
192 old: (key, left_value),
193 new: (_, right_value),
194 } => match merge(key, left_value, right_value) {
195 MergeResult::Left => {
196 right_updates.push((key.clone(), left_value.clone()))
197 }
198 MergeResult::Right => {
199 left_updates.push((key.clone(), right_value.clone()))
200 }
201 MergeResult::New(new_value) => {
202 left_updates.push((key.clone(), new_value.clone()));
203 right_updates.push((key.clone(), new_value))
204 }
205 },
206 }
207 }
208 if left_updates.len() < right_updates.len() {
209 for (key, value) in left_updates {
210 left.insert(key, value);
211 }
212 left
213 } else {
214 for (key, value) in right_updates {
215 right.insert(key, value);
216 }
217 right
218 }
219 }
220
221 /// Like `Iterator::filter_map`, but over a fallible iterator of `Result`s.
222 ///
223 /// The callback is only called for incoming `Ok` values. Errors are passed
224 /// through as-is. In order to let it use the `?` operator the callback is
225 /// expected to return a `Result` of `Option`, instead of an `Option` of
226 /// `Result`.
227 pub fn filter_map_results<'a, I, F, A, B, E>(
228 iter: I,
229 f: F,
230 ) -> impl Iterator<Item = Result<B, E>> + 'a
231 where
232 I: Iterator<Item = Result<A, E>> + 'a,
233 F: Fn(A) -> Result<Option<B>, E> + 'a,
234 {
235 iter.filter_map(move |result| match result {
236 Ok(node) => f(node).transpose(),
237 Err(e) => Some(Err(e)),
238 })
239 }
240
241 /// Like `itertools::merge_join_by`, but merges fallible iterators.
242 ///
243 /// The callback is only used for Ok values. Errors are passed through as-is.
244 /// Errors compare less than Ok values, which makes the error handling
245 /// conservative.
246 pub fn merge_join_results_by<'a, I1, I2, F, A, B, E>(
247 iter1: I1,
248 iter2: I2,
249 f: F,
250 ) -> impl Iterator<Item = Result<EitherOrBoth<A, B>, E>> + 'a
251 where
252 I1: Iterator<Item = Result<A, E>> + 'a,
253 I2: Iterator<Item = Result<B, E>> + 'a,
254 F: FnMut(&A, &B) -> Ordering + 'a,
255 {
256 let mut g = f;
257 iter1
258 .merge_join_by(iter2, move |i1, i2| match i1 {
259 Err(_) => Ordering::Less,
260 Ok(i1) => match i2 {
261 Err(_) => Ordering::Greater,
262 Ok(i2) => g(i1, i2),
263 },
264 })
265 .map(|result| match result {
266 EitherOrBoth::Left(Err(e)) => Err(e),
267 EitherOrBoth::Right(Err(e)) => Err(e),
268 EitherOrBoth::Both(Err(e), _) => Err(e),
269 EitherOrBoth::Both(_, Err(e)) => Err(e),
270 EitherOrBoth::Left(Ok(v)) => Ok(EitherOrBoth::Left(v)),
271 EitherOrBoth::Right(Ok(v)) => Ok(EitherOrBoth::Right(v)),
272 EitherOrBoth::Both(Ok(v1), Ok(v2)) => {
273 Ok(EitherOrBoth::Both(v1, v2))
274 }
275 })
276 }
277
278 /// Force the global rayon threadpool to not exceed 16 concurrent threads
279 /// unless the user has specified a value.
280 /// This is a stop-gap measure until we figure out why using more than 16
281 /// threads makes `status` and `update` slower for each additional thread.
282 ///
283 /// TODO find the underlying cause and fix it, then remove this.
284 ///
285 /// # Errors
286 ///
287 /// Returns an error if the global threadpool has already been initialized if
288 /// we try to initialize it.
289 pub fn cap_default_rayon_threads() -> Result<(), rayon::ThreadPoolBuildError> {
290 const THREAD_CAP: usize = 16;
291
292 if std::env::var("RAYON_NUM_THREADS").is_err() {
293 let available_parallelism =
294 std::thread::available_parallelism().map(usize::from).unwrap_or(1);
295 let new_thread_count = THREAD_CAP.min(available_parallelism);
296 let res = rayon::ThreadPoolBuilder::new()
297 .num_threads(new_thread_count)
298 .build_global();
299 if res.is_ok() {
300 tracing::debug!(
301 name: "threadpool capped",
302 "Capped the rayon threadpool to {new_thread_count} threads",
303 );
304 }
305 return res;
306 }
307 Ok(())
308 }
309
310 /// Represent the data from disk or from a Revision.
311 ///
312 /// TODO: We should probably use Bytes, from the https://crates.io/crates/bytes
313 #[derive(Clone, PartialEq, Eq, Debug)]
314 pub struct RawData {
315 inner: Arc<Vec<u8>>,
316 }
317
318 impl RawData {
319 pub fn empty() -> Self {
320 Self::from(vec![])
321 }
322
323 pub fn len(&self) -> usize {
324 self.inner.len()
325 }
326
327 pub fn is_empty(&self) -> bool {
328 self.inner.is_empty()
329 }
330 }
331
332 impl From<Cow<'_, [u8]>> for RawData {
333 fn from(src: Cow<'_, [u8]>) -> Self {
334 Self { inner: src.into_owned().into() }
335 }
336 }
337
338 impl From<Vec<u8>> for RawData {
339 fn from(src: Vec<u8>) -> Self {
340 Self { inner: src.into() }
341 }
342 }
343
344 impl From<&[u8]> for RawData {
345 fn from(src: &[u8]) -> Self {
346 Self { inner: src.to_vec().into() }
347 }
348 }
349
350 impl From<RawData> for Vec<u8> {
351 fn from(src: RawData) -> Self {
352 src.inner.to_vec()
353 }
354 }
355
356 impl AsRef<[u8]> for RawData {
357 fn as_ref(&self) -> &[u8] {
358 self.inner.as_ref()
359 }
360 }
361 impl std::ops::Deref for RawData {
362 type Target = [u8];
363
364 fn deref(&self) -> &Self::Target {
365 self.as_ref()
366 }
367 }
368
369 /// Limits the actual memory usage of all byte slices in its cache. It does not
370 /// take into account the size of the map itself.
371 ///
372 /// Note that the size could be an overestimate of the actual heap size since
373 /// each [`Arc`] could point to the same underlying bytes. In practice, we
374 /// don't use this cache in a way that could be confusing.
375 pub struct ByTotalChunksSize {
376 /// Current sum of the length of all slices that have been inserted and
377 /// are still currently in cache.
378 total_chunks_size: usize,
379 /// Maximum of [`Self::total_chunks_size`] before old entries are
380 /// discarded.
381 max_chunks_size: usize,
382 /// When the maximum is increased, it also gets multiplied by this factor.
383 /// It is useful to make sure the cache can hold the uncompressed chunks
384 /// for a few revisions at any time, while limiting the memory usage to a
385 /// factor of what operations on these chunks would already cost anyway.
386 resize_factor: usize,
387 }
388
389 impl ByTotalChunksSize {
390 /// Return a new [`Self`] limiter with `max_chunks_size` bytes as a maximum
391 /// size for all bytes in cache.
392 pub fn new(max_chunks_size: usize, resize_factor: usize) -> Self {
393 Self { total_chunks_size: 0, max_chunks_size, resize_factor }
394 }
395
396 /// Make sure the cache can contains "factor" time the largest content
397 /// associated with it.
398 pub fn maybe_grow_max(&mut self, new_max: usize) {
399 let candidate = new_max * self.resize_factor;
400 if candidate > self.max_chunks_size {
401 self.max_chunks_size = candidate;
402 }
403 }
404 }
405
406 impl<K> schnellru::Limiter<K, RawData> for ByTotalChunksSize
407 where
408 K: PartialEq + core::fmt::Debug,
409 {
410 type KeyToInsert<'a> = K;
411
412 type LinkType = u32;
413
414 fn is_over_the_limit(&self, _length: usize) -> bool {
415 self.total_chunks_size > self.max_chunks_size
416 }
417
418 fn on_insert(
419 &mut self,
420 _length: usize,
421 key: Self::KeyToInsert<'_>,
422 value: RawData,
423 ) -> Option<(K, RawData)> {
424 let new_size = value.len();
425 self.maybe_grow_max(new_size);
426
427 self.total_chunks_size += new_size;
428 Some((key, value))
429 }
430
431 fn on_replace(
432 &mut self,
433 _length: usize,
434 old_key: &mut K,
435 new_key: Self::KeyToInsert<'_>,
436 old_value: &mut RawData,
437 new_value: &mut RawData,
438 ) -> bool {
439 assert_eq!(*old_key, new_key);
440
441 let new_size = new_value.len();
442 self.maybe_grow_max(new_size);
443 let old_size = old_value.len();
444 self.total_chunks_size = self.total_chunks_size - old_size + new_size;
445 true
446 }
447
448 fn on_removed(&mut self, _key: &mut K, value: &mut RawData) {
449 self.total_chunks_size -= value.len();
450 }
451
452 fn on_cleared(&mut self) {
453 self.total_chunks_size = 0;
454 }
455
456 fn on_grow(&mut self, _new_memory_usage: usize) -> bool {
457 // We don't care about the size of the map itself
458 true
459 }
460 }