parquet 58.1.0

Apache Parquet implementation in Rust
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
// 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.

// These macros are adapted from Jörn Horstmann's thrift macros at
// https://github.com/jhorstmann/compact-thrift
// They allow for pasting sections of the Parquet thrift IDL file
// into a macro to generate rust structures and implementations.

//! This is a collection of macros used to parse Thrift IDL descriptions of structs,
//! unions, and enums into their corresponding Rust types. These macros will also
//! generate the code necessary to serialize and deserialize to/from the [Thrift compact]
//! protocol.
//!
//! Further details of how to use them (and other aspects of the Thrift serialization process)
//! can be found in [THRIFT.md].
//!
//! [Thrift compact]: https://github.com/apache/thrift/blob/master/doc/specs/thrift-compact-protocol.md#list-and-set
//! [THRIFT.md]: https://github.com/apache/arrow-rs/blob/main/parquet/THRIFT.md

#[doc(hidden)]
#[macro_export]
#[allow(clippy::crate_in_macro_def)]
/// Macro used to generate rust enums from a Thrift `enum` definition.
///
/// Note:
///  - All enums generated with this macro will have `pub` visibility.
///  - When utilizing this macro the Thrift serialization traits and structs need to be in scope.
macro_rules! thrift_enum {
    ($(#[$($def_attrs:tt)*])* enum $identifier:ident { $($(#[$($field_attrs:tt)*])* $field_name:ident = $field_value:literal;)* }) => {
        $(#[$($def_attrs)*])*
        #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
        #[allow(non_camel_case_types)]
        #[allow(missing_docs)]
        pub enum $identifier {
            $($(#[cfg_attr(not(doctest), $($field_attrs)*)])* $field_name = $field_value,)*
        }

        impl<'a, R: ThriftCompactInputProtocol<'a>> ReadThrift<'a, R> for $identifier {
            #[allow(deprecated)]
            fn read_thrift(prot: &mut R) -> Result<Self> {
                let val = prot.read_i32()?;
                match val {
                    $($field_value => Ok(Self::$field_name),)*
                    _ => Err(general_err!("Unexpected {} {}", stringify!($identifier), val)),
                }
            }
        }

        impl fmt::Display for $identifier {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, "{self:?}")
            }
        }

        impl WriteThrift for $identifier {
            const ELEMENT_TYPE: ElementType = ElementType::I32;

            fn write_thrift<W: Write>(&self, writer: &mut ThriftCompactOutputProtocol<W>) -> Result<()> {
                writer.write_i32(*self as i32)
            }
        }

        impl WriteThriftField for $identifier {
            fn write_thrift_field<W: Write>(&self, writer: &mut ThriftCompactOutputProtocol<W>, field_id: i16, last_field_id: i16) -> Result<i16> {
                writer.write_field_begin(FieldType::I32, field_id, last_field_id)?;
                self.write_thrift(writer)?;
                Ok(field_id)
            }
        }

        impl $identifier {
            #[allow(deprecated)]
            #[doc = "Returns a slice containing every variant of this enum."]
            #[allow(dead_code)]
            pub const VARIANTS: &'static [Self] = &[
                $(Self::$field_name),*
            ];

            #[allow(deprecated)]
            const fn max_discriminant_impl() -> i32 {
                let values: &[i32] = &[$($field_value),*];
                let mut max = values[0];
                let mut idx = 1;
                while idx < values.len() {
                    let candidate = values[idx];
                    if candidate > max {
                        max = candidate;
                    }
                    idx += 1;
                }
                max
            }

            #[allow(deprecated)]
            #[doc = "Returns the largest discriminant value defined for this enum."]
            #[allow(dead_code)]
            pub const MAX_DISCRIMINANT: i32 = Self::max_discriminant_impl();
        }
    }
}

