vortex_array/search_sorted/
primitive.rs1use 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
20pub struct SearchSortedPrimitiveArray<'a, T> {
30 reader: Reader<'a, T>,
31 len: usize,
32 ctx: RefCell<&'a mut ExecutionCtx>,
33 _ptype: PhantomData<T>,
34}
35
36enum Reader<'a, T> {
38 Values(&'a [T]),
41 Probe(RefCell<RepeatedArrayProbe>),
43 Borrowed(RefCell<ArrayProbe<'a>>),
46}
47
48impl<'a, T: NativePType> SearchSortedPrimitiveArray<'a, T> {
49 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 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 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 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 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 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 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}