Skip to main content

vortex_array/search_sorted/
primitive.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::cell::RefCell;
5use std::cmp::Ordering;
6use std::marker::PhantomData;
7
8use vortex_error::VortexExpect;
9use vortex_error::VortexResult;
10
11use crate::ArrayProbe;
12use crate::ArrayRef;
13use crate::ExecutionCtx;
14use crate::RepeatedArrayProbe;
15use crate::arrays::Primitive;
16use crate::arrays::primitive::PrimitiveArrayExt;
17use crate::dtype::NativePType;
18use crate::search_sorted::IndexOrd;
19
20/// A [`SearchSorted`](crate::search_sorted::SearchSorted) adapter over a sorted primitive-typed
21/// array, comparing elements as the native type `T`.
22///
23/// Reads go through a [`RepeatedArrayProbe`], so the encoding state and validity resolved on the
24/// first comparison are reused by the rest of the search rather than rebuilt per probe.
25///
26/// Values can be searched as `T`, `Option<T>`, or `usize`. Searching as `T` or `usize` treats
27/// null elements as `T::zero()`; use `Option<T>` when the array may contain nulls, in which case
28/// nulls sort before all non-null values.
29pub struct SearchSortedPrimitiveArray<'a, T> {
30    reader: Reader<'a, T>,
31    len: usize,
32    ctx: RefCell<&'a mut ExecutionCtx>,
33    _ptype: PhantomData<T>,
34}
35
36/// Where a comparison reads its element from.
37enum Reader<'a, T> {
38    /// The array's own buffer. Only for a canonical, non-nullable, host-backed array, where
39    /// every element is a `T` at a known offset and none of them is null.
40    Values(&'a [T]),
41    /// Anything else, through one probe reused by the whole search.
42    Probe(RefCell<RepeatedArrayProbe>),
43    /// Anything else, through a probe the caller already holds, such as a child slot of the
44    /// array it is reading, so the search shares whatever that probe has resolved.
45    Borrowed(RefCell<ArrayProbe<'a>>),
46}
47
48impl<'a, T: NativePType> SearchSortedPrimitiveArray<'a, T> {
49    /// Wraps `array` for searching, panicking if the array's [`PType`](crate::dtype::PType) is
50    /// not `T::PTYPE`.
51    pub fn new(array: &'a ArrayRef, ctx: &'a mut ExecutionCtx) -> Self {
52        assert_eq!(
53            array.dtype().as_ptype(),
54            T::PTYPE,
55            "Array PType must match primitive type"
56        );
57        Self {
58            reader: Self::reader(array),
59            len: array.len(),
60            ctx: RefCell::new(ctx),
61            _ptype: PhantomData,
62        }
63    }
64
65    /// Wraps the array `probe` reads for searching, reading through `probe` rather than a new
66    /// one, panicking if the array's [`PType`](crate::dtype::PType) is not `T::PTYPE`.
67    ///
68    /// A caller that already holds a probe of the array, such as a child slot of a
69    /// [`ProbeState`](crate::ProbeState), searches through it so a repeated read shares that
70    /// probe's state across its searches.
71    pub fn with_probe(probe: ArrayProbe<'a>, ctx: &'a mut ExecutionCtx) -> Self {
72        let array = probe.array();
73        assert_eq!(
74            array.dtype().as_ptype(),
75            T::PTYPE,
76            "Array PType must match primitive type"
77        );
78        let len = array.len();
79        let reader = match probe {
80            ArrayProbe::Once(array) => Self::reader(array),
81            ArrayProbe::Repeated(probe) if Self::values(probe.array()).is_some() => {
82                let probe: &'a RepeatedArrayProbe = probe;
83                Reader::Values(
84                    Self::values(probe.array()).vortex_expect("checked to offer values above"),
85                )
86            }
87            probe @ ArrayProbe::Repeated(_) => Reader::Borrowed(RefCell::new(probe)),
88        };
89        Self {
90            reader,
91            len,
92            ctx: RefCell::new(ctx),
93            _ptype: PhantomData,
94        }
95    }
96
97    /// Reads the buffer directly when the array can offer one, and probes otherwise.
98    ///
99    /// A nullable array is excluded because the buffer holds an arbitrary value where an element
100    /// is null, and a device-backed array because its buffer is not addressable here.
101    fn reader(array: &'a ArrayRef) -> Reader<'a, T> {
102        match Self::values(array) {
103            Some(values) => Reader::Values(values),
104            None => Reader::Probe(RefCell::new(array.repeated_probe())),
105        }
106    }
107
108    /// The array's own buffer, if it is a canonical, non-nullable, host-backed array.
109    fn values(array: &ArrayRef) -> Option<&[T]> {
110        if !array.dtype().is_nullable()
111            && let Some(primitive) = array.as_opt::<Primitive>()
112            && primitive.buffer_handle().as_host_opt().is_some()
113        {
114            return primitive.data().as_slice::<T>().get(..array.len());
115        }
116        None
117    }
118
119    /// Returns the value at `idx`, or `None` if the element is null.
120    ///
121    /// The probe and the context are separate cells, so the two borrows never overlap.
122    fn typed_value(&self, idx: usize) -> VortexResult<Option<T>> {
123        let scalar = match &self.reader {
124            Reader::Values(values) => return Ok(Some(values[idx])),
125            Reader::Probe(probe) => probe
126                .borrow_mut()
127                .execute_scalar(idx, &mut self.ctx.borrow_mut())?,
128            Reader::Borrowed(probe) => probe
129                .borrow_mut()
130                .execute_scalar(idx, &mut self.ctx.borrow_mut())?,
131        };
132        Ok(scalar.as_primitive().typed_value::<T>())
133    }
134
135    /// Returns the value at `idx`, with nulls mapped to `T::zero()`.
136    fn value(&self, idx: usize) -> VortexResult<T> {
137        Ok(self.typed_value(idx)?.unwrap_or_else(|| T::zero()))
138    }
139}
140
141impl<T: NativePType> IndexOrd<T> for SearchSortedPrimitiveArray<'_, T> {
142    fn index_cmp(&self, idx: usize, elem: &T) -> VortexResult<Option<Ordering>> {
143        let value = self.value(idx)?;
144        Ok(Some(value.total_compare(*elem)))
145    }
146
147    fn index_len(&self) -> usize {
148        self.len
149    }
150}
151
152impl<T: NativePType> IndexOrd<Option<T>> for SearchSortedPrimitiveArray<'_, T> {
153    fn index_cmp(&self, idx: usize, elem: &Option<T>) -> VortexResult<Option<Ordering>> {
154        // A null element reads back as a null scalar, so one read answers both whether the
155        // element is valid and what its value is.
156        let value = self.typed_value(idx)?;
157
158        Ok(match (value, elem.as_ref()) {
159            (Some(l), Some(r)) => Some(l.total_compare(*r)),
160            (Some(_), None) => Some(Ordering::Greater),
161            (None, Some(_)) => Some(Ordering::Less),
162            (None, None) => Some(Ordering::Equal),
163        })
164    }
165
166    fn index_len(&self) -> usize {
167        self.len
168    }
169}
170
171impl<T: NativePType> IndexOrd<usize> for SearchSortedPrimitiveArray<'_, T> {
172    fn index_cmp(&self, idx: usize, elem: &usize) -> VortexResult<Option<Ordering>> {
173        let value = self.value(idx)?;
174
175        let Some(elem_t) = T::from_usize(*elem) else {
176            return Ok(Some(Ordering::Less));
177        };
178
179        Ok(Some(value.total_compare(elem_t)))
180    }
181
182    fn index_len(&self) -> usize {
183        self.len
184    }
185}
186
187#[cfg(test)]
188mod tests {
189    use std::sync::LazyLock;
190
191    use vortex_buffer::buffer;
192    use vortex_error::VortexResult;
193    use vortex_session::VortexSession;
194
195    use super::Reader;
196    use crate::IntoArray;
197    use crate::arrays::PrimitiveArray;
198    use crate::executor::VortexSessionExecute;
199    use crate::search_sorted::SearchResult;
200    use crate::search_sorted::SearchSorted;
201    use crate::search_sorted::SearchSortedPrimitiveArray;
202    use crate::search_sorted::SearchSortedSide;
203    use crate::validity::Validity;
204
205    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
206
207    #[test]
208    fn search_sorted_reads_canonical_values_directly() -> VortexResult<()> {
209        let mut ctx = SESSION.create_execution_ctx();
210        let array = PrimitiveArray::new(buffer![1i32, 2, 3, 4], Validity::NonNullable).into_array();
211        let searcher = SearchSortedPrimitiveArray::<i32>::new(&array, &mut ctx);
212        assert!(matches!(searcher.reader, Reader::Values(_)));
213        assert_eq!(
214            searcher.search_sorted(&3i32, SearchSortedSide::Left)?,
215            SearchResult::Found(2)
216        );
217        Ok(())
218    }
219
220    #[test]
221    fn search_sorted_nullable_values_respects_validity() -> VortexResult<()> {
222        let mut ctx = SESSION.create_execution_ctx();
223        let array = PrimitiveArray::new(
224            buffer![99i32, 2, 3, 4],
225            Validity::from_iter([false, true, true, true]),
226        )
227        .into_array();
228        let searcher = SearchSortedPrimitiveArray::<i32>::new(&array, &mut ctx);
229        assert_eq!(
230            searcher.search_sorted(&None::<i32>, SearchSortedSide::Left)?,
231            SearchResult::Found(0)
232        );
233        assert_eq!(
234            searcher.search_sorted(&Some(3i32), SearchSortedSide::Left)?,
235            SearchResult::Found(2)
236        );
237        Ok(())
238    }
239
240    #[test]
241    fn search_sorted_optional_value() -> VortexResult<()> {
242        let array = PrimitiveArray::new(buffer![1i32, 2, 3, 4], Validity::AllValid).into_array();
243        let mut ctx = SESSION.create_execution_ctx();
244        let res = SearchSortedPrimitiveArray::<i32>::new(&array, &mut ctx)
245            .search_sorted(&Some(3i32), SearchSortedSide::Left)?;
246        assert_eq!(res, SearchResult::Found(2));
247        Ok(())
248    }
249
250    #[test]
251    fn search_sorted_optional_value_with_nulls() -> VortexResult<()> {
252        let array =
253            PrimitiveArray::from_option_iter([None, None, Some(2i32), Some(3)]).into_array();
254        let mut ctx = SESSION.create_execution_ctx();
255        let searcher = SearchSortedPrimitiveArray::<i32>::new(&array, &mut ctx);
256        assert_eq!(
257            searcher.search_sorted(&Some(2i32), SearchSortedSide::Left)?,
258            SearchResult::Found(2)
259        );
260        assert_eq!(
261            searcher.search_sorted(&None, SearchSortedSide::Right)?,
262            SearchResult::Found(2)
263        );
264        Ok(())
265    }
266}