1 // This Source Code Form is subject to the terms of the Mozilla Public
2 // License, v. 2.0. If a copy of the MPL was not distributed with this
3 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
4 
5 // Every codebase needs a `util` module.
6 
7 use std::cmp::Ordering;
8 use std::ops::{Bound, IndexMut, Range, RangeBounds};
9 use std::ptr;
10 
11 #[cfg(feature = "pool")]
12 pub(crate) use refpool::{PoolClone, PoolDefault};
13 
14 // The `Ref` type is an alias for either `Rc` or `Arc`, user's choice.
15 
16 // `Arc` without refpool
17 #[cfg(all(threadsafe))]
18 pub(crate) use crate::fakepool::{Arc as PoolRef, Pool, PoolClone, PoolDefault};
19 
20 // `Ref` == `Arc` when threadsafe
21 #[cfg(threadsafe)]
22 pub(crate) type Ref<A> = std::sync::Arc<A>;
23 
24 // `Rc` without refpool
25 #[cfg(all(not(threadsafe), not(feature = "pool")))]
26 pub(crate) use crate::fakepool::{Pool, PoolClone, PoolDefault, Rc as PoolRef};
27 
28 // `Rc` with refpool
29 #[cfg(all(not(threadsafe), feature = "pool"))]
30 pub(crate) type PoolRef<A> = refpool::PoolRef<A>;
31 #[cfg(all(not(threadsafe), feature = "pool"))]
32 pub(crate) type Pool<A> = refpool::Pool<A>;
33 
34 // `Ref` == `Rc` when not threadsafe
35 #[cfg(not(threadsafe))]
36 pub(crate) type Ref<A> = std::rc::Rc<A>;
37 
clone_ref<A>(r: Ref<A>) -> A where A: Clone,38 pub(crate) fn clone_ref<A>(r: Ref<A>) -> A
39 where
40     A: Clone,
41 {
42     Ref::try_unwrap(r).unwrap_or_else(|r| (*r).clone())
43 }
44 
45 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
46 pub(crate) enum Side {
47     Left,
48     Right,
49 }
50 
51 /// Swap two values of anything implementing `IndexMut`.
52 ///
53 /// Like `slice::swap`, but more generic.
54 #[allow(unsafe_code)]
swap_indices<V>(vector: &mut V, a: usize, b: usize) where V: IndexMut<usize>, V::Output: Sized,55 pub(crate) fn swap_indices<V>(vector: &mut V, a: usize, b: usize)
56 where
57     V: IndexMut<usize>,
58     V::Output: Sized,
59 {
60     if a == b {
61         return;
62     }
63     // so sorry, but there's no implementation for this in std that's
64     // sufficiently generic
65     let pa: *mut V::Output = &mut vector[a];
66     let pb: *mut V::Output = &mut vector[b];
67     unsafe {
68         ptr::swap(pa, pb);
69     }
70 }
71 
72 #[allow(dead_code)]
linear_search_by<'a, A, I, F>(iterable: I, mut cmp: F) -> Result<usize, usize> where A: 'a, I: IntoIterator<Item = &'a A>, F: FnMut(&A) -> Ordering,73 pub(crate) fn linear_search_by<'a, A, I, F>(iterable: I, mut cmp: F) -> Result<usize, usize>
74 where
75     A: 'a,
76     I: IntoIterator<Item = &'a A>,
77     F: FnMut(&A) -> Ordering,
78 {
79     let mut pos = 0;
80     for value in iterable {
81         match cmp(value) {
82             Ordering::Equal => return Ok(pos),
83             Ordering::Greater => return Err(pos),
84             Ordering::Less => {}
85         }
86         pos += 1;
87     }
88     Err(pos)
89 }
90 
to_range<R>(range: &R, right_unbounded: usize) -> Range<usize> where R: RangeBounds<usize>,91 pub(crate) fn to_range<R>(range: &R, right_unbounded: usize) -> Range<usize>
92 where
93     R: RangeBounds<usize>,
94 {
95     let start_index = match range.start_bound() {
96         Bound::Included(i) => *i,
97         Bound::Excluded(i) => *i + 1,
98         Bound::Unbounded => 0,
99     };
100     let end_index = match range.end_bound() {
101         Bound::Included(i) => *i + 1,
102         Bound::Excluded(i) => *i,
103         Bound::Unbounded => right_unbounded,
104     };
105     start_index..end_index
106 }
107 
108 macro_rules! def_pool {
109     ($name:ident<$($arg:tt),*>, $pooltype:ty) => {
110         /// A memory pool for the appropriate node type.
111         pub struct $name<$($arg,)*>(Pool<$pooltype>);
112 
113         impl<$($arg,)*> $name<$($arg,)*> {
114             /// Create a new pool with the given size.
115             pub fn new(size: usize) -> Self {
116                 Self(Pool::new(size))
117             }
118 
119             /// Fill the pool with preallocated chunks.
120             pub fn fill(&self) {
121                 self.0.fill();
122             }
123 
124             ///Get the current size of the pool.
125             pub fn pool_size(&self) -> usize {
126                 self.0.get_pool_size()
127             }
128         }
129 
130         impl<$($arg,)*> Default for $name<$($arg,)*> {
131             fn default() -> Self {
132                 Self::new($crate::config::POOL_SIZE)
133             }
134         }
135 
136         impl<$($arg,)*> Clone for $name<$($arg,)*> {
137             fn clone(&self) -> Self {
138                 Self(self.0.clone())
139             }
140         }
141     };
142 }
143