/
converter.rs
335 lines (292 loc) · 9.96 KB
/
converter.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
// 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::data_type::{ByteArray, FixedLenByteArray, Int96};
use arrow::array::{
Array, ArrayRef, BinaryArray, BinaryBuilder, DecimalArray, FixedSizeBinaryArray,
FixedSizeBinaryBuilder, IntervalDayTimeArray, IntervalDayTimeBuilder,
IntervalYearMonthArray, IntervalYearMonthBuilder, LargeBinaryArray,
LargeBinaryBuilder, LargeStringArray, LargeStringBuilder, StringArray, StringBuilder,
TimestampNanosecondArray,
};
use std::convert::{From, TryInto};
use std::sync::Arc;
use crate::errors::Result;
use std::marker::PhantomData;
/// A converter is used to consume record reader's content and convert it to arrow
/// primitive array.
pub trait Converter<S, T> {
/// This method converts record reader's buffered content into arrow array.
/// It will consume record reader's data, but will not reset record reader's
/// state.
fn convert(&self, source: S) -> Result<T>;
}
pub struct FixedSizeArrayConverter {
byte_width: i32,
}
impl FixedSizeArrayConverter {
pub fn new(byte_width: i32) -> Self {
Self { byte_width }
}
}
impl Converter<Vec<Option<FixedLenByteArray>>, FixedSizeBinaryArray>
for FixedSizeArrayConverter
{
fn convert(
&self,
source: Vec<Option<FixedLenByteArray>>,
) -> Result<FixedSizeBinaryArray> {
let mut builder = FixedSizeBinaryBuilder::new(source.len(), self.byte_width);
for v in source {
match v {
Some(array) => builder.append_value(array.data()),
None => builder.append_null(),
}?
}
Ok(builder.finish())
}
}
pub struct DecimalArrayConverter {
precision: i32,
scale: i32,
}
impl DecimalArrayConverter {
pub fn new(precision: i32, scale: i32) -> Self {
Self { precision, scale }
}
fn from_bytes_to_i128(b: &[u8]) -> i128 {
assert!(b.len() <= 16, "DecimalArray supports only up to size 16");
let first_bit = b[0] & 128u8 == 128u8;
let mut result = if first_bit { [255u8; 16] } else { [0u8; 16] };
for (i, v) in b.iter().enumerate() {
result[i + (16 - b.len())] = *v;
}
i128::from_be_bytes(result)
}
}
impl Converter<Vec<Option<FixedLenByteArray>>, DecimalArray> for DecimalArrayConverter {
fn convert(&self, source: Vec<Option<FixedLenByteArray>>) -> Result<DecimalArray> {
let array = source
.into_iter()
.map(|array| array.map(|array| Self::from_bytes_to_i128(array.data())))
.collect::<DecimalArray>()
.with_precision_and_scale(self.precision as usize, self.scale as usize)?;
Ok(array)
}
}
/// An Arrow Interval converter, which reads the first 4 bytes of a Parquet interval,
/// and interprets it as an i32 value representing the Arrow YearMonth value
pub struct IntervalYearMonthArrayConverter {}
impl Converter<Vec<Option<FixedLenByteArray>>, IntervalYearMonthArray>
for IntervalYearMonthArrayConverter
{
fn convert(
&self,
source: Vec<Option<FixedLenByteArray>>,
) -> Result<IntervalYearMonthArray> {
let mut builder = IntervalYearMonthBuilder::new(source.len());
for v in source {
match v {
Some(array) => builder.append_value(i32::from_le_bytes(
array.data()[0..4].try_into().unwrap(),
)),
None => builder.append_null(),
}?
}
Ok(builder.finish())
}
}
/// An Arrow Interval converter, which reads the last 8 bytes of a Parquet interval,
/// and interprets it as an i32 value representing the Arrow DayTime value
pub struct IntervalDayTimeArrayConverter {}
impl Converter<Vec<Option<FixedLenByteArray>>, IntervalDayTimeArray>
for IntervalDayTimeArrayConverter
{
fn convert(
&self,
source: Vec<Option<FixedLenByteArray>>,
) -> Result<IntervalDayTimeArray> {
let mut builder = IntervalDayTimeBuilder::new(source.len());
for v in source {
match v {
Some(array) => builder.append_value(i64::from_le_bytes(
array.data()[4..12].try_into().unwrap(),
)),
None => builder.append_null(),
}?
}
Ok(builder.finish())
}
}
pub struct Int96ArrayConverter {
pub timezone: Option<String>,
}
impl Converter<Vec<Option<Int96>>, TimestampNanosecondArray> for Int96ArrayConverter {
fn convert(&self, source: Vec<Option<Int96>>) -> Result<TimestampNanosecondArray> {
Ok(TimestampNanosecondArray::from_opt_vec(
source
.into_iter()
.map(|int96| int96.map(|val| val.to_i64() * 1_000_000))
.collect(),
self.timezone.clone(),
))
}
}
pub struct Utf8ArrayConverter {}
impl Converter<Vec<Option<ByteArray>>, StringArray> for Utf8ArrayConverter {
fn convert(&self, source: Vec<Option<ByteArray>>) -> Result<StringArray> {
let data_size = source
.iter()
.map(|x| x.as_ref().map(|b| b.len()).unwrap_or(0))
.sum();
let mut builder = StringBuilder::with_capacity(source.len(), data_size);
for v in source {
match v {
Some(array) => builder.append_value(array.as_utf8()?),
None => builder.append_null(),
}?
}
Ok(builder.finish())
}
}
pub struct LargeUtf8ArrayConverter {}
impl Converter<Vec<Option<ByteArray>>, LargeStringArray> for LargeUtf8ArrayConverter {
fn convert(&self, source: Vec<Option<ByteArray>>) -> Result<LargeStringArray> {
let data_size = source
.iter()
.map(|x| x.as_ref().map(|b| b.len()).unwrap_or(0))
.sum();
let mut builder = LargeStringBuilder::with_capacity(source.len(), data_size);
for v in source {
match v {
Some(array) => builder.append_value(array.as_utf8()?),
None => builder.append_null(),
}?
}
Ok(builder.finish())
}
}
pub struct BinaryArrayConverter {}
impl Converter<Vec<Option<ByteArray>>, BinaryArray> for BinaryArrayConverter {
fn convert(&self, source: Vec<Option<ByteArray>>) -> Result<BinaryArray> {
let mut builder = BinaryBuilder::new(source.len());
for v in source {
match v {
Some(array) => builder.append_value(array.data()),
None => builder.append_null(),
}?
}
Ok(builder.finish())
}
}
pub struct LargeBinaryArrayConverter {}
impl Converter<Vec<Option<ByteArray>>, LargeBinaryArray> for LargeBinaryArrayConverter {
fn convert(&self, source: Vec<Option<ByteArray>>) -> Result<LargeBinaryArray> {
let mut builder = LargeBinaryBuilder::new(source.len());
for v in source {
match v {
Some(array) => builder.append_value(array.data()),
None => builder.append_null(),
}?
}
Ok(builder.finish())
}
}
pub type Utf8Converter =
ArrayRefConverter<Vec<Option<ByteArray>>, StringArray, Utf8ArrayConverter>;
pub type LargeUtf8Converter =
ArrayRefConverter<Vec<Option<ByteArray>>, LargeStringArray, LargeUtf8ArrayConverter>;
pub type BinaryConverter =
ArrayRefConverter<Vec<Option<ByteArray>>, BinaryArray, BinaryArrayConverter>;
pub type LargeBinaryConverter = ArrayRefConverter<
Vec<Option<ByteArray>>,
LargeBinaryArray,
LargeBinaryArrayConverter,
>;
pub type Int96Converter =
ArrayRefConverter<Vec<Option<Int96>>, TimestampNanosecondArray, Int96ArrayConverter>;
pub type FixedLenBinaryConverter = ArrayRefConverter<
Vec<Option<FixedLenByteArray>>,
FixedSizeBinaryArray,
FixedSizeArrayConverter,
>;
pub type IntervalYearMonthConverter = ArrayRefConverter<
Vec<Option<FixedLenByteArray>>,
IntervalYearMonthArray,
IntervalYearMonthArrayConverter,
>;
pub type IntervalDayTimeConverter = ArrayRefConverter<
Vec<Option<FixedLenByteArray>>,
IntervalDayTimeArray,
IntervalDayTimeArrayConverter,
>;
pub type DecimalConverter = ArrayRefConverter<
Vec<Option<FixedLenByteArray>>,
DecimalArray,
DecimalArrayConverter,
>;
pub struct FromConverter<S, T> {
_source: PhantomData<S>,
_dest: PhantomData<T>,
}
impl<S, T> FromConverter<S, T>
where
T: From<S>,
{
pub fn new() -> Self {
Self {
_source: PhantomData,
_dest: PhantomData,
}
}
}
impl<S, T> Converter<S, T> for FromConverter<S, T>
where
T: From<S>,
{
fn convert(&self, source: S) -> Result<T> {
Ok(T::from(source))
}
}
pub struct ArrayRefConverter<S, A, C> {
_source: PhantomData<S>,
_array: PhantomData<A>,
converter: C,
}
impl<S, A, C> ArrayRefConverter<S, A, C>
where
A: Array + 'static,
C: Converter<S, A> + 'static,
{
pub fn new(converter: C) -> Self {
Self {
_source: PhantomData,
_array: PhantomData,
converter,
}
}
}
impl<S, A, C> Converter<S, ArrayRef> for ArrayRefConverter<S, A, C>
where
A: Array + 'static,
C: Converter<S, A> + 'static,
{
fn convert(&self, source: S) -> Result<ArrayRef> {
self.converter
.convert(source)
.map(|array| Arc::new(array) as ArrayRef)
}
}