You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "PinkCrow007 (via GitHub)" <gi...@apache.org> on 2025/06/13 06:38:00 UTC

[PR] Initial Builder API for Creating Variant Values [arrow-rs]

PinkCrow007 opened a new pull request, #7653:
URL: https://github.com/apache/arrow-rs/pull/7653

   # Which issue does this PR close?
   
   Closes #7424
   
   # Rationale for this change
   
   This PR introduces a basic builder API for creating Variant values, building on the foundation laid by @mkarbo. The builder provides a user-friendly nested API while maintaining performance through a single-buffer design. The design was shaped with huge help from @alamb, @scovich and @Weijun-H ’s feedback, and draws much inspiration from the excellent work by @zeroshade
   
   This is an initial version and does not yet support nested values, metadata key sorting, and so on
   
   # What changes are included in this PR?
   
   - Adds VariantBuilder, ObjectBuilder, ArrayBuilder
   
   # Are there any user-facing changes?
   
   The new API's added in parquet-variant will be user facing.
   
   


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2153233015


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());
+                id
+            }
+        }
+    }
+
+    fn offset(&self) -> usize {
+        self.buffer.len()
+    }
+
+    /// Create an [`ArrayBuilder`] for creating [`Variant::Array`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_array(&mut self) -> ArrayBuilder {
+        ArrayBuilder::new(self)
+    }
+
+    /// Create an [`ObjectBuilder`] for creating [`Variant::Object`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_object(&mut self) -> ObjectBuilder {
+        ObjectBuilder::new(self)
+    }
+
+    pub fn finish(self) -> (Vec<u8>, Vec<u8>) {
+        let nkeys = self.dict_keys.len();
+
+        // Calculate metadata size
+        let total_dict_size: usize = self.dict_keys.iter().map(|k| k.len()).sum();
+
+        // Determine appropriate offset size based on the larger of dict size or total string size
+        let max_offset = std::cmp::max(total_dict_size, nkeys);
+        let offset_size = int_size(max_offset);
+
+        let offset_start = 1 + offset_size as usize;
+        let string_start = offset_start + (nkeys + 1) * offset_size as usize;
+        let metadata_size = string_start + total_dict_size;
+
+        // Pre-allocate exact size to avoid reallocations
+        let mut metadata = vec![0u8; metadata_size];
+
+        // Write header: version=1, not sorted, with calculated offset_size
+        metadata[0] = 0x01 | ((offset_size - 1) << 6);
+
+        // Write dictionary size
+        write_offset(&mut metadata[1..], nkeys, offset_size);
+
+        // Write offsets and string data
+        let mut cur_offset = 0;
+        for (i, key) in self.dict_keys.iter().enumerate() {
+            write_offset(
+                &mut metadata[offset_start + i * offset_size as usize..],
+                cur_offset,
+                offset_size,
+            );
+            let start = string_start + cur_offset;
+            metadata[start..start + key.len()].copy_from_slice(key.as_bytes());
+            cur_offset += key.len();
+        }
+        // Write final offset
+        write_offset(
+            &mut metadata[offset_start + nkeys * offset_size as usize..],
+            cur_offset,
+            offset_size,
+        );
+
+        (metadata, self.buffer)
+    }
+
+    pub fn append_value<T: Into<Variant<'static, 'static>>>(&mut self, value: T) {
+        let variant = value.into();
+        match variant {
+            Variant::Null => self.append_null(),
+            Variant::BooleanTrue => self.append_bool(true),
+            Variant::BooleanFalse => self.append_bool(false),
+            Variant::Int8(v) => self.append_int8(v),
+            Variant::Int16(v) => self.append_int16(v),
+            Variant::Int32(v) => self.append_int32(v),
+            Variant::Int64(v) => self.append_int64(v),
+            Variant::Date(v) => self.append_date(v),
+            Variant::TimestampMicros(v) => self.append_timestamp_micros(v),
+            Variant::TimestampNtzMicros(v) => self.append_timestamp_ntz_micros(v),
+            Variant::Decimal4 { integer, scale } => self.append_decimal4(integer, scale),
+            Variant::Decimal8 { integer, scale } => self.append_decimal8(integer, scale),
+            Variant::Decimal16 { integer, scale } => self.append_decimal16(integer, scale),
+            Variant::Float(v) => self.append_float(v),
+            Variant::Double(v) => self.append_double(v),
+            Variant::Binary(v) => self.append_binary(v),
+            Variant::String(s) | Variant::ShortString(s) => self.append_string(s),

Review Comment:
   Tracking with
    - https://github.com/apache/arrow-rs/issues/7700



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "PinkCrow007 (via GitHub)" <gi...@apache.org>.
PinkCrow007 commented on PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#issuecomment-2982817424

   Huge thanks @alamb @scovich — I’m honestly really touched by all the care and thought you put into this. I learned so much from your improvements and comments. Really appreciate you helping push it forward! I’ll keep working on the follow-ups and keep learning from you!


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2153239491


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,737 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+const UNIX_EPOCH_DATE: chrono::NaiveDate = chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = (value >> (i * 8)) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Some(Variant::ShortString("Jiaying"))
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Some(Variant::ShortString("Li"))
+/// );
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::List(variant_list) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_list.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_list.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_list.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value.signed_duration_since(UNIX_EPOCH_DATE).num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());
+                id
+            }
+        }
+    }
+
+    fn offset(&self) -> usize {
+        self.buffer.len()
+    }
+
+    /// Create an [`ArrayBuilder`] for creating [`Variant::Array`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_array(&mut self) -> ArrayBuilder {
+        ArrayBuilder::new(self)
+    }
+
+    /// Create an [`ObjectBuilder`] for creating [`Variant::Object`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_object(&mut self) -> ObjectBuilder {
+        ObjectBuilder::new(self)
+    }
+
+    pub fn finish(self) -> (Vec<u8>, Vec<u8>) {
+        let nkeys = self.dict_keys.len();
+
+        // Calculate metadata size
+        let total_dict_size: usize = self.dict_keys.iter().map(|k| k.len()).sum();
+
+        // Determine appropriate offset size based on the larger of dict size or total string size
+        let max_offset = std::cmp::max(total_dict_size, nkeys);
+        let offset_size = int_size(max_offset);
+
+        let offset_start = 1 + offset_size as usize;
+        let string_start = offset_start + (nkeys + 1) * offset_size as usize;
+        let metadata_size = string_start + total_dict_size;
+
+        // Pre-allocate exact size to avoid reallocations
+        let mut metadata = vec![0u8; metadata_size];
+
+        // Write header: version=1, not sorted, with calculated offset_size
+        metadata[0] = 0x01 | ((offset_size - 1) << 6);
+
+        // Write dictionary size
+        write_offset(&mut metadata[1..], nkeys, offset_size);
+
+        // Write offsets and string data
+        let mut cur_offset = 0;
+        for (i, key) in self.dict_keys.iter().enumerate() {
+            write_offset(
+                &mut metadata[offset_start + i * offset_size as usize..],
+                cur_offset,
+                offset_size,
+            );
+            let start = string_start + cur_offset;
+            metadata[start..start + key.len()].copy_from_slice(key.as_bytes());
+            cur_offset += key.len();
+        }
+        // Write final offset
+        write_offset(
+            &mut metadata[offset_start + nkeys * offset_size as usize..],
+            cur_offset,
+            offset_size,
+        );
+
+        (metadata, self.buffer)
+    }
+
+    pub fn append_value<T: Into<Variant<'static, 'static>>>(&mut self, value: T) {
+        let variant = value.into();
+        match variant {
+            Variant::Null => self.append_null(),
+            Variant::BooleanTrue => self.append_bool(true),
+            Variant::BooleanFalse => self.append_bool(false),
+            Variant::Int8(v) => self.append_int8(v),
+            Variant::Int16(v) => self.append_int16(v),
+            Variant::Int32(v) => self.append_int32(v),
+            Variant::Int64(v) => self.append_int64(v),
+            Variant::Date(v) => self.append_date(v),
+            Variant::TimestampMicros(v) => self.append_timestamp_micros(v),
+            Variant::TimestampNtzMicros(v) => self.append_timestamp_ntz_micros(v),
+            Variant::Decimal4 { integer, scale } => self.append_decimal4(integer, scale),
+            Variant::Decimal8 { integer, scale } => self.append_decimal8(integer, scale),
+            Variant::Decimal16 { integer, scale } => self.append_decimal16(integer, scale),
+            Variant::Float(v) => self.append_float(v),
+            Variant::Double(v) => self.append_double(v),
+            Variant::Binary(v) => self.append_binary(v),
+            Variant::String(s) | Variant::ShortString(s) => self.append_string(s),
+            Variant::Object(_) | Variant::List(_) => {
+                unreachable!("Object and Array variants cannot be created through Into<Variant>")

Review Comment:
   - Filed  https://github.com/apache/arrow-rs/issues/7701



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#issuecomment-2981814076

   I also updated the naming to match the change to rename `Variant::Array` to `Variant::List` 
   
   The more I see that the less I like it -- I will file a separate ticket


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2145517024


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,424 @@
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+pub fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+pub fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+pub fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+pub fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());
+                id
+            }
+        }
+    }
+
+    fn offset(&self) -> usize {
+        self.buffer.len()
+    }
+
+    pub fn new_array(&mut self) -> ArrayBuilder {
+        ArrayBuilder::new(self)
+    }
+
+    pub fn new_object(&mut self) -> ObjectBuilder {
+        ObjectBuilder::new(self)
+    }
+
+    pub fn finish(self) -> (Vec<u8>, Vec<u8>) {
+        let nkeys = self.dict_keys.len();
+
+        // Calculate metadata size
+        let total_dict_size: usize = self.dict_keys.iter().map(|k| k.len()).sum();
+
+        // Determine appropriate offset size based on the larger of dict size or total string size
+        let max_offset = std::cmp::max(total_dict_size, nkeys);
+        let offset_size = int_size(max_offset);
+
+        let offset_start = 1 + offset_size as usize;
+        let string_start = offset_start + (nkeys + 1) * offset_size as usize;
+        let metadata_size = string_start + total_dict_size;
+
+        // Pre-allocate exact size to avoid reallocations
+        let mut metadata = Vec::with_capacity(metadata_size);
+        metadata.resize(metadata_size, 0);
+
+        // Write header: version=1, not sorted, with calculated offset_size
+        metadata[0] = 0x01 | ((offset_size - 1) << 6);
+
+        // Write dictionary size
+        write_offset(&mut metadata[1..], nkeys, offset_size);
+
+        // Write offsets and string data
+        let mut cur_offset = 0;
+        for (i, key) in self.dict_keys.iter().enumerate() {
+            write_offset(
+                &mut metadata[offset_start + i * offset_size as usize..],
+                cur_offset,
+                offset_size,
+            );
+            let start = string_start + cur_offset;
+            metadata[start..start + key.len()].copy_from_slice(key.as_bytes());
+            cur_offset += key.len();
+        }
+        // Write final offset
+        write_offset(
+            &mut metadata[offset_start + nkeys * offset_size as usize..],
+            cur_offset,
+            offset_size,
+        );
+
+        (metadata, self.buffer)
+    }
+
+    pub fn append_value<T: Into<Variant<'static, 'static>>>(&mut self, value: T) {
+        let variant = value.into();
+        match variant {
+            Variant::Null => self.append_null(),
+            Variant::BooleanTrue => self.append_bool(true),
+            Variant::BooleanFalse => self.append_bool(false),
+            Variant::Int8(v) => self.append_int8(v),
+            Variant::String(s) | Variant::ShortString(s) => self.append_string(s),
+            // TODO: Add types for the rest of primitives
+            Variant::Object(_) | Variant::Array(_) => {
+                unreachable!("Object and Array variants cannot be created through Into<Variant>")
+            }
+        }
+    }
+}
+
+impl Default for VariantBuilder {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+pub struct ArrayBuilder<'a> {
+    parent: &'a mut VariantBuilder,
+    start_pos: usize,
+    offsets: Vec<usize>,
+}
+
+impl<'a> ArrayBuilder<'a> {
+    fn new(parent: &'a mut VariantBuilder) -> Self {
+        let start_pos = parent.offset();
+        Self {
+            parent,
+            start_pos,
+            offsets: vec![0],
+        }
+    }
+
+    pub fn append_value<T: Into<Variant<'static, 'static>>>(&mut self, value: T) {
+        self.parent.append_value(value);
+        let element_end = self.parent.offset() - self.start_pos;
+        self.offsets.push(element_end);
+    }
+
+    pub fn finish(self) {
+        let data_size = self.parent.offset() - self.start_pos;
+        let num_elements = self.offsets.len() - 1;
+        let is_large = num_elements > u8::MAX as usize;
+        let size_bytes = if is_large { 4 } else { 1 };
+        let offset_size = int_size(data_size);
+        let header_size = 1 + size_bytes + (num_elements + 1) * offset_size as usize;
+
+        make_room_for_header(&mut self.parent.buffer, self.start_pos, header_size);
+
+        // Write header
+        let mut pos = self.start_pos;
+        self.parent.buffer[pos] = array_header(is_large, offset_size);
+        pos += 1;
+
+        if is_large {
+            self.parent.buffer[pos..pos + 4].copy_from_slice(&(num_elements as u32).to_le_bytes());
+            pos += 4;
+        } else {
+            self.parent.buffer[pos] = num_elements as u8;
+            pos += 1;
+        }
+
+        // Write offsets
+        for offset in &self.offsets {
+            write_offset(
+                &mut self.parent.buffer[pos..pos + offset_size as usize],
+                *offset,
+                offset_size,
+            );
+            pos += offset_size as usize;
+        }
+    }
+}
+
+pub struct ObjectBuilder<'a> {
+    parent: &'a mut VariantBuilder,
+    start_pos: usize,
+    fields: Vec<(u32, usize)>, // (field_id, offset)
+}
+
+impl<'a> ObjectBuilder<'a> {
+    fn new(parent: &'a mut VariantBuilder) -> Self {
+        let start_pos = parent.offset();
+        Self {
+            parent,
+            start_pos,
+            fields: Vec::new(),
+        }
+    }
+
+    /// Add a field with key and value to the object
+    pub fn append_value<T: Into<Variant<'static, 'static>>>(&mut self, key: &str, value: T) {
+        let id = self.parent.add_key(key);
+        let field_start = self.parent.offset() - self.start_pos;
+        self.parent.append_value(value);
+        self.fields.push((id, field_start));
+    }
+
+    /// Finalize object with sorted fields
+    pub fn finish(mut self) {
+        // Sort fields by key name
+        self.fields.sort_by(|a, b| {
+            let key_a = &self.parent.dict_keys[a.0 as usize];
+            let key_b = &self.parent.dict_keys[b.0 as usize];
+            key_a.cmp(key_b)
+        });
+
+        let data_size = self.parent.offset() - self.start_pos;
+        let num_fields = self.fields.len();
+        let is_large = num_fields > u8::MAX as usize;
+        let size_bytes = if is_large { 4 } else { 1 };
+
+        let max_id = self.fields.iter().map(|&(id, _)| id).max().unwrap_or(0);
+        let id_size = int_size(max_id as usize);
+        let offset_size = int_size(data_size);
+
+        let header_size = 1
+            + size_bytes
+            + num_fields * id_size as usize
+            + (num_fields + 1) * offset_size as usize;
+
+        make_room_for_header(&mut self.parent.buffer, self.start_pos, header_size);
+
+        // Write header
+        let mut pos = self.start_pos;
+        self.parent.buffer[pos] = object_header(is_large, id_size, offset_size);
+        pos += 1;
+
+        if is_large {
+            self.parent.buffer[pos..pos + 4].copy_from_slice(&(num_fields as u32).to_le_bytes());
+            pos += 4;
+        } else {
+            self.parent.buffer[pos] = num_fields as u8;
+            pos += 1;
+        }
+
+        // Write field IDs (sorted order)
+        for &(id, _) in &self.fields {
+            write_offset(
+                &mut self.parent.buffer[pos..pos + id_size as usize],
+                id as usize,
+                id_size,
+            );
+            pos += id_size as usize;
+        }
+
+        // Write field offsets
+        for &(_, offset) in &self.fields {
+            write_offset(
+                &mut self.parent.buffer[pos..pos + offset_size as usize],
+                offset,
+                offset_size,
+            );
+            pos += offset_size as usize;
+        }
+        write_offset(
+            &mut self.parent.buffer[pos..pos + offset_size as usize],
+            data_size,
+            offset_size,
+        );
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_simple_usage() {
+        let mut builder = VariantBuilder::new();
+
+        builder.append_value(());
+        builder.append_value(true);
+        builder.append_value(42i8);
+        builder.append_value("hello");
+
+        let (metadata, value) = builder.finish();

Review Comment:
   I am not quite sure what this is supposed to have done -- the builder had 4 variant values pushed but only returned one it seems
   
   I suggest you update the test to assert_eq against a `Variant` value here too
   
   like
   ```rust
   let metadata = VariantMetadata::try_new(&metadata).unwrap();
   let variant = Variant::try_new(&metadata, &value).unwrap();
   assert_eq!(variant, /* Not clear to me what this should be 🤔 */);
   ```
   
   BTW perhaps the behavior should be that an `builder.append_value` consumes the builder and finishes the value



##########
parquet-variant/tests/variant_interop.rs:
##########
@@ -82,6 +82,41 @@ fn variant_primitive() -> Result<(), ArrowError> {
     Ok(())
 }
 
+#[test]
+fn variant_primitive_builder() -> Result<(), ArrowError> {

Review Comment:
   this is neat



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,424 @@
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+pub fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {

Review Comment:
   I don't think these functions need to be `pub` (they are an implementation detail I think of this module)



##########
parquet-variant/src/variant.rs:
##########
@@ -502,6 +502,12 @@ impl<'m, 'v> From<&'v str> for Variant<'m, 'v> {
     }
 }
 
+impl<'m, 'v> From<()> for Variant<'m, 'v> {
+    fn from(_: ()) -> Self {
+        Variant::Null

Review Comment:
   Ideally this should not return Null but the actual variant value
   
   I think with the change in this PR you could implement this API directly
   - https://github.com/apache/arrow-rs/pull/7663



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,424 @@
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+pub fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+pub fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+pub fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+pub fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+pub struct VariantBuilder {

Review Comment:
   I think adding documentation / examples to this would help a lot. See this PR for a proposal:
   - https://github.com/PinkCrow007/arrow-rs/pull/1



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2153202225


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());

Review Comment:
   Tracking with
   - https://github.com/apache/arrow-rs/issues/7698



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2153096460


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());

Review Comment:
   > (**) Sort+dedup is actually quite some work, because it requires finding and rewriting all field ids scattered through the value bytes. So it would almost certainly be a second step (either a preliminary pass before we actually generate the variant value bytes, or as a fix-up pass afterward to rewrite field ids)
   
   @zeroshade  described a pretty elegant solution in the Go variant builder which was to write the dictionary fields in the order they are encountered., and then decides if the dictionary is sorted when writing it out. The builder has an additional API that you can use to directly add a dictionary key
   
   One benefit of this approach is that different writers can decide if they care about sorted dictionaries and if they do they can do a pre-pass to figure them out and add them directly to the builder



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2153097947


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();

Review Comment:
   Here is the solution that @zeroshade suggested:
   - https://github.com/apache/arrow-rs/pull/7653#discussion_r2153096460



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2149608322


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());

Review Comment:
   Maybe the dictionary could be a map to `u32` (an index into the relevant entry in the `dict_keys` Vec)



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2153098632


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())

Review Comment:
   done



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2153169790


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();

Review Comment:
   Supporting nested data is tracked here:
    - https://github.com/apache/arrow-rs/issues/7696



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "scovich (via GitHub)" <gi...@apache.org>.
scovich commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2147015818


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();

Review Comment:
   In order to deal with nested data efficiently, we will need a separate metadata builder that multiple object builders can make use of. Otherwise, we would need to merge multiple metadata dictionaries, which would also require rewriting the corresponding field ids. Very complex and error-prone.
   
   We should also give some thought into how to build sorted metadata dictionaries. It probably would require making two passes -- one to identify the string values and sort them into a variant metadata; and another to build the variant value that references the string ids?



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())

Review Comment:
   Is this `unwrap` somehow infallible? Otherwise we have a lurking panic here.



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());
+                id
+            }
+        }
+    }
+
+    fn offset(&self) -> usize {
+        self.buffer.len()
+    }
+
+    /// Create an [`ArrayBuilder`] for creating [`Variant::Array`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_array(&mut self) -> ArrayBuilder {
+        ArrayBuilder::new(self)
+    }
+
+    /// Create an [`ObjectBuilder`] for creating [`Variant::Object`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_object(&mut self) -> ObjectBuilder {
+        ObjectBuilder::new(self)
+    }
+
+    pub fn finish(self) -> (Vec<u8>, Vec<u8>) {
+        let nkeys = self.dict_keys.len();
+
+        // Calculate metadata size
+        let total_dict_size: usize = self.dict_keys.iter().map(|k| k.len()).sum();
+
+        // Determine appropriate offset size based on the larger of dict size or total string size
+        let max_offset = std::cmp::max(total_dict_size, nkeys);
+        let offset_size = int_size(max_offset);
+
+        let offset_start = 1 + offset_size as usize;
+        let string_start = offset_start + (nkeys + 1) * offset_size as usize;
+        let metadata_size = string_start + total_dict_size;
+
+        // Pre-allocate exact size to avoid reallocations
+        let mut metadata = vec![0u8; metadata_size];
+
+        // Write header: version=1, not sorted, with calculated offset_size
+        metadata[0] = 0x01 | ((offset_size - 1) << 6);
+
+        // Write dictionary size
+        write_offset(&mut metadata[1..], nkeys, offset_size);
+
+        // Write offsets and string data
+        let mut cur_offset = 0;
+        for (i, key) in self.dict_keys.iter().enumerate() {
+            write_offset(
+                &mut metadata[offset_start + i * offset_size as usize..],
+                cur_offset,
+                offset_size,
+            );
+            let start = string_start + cur_offset;
+            metadata[start..start + key.len()].copy_from_slice(key.as_bytes());
+            cur_offset += key.len();
+        }
+        // Write final offset
+        write_offset(
+            &mut metadata[offset_start + nkeys * offset_size as usize..],
+            cur_offset,
+            offset_size,
+        );
+
+        (metadata, self.buffer)
+    }
+
+    pub fn append_value<T: Into<Variant<'static, 'static>>>(&mut self, value: T) {

Review Comment:
   Can we adjust lifetimes, so normal strings can be appended and not just string constants?
   ```suggestion
       pub fn append_value<'v, T: Into<Variant<'_, 'v>>>(&mut self, value: T) {
   ```



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());
+                id
+            }
+        }
+    }
+
+    fn offset(&self) -> usize {
+        self.buffer.len()
+    }
+
+    /// Create an [`ArrayBuilder`] for creating [`Variant::Array`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_array(&mut self) -> ArrayBuilder {
+        ArrayBuilder::new(self)
+    }
+
+    /// Create an [`ObjectBuilder`] for creating [`Variant::Object`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_object(&mut self) -> ObjectBuilder {
+        ObjectBuilder::new(self)
+    }
+
+    pub fn finish(self) -> (Vec<u8>, Vec<u8>) {

Review Comment:
   Update: Never mind -- I missed the fact that `VariantBuilder` is the truly top-level builder, and the array/object builders both nest around it. There's still the problem that variant can't impl From arrays/objects, but I guess we could add a call to create a new object/array builder from an existing one, in order to achieve nesting?



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);

