forked from apache/arrow-rs
/
converter.rs
274 lines (239 loc) · 8.44 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
// 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, Decimal128Array, FixedSizeBinaryArray, FixedSizeBinaryBuilder,
IntervalDayTimeArray, IntervalDayTimeBuilder, IntervalYearMonthArray,
IntervalYearMonthBuilder, TimestampNanosecondArray,
};
use std::sync::Arc;
use crate::errors::Result;
use std::marker::PhantomData;
#[cfg(test)]
use arrow::array::{StringArray, StringBuilder};
/// 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::with_capacity(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 }
}
}
impl Converter<Vec<Option<FixedLenByteArray>>, Decimal128Array>
for DecimalArrayConverter
{
fn convert(&self, source: Vec<Option<FixedLenByteArray>>) -> Result<Decimal128Array> {
let array = source
.into_iter()
.map(|array| array.map(|array| from_bytes_to_i128(array.data())))
.collect::<Decimal128Array>()
.with_precision_and_scale(self.precision as usize, self.scale as usize)?;
Ok(array)
}
}
impl Converter<Vec<Option<ByteArray>>, Decimal128Array> for DecimalArrayConverter {
fn convert(&self, source: Vec<Option<ByteArray>>) -> Result<Decimal128Array> {
let array = source
.into_iter()
.map(|array| array.map(|array| from_bytes_to_i128(array.data())))
.collect::<Decimal128Array>()
.with_precision_and_scale(self.precision as usize, self.scale as usize)?;
Ok(array)
}
}
// Convert the bytes array to i128.
// The endian of the input bytes array must be big-endian.
fn from_bytes_to_i128(b: &[u8]) -> i128 {
assert!(b.len() <= 16, "Decimal128Array 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;
}
// The bytes array are from parquet file and must be the big-endian.
// The endian is defined by parquet format, and the reference document
// https://github.com/apache/parquet-format/blob/54e53e5d7794d383529dd30746378f19a12afd58/src/main/thrift/parquet.thrift#L66
i128::from_be_bytes(result)
}
/// 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(),
))
}
}
#[cfg(test)]
pub struct Utf8ArrayConverter {}
#[cfg(test)]
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())
}
}
#[cfg(test)]
pub type Utf8Converter =
ArrayRefConverter<Vec<Option<ByteArray>>, StringArray, Utf8ArrayConverter>;
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 DecimalFixedLengthByteArrayConverter = ArrayRefConverter<
Vec<Option<FixedLenByteArray>>,
Decimal128Array,
DecimalArrayConverter,
>;
pub type DecimalByteArrayConvert =
ArrayRefConverter<Vec<Option<ByteArray>>, Decimal128Array, DecimalArrayConverter>;
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)
}
}