im/
util.rs

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
7use std::cmp::Ordering;
8use std::ops::{Bound, IndexMut, Range, RangeBounds};
9use std::ptr;
10
11#[cfg(feature = "pool")]
12pub(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))]
18pub(crate) use crate::fakepool::{Arc as PoolRef, Pool, PoolClone, PoolDefault};
19
20// `Ref` == `Arc` when threadsafe
21#[cfg(threadsafe)]
22pub(crate) type Ref<A> = std::sync::Arc<A>;
23
24// `Rc` without refpool
25#[cfg(all(not(threadsafe), not(feature = "pool")))]
26pub(crate) use crate::fakepool::{Pool, PoolClone, PoolDefault, Rc as PoolRef};
27
28// `Rc` with refpool
29#[cfg(all(not(threadsafe), feature = "pool"))]
30pub(crate) type PoolRef<A> = refpool::PoolRef<A>;
31#[cfg(all(not(threadsafe), feature = "pool"))]
32pub(crate) type Pool<A> = refpool::Pool<A>;
33
34// `Ref` == `Rc` when not threadsafe
35#[cfg(not(threadsafe))]
36pub(crate) type Ref<A> = std::rc::Rc<A>;
37
38pub(crate) fn clone_ref<A>(r: Ref<A>) -> A
39where
40    A: Clone,
41{
42    Ref::try_unwrap(r).unwrap_or_else(|r| (*r).clone())
43}
44
45#[derive(Clone, Copy, PartialEq, Eq, Debug)]
46pub(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)]
55pub(crate) fn swap_indices<V>(vector: &mut V, a: usize, b: usize)
56where
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)]
73pub(crate) fn linear_search_by<'a, A, I, F>(iterable: I, mut cmp: F) -> Result<usize, usize>
74where
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
91pub(crate) fn to_range<R>(range: &R, right_unbounded: usize) -> Range<usize>
92where
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
108macro_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}