Review Comment:
   Should we validate the scale before pushing it?



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {

Review Comment:
   nit, to match the variant spec:
   ```suggestion
       fn append_decimal4(&mut self, unscaled_value: i32, scale: u8) {
   ```
   (more below)



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;

Review Comment:
   probably don't need the 0xff mask if anyway casting to u8?



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());

Review Comment:
   It's a bit unfortunate we have to double-allocate strings. Ideally the dictionary could track `&str` backed by `dict_keys`, but I don't know how to manage mutability and lifetimes to achieve that...



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());
+                id
+            }
+        }
+    }
+
+    fn offset(&self) -> usize {
+        self.buffer.len()
+    }
+
+    /// Create an [`ArrayBuilder`] for creating [`Variant::Array`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_array(&mut self) -> ArrayBuilder {
+        ArrayBuilder::new(self)
+    }
+
+    /// Create an [`ObjectBuilder`] for creating [`Variant::Object`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_object(&mut self) -> ObjectBuilder {
+        ObjectBuilder::new(self)
+    }
+
+    pub fn finish(self) -> (Vec<u8>, Vec<u8>) {

Review Comment:
   I don't think this approach can be easily extended to allow nested variants? 



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())

Review Comment:
   Update: Looks like [from_ymd_opt](https://docs.rs/chrono/latest/chrono/naive/struct.NaiveDate.html#method.from_ymd_opt) is `const`; we could define+use a constant so a failed `unwrap` produces a compilation failure instead of a runtime panic.



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());
+                id
+            }
+        }
+    }
+
+    fn offset(&self) -> usize {
+        self.buffer.len()
+    }
+
+    /// Create an [`ArrayBuilder`] for creating [`Variant::Array`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_array(&mut self) -> ArrayBuilder {
+        ArrayBuilder::new(self)
+    }
+
+    /// Create an [`ObjectBuilder`] for creating [`Variant::Object`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_object(&mut self) -> ObjectBuilder {

