Skip to main content

vortex_array/search_sorted/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod decoded;
5mod primitive;
6mod scalar;
7
8use std::cmp::Ordering;
9use std::cmp::Ordering::Equal;
10use std::cmp::Ordering::Greater;
11use std::cmp::Ordering::Less;
12use std::fmt::Debug;
13use std::fmt::Display;
14use std::fmt::Formatter;
15use std::hint;
16
17pub(crate) use decoded::*;
18pub use primitive::*;
19pub use scalar::*;
20use vortex_error::VortexResult;
21
22#[derive(Debug, Copy, Clone, Eq, PartialEq)]
23pub enum SearchSortedSide {
24    Left,
25    Right,
26}
27
28impl Display for SearchSortedSide {
29    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
30        match self {
31            SearchSortedSide::Left => write!(f, "left"),
32            SearchSortedSide::Right => write!(f, "right"),
33        }
34    }
35}
36
37/// Result of performing search_sorted on an Array
38#[derive(Debug, Copy, Clone, PartialEq, Eq)]
39pub enum SearchResult {
40    /// Result for a found element was found in the array and another one could be inserted at the given position
41    /// in the sorted order
42    Found(usize),
43
44    /// Result for an element not found, but that could be inserted at the given position
45    /// in the sorted order.
46    NotFound(usize),
47}
48
49impl SearchResult {
50    /// Convert search result to an index only if the value have been found
51    pub fn to_found(self) -> Option<usize> {
52        match self {
53            Self::Found(i) => Some(i),
54            Self::NotFound(_) => None,
55        }
56    }
57
58    /// Extract index out of search result regardless of whether the value have been found or not
59    pub fn to_index(self) -> usize {
60        match self {
61            Self::Found(i) => i,
62            Self::NotFound(i) => i,
63        }
64    }
65
66    /// Convert search result into an index suitable for searching array of offset indices, i.e. first element starts at 0.
67    ///
68    /// For example for a ChunkedArray with chunk offsets array [0, 3, 8, 10] you can use this method to
69    /// obtain index suitable for indexing into it after performing a search
70    pub fn to_offsets_index(self, len: usize, side: SearchSortedSide) -> usize {
71        match self {
72            SearchResult::Found(i) => {
73                if side == SearchSortedSide::Right || i == len {
74                    i.saturating_sub(1)
75                } else {
76                    i
77                }
78            }
79            SearchResult::NotFound(i) => i.saturating_sub(1),
80        }
81    }
82
83    /// Convert search result into an index suitable for searching array of end indices without 0 offset,
84    /// i.e. first element implicitly covers 0..0th-element range.
85    ///
86    /// For example for a RunEndArray with ends array [3, 8, 10], you can use this method to obtain index suitable for
87    /// indexing into it after performing a search
88    pub fn to_ends_index(self, len: usize) -> usize {
89        let idx = self.to_index();
90        if idx == len { idx - 1 } else { idx }
91    }
92}
93
94impl Display for SearchResult {
95    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
96        match self {
97            SearchResult::Found(i) => write!(f, "Found({i})"),
98            SearchResult::NotFound(i) => write!(f, "NotFound({i})"),
99        }
100    }
101}
102
103pub trait IndexOrd<V> {
104    /// PartialOrd of the value at index `idx` with `elem`.
105    /// For example, if self\[idx\] > elem, return Some(Greater).
106    fn index_cmp(&self, idx: usize, elem: &V) -> VortexResult<Option<Ordering>>;
107
108    #[inline]
109    fn index_lt(&self, idx: usize, elem: &V) -> VortexResult<bool> {
110        Ok(matches!(self.index_cmp(idx, elem)?, Some(Less)))
111    }
112
113    #[inline]
114    fn index_le(&self, idx: usize, elem: &V) -> VortexResult<bool> {
115        Ok(matches!(self.index_cmp(idx, elem)?, Some(Less | Equal)))
116    }
117
118    fn index_gt(&self, idx: usize, elem: &V) -> VortexResult<bool> {
119        Ok(matches!(self.index_cmp(idx, elem)?, Some(Greater)))
120    }
121
122    fn index_ge(&self, idx: usize, elem: &V) -> VortexResult<bool> {
123        Ok(matches!(self.index_cmp(idx, elem)?, Some(Greater | Equal)))
124    }
125
126    /// Get the length of the underlying ordered collection
127    fn index_len(&self) -> usize;
128}
129
130/// Searches for value assuming the array is sorted.
131///
132/// Returned indices satisfy following condition if the search for value was to be inserted into the array at found positions
133///
134/// |side |result satisfies|
135/// |-----|----------------|
136/// |left |array\[i-1\] < value <= array\[i\]|
137/// |right|array\[i-1\] <= value < array\[i\]|
138pub trait SearchSorted<T> {
139    #[inline]
140    fn search_sorted(&self, value: &T, side: SearchSortedSide) -> VortexResult<SearchResult>
141    where
142        Self: IndexOrd<T>,
143    {
144        match side {
145            SearchSortedSide::Left => self.search_sorted_by(
146                |idx| Ok(self.index_cmp(idx, value)?.unwrap_or(Less)),
147                |idx| {
148                    Ok(if self.index_lt(idx, value)? {
149                        Less
150                    } else {
151                        Greater
152                    })
153                },
154                side,
155            ),
156            SearchSortedSide::Right => self.search_sorted_by(
157                |idx| Ok(self.index_cmp(idx, value)?.unwrap_or(Less)),
158                |idx| {
159                    Ok(if self.index_le(idx, value)? {
160                        Less
161                    } else {
162                        Greater
163                    })
164                },
165                side,
166            ),
167        }
168    }
169
170    /// find function is used to find the element if it exists, if element exists side_find will be
171    /// used to find desired index amongst equal values
172    fn search_sorted_by<
173        F: FnMut(usize) -> VortexResult<Ordering>,
174        N: FnMut(usize) -> VortexResult<Ordering>,
175    >(
176        &self,
177        find: F,
178        side_find: N,
179        side: SearchSortedSide,
180    ) -> VortexResult<SearchResult>;
181}
182
183// Default implementation for types that implement IndexOrd.
184impl<S, T> SearchSorted<T> for S
185where
186    S: IndexOrd<T> + ?Sized,
187{
188    #[inline]
189    fn search_sorted_by<
190        F: FnMut(usize) -> VortexResult<Ordering>,
191        N: FnMut(usize) -> VortexResult<Ordering>,
192    >(
193        &self,
194        find: F,
195        side_find: N,
196        side: SearchSortedSide,
197    ) -> VortexResult<SearchResult> {
198        match search_sorted_side_idx(find, 0, self.index_len())? {
199            SearchResult::Found(found) => {
200                let idx_search = match side {
201                    SearchSortedSide::Left => search_sorted_side_idx(side_find, 0, found)?,
202                    SearchSortedSide::Right => {
203                        search_sorted_side_idx(side_find, found, self.index_len())?
204                    }
205                };
206                match idx_search {
207                    SearchResult::NotFound(i) => Ok(SearchResult::Found(i)),
208                    _ => unreachable!(
209                        "searching amongst equal values should never return Found result"
210                    ),
211                }
212            }
213            s => Ok(s),
214        }
215    }
216}
217
218// Code adapted from Rust standard library slice::binary_search_by
219#[inline]
220fn search_sorted_side_idx<F: FnMut(usize) -> VortexResult<Ordering>>(
221    mut find: F,
222    from: usize,
223    to: usize,
224) -> VortexResult<SearchResult> {
225    let mut size = to - from;
226    if size == 0 {
227        return Ok(SearchResult::NotFound(0));
228    }
229    let mut base = from;
230
231    // This loop intentionally doesn't have an early exit if the comparison
232    // returns Equal. We want the number of loop iterations to depend *only*
233    // on the size of the input slice so that the CPU can reliably predict
234    // the loop count.
235    while size > 1 {
236        let half = size / 2;
237        let mid = base + half;
238
239        // SAFETY: the call is made safe by the following inconstants:
240        // - `mid >= 0`: by definition
241        // - `mid < size`: `mid = size / 2 + size / 4 + size / 8 ...`
242        let cmp = find(mid)?;
243
244        // Binary search interacts poorly with branch prediction, so force
245        // the compiler to use conditional moves if supported by the target
246        // architecture.
247        base = hint::select_unpredictable(cmp == Greater, base, mid);
248
249        // This is imprecise in the case where `size` is odd and the
250        // comparison returns Greater: the mid element still gets included
251        // by `size` even though it's known to be larger than the element
252        // being searched for.
253        // This is fine though: we gain more performance by keeping the
254        // loop iteration count invariant (and thus predictable) than we
255        // lose from considering one additional element.
256        size -= half;
257    }
258
259    // SAFETY: base is always in [0, size) because base <= mid.
260    let cmp = find(base)?;
261    if cmp == Equal {
262        // SAFETY: same as the call to `find` above.
263        unsafe { hint::assert_unchecked(base < to) };
264        Ok(SearchResult::Found(base))
265    } else {
266        let result = base + (cmp == Less) as usize;
267        // SAFETY: same as the call to `find` above.
268        // Note that this is `<=`, unlike the assert in the `Found` path.
269        unsafe { hint::assert_unchecked(result <= to) };
270        Ok(SearchResult::NotFound(result))
271    }
272}
273
274impl<T: PartialOrd> IndexOrd<T> for [T] {
275    #[inline]
276    fn index_cmp(&self, idx: usize, elem: &T) -> VortexResult<Option<Ordering>> {
277        // SAFETY: Used in search_sorted_by same as the standard library. The search_sorted ensures idx is in bounds
278        Ok(unsafe { self.get_unchecked(idx) }.partial_cmp(elem))
279    }
280
281    #[inline]
282    fn index_len(&self) -> usize {
283        self.len()
284    }
285}
286
287#[cfg(test)]
288mod tests {
289    use vortex_error::VortexResult;
290
291    use crate::search_sorted::SearchResult;
292    use crate::search_sorted::SearchSorted;
293    use crate::search_sorted::SearchSortedSide;
294
295    #[test]
296    fn left_side_equal() -> VortexResult<()> {
297        let arr = [0, 1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9];
298        let res = arr.search_sorted(&2, SearchSortedSide::Left)?;
299        assert_eq!(arr[res.to_index()], 2);
300        assert_eq!(res, SearchResult::Found(2));
301        Ok(())
302    }
303
304    #[test]
305    fn right_side_equal() -> VortexResult<()> {
306        let arr = [0, 1, 2, 2, 2, 2, 3, 4, 5, 6, 7, 8, 9];
307        let res = arr.search_sorted(&2, SearchSortedSide::Right)?;
308        assert_eq!(arr[res.to_index() - 1], 2);
309        assert_eq!(res, SearchResult::Found(6));
310        Ok(())
311    }
312
313    #[test]
314    fn left_side_equal_beginning() -> VortexResult<()> {
315        let arr = [0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
316        let res = arr.search_sorted(&0, SearchSortedSide::Left)?;
317        assert_eq!(arr[res.to_index()], 0);
318        assert_eq!(res, SearchResult::Found(0));
319        Ok(())
320    }
321
322    #[test]
323    fn right_side_equal_beginning() -> VortexResult<()> {
324        let arr = [0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
325        let res = arr.search_sorted(&0, SearchSortedSide::Right)?;
326        assert_eq!(arr[res.to_index() - 1], 0);
327        assert_eq!(res, SearchResult::Found(4));
328        Ok(())
329    }
330
331    #[test]
332    fn left_side_equal_end() -> VortexResult<()> {
333        let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9];
334        let res = arr.search_sorted(&9, SearchSortedSide::Left)?;
335        assert_eq!(arr[res.to_index()], 9);
336        assert_eq!(res, SearchResult::Found(9));
337        Ok(())
338    }
339
340    #[test]
341    fn right_side_equal_end() -> VortexResult<()> {
342        let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9];
343        let res = arr.search_sorted(&9, SearchSortedSide::Right)?;
344        assert_eq!(arr[res.to_index() - 1], 9);
345        assert_eq!(res, SearchResult::Found(13));
346        Ok(())
347    }
348}