tustvold commented on a change in pull request #1782:
URL: https://github.com/apache/arrow-datafusion/pull/1782#discussion_r801608112



##########
File path: datafusion/src/row/writer.rs
##########
@@ -0,0 +1,322 @@
+// 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.
+
+//! Reusable row writer backed by Vec<u8> to stitch attributes together
+
+use crate::row::bitmap::{bytes_for, set_bit};
+use crate::row::{estimate_row_width, fixed_size, get_offsets, supported};
+use arrow::array::Array;
+use arrow::datatypes::{DataType, Schema};
+use arrow::record_batch::RecordBatch;
+use std::cmp::max;
+use std::sync::Arc;
+
+/// Append batch from `row_idx` to `output` buffer start from `offset`
+/// # Panics
+///
+/// This function will panic if the output buffer doesn't have enough space to 
hold all the rows
+pub fn write_batch_unchecked(
+    output: &mut [u8],
+    offset: usize,
+    batch: &RecordBatch,
+    row_idx: usize,
+    schema: Arc<Schema>,
+) -> Vec<usize> {
+    let mut writer = RowWriter::new(&schema);
+    let mut current_offset = offset;
+    let mut offsets = vec![];
+    for cur_row in row_idx..batch.num_rows() {
+        offsets.push(current_offset);
+        let row_width = write_row(&mut writer, cur_row, batch, &schema);
+        output[current_offset..current_offset + row_width]
+            .copy_from_slice(writer.get_row());
+        current_offset += row_width;
+        writer.reset()
+    }
+    offsets
+}
+
+macro_rules! set_idx {
+    ($WIDTH: literal, $SELF: ident, $IDX: ident, $VALUE: ident) => {{
+        $SELF.assert_index_valid($IDX);
+        let offset = $SELF.field_offsets[$IDX];
+        $SELF.data[offset..offset + 
$WIDTH].copy_from_slice(&$VALUE.to_le_bytes());
+    }};
+}
+
+macro_rules! fn_set_idx {
+    ($NATIVE: ident, $WIDTH: literal) => {
+        paste::item! {
+            fn [<set_ $NATIVE>](&mut self, idx: usize, value: $NATIVE) {
+                self.assert_index_valid(idx);
+                let offset = self.field_offsets[idx];
+                self.data[offset..offset + 
$WIDTH].copy_from_slice(&value.to_le_bytes());
+            }
+        }
+    };
+}
+
+/// Reusable row writer backed by Vec<u8>
+pub struct RowWriter {
+    data: Vec<u8>,
+    field_count: usize,
+    row_width: usize,
+    null_width: usize,
+    values_width: usize,
+    varlena_width: usize,
+    varlena_offset: usize,
+    field_offsets: Vec<usize>,
+}
+
+impl RowWriter {
+    /// new
+    pub fn new(schema: &Arc<Schema>) -> Self {
+        assert!(supported(schema));
+        let field_count = schema.fields().len();
+        let null_width = bytes_for(field_count);
+        let (field_offsets, values_width) = get_offsets(null_width, schema);
+        let mut init_capacity = estimate_row_width(null_width, schema);
+        if !fixed_size(schema) {
+            // double the capacity to avoid repeated resize
+            init_capacity *= 2;
+        }
+        Self {
+            data: vec![0; init_capacity],
+            field_count,
+            row_width: 0,
+            null_width,
+            values_width,
+            varlena_width: 0,
+            varlena_offset: null_width + values_width,
+            field_offsets,
+        }
+    }
+
+    /// Reset the row writer state for new tuple
+    pub fn reset(&mut self) {
+        self.data.fill(0);
+        self.row_width = 0;
+        self.varlena_width = 0;
+        self.varlena_offset = self.null_width + self.values_width;
+    }
+
+    #[inline]
+    fn assert_index_valid(&self, idx: usize) {
+        assert!(idx < self.field_count);
+    }
+
+    fn set_null_at(&mut self, idx: usize) {
+        let null_bits = &mut self.data[0..self.null_width];
+        set_bit(null_bits, idx, false)
+    }
+
+    fn set_non_null_at(&mut self, idx: usize) {
+        let null_bits = &mut self.data[0..self.null_width];
+        set_bit(null_bits, idx, true)
+    }
+
+    fn set_bool(&mut self, idx: usize, value: bool) {
+        self.assert_index_valid(idx);
+        let offset = self.field_offsets[idx];
+        self.data[offset] = if value { 1 } else { 0 };
+    }
+
+    fn set_u8(&mut self, idx: usize, value: u8) {
+        self.assert_index_valid(idx);
+        let offset = self.field_offsets[idx];
+        self.data[offset] = value;
+    }
+
+    fn_set_idx!(u16, 2);
+    fn_set_idx!(u32, 4);
+    fn_set_idx!(u64, 8);
+    fn_set_idx!(i16, 2);
+    fn_set_idx!(i32, 4);
+    fn_set_idx!(i64, 8);
+    fn_set_idx!(f32, 4);
+    fn_set_idx!(f64, 8);
+
+    fn set_i8(&mut self, idx: usize, value: i8) {
+        self.assert_index_valid(idx);
+        let offset = self.field_offsets[idx];
+        self.data[offset] = value.to_le_bytes()[0];
+    }
+
+    fn set_date32(&mut self, idx: usize, value: i32) {
+        set_idx!(4, self, idx, value)
+    }
+
+    fn set_date64(&mut self, idx: usize, value: i64) {
+        set_idx!(8, self, idx, value)
+    }
+
+    fn set_offset_size(&mut self, idx: usize, size: usize) {
+        let offset_and_size: u64 = (self.varlena_offset << 32 | size) as u64;

Review comment:
       This should probably panic if `size` or `verlana_offset` are too large, 
on a related note - perhaps they should be `u64`?




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to