-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathmod.rs
601 lines (521 loc) · 17.4 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
use std::fmt::{Debug, Formatter};
use std::ops::Range;
use std::sync::{Arc, RwLock};
use arrow_array::builder::{BinaryViewBuilder, GenericByteViewBuilder, StringViewBuilder};
use arrow_array::types::{BinaryViewType, ByteViewType, StringViewType};
use arrow_array::{
ArrayRef as ArrowArrayRef, BinaryViewArray, GenericByteViewArray, StringViewArray,
};
use arrow_buffer::ScalarBuffer;
use static_assertions::{assert_eq_align, assert_eq_size};
use vortex_buffer::{Alignment, Buffer, ByteBuffer};
use vortex_dtype::DType;
use vortex_error::{VortexExpect, VortexResult, VortexUnwrap, vortex_bail, vortex_panic};
use vortex_mask::Mask;
use crate::array::{ArrayCanonicalImpl, ArrayValidityImpl};
use crate::arrow::FromArrowArray;
use crate::builders::ArrayBuilder;
use crate::encoding::encoding_ids;
use crate::stats::StatsSet;
use crate::validity::Validity;
use crate::vtable::VTableRef;
use crate::{
Array, ArrayImpl, ArrayRef, ArrayStatisticsImpl, Canonical, EmptyMetadata, Encoding,
EncodingId, TryFromArrayRef, try_from_array_ref,
};
mod accessor;
mod compute;
mod serde;
mod stats;
mod variants;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(C, align(8))]
pub struct Inlined {
size: u32,
data: [u8; BinaryView::MAX_INLINED_SIZE],
}
impl Inlined {
pub fn new(value: &[u8]) -> Self {
assert!(
value.len() <= BinaryView::MAX_INLINED_SIZE,
"Inlined strings must be shorter than 13 characters, {} given",
value.len()
);
let mut inlined = Self {
size: value.len().try_into().vortex_unwrap(),
data: [0u8; BinaryView::MAX_INLINED_SIZE],
};
inlined.data[..value.len()].copy_from_slice(value);
inlined
}
#[inline]
pub fn value(&self) -> &[u8] {
&self.data[0..(self.size as usize)]
}
}
#[derive(Clone, Copy, Debug)]
#[repr(C, align(8))]
pub struct Ref {
size: u32,
prefix: [u8; 4],
buffer_index: u32,
offset: u32,
}
impl Ref {
pub fn new(size: u32, prefix: [u8; 4], buffer_index: u32, offset: u32) -> Self {
Self {
size,
prefix,
buffer_index,
offset,
}
}
#[inline]
pub fn buffer_index(&self) -> u32 {
self.buffer_index
}
#[inline]
pub fn offset(&self) -> u32 {
self.offset
}
#[inline]
pub fn prefix(&self) -> &[u8; 4] {
&self.prefix
}
#[inline]
pub fn to_range(&self) -> Range<usize> {
self.offset as usize..(self.offset + self.size) as usize
}
}
#[derive(Clone, Copy)]
#[repr(C, align(16))]
pub union BinaryView {
// Numeric representation. This is logically `u128`, but we split it into the high and low
// bits to preserve the alignment.
le_bytes: [u8; 16],
// Inlined representation: strings <= 12 bytes
inlined: Inlined,
// Reference type: strings > 12 bytes.
_ref: Ref,
}
assert_eq_size!(BinaryView, [u8; 16]);
assert_eq_size!(Inlined, [u8; 16]);
assert_eq_size!(Ref, [u8; 16]);
assert_eq_align!(BinaryView, u128);
impl BinaryView {
pub const MAX_INLINED_SIZE: usize = 12;
pub fn empty_view() -> Self {
Self {
inlined: Inlined::new(&[]),
}
}
pub fn new_inlined(value: &[u8]) -> Self {
assert!(
value.len() <= Self::MAX_INLINED_SIZE,
"expected inlined value to be <= 12 bytes, was {}",
value.len()
);
Self {
inlined: Inlined::new(value),
}
}
/// Create a new view over bytes stored in a block.
pub fn new_view(len: u32, prefix: [u8; 4], block: u32, offset: u32) -> Self {
Self {
_ref: Ref::new(len, prefix, block, offset),
}
}
#[inline]
pub fn len(&self) -> u32 {
unsafe { self.inlined.size }
}
#[inline]
pub fn is_empty(&self) -> bool {
self.len() > 0
}
#[inline]
#[allow(clippy::cast_possible_truncation)]
pub fn is_inlined(&self) -> bool {
self.len() <= (Self::MAX_INLINED_SIZE as u32)
}
pub fn as_inlined(&self) -> &Inlined {
unsafe { &self.inlined }
}
pub fn as_view(&self) -> &Ref {
unsafe { &self._ref }
}
pub fn as_u128(&self) -> u128 {
// SAFETY: binary view always safe to read as u128 LE bytes
unsafe { u128::from_le_bytes(self.le_bytes) }
}
/// Shifts the buffer reference by the view by a given offset, useful when merging many
/// varbinview arrays into one.
#[inline(always)]
pub fn offset_view(self, offset: u32) -> Self {
if self.is_inlined() {
self
} else {
// Referencing views must have their buffer_index adjusted with new offsets
let view_ref = self.as_view();
BinaryView::new_view(
self.len(),
*view_ref.prefix(),
offset + view_ref.buffer_index(),
view_ref.offset(),
)
}
}
}
impl From<u128> for BinaryView {
fn from(value: u128) -> Self {
BinaryView {
le_bytes: value.to_le_bytes(),
}
}
}
impl Debug for BinaryView {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let mut s = f.debug_struct("BinaryView");
if self.is_inlined() {
s.field("inline", &"i".to_string());
} else {
s.field("ref", &"r".to_string());
}
s.finish()
}
}
#[derive(Clone, Debug)]
pub struct VarBinViewArray {
dtype: DType,
buffers: Vec<ByteBuffer>,
views: Buffer<BinaryView>,
validity: Validity,
stats_set: Arc<RwLock<StatsSet>>,
}
try_from_array_ref!(VarBinViewArray);
pub struct VarBinViewEncoding;
impl Encoding for VarBinViewEncoding {
const ID: EncodingId = EncodingId::new("vortex.varbinview", encoding_ids::VAR_BIN_VIEW);
type Array = VarBinViewArray;
type Metadata = EmptyMetadata;
}
impl VarBinViewArray {
pub fn try_new(
views: Buffer<BinaryView>,
buffers: Vec<ByteBuffer>,
dtype: DType,
validity: Validity,
) -> VortexResult<Self> {
if views.alignment() != Alignment::of::<BinaryView>() {
vortex_bail!("Views must be aligned to a 128 bits");
}
if !matches!(dtype, DType::Binary(_) | DType::Utf8(_)) {
vortex_bail!(MismatchedTypes: "utf8 or binary", dtype);
}
if dtype.is_nullable() == (validity == Validity::NonNullable) {
vortex_bail!("incorrect validity {:?}", validity);
}
Ok(Self {
dtype,
buffers,
views,
validity,
stats_set: Default::default(),
})
}
/// Number of raw string data buffers held by this array.
pub fn nbuffers(&self) -> usize {
self.buffers.len()
}
/// Access to the primitive views buffer.
///
/// Variable-sized binary view buffer contain a "view" child array, with 16-byte entries that
/// contain either a pointer into one of the array's owned `buffer`s OR an inlined copy of
/// the string (if the string has 12 bytes or fewer).
#[inline]
pub fn views(&self) -> &Buffer<BinaryView> {
&self.views
}
/// Access value bytes at a given index
///
/// Will return a bytebuffer pointing to the underlying data without performing a copy
#[inline]
pub fn bytes_at(&self, index: usize) -> ByteBuffer {
let views = self.views();
let view = &views[index];
// Expect this to be the common case: strings > 12 bytes.
if !view.is_inlined() {
let view_ref = view.as_view();
self.buffer(view_ref.buffer_index() as usize)
.slice(view_ref.to_range())
} else {
// Return access to the range of bytes around it.
views
.clone()
.into_byte_buffer()
.slice_ref(view.as_inlined().value())
}
}
/// Access one of the backing data buffers.
///
/// # Panics
///
/// This method panics if the provided index is out of bounds for the set of buffers provided
/// at construction time.
#[inline]
pub fn buffer(&self, idx: usize) -> &ByteBuffer {
if idx >= self.nbuffers() {
vortex_panic!(
"{idx} buffer index out of bounds, there are {} buffers",
self.nbuffers()
);
}
&self.buffers[idx]
}
/// Iterate over the underlying raw data buffers, not including the views buffer.
#[inline]
pub fn buffers(&self) -> &[ByteBuffer] {
&self.buffers
}
/// Validity of the array
pub fn validity(&self) -> &Validity {
&self.validity
}
/// Accumulate an iterable set of values into our type here.
#[allow(clippy::same_name_method)]
pub fn from_iter<T: AsRef<[u8]>, I: IntoIterator<Item = Option<T>>>(
iter: I,
dtype: DType,
) -> Self {
match dtype {
DType::Utf8(nullability) => {
let string_view_array = generic_byte_view_builder::<StringViewType, _, _>(
iter.into_iter(),
|builder, v| {
match v {
None => builder.append_null(),
Some(inner) => {
// SAFETY: the caller must provide valid utf8 values if Utf8 DType is passed.
let utf8 = unsafe { std::str::from_utf8_unchecked(inner.as_ref()) };
builder.append_value(utf8);
}
}
},
);
VarBinViewArray::try_from_array(ArrayRef::from_arrow(
&string_view_array,
nullability.into(),
))
.vortex_expect("StringViewArray to VarBinViewArray downcast")
}
DType::Binary(nullability) => {
let binary_view_array = generic_byte_view_builder::<BinaryViewType, _, _>(
iter.into_iter(),
GenericByteViewBuilder::append_option,
);
VarBinViewArray::try_from_array(ArrayRef::from_arrow(
&binary_view_array,
nullability.into(),
))
.vortex_expect("BinaryViewArray to VarBinViewArray downcast")
}
other => vortex_panic!("VarBinViewArray must be Utf8 or Binary, was {other}"),
}
}
pub fn from_iter_str<T: AsRef<str>, I: IntoIterator<Item = T>>(iter: I) -> Self {
let iter = iter.into_iter();
let mut builder = StringViewBuilder::with_capacity(iter.size_hint().0);
for s in iter {
builder.append_value(s);
}
let array = ArrayRef::from_arrow(&builder.finish(), false);
VarBinViewArray::try_from_array(array)
.vortex_expect("VarBinViewArray from StringViewBuilder")
}
pub fn from_iter_nullable_str<T: AsRef<str>, I: IntoIterator<Item = Option<T>>>(
iter: I,
) -> Self {
let iter = iter.into_iter();
let mut builder = StringViewBuilder::with_capacity(iter.size_hint().0);
builder.extend(iter);
let array = ArrayRef::from_arrow(&builder.finish(), true);
VarBinViewArray::try_from_array(array)
.vortex_expect("VarBinViewArray from StringViewBuilder")
}
pub fn from_iter_bin<T: AsRef<[u8]>, I: IntoIterator<Item = T>>(iter: I) -> Self {
let iter = iter.into_iter();
let mut builder = BinaryViewBuilder::with_capacity(iter.size_hint().0);
for b in iter {
builder.append_value(b);
}
let array = ArrayRef::from_arrow(&builder.finish(), false);
VarBinViewArray::try_from_array(array)
.vortex_expect("VarBinViewArray from StringViewBuilder")
}
pub fn from_iter_nullable_bin<T: AsRef<[u8]>, I: IntoIterator<Item = Option<T>>>(
iter: I,
) -> Self {
let iter = iter.into_iter();
let mut builder = BinaryViewBuilder::with_capacity(iter.size_hint().0);
builder.extend(iter);
let array = ArrayRef::from_arrow(&builder.finish(), true);
VarBinViewArray::try_from_array(array)
.vortex_expect("VarBinViewArray from StringViewBuilder")
}
}
// Generic helper to create an Arrow ByteViewBuilder of the appropriate type.
fn generic_byte_view_builder<B, V, F>(
values: impl Iterator<Item = Option<V>>,
mut append_fn: F,
) -> GenericByteViewArray<B>
where
B: ByteViewType,
V: AsRef<[u8]>,
F: FnMut(&mut GenericByteViewBuilder<B>, Option<V>),
{
let mut builder = GenericByteViewBuilder::<B>::new();
for value in values {
append_fn(&mut builder, value);
}
builder.finish()
}
impl ArrayImpl for VarBinViewArray {
type Encoding = VarBinViewEncoding;
fn _len(&self) -> usize {
self.views.len()
}
fn _dtype(&self) -> &DType {
&self.dtype
}
fn _vtable(&self) -> VTableRef {
VTableRef::new_ref(&VarBinViewEncoding)
}
}
impl ArrayStatisticsImpl for VarBinViewArray {
fn _stats_set(&self) -> &RwLock<StatsSet> {
&self.stats_set
}
}
impl ArrayCanonicalImpl for VarBinViewArray {
fn _to_canonical(&self) -> VortexResult<Canonical> {
Ok(Canonical::VarBinView(self.clone()))
}
fn _append_to_builder(&self, builder: &mut dyn ArrayBuilder) -> VortexResult<()> {
builder.extend_from_array(self)
}
}
pub(crate) fn varbinview_as_arrow(var_bin_view: &VarBinViewArray) -> ArrowArrayRef {
let views = var_bin_view.views().clone();
let nulls = var_bin_view
.validity_mask()
.vortex_expect("VarBinViewArray: failed to get logical validity")
.to_null_buffer();
let data = (0..var_bin_view.nbuffers())
.map(|i| var_bin_view.buffer(i))
.collect::<Vec<_>>();
let data = data
.into_iter()
.map(|p| p.clone().into_arrow_buffer())
.collect::<Vec<_>>();
// Switch on Arrow DType.
match var_bin_view.dtype() {
DType::Binary(_) => Arc::new(unsafe {
BinaryViewArray::new_unchecked(
ScalarBuffer::<u128>::from(views.into_byte_buffer().into_arrow_buffer()),
data,
nulls,
)
}),
DType::Utf8(_) => Arc::new(unsafe {
StringViewArray::new_unchecked(
ScalarBuffer::<u128>::from(views.into_byte_buffer().into_arrow_buffer()),
data,
nulls,
)
}),
_ => vortex_panic!("expected utf8 or binary, got {}", var_bin_view.dtype()),
}
}
impl ArrayValidityImpl for VarBinViewArray {
fn _is_valid(&self, index: usize) -> VortexResult<bool> {
self.validity.is_valid(index)
}
fn _all_valid(&self) -> VortexResult<bool> {
self.validity.all_valid()
}
fn _all_invalid(&self) -> VortexResult<bool> {
self.validity.all_invalid()
}
fn _validity_mask(&self) -> VortexResult<Mask> {
self.validity.to_logical(self.len())
}
}
impl<'a> FromIterator<Option<&'a [u8]>> for VarBinViewArray {
fn from_iter<T: IntoIterator<Item = Option<&'a [u8]>>>(iter: T) -> Self {
Self::from_iter_nullable_bin(iter)
}
}
impl FromIterator<Option<Vec<u8>>> for VarBinViewArray {
fn from_iter<T: IntoIterator<Item = Option<Vec<u8>>>>(iter: T) -> Self {
Self::from_iter_nullable_bin(iter)
}
}
impl FromIterator<Option<String>> for VarBinViewArray {
fn from_iter<T: IntoIterator<Item = Option<String>>>(iter: T) -> Self {
Self::from_iter_nullable_str(iter)
}
}
impl<'a> FromIterator<Option<&'a str>> for VarBinViewArray {
fn from_iter<T: IntoIterator<Item = Option<&'a str>>>(iter: T) -> Self {
Self::from_iter_nullable_str(iter)
}
}
#[cfg(test)]
mod test {
use vortex_scalar::Scalar;
use crate::Canonical;
use crate::array::Array;
use crate::arrays::varbinview::{BinaryView, VarBinViewArray};
use crate::compute::{scalar_at, slice};
#[test]
pub fn varbin_view() {
let binary_arr =
VarBinViewArray::from_iter_str(["hello world", "hello world this is a long string"]);
assert_eq!(binary_arr.len(), 2);
assert_eq!(
scalar_at(&binary_arr, 0).unwrap(),
Scalar::from("hello world")
);
assert_eq!(
scalar_at(&binary_arr, 1).unwrap(),
Scalar::from("hello world this is a long string")
);
}
#[test]
pub fn slice_array() {
let binary_arr = slice(
&VarBinViewArray::from_iter_str(["hello world", "hello world this is a long string"]),
1,
2,
)
.unwrap();
assert_eq!(
scalar_at(&binary_arr, 0).unwrap(),
Scalar::from("hello world this is a long string")
);
}
#[test]
pub fn flatten_array() {
let binary_arr = VarBinViewArray::from_iter_str(["string1", "string2"]);
let flattened = binary_arr.to_canonical().unwrap();
assert!(matches!(flattened, Canonical::VarBinView(_)));
let var_bin = flattened.into_varbinview().unwrap().into_array();
assert_eq!(scalar_at(&var_bin, 0).unwrap(), Scalar::from("string1"));
assert_eq!(scalar_at(&var_bin, 1).unwrap(), Scalar::from("string2"));
}
#[test]
pub fn binary_view_size_and_alignment() {
assert_eq!(size_of::<BinaryView>(), 16);
assert_eq!(align_of::<BinaryView>(), 16);
}
}