/
dictionary.rs
282 lines (252 loc) · 9.04 KB
/
dictionary.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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use crate::compute::SortOptions;
use crate::row::fixed::{FixedLengthEncoding, FromSlice};
use crate::row::interner::{Interned, OrderPreservingInterner};
use crate::row::{null_sentinel, Rows};
use arrow_array::builder::*;
use arrow_array::cast::*;
use arrow_array::types::*;
use arrow_array::*;
use arrow_buffer::{ArrowNativeType, MutableBuffer, ToByteSlice};
use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::{ArrowError, DataType};
use std::collections::hash_map::Entry;
use std::collections::HashMap;
/// Computes the dictionary mapping for the given dictionary values
pub fn compute_dictionary_mapping(
interner: &mut OrderPreservingInterner,
values: &ArrayRef,
) -> Vec<Option<Interned>> {
downcast_primitive_array! {
values => interner
.intern(values.iter().map(|x| x.map(|x| x.encode()))),
DataType::Binary => {
let iter = as_generic_binary_array::<i64>(values).iter();
interner.intern(iter)
}
DataType::LargeBinary => {
let iter = as_generic_binary_array::<i64>(values).iter();
interner.intern(iter)
}
DataType::Utf8 => {
let iter = as_string_array(values).iter().map(|x| x.map(|x| x.as_bytes()));
interner.intern(iter)
}
DataType::LargeUtf8 => {
let iter = as_largestring_array(values).iter().map(|x| x.map(|x| x.as_bytes()));
interner.intern(iter)
}
_ => unreachable!(),
}
}
/// Dictionary types are encoded as
///
/// - single `0_u8` if null
/// - the bytes of the corresponding normalized key including the null terminator
pub fn encode_dictionary<K: ArrowDictionaryKeyType>(
out: &mut Rows,
column: &DictionaryArray<K>,
normalized_keys: &[Option<&[u8]>],
opts: SortOptions,
) {
for (offset, k) in out.offsets.iter_mut().skip(1).zip(column.keys()) {
match k.and_then(|k| normalized_keys[k.as_usize()]) {
Some(normalized_key) => {
let end_offset = *offset + 1 + normalized_key.len();
out.buffer[*offset] = 1;
out.buffer[*offset + 1..end_offset].copy_from_slice(normalized_key);
// Negate if descending
if opts.descending {
out.buffer[*offset..end_offset]
.iter_mut()
.for_each(|v| *v = !*v)
}
*offset = end_offset;
}
None => {
out.buffer[*offset] = null_sentinel(opts);
*offset += 1;
}
}
}
}
macro_rules! decode_primitive_helper {
($t:ty, $values: ident, $data_type:ident) => {
decode_primitive::<$t>(&$values, $data_type.clone())
};
}
/// Decodes a string array from `rows` with the provided `options`
///
/// # Safety
///
/// `interner` must contain valid data for the provided `value_type`
pub unsafe fn decode_dictionary<K: ArrowDictionaryKeyType>(
interner: &OrderPreservingInterner,
value_type: &DataType,
options: SortOptions,
rows: &mut [&[u8]],
) -> Result<DictionaryArray<K>, ArrowError> {
let len = rows.len();
let mut dictionary: HashMap<Interned, K::Native> = HashMap::with_capacity(len);
let null_sentinel = null_sentinel(options);
// If descending, the null terminator will have been negated
let null_terminator = match options.descending {
true => 0xFF,
false => 0_u8,
};
let mut null_builder = BooleanBufferBuilder::new(len);
let mut keys = BufferBuilder::<K::Native>::new(len);
let mut values = Vec::with_capacity(len);
let mut null_count = 0;
let mut key_scratch = Vec::new();
for row in rows {
if row[0] == null_sentinel {
null_builder.append(false);
null_count += 1;
*row = &row[1..];
keys.append(K::Native::default());
continue;
}
let key_offset = row
.iter()
.skip(1)
.position(|x| *x == null_terminator)
.unwrap();
// Extract the normalized key including the null terminator
let key = &row[1..key_offset + 2];
*row = &row[key_offset + 2..];
let interned = match options.descending {
true => {
// If options.descending the normalized key will have been
// negated we must first reverse this
key_scratch.clear();
key_scratch.extend_from_slice(key);
key_scratch.iter_mut().for_each(|o| *o = !*o);
interner.lookup(&key_scratch).unwrap()
}
false => interner.lookup(key).unwrap(),
};
let k = match dictionary.entry(interned) {
Entry::Vacant(v) => {
let k = values.len();
values.push(interner.value(interned));
let key = K::Native::from_usize(k)
.ok_or(ArrowError::DictionaryKeyOverflowError)?;
*v.insert(key)
}
Entry::Occupied(o) => *o.get(),
};
keys.append(k);
null_builder.append(true);
}
let child = downcast_primitive! {
value_type => (decode_primitive_helper, values, value_type),
DataType::Null => NullArray::new(values.len()).into_data(),
DataType::Boolean => decode_bool(&values),
DataType::Utf8 => decode_string::<i32>(&values),
DataType::LargeUtf8 => decode_string::<i64>(&values),
DataType::Binary => decode_binary::<i32>(&values),
DataType::LargeBinary => decode_binary::<i64>(&values),
_ => unreachable!(),
};
let data_type =
DataType::Dictionary(Box::new(K::DATA_TYPE), Box::new(value_type.clone()));
let builder = ArrayDataBuilder::new(data_type)
.len(len)
.null_bit_buffer(Some(null_builder.finish()))
.null_count(null_count)
.add_buffer(keys.finish())
.add_child_data(child);
Ok(DictionaryArray::from(builder.build_unchecked()))
}
/// Decodes a binary array from dictionary values
///
/// # Safety
///
/// Values must be valid UTF-8
fn decode_binary<O: OffsetSizeTrait>(values: &[&[u8]]) -> ArrayData {
let capacity = values.iter().map(|x| x.len()).sum();
let mut builder = GenericBinaryBuilder::<O>::with_capacity(values.len(), capacity);
for v in values {
builder.append_value(v)
}
builder.finish().into_data()
}
/// Decodes a string array from dictionary values
///
/// # Safety
///
/// Values must be valid UTF-8
unsafe fn decode_string<O: OffsetSizeTrait>(values: &[&[u8]]) -> ArrayData {
let d = match O::IS_LARGE {
true => DataType::LargeUtf8,
false => DataType::Utf8,
};
decode_binary::<O>(values)
.into_builder()
.data_type(d)
.build_unchecked()
}
/// Decodes a boolean array from dictionary values
fn decode_bool(values: &[&[u8]]) -> ArrayData {
let mut builder = BooleanBufferBuilder::new(values.len());
for value in values {
builder.append(bool::decode([value[0]]))
}
let builder = ArrayDataBuilder::new(DataType::Boolean)
.len(values.len())
.add_buffer(builder.finish());
// SAFETY: Buffers correct length
unsafe { builder.build_unchecked() }
}
/// Decodes a fixed length type array from dictionary values
///
/// # Safety
///
/// `data_type` must be appropriate native type for `T`
unsafe fn decode_fixed<T: FixedLengthEncoding + ToByteSlice>(
values: &[&[u8]],
data_type: DataType,
) -> ArrayData {
let mut buffer = MutableBuffer::new(std::mem::size_of::<T>() * values.len());
for value in values {
let value = T::Encoded::from_slice(value, false);
buffer.push(T::decode(value))
}
let builder = ArrayDataBuilder::new(data_type)
.len(values.len())
.add_buffer(buffer.into());
// SAFETY: Buffers correct length
builder.build_unchecked()
}
/// Decodes a `PrimitiveArray` from dictionary values
fn decode_primitive<T: ArrowPrimitiveType>(
values: &[&[u8]],
data_type: DataType,
) -> ArrayData
where
T::Native: FixedLengthEncoding,
{
assert_eq!(
std::mem::discriminant(&T::DATA_TYPE),
std::mem::discriminant(&data_type),
);
// SAFETY:
// Validated data type above
unsafe { decode_fixed::<T::Native>(values, data_type) }
}