Skip to main content

parquet/arrow/buffer/
view_buffer.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::arrow::record_reader::buffer::ValuesBuffer;
6use crate::errors::Result;
7use arrow_array::{ArrayRef, BinaryViewArray, StringViewArray};
8use arrow_buffer::{Buffer, NullBuffer, ScalarBuffer};
9use arrow_schema::DataType as ArrowType;
10use std::sync::Arc;
11
12/// A buffer of view type byte arrays that can be converted into
13/// `GenericByteViewArray`
14///
15/// Note this does not reuse `GenericByteViewBuilder` due to the need to call `pad_nulls`
16/// and reuse the existing logic for Vec in the parquet crate
17#[derive(Debug, Default)]
18pub struct ViewBuffer {
19    pub views: Vec<u128>,
20    pub buffers: Vec<Buffer>,
21}
22
23impl ViewBuffer {
24    /// Create a new ViewBuffer with capacity for the specified number of views
25    pub fn with_capacity(capacity: usize) -> Self {
26        Self {
27            views: Vec::with_capacity(capacity),
28            buffers: Vec::new(),
29        }
30    }
31
32    pub fn is_empty(&self) -> bool {
33        self.views.is_empty()
34    }
35
36    pub fn append_block(&mut self, block: Buffer) -> u32 {
37        let block_id = self.buffers.len() as u32;
38        self.buffers.push(block);
39        block_id
40    }
41
42    /// Converts this into an [`ArrayRef`] with the provided `data_type` and `null_buffer`
43    pub fn into_array(self, null_buffer: Option<Buffer>, data_type: &ArrowType) -> ArrayRef {
44        let len = self.views.len();
45        let views = ScalarBuffer::from(self.views);
46        let nulls = null_buffer.and_then(|b| NullBuffer::from_unsliced_buffer(b, len));
47        let buffers = self.buffers.into();
48        match data_type {
49            ArrowType::Utf8View => {
50                // Safety: views were created correctly, and checked that the data is utf8 when building the buffer
51                unsafe { Arc::new(StringViewArray::new_unchecked(views, buffers, nulls)) }
52            }
53            ArrowType::BinaryView => {
54                // Safety: views were created correctly
55                unsafe { Arc::new(BinaryViewArray::new_unchecked(views, buffers, nulls)) }
56            }
57            _ => panic!("Unsupported data type: {data_type}"),
58        }
59    }
60}
61
62impl ValuesBuffer for ViewBuffer {
63    fn with_capacity(capacity: usize) -> Self {
64        Self::with_capacity(capacity)
65    }
66
67    fn reserve_exact(&mut self, additional: usize) {
68        self.views.reserve_exact(additional);
69    }
70
71    fn pad_nulls(
72        &mut self,
73        read_offset: usize,
74        values_read: usize,
75        levels_read: usize,
76        valid_mask: &[u8],
77    ) -> Result<()> {
78        self.views
79            .pad_nulls(read_offset, values_read, levels_read, valid_mask)
80    }
81}
82
83#[cfg(test)]
84mod tests {
85
86    use arrow::array::make_view;
87    use arrow_array::Array;
88
89    use super::*;
90
91    #[test]
92    fn test_view_buffer_empty() {
93        let buffer = ViewBuffer::with_capacity(0);
94        let array = buffer.into_array(None, &ArrowType::Utf8View);
95        let strings = array
96            .as_any()
97            .downcast_ref::<arrow::array::StringViewArray>()
98            .unwrap();
99        assert_eq!(strings.len(), 0);
100    }
101
102    #[test]
103    fn test_view_buffer_append_view() {
104        let mut buffer = ViewBuffer::with_capacity(0);
105        let data = b"0123456789long string to test string view";
106        let string_buffer = Buffer::from(data);
107        let block_id = buffer.append_block(string_buffer);
108
109        buffer.views.push(make_view(&data[0..1], block_id, 0));
110        buffer.views.push(make_view(&data[1..10], block_id, 1));
111        buffer.views.push(make_view(&data[10..41], block_id, 10));
112
113        let array = buffer.into_array(None, &ArrowType::Utf8View);
114        let string_array = array
115            .as_any()
116            .downcast_ref::<arrow::array::StringViewArray>()
117            .unwrap();
118        assert_eq!(
119            string_array.iter().collect::<Vec<_>>(),
120            vec![
121                Some("0"),
122                Some("123456789"),
123                Some("long string to test string view"),
124            ]
125        );
126    }
127
128    #[test]
129    fn test_view_buffer_pad_null() {
130        let mut buffer = ViewBuffer::with_capacity(0);
131        let data = b"0123456789long string to test string view";
132        let string_buffer = Buffer::from(data);
133        let block_id = buffer.append_block(string_buffer);
134
135        buffer.views.push(make_view(&data[0..1], block_id, 0));
136        buffer.views.push(make_view(&data[1..10], block_id, 1));
137        buffer.views.push(make_view(&data[10..41], block_id, 10));
138
139        let valid = [true, false, false, true, false, false, true];
140        let valid_mask = Buffer::from_iter(valid.iter().copied());
141
142        buffer
143            .pad_nulls(1, 2, valid.len() - 1, valid_mask.as_slice())
144            .unwrap();
145
146        let array = buffer.into_array(Some(valid_mask), &ArrowType::Utf8View);
147        let strings = array
148            .as_any()
149            .downcast_ref::<arrow::array::StringViewArray>()
150            .unwrap();
151
152        assert_eq!(
153            strings.iter().collect::<Vec<_>>(),
154            vec![
155                Some("0"),
156                None,
157                None,
158                Some("123456789"),
159                None,
160                None,
161                Some("long string to test string view"),
162            ]
163        );
164    }
165}