1use bytes::Bytes;
19
20use crate::basic::{ConvertedType, Encoding, LogicalType, Type};
21use crate::bloom_filter::Sbbf;
22use crate::column::writer::{
23 compare_greater, fallback_encoding, has_dictionary_support, is_nan, update_max, update_min,
24};
25use crate::data_type::DataType;
26use crate::data_type::private::ParquetValueType;
27use crate::encodings::encoding::{DictEncoder, Encoder, get_encoder};
28use crate::errors::{ParquetError, Result};
29use crate::file::properties::{EnabledStatistics, ResolvedColumnProperties, WriterProperties};
30use crate::geospatial::accumulator::{GeoStatsAccumulator, try_new_geo_stats_accumulator};
31use crate::geospatial::statistics::GeospatialStatistics;
32use crate::schema::types::{BasicTypeInfo, ColumnDescPtr};
33
34pub trait ColumnValues {
36 fn len(&self) -> usize;
38}
39
40#[cfg(feature = "arrow")]
41impl ColumnValues for dyn arrow_array::Array {
42 fn len(&self) -> usize {
43 arrow_array::Array::len(self)
44 }
45}
46
47impl<T: ParquetValueType> ColumnValues for [T] {
48 fn len(&self) -> usize {
49 self.len()
50 }
51}
52
53pub struct DictionaryPage {
55 pub buf: Bytes,
56 pub num_values: usize,
57 pub is_sorted: bool,
58}
59
60pub struct DataPageValues<T> {
62 pub buf: Bytes,
63 pub num_values: usize,
64 pub encoding: Encoding,
65 pub min_value: Option<T>,
66 pub max_value: Option<T>,
67 pub nan_count: Option<u64>,
68 pub variable_length_bytes: Option<i64>,
69}
70
71pub trait ColumnValueEncoder {
74 type T: ParquetValueType;
78
79 type Values: ColumnValues + ?Sized;
81
82 #[expect(
87 private_interfaces,
88 reason = "this trait is not nameable outside the crate"
89 )]
90 fn try_new(
91 descr: &ColumnDescPtr,
92 props: &WriterProperties,
93 column_props: &ResolvedColumnProperties,
94 ) -> Result<Self>
95 where
96 Self: Sized;
97
98 fn write(&mut self, values: &Self::Values, offset: usize, len: usize) -> Result<()>;
100
101 fn write_gather(&mut self, values: &Self::Values, indices: &[usize]) -> Result<()>;
103
104 fn count_values_within_byte_budget(
121 _values: &Self::Values,
122 _offset: usize,
123 _len: usize,
124 _byte_budget: usize,
125 ) -> Option<usize> {
126 None
127 }
128
129 fn count_values_within_byte_budget_gather(
133 _values: &Self::Values,
134 _indices: &[usize],
135 _byte_budget: usize,
136 ) -> Option<usize> {
137 None
138 }
139
140 fn num_values(&self) -> usize;
142
143 fn has_dictionary(&self) -> bool;
145
146 fn compresses_against_previous_value(&self) -> bool {
164 false
165 }
166
167 fn estimated_memory_size(&self) -> usize;
170
171 fn estimated_dict_page_size(&self) -> Option<usize>;
173
174 fn estimated_data_page_size(&self) -> usize;
179
180 fn flush_dict_page(&mut self) -> Result<Option<DictionaryPage>>;
186
187 fn flush_data_page(&mut self) -> Result<DataPageValues<Self::T>>;
189
190 fn flush_bloom_filter(&mut self) -> Option<Sbbf>;
194
195 fn flush_geospatial_statistics(&mut self) -> Option<Box<GeospatialStatistics>>;
198}
199
200pub struct ColumnValueEncoderImpl<T: DataType> {
201 encoder: Box<dyn Encoder<T>>,
202 dict_encoder: Option<DictEncoder<T>>,
203 descr: ColumnDescPtr,
204 num_values: usize,
205 statistics_enabled: EnabledStatistics,
206 min_value: Option<T::T>,
207 max_value: Option<T::T>,
208 nan_count: Option<u64>,
209 bloom_filter: Option<Sbbf>,
210 bloom_filter_target_fpp: f64,
211 variable_length_bytes: Option<i64>,
212 geo_stats_accumulator: Option<Box<dyn GeoStatsAccumulator>>,
213}
214
215impl<T: DataType> ColumnValueEncoderImpl<T> {
216 fn is_floating_point_column(&self) -> bool {
217 matches!(self.descr.physical_type(), Type::FLOAT | Type::DOUBLE)
218 || self.descr.logical_type_ref() == Some(&LogicalType::Float16)
219 }
220
221 fn write_slice(&mut self, slice: &[T::T]) -> Result<()> {
222 if self.statistics_enabled != EnabledStatistics::None
223 && self.descr.converted_type() != ConvertedType::INTERVAL
225 {
226 if let Some(accumulator) = self.geo_stats_accumulator.as_deref_mut() {
227 update_geo_stats_accumulator(accumulator, slice.iter());
228 } else if let Some((min, max, nan_count)) =
229 get_min_max(self.descr.get_basic_info(), slice.iter())
230 {
231 update_min(&self.descr, &min, &mut self.min_value);
232 update_max(&self.descr, &max, &mut self.max_value);
233 if self.is_floating_point_column() {
234 *self.nan_count.get_or_insert(0) += nan_count;
235 }
236 }
237
238 if let Some(var_bytes) = T::T::variable_length_bytes(slice) {
239 *self.variable_length_bytes.get_or_insert(0) += var_bytes;
240 }
241 }
242
243 if let Some(bloom_filter) = &mut self.bloom_filter {
245 for value in slice {
246 bloom_filter.insert(value);
247 }
248 }
249
250 match &mut self.dict_encoder {
251 Some(encoder) => encoder.put(slice),
252 _ => self.encoder.put(slice),
253 }
254 }
255}
256
257impl<T: DataType> ColumnValueEncoder for ColumnValueEncoderImpl<T> {
258 type T = T::T;
259
260 type Values = [T::T];
261
262 fn flush_bloom_filter(&mut self) -> Option<Sbbf> {
263 let mut sbbf = self.bloom_filter.take()?;
264 sbbf.fold_to_target_fpp(self.bloom_filter_target_fpp);
265 Some(sbbf)
266 }
267
268 #[expect(
269 private_interfaces,
270 reason = "this trait is not nameable outside the crate"
271 )]
272 fn try_new(
273 descr: &ColumnDescPtr,
274 props: &WriterProperties,
275 column_props: &ResolvedColumnProperties,
276 ) -> Result<Self> {
277 let dict_supported = column_props.dictionary_enabled
278 && has_dictionary_support(T::get_physical_type(), props);
279 let dict_encoder = dict_supported.then(|| DictEncoder::new(descr.clone()));
280
281 let encoder = get_encoder(
283 column_props
284 .encoding
285 .unwrap_or_else(|| fallback_encoding(T::get_physical_type(), props)),
286 descr,
287 )?;
288
289 let statistics_enabled = column_props.statistics_enabled;
290
291 let (bloom_filter, bloom_filter_target_fpp) = create_bloom_filter(column_props)?;
292
293 let geo_stats_accumulator = try_new_geo_stats_accumulator(descr);
294
295 Ok(Self {
296 encoder,
297 dict_encoder,
298 descr: descr.clone(),
299 num_values: 0,
300 statistics_enabled,
301 bloom_filter,
302 bloom_filter_target_fpp,
303 min_value: None,
304 max_value: None,
305 nan_count: None,
306 variable_length_bytes: None,
307 geo_stats_accumulator,
308 })
309 }
310
311 fn write(&mut self, values: &[T::T], offset: usize, len: usize) -> Result<()> {
312 self.num_values += len;
313
314 let slice = values.get(offset..offset + len).ok_or_else(|| {
315 general_err!(
316 "Expected to write {} values, but have only {}",
317 len,
318 values.len() - offset
319 )
320 })?;
321
322 self.write_slice(slice)
323 }
324
325 fn write_gather(&mut self, values: &Self::Values, indices: &[usize]) -> Result<()> {
326 self.num_values += indices.len();
327 let slice: Vec<_> = indices.iter().map(|idx| values[*idx].clone()).collect();
328 self.write_slice(&slice)
329 }
330
331 fn count_values_within_byte_budget(
332 values: &[T::T],
333 offset: usize,
334 len: usize,
335 byte_budget: usize,
336 ) -> Option<usize> {
337 let end = (offset + len).min(values.len());
341 let start = offset.min(end);
342 count_within_budget::<T>(
343 end - start,
344 byte_budget,
345 values[start..end].iter().map(Some),
346 )
347 }
348
349 fn count_values_within_byte_budget_gather(
350 values: &[T::T],
351 indices: &[usize],
352 byte_budget: usize,
353 ) -> Option<usize> {
354 count_within_budget::<T>(
358 indices.len(),
359 byte_budget,
360 indices.iter().map(|&i| values.get(i)),
361 )
362 }
363
364 fn num_values(&self) -> usize {
365 self.num_values
366 }
367
368 fn has_dictionary(&self) -> bool {
369 self.dict_encoder.is_some()
370 }
371
372 fn compresses_against_previous_value(&self) -> bool {
373 self.dict_encoder.is_none() && self.encoder.encoding() == Encoding::DELTA_BYTE_ARRAY
376 }
377
378 fn estimated_memory_size(&self) -> usize {
379 let encoder_size = self.encoder.estimated_memory_size();
380
381 let dict_encoder_size = self
382 .dict_encoder
383 .as_ref()
384 .map(|encoder| encoder.estimated_memory_size())
385 .unwrap_or_default();
386
387 let bloom_filter_size = self
388 .bloom_filter
389 .as_ref()
390 .map(|bf| bf.estimated_memory_size())
391 .unwrap_or_default();
392
393 encoder_size + dict_encoder_size + bloom_filter_size
394 }
395
396 fn estimated_dict_page_size(&self) -> Option<usize> {
397 Some(self.dict_encoder.as_ref()?.dict_encoded_size())
398 }
399
400 fn estimated_data_page_size(&self) -> usize {
401 match &self.dict_encoder {
402 Some(encoder) => encoder.estimated_data_encoded_size(),
403 _ => self.encoder.estimated_data_encoded_size(),
404 }
405 }
406
407 fn flush_dict_page(&mut self) -> Result<Option<DictionaryPage>> {
408 match self.dict_encoder.take() {
409 Some(encoder) => {
410 if self.num_values != 0 {
411 return Err(general_err!(
412 "Must flush data pages before flushing dictionary"
413 ));
414 }
415
416 let buf = encoder.write_dict()?;
417
418 Ok(Some(DictionaryPage {
419 buf,
420 num_values: encoder.num_entries(),
421 is_sorted: encoder.is_sorted(),
422 }))
423 }
424 _ => Ok(None),
425 }
426 }
427
428 fn flush_data_page(&mut self) -> Result<DataPageValues<T::T>> {
429 let (buf, encoding) = match &mut self.dict_encoder {
430 Some(encoder) => (encoder.write_indices()?, Encoding::RLE_DICTIONARY),
431 _ => (self.encoder.flush_buffer()?, self.encoder.encoding()),
432 };
433
434 Ok(DataPageValues {
435 buf,
436 encoding,
437 num_values: std::mem::take(&mut self.num_values),
438 min_value: self.min_value.take(),
439 max_value: self.max_value.take(),
440 nan_count: self.nan_count.take(),
441 variable_length_bytes: self.variable_length_bytes.take(),
442 })
443 }
444
445 fn flush_geospatial_statistics(&mut self) -> Option<Box<GeospatialStatistics>> {
446 self.geo_stats_accumulator.as_mut().map(|a| a.finish())?
447 }
448}
449
450fn get_min_max<'a, T, I>(basic_type_info: &BasicTypeInfo, mut iter: I) -> Option<(T, T, u64)>
457where
458 T: ParquetValueType + 'a,
459 I: Iterator<Item = &'a T>,
460{
461 let first = iter.next()?;
462 let mut min_max_nan = is_nan(basic_type_info, first);
463 let mut nan_count = min_max_nan as u64;
464
465 let mut min = first;
466 let mut max = first;
467 for val in iter {
468 match (min_max_nan, is_nan(basic_type_info, val)) {
469 (false, true) => {
471 nan_count += 1;
472 }
473 (true, false) => {
475 min = val;
476 max = val;
477 min_max_nan = false;
478 }
479 (_, val_is_nan) => {
481 nan_count += val_is_nan as u64;
482 if compare_greater(basic_type_info, min, val) {
485 min = val;
486 } else if compare_greater(basic_type_info, val, max) {
487 max = val;
488 }
489 }
490 }
491 }
492
493 Some((min.clone(), max.clone(), nan_count))
494}
495
496pub(crate) fn create_bloom_filter(
499 column_props: &ResolvedColumnProperties,
500) -> Result<(Option<Sbbf>, f64)> {
501 match column_props.bloom_filter_properties.as_ref() {
502 Some(bf_props) => Ok((
503 Some(Sbbf::new_with_ndv_fpp(bf_props.ndv(), bf_props.fpp())?),
504 bf_props.fpp(),
505 )),
506 None => Ok((None, 0.0)),
507 }
508}
509
510fn update_geo_stats_accumulator<'a, T, I>(bounder: &mut dyn GeoStatsAccumulator, iter: I)
511where
512 T: ParquetValueType + 'a,
513 I: Iterator<Item = &'a T>,
514{
515 if bounder.is_valid() {
516 for val in iter {
517 bounder.update_wkb(val.as_bytes());
518 }
519 }
520}
521
522#[inline]
536fn plain_encoded_byte_size<T: DataType>(value: &T::T) -> usize {
537 let (overhead, bytes) = value.dict_encoding_size();
538 match <T::T as ParquetValueType>::PHYSICAL_TYPE {
539 Type::BYTE_ARRAY => overhead + bytes,
541 Type::FIXED_LEN_BYTE_ARRAY => bytes,
544 _ => overhead,
548 }
549}
550
551#[inline]
566fn count_within_budget<'a, T: DataType>(
567 n: usize,
568 byte_budget: usize,
569 vals: impl Iterator<Item = Option<&'a T::T>>,
570) -> Option<usize>
571where
572 T::T: 'a,
573{
574 let phys = <T::T as ParquetValueType>::PHYSICAL_TYPE;
577 if phys != Type::BYTE_ARRAY && phys != Type::FIXED_LEN_BYTE_ARRAY {
578 let per = std::mem::size_of::<T::T>().max(1);
579 return Some((byte_budget / per).max(1).min(n));
580 }
581 let mut cum: usize = 0;
583 for (i, v) in vals.enumerate() {
584 if let Some(v) = v {
585 cum = cum.saturating_add(plain_encoded_byte_size::<T>(v));
586 }
587 if cum > byte_budget {
588 return Some(i + 1);
589 }
590 }
591 Some(n)
592}