1use std::fmt::Display;
5use std::fmt::Formatter;
6
7use vortex_array::ArrayRef;
8use vortex_array::ExecutionCtx;
9use vortex_array::IntoArray;
10use vortex_array::arrays::ConstantArray;
11use vortex_array::arrays::VarBinViewArray;
12use vortex_array::builders::ArrayBuilder;
13use vortex_array::builders::VarBinViewBuilder;
14use vortex_array::dtype::DType;
15use vortex_array::dtype::Nullability;
16use vortex_array::scalar::Scalar;
17use vortex_array::scalar_fn::Arity;
18use vortex_array::scalar_fn::ChildName;
19use vortex_array::scalar_fn::ExecutionArgs;
20use vortex_array::scalar_fn::ScalarFnId;
21use vortex_array::scalar_fn::ScalarFnVTable;
22use vortex_error::VortexResult;
23use vortex_error::vortex_bail;
24use vortex_error::vortex_err;
25use vortex_session::registry::CachedId;
26
27use crate::lower::is_lowercase_ascii;
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
31pub enum LowerBoundKind {
32 Min,
33 Max,
34}
35
36impl Display for LowerBoundKind {
37 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
38 match self {
39 Self::Min => write!(f, "min"),
40 Self::Max => write!(f, "max"),
41 }
42 }
43}
44
45#[derive(Clone)]
54pub struct LowerBound;
55
56impl ScalarFnVTable for LowerBound {
57 type Options = LowerBoundKind;
58
59 fn id(&self) -> ScalarFnId {
60 static ID: CachedId = CachedId::new("vortex.lower_bound");
61 *ID
62 }
63
64 fn arity(&self, _options: &Self::Options) -> Arity {
65 Arity::Exact(2)
66 }
67
68 fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
69 match child_idx {
70 0 => ChildName::from("min"),
71 1 => ChildName::from("max"),
72 _ => unreachable!("Invalid child index {child_idx} for lower_bound()"),
73 }
74 }
75
76 fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
77 let (min, max) = (&arg_dtypes[0], &arg_dtypes[1]);
78 if !min.is_utf8() || !max.is_utf8() {
79 vortex_bail!("lower_bound() requires Utf8 arguments, got {min} and {max}");
80 }
81 Ok(DType::Utf8(Nullability::Nullable))
82 }
83
84 fn execute(
85 &self,
86 kind: &Self::Options,
87 args: &dyn ExecutionArgs,
88 ctx: &mut ExecutionCtx,
89 ) -> VortexResult<ArrayRef> {
90 let dtype = DType::Utf8(Nullability::Nullable);
91 let (min, max) = (args.get(0)?, args.get(1)?);
92 if let (Some(min), Some(max)) = (min.as_constant(), max.as_constant()) {
93 let mut scratch = String::new();
94 let value = match (min.as_utf8().value(), max.as_utf8().value()) {
95 (Some(min), Some(max)) => bound(min.as_str(), max.as_str(), *kind, &mut scratch)
96 .map(|value| Scalar::utf8(value, Nullability::Nullable)),
97 _ => None,
98 };
99 let value = value.unwrap_or_else(|| Scalar::null(dtype));
100 return Ok(ConstantArray::new(value, args.row_count()).into_array());
101 }
102
103 let min = min.execute::<VarBinViewArray>(ctx)?;
104 let max = max.execute::<VarBinViewArray>(ctx)?;
105 let min_valid = min.validity()?.execute_mask(min.len(), ctx)?;
106 let max_valid = max.validity()?.execute_mask(max.len(), ctx)?;
107 let (min_views, max_views) = (min.resolved_views(), max.resolved_views());
108 let mut builder =
109 VarBinViewBuilder::with_capacity_in(dtype, min.len(), ctx.allocator().clone());
110 let mut scratch = String::new();
111 for i in 0..min.len() {
112 if !min_valid.value(i) || !max_valid.value(i) {
113 builder.append_null();
114 continue;
115 }
116 let low = std::str::from_utf8(min_views.bytes(i))
117 .map_err(|e| vortex_err!("lower_bound() min is not valid UTF-8: {e}"))?;
118 let high = std::str::from_utf8(max_views.bytes(i))
119 .map_err(|e| vortex_err!("lower_bound() max is not valid UTF-8: {e}"))?;
120 match bound(low, high, *kind, &mut scratch) {
121 Some(value) => builder.append_value(value),
122 None => builder.append_null(),
123 }
124 }
125 Ok(builder.finish_into_varbinview().into_array())
126 }
127
128 fn is_strict(&self, _options: &Self::Options) -> bool {
129 true
130 }
131
132 fn is_infallible(&self, _options: &Self::Options) -> bool {
133 true
134 }
135}
136
137fn bound<'a>(
139 low: &str,
140 high: &str,
141 kind: LowerBoundKind,
142 scratch: &'a mut String,
143) -> Option<&'a str> {
144 scratch.clear();
145 if low == high {
146 if is_lowercase_ascii(low.as_bytes()) {
147 scratch.push_str(low);
148 } else {
149 scratch.push_str(&low.to_lowercase());
150 }
151 return Some(scratch);
152 }
153
154 let common = low
155 .bytes()
156 .zip(high.bytes())
157 .take_while(|(low, high)| low == high)
158 .count();
159 let prefix = &low.as_bytes()[..common];
160 if !prefix.is_ascii() {
161 return None;
162 }
163 scratch.extend(
166 prefix
167 .iter()
168 .map(|&byte| char::from(byte.to_ascii_lowercase())),
169 );
170 match (low.as_bytes().get(common), high.as_bytes().get(common)) {
171 (Some(&low), Some(&high)) if high.is_ascii() => {
175 let lowered = (low..=high).map(|byte| byte.to_ascii_lowercase());
176 let byte = match kind {
177 LowerBoundKind::Min => lowered.min()?,
178 LowerBoundKind::Max => lowered.max()? + 1,
179 };
180 scratch.push(char::from(byte));
181 }
182 (None, Some(_)) => {
184 if kind == LowerBoundKind::Max {
185 let last = scratch.pop()?;
187 scratch.push(char::from_u32(u32::from(last) + 1)?);
188 }
189 }
190 _ => return None,
191 }
192 Some(scratch)
193}
194
195#[cfg(test)]
196mod tests {
197 use rstest::rstest;
198
199 use super::LowerBoundKind;
200 use super::bound;
201
202 #[rstest]
203 #[case::equal_ascii("ABC", "ABC", Some("abc"), Some("abc"))]
204 #[case::equal_unicode("ΟΣ", "ΟΣ", Some("ος"), Some("ος"))]
205 #[case::shared_prefix(
206 "Namespace-000",
207 "Namespace-001",
208 Some("namespace-000"),
209 Some("namespace-002")
210 )]
211 #[case::non_monotonic_range("Z", "a", Some("["), Some("{"))]
212 #[case::uppercase_range("A", "Z", Some("a"), Some("{"))]
213 #[case::descending_lowercase("K", "z", Some("["), Some("{"))]
214 #[case::prefix_of_max("prefix", "prefix-long", Some("prefix"), Some("prefiy"))]
215 #[case::empty_prefix("", "abc", Some(""), None)]
216 #[case::delete_successor("a\u{7f}", "a\u{7f}b", Some("a\u{7f}"), Some("a\u{80}"))]
217 #[case::max_ascii_byte("a\u{7e}", "a\u{7f}", Some("a\u{7e}"), Some("a\u{80}"))]
218 #[case::non_ascii_prefix("éa", "éb", None, None)]
219 #[case::non_ascii_divergence("a", "é", None, None)]
220 fn bounds(
221 #[case] low: &str,
222 #[case] high: &str,
223 #[case] min: Option<&str>,
224 #[case] max: Option<&str>,
225 ) {
226 let mut scratch = String::new();
227 assert_eq!(
228 bound(low, high, LowerBoundKind::Min, &mut scratch).map(str::to_owned),
229 min.map(str::to_owned)
230 );
231 assert_eq!(
232 bound(low, high, LowerBoundKind::Max, &mut scratch).map(str::to_owned),
233 max.map(str::to_owned)
234 );
235 }
236}