/// Macro used to generate Rust enums for Thrift unions in which all variants are typed with empty
/// structs.
///
/// Because the compact protocol does not write any struct type information, these empty structs
/// become a single `0` (end-of-fields marker) upon serialization. Rather than trying to deserialize
/// an empty struct, we can instead simply read the `0` and discard it.
///
/// The resulting Rust enum will have all unit variants.
///
/// Note:
///  - All enums generated with this macro will have `pub` visibility.
///  - When utilizing this macro the Thrift serialization traits and structs need to be in scope.
#[doc(hidden)]
#[macro_export]
#[allow(clippy::crate_in_macro_def)]
macro_rules! thrift_union_all_empty {
    ($(#[$($def_attrs:tt)*])* union $identifier:ident { $($(#[$($field_attrs:tt)*])* $field_id:literal : $field_type:ident $(< $element_type:ident >)? $field_name:ident $(;)?)* }) => {
        $(#[cfg_attr(not(doctest), $($def_attrs)*)])*
        #[derive(Clone, Copy, Debug, Eq, PartialEq)]
        #[allow(non_camel_case_types)]
        #[allow(non_snake_case)]
        #[allow(missing_docs)]
        pub enum $identifier {
            $($(#[cfg_attr(not(doctest), $($field_attrs)*)])* $field_name),*
        }

        impl<'a, R: ThriftCompactInputProtocol<'a>> ReadThrift<'a, R> for $identifier {
            fn read_thrift(prot: &mut R) -> Result<Self> {
                let field_ident = prot.read_field_begin(0)?;
                if field_ident.field_type == FieldType::Stop {
                    return Err(general_err!("Received empty union from remote {}", stringify!($identifier)));
                }
                let ret = match field_ident.id {
                    $($field_id => {
                        prot.skip_empty_struct()?;
                        Self::$field_name
                    }
                    )*
                    _ => {
                        return Err(general_err!("Unexpected {} {}", stringify!($identifier), field_ident.id));
                    }
                };
                let field_ident = prot.read_field_begin(field_ident.id)?;
                if field_ident.field_type != FieldType::Stop {
                    return Err(general_err!(
                        "Received multiple fields for union from remote {}", stringify!($identifier)
                    ));
                }
                Ok(ret)
            }
        }

        impl WriteThrift for $identifier {
            const ELEMENT_TYPE: ElementType = ElementType::Struct;

            fn write_thrift<W: Write>(&self, writer: &mut ThriftCompactOutputProtocol<W>) -> Result<()> {
                match *self {
                    $(Self::$field_name => writer.write_empty_struct($field_id, 0)?,)*
                };
                // write end of struct for this union
                writer.write_struct_end()
            }
        }

        impl WriteThriftField for $identifier {
            fn write_thrift_field<W: Write>(&self, writer: &mut ThriftCompactOutputProtocol<W>, field_id: i16, last_field_id: i16) -> Result<i16> {
                writer.write_field_begin(FieldType::Struct, field_id, last_field_id)?;
                self.write_thrift(writer)?;
                Ok(field_id)
            }
        }
    }
}

/// Macro used to generate Rust enums for Thrift unions where variants are a mix of unit and
/// tuple types.
///
/// Use of this macro requires modifying the thrift IDL. For variants with empty structs as their
/// type, delete the typename (i.e. `1: EmptyStruct Var1;` becomes `1: Var1`). For variants with a
/// non-empty type, the typename must be contained within parens (e.g. `1: MyType Var1;` becomes
/// `1: (MyType) Var1;`).
///
/// Note:
///  - All enums generated with this macro will have `pub` visibility.
///  - This macro allows for specifying lifetime annotations for the resulting `enum` and its fields.
///  - When utilizing this macro the Thrift serialization traits and structs need to be in scope.
#[doc(hidden)]
#[macro_export]
#[allow(clippy::crate_in_macro_def)]
macro_rules! thrift_union {
    ($(#[$($def_attrs:tt)*])* union $identifier:ident $(< $lt:lifetime >)? { $($(#[$($field_attrs:tt)*])* $field_id:literal : $( ( $field_type:ident $(< $element_type:ident >)? $(< $field_lt:lifetime >)?) )? $field_name:ident $(;)?)* }) => {
        $(#[cfg_attr(not(doctest), $($def_attrs)*)])*
        #[derive(Clone, Debug, Eq, PartialEq)]
        #[allow(non_camel_case_types)]
        #[allow(non_snake_case)]
        #[allow(missing_docs)]
        pub enum $identifier $(<$lt>)? {
            $($(#[cfg_attr(not(doctest), $($field_attrs)*)])* $field_name $( ( $crate::__thrift_union_type!{$field_type $($field_lt)? $($element_type)?} ) )?),*
        }

        impl<'a, R: ThriftCompactInputProtocol<'a>> ReadThrift<'a, R> for $identifier $(<$lt>)? {
            fn read_thrift(prot: &mut R) -> Result<Self> {
                let field_ident = prot.read_field_begin(0)?;
                if field_ident.field_type == FieldType::Stop {
                    return Err(general_err!("Received empty union from remote {}", stringify!($identifier)));
                }
                let ret = match field_ident.id {
                    $($field_id => {
                        let val = $crate::__thrift_read_variant!(prot, $field_name $($field_type $($element_type)?)?);
                        val
                    })*
                    _ => {
                        return Err(general_err!("Unexpected {} {}", stringify!($identifier), field_ident.id));
                    }
                };
                let field_ident = prot.read_field_begin(field_ident.id)?;
                if field_ident.field_type != FieldType::Stop {
                    return Err(general_err!(
                        concat!("Received multiple fields for union from remote {}", stringify!($identifier))
                    ));
                }
                Ok(ret)
            }
        }

        impl $(<$lt>)? WriteThrift for $identifier $(<$lt>)? {
            const ELEMENT_TYPE: ElementType = ElementType::Struct;

            fn write_thrift<W: Write>(&self, writer: &mut ThriftCompactOutputProtocol<W>) -> Result<()> {
                match self {
                    $($crate::__thrift_write_variant_lhs!($field_name $($field_type)?, variant_val) =>
                      $crate::__thrift_write_variant_rhs!($field_id $($field_type)?, writer, variant_val),)*
                };
                writer.write_struct_end()
            }
        }

        impl $(<$lt>)? WriteThriftField for $identifier $(<$lt>)? {
            fn write_thrift_field<W: Write>(&self, writer: &mut ThriftCompactOutputProtocol<W>, field_id: i16, last_field_id: i16) -> Result<i16> {
                writer.write_field_begin(FieldType::Struct, field_id, last_field_id)?;
                self.write_thrift(writer)?;
                Ok(field_id)
            }
        }
    }
}

/// Macro used to generate Rust structs from a Thrift `struct` definition.
///
/// Note:
///  - This macro allows for specifying the visibility of the resulting `struct` and its fields.
///    + The `struct` and all fields will have the same visibility.
///  - This macro allows for specifying lifetime annotations for the resulting `struct` and its fields.
///  - When utilizing this macro the Thrift serialization traits and structs need to be in scope.
#[doc(hidden)]
#[macro_export]
macro_rules! thrift_struct {
    ($(#[$($def_attrs:tt)*])* $vis:vis struct $identifier:ident $(< $lt:lifetime >)? { $($(#[$($field_attrs:tt)*])* $field_id:literal : $required_or_optional:ident $field_type:ident $(< $field_lt:lifetime >)? $(< $element_type:ident >)? $field_name:ident $(= $default_value:literal)? $(;)?)* }) => {
        $(#[cfg_attr(not(doctest), $($def_attrs)*)])*
        #[derive(Clone, Debug, Eq, PartialEq)]
        #[allow(non_camel_case_types)]
        #[allow(non_snake_case)]
        #[allow(missing_docs)]
        $vis struct $identifier $(<$lt>)? {
            $($(#[cfg_attr(not(doctest), $($field_attrs)*)])* $vis $field_name: $crate::__thrift_required_or_optional!($required_or_optional $crate::__thrift_field_type!($field_type $($field_lt)? $($element_type)?))),*
        }

        impl<'a, R: ThriftCompactInputProtocol<'a>> ReadThrift<'a, R> for $identifier $(<$lt>)? {
            fn read_thrift(prot: &mut R) -> Result<Self> {
                $(let mut $field_name: Option<$crate::__thrift_field_type!($field_type $($field_lt)? $($element_type)?)> = None;)*
                let mut last_field_id = 0i16;
                loop {
                    let field_ident = prot.read_field_begin(last_field_id)?;
                    if field_ident.field_type == FieldType::Stop {
                        break;
                    }
                    match field_ident.id {
                        $($field_id => {
                            let val = $crate::__thrift_read_field!(prot, field_ident, $field_type $($field_lt)? $($element_type)?);
                            $field_name = Some(val);
                        })*
                        _ => {
                            prot.skip(field_ident.field_type)?;
                        }
                    };
                    last_field_id = field_ident.id;
                }
                $($crate::__thrift_result_required_or_optional!($required_or_optional $field_name);)*
                Ok(Self {
                    $($field_name),*
                })
            }
        }

        impl $(<$lt>)? WriteThrift for $identifier $(<$lt>)? {
            const ELEMENT_TYPE: ElementType = ElementType::Struct;

            #[allow(unused_assignments)]
            fn write_thrift<W: Write>(&self, writer: &mut ThriftCompactOutputProtocol<W>) -> Result<()> {
                #[allow(unused_mut, unused_variables)]
                let mut last_field_id = 0i16;
                $($crate::__thrift_write_required_or_optional_field!($required_or_optional $field_name, $field_id, $field_type, self, writer, last_field_id);)*
                writer.write_struct_end()
            }
        }

        impl $(<$lt>)? WriteThriftField for $identifier $(<$lt>)? {
            fn write_thrift_field<W: Write>(&self, writer: &mut ThriftCompactOutputProtocol<W>, field_id: i16, last_field_id: i16) -> Result<i16> {
                writer.write_field_begin(FieldType::Struct, field_id, last_field_id)?;
                self.write_thrift(writer)?;
                Ok(field_id)
            }
        }
    }
}

#[doc(hidden)]
#[macro_export]
/// Generate `WriteThriftField` implementation for a struct.
macro_rules! write_thrift_field {
    ($identifier:ident $(< $lt:lifetime >)?, $fld_type:expr) => {
        impl $(<$lt>)? WriteThriftField for $identifier $(<$lt>)? {
            fn write_thrift_field<W: Write>(&self, writer: &mut ThriftCompactOutputProtocol<W>, field_id: i16, last_field_id: i16) -> Result<i16> {
                writer.write_field_begin($fld_type, field_id, last_field_id)?;
                self.write_thrift(writer)?;
                Ok(field_id)
            }
        }
    }
}

#[doc(hidden)]
#[macro_export]
macro_rules! __thrift_write_required_or_optional_field {
    (required $field_name:ident, $field_id:literal, $field_type:ident, $self:tt, $writer:tt, $last_id:tt) => {
        $crate::__thrift_write_required_field!(
            $field_type,
            $field_name,
            $field_id,
            $self,
            $writer,
            $last_id
        )
    };
    (optional $field_name:ident, $field_id:literal, $field_type:ident, $self:tt, $writer:tt, $last_id:tt) => {
        $crate::__thrift_write_optional_field!(
            $field_type,
            $field_name,
            $field_id,
            $self,
            $writer,
            $last_id
        )
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __thrift_write_required_field {
    (binary, $field_name:ident, $field_id:literal, $self:ident, $writer:ident, $last_id:ident) => {
        $writer.write_field_begin(FieldType::Binary, $field_id, $last_id)?;
        $writer.write_bytes($self.$field_name)?;
        $last_id = $field_id;
    };
    ($field_type:ident, $field_name:ident, $field_id:literal, $self:ident, $writer:ident, $last_id:ident) => {
        $last_id = $self
            .$field_name
            .write_thrift_field($writer, $field_id, $last_id)?;
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __thrift_write_optional_field {
    (binary, $field_name:ident, $field_id:literal, $self:ident, $writer:tt, $last_id:tt) => {
        if $self.$field_name.is_some() {
            $writer.write_field_begin(FieldType::Binary, $field_id, $last_id)?;
            $writer.write_bytes($self.$field_name.as_ref().unwrap())?;
            $last_id = $field_id;
        }
    };
    ($field_type:ident, $field_name:ident, $field_id:literal, $self:ident, $writer:tt, $last_id:tt) => {
        if $self.$field_name.is_some() {
            $last_id = $self
                .$field_name
                .as_ref()
                .unwrap()
                .write_thrift_field($writer, $field_id, $last_id)?;
        }
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __thrift_required_or_optional {
    (required $field_type:ty) => { $field_type };
    (optional $field_type:ty) => { Option<$field_type> };
}

// Performance note: using `expect` here is about 4% faster on the page index bench,
// but we want to propagate errors. Using `ok_or` is *much* slower.
#[doc(hidden)]
#[macro_export]
macro_rules! __thrift_result_required_or_optional {
    (required $field_name:ident) => {
        let Some($field_name) = $field_name else {
            return Err(general_err!(concat!(
                "Required field ",
                stringify!($field_name),
                " is missing",
            )));
        };
    };
    (optional $field_name:ident) => {};
}

#[doc(hidden)]
#[macro_export]
macro_rules! __thrift_read_field {
    ($prot:tt, $field_ident:tt, list $lt:lifetime binary) => {
        read_thrift_vec::<&'a [u8], R>(&mut *$prot)?
    };
    ($prot:tt, $field_ident:tt, list $lt:lifetime $element_type:ident) => {
        read_thrift_vec::<$element_type, R>(&mut *$prot)?
    };
    ($prot:tt, $field_ident:tt, list string) => {
        read_thrift_vec::<String, R>(&mut *$prot)?
    };
    ($prot:tt, $field_ident:tt, list $element_type:ident) => {
        read_thrift_vec::<$element_type, R>(&mut *$prot)?
    };
    ($prot:tt, $field_ident:tt, string $lt:lifetime) => {
        <&$lt str>::read_thrift(&mut *$prot)?
    };
    ($prot:tt, $field_ident:tt, binary $lt:lifetime) => {
        <&$lt [u8]>::read_thrift(&mut *$prot)?
    };
    ($prot:tt, $field_ident:tt, $field_type:ident $lt:lifetime) => {
        $field_type::read_thrift(&mut *$prot)?
    };
    ($prot:tt, $field_ident:tt, string) => {
        String::read_thrift(&mut *$prot)?
    };
    ($prot:tt, $field_ident:tt, binary) => {
        // this one needs to not conflict with `list<i8>`
        $prot.read_bytes_owned()?
    };
    ($prot:tt, $field_ident:tt, double) => {
        $crate::parquet_thrift::OrderedF64::read_thrift(&mut *$prot)?
    };
    ($prot:tt, $field_ident:tt, bool) => {
        $field_ident.bool_val.unwrap()
    };
    ($prot:tt, $field_ident:tt, $field_type:ident) => {
        $field_type::read_thrift(&mut *$prot)?
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __thrift_field_type {
    (binary $lt:lifetime) => { &$lt [u8] };
    (string $lt:lifetime) => { &$lt str };
    ($field_type:ident $lt:lifetime) => { $field_type<$lt> };
    (list $lt:lifetime $element_type:ident) => { Vec< $crate::__thrift_field_type!($element_type $lt) > };
    (list string) => { Vec<String> };
    (list $element_type:ident) => { Vec< $crate::__thrift_field_type!($element_type) > };
    (binary) => { Vec<u8> };
    (string) => { String };
    (double) => { $crate::parquet_thrift::OrderedF64 };
    ($field_type:ty) => { $field_type };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __thrift_union_type {
    (binary $lt:lifetime) => { &$lt [u8] };
    (string $lt:lifetime) => { &$lt str };
    ($field_type:ident $lt:lifetime) => { $field_type<$lt> };
    ($field_type:ident) => { $field_type };
    (list $field_type:ident) => { Vec<$field_type> };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __thrift_read_variant {
    ($prot:tt, $field_name:ident $field_type:ident) => {
        Self::$field_name($field_type::read_thrift(&mut *$prot)?)
    };
    ($prot:tt, $field_name:ident list $field_type:ident) => {
        Self::$field_name(Vec::<$field_type>::read_thrift(&mut *$prot)?)
    };
    ($prot:tt, $field_name:ident) => {{
        $prot.skip_empty_struct()?;
        Self::$field_name
    }};
}

#[doc(hidden)]
#[macro_export]
macro_rules! __thrift_write_variant_lhs {
    ($field_name:ident $field_type:ident, $val:tt) => {
        Self::$field_name($val)
    };
    ($field_name:ident, $val:tt) => {
        Self::$field_name
    };
}

#[doc(hidden)]
#[macro_export]
macro_rules! __thrift_write_variant_rhs {
    ($field_id:literal $field_type:ident, $writer:tt, $val:ident) => {
        $val.write_thrift_field($writer, $field_id, 0)?
    };
    ($field_id:literal, $writer:tt, $val:tt) => {
        $writer.write_empty_struct($field_id, 0)?
    };
}