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
use crate::{
bitmap::Bitmap,
buffer::Buffer,
datatypes::{DataType, Field, UnionMode},
error::Error,
scalar::{new_scalar, Scalar},
};
use super::{new_empty_array, new_null_array, Array};
mod ffi;
pub(super) mod fmt;
mod iterator;
type UnionComponents<'a> = (&'a [Field], Option<&'a [i32]>, UnionMode);
#[derive(Clone)]
pub struct UnionArray {
types: Buffer<i8>,
map: Option<[usize; 127]>,
fields: Vec<Box<dyn Array>>,
offsets: Option<Buffer<i32>>,
data_type: DataType,
offset: usize,
}
impl UnionArray {
pub fn try_new(
data_type: DataType,
types: Buffer<i8>,
fields: Vec<Box<dyn Array>>,
offsets: Option<Buffer<i32>>,
) -> Result<Self, Error> {
let (f, ids, mode) = Self::try_get_all(&data_type)?;
if f.len() != fields.len() {
return Err(Error::oos(
"The number of `fields` must equal the number of children fields in DataType::Union",
));
};
let number_of_fields: i8 = fields
.len()
.try_into()
.map_err(|_| Error::oos("The number of `fields` cannot be larger than i8::MAX"))?;
f
.iter().map(|a| a.data_type())
.zip(fields.iter().map(|a| a.data_type()))
.enumerate()
.try_for_each(|(index, (data_type, child))| {
if data_type != child {
Err(Error::oos(format!(
"The children DataTypes of a UnionArray must equal the children data types.
However, the field {index} has data type {data_type:?} but the value has data type {child:?}"
)))
} else {
Ok(())
}
})?;
if let Some(offsets) = &offsets {
if offsets.len() != types.len() {
return Err(Error::oos(
"In a UnionArray, the offsets' length must be equal to the number of types",
));
}
}
if offsets.is_none() != mode.is_sparse() {
return Err(Error::oos(
"In a sparse UnionArray, the offsets must be set (and vice-versa)",
));
}
let map = if let Some(&ids) = ids.as_ref() {
if ids.len() != fields.len() {
return Err(Error::oos(
"In a union, when the ids are set, their length must be equal to the number of fields",
));
}
let mut hash = [0; 127];
for (pos, &id) in ids.iter().enumerate() {
if !(0..=127).contains(&id) {
return Err(Error::oos(
"In a union, when the ids are set, every id must belong to [0, 128[",
));
}
hash[id as usize] = pos;
}
types.iter().try_for_each(|&type_| {
if type_ < 0 {
return Err(Error::oos("In a union, when the ids are set, every type must be >= 0"));
}
let id = hash[type_ as usize];
if id >= fields.len() {
Err(Error::oos("In a union, when the ids are set, each id must be smaller than the number of fields."))
} else {
Ok(())
}
})?;
Some(hash)
} else {
let mut is_valid = true;
for &type_ in types.iter() {
if type_ < 0 || type_ >= number_of_fields {
is_valid = false
}
}
if !is_valid {
return Err(Error::oos(
"Every type in `types` must be larger than 0 and smaller than the number of fields.",
));
}
None
};
Ok(Self {
data_type,
map,
fields,
offsets,
types,
offset: 0,
})
}
pub fn new(
data_type: DataType,
types: Buffer<i8>,
fields: Vec<Box<dyn Array>>,
offsets: Option<Buffer<i32>>,
) -> Self {
Self::try_new(data_type, types, fields, offsets).unwrap()
}
pub fn new_null(data_type: DataType, length: usize) -> Self {
if let DataType::Union(f, _, mode) = &data_type {
let fields = f
.iter()
.map(|x| new_null_array(x.data_type().clone(), length))
.collect();
let offsets = if mode.is_sparse() {
None
} else {
Some((0..length as i32).collect::<Vec<_>>().into())
};
let types = vec![0i8; length].into();
Self::new(data_type, types, fields, offsets)
} else {
panic!("Union struct must be created with the corresponding Union DataType")
}
}
pub fn new_empty(data_type: DataType) -> Self {
if let DataType::Union(f, _, mode) = &data_type {
let fields = f
.iter()
.map(|x| new_empty_array(x.data_type().clone()))
.collect();
let offsets = if mode.is_sparse() {
None
} else {
Some(Buffer::default())
};
Self {
data_type,
map: None,
fields,
offsets,
types: Buffer::new(),
offset: 0,
}
} else {
panic!("Union struct must be created with the corresponding Union DataType")
}
}
pub fn boxed(self) -> Box<dyn Array> {
Box::new(self)
}
pub fn arced(self) -> std::sync::Arc<dyn Array> {
std::sync::Arc::new(self)
}
}
impl UnionArray {
#[inline]
pub fn slice(&self, offset: usize, length: usize) -> Self {
assert!(
offset + length <= self.len(),
"the offset of the new array cannot exceed the existing length"
);
unsafe { self.slice_unchecked(offset, length) }
}
#[inline]
pub unsafe fn slice_unchecked(&self, offset: usize, length: usize) -> Self {
debug_assert!(offset + length <= self.len());
Self {
data_type: self.data_type.clone(),
fields: self.fields.clone(),
map: self.map,
types: self.types.clone().slice_unchecked(offset, length),
offsets: self
.offsets
.clone()
.map(|offsets| offsets.slice_unchecked(offset, length)),
offset: self.offset + offset,
}
}
}
impl UnionArray {
#[inline]
pub fn len(&self) -> usize {
self.types.len()
}
pub fn offsets(&self) -> Option<&Buffer<i32>> {
self.offsets.as_ref()
}
pub fn fields(&self) -> &Vec<Box<dyn Array>> {
&self.fields
}
pub fn types(&self) -> &Buffer<i8> {
&self.types
}
#[inline]
unsafe fn field_slot_unchecked(&self, index: usize) -> usize {
self.offsets()
.as_ref()
.map(|x| *x.get_unchecked(index) as usize)
.unwrap_or(index + self.offset)
}
#[inline]
pub fn index(&self, index: usize) -> (usize, usize) {
assert!(index < self.len());
unsafe { self.index_unchecked(index) }
}
#[inline]
pub unsafe fn index_unchecked(&self, index: usize) -> (usize, usize) {
debug_assert!(index < self.len());
let type_ = unsafe { *self.types.get_unchecked(index) };
let type_ = self
.map
.as_ref()
.map(|map| unsafe { *map.get_unchecked(type_ as usize) })
.unwrap_or(type_ as usize);
let index = self.field_slot_unchecked(index);
(type_, index)
}
pub fn value(&self, index: usize) -> Box<dyn Scalar> {
assert!(index < self.len());
unsafe { self.value_unchecked(index) }
}
pub unsafe fn value_unchecked(&self, index: usize) -> Box<dyn Scalar> {
debug_assert!(index < self.len());
let (type_, index) = self.index_unchecked(index);
debug_assert!(type_ < self.fields.len());
let field = self.fields.get_unchecked(type_).as_ref();
new_scalar(field, index)
}
}
impl Array for UnionArray {
fn as_any(&self) -> &dyn std::any::Any {
self
}
#[inline]
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
self
}
fn len(&self) -> usize {
self.len()
}
fn data_type(&self) -> &DataType {
&self.data_type
}
fn validity(&self) -> Option<&Bitmap> {
None
}
fn slice(&self, offset: usize, length: usize) -> Box<dyn Array> {
Box::new(self.slice(offset, length))
}
unsafe fn slice_unchecked(&self, offset: usize, length: usize) -> Box<dyn Array> {
Box::new(self.slice_unchecked(offset, length))
}
fn with_validity(&self, _: Option<Bitmap>) -> Box<dyn Array> {
panic!("cannot set validity of a union array")
}
fn to_boxed(&self) -> Box<dyn Array> {
Box::new(self.clone())
}
}
impl UnionArray {
fn try_get_all(data_type: &DataType) -> Result<UnionComponents, Error> {
match data_type.to_logical_type() {
DataType::Union(fields, ids, mode) => {
Ok((fields, ids.as_ref().map(|x| x.as_ref()), *mode))
}
_ => Err(Error::oos(
"The UnionArray requires a logical type of DataType::Union",
)),
}
}
fn get_all(data_type: &DataType) -> (&[Field], Option<&[i32]>, UnionMode) {
Self::try_get_all(data_type).unwrap()
}
pub fn get_fields(data_type: &DataType) -> &[Field] {
Self::get_all(data_type).0
}
pub fn is_sparse(data_type: &DataType) -> bool {
Self::get_all(data_type).2.is_sparse()
}
}