1use std::fmt::{Debug, Formatter};
2use std::ops::Range;
3use std::sync::Arc;
4
5use arrow_array::builder::{BinaryViewBuilder, GenericByteViewBuilder, StringViewBuilder};
6use arrow_array::types::{BinaryViewType, ByteViewType, StringViewType};
7use arrow_array::{
8 ArrayRef as ArrowArrayRef, BinaryViewArray, GenericByteViewArray, StringViewArray,
9};
10use arrow_buffer::ScalarBuffer;
11use static_assertions::{assert_eq_align, assert_eq_size};
12use vortex_buffer::{Alignment, Buffer, ByteBuffer};
13use vortex_dtype::DType;
14use vortex_error::{
15 VortexExpect, VortexResult, VortexUnwrap, vortex_bail, vortex_err, vortex_panic,
16};
17use vortex_mask::Mask;
18
19use crate::array::{ArrayCanonicalImpl, ArrayValidityImpl};
20use crate::arrow::FromArrowArray;
21use crate::builders::ArrayBuilder;
22use crate::stats::{ArrayStats, StatsSetRef};
23use crate::validity::Validity;
24use crate::vtable::VTableRef;
25use crate::{
26 Array, ArrayImpl, ArrayRef, ArrayStatisticsImpl, Canonical, EmptyMetadata, Encoding,
27 TryFromArrayRef, try_from_array_ref,
28};
29
30mod accessor;
31mod compute;
32mod serde;
33mod variants;
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36#[repr(C, align(8))]
37pub struct Inlined {
38 size: u32,
39 data: [u8; BinaryView::MAX_INLINED_SIZE],
40}
41
42impl Inlined {
43 fn new<const N: usize>(value: &[u8]) -> Self {
44 let mut inlined = Self {
45 size: N.try_into().vortex_unwrap(),
46 data: [0u8; BinaryView::MAX_INLINED_SIZE],
47 };
48 inlined.data[..N].copy_from_slice(&value[..N]);
49 inlined
50 }
51
52 #[inline]
53 pub fn value(&self) -> &[u8] {
54 &self.data[0..(self.size as usize)]
55 }
56}
57
58#[derive(Clone, Copy, Debug)]
59#[repr(C, align(8))]
60pub struct Ref {
61 size: u32,
62 prefix: [u8; 4],
63 buffer_index: u32,
64 offset: u32,
65}
66
67impl Ref {
68 pub fn new(size: u32, prefix: [u8; 4], buffer_index: u32, offset: u32) -> Self {
69 Self {
70 size,
71 prefix,
72 buffer_index,
73 offset,
74 }
75 }
76
77 #[inline]
78 pub fn buffer_index(&self) -> u32 {
79 self.buffer_index
80 }
81
82 #[inline]
83 pub fn offset(&self) -> u32 {
84 self.offset
85 }
86
87 #[inline]
88 pub fn prefix(&self) -> &[u8; 4] {
89 &self.prefix
90 }
91
92 #[inline]
93 pub fn to_range(&self) -> Range<usize> {
94 self.offset as usize..(self.offset + self.size) as usize
95 }
96}
97
98#[derive(Clone, Copy)]
99#[repr(C, align(16))]
100pub union BinaryView {
101 le_bytes: [u8; 16],
104
105 inlined: Inlined,
107
108 _ref: Ref,
110}
111
112assert_eq_size!(BinaryView, [u8; 16]);
113assert_eq_size!(Inlined, [u8; 16]);
114assert_eq_size!(Ref, [u8; 16]);
115assert_eq_align!(BinaryView, u128);
116
117impl BinaryView {
118 pub const MAX_INLINED_SIZE: usize = 12;
119
120 #[inline(never)]
128 pub fn make_view(value: &[u8], block: u32, offset: u32) -> Self {
129 match value.len() {
130 0 => Self {
131 inlined: Inlined::new::<0>(value),
132 },
133 1 => Self {
134 inlined: Inlined::new::<1>(value),
135 },
136 2 => Self {
137 inlined: Inlined::new::<2>(value),
138 },
139 3 => Self {
140 inlined: Inlined::new::<3>(value),
141 },
142 4 => Self {
143 inlined: Inlined::new::<4>(value),
144 },
145 5 => Self {
146 inlined: Inlined::new::<5>(value),
147 },
148 6 => Self {
149 inlined: Inlined::new::<6>(value),
150 },
151 7 => Self {
152 inlined: Inlined::new::<7>(value),
153 },
154 8 => Self {
155 inlined: Inlined::new::<8>(value),
156 },
157 9 => Self {
158 inlined: Inlined::new::<9>(value),
159 },
160 10 => Self {
161 inlined: Inlined::new::<10>(value),
162 },
163 11 => Self {
164 inlined: Inlined::new::<11>(value),
165 },
166 12 => Self {
167 inlined: Inlined::new::<12>(value),
168 },
169 _ => Self {
170 _ref: Ref::new(
171 u32::try_from(value.len()).vortex_unwrap(),
172 value[0..4].try_into().vortex_unwrap(),
173 block,
174 offset,
175 ),
176 },
177 }
178 }
179
180 #[inline]
182 pub fn empty_view() -> Self {
183 Self::new_inlined(&[])
184 }
185
186 #[inline]
188 pub fn new_inlined(value: &[u8]) -> Self {
189 assert!(
190 value.len() <= Self::MAX_INLINED_SIZE,
191 "expected inlined value to be <= 12 bytes, was {}",
192 value.len()
193 );
194
195 Self::make_view(value, 0, 0)
196 }
197
198 #[inline]
199 pub fn len(&self) -> u32 {
200 unsafe { self.inlined.size }
201 }
202
203 #[inline]
204 pub fn is_empty(&self) -> bool {
205 self.len() > 0
206 }
207
208 #[inline]
209 #[allow(clippy::cast_possible_truncation)]
210 pub fn is_inlined(&self) -> bool {
211 self.len() <= (Self::MAX_INLINED_SIZE as u32)
212 }
213
214 pub fn as_inlined(&self) -> &Inlined {
215 unsafe { &self.inlined }
216 }
217
218 pub fn as_view(&self) -> &Ref {
219 unsafe { &self._ref }
220 }
221
222 pub fn as_u128(&self) -> u128 {
223 unsafe { u128::from_le_bytes(self.le_bytes) }
225 }
226
227 #[inline(always)]
230 pub fn offset_view(self, offset: u32) -> Self {
231 if self.is_inlined() {
232 self
233 } else {
234 let view_ref = self.as_view();
236 Self {
237 _ref: Ref::new(
238 self.len(),
239 *view_ref.prefix(),
240 offset + view_ref.buffer_index(),
241 view_ref.offset(),
242 ),
243 }
244 }
245 }
246}
247
248impl From<u128> for BinaryView {
249 fn from(value: u128) -> Self {
250 BinaryView {
251 le_bytes: value.to_le_bytes(),
252 }
253 }
254}
255
256impl Debug for BinaryView {
257 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
258 let mut s = f.debug_struct("BinaryView");
259 if self.is_inlined() {
260 s.field("inline", &"i".to_string());
261 } else {
262 s.field("ref", &"r".to_string());
263 }
264 s.finish()
265 }
266}
267
268#[derive(Clone, Debug)]
269pub struct VarBinViewArray {
270 dtype: DType,
271 buffers: Vec<ByteBuffer>,
272 views: Buffer<BinaryView>,
273 validity: Validity,
274 stats_set: ArrayStats,
275}
276
277try_from_array_ref!(VarBinViewArray);
278
279pub struct VarBinViewEncoding;
280impl Encoding for VarBinViewEncoding {
281 type Array = VarBinViewArray;
282 type Metadata = EmptyMetadata;
283}
284
285impl VarBinViewArray {
286 pub fn try_new(
287 views: Buffer<BinaryView>,
288 buffers: Vec<ByteBuffer>,
289 dtype: DType,
290 validity: Validity,
291 ) -> VortexResult<Self> {
292 if views.alignment() != Alignment::of::<BinaryView>() {
293 vortex_bail!("Views must be aligned to a 128 bits");
294 }
295
296 if !matches!(dtype, DType::Binary(_) | DType::Utf8(_)) {
297 vortex_bail!(MismatchedTypes: "utf8 or binary", dtype);
298 }
299
300 if dtype.is_nullable() == (validity == Validity::NonNullable) {
301 vortex_bail!("incorrect validity {:?}", validity);
302 }
303
304 Ok(Self {
305 dtype,
306 buffers,
307 views,
308 validity,
309 stats_set: Default::default(),
310 })
311 }
312
313 pub fn nbuffers(&self) -> usize {
315 self.buffers.len()
316 }
317
318 #[inline]
324 pub fn views(&self) -> &Buffer<BinaryView> {
325 &self.views
326 }
327
328 #[inline]
332 pub fn bytes_at(&self, index: usize) -> ByteBuffer {
333 let views = self.views();
334 let view = &views[index];
335 if !view.is_inlined() {
337 let view_ref = view.as_view();
338 self.buffer(view_ref.buffer_index() as usize)
339 .slice(view_ref.to_range())
340 } else {
341 views
343 .clone()
344 .into_byte_buffer()
345 .slice_ref(view.as_inlined().value())
346 }
347 }
348
349 #[inline]
356 pub fn buffer(&self, idx: usize) -> &ByteBuffer {
357 if idx >= self.nbuffers() {
358 vortex_panic!(
359 "{idx} buffer index out of bounds, there are {} buffers",
360 self.nbuffers()
361 );
362 }
363 &self.buffers[idx]
364 }
365
366 #[inline]
368 pub fn buffers(&self) -> &[ByteBuffer] {
369 &self.buffers
370 }
371
372 pub fn validity(&self) -> &Validity {
374 &self.validity
375 }
376
377 #[allow(clippy::same_name_method)]
379 pub fn from_iter<T: AsRef<[u8]>, I: IntoIterator<Item = Option<T>>>(
380 iter: I,
381 dtype: DType,
382 ) -> Self {
383 match dtype {
384 DType::Utf8(nullability) => {
385 let string_view_array = generic_byte_view_builder::<StringViewType, _, _>(
386 iter.into_iter(),
387 |builder, v| {
388 match v {
389 None => builder.append_null(),
390 Some(inner) => {
391 let utf8 = unsafe { std::str::from_utf8_unchecked(inner.as_ref()) };
393 builder.append_value(utf8);
394 }
395 }
396 },
397 );
398 VarBinViewArray::try_from_array(ArrayRef::from_arrow(
399 &string_view_array,
400 nullability.into(),
401 ))
402 .map_err(|_| vortex_err!("Array was not a VarBinViewArray"))
403 .vortex_expect("StringViewArray to VarBinViewArray downcast")
404 }
405 DType::Binary(nullability) => {
406 let binary_view_array = generic_byte_view_builder::<BinaryViewType, _, _>(
407 iter.into_iter(),
408 GenericByteViewBuilder::append_option,
409 );
410 VarBinViewArray::try_from_array(ArrayRef::from_arrow(
411 &binary_view_array,
412 nullability.into(),
413 ))
414 .map_err(|_| vortex_err!("Array was not a VarBinViewArray"))
415 .vortex_expect("BinaryViewArray to VarBinViewArray downcast")
416 }
417 other => vortex_panic!("VarBinViewArray must be Utf8 or Binary, was {other}"),
418 }
419 }
420
421 pub fn from_iter_str<T: AsRef<str>, I: IntoIterator<Item = T>>(iter: I) -> Self {
422 let iter = iter.into_iter();
423 let mut builder = StringViewBuilder::with_capacity(iter.size_hint().0);
424 for s in iter {
425 builder.append_value(s);
426 }
427 let array = ArrayRef::from_arrow(&builder.finish(), false);
428 VarBinViewArray::try_from_array(array)
429 .map_err(|_| vortex_err!("Array was not a VarBinViewArray"))
430 .vortex_expect("VarBinViewArray from StringViewBuilder")
431 }
432
433 pub fn from_iter_nullable_str<T: AsRef<str>, I: IntoIterator<Item = Option<T>>>(
434 iter: I,
435 ) -> Self {
436 let iter = iter.into_iter();
437 let mut builder = StringViewBuilder::with_capacity(iter.size_hint().0);
438 builder.extend(iter);
439
440 let array = ArrayRef::from_arrow(&builder.finish(), true);
441 VarBinViewArray::try_from_array(array)
442 .map_err(|_| vortex_err!("Array was not a VarBinViewArray"))
443 .vortex_expect("VarBinViewArray from StringViewBuilder")
444 }
445
446 pub fn from_iter_bin<T: AsRef<[u8]>, I: IntoIterator<Item = T>>(iter: I) -> Self {
447 let iter = iter.into_iter();
448 let mut builder = BinaryViewBuilder::with_capacity(iter.size_hint().0);
449 for b in iter {
450 builder.append_value(b);
451 }
452 let array = ArrayRef::from_arrow(&builder.finish(), false);
453 VarBinViewArray::try_from_array(array)
454 .map_err(|_| vortex_err!("Array was not a VarBinViewArray"))
455 .vortex_expect("VarBinViewArray from StringViewBuilder")
456 }
457
458 pub fn from_iter_nullable_bin<T: AsRef<[u8]>, I: IntoIterator<Item = Option<T>>>(
459 iter: I,
460 ) -> Self {
461 let iter = iter.into_iter();
462 let mut builder = BinaryViewBuilder::with_capacity(iter.size_hint().0);
463 builder.extend(iter);
464 let array = ArrayRef::from_arrow(&builder.finish(), true);
465 VarBinViewArray::try_from_array(array)
466 .map_err(|_| vortex_err!("Array was not a VarBinViewArray"))
467 .vortex_expect("VarBinViewArray from StringViewBuilder")
468 }
469}
470
471fn generic_byte_view_builder<B, V, F>(
473 values: impl Iterator<Item = Option<V>>,
474 mut append_fn: F,
475) -> GenericByteViewArray<B>
476where
477 B: ByteViewType,
478 V: AsRef<[u8]>,
479 F: FnMut(&mut GenericByteViewBuilder<B>, Option<V>),
480{
481 let mut builder = GenericByteViewBuilder::<B>::new();
482
483 for value in values {
484 append_fn(&mut builder, value);
485 }
486
487 builder.finish()
488}
489
490impl ArrayImpl for VarBinViewArray {
491 type Encoding = VarBinViewEncoding;
492
493 fn _len(&self) -> usize {
494 self.views.len()
495 }
496
497 fn _dtype(&self) -> &DType {
498 &self.dtype
499 }
500
501 fn _vtable(&self) -> VTableRef {
502 VTableRef::new_ref(&VarBinViewEncoding)
503 }
504
505 fn _with_children(&self, children: &[ArrayRef]) -> VortexResult<Self> {
506 let mut this = self.clone();
507
508 if let Validity::Array(array) = &mut this.validity {
509 *array = children[0].clone();
510 }
511
512 Ok(this)
513 }
514}
515
516impl ArrayStatisticsImpl for VarBinViewArray {
517 fn _stats_ref(&self) -> StatsSetRef<'_> {
518 self.stats_set.to_ref(self)
519 }
520}
521
522impl ArrayCanonicalImpl for VarBinViewArray {
523 fn _to_canonical(&self) -> VortexResult<Canonical> {
524 Ok(Canonical::VarBinView(self.clone()))
525 }
526
527 fn _append_to_builder(&self, builder: &mut dyn ArrayBuilder) -> VortexResult<()> {
528 builder.extend_from_array(self)
529 }
530}
531
532pub(crate) fn varbinview_as_arrow(var_bin_view: &VarBinViewArray) -> ArrowArrayRef {
533 let views = var_bin_view.views().clone();
534
535 let nulls = var_bin_view
536 .validity_mask()
537 .vortex_expect("VarBinViewArray: failed to get logical validity")
538 .to_null_buffer();
539
540 let data = (0..var_bin_view.nbuffers())
541 .map(|i| var_bin_view.buffer(i))
542 .collect::<Vec<_>>();
543
544 let data = data
545 .into_iter()
546 .map(|p| p.clone().into_arrow_buffer())
547 .collect::<Vec<_>>();
548
549 match var_bin_view.dtype() {
551 DType::Binary(_) => Arc::new(unsafe {
552 BinaryViewArray::new_unchecked(
553 ScalarBuffer::<u128>::from(views.into_byte_buffer().into_arrow_buffer()),
554 data,
555 nulls,
556 )
557 }),
558 DType::Utf8(_) => Arc::new(unsafe {
559 StringViewArray::new_unchecked(
560 ScalarBuffer::<u128>::from(views.into_byte_buffer().into_arrow_buffer()),
561 data,
562 nulls,
563 )
564 }),
565 _ => vortex_panic!("expected utf8 or binary, got {}", var_bin_view.dtype()),
566 }
567}
568
569impl ArrayValidityImpl for VarBinViewArray {
570 fn _is_valid(&self, index: usize) -> VortexResult<bool> {
571 self.validity.is_valid(index)
572 }
573
574 fn _all_valid(&self) -> VortexResult<bool> {
575 self.validity.all_valid()
576 }
577
578 fn _all_invalid(&self) -> VortexResult<bool> {
579 self.validity.all_invalid()
580 }
581
582 fn _validity_mask(&self) -> VortexResult<Mask> {
583 self.validity.to_mask(self.len())
584 }
585}
586
587impl<'a> FromIterator<Option<&'a [u8]>> for VarBinViewArray {
588 fn from_iter<T: IntoIterator<Item = Option<&'a [u8]>>>(iter: T) -> Self {
589 Self::from_iter_nullable_bin(iter)
590 }
591}
592
593impl FromIterator<Option<Vec<u8>>> for VarBinViewArray {
594 fn from_iter<T: IntoIterator<Item = Option<Vec<u8>>>>(iter: T) -> Self {
595 Self::from_iter_nullable_bin(iter)
596 }
597}
598
599impl FromIterator<Option<String>> for VarBinViewArray {
600 fn from_iter<T: IntoIterator<Item = Option<String>>>(iter: T) -> Self {
601 Self::from_iter_nullable_str(iter)
602 }
603}
604
605impl<'a> FromIterator<Option<&'a str>> for VarBinViewArray {
606 fn from_iter<T: IntoIterator<Item = Option<&'a str>>>(iter: T) -> Self {
607 Self::from_iter_nullable_str(iter)
608 }
609}
610
611#[cfg(test)]
612mod test {
613 use vortex_scalar::Scalar;
614
615 use crate::Canonical;
616 use crate::array::Array;
617 use crate::arrays::varbinview::{BinaryView, VarBinViewArray};
618 use crate::compute::{scalar_at, slice};
619
620 #[test]
621 pub fn varbin_view() {
622 let binary_arr =
623 VarBinViewArray::from_iter_str(["hello world", "hello world this is a long string"]);
624 assert_eq!(binary_arr.len(), 2);
625 assert_eq!(
626 scalar_at(&binary_arr, 0).unwrap(),
627 Scalar::from("hello world")
628 );
629 assert_eq!(
630 scalar_at(&binary_arr, 1).unwrap(),
631 Scalar::from("hello world this is a long string")
632 );
633 }
634
635 #[test]
636 pub fn slice_array() {
637 let binary_arr = slice(
638 &VarBinViewArray::from_iter_str(["hello world", "hello world this is a long string"]),
639 1,
640 2,
641 )
642 .unwrap();
643 assert_eq!(
644 scalar_at(&binary_arr, 0).unwrap(),
645 Scalar::from("hello world this is a long string")
646 );
647 }
648
649 #[test]
650 pub fn flatten_array() {
651 let binary_arr = VarBinViewArray::from_iter_str(["string1", "string2"]);
652
653 let flattened = binary_arr.to_canonical().unwrap();
654 assert!(matches!(flattened, Canonical::VarBinView(_)));
655
656 let var_bin = flattened.into_varbinview().unwrap().into_array();
657 assert_eq!(scalar_at(&var_bin, 0).unwrap(), Scalar::from("string1"));
658 assert_eq!(scalar_at(&var_bin, 1).unwrap(), Scalar::from("string2"));
659 }
660
661 #[test]
662 pub fn binary_view_size_and_alignment() {
663 assert_eq!(size_of::<BinaryView>(), 16);
664 assert_eq!(align_of::<BinaryView>(), 16);
665 }
666}