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
use crate::{
encoding::hybrid_rle,
error::Error,
page::{split_buffer, DataPage, PrimitivePageDict},
parquet_bridge::{Encoding, Repetition},
types::{decode, NativeType},
};
use super::utils;
pub type Casted<'a, T> = std::iter::Map<std::slice::ChunksExact<'a, u8>, fn(&'a [u8]) -> T>;
pub fn native_cast<T: NativeType>(page: &DataPage) -> Result<Casted<T>, Error> {
let (_, _, values) = split_buffer(page);
if values.len() % std::mem::size_of::<T>() != 0 {
return Err(Error::OutOfSpec(
"A primitive page data's len must be a multiple of the type".to_string(),
));
}
Ok(values
.chunks_exact(std::mem::size_of::<T>())
.map(decode::<T>))
}
#[derive(Debug)]
pub struct Dictionary<'a, T>
where
T: NativeType,
{
pub indexes: hybrid_rle::HybridRleDecoder<'a>,
pub values: &'a [T],
}
impl<'a, T> Dictionary<'a, T>
where
T: NativeType,
{
pub fn new(page: &'a DataPage, dict: &'a PrimitivePageDict<T>) -> Self {
let indexes = utils::dict_indices_decoder(page);
Self {
values: dict.values(),
indexes,
}
}
pub fn len(&self) -> usize {
self.indexes.size_hint().0
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
#[derive(Debug)]
pub enum NativePageState<'a, T>
where
T: NativeType,
{
Optional(utils::DefLevelsDecoder<'a>, Casted<'a, T>),
Required(Casted<'a, T>),
RequiredDictionary(Dictionary<'a, T>),
OptionalDictionary(utils::DefLevelsDecoder<'a>, Dictionary<'a, T>),
}
impl<'a, T: NativeType> NativePageState<'a, T> {
pub fn try_new(page: &'a DataPage) -> Result<Self, Error> {
let is_optional =
page.descriptor.primitive_type.field_info.repetition == Repetition::Optional;
match (page.encoding(), page.dictionary_page(), is_optional) {
(Encoding::PlainDictionary | Encoding::RleDictionary, Some(dict), false) => {
let dict = dict.as_any().downcast_ref().unwrap();
Ok(Self::RequiredDictionary(Dictionary::new(page, dict)))
}
(Encoding::PlainDictionary | Encoding::RleDictionary, Some(dict), true) => {
let dict = dict.as_any().downcast_ref().unwrap();
Ok(Self::OptionalDictionary(
utils::DefLevelsDecoder::new(page),
Dictionary::new(page, dict),
))
}
(Encoding::Plain, _, true) => {
let validity = utils::DefLevelsDecoder::new(page);
let values = native_cast(page)?;
Ok(Self::Optional(validity, values))
}
(Encoding::Plain, _, false) => Ok(Self::Required(native_cast(page)?)),
_ => Err(Error::General(format!(
"Viewing page for encoding {:?} for native type {} not supported",
page.encoding(),
std::any::type_name::<T>()
))),
}
}
}