Review Comment:
   Arrays and objects are tricky to build incrementally. The value offset and field id arrays require either knowing the number of elements/fields to be created in advance (and then worrying about what happens if the caller builds too many/few entries afterward), or building the arrays in separate storage and then moving an arbitrarily large number of buffered bytes to make room for the them after the fact. 
   
   I guess this PR takes the latter approach, but for deeply nested data that will lead to something that looks like quadratic cost -- O(num_bytes * depth) -- as the deepest fields get moved repeatedly while finishing each of the parent builders in turn.
   
   Not sure the best solution here...



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());
+                id
+            }
+        }
+    }
+
+    fn offset(&self) -> usize {
+        self.buffer.len()
+    }
+
+    /// Create an [`ArrayBuilder`] for creating [`Variant::Array`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_array(&mut self) -> ArrayBuilder {
+        ArrayBuilder::new(self)
+    }
+
+    /// Create an [`ObjectBuilder`] for creating [`Variant::Object`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_object(&mut self) -> ObjectBuilder {
+        ObjectBuilder::new(self)
+    }
+
+    pub fn finish(self) -> (Vec<u8>, Vec<u8>) {
+        let nkeys = self.dict_keys.len();
+
+        // Calculate metadata size
+        let total_dict_size: usize = self.dict_keys.iter().map(|k| k.len()).sum();
+
+        // Determine appropriate offset size based on the larger of dict size or total string size
+        let max_offset = std::cmp::max(total_dict_size, nkeys);
+        let offset_size = int_size(max_offset);
+
+        let offset_start = 1 + offset_size as usize;
+        let string_start = offset_start + (nkeys + 1) * offset_size as usize;
+        let metadata_size = string_start + total_dict_size;
+
+        // Pre-allocate exact size to avoid reallocations
+        let mut metadata = vec![0u8; metadata_size];
+
+        // Write header: version=1, not sorted, with calculated offset_size
+        metadata[0] = 0x01 | ((offset_size - 1) << 6);
+
+        // Write dictionary size
+        write_offset(&mut metadata[1..], nkeys, offset_size);
+
+        // Write offsets and string data
+        let mut cur_offset = 0;
+        for (i, key) in self.dict_keys.iter().enumerate() {
+            write_offset(
+                &mut metadata[offset_start + i * offset_size as usize..],
+                cur_offset,
+                offset_size,
+            );
+            let start = string_start + cur_offset;
+            metadata[start..start + key.len()].copy_from_slice(key.as_bytes());
+            cur_offset += key.len();
+        }
+        // Write final offset
+        write_offset(
+            &mut metadata[offset_start + nkeys * offset_size as usize..],
+            cur_offset,
+            offset_size,
+        );
+
+        (metadata, self.buffer)
+    }
+
+    pub fn append_value<T: Into<Variant<'static, 'static>>>(&mut self, value: T) {
+        let variant = value.into();
+        match variant {
+            Variant::Null => self.append_null(),
+            Variant::BooleanTrue => self.append_bool(true),
+            Variant::BooleanFalse => self.append_bool(false),
+            Variant::Int8(v) => self.append_int8(v),
+            Variant::Int16(v) => self.append_int16(v),
+            Variant::Int32(v) => self.append_int32(v),
+            Variant::Int64(v) => self.append_int64(v),
+            Variant::Date(v) => self.append_date(v),
+            Variant::TimestampMicros(v) => self.append_timestamp_micros(v),
+            Variant::TimestampNtzMicros(v) => self.append_timestamp_ntz_micros(v),
+            Variant::Decimal4 { integer, scale } => self.append_decimal4(integer, scale),
+            Variant::Decimal8 { integer, scale } => self.append_decimal8(integer, scale),
+            Variant::Decimal16 { integer, scale } => self.append_decimal16(integer, scale),
+            Variant::Float(v) => self.append_float(v),
+            Variant::Double(v) => self.append_double(v),
+            Variant::Binary(v) => self.append_binary(v),
+            Variant::String(s) | Variant::ShortString(s) => self.append_string(s),

Review Comment:
   this will make three times deciding between short vs. long string? one to make the input, another here, and a third to consume it? Any way we could make this more direct/efficient?



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);

Review Comment:
   If we're truncating the reported length to u32, should we also truncate the slice we extend from? That would produce an incorrect but "safe" result.
   
   Actually tho... the buffer's max allocation size is isize::MAX, so we probably need a length check to avoid panic?
   
   Allocation panics in general would seem to be a problem... how can code that aims to be panic-free defend itself?



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2149608322


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());

