1use std::fmt::Display;
5use std::fmt::Formatter;
6
7use num_traits::AsPrimitive;
8use vortex_buffer::BufferAllocatorRef;
9use vortex_buffer::ByteBuffer;
10use vortex_error::VortexExpect;
11use vortex_error::VortexResult;
12use vortex_error::vortex_bail;
13use vortex_error::vortex_ensure;
14use vortex_error::vortex_ensure_eq;
15use vortex_error::vortex_err;
16use vortex_mask::Mask;
17
18use crate::ArrayRef;
19use crate::ArraySlots;
20use crate::ExecutionCtx;
21use crate::array::Array;
22use crate::array::ArrayParts;
23use crate::array::TypedArrayRef;
24use crate::array::child_to_validity;
25use crate::array::validity_to_child;
26use crate::array_slots;
27use crate::arrays::PrimitiveArray;
28use crate::arrays::VarBin;
29use crate::arrays::varbin::builder::VarBinBuilder;
30use crate::buffer::BufferHandle;
31use crate::dtype::DType;
32use crate::dtype::IntegerPType;
33use crate::dtype::Nullability;
34use crate::dtype::OffsetBuilderPType;
35use crate::match_each_integer_ptype;
36use crate::scalar::ScalarValue;
37use crate::stats::Precision;
38use crate::stats::Stat;
39use crate::validity::Validity;
40
41fn is_char_boundary_at(bytes: &[u8], index: usize) -> bool {
43 index == bytes.len() || bytes[index] & 0b1100_0000 != 0b1000_0000
45}
46
47pub(crate) fn offsets_tile_utf8<O: AsPrimitive<usize> + PartialOrd>(
54 offsets: &[O],
55 bytes: &[u8],
56) -> bool {
57 let (Some(first), Some(last)) = (offsets.first(), offsets.last()) else {
58 return false;
59 };
60 let (first, last): (usize, usize) = (first.as_(), last.as_());
61
62 first <= last
63 && last <= bytes.len()
64 && offsets.windows(2).all(|pair| pair[0] <= pair[1])
65 && simdutf8::basic::from_utf8(&bytes[first..last]).is_ok()
66 && offsets
67 .iter()
68 .all(|&offset| is_char_boundary_at(bytes, offset.as_()))
69}
70
71#[array_slots(VarBin)]
72pub struct VarBinSlots {
73 #[slot(0)]
75 pub offsets: ArrayRef,
76 #[slot(1)]
78 pub validity_child: Option<ArrayRef>,
79}
80
81#[derive(Clone, Debug)]
82pub struct VarBinData {
83 pub(super) bytes: BufferHandle,
84}
85
86impl Display for VarBinData {
87 fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result {
88 Ok(())
89 }
90}
91
92pub struct VarBinDataParts {
93 pub dtype: DType,
94 pub bytes: BufferHandle,
95 pub offsets: ArrayRef,
96 pub validity: Validity,
97}
98
99impl VarBinData {
100 pub fn build(
107 offsets: ArrayRef,
108 bytes: ByteBuffer,
109 dtype: DType,
110 validity: Validity,
111 ctx: &mut ExecutionCtx,
112 ) -> Self {
113 Self::try_build(offsets, bytes, dtype, validity, ctx).vortex_expect("VarBinArray new")
114 }
115
116 pub fn build_from_handle(
123 offset: ArrayRef,
124 bytes: BufferHandle,
125 dtype: DType,
126 validity: Validity,
127 ctx: &mut ExecutionCtx,
128 ) -> Self {
129 Self::try_build_from_handle(offset, bytes, dtype, validity, ctx)
130 .vortex_expect("VarBinArray new")
131 }
132
133 pub(crate) fn make_slots(offsets: ArrayRef, validity: &Validity, len: usize) -> ArraySlots {
134 VarBinSlots {
135 offsets,
136 validity_child: validity_to_child(validity, len),
137 }
138 .into_slots()
139 }
140
141 pub fn try_build(
150 offsets: ArrayRef,
151 bytes: ByteBuffer,
152 dtype: DType,
153 validity: Validity,
154 ctx: &mut ExecutionCtx,
155 ) -> VortexResult<Self> {
156 let bytes = BufferHandle::new_host(bytes);
157 Self::validate(&offsets, &bytes, &dtype, &validity, ctx)?;
158
159 Ok(unsafe { Self::new_unchecked_from_handle(bytes) })
161 }
162
163 pub fn try_build_from_handle(
173 offsets: ArrayRef,
174 bytes: BufferHandle,
175 dtype: DType,
176 validity: Validity,
177 ctx: &mut ExecutionCtx,
178 ) -> VortexResult<Self> {
179 Self::validate(&offsets, &bytes, &dtype, &validity, ctx)?;
180
181 Ok(unsafe { Self::new_unchecked_from_handle(bytes) })
183 }
184
185 pub unsafe fn new_unchecked(bytes: ByteBuffer) -> Self {
214 unsafe { Self::new_unchecked_from_handle(BufferHandle::new_host(bytes)) }
217 }
218
219 pub unsafe fn new_unchecked_from_handle(bytes: BufferHandle) -> Self {
226 Self { bytes }
227 }
228
229 pub fn validate(
233 offsets: &ArrayRef,
234 bytes: &BufferHandle,
235 dtype: &DType,
236 validity: &Validity,
237 ctx: &mut ExecutionCtx,
238 ) -> VortexResult<()> {
239 vortex_ensure!(
241 offsets.dtype().is_int() && !offsets.dtype().is_nullable(),
242 "expected type: non nullable int but instead got {}",
243 offsets.dtype()
244 );
245
246 vortex_ensure!(
248 matches!(dtype, DType::Binary(_) | DType::Utf8(_)),
249 "expected type: utf8 or binary but instead got {}",
250 dtype
251 );
252
253 vortex_ensure!(
255 dtype.is_nullable() != matches!(validity, Validity::NonNullable),
256 "incorrect validity {:?} for dtype {}",
257 validity,
258 dtype
259 );
260
261 vortex_ensure!(
263 !offsets.is_empty(),
264 "Offsets must have at least one element"
265 );
266
267 if let Some(validity_len) = validity.maybe_len() {
269 vortex_ensure_eq!(
270 validity_len,
271 offsets.len() - 1,
272 "Validity length doesn't match array length",
273 );
274 }
275
276 if offsets.is_host()
279 && bytes.is_on_host()
280 && matches!(dtype, DType::Utf8(_))
281 && let Some(bytes) = bytes.as_host_opt()
282 {
283 Self::validate_utf8(offsets, bytes.as_ref(), validity, ctx)?;
284 } else if offsets.is_host() {
285 Self::validate_offsets(offsets, bytes.len(), ctx)?;
286 }
287
288 Ok(())
289 }
290
291 fn validate_offsets(
293 offsets: &ArrayRef,
294 bytes_len: usize,
295 ctx: &mut ExecutionCtx,
296 ) -> VortexResult<()> {
297 let primitive_offsets = offsets.clone().execute::<PrimitiveArray>(ctx)?;
300
301 match_each_integer_ptype!(primitive_offsets.dtype().as_ptype(), |P| {
302 Self::validate_offset_slice(offsets, primitive_offsets.as_slice::<P>(), bytes_len)
303 })
304 }
305
306 fn validate_offset_slice<P>(
307 offsets: &ArrayRef,
308 offsets_slice: &[P],
309 bytes_len: usize,
310 ) -> VortexResult<()>
311 where
312 P: IntegerPType + TryFrom<usize> + Into<ScalarValue>,
313 {
314 if let Some(idx) = offsets_slice.windows(2).position(|w| w[0] > w[1]) {
316 vortex_bail!(
317 "offsets must be sorted, but offset {} at index {idx} is greater than \
318 offset {} at index {}",
319 offsets_slice[idx],
320 offsets_slice[idx + 1],
321 idx + 1
322 );
323 }
324
325 if let (Some(&min), Some(&max)) = (offsets_slice.first(), offsets_slice.last()) {
328 vortex_ensure!(
329 min >= P::zero(),
330 "offsets minimum {min} outside valid range [0, {max}]"
331 );
332
333 vortex_ensure!(
335 P::try_from(bytes_len).ok().is_none_or(|len| max <= len),
336 "Max offset {max} is beyond the length of the bytes buffer {bytes_len}"
337 );
338
339 let stats = offsets.statistics();
342 stats.set(Stat::IsSorted, Precision::exact(true));
343 stats.set(Stat::Min, Precision::exact(min));
344 stats.set(Stat::Max, Precision::exact(max));
345 }
346
347 Ok(())
348 }
349
350 fn validate_utf8(
352 offsets: &ArrayRef,
353 bytes: &[u8],
354 validity: &Validity,
355 ctx: &mut ExecutionCtx,
356 ) -> VortexResult<()> {
357 let primitive_offsets = offsets.clone().execute::<PrimitiveArray>(ctx)?;
359
360 let mask = match validity {
364 Validity::Array(_) => {
365 Some(validity.execute_mask(primitive_offsets.len().saturating_sub(1), ctx)?)
366 }
367 _ => None,
368 };
369 let all_invalid = validity.definitely_all_null();
370
371 match_each_integer_ptype!(primitive_offsets.dtype().as_ptype(), |O| {
372 Self::validate_utf8_offsets(
373 offsets,
374 primitive_offsets.as_slice::<O>(),
375 bytes,
376 mask.as_ref(),
377 all_invalid,
378 )
379 })
380 }
381
382 fn validate_utf8_offsets<
383 O: IntegerPType + AsPrimitive<usize> + TryFrom<usize> + Into<ScalarValue>,
384 >(
385 offsets: &ArrayRef,
386 offsets_slice: &[O],
387 bytes: &[u8],
388 mask: Option<&Mask>,
389 all_invalid: bool,
390 ) -> VortexResult<()> {
391 let last_offset: usize = offsets_slice[offsets_slice.len() - 1].as_();
392 vortex_ensure!(
393 last_offset <= bytes.len(),
394 "Last offset {} exceeds bytes length {}",
395 last_offset,
396 bytes.len()
397 );
398
399 if offsets_tile_utf8(offsets_slice, bytes) {
400 let stats = offsets.statistics();
403 stats.set(Stat::IsSorted, Precision::exact(true));
404 stats.set(Stat::Min, Precision::exact(offsets_slice[0]));
405 stats.set(
406 Stat::Max,
407 Precision::exact(offsets_slice[offsets_slice.len() - 1]),
408 );
409
410 return Ok(());
411 }
412
413 Self::validate_offset_slice(offsets, offsets_slice, bytes.len())?;
416
417 let validate_at = |i: usize, start: usize, end: usize| -> VortexResult<()> {
418 let string_bytes = bytes.get(start..end).ok_or_else(|| {
419 vortex_err!(
420 "offsets {start}..{end} at index {i} are out of order or out of bounds for bytes of length {}",
421 bytes.len()
422 )
423 })?;
424 simdutf8::basic::from_utf8(string_bytes).map_err(|_| {
425 #[expect(clippy::unwrap_used)]
426 let err = simdutf8::compat::from_utf8(string_bytes).unwrap_err();
428 vortex_err!("invalid utf-8: {err} at index {i}")
429 })?;
430 Ok(())
431 };
432
433 for (i, (start, end)) in offsets_slice
435 .windows(2)
436 .map(|o| (o[0].as_(), o[1].as_()))
437 .enumerate()
438 {
439 let valid = mask.map_or(!all_invalid, |mask| mask.value(i));
440 if valid {
441 validate_at(i, start, end)?;
442 }
443 }
444 Ok(())
445 }
446
447 #[inline]
455 pub fn bytes(&self) -> &ByteBuffer {
456 self.bytes.as_host()
457 }
458
459 #[inline]
461 pub fn bytes_handle(&self) -> &BufferHandle {
462 &self.bytes
463 }
464}
465
466pub trait VarBinArrayExt: TypedArrayRef<VarBin> {
467 fn dtype_parts(&self) -> (bool, Nullability) {
468 match self.dtype() {
469 DType::Utf8(nullability) => (true, *nullability),
470 DType::Binary(nullability) => (false, *nullability),
471 _ => unreachable!("VarBinArrayExt requires a utf8 or binary dtype"),
472 }
473 }
474
475 fn is_utf8(&self) -> bool {
476 self.dtype_parts().0
477 }
478
479 fn nullability(&self) -> Nullability {
480 self.dtype_parts().1
481 }
482
483 fn varbin_validity(&self) -> Validity {
484 child_to_validity(self.validity_child(), self.nullability())
485 }
486
487 fn offset_at(&self, index: usize, ctx: &mut ExecutionCtx) -> usize {
488 assert!(
489 index <= self.len(),
490 "Index {index} out of bounds 0..={}",
491 self.len()
492 );
493
494 (&self
495 .offsets()
496 .execute_scalar(index, ctx)
497 .vortex_expect("offsets must support execute_scalar"))
498 .try_into()
499 .vortex_expect("Failed to convert offset to usize")
500 }
501
502 fn bytes_at(&self, index: usize, ctx: &mut ExecutionCtx) -> ByteBuffer {
503 let start = self.offset_at(index, ctx);
504 let end = self.offset_at(index + 1, ctx);
505 self.bytes().slice(start..end)
506 }
507
508 fn sliced_bytes(&self, ctx: &mut ExecutionCtx) -> ByteBuffer {
509 let first_offset: usize = self.offset_at(0, ctx);
510 let last_offset = self.offset_at(self.len(), ctx);
511 self.bytes().slice(first_offset..last_offset)
512 }
513}
514impl<T: TypedArrayRef<VarBin>> VarBinArrayExt for T {}
515
516impl Array<VarBin> {
518 pub fn from_vec<T: AsRef<[u8]>>(vec: Vec<T>, dtype: DType) -> Self {
519 let size: usize = vec.iter().map(|v| v.as_ref().len()).sum();
520 if size < u32::MAX as usize {
521 Self::from_vec_sized::<u32, T>(vec, dtype)
522 } else {
523 Self::from_vec_sized::<u64, T>(vec, dtype)
524 }
525 }
526
527 #[expect(
528 clippy::same_name_method,
529 reason = "intentionally named from_iter like Iterator::from_iter"
530 )]
531 pub fn from_iter<T: AsRef<[u8]>, I: IntoIterator<Item = Option<T>>>(
532 iter: I,
533 dtype: DType,
534 ) -> Self {
535 let iter = iter.into_iter();
536 let mut builder = VarBinBuilder::<u32>::with_capacity_in(
537 dtype,
538 iter.size_hint().0,
539 BufferAllocatorRef::static_ref(),
540 );
541 for v in iter {
542 builder.append(v.as_ref().map(|o| o.as_ref()));
543 }
544 builder.finish_into_varbin()
545 }
546
547 pub fn from_iter_nonnull<T: AsRef<[u8]>, I: IntoIterator<Item = T>>(
548 iter: I,
549 dtype: DType,
550 ) -> Self {
551 let iter = iter.into_iter();
552 let mut builder = VarBinBuilder::<u32>::with_capacity_in(
553 dtype,
554 iter.size_hint().0,
555 BufferAllocatorRef::static_ref(),
556 );
557 for v in iter {
558 builder.append_value(v);
559 }
560 builder.finish_into_varbin()
561 }
562
563 fn from_vec_sized<O, T>(vec: Vec<T>, dtype: DType) -> Self
564 where
565 O: OffsetBuilderPType,
566 T: AsRef<[u8]>,
567 {
568 let mut builder = VarBinBuilder::<O>::with_capacity_in(
569 dtype,
570 vec.len(),
571 BufferAllocatorRef::static_ref(),
572 );
573 for v in vec {
574 builder.append_value(v.as_ref());
575 }
576 builder.finish_into_varbin()
577 }
578
579 pub fn from_strs(value: Vec<&str>) -> Self {
581 Self::from_vec(value, DType::Utf8(Nullability::NonNullable))
582 }
583
584 pub fn from_nullable_strs(value: Vec<Option<&str>>) -> Self {
586 Self::from_iter(value, DType::Utf8(Nullability::Nullable))
587 }
588
589 pub fn from_bytes(value: Vec<&[u8]>) -> Self {
591 Self::from_vec(value, DType::Binary(Nullability::NonNullable))
592 }
593
594 pub fn from_nullable_bytes(value: Vec<Option<&[u8]>>) -> Self {
596 Self::from_iter(value, DType::Binary(Nullability::Nullable))
597 }
598
599 pub fn into_data_parts(self) -> VarBinDataParts {
600 let dtype = self.dtype().clone();
601 let validity = self.varbin_validity();
602 let offsets = self.offsets().clone();
603 let data = self.into_data();
604 VarBinDataParts {
605 dtype,
606 bytes: data.bytes,
607 offsets,
608 validity,
609 }
610 }
611}
612
613impl Array<VarBin> {
614 pub fn new(
616 offsets: ArrayRef,
617 bytes: ByteBuffer,
618 dtype: DType,
619 validity: Validity,
620 ctx: &mut ExecutionCtx,
621 ) -> Self {
622 let len = offsets.len().saturating_sub(1);
623 let slots = VarBinData::make_slots(offsets, &validity, len);
624 let data = VarBinData::build(
625 slots[VarBinSlots::OFFSETS]
626 .as_ref()
627 .vortex_expect("VarBinArray offsets slot")
628 .clone(),
629 bytes,
630 dtype.clone(),
631 validity,
632 ctx,
633 );
634 unsafe { Array::from_parts_unchecked(ArrayParts::new(VarBin, dtype, len, data, slots)) }
635 }
636
637 pub unsafe fn new_unchecked(
643 offsets: ArrayRef,
644 bytes: ByteBuffer,
645 dtype: DType,
646 validity: Validity,
647 ) -> Self {
648 let len = offsets.len().saturating_sub(1);
649 let slots = VarBinData::make_slots(offsets, &validity, len);
650 let data = unsafe { VarBinData::new_unchecked(bytes) };
651 unsafe { Array::from_parts_unchecked(ArrayParts::new(VarBin, dtype, len, data, slots)) }
652 }
653
654 pub unsafe fn new_unchecked_from_handle(
660 offsets: ArrayRef,
661 bytes: BufferHandle,
662 dtype: DType,
663 validity: Validity,
664 ) -> Self {
665 let len = offsets.len().saturating_sub(1);
666 let slots = VarBinData::make_slots(offsets, &validity, len);
667 let data = unsafe { VarBinData::new_unchecked_from_handle(bytes) };
668 unsafe { Array::from_parts_unchecked(ArrayParts::new(VarBin, dtype, len, data, slots)) }
669 }
670
671 pub fn try_new(
674 offsets: ArrayRef,
675 bytes: ByteBuffer,
676 dtype: DType,
677 validity: Validity,
678 ctx: &mut ExecutionCtx,
679 ) -> VortexResult<Self> {
680 let len = offsets.len() - 1;
681 let bytes = BufferHandle::new_host(bytes);
682 VarBinData::validate(&offsets, &bytes, &dtype, &validity, ctx)?;
683 let slots = VarBinData::make_slots(offsets, &validity, len);
684 let data = unsafe { VarBinData::new_unchecked_from_handle(bytes) };
686 Ok(
687 unsafe {
688 Array::from_parts_unchecked(ArrayParts::new(VarBin, dtype, len, data, slots))
689 },
690 )
691 }
692}
693
694impl From<Vec<&[u8]>> for Array<VarBin> {
695 fn from(value: Vec<&[u8]>) -> Self {
696 Self::from_vec(value, DType::Binary(Nullability::NonNullable))
697 }
698}
699
700impl From<Vec<Vec<u8>>> for Array<VarBin> {
701 fn from(value: Vec<Vec<u8>>) -> Self {
702 Self::from_vec(value, DType::Binary(Nullability::NonNullable))
703 }
704}
705
706impl From<Vec<String>> for Array<VarBin> {
707 fn from(value: Vec<String>) -> Self {
708 Self::from_vec(value, DType::Utf8(Nullability::NonNullable))
709 }
710}
711
712impl From<Vec<&str>> for Array<VarBin> {
713 fn from(value: Vec<&str>) -> Self {
714 Self::from_vec(value, DType::Utf8(Nullability::NonNullable))
715 }
716}
717
718impl From<Vec<Option<&[u8]>>> for Array<VarBin> {
719 fn from(value: Vec<Option<&[u8]>>) -> Self {
720 Self::from_iter(value, DType::Binary(Nullability::Nullable))
721 }
722}
723
724impl From<Vec<Option<Vec<u8>>>> for Array<VarBin> {
725 fn from(value: Vec<Option<Vec<u8>>>) -> Self {
726 Self::from_iter(value, DType::Binary(Nullability::Nullable))
727 }
728}
729
730impl From<Vec<Option<String>>> for Array<VarBin> {
731 fn from(value: Vec<Option<String>>) -> Self {
732 Self::from_iter(value, DType::Utf8(Nullability::Nullable))
733 }
734}
735
736impl From<Vec<Option<&str>>> for Array<VarBin> {
737 fn from(value: Vec<Option<&str>>) -> Self {
738 Self::from_iter(value, DType::Utf8(Nullability::Nullable))
739 }
740}
741
742impl<'a> FromIterator<Option<&'a [u8]>> for Array<VarBin> {
743 fn from_iter<T: IntoIterator<Item = Option<&'a [u8]>>>(iter: T) -> Self {
744 Self::from_iter(iter, DType::Binary(Nullability::Nullable))
745 }
746}
747
748impl FromIterator<Option<Vec<u8>>> for Array<VarBin> {
749 fn from_iter<T: IntoIterator<Item = Option<Vec<u8>>>>(iter: T) -> Self {
750 Self::from_iter(iter, DType::Binary(Nullability::Nullable))
751 }
752}
753
754impl FromIterator<Option<String>> for Array<VarBin> {
755 fn from_iter<T: IntoIterator<Item = Option<String>>>(iter: T) -> Self {
756 Self::from_iter(iter, DType::Utf8(Nullability::Nullable))
757 }
758}
759
760impl<'a> FromIterator<Option<&'a str>> for Array<VarBin> {
761 fn from_iter<T: IntoIterator<Item = Option<&'a str>>>(iter: T) -> Self {
762 Self::from_iter(iter, DType::Utf8(Nullability::Nullable))
763 }
764}