Review Comment:
   Maybe the dictionary could be a map to `u32` (an index into the relevant entry in the `dict_keys` Vec) instead of a String



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2153231316


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());
+                id
+            }
+        }
+    }
+
+    fn offset(&self) -> usize {
+        self.buffer.len()
+    }
+
+    /// Create an [`ArrayBuilder`] for creating [`Variant::Array`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_array(&mut self) -> ArrayBuilder {
+        ArrayBuilder::new(self)
+    }
+
+    /// Create an [`ObjectBuilder`] for creating [`Variant::Object`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_object(&mut self) -> ObjectBuilder {

Review Comment:
   Tracking in 
   - https://github.com/apache/arrow-rs/issues/7699



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb merged PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "scovich (via GitHub)" <gi...@apache.org>.
scovich commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2150771544


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());

Review Comment:
   Storing offset pairs would also work really nicely if we decide not to sort+dedup the `metadata` field entries (**), because then the `Vec<u8>` can simply be copied as-is to its final home. 
   
   (**) Sort+dedup is actually quite some work, because it requires finding and rewriting all field ids scattered through the `value` bytes. So it would almost certainly be a second step (either a preliminary pass before we actually generate the variant value bytes, or as a fix-up pass afterward to rewrite field ids)



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());

Review Comment:
   Storing offset pairs directly would also work really nicely if we decide not to sort+dedup the `metadata` field entries (**), because then the `Vec<u8>` can simply be copied as-is to its final home. 
   
   (**) Sort+dedup is actually quite some work, because it requires finding and rewriting all field ids scattered through the `value` bytes. So it would almost certainly be a second step (either a preliminary pass before we actually generate the variant value bytes, or as a fix-up pass afterward to rewrite field ids)



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "scovich (via GitHub)" <gi...@apache.org>.
scovich commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2150766149


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());

Review Comment:
   That could work. Also, we ultimately need a single packed array of utf8 bytes; so we might want to consider storing the same kinds of offsets that the actual variant metadata stores, where each string's bytes are found in the range `offset[i]..offset[i+1]`. That shouldn't be any more expensive to access (sort) vs. an array of (heap-allocated) strings?



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#issuecomment-2981963862

   All right -- I have filed a bunch of follow on tickets, and attached them to 
   - https://github.com/apache/arrow-rs/issues/6736
   
   Once I get the CI to pass I'll plan to merge this PR
   
   Thanks again @PinkCrow007 and @scovich 


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2153174807


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);

Review Comment:
   - Tracking in https://github.com/apache/arrow-rs/issues/7697



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#discussion_r2153111190


##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);

Review Comment:
   We probably should (or at least have optional checking 🤔 )



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());
+                id
+            }
+        }
+    }
+
+    fn offset(&self) -> usize {
+        self.buffer.len()
+    }
+
+    /// Create an [`ArrayBuilder`] for creating [`Variant::Array`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_array(&mut self) -> ArrayBuilder {
+        ArrayBuilder::new(self)
+    }
+
+    /// Create an [`ObjectBuilder`] for creating [`Variant::Object`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_object(&mut self) -> ObjectBuilder {
+        ObjectBuilder::new(self)
+    }
+
+    pub fn finish(self) -> (Vec<u8>, Vec<u8>) {

Review Comment:
   > There's still the problem that variant can't impl From arrays/objects, but I guess we could add a call to create a new object/array builder from an existing one, in order to achieve nesting?
   
   I am not sure we will be able to implement a general purpose `From` impl for native rust slices or objects. We could potentially offer a `serde` style thing (like `serde_json` but `serde_variant` 🤔 )



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,737 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+const UNIX_EPOCH_DATE: chrono::NaiveDate = chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = (value >> (i * 8)) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Some(Variant::ShortString("Jiaying"))
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Some(Variant::ShortString("Li"))
+/// );
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::List(variant_list) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_list.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_list.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_list.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value.signed_duration_since(UNIX_EPOCH_DATE).num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());
+                id
+            }
+        }
+    }
+
+    fn offset(&self) -> usize {
+        self.buffer.len()
+    }
+
+    /// Create an [`ArrayBuilder`] for creating [`Variant::Array`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_array(&mut self) -> ArrayBuilder {
+        ArrayBuilder::new(self)
+    }
+
+    /// Create an [`ObjectBuilder`] for creating [`Variant::Object`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_object(&mut self) -> ObjectBuilder {
+        ObjectBuilder::new(self)
+    }
+
+    pub fn finish(self) -> (Vec<u8>, Vec<u8>) {
+        let nkeys = self.dict_keys.len();
+
+        // Calculate metadata size
+        let total_dict_size: usize = self.dict_keys.iter().map(|k| k.len()).sum();
+
+        // Determine appropriate offset size based on the larger of dict size or total string size
+        let max_offset = std::cmp::max(total_dict_size, nkeys);
+        let offset_size = int_size(max_offset);
+
+        let offset_start = 1 + offset_size as usize;
+        let string_start = offset_start + (nkeys + 1) * offset_size as usize;
+        let metadata_size = string_start + total_dict_size;
+
+        // Pre-allocate exact size to avoid reallocations
+        let mut metadata = vec![0u8; metadata_size];
+
+        // Write header: version=1, not sorted, with calculated offset_size
+        metadata[0] = 0x01 | ((offset_size - 1) << 6);
+
+        // Write dictionary size
+        write_offset(&mut metadata[1..], nkeys, offset_size);
+
+        // Write offsets and string data
+        let mut cur_offset = 0;
+        for (i, key) in self.dict_keys.iter().enumerate() {
+            write_offset(
+                &mut metadata[offset_start + i * offset_size as usize..],
+                cur_offset,
+                offset_size,
+            );
+            let start = string_start + cur_offset;
+            metadata[start..start + key.len()].copy_from_slice(key.as_bytes());
+            cur_offset += key.len();
+        }
+        // Write final offset
+        write_offset(
+            &mut metadata[offset_start + nkeys * offset_size as usize..],
+            cur_offset,
+            offset_size,
+        );
+
+        (metadata, self.buffer)
+    }
+
+    pub fn append_value<T: Into<Variant<'static, 'static>>>(&mut self, value: T) {
+        let variant = value.into();
+        match variant {
+            Variant::Null => self.append_null(),
+            Variant::BooleanTrue => self.append_bool(true),
+            Variant::BooleanFalse => self.append_bool(false),
+            Variant::Int8(v) => self.append_int8(v),
+            Variant::Int16(v) => self.append_int16(v),
+            Variant::Int32(v) => self.append_int32(v),
+            Variant::Int64(v) => self.append_int64(v),
+            Variant::Date(v) => self.append_date(v),
+            Variant::TimestampMicros(v) => self.append_timestamp_micros(v),
+            Variant::TimestampNtzMicros(v) => self.append_timestamp_ntz_micros(v),
+            Variant::Decimal4 { integer, scale } => self.append_decimal4(integer, scale),
+            Variant::Decimal8 { integer, scale } => self.append_decimal8(integer, scale),
+            Variant::Decimal16 { integer, scale } => self.append_decimal16(integer, scale),
+            Variant::Float(v) => self.append_float(v),
+            Variant::Double(v) => self.append_double(v),
+            Variant::Binary(v) => self.append_binary(v),
+            Variant::String(s) | Variant::ShortString(s) => self.append_string(s),
+            Variant::Object(_) | Variant::List(_) => {
+                unreachable!("Object and Array variants cannot be created through Into<Variant>")

Review Comment:
   FWIW I think you can append a variant object. I will write a test / file a ticket



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);

Review Comment:
   I think we should throw an error if value.len() > u32::max



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());
+                id
+            }
+        }
+    }
+
+    fn offset(&self) -> usize {
+        self.buffer.len()
+    }
+
+    /// Create an [`ArrayBuilder`] for creating [`Variant::Array`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_array(&mut self) -> ArrayBuilder {
+        ArrayBuilder::new(self)
+    }
+
+    /// Create an [`ObjectBuilder`] for creating [`Variant::Object`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_object(&mut self) -> ObjectBuilder {
+        ObjectBuilder::new(self)
+    }
+
+    pub fn finish(self) -> (Vec<u8>, Vec<u8>) {
+        let nkeys = self.dict_keys.len();
+
+        // Calculate metadata size
+        let total_dict_size: usize = self.dict_keys.iter().map(|k| k.len()).sum();
+
+        // Determine appropriate offset size based on the larger of dict size or total string size
+        let max_offset = std::cmp::max(total_dict_size, nkeys);
+        let offset_size = int_size(max_offset);
+
+        let offset_start = 1 + offset_size as usize;
+        let string_start = offset_start + (nkeys + 1) * offset_size as usize;
+        let metadata_size = string_start + total_dict_size;
+
+        // Pre-allocate exact size to avoid reallocations
+        let mut metadata = vec![0u8; metadata_size];
+
+        // Write header: version=1, not sorted, with calculated offset_size
+        metadata[0] = 0x01 | ((offset_size - 1) << 6);
+
+        // Write dictionary size
+        write_offset(&mut metadata[1..], nkeys, offset_size);
+
+        // Write offsets and string data
+        let mut cur_offset = 0;
+        for (i, key) in self.dict_keys.iter().enumerate() {
+            write_offset(
+                &mut metadata[offset_start + i * offset_size as usize..],
+                cur_offset,
+                offset_size,
+            );
+            let start = string_start + cur_offset;
+            metadata[start..start + key.len()].copy_from_slice(key.as_bytes());
+            cur_offset += key.len();
+        }
+        // Write final offset
+        write_offset(
+            &mut metadata[offset_start + nkeys * offset_size as usize..],
+            cur_offset,
+            offset_size,
+        );
+
+        (metadata, self.buffer)
+    }
+
+    pub fn append_value<T: Into<Variant<'static, 'static>>>(&mut self, value: T) {

Review Comment:
   I did so in d7d144916e



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());
+                id
+            }
+        }
+    }
+
+    fn offset(&self) -> usize {
+        self.buffer.len()
+    }
+
+    /// Create an [`ArrayBuilder`] for creating [`Variant::Array`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_array(&mut self) -> ArrayBuilder {
+        ArrayBuilder::new(self)
+    }
+
+    /// Create an [`ObjectBuilder`] for creating [`Variant::Object`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_object(&mut self) -> ObjectBuilder {

Review Comment:
   Maybe the builder can leave room for the list length and then append the values, and then go back and update the length when the list is finsihed
   
   This would get tricky for building "large" lists as the length field may not be known upfront.
   
   we could also introduce potentially a functon like `new_large_object()` or something for callers to hint up front their object has many fields, and if they use `new_object` but push too many values fallback to copying



##########
parquet-variant/src/builder.rs:
##########
@@ -0,0 +1,757 @@
+// 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.
+use crate::decoder::{VariantBasicType, VariantPrimitiveType};
+use crate::Variant;
+use std::collections::HashMap;
+
+const BASIC_TYPE_BITS: u8 = 2;
+const MAX_SHORT_STRING_SIZE: usize = 0x3F;
+
+fn primitive_header(primitive_type: VariantPrimitiveType) -> u8 {
+    (primitive_type as u8) << 2 | VariantBasicType::Primitive as u8
+}
+
+fn short_string_header(len: usize) -> u8 {
+    (len as u8) << 2 | VariantBasicType::ShortString as u8
+}
+
+fn array_header(large: bool, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Array as u8
+}
+
+fn object_header(large: bool, id_size: u8, offset_size: u8) -> u8 {
+    let large_bit = if large { 1 } else { 0 };
+    (large_bit << (BASIC_TYPE_BITS + 4))
+        | ((id_size - 1) << (BASIC_TYPE_BITS + 2))
+        | ((offset_size - 1) << BASIC_TYPE_BITS)
+        | VariantBasicType::Object as u8
+}
+
+fn int_size(v: usize) -> u8 {
+    match v {
+        0..=0xFF => 1,
+        0x100..=0xFFFF => 2,
+        0x10000..=0xFFFFFF => 3,
+        _ => 4,
+    }
+}
+
+/// Write little-endian integer to buffer
+fn write_offset(buf: &mut [u8], value: usize, nbytes: u8) {
+    for i in 0..nbytes {
+        buf[i as usize] = ((value >> (i * 8)) & 0xFF) as u8;
+    }
+}
+
+/// Helper to make room for header by moving data
+fn make_room_for_header(buffer: &mut Vec<u8>, start_pos: usize, header_size: usize) {
+    let current_len = buffer.len();
+    buffer.resize(current_len + header_size, 0);
+
+    let src_start = start_pos;
+    let src_end = current_len;
+    let dst_start = start_pos + header_size;
+
+    buffer.copy_within(src_start..src_end, dst_start);
+}
+
+/// Builder for [`Variant`] values
+///
+/// # Example: create a Primitive Int8
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// builder.append_value(Variant::Int8(42));
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// assert_eq!(variant, Variant::Int8(42));
+/// ```
+///
+/// # Example: Create an Object
+/// This example shows how to create an object with two fields:
+/// ```json
+/// {
+///  "first_name": "Jiaying",
+///  "last_name": "Li"
+/// }
+/// ```
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+/// let mut builder = VariantBuilder::new();
+/// // Create an object builder that will write fields to the object
+/// let mut object_builder = builder.new_object();
+/// object_builder.append_value("first_name", "Jiaying");
+/// object_builder.append_value("last_name", "Li");
+/// object_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Object(variant_object) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// /* TODO: uncomment this, but now VariantObject:field is not implemented
+/// assert_eq!(
+///   variant_object.field("first_name").unwrap(),
+///   Variant::String("Jiaying")
+/// );
+/// assert_eq!(
+///   variant_object.field("last_name").unwrap(),
+///   Variant::String("Li")
+/// );
+/// */
+/// ```
+///
+/// # Example: Create an Array
+///
+/// This example shows how to create an array of integers: `[1, 2, 3]`.
+/// ```
+///  # use parquet_variant::{Variant, VariantBuilder, VariantMetadata};
+///  let mut builder = VariantBuilder::new();
+///  // Create an array builder that will write elements to the array
+///  let mut array_builder = builder.new_array();
+///  array_builder.append_value(1i8);
+///  array_builder.append_value(2i8);
+///  array_builder.append_value(3i8);
+///  array_builder.finish();
+/// // Finish the builder to get the metadata and value
+/// let (metadata, value) = builder.finish();
+/// // use the Variant API to verify the result
+/// let metadata = VariantMetadata::try_new(&metadata).unwrap();
+/// let variant = Variant::try_new(&metadata, &value).unwrap();
+/// let Variant::Array(variant_array) = variant else {
+///   panic!("unexpected variant type")
+/// };
+/// // Verify the array contents
+/// assert_eq!(variant_array.get(0).unwrap(), Variant::Int8(1));
+/// assert_eq!(variant_array.get(1).unwrap(), Variant::Int8(2));
+/// assert_eq!(variant_array.get(2).unwrap(), Variant::Int8(3));
+/// ```
+///
+/// # Example: Array of objects
+///
+/// THis example shows how to create an array of objects:
+/// ```json
+/// [
+///  {
+///   "first_name": "Jiaying",
+///  "last_name": "Li"
+/// },
+///   {
+///    "first_name": "Malthe",
+///    "last_name": "Karbo"
+/// }
+/// ```
+///
+/// TODO
+///
+pub struct VariantBuilder {
+    buffer: Vec<u8>,
+    dict: HashMap<String, u32>,
+    dict_keys: Vec<String>,
+}
+
+impl VariantBuilder {
+    pub fn new() -> Self {
+        Self {
+            buffer: Vec::new(),
+            dict: HashMap::new(),
+            dict_keys: Vec::new(),
+        }
+    }
+
+    fn append_null(&mut self) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Null));
+    }
+
+    fn append_bool(&mut self, value: bool) {
+        let primitive_type = if value {
+            VariantPrimitiveType::BooleanTrue
+        } else {
+            VariantPrimitiveType::BooleanFalse
+        };
+        self.buffer.push(primitive_header(primitive_type));
+    }
+
+    fn append_int8(&mut self, value: i8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int8));
+        self.buffer.push(value as u8);
+    }
+
+    fn append_int16(&mut self, value: i16) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int16));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int32(&mut self, value: i32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int32));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_int64(&mut self, value: i64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Int64));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_float(&mut self, value: f32) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Float));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_double(&mut self, value: f64) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Double));
+        self.buffer.extend_from_slice(&value.to_le_bytes());
+    }
+
+    fn append_date(&mut self, value: chrono::NaiveDate) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Date));
+        let days_since_epoch = value
+            .signed_duration_since(chrono::NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
+            .num_days() as i32;
+        self.buffer
+            .extend_from_slice(&days_since_epoch.to_le_bytes());
+    }
+
+    fn append_timestamp_micros(&mut self, value: chrono::DateTime<chrono::Utc>) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampMicros));
+        let micros = value.timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_timestamp_ntz_micros(&mut self, value: chrono::NaiveDateTime) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::TimestampNtzMicros));
+        let micros = value.and_utc().timestamp_micros();
+        self.buffer.extend_from_slice(&micros.to_le_bytes());
+    }
+
+    fn append_decimal4(&mut self, integer: i32, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal4));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal8(&mut self, integer: i64, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal8));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_decimal16(&mut self, integer: i128, scale: u8) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Decimal16));
+        self.buffer.push(scale);
+        self.buffer.extend_from_slice(&integer.to_le_bytes());
+    }
+
+    fn append_binary(&mut self, value: &[u8]) {
+        self.buffer
+            .push(primitive_header(VariantPrimitiveType::Binary));
+        self.buffer
+            .extend_from_slice(&(value.len() as u32).to_le_bytes());
+        self.buffer.extend_from_slice(value);
+    }
+
+    fn append_string(&mut self, value: &str) {
+        if value.len() <= MAX_SHORT_STRING_SIZE {
+            self.buffer.push(short_string_header(value.len()));
+            self.buffer.extend_from_slice(value.as_bytes());
+        } else {
+            self.buffer
+                .push(primitive_header(VariantPrimitiveType::String));
+            self.buffer
+                .extend_from_slice(&(value.len() as u32).to_le_bytes());
+            self.buffer.extend_from_slice(value.as_bytes());
+        }
+    }
+
+    /// Add key to dictionary, return its ID
+    fn add_key(&mut self, key: &str) -> u32 {
+        use std::collections::hash_map::Entry;
+        match self.dict.entry(key.to_string()) {
+            Entry::Occupied(entry) => *entry.get(),
+            Entry::Vacant(entry) => {
+                let id = self.dict_keys.len() as u32;
+                entry.insert(id);
+                self.dict_keys.push(key.to_string());
+                id
+            }
+        }
+    }
+
+    fn offset(&self) -> usize {
+        self.buffer.len()
+    }
+
+    /// Create an [`ArrayBuilder`] for creating [`Variant::Array`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_array(&mut self) -> ArrayBuilder {
+        ArrayBuilder::new(self)
+    }
+
+    /// Create an [`ObjectBuilder`] for creating [`Variant::Object`] values.
+    ///
+    /// See the examples on [`VariantBuilder`] for usage.
+    pub fn new_object(&mut self) -> ObjectBuilder {
+        ObjectBuilder::new(self)
+    }
+
+    pub fn finish(self) -> (Vec<u8>, Vec<u8>) {
+        let nkeys = self.dict_keys.len();
+
+        // Calculate metadata size
+        let total_dict_size: usize = self.dict_keys.iter().map(|k| k.len()).sum();
+
+        // Determine appropriate offset size based on the larger of dict size or total string size
+        let max_offset = std::cmp::max(total_dict_size, nkeys);
+        let offset_size = int_size(max_offset);
+
+        let offset_start = 1 + offset_size as usize;
+        let string_start = offset_start + (nkeys + 1) * offset_size as usize;
+        let metadata_size = string_start + total_dict_size;
+
+        // Pre-allocate exact size to avoid reallocations
+        let mut metadata = vec![0u8; metadata_size];
+
+        // Write header: version=1, not sorted, with calculated offset_size
+        metadata[0] = 0x01 | ((offset_size - 1) << 6);
+
+        // Write dictionary size
+        write_offset(&mut metadata[1..], nkeys, offset_size);
+
+        // Write offsets and string data
+        let mut cur_offset = 0;
+        for (i, key) in self.dict_keys.iter().enumerate() {
+            write_offset(
+                &mut metadata[offset_start + i * offset_size as usize..],
+                cur_offset,
+                offset_size,
+            );
+            let start = string_start + cur_offset;
+            metadata[start..start + key.len()].copy_from_slice(key.as_bytes());
+            cur_offset += key.len();
+        }
+        // Write final offset
+        write_offset(
+            &mut metadata[offset_start + nkeys * offset_size as usize..],
+            cur_offset,
+            offset_size,
+        );
+
+        (metadata, self.buffer)
+    }
+
+    pub fn append_value<T: Into<Variant<'static, 'static>>>(&mut self, value: T) {
+        let variant = value.into();
+        match variant {
+            Variant::Null => self.append_null(),
+            Variant::BooleanTrue => self.append_bool(true),
+            Variant::BooleanFalse => self.append_bool(false),
+            Variant::Int8(v) => self.append_int8(v),
+            Variant::Int16(v) => self.append_int16(v),
+            Variant::Int32(v) => self.append_int32(v),
+            Variant::Int64(v) => self.append_int64(v),
+            Variant::Date(v) => self.append_date(v),
+            Variant::TimestampMicros(v) => self.append_timestamp_micros(v),
+            Variant::TimestampNtzMicros(v) => self.append_timestamp_ntz_micros(v),
+            Variant::Decimal4 { integer, scale } => self.append_decimal4(integer, scale),
+            Variant::Decimal8 { integer, scale } => self.append_decimal8(integer, scale),
+            Variant::Decimal16 { integer, scale } => self.append_decimal16(integer, scale),
+            Variant::Float(v) => self.append_float(v),
+            Variant::Double(v) => self.append_double(v),
+            Variant::Binary(v) => self.append_binary(v),
+            Variant::String(s) | Variant::ShortString(s) => self.append_string(s),

Review Comment:
   I think it would be nice to have a `self.append_short_string` and `self.append_string` and then call the appropriate ones. We could have `self.append_short_string` return an error potentially as well if the string was too long



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Initial Builder API for Creating Variant Values [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #7653:
URL: https://github.com/apache/arrow-rs/pull/7653#issuecomment-2970983400

   It also looks like there are some CI failures on this PR:
   * RAT means you have to put the apache license at the start of the file
   * Clippy means run `cargo clippy -p parquet-variant`
   * The test seems to be failing when you run `cargo test -p parquet-variant`


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org