Skip to main content

arrow_ipc/
writer.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! Arrow IPC File and Stream Writers
6//!
7//! # Notes
8//!
9//! [`FileWriter`] and [`StreamWriter`] have similar interfaces,
10//! however the [`FileWriter`] expects a reader that supports [`Seek`]ing
11//!
12//! [`Seek`]: std::io::Seek
13
14use std::cmp::min;
15use std::collections::HashMap;
16use std::io::{BufWriter, Write};
17use std::mem::size_of;
18use std::sync::Arc;
19
20use flatbuffers::FlatBufferBuilder;
21
22use arrow_array::cast::*;
23use arrow_array::types::{Int16Type, Int32Type, Int64Type, RunEndIndexType};
24use arrow_array::*;
25use arrow_buffer::{ArrowNativeType, Buffer, MutableBuffer, ToByteSlice};
26use arrow_data::{ArrayData, ArrayDataBuilder, BufferSpec, layout};
27use arrow_schema::*;
28
29use crate::CONTINUATION_MARKER;
30use crate::compression::{CompressionCodec, Lz4BlockSize};
31#[expect(deprecated)]
32pub use crate::compression::{CompressionContext, IpcWriteContext};
33use crate::convert::IpcSchemaEncoder;
34
35/// IPC write options used to control the behaviour of the [`IpcDataGenerator`]
36#[derive(Debug, Clone)]
37pub struct IpcWriteOptions {
38    /// Write padding after memory buffers to this multiple of bytes.
39    /// Must be 8, 16, 32, or 64 - defaults to 64.
40    alignment: u8,
41    /// The legacy format is for releases before 0.15.0, and uses metadata V4
42    write_legacy_ipc_format: bool,
43    /// The metadata version to write. The Rust IPC writer supports V4+
44    ///
45    /// *Default versions per crate*
46    ///
47    /// When creating the default IpcWriteOptions, the following metadata versions are used:
48    ///
49    /// version 2.0.0: V4, with legacy format enabled
50    /// version 4.0.0: V5
51    metadata_version: crate::MetadataVersion,
52    /// Compression, if desired. Will result in a runtime error
53    /// if the corresponding feature is not enabled
54    batch_compression_type: Option<crate::CompressionType>,
55    // Compression level
56    batch_compression_level: Option<i32>,
57    /// The lz4 frame block size; `None` selects 256 KiB.
58    batch_lz4_block_size: Option<Lz4BlockSize>,
59    /// How to handle updating dictionaries in IPC messages
60    dictionary_handling: DictionaryHandling,
61}
62
63/// A single buffer segment ready to be written to the output stream.
64///
65/// For the uncompressed path the original Arc-backed [`Buffer`] is stored
66/// directly (zero copy). For the compressed path the compressed bytes are
67/// owned by a scratch `Vec<u8>`.
68enum EncodedBuffer {
69    /// Uncompressed: Arc-backed reference to the original array buffer.
70    Raw(Buffer),
71    /// Compressed: owned scratch bytes produced by the codec.
72    Compressed(Vec<u8>),
73}
74
75impl EncodedBuffer {
76    fn as_slice(&self) -> &[u8] {
77        match self {
78            EncodedBuffer::Raw(b) => b.as_slice(),
79            EncodedBuffer::Compressed(v) => v.as_slice(),
80        }
81    }
82
83    fn len(&self) -> usize {
84        match self {
85            EncodedBuffer::Raw(b) => b.len(),
86            EncodedBuffer::Compressed(v) => v.len(),
87        }
88    }
89}
90/// Accumulates the IPC metadata produced by [`write_array_data`].
91///
92/// `nodes` and `buffers` are serialised into the flatbuffer `RecordBatch` (or `DictionaryBatch`)
93/// header. The companion [`IpcBodySink`] holds the actual encoded bytes.
94#[derive(Default)]
95struct IpcMetadataBuilder {
96    nodes: Vec<crate::FieldNode>,
97    buffers: Vec<crate::Buffer>,
98}
99
100/// Destination for the raw Arrow data bytes (the IPC message body) produced by [`write_array_data`].
101///
102/// The companion [`IpcMetadataBuilder`] accumulates the flatbuffer metadata
103/// (offset + length of each buffer in the body); together they form a complete IPC message.
104enum IpcBodySink<'a> {
105    /// Serialize buffer bytes (with padding) into a contiguous byte vec.
106    Write(&'a mut Vec<u8>),
107    /// Accumulate pre-encoded buffer segments for deferred zero-copy streaming.
108    Collect(&'a mut Vec<EncodedBuffer>),
109}
110impl IpcBodySink<'_> {
111    /// Writes the encoded buffer to the sink.
112    pub fn write(&mut self, pad_len: usize, buffer: EncodedBuffer) {
113        match self {
114            IpcBodySink::Write(vec) => {
115                vec.extend_from_slice(buffer.as_slice());
116                vec.extend_from_slice(&PADDING[..pad_len]);
117            }
118            IpcBodySink::Collect(vec) => {
119                vec.push(buffer);
120            }
121        }
122    }
123}
124
125struct MetadataLayout {
126    padded_header_len: usize,
127    padded_metadata_len: usize,
128    metadata_padding: usize,
129}
130
131impl MetadataLayout {
132    /// Lays out the header of a message that starts `offset` bytes past an alignment
133    /// boundary, padding the metadata so that the header ends on the next boundary.
134    fn new(offset: usize, metadata_len: usize, write_options: &IpcWriteOptions) -> MetadataLayout {
135        let prefix_size = if write_options.write_legacy_ipc_format {
136            4
137        } else {
138            8
139        };
140        let alignment_mask = usize::from(write_options.alignment - 1);
141        let padded_header_len =
142            ((offset + metadata_len + prefix_size + alignment_mask) & !alignment_mask) - offset;
143        let padded_metadata_len = padded_header_len - prefix_size;
144        let metadata_padding = padded_metadata_len - metadata_len;
145
146        MetadataLayout {
147            padded_header_len,
148            padded_metadata_len,
149            metadata_padding,
150        }
151    }
152}
153
154/// Destination-specific byte writing for a framed IPC message.
155///
156/// The default owned-buffer methods borrow their bytes and call `write_slice`,
157/// which can copy the data. Sink implementations that can take ownership of
158/// generated bytes should override `write_vec` or `write_encoded_buffer`.
159trait IpcMessageSink {
160    fn write_slice(&mut self, bytes: &[u8]) -> Result<(), ArrowError>;
161
162    fn write_vec(&mut self, bytes: Vec<u8>) -> Result<(), ArrowError> {
163        self.write_slice(&bytes)
164    }
165
166    fn write_encoded_buffer(&mut self, buffer: EncodedBuffer) -> Result<(), ArrowError> {
167        self.write_slice(buffer.as_slice())
168    }
169}
170
171/// Shared IPC framing helpers for [`IpcMessageSink`].
172trait IpcMessageSinkExt: IpcMessageSink {
173    fn write_padding(&mut self, len: usize) -> Result<(), ArrowError> {
174        self.write_slice(&PADDING[..len])
175    }
176
177    /// Writes the IPC continuation marker and metadata length prefix.
178    fn write_continuation(
179        &mut self,
180        write_options: &IpcWriteOptions,
181        metadata_len: i32,
182    ) -> Result<(), ArrowError> {
183        let mut buffer = [0; 8];
184        let len = match write_options.metadata_version {
185            crate::MetadataVersion::V1
186            | crate::MetadataVersion::V2
187            | crate::MetadataVersion::V3 => {
188                unreachable!("Options with the metadata version cannot be created")
189            }
190            crate::MetadataVersion::V4 => {
191                let metadata_len_bytes = metadata_len.to_le_bytes();
192                if !write_options.write_legacy_ipc_format {
193                    // v0.15.0 format
194                    buffer[..4].copy_from_slice(&CONTINUATION_MARKER);
195                    buffer[4..].copy_from_slice(&metadata_len_bytes);
196                    8
197                } else {
198                    buffer[..4].copy_from_slice(&metadata_len_bytes);
199                    4
200                }
201            }
202            crate::MetadataVersion::V5 => {
203                buffer[..4].copy_from_slice(&CONTINUATION_MARKER);
204                buffer[4..].copy_from_slice(&metadata_len.to_le_bytes());
205                8
206            }
207            z => panic!("Unsupported crate::MetadataVersion {z:?}"),
208        };
209        self.write_slice(&buffer[..len])
210    }
211
212    fn write_body_data(&mut self, data: Vec<u8>, alignment: u8) -> Result<usize, ArrowError> {
213        let len = data.len();
214        let pad_len = pad_to_alignment(alignment, len);
215        self.write_vec(data)?;
216        self.write_padding(pad_len)?;
217        Ok(len + pad_len)
218    }
219
220    /// Writes an already encoded IPC message with optional contiguous body data.
221    ///
222    /// This is used for schema and dictionary messages represented by [`EncodedData`].
223    /// The message starts `offset` bytes past an alignment boundary of the output.
224    /// Returns the padded metadata length and body length written.
225    fn write_encoded_data(
226        &mut self,
227        encoded: EncodedData,
228        write_options: &IpcWriteOptions,
229        offset: usize,
230    ) -> Result<(usize, usize), ArrowError> {
231        let arrow_data_len = encoded.arrow_data.len();
232        if !arrow_data_len.is_multiple_of(usize::from(write_options.alignment)) {
233            return Err(ArrowError::MemoryError(
234                "Arrow data not aligned".to_string(),
235            ));
236        }
237
238        let metadata = encoded.ipc_message;
239        let metadata_len = metadata.len();
240        let layout = MetadataLayout::new(offset, metadata_len, write_options);
241
242        self.write_continuation(write_options, layout.padded_metadata_len as i32)?;
243        self.write_vec(metadata)?;
244        self.write_padding(layout.metadata_padding)?;
245
246        let body_len = if arrow_data_len > 0 {
247            self.write_body_data(encoded.arrow_data, write_options.alignment)?
248        } else {
249            0
250        };
251
252        Ok((layout.padded_header_len, body_len))
253    }
254
255    /// Writes the IPC end-of-stream marker.
256    fn write_eos(&mut self, write_options: &IpcWriteOptions) -> Result<(), ArrowError> {
257        self.write_continuation(write_options, 0)?;
258        Ok(())
259    }
260}
261
262impl<T: IpcMessageSink + ?Sized> IpcMessageSinkExt for T {}
263
264/// Optional hot-path hook for record batch messages.
265trait IpcRecordBatchSink: IpcMessageSinkExt {
266    /// Writes a record batch (or dictionary batch) message from its encoded
267    /// metadata and body buffers.
268    ///
269    /// `metadata` is the raw flatbuffer [`crate::Message`] (without continuation
270    /// prefix), borrowed from the reused [`FlatBufferBuilder`]. The body buffers are
271    /// already materialized as [`EncodedBuffer`] segments, allowing buffer output to
272    /// preserve uncompressed Arrow buffers. They are drained out of
273    /// `encoded_buffers` so the caller can reuse its allocation.
274    ///
275    /// Each body buffer is padded to the alignment as it is written, so the body
276    /// needs no trailing padding.
277    ///
278    /// Returns the padded metadata length and body length written.
279    fn write_record_batch(
280        &mut self,
281        metadata: &[u8],
282        encoded_buffers: &mut Vec<EncodedBuffer>,
283        body_len: usize,
284        write_options: &IpcWriteOptions,
285    ) -> Result<(usize, usize), ArrowError> {
286        let alignment = write_options.alignment;
287        let layout = MetadataLayout::new(0, metadata.len(), write_options);
288
289        self.write_continuation(write_options, layout.padded_metadata_len as i32)?;
290        self.write_slice(metadata)?;
291        self.write_padding(layout.metadata_padding)?;
292        for enc in encoded_buffers.drain(..) {
293            let len = enc.len();
294            self.write_encoded_buffer(enc)?;
295            self.write_padding(pad_to_alignment(alignment, len))?;
296        }
297
298        Ok((layout.padded_header_len, body_len))
299    }
300}
301
302impl<W> IpcMessageSink for W
303where
304    W: Write,
305{
306    fn write_slice(&mut self, bytes: &[u8]) -> Result<(), ArrowError> {
307        if !bytes.is_empty() {
308            self.write_all(bytes)?;
309        }
310        Ok(())
311    }
312}
313
314impl<W> IpcRecordBatchSink for W
315where
316    W: Write,
317{
318    fn write_record_batch(
319        &mut self,
320        metadata: &[u8],
321        encoded_buffers: &mut Vec<EncodedBuffer>,
322        body_len: usize,
323        write_options: &IpcWriteOptions,
324    ) -> Result<(usize, usize), ArrowError> {
325        let alignment = write_options.alignment;
326        let layout = MetadataLayout::new(0, metadata.len(), write_options);
327
328        self.write_continuation(write_options, layout.padded_metadata_len as i32)?;
329        self.write_all(metadata)?;
330        self.write_all(&PADDING[..layout.metadata_padding])?;
331        for enc in encoded_buffers.iter_mut() {
332            self.write_all(enc.as_slice())?;
333            self.write_all(&PADDING[..pad_to_alignment(alignment, enc.len())])?;
334        }
335        // Clearing the buffers after the loop instead of draining the vec is
336        // a deliberate choice. It seems to perform much better on certain
337        // ARM chips.
338        //
339        // See: https://github.com/apache/arrow-rs/pull/10128#issuecomment-5406019272
340        encoded_buffers.clear();
341
342        Ok((layout.padded_header_len, body_len))
343    }
344}
345
346/// Accumulates complete framed IPC messages as ordered buffers.
347struct Buffers<'a> {
348    out: &'a mut Vec<Buffer>,
349}
350
351impl IpcMessageSink for Buffers<'_> {
352    fn write_slice(&mut self, bytes: &[u8]) -> Result<(), ArrowError> {
353        if !bytes.is_empty() {
354            self.out.push(Buffer::from(bytes));
355        }
356        Ok(())
357    }
358
359    fn write_vec(&mut self, bytes: Vec<u8>) -> Result<(), ArrowError> {
360        if !bytes.is_empty() {
361            self.out.push(Buffer::from(bytes));
362        }
363        Ok(())
364    }
365
366    fn write_encoded_buffer(&mut self, buffer: EncodedBuffer) -> Result<(), ArrowError> {
367        match buffer {
368            EncodedBuffer::Raw(buffer) => self.out.push(buffer),
369            EncodedBuffer::Compressed(bytes) => self.out.push(Buffer::from(bytes)),
370        }
371        Ok(())
372    }
373}
374
375impl IpcRecordBatchSink for Buffers<'_> {}
376
377/// Per-message sizes produced by [`IpcDataGenerator::write`].
378///
379/// [`FileWriter`] uses these to build the Block index entries required by the IPC footer for
380/// random-access reads.
381struct IpcWriteMetadata {
382    /// Per-dictionary `(padded_header_len, body_len)` for each dictionary batch written
383    /// before the record batch.
384    dictionary_block_sizes: Vec<(usize, usize)>,
385    /// Flatbuffer header size including continuation prefix and alignment padding.
386    padded_header_len: usize,
387    /// Total length of the record-batch body including alignment padding
388    body_len: usize,
389}
390
391impl IpcWriteOptions {
392    /// Configures compression when writing IPC files.
393    ///
394    /// Will result in a runtime error if the corresponding feature
395    /// is not enabled
396    pub fn try_with_compression(
397        mut self,
398        batch_compression_type: Option<crate::CompressionType>,
399    ) -> Result<Self, ArrowError> {
400        if matches!(batch_compression_type, Some(crate::CompressionType::ZSTD))
401            && self.batch_lz4_block_size.is_some()
402        {
403            return Err(ArrowError::InvalidArgumentError(
404                "lz4 frame block size does not apply to ZSTD compression".to_string(),
405            ));
406        }
407
408        self.batch_compression_type = batch_compression_type;
409
410        if self.batch_compression_type.is_some()
411            && self.metadata_version < crate::MetadataVersion::V5
412        {
413            return Err(ArrowError::InvalidArgumentError(
414                "Compression only supported in metadata v5 and above".to_string(),
415            ));
416        }
417        Ok(self)
418    }
419
420    /// Configures the compression level used when writing compressed IPC batches.
421    ///
422    /// Compression levels require metadata V5 or newer and are currently only
423    /// supported for ZSTD compression.
424    pub fn try_with_compression_level(
425        mut self,
426        batch_compression_level: Option<i32>,
427    ) -> Result<Self, ArrowError> {
428        self.batch_compression_level = batch_compression_level;
429
430        if self.batch_compression_level.is_some()
431            && self.metadata_version < crate::MetadataVersion::V5
432        {
433            return Err(ArrowError::InvalidArgumentError(
434                "Compression only supported in metadata v5 and above".to_string(),
435            ));
436        }
437
438        match (self.batch_compression_type, self.batch_compression_level) {
439            (Some(crate::CompressionType::ZSTD), Some(level)) => {
440                return self.check_zstd_level(level);
441            }
442            (Some(crate::CompressionType::LZ4_FRAME), Some(_)) => {
443                return Err(ArrowError::InvalidArgumentError(
444                    "LZ4 Frame compression does not support configurable compression levels"
445                        .to_string(),
446                ));
447            }
448            _ => {}
449        }
450
451        Ok(self)
452    }
453
454    /// Configures the lz4 frame block size used when compressing batches with
455    /// [`crate::CompressionType::LZ4_FRAME`].
456    ///
457    /// `None` restores the default of 256 KiB, which balances compression throughput against the
458    /// buffers retained by the reusable encoder. The LZ4 frame header can only describe the
459    /// block sizes 64 KiB, 256 KiB, 1 MiB and 4 MiB; any other value returns an
460    /// [`ArrowError::InvalidArgumentError`]. Like the other compression settings this requires
461    /// metadata version V5 or newer, and it has no effect when another compression codec is
462    /// selected.
463    pub fn try_with_lz4_block_size(
464        mut self,
465        block_size: Option<usize>,
466    ) -> Result<Self, ArrowError> {
467        let block_size = block_size.map(|bytes| {
468            Lz4BlockSize::from_bytes(bytes).ok_or_else(|| {
469                ArrowError::InvalidArgumentError(format!(
470                    "Unsupported lz4 block size {bytes}, must be one of 65536, 262144, 1048576, or 4194304 bytes"
471                ))
472            })
473        }).transpose()?;
474
475        if block_size.is_some() {
476            if self.metadata_version < crate::MetadataVersion::V5 {
477                return Err(ArrowError::InvalidArgumentError(
478                    "Compression only supported in metadata v5 and above".to_string(),
479                ));
480            }
481
482            if matches!(
483                self.batch_compression_type,
484                Some(crate::CompressionType::ZSTD)
485            ) {
486                return Err(ArrowError::InvalidArgumentError(
487                    "lz4 frame block size does not apply to ZSTD compression".to_string(),
488                ));
489            }
490        }
491
492        self.batch_lz4_block_size = block_size;
493        Ok(self)
494    }
495
496    /// The lz4 frame block size to compress with, in bytes.
497    pub(crate) fn lz4_block_size(&self) -> Lz4BlockSize {
498        self.batch_lz4_block_size.unwrap_or(Lz4BlockSize::DEFAULT)
499    }
500
501    #[cfg(not(feature = "zstd"))]
502    fn check_zstd_level(self, _level: i32) -> Result<Self, ArrowError> {
503        Err(ArrowError::InvalidArgumentError(
504            "zstd IPC compression requires the zstd feature".to_string(),
505        ))
506    }
507
508    #[cfg(feature = "zstd")]
509    fn check_zstd_level(self, level: i32) -> Result<Self, ArrowError> {
510        let range = zstd::compression_level_range();
511        if !range.contains(&level) {
512            return Err(ArrowError::InvalidArgumentError(format!(
513                "ZSTD compression level must be between {} and {}, got {}",
514                range.start(),
515                range.end(),
516                level,
517            )));
518        }
519
520        Ok(self)
521    }
522
523    /// Try to create IpcWriteOptions, checking for incompatible settings
524    pub fn try_new(
525        alignment: usize,
526        write_legacy_ipc_format: bool,
527        metadata_version: crate::MetadataVersion,
528    ) -> Result<Self, ArrowError> {
529        let alignment: u8 = match alignment {
530            8 => 8,
531            16 => 16,
532            32 => 32,
533            64 => 64,
534            _ => {
535                return Err(ArrowError::InvalidArgumentError(
536                    "Alignment should be 8, 16, 32, or 64.".to_string(),
537                ));
538            }
539        };
540        match metadata_version {
541            crate::MetadataVersion::V1
542            | crate::MetadataVersion::V2
543            | crate::MetadataVersion::V3 => Err(ArrowError::InvalidArgumentError(
544                "Writing IPC metadata version 3 and lower not supported".to_string(),
545            )),
546            crate::MetadataVersion::V4 => Ok(Self {
547                alignment,
548                write_legacy_ipc_format,
549                metadata_version,
550                batch_compression_type: None,
551                batch_compression_level: None,
552                batch_lz4_block_size: None,
553                dictionary_handling: DictionaryHandling::default(),
554            }),
555            crate::MetadataVersion::V5 => {
556                if write_legacy_ipc_format {
557                    Err(ArrowError::InvalidArgumentError(
558                        "Legacy IPC format only supported on metadata version 4".to_string(),
559                    ))
560                } else {
561                    Ok(Self {
562                        alignment,
563                        write_legacy_ipc_format,
564                        metadata_version,
565                        batch_compression_type: None,
566                        batch_compression_level: None,
567                        batch_lz4_block_size: None,
568                        dictionary_handling: DictionaryHandling::default(),
569                    })
570                }
571            }
572            z => Err(ArrowError::InvalidArgumentError(format!(
573                "Unsupported crate::MetadataVersion {z:?}"
574            ))),
575        }
576    }
577
578    /// Configure how dictionaries are handled in IPC messages
579    pub fn with_dictionary_handling(mut self, dictionary_handling: DictionaryHandling) -> Self {
580        self.dictionary_handling = dictionary_handling;
581        self
582    }
583}
584
585impl Default for IpcWriteOptions {
586    fn default() -> Self {
587        Self {
588            alignment: 64,
589            write_legacy_ipc_format: false,
590            metadata_version: crate::MetadataVersion::V5,
591            batch_compression_type: None,
592            batch_compression_level: None,
593            batch_lz4_block_size: None,
594            dictionary_handling: DictionaryHandling::default(),
595        }
596    }
597}
598
599#[derive(Debug, Default)]
600/// Handles low level details of encoding [`Array`] and [`Schema`] into the
601/// [Arrow IPC Format].
602///
603/// # Example
604/// ```
605/// # fn run() {
606/// # use std::sync::Arc;
607/// # use arrow_array::UInt64Array;
608/// # use arrow_array::RecordBatch;
609/// # use arrow_ipc::writer::{IpcWriteContext, DictionaryTracker, IpcDataGenerator, IpcWriteOptions};
610///
611/// // Create a record batch
612/// let batch = RecordBatch::try_from_iter(vec![
613///  ("col2", Arc::new(UInt64Array::from_iter([10, 23, 33])) as _)
614/// ]).unwrap();
615///
616/// // Error of dictionary ids are replaced.
617/// let error_on_replacement = true;
618/// let options = IpcWriteOptions::default();
619/// let mut dictionary_tracker = DictionaryTracker::new(error_on_replacement);
620///
621/// let mut ipc_write_context = IpcWriteContext::default();
622///
623/// // encode the batch into zero or more encoded dictionaries
624/// // and the data for the actual array.
625/// let data_gen = IpcDataGenerator::default();
626/// let (encoded_dictionaries, encoded_message) = data_gen
627///   .encode(&batch, &mut dictionary_tracker, &options, &mut ipc_write_context)
628///   .unwrap();
629/// # }
630/// ```
631///
632/// [Arrow IPC Format]: https://arrow.apache.org/docs/format/Columnar.html#serialization-and-interprocess-communication-ipc
633pub struct IpcDataGenerator {}
634
635/// A dictionary determined to need sending as a part of a record batch.
636struct DictionaryToEncode {
637    id: i64,
638    data: ArrayData,
639    is_delta: bool,
640}
641
642/// The result of encoding a record batch's body and flatbuffer `RecordBatch` table
643/// via [`IpcDataGenerator::encode_record_batch_data`].
644///
645/// The `RecordBatch` table is left in-progress in the caller's [`FlatBufferBuilder`];
646/// the caller wraps `record_batch` in a `Message` (directly for a record batch
647/// message, or inside a `DictionaryBatch` for a dictionary message).
648struct EncodedRecordBatchMeta {
649    /// In-progress flatbuffer offset of the `RecordBatch` table.
650    fb_offset: flatbuffers::WIPOffset<crate::RecordBatch<'static>>,
651    /// Total body length written to the sink (the sum of each buffer's encoded
652    /// length and its alignment padding).
653    body_len: usize,
654}
655
656impl IpcDataGenerator {
657    /// Converts a schema to an IPC message along with `dictionary_tracker`
658    /// and returns it encoded inside [EncodedData] as a flatbuffer.
659    pub fn schema_to_bytes_with_dictionary_tracker(
660        &self,
661        schema: &Schema,
662        dictionary_tracker: &mut DictionaryTracker,
663        write_options: &IpcWriteOptions,
664    ) -> EncodedData {
665        let mut fbb = FlatBufferBuilder::new();
666        let schema = {
667            let fb = IpcSchemaEncoder::new()
668                .with_dictionary_tracker(dictionary_tracker)
669                .schema_to_fb_offset(&mut fbb, schema);
670            fb.as_union_value()
671        };
672
673        let mut message = crate::MessageBuilder::new(&mut fbb);
674        message.add_version(write_options.metadata_version);
675        message.add_header_type(crate::MessageHeader::Schema);
676        message.add_bodyLength(0);
677        message.add_header(schema);
678        // TODO: custom metadata
679        let root = message.finish();
680        fbb.finish(root, None);
681
682        let metadata = fbb.finished_data();
683        EncodedData {
684            ipc_message: metadata.to_vec(),
685            arrow_data: vec![],
686        }
687    }
688
689    fn _collect_dict_updates<I: Iterator<Item = i64>>(
690        &self,
691        column: &ArrayRef,
692        dictionaries_to_encode: &mut Vec<DictionaryToEncode>,
693        dictionary_tracker: &mut DictionaryTracker,
694        write_options: &IpcWriteOptions,
695        dict_id: &mut I,
696    ) -> Result<(), ArrowError> {
697        match column.data_type() {
698            DataType::Struct(fields) => {
699                let s = as_struct_array(column);
700                for (field, column) in fields.iter().zip(s.columns()) {
701                    self.collect_dict_updates(
702                        field,
703                        column,
704                        dictionaries_to_encode,
705                        dictionary_tracker,
706                        write_options,
707                        dict_id,
708                    )?;
709                }
710            }
711            DataType::RunEndEncoded(_, values) => {
712                let data = column.to_data();
713                if data.child_data().len() != 2 {
714                    return Err(ArrowError::InvalidArgumentError(format!(
715                        "The run encoded array should have exactly two child arrays. Found {}",
716                        data.child_data().len()
717                    )));
718                }
719                // The run_ends array is not expected to be dictionary encoded. Hence encode dictionaries
720                // only for values array.
721                let values_array = make_array(data.child_data()[1].clone());
722                self.collect_dict_updates(
723                    values,
724                    &values_array,
725                    dictionaries_to_encode,
726                    dictionary_tracker,
727                    write_options,
728                    dict_id,
729                )?;
730            }
731            DataType::List(field) => {
732                let list = as_list_array(column);
733                self.collect_dict_updates(
734                    field,
735                    list.values(),
736                    dictionaries_to_encode,
737                    dictionary_tracker,
738                    write_options,
739                    dict_id,
740                )?;
741            }
742            DataType::LargeList(field) => {
743                let list = as_large_list_array(column);
744                self.collect_dict_updates(
745                    field,
746                    list.values(),
747                    dictionaries_to_encode,
748                    dictionary_tracker,
749                    write_options,
750                    dict_id,
751                )?;
752            }
753            DataType::ListView(field) => {
754                let list = column.as_list_view::<i32>();
755                self.collect_dict_updates(
756                    field,
757                    list.values(),
758                    dictionaries_to_encode,
759                    dictionary_tracker,
760                    write_options,
761                    dict_id,
762                )?;
763            }
764            DataType::LargeListView(field) => {
765                let list = column.as_list_view::<i64>();
766                self.collect_dict_updates(
767                    field,
768                    list.values(),
769                    dictionaries_to_encode,
770                    dictionary_tracker,
771                    write_options,
772                    dict_id,
773                )?;
774            }
775            DataType::FixedSizeList(field, _) => {
776                let list = column
777                    .as_any()
778                    .downcast_ref::<FixedSizeListArray>()
779                    .expect("Unable to downcast to fixed size list array");
780                self.collect_dict_updates(
781                    field,
782                    list.values(),
783                    dictionaries_to_encode,
784                    dictionary_tracker,
785                    write_options,
786                    dict_id,
787                )?;
788            }
789            DataType::Map(field, _) => {
790                let map_array = as_map_array(column);
791
792                let (keys, values) = match field.data_type() {
793                    DataType::Struct(fields) if fields.len() == 2 => (&fields[0], &fields[1]),
794                    _ => panic!("Incorrect field data type {:?}", field.data_type()),
795                };
796
797                // keys
798                self.collect_dict_updates(
799                    keys,
800                    map_array.keys(),
801                    dictionaries_to_encode,
802                    dictionary_tracker,
803                    write_options,
804                    dict_id,
805                )?;
806
807                // values
808                self.collect_dict_updates(
809                    values,
810                    map_array.values(),
811                    dictionaries_to_encode,
812                    dictionary_tracker,
813                    write_options,
814                    dict_id,
815                )?;
816            }
817            DataType::Union(fields, _) => {
818                let union = as_union_array(column);
819                for (type_id, field) in fields.iter() {
820                    let column = union.child(type_id);
821                    self.collect_dict_updates(
822                        field,
823                        column,
824                        dictionaries_to_encode,
825                        dictionary_tracker,
826                        write_options,
827                        dict_id,
828                    )?;
829                }
830            }
831            _ => (),
832        }
833
834        Ok(())
835    }
836
837    // Collect all dicts that need a dictionary message i.e. ones that were
838    // either not in the tracker previously or ones that were but need a
839    // replacement or delta.
840    fn collect_dict_updates<I: Iterator<Item = i64>>(
841        &self,
842        field: &Field,
843        column: &ArrayRef,
844        dictionaries_to_encode: &mut Vec<DictionaryToEncode>,
845        dictionary_tracker: &mut DictionaryTracker,
846        write_options: &IpcWriteOptions,
847        dict_id_seq: &mut I,
848    ) -> Result<(), ArrowError> {
849        match column.data_type() {
850            DataType::Dictionary(_key_type, value_type) => {
851                if matches!(value_type.as_ref(), DataType::Dictionary(_, _)) {
852                    return Err(ArrowError::InvalidArgumentError(format!(
853                        "Arrow IPC field metadata cannot encode direct dictionary-of-dictionary values for field {:?}",
854                        field.name()
855                    )));
856                }
857
858                let dict_data = column.to_data();
859                let dict_values = &dict_data.child_data()[0];
860
861                let values = make_array(dict_data.child_data()[0].clone());
862
863                self._collect_dict_updates(
864                    &values,
865                    dictionaries_to_encode,
866                    dictionary_tracker,
867                    write_options,
868                    dict_id_seq,
869                )?;
870
871                // It's important to only take the dict_id at this point, because the dict ID
872                // sequence is assigned depth-first, so we need to first encode children and have
873                // them take their assigned dict IDs before we take the dict ID for this field.
874                let dict_id = dict_id_seq.next().ok_or_else(|| {
875                    ArrowError::IpcError(format!(
876                        "no dict id for field {:?}: field.data_type={:?}, column.data_type={:?}",
877                        field.name(),
878                        field.data_type(),
879                        column.data_type()
880                    ))
881                })?;
882
883                match dictionary_tracker.insert_column(
884                    dict_id,
885                    column,
886                    write_options.dictionary_handling,
887                )? {
888                    DictionaryUpdate::None => {}
889                    DictionaryUpdate::New | DictionaryUpdate::Replaced => {
890                        dictionaries_to_encode.push(DictionaryToEncode {
891                            id: dict_id,
892                            data: dict_values.clone(),
893                            is_delta: false,
894                        });
895                    }
896                    DictionaryUpdate::Delta(data) => {
897                        dictionaries_to_encode.push(DictionaryToEncode {
898                            id: dict_id,
899                            data,
900                            is_delta: true,
901                        });
902                    }
903                }
904            }
905            _ => self._collect_dict_updates(
906                column,
907                dictionaries_to_encode,
908                dictionary_tracker,
909                write_options,
910                dict_id_seq,
911            )?,
912        }
913
914        Ok(())
915    }
916
917    /// Encodes a batch to a number of [EncodedData] items (dictionary batches + the record batch).
918    /// The [DictionaryTracker] keeps track of dictionaries with new `dict_id`s  (so they are only sent once)
919    /// Make sure the [DictionaryTracker] is initialized at the start of the stream.
920    pub fn encode(
921        &self,
922        batch: &RecordBatch,
923        dictionary_tracker: &mut DictionaryTracker,
924        write_options: &IpcWriteOptions,
925        ipc_write_context: &mut IpcWriteContext,
926    ) -> Result<(Vec<EncodedData>, EncodedData), ArrowError> {
927        let dictionaries = self.collect_all_dicts(batch, dictionary_tracker, write_options)?;
928        let mut encoded_dictionaries = Vec::with_capacity(dictionaries.len());
929        for dict in dictionaries {
930            encoded_dictionaries.push(self.dictionary_batch_to_bytes(
931                dict,
932                write_options,
933                ipc_write_context,
934            )?);
935        }
936        let mut arrow_data = ipc_write_context.scratch();
937        self.record_batch_to_bytes(
938            batch,
939            write_options,
940            ipc_write_context,
941            &mut IpcBodySink::Write(&mut arrow_data),
942        )?;
943        ipc_write_context.reserve_scratch_with_capacity(arrow_data.capacity());
944        Ok((
945            encoded_dictionaries,
946            EncodedData {
947                ipc_message: ipc_write_context.mut_fbb().finished_data().to_vec(),
948                arrow_data,
949            },
950        ))
951    }
952
953    /// Walk the record batch and collect dictionaries for later encoding.
954    fn collect_all_dicts(
955        &self,
956        batch: &RecordBatch,
957        dictionary_tracker: &mut DictionaryTracker,
958        write_options: &IpcWriteOptions,
959    ) -> Result<Vec<DictionaryToEncode>, ArrowError> {
960        let schema = batch.schema();
961        let mut dictionaries = Vec::with_capacity(schema.flattened_fields().len());
962        let mut dict_id = dictionary_tracker.dict_ids.clone().into_iter();
963        for (i, field) in schema.fields().iter().enumerate() {
964            self.collect_dict_updates(
965                field,
966                batch.column(i),
967                &mut dictionaries,
968                dictionary_tracker,
969                write_options,
970                &mut dict_id,
971            )?;
972        }
973        Ok(dictionaries)
974    }
975
976    /// Write dictionary batches and the record batch directly to `writer`, skipping the
977    /// intermediate body `Vec<u8>` allocations
978    /// Returns [`IpcWriteMetadata`] with the sizes needed to build footer blocks.
979    fn write<W: Write>(
980        &self,
981        batch: &RecordBatch,
982        dictionary_tracker: &mut DictionaryTracker,
983        write_options: &IpcWriteOptions,
984        ipc_write_context: &mut IpcWriteContext,
985        writer: &mut W,
986    ) -> Result<IpcWriteMetadata, ArrowError> {
987        self.write_to_sink(
988            batch,
989            dictionary_tracker,
990            write_options,
991            ipc_write_context,
992            writer,
993        )
994    }
995
996    /// Encode dictionary batches and the record batch to output buffers, skipping the
997    /// intermediate body `Vec<u8>` allocations for uncompressed record batch buffers.
998    fn encode_to_buffers(
999        &self,
1000        batch: &RecordBatch,
1001        dictionary_tracker: &mut DictionaryTracker,
1002        write_options: &IpcWriteOptions,
1003        ipc_write_context: &mut IpcWriteContext,
1004        out: &mut Vec<Buffer>,
1005    ) -> Result<IpcWriteMetadata, ArrowError> {
1006        let mut sink = Buffers { out };
1007        self.write_to_sink(
1008            batch,
1009            dictionary_tracker,
1010            write_options,
1011            ipc_write_context,
1012            &mut sink,
1013        )
1014    }
1015
1016    fn write_to_sink<S: IpcRecordBatchSink>(
1017        &self,
1018        batch: &RecordBatch,
1019        dictionary_tracker: &mut DictionaryTracker,
1020        write_options: &IpcWriteOptions,
1021        ipc_write_context: &mut IpcWriteContext,
1022        sink: &mut S,
1023    ) -> Result<IpcWriteMetadata, ArrowError> {
1024        let dictionaries = self.collect_all_dicts(batch, dictionary_tracker, write_options)?;
1025        let mut dictionary_block_sizes = Vec::with_capacity(dictionaries.len());
1026
1027        let capacity = batch
1028            .columns()
1029            .iter()
1030            .map(|a| estimate_encoded_buffer_count(a.data_type()))
1031            .sum();
1032        let mut encoded_buffers: Vec<EncodedBuffer> = Vec::with_capacity(capacity);
1033
1034        for dict in &dictionaries {
1035            encoded_buffers.clear();
1036
1037            let body_len = self.dictionary_batch_to_sink(
1038                dict,
1039                write_options,
1040                ipc_write_context,
1041                &mut IpcBodySink::Collect(&mut encoded_buffers),
1042            )?;
1043
1044            dictionary_block_sizes.push(sink.write_record_batch(
1045                ipc_write_context.mut_fbb().finished_data(),
1046                &mut encoded_buffers,
1047                body_len,
1048                write_options,
1049            )?);
1050        }
1051
1052        encoded_buffers.clear();
1053        let body_len = self.record_batch_to_bytes(
1054            batch,
1055            write_options,
1056            ipc_write_context,
1057            &mut IpcBodySink::Collect(&mut encoded_buffers),
1058        )?;
1059
1060        let (padded_header_len, body_len) = sink.write_record_batch(
1061            ipc_write_context.mut_fbb().finished_data(),
1062            &mut encoded_buffers,
1063            body_len,
1064            write_options,
1065        )?;
1066
1067        Ok(IpcWriteMetadata {
1068            dictionary_block_sizes,
1069            padded_header_len,
1070            body_len,
1071        })
1072    }
1073
1074    /// Encodes a batch to a number of [EncodedData] items (dictionary batches + the record batch).
1075    /// The [DictionaryTracker] keeps track of dictionaries with new `dict_id`s  (so they are only sent once)
1076    /// Make sure the [DictionaryTracker] is initialized at the start of the stream.
1077    #[deprecated(since = "57.0.0", note = "Use `encode` instead")]
1078    pub fn encoded_batch(
1079        &self,
1080        batch: &RecordBatch,
1081        dictionary_tracker: &mut DictionaryTracker,
1082        write_options: &IpcWriteOptions,
1083    ) -> Result<(Vec<EncodedData>, EncodedData), ArrowError> {
1084        self.encode(
1085            batch,
1086            dictionary_tracker,
1087            write_options,
1088            &mut Default::default(),
1089        )
1090    }
1091
1092    /// Encodes a `RecordBatch` into a flatbuffer IPC message and fills `sink` with the
1093    /// serialised buffer data.
1094    ///
1095    /// Returns the total body length written to `sink` (including per-buffer alignment
1096    /// padding).
1097    ///
1098    /// The FlatBuffer [`crate::Message`] is located in `ipc_write_context`'s
1099    /// [`FlatBufferBuilder`] finished bytes. A successful Result from this function
1100    /// guarantees the builder is in a finished state to call
1101    /// [`FlatBufferBuilder::finished_data`].
1102    fn record_batch_to_bytes(
1103        &self,
1104        batch: &RecordBatch,
1105        write_options: &IpcWriteOptions,
1106        ipc_write_context: &mut IpcWriteContext,
1107        sink: &mut IpcBodySink<'_>,
1108    ) -> Result<usize, ArrowError> {
1109        // Reset the fbb
1110        ipc_write_context.mut_fbb().reset();
1111
1112        let EncodedRecordBatchMeta {
1113            fb_offset: record_batch,
1114            body_len,
1115        } = self.encode_record_batch_data(
1116            batch.columns().iter().map(|array| array.to_data()),
1117            batch.num_rows() as i64,
1118            write_options,
1119            ipc_write_context,
1120            sink,
1121        )?;
1122
1123        let fbb = ipc_write_context.mut_fbb();
1124        let mut message = crate::MessageBuilder::new(fbb);
1125        message.add_version(write_options.metadata_version);
1126        message.add_header_type(crate::MessageHeader::RecordBatch);
1127        message.add_bodyLength(body_len as i64);
1128        message.add_header(record_batch.as_union_value());
1129        let root = message.finish();
1130        fbb.finish(root, None);
1131
1132        Ok(body_len)
1133    }
1134
1135    /// Write dictionary values into two sets of bytes, one for the header (crate::Message) and the
1136    /// other for the data
1137    fn dictionary_batch_to_bytes(
1138        &self,
1139        dict: DictionaryToEncode,
1140        write_options: &IpcWriteOptions,
1141        ipc_write_context: &mut IpcWriteContext,
1142    ) -> Result<EncodedData, ArrowError> {
1143        let mut arrow_data: Vec<u8> = vec![];
1144        self.dictionary_batch_to_sink(
1145            &dict,
1146            write_options,
1147            ipc_write_context,
1148            &mut IpcBodySink::Write(&mut arrow_data),
1149        )?;
1150
1151        Ok(EncodedData {
1152            ipc_message: ipc_write_context.mut_fbb().finished_data().to_vec(),
1153            arrow_data,
1154        })
1155    }
1156
1157    /// Encodes a dictionary batch's flatbuffer metadata into `ipc_write_context`'s
1158    /// builder (read back via `ipc_write_context.mut_fbb().finished_data()`) and fills
1159    /// `sink` with its body buffers.
1160    ///
1161    /// Returns the total body length written to `sink` (including per-buffer alignment
1162    /// padding).
1163    fn dictionary_batch_to_sink(
1164        &self,
1165        dict: &DictionaryToEncode,
1166        write_options: &IpcWriteOptions,
1167        ipc_write_context: &mut IpcWriteContext,
1168        sink: &mut IpcBodySink<'_>,
1169    ) -> Result<usize, ArrowError> {
1170        // Reset fbb
1171        ipc_write_context.mut_fbb().reset();
1172
1173        // A dictionary batch is a record batch (the single column of dictionary
1174        // values) wrapped in a DictionaryBatch, so we share the record batch body
1175        // and table encoding and only differ in the message framing.
1176        let EncodedRecordBatchMeta {
1177            fb_offset: record_batch,
1178            body_len,
1179        } = self.encode_record_batch_data(
1180            std::iter::once(dict.data.clone()),
1181            dict.data.len() as i64,
1182            write_options,
1183            ipc_write_context,
1184            sink,
1185        )?;
1186
1187        let fbb = ipc_write_context.mut_fbb();
1188        let root = {
1189            let mut batch_builder = crate::DictionaryBatchBuilder::new(fbb);
1190            batch_builder.add_id(dict.id);
1191            batch_builder.add_data(record_batch);
1192            batch_builder.add_isDelta(dict.is_delta);
1193            batch_builder.finish().as_union_value()
1194        };
1195
1196        let root = {
1197            let mut message_builder = crate::MessageBuilder::new(fbb);
1198            message_builder.add_version(write_options.metadata_version);
1199            message_builder.add_header_type(crate::MessageHeader::DictionaryBatch);
1200            message_builder.add_bodyLength(body_len as i64);
1201            message_builder.add_header(root);
1202            message_builder.finish()
1203        };
1204
1205        fbb.finish(root, None);
1206
1207        Ok(body_len)
1208    }
1209
1210    /// Encode the body buffers of a single record batch into `sink` and build the
1211    /// flatbuffer `RecordBatch` table into `ipc_write_context`'s builder.
1212    ///
1213    /// This is the shared core of [`Self::record_batch_to_bytes`] and
1214    /// [`Self::dictionary_batch_to_sink`]: a dictionary message embeds a record
1215    /// batch (its single column of values), so both encode the same `RecordBatch`
1216    /// table and only differ in how they wrap the returned offset in a message.
1217    ///
1218    /// `columns` yields the column data in IPC buffer order and `row_count` is the
1219    /// logical length recorded in the `RecordBatch` header. The caller is responsible
1220    /// for wrapping the returned [`EncodedRecordBatchMeta::fb_offset`] in a `Message`
1221    /// and calling [`FlatBufferBuilder::finish`].
1222    #[inline]
1223    fn encode_record_batch_data(
1224        &self,
1225        columns: impl IntoIterator<Item = ArrayData>,
1226        row_count: i64,
1227        write_options: &IpcWriteOptions,
1228        ipc_write_context: &mut IpcWriteContext,
1229        sink: &mut IpcBodySink<'_>,
1230    ) -> Result<EncodedRecordBatchMeta, ArrowError> {
1231        let batch_compression_type = write_options.batch_compression_type;
1232
1233        // Keep the reusable lz4 encoder cached in `ipc_write_context` in sync with these
1234        // options: the context may outlive a single writer or option set.
1235        ipc_write_context.set_lz4_block_size(write_options.lz4_block_size());
1236
1237        let compression = batch_compression_type.map(|batch_compression_type| {
1238            let fbb = ipc_write_context.mut_fbb();
1239            let mut c = crate::BodyCompressionBuilder::new(fbb);
1240            c.add_method(crate::BodyCompressionMethod::BUFFER);
1241            c.add_codec(batch_compression_type);
1242            c.finish()
1243        });
1244
1245        let batch_compression_level = write_options.batch_compression_level;
1246        let compression_codec: Option<CompressionCodec> = batch_compression_type
1247            .map(|compression_type| match batch_compression_level {
1248                Some(level) => {
1249                    CompressionCodec::try_new_with_compression_level(compression_type, level)
1250                }
1251                None => compression_type.try_into(),
1252            })
1253            .transpose()?;
1254
1255        let mut meta = IpcMetadataBuilder::default();
1256        let mut variadic_buffer_counts: Vec<i64> = vec![];
1257        let mut offset = 0i64;
1258
1259        for array_data in columns {
1260            offset = write_array_data(
1261                &array_data,
1262                &mut meta,
1263                sink,
1264                offset,
1265                compression_codec,
1266                ipc_write_context,
1267                write_options,
1268            )?;
1269            append_variadic_buffer_counts(&mut variadic_buffer_counts, &array_data);
1270        }
1271
1272        // Each buffer is padded to the alignment as it is written, so `offset` is
1273        // already a multiple of the alignment -- the body needs no trailing padding.
1274        debug_assert_eq!(offset % write_options.alignment as i64, 0);
1275        let body_len = offset as usize;
1276
1277        let fbb = ipc_write_context.mut_fbb();
1278        let buffers = fbb.create_vector(&meta.buffers);
1279        let nodes = fbb.create_vector(&meta.nodes);
1280        let variadic_buffer = if variadic_buffer_counts.is_empty() {
1281            None
1282        } else {
1283            Some(fbb.create_vector(&variadic_buffer_counts))
1284        };
1285
1286        let mut batch_builder = crate::RecordBatchBuilder::new(fbb);
1287        batch_builder.add_length(row_count);
1288        batch_builder.add_nodes(nodes);
1289        batch_builder.add_buffers(buffers);
1290        if let Some(c) = compression {
1291            batch_builder.add_compression(c);
1292        }
1293        if let Some(v) = variadic_buffer {
1294            batch_builder.add_variadicBufferCounts(v);
1295        }
1296        let record_batch = batch_builder.finish();
1297
1298        Ok(EncodedRecordBatchMeta {
1299            fb_offset: record_batch,
1300            body_len,
1301        })
1302    }
1303}
1304
1305fn ensure_supported_ipc_schema(schema: &Schema) -> Result<(), ArrowError> {
1306    schema
1307        .fields()
1308        .iter()
1309        .try_for_each(|field| ensure_supported_ipc_data_type(field.name(), field.data_type()))
1310}
1311
1312fn ensure_supported_ipc_data_type(
1313    field_name: &str,
1314    data_type: &DataType,
1315) -> Result<(), ArrowError> {
1316    match data_type {
1317        DataType::Dictionary(_, value_type)
1318            if matches!(value_type.as_ref(), DataType::Dictionary(_, _)) =>
1319        {
1320            Err(ArrowError::InvalidArgumentError(format!(
1321                "Arrow IPC field metadata cannot encode direct dictionary-of-dictionary values for field {field_name:?}"
1322            )))
1323        }
1324        DataType::Dictionary(_, value_type) => {
1325            ensure_supported_ipc_data_type(field_name, value_type)
1326        }
1327        DataType::Struct(fields) => fields
1328            .iter()
1329            .try_for_each(|field| ensure_supported_ipc_data_type(field.name(), field.data_type())),
1330        DataType::RunEndEncoded(_, field)
1331        | DataType::List(field)
1332        | DataType::LargeList(field)
1333        | DataType::ListView(field)
1334        | DataType::LargeListView(field)
1335        | DataType::FixedSizeList(field, _)
1336        | DataType::Map(field, _) => {
1337            ensure_supported_ipc_data_type(field.name(), field.data_type())
1338        }
1339        DataType::Union(fields, _) => fields.iter().try_for_each(|(_, field)| {
1340            ensure_supported_ipc_data_type(field.name(), field.data_type())
1341        }),
1342        _ => Ok(()),
1343    }
1344}
1345
1346fn append_variadic_buffer_counts(counts: &mut Vec<i64>, array: &ArrayData) {
1347    match array.data_type() {
1348        DataType::BinaryView | DataType::Utf8View => {
1349            // The spec documents the counts only includes the variadic buffers, not the view/null buffers.
1350            // https://arrow.apache.org/docs/format/Columnar.html#variadic-buffers
1351            counts.push(array.buffers().len() as i64 - 1);
1352        }
1353        DataType::Dictionary(_, _) => {
1354            // Do nothing
1355            // Dictionary values are handled in special dictionary messages
1356        }
1357        _ => {
1358            for child in array.child_data() {
1359                append_variadic_buffer_counts(counts, child)
1360            }
1361        }
1362    }
1363}
1364
1365pub(crate) fn unslice_run_array(arr: ArrayData) -> Result<ArrayData, ArrowError> {
1366    match arr.data_type() {
1367        DataType::RunEndEncoded(k, _) => match k.data_type() {
1368            DataType::Int16 => {
1369                Ok(into_zero_offset_run_array(RunArray::<Int16Type>::from(arr))?.into_data())
1370            }
1371            DataType::Int32 => {
1372                Ok(into_zero_offset_run_array(RunArray::<Int32Type>::from(arr))?.into_data())
1373            }
1374            DataType::Int64 => {
1375                Ok(into_zero_offset_run_array(RunArray::<Int64Type>::from(arr))?.into_data())
1376            }
1377            d => unreachable!("Unexpected data type {d}"),
1378        },
1379        d => Err(ArrowError::InvalidArgumentError(format!(
1380            "The given array is not a run array. Data type of given array: {d}"
1381        ))),
1382    }
1383}
1384
1385// Returns a `RunArray` with zero offset and length matching the last value
1386// in run_ends array.
1387fn into_zero_offset_run_array<R: RunEndIndexType>(
1388    run_array: RunArray<R>,
1389) -> Result<RunArray<R>, ArrowError> {
1390    // Empty slices have no physical runs, regardless of their offset.
1391    if run_array.is_empty() {
1392        return Ok(ArrayData::new_empty(run_array.data_type()).into());
1393    }
1394
1395    let run_ends = run_array.run_ends();
1396    if run_ends.offset() == 0 && run_ends.max_value() == run_ends.len() {
1397        return Ok(run_array);
1398    }
1399
1400    // The physical index of original run_ends array from which the `ArrayData`is sliced.
1401    let start_physical_index = run_ends.get_start_physical_index();
1402
1403    // The physical index of original run_ends array until which the `ArrayData`is sliced.
1404    let end_physical_index = run_ends.get_end_physical_index();
1405
1406    let physical_length = end_physical_index - start_physical_index + 1;
1407
1408    // build new run_ends array by subtracting offset from run ends.
1409    let offset = R::Native::usize_as(run_ends.offset());
1410    let mut run_ends_values = Vec::<R::Native>::with_capacity(physical_length);
1411    for run_end_value in &run_ends.values()[start_physical_index..end_physical_index] {
1412        run_ends_values.push(run_end_value.sub_wrapping(offset));
1413    }
1414    run_ends_values.push(R::Native::from_usize(run_array.len()).unwrap());
1415    let offset_buffer = Buffer::from_vec(run_ends_values);
1416    let new_run_ends = unsafe {
1417        // Safety:
1418        // The function builds a valid run_ends array and hence need not be validated.
1419        ArrayDataBuilder::new(R::DATA_TYPE)
1420            .len(physical_length)
1421            .add_buffer(offset_buffer)
1422            .build_unchecked()
1423    };
1424
1425    // build new values by slicing physical indices.
1426    let new_values = run_array
1427        .values()
1428        .slice(start_physical_index, physical_length)
1429        .into_data();
1430
1431    let builder = ArrayDataBuilder::new(run_array.data_type().clone())
1432        .len(run_array.len())
1433        .add_child_data(new_run_ends)
1434        .add_child_data(new_values);
1435    let array_data = unsafe {
1436        // Safety:
1437        //  This function builds a valid run array and hence can skip validation.
1438        builder.build_unchecked()
1439    };
1440    Ok(array_data.into())
1441}
1442
1443/// Controls how dictionaries are handled in Arrow IPC messages
1444#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1445pub enum DictionaryHandling {
1446    /// Send the entire dictionary every time it is encountered (default)
1447    #[default]
1448    Resend,
1449    /// Send only new dictionary values since the last batch (delta encoding)
1450    ///
1451    /// When a dictionary is first encountered, the entire dictionary is sent.
1452    /// For subsequent batches, only values that are new (not previously sent)
1453    /// are transmitted with the `isDelta` flag set to true.
1454    Delta,
1455}
1456
1457/// Describes what kind of update took place after a call to [`DictionaryTracker::insert`].
1458#[derive(Debug, Clone)]
1459pub enum DictionaryUpdate {
1460    /// No dictionary was written, the dictionary was identical to what was already
1461    /// in the tracker.
1462    None,
1463    /// No dictionary was present in the tracker
1464    New,
1465    /// Dictionary was replaced with the new data
1466    Replaced,
1467    /// Dictionary was updated, ArrayData is the delta between old and new
1468    Delta(ArrayData),
1469}
1470
1471/// Keeps track of dictionaries that have been written, to avoid emitting the same dictionary
1472/// multiple times.
1473///
1474/// Can optionally error if an update to an existing dictionary is attempted, which
1475/// isn't allowed in the `FileWriter`.
1476#[derive(Debug)]
1477pub struct DictionaryTracker {
1478    // NOTE: When adding fields, update the clear() method accordingly.
1479    written: HashMap<i64, ArrayData>,
1480    dict_ids: Vec<i64>,
1481    error_on_replacement: bool,
1482}
1483
1484impl DictionaryTracker {
1485    /// Create a new [`DictionaryTracker`].
1486    ///
1487    /// If `error_on_replacement`
1488    /// is true, an error will be generated if an update to an
1489    /// existing dictionary is attempted.
1490    pub fn new(error_on_replacement: bool) -> Self {
1491        Self {
1492            written: HashMap::new(),
1493            dict_ids: Vec::new(),
1494            error_on_replacement,
1495        }
1496    }
1497
1498    /// Record and return the next dictionary ID.
1499    pub fn next_dict_id(&mut self) -> i64 {
1500        let next = self
1501            .dict_ids
1502            .last()
1503            .copied()
1504            .map(|i| i + 1)
1505            .unwrap_or_default();
1506
1507        self.dict_ids.push(next);
1508        next
1509    }
1510
1511    /// Return the sequence of dictionary IDs in the order they should be observed while
1512    /// traversing the schema
1513    pub fn dict_id(&mut self) -> &[i64] {
1514        &self.dict_ids
1515    }
1516
1517    /// Keep track of the dictionary with the given ID and values. Behavior:
1518    ///
1519    /// * If this ID has been written already and has the same data, return `Ok(false)` to indicate
1520    ///   that the dictionary was not actually inserted (because it's already been seen).
1521    /// * If this ID has been written already but with different data, and this tracker is
1522    ///   configured to return an error, return an error.
1523    /// * If the tracker has not been configured to error on replacement or this dictionary
1524    ///   has never been seen before, return `Ok(true)` to indicate that the dictionary was just
1525    ///   inserted.
1526    #[deprecated(since = "56.1.0", note = "Use `insert_column` instead")]
1527    pub fn insert(&mut self, dict_id: i64, column: &ArrayRef) -> Result<bool, ArrowError> {
1528        let dict_data = column.to_data();
1529        let dict_values = &dict_data.child_data()[0];
1530
1531        // If a dictionary with this id was already emitted, check if it was the same.
1532        if let Some(last) = self.written.get(&dict_id) {
1533            if ArrayData::ptr_eq(&last.child_data()[0], dict_values) {
1534                // Same dictionary values => no need to emit it again
1535                return Ok(false);
1536            }
1537            if self.error_on_replacement {
1538                // If error on replacement perform a logical comparison
1539                if last.child_data()[0] == *dict_values {
1540                    // Same dictionary values => no need to emit it again
1541                    return Ok(false);
1542                }
1543                return Err(ArrowError::InvalidArgumentError(
1544                    "Dictionary replacement detected when writing IPC file format. \
1545                     Arrow IPC files only support a single dictionary for a given field \
1546                     across all batches."
1547                        .to_string(),
1548                ));
1549            }
1550        }
1551
1552        self.written.insert(dict_id, dict_data);
1553        Ok(true)
1554    }
1555
1556    /// Keep track of the dictionary with the given ID and values. The return
1557    /// value indicates what, if any, update to the internal map took place
1558    /// and how it should be interpreted based on the `dict_handling` parameter.
1559    ///
1560    /// # Returns
1561    ///
1562    /// * `Ok(Dictionary::New)` - If the dictionary was not previously written
1563    /// * `Ok(Dictionary::Replaced)` - If the dictionary was previously written
1564    ///   with completely different data, or if the data is a delta of the existing,
1565    ///   but with `dict_handling` set to `DictionaryHandling::Resend`
1566    /// * `Ok(Dictionary::Delta)` - If the dictionary was previously written, but
1567    ///   the new data is a delta of the old and the `dict_handling` is set to
1568    ///   `DictionaryHandling::Delta`
1569    /// * `Err(e)` - If the dictionary was previously written with different data,
1570    ///   and `error_on_replacement` is set to `true`.
1571    pub fn insert_column(
1572        &mut self,
1573        dict_id: i64,
1574        column: &ArrayRef,
1575        dict_handling: DictionaryHandling,
1576    ) -> Result<DictionaryUpdate, ArrowError> {
1577        let new_data = column.to_data();
1578        let new_values = &new_data.child_data()[0];
1579
1580        // If there is no existing dictionary with this ID, we always insert
1581        let Some(old) = self.written.get(&dict_id) else {
1582            self.written.insert(dict_id, new_data);
1583            return Ok(DictionaryUpdate::New);
1584        };
1585
1586        // Fast path - If the array data points to the same buffer as the
1587        // existing then they're the same.
1588        let old_values = &old.child_data()[0];
1589        if ArrayData::ptr_eq(old_values, new_values) {
1590            return Ok(DictionaryUpdate::None);
1591        }
1592
1593        // Slow path - Compare the dictionaries value by value
1594        let comparison = compare_dictionaries(old_values, new_values);
1595        if matches!(comparison, DictionaryComparison::Equal) {
1596            return Ok(DictionaryUpdate::None);
1597        }
1598
1599        const REPLACEMENT_ERROR: &str = "Dictionary replacement detected when writing IPC file format. \
1600                 Arrow IPC files only support a single dictionary for a given field \
1601                 across all batches.";
1602
1603        match comparison {
1604            DictionaryComparison::NotEqual => {
1605                if self.error_on_replacement {
1606                    return Err(ArrowError::InvalidArgumentError(
1607                        REPLACEMENT_ERROR.to_string(),
1608                    ));
1609                }
1610
1611                self.written.insert(dict_id, new_data);
1612                Ok(DictionaryUpdate::Replaced)
1613            }
1614            DictionaryComparison::Delta => match dict_handling {
1615                DictionaryHandling::Resend => {
1616                    if self.error_on_replacement {
1617                        return Err(ArrowError::InvalidArgumentError(
1618                            REPLACEMENT_ERROR.to_string(),
1619                        ));
1620                    }
1621
1622                    self.written.insert(dict_id, new_data);
1623                    Ok(DictionaryUpdate::Replaced)
1624                }
1625                DictionaryHandling::Delta => {
1626                    let delta =
1627                        new_values.slice(old_values.len(), new_values.len() - old_values.len());
1628                    self.written.insert(dict_id, new_data);
1629                    Ok(DictionaryUpdate::Delta(delta))
1630                }
1631            },
1632            DictionaryComparison::Equal => unreachable!("Already checked equal case"),
1633        }
1634    }
1635
1636    /// Clears the state of the dictionary tracker.
1637    ///
1638    /// This allows the dictionary tracker to be reused for a new IPC stream while avoiding the
1639    /// allocation cost of creating a new instance. This method should not be called if
1640    /// the dictionary tracker will be used to continue writing to an existing IPC stream.
1641    pub fn clear(&mut self) {
1642        self.dict_ids.clear();
1643        self.written.clear();
1644    }
1645}
1646
1647/// Describes how two dictionary arrays compare to each other.
1648#[derive(Debug, Clone)]
1649enum DictionaryComparison {
1650    /// Neither a delta, nor an exact match
1651    NotEqual,
1652    /// Exact element-wise match
1653    Equal,
1654    /// The two arrays are dictionary deltas of each other, meaning the first
1655    /// is a prefix of the second.
1656    Delta,
1657}
1658
1659// Compares two dictionaries and returns a [`DictionaryComparison`].
1660fn compare_dictionaries(old: &ArrayData, new: &ArrayData) -> DictionaryComparison {
1661    // Check for exact match
1662    let existing_len = old.len();
1663    let new_len = new.len();
1664    if existing_len == new_len {
1665        return if *old == *new {
1666            DictionaryComparison::Equal
1667        } else {
1668            DictionaryComparison::NotEqual
1669        };
1670    }
1671
1672    // Can't be a delta if the new is shorter than the existing
1673    if new_len < existing_len {
1674        return DictionaryComparison::NotEqual;
1675    }
1676
1677    // Check for delta
1678    if new.slice(0, existing_len) == *old {
1679        return DictionaryComparison::Delta;
1680    }
1681
1682    DictionaryComparison::NotEqual
1683}
1684
1685/// Arrow File Writer
1686///
1687/// Writes Arrow [`RecordBatch`]es in the [IPC File Format].
1688///
1689/// # See Also
1690///
1691/// * [`StreamWriter`] for writing IPC Streams
1692///
1693/// # Example
1694/// ```
1695/// # use arrow_array::record_batch;
1696/// # use arrow_ipc::writer::FileWriter;
1697/// # let mut file = vec![]; // mimic a file for the example
1698/// let batch = record_batch!(("a", Int32, [1, 2, 3])).unwrap();
1699/// // create a new writer, the schema must be known in advance
1700/// let mut writer = FileWriter::try_new(&mut file, &batch.schema()).unwrap();
1701/// // write each batch to the underlying writer
1702/// writer.write(&batch).unwrap();
1703/// // When all batches are written, call finish to flush all buffers
1704/// writer.finish().unwrap();
1705/// ```
1706/// [IPC File Format]: https://arrow.apache.org/docs/format/Columnar.html#ipc-file-format
1707pub struct FileWriter<W> {
1708    /// The object to write to
1709    writer: W,
1710    /// IPC write options
1711    write_options: IpcWriteOptions,
1712    /// A reference to the schema, used in validating record batches
1713    schema: SchemaRef,
1714    /// The number of bytes between each block of bytes, as an offset for random access
1715    block_offsets: usize,
1716    /// Dictionary blocks that will be written as part of the IPC footer
1717    dictionary_blocks: Vec<crate::Block>,
1718    /// Record blocks that will be written as part of the IPC footer
1719    record_blocks: Vec<crate::Block>,
1720    /// Whether the writer footer has been written, and the writer is finished
1721    finished: bool,
1722    /// Keeps track of dictionaries that have been written
1723    dictionary_tracker: DictionaryTracker,
1724    /// User level customized metadata
1725    custom_metadata: Metadata,
1726
1727    data_gen: IpcDataGenerator,
1728
1729    /// Holds reusable scratch state shared across all messages -- including the
1730    /// [`FlatBufferBuilder`] whose internal buffer is reused to avoid reallocating
1731    /// on every batch.
1732    ipc_write_context: IpcWriteContext,
1733}
1734
1735impl<W: Write> FileWriter<BufWriter<W>> {
1736    /// Try to create a new file writer with the writer wrapped in a BufWriter.
1737    ///
1738    /// See [`FileWriter::try_new`] for an unbuffered version.
1739    pub fn try_new_buffered(writer: W, schema: &Schema) -> Result<Self, ArrowError> {
1740        Self::try_new(BufWriter::new(writer), schema)
1741    }
1742}
1743
1744impl<W: Write> FileWriter<W> {
1745    /// Try to create a new writer, with the schema written as part of the header
1746    ///
1747    /// Note the created writer is not buffered. See [`FileWriter::try_new_buffered`] for details.
1748    ///
1749    /// # Errors
1750    ///
1751    /// An [`Err`] may be returned if writing the header to the writer fails.
1752    pub fn try_new(writer: W, schema: &Schema) -> Result<Self, ArrowError> {
1753        let write_options = IpcWriteOptions::default();
1754        Self::try_new_with_options(writer, schema, write_options)
1755    }
1756
1757    /// Try to create a new writer with IpcWriteOptions
1758    ///
1759    /// Note the created writer is not buffered. See [`FileWriter::try_new_buffered`] for details.
1760    ///
1761    /// # Errors
1762    ///
1763    /// An [`Err`] may be returned if writing the header to the writer fails.
1764    pub fn try_new_with_options(
1765        mut writer: W,
1766        schema: &Schema,
1767        write_options: IpcWriteOptions,
1768    ) -> Result<Self, ArrowError> {
1769        ensure_supported_ipc_schema(schema)?;
1770
1771        let data_gen = IpcDataGenerator::default();
1772        // The IPC stream starts right after the magic and its padding to 8 bytes
1773        let pad_len = pad_to_alignment(8, super::ARROW_MAGIC.len());
1774        let header_size = super::ARROW_MAGIC.len() + pad_len;
1775        writer.write_all(&super::ARROW_MAGIC)?;
1776        writer.write_all(&PADDING[..pad_len])?;
1777        // write the schema, set the written bytes to the schema + header
1778        let mut dictionary_tracker = DictionaryTracker::new(true);
1779        let encoded_message = data_gen.schema_to_bytes_with_dictionary_tracker(
1780            schema,
1781            &mut dictionary_tracker,
1782            &write_options,
1783        );
1784        // Pad the schema message so that the messages after it start at a multiple of
1785        // the alignment in the file
1786        let (meta, data) =
1787            writer.write_encoded_data(encoded_message, &write_options, header_size)?;
1788        Ok(Self {
1789            writer,
1790            write_options,
1791            schema: Arc::new(schema.clone()),
1792            block_offsets: meta + data + header_size,
1793            dictionary_blocks: vec![],
1794            record_blocks: vec![],
1795            finished: false,
1796            dictionary_tracker,
1797            custom_metadata: Default::default(),
1798            data_gen,
1799            ipc_write_context: IpcWriteContext::default(),
1800        })
1801    }
1802
1803    /// Adds a key-value pair to the [FileWriter]'s custom metadata
1804    pub fn write_metadata(&mut self, key: impl Into<String>, value: impl Into<String>) {
1805        self.custom_metadata.insert(key.into(), value.into());
1806    }
1807
1808    /// Write a record batch to the file
1809    pub fn write(&mut self, batch: &RecordBatch) -> Result<(), ArrowError> {
1810        if self.finished {
1811            return Err(ArrowError::IpcError(
1812                "Cannot write record batch to file writer as it is closed".to_string(),
1813            ));
1814        }
1815
1816        let meta = self.data_gen.write(
1817            batch,
1818            &mut self.dictionary_tracker,
1819            &self.write_options,
1820            &mut self.ipc_write_context,
1821            &mut self.writer,
1822        )?;
1823
1824        for (header_len, body_len) in meta.dictionary_block_sizes {
1825            let block = crate::Block::new(
1826                self.block_offsets as i64,
1827                header_len as i32,
1828                body_len as i64,
1829            );
1830            self.dictionary_blocks.push(block);
1831            self.block_offsets += header_len + body_len;
1832        }
1833
1834        // add a record block for the footer
1835        let block = crate::Block::new(
1836            self.block_offsets as i64,
1837            meta.padded_header_len as i32,
1838            meta.body_len as i64,
1839        );
1840        self.record_blocks.push(block);
1841        self.block_offsets += meta.padded_header_len + meta.body_len;
1842        Ok(())
1843    }
1844
1845    /// Write footer and closing tag, then mark the writer as done
1846    pub fn finish(&mut self) -> Result<(), ArrowError> {
1847        if self.finished {
1848            return Err(ArrowError::IpcError(
1849                "Cannot write footer to file writer as it is closed".to_string(),
1850            ));
1851        }
1852
1853        // write EOS
1854        self.writer.write_eos(&self.write_options)?;
1855
1856        let mut fbb = FlatBufferBuilder::new();
1857        let dictionaries = fbb.create_vector(&self.dictionary_blocks);
1858        let record_batches = fbb.create_vector(&self.record_blocks);
1859
1860        // dictionaries are already written, so we can reset dictionary tracker to reuse for schema
1861        self.dictionary_tracker.clear();
1862        let schema = IpcSchemaEncoder::new()
1863            .with_dictionary_tracker(&mut self.dictionary_tracker)
1864            .schema_to_fb_offset(&mut fbb, &self.schema);
1865        let fb_custom_metadata = (!self.custom_metadata.is_empty())
1866            .then(|| crate::convert::metadata_to_fb(&mut fbb, &self.custom_metadata));
1867
1868        let root = {
1869            let mut footer_builder = crate::FooterBuilder::new(&mut fbb);
1870            footer_builder.add_version(self.write_options.metadata_version);
1871            footer_builder.add_schema(schema);
1872            footer_builder.add_dictionaries(dictionaries);
1873            footer_builder.add_recordBatches(record_batches);
1874            if let Some(fb_custom_metadata) = fb_custom_metadata {
1875                footer_builder.add_custom_metadata(fb_custom_metadata);
1876            }
1877            footer_builder.finish()
1878        };
1879        fbb.finish(root, None);
1880        let footer_data = fbb.finished_data();
1881        self.writer.write_all(footer_data)?;
1882        self.writer
1883            .write_all(&(footer_data.len() as i32).to_le_bytes())?;
1884        self.writer.write_all(&super::ARROW_MAGIC)?;
1885        self.writer.flush()?;
1886        self.finished = true;
1887
1888        Ok(())
1889    }
1890
1891    /// Returns the arrow [`SchemaRef`] for this arrow file.
1892    pub fn schema(&self) -> &SchemaRef {
1893        &self.schema
1894    }
1895
1896    /// Gets a reference to the underlying writer.
1897    pub fn get_ref(&self) -> &W {
1898        &self.writer
1899    }
1900
1901    /// Gets a mutable reference to the underlying writer.
1902    ///
1903    /// It is inadvisable to directly write to the underlying writer.
1904    pub fn get_mut(&mut self) -> &mut W {
1905        &mut self.writer
1906    }
1907
1908    /// Flush the underlying writer.
1909    ///
1910    /// Both the BufWriter and the underlying writer are flushed.
1911    pub fn flush(&mut self) -> Result<(), ArrowError> {
1912        self.writer.flush()?;
1913        Ok(())
1914    }
1915
1916    /// Unwraps the underlying writer.
1917    ///
1918    /// The writer is flushed and the FileWriter is finished before returning.
1919    ///
1920    /// # Errors
1921    ///
1922    /// An [`Err`] may be returned if an error occurs while finishing the StreamWriter
1923    /// or while flushing the writer.
1924    pub fn into_inner(mut self) -> Result<W, ArrowError> {
1925        if !self.finished {
1926            // `finish` flushes the writer.
1927            self.finish()?;
1928        }
1929        Ok(self.writer)
1930    }
1931}
1932
1933impl<W: Write> RecordBatchWriter for FileWriter<W> {
1934    fn write(&mut self, batch: &RecordBatch) -> Result<(), ArrowError> {
1935        self.write(batch)
1936    }
1937
1938    fn close(mut self) -> Result<(), ArrowError> {
1939        self.finish()
1940    }
1941}
1942
1943/// Arrow IPC stream encoder.
1944///
1945/// Encodes Arrow [`RecordBatch`]es to byte buffers using the [IPC Streaming Format],
1946/// without performing any IO.
1947///
1948/// The returned [`Buffer`]s are ordered and should be written to the destination
1949/// stream in order. Uncompressed record batch body buffers can share the original
1950/// Arrow buffers instead of being copied into an intermediate contiguous buffer.
1951///
1952/// # Example
1953/// ```
1954/// # use arrow_array::record_batch;
1955/// # use arrow_ipc::writer::StreamEncoder;
1956/// # use arrow_schema::ArrowError;
1957/// # fn main() -> Result<(), ArrowError> {
1958/// let batch = record_batch!(("a", Int32, [1, 2, 3]))?;
1959///
1960/// let mut encoder = StreamEncoder::try_new(&batch.schema())?;
1961/// let mut stream = vec![];
1962/// for buffer in encoder.encode(&batch)? {
1963///     stream.extend_from_slice(buffer.as_slice());
1964/// }
1965/// for buffer in encoder.finish()? {
1966///     stream.extend_from_slice(buffer.as_slice());
1967/// }
1968/// # Ok(())
1969/// # }
1970/// ```
1971pub struct StreamEncoder {
1972    schema: Schema,
1973    /// IPC write options
1974    write_options: IpcWriteOptions,
1975    /// Whether the stream schema has been encoded
1976    schema_encoded: bool,
1977    /// Keeps track of dictionaries that have been encoded
1978    dictionary_tracker: DictionaryTracker,
1979    data_gen: IpcDataGenerator,
1980    ipc_write_context: IpcWriteContext,
1981}
1982
1983impl StreamEncoder {
1984    /// Try to create a new stream encoder.
1985    pub fn try_new(schema: &Schema) -> Result<Self, ArrowError> {
1986        let write_options = IpcWriteOptions::default();
1987        Self::try_new_with_options(schema, write_options)
1988    }
1989
1990    /// Try to create a new stream encoder with [`IpcWriteOptions`].
1991    pub fn try_new_with_options(
1992        schema: &Schema,
1993        write_options: IpcWriteOptions,
1994    ) -> Result<Self, ArrowError> {
1995        ensure_supported_ipc_schema(schema)?;
1996
1997        Ok(Self {
1998            schema: schema.clone(),
1999            write_options,
2000            schema_encoded: false,
2001            dictionary_tracker: DictionaryTracker::new(false),
2002            data_gen: IpcDataGenerator::default(),
2003            ipc_write_context: IpcWriteContext::default(),
2004        })
2005    }
2006
2007    /// Encode a [`RecordBatch`] into buffers.
2008    ///
2009    /// The first call also includes the IPC stream schema message before the
2010    /// record batch message. Later calls only include dictionary and record
2011    /// batch messages.
2012    ///
2013    /// # Errors
2014    ///
2015    /// Returns an error if encoding fails.
2016    pub fn encode(&mut self, batch: &RecordBatch) -> Result<Vec<Buffer>, ArrowError> {
2017        let mut out = vec![];
2018        self.encode_schema(&mut out)?;
2019        self.data_gen.encode_to_buffers(
2020            batch,
2021            &mut self.dictionary_tracker,
2022            &self.write_options,
2023            &mut self.ipc_write_context,
2024            &mut out,
2025        )?;
2026        Ok(out)
2027    }
2028
2029    /// Encode the end-of-stream marker.
2030    ///
2031    /// If no batches have been encoded, this also emits the IPC stream schema
2032    /// message so the returned buffers form a valid empty IPC stream.
2033    ///
2034    /// # Errors
2035    ///
2036    /// Returns an error if encoding the schema or end-of-stream marker fails.
2037    pub fn finish(mut self) -> Result<Vec<Buffer>, ArrowError> {
2038        let mut out = vec![];
2039        self.encode_schema(&mut out)?;
2040        let mut sink = Buffers { out: &mut out };
2041        sink.write_eos(&self.write_options)?;
2042        Ok(out)
2043    }
2044
2045    fn encode_schema(&mut self, out: &mut Vec<Buffer>) -> Result<(), ArrowError> {
2046        if !self.schema_encoded {
2047            let encoded_message = self.data_gen.schema_to_bytes_with_dictionary_tracker(
2048                &self.schema,
2049                &mut self.dictionary_tracker,
2050                &self.write_options,
2051            );
2052            let mut sink = Buffers { out };
2053            sink.write_encoded_data(encoded_message, &self.write_options, 0)?;
2054            self.schema_encoded = true;
2055        }
2056        Ok(())
2057    }
2058}
2059
2060/// Arrow Stream Writer
2061///
2062/// Writes Arrow [`RecordBatch`]es to bytes using the [IPC Streaming Format].
2063///
2064/// # See Also
2065///
2066/// * [`FileWriter`] for writing IPC Files
2067///
2068/// # Example - Basic usage
2069/// ```
2070/// # use arrow_array::record_batch;
2071/// # use arrow_ipc::writer::StreamWriter;
2072/// # let mut stream = vec![]; // mimic a stream for the example
2073/// let batch = record_batch!(("a", Int32, [1, 2, 3])).unwrap();
2074/// // create a new writer, the schema must be known in advance
2075/// let mut writer = StreamWriter::try_new(&mut stream, &batch.schema()).unwrap();
2076/// // write each batch to the underlying stream
2077/// writer.write(&batch).unwrap();
2078/// // When all batches are written, call finish to flush all buffers
2079/// writer.finish().unwrap();
2080/// ```
2081/// # Example - Efficient delta dictionaries
2082/// ```
2083/// # use arrow_array::record_batch;
2084/// # use arrow_ipc::writer::{StreamWriter, IpcWriteOptions};
2085/// # use arrow_ipc::writer::DictionaryHandling;
2086/// # use arrow_schema::{DataType, Field, Schema, SchemaRef};
2087/// # use arrow_array::{
2088/// #    builder::StringDictionaryBuilder, types::Int32Type, Array, ArrayRef, DictionaryArray,
2089/// #    RecordBatch, StringArray,
2090/// # };
2091/// # use std::sync::Arc;
2092///
2093/// let schema = Arc::new(Schema::new(vec![Field::new(
2094///    "col1",
2095///    DataType::Dictionary(Box::from(DataType::Int32), Box::from(DataType::Utf8)),
2096///    true,
2097/// )]));
2098///
2099/// let mut builder = StringDictionaryBuilder::<arrow_array::types::Int32Type>::new();
2100///
2101/// // `finish_preserve_values` will keep the dictionary values along with their
2102/// // key assignments so that they can be re-used in the next batch.
2103/// builder.append("a").unwrap();
2104/// builder.append("b").unwrap();
2105/// let array1 = builder.finish_preserve_values();
2106/// let batch1 = RecordBatch::try_new(schema.clone(), vec![Arc::new(array1) as ArrayRef]).unwrap();
2107///
2108/// // In this batch, 'a' will have the same dictionary key as 'a' in the previous batch,
2109/// // and 'd' will take the next available key.
2110/// builder.append("a").unwrap();
2111/// builder.append("d").unwrap();
2112/// let array2 = builder.finish_preserve_values();
2113/// let batch2 = RecordBatch::try_new(schema.clone(), vec![Arc::new(array2) as ArrayRef]).unwrap();
2114///
2115/// let mut stream = vec![];
2116/// // You must set `.with_dictionary_handling(DictionaryHandling::Delta)` to
2117/// // enable delta dictionaries in the writer
2118/// let options = IpcWriteOptions::default().with_dictionary_handling(DictionaryHandling::Delta);
2119/// let mut writer = StreamWriter::try_new_with_options(&mut stream, &schema, options).unwrap();
2120///
2121/// // When writing the first batch, a dictionary message with 'a' and 'b' will be written
2122/// // prior to the record batch.
2123/// writer.write(&batch1).unwrap();
2124/// // With the second batch only a delta dictionary with 'd' will be written
2125/// // prior to the record batch. This is only possible with `finish_preserve_values`.
2126/// // Without it, 'a' and 'd' in this batch would have different keys than the
2127/// // first batch and so we'd have to send a replacement dictionary with new keys
2128/// // for both.
2129/// writer.write(&batch2).unwrap();
2130/// writer.finish().unwrap();
2131/// ```
2132/// [IPC Streaming Format]: https://arrow.apache.org/docs/format/Columnar.html#ipc-streaming-format
2133pub struct StreamWriter<W> {
2134    /// The object to write to
2135    writer: W,
2136    /// IPC write options
2137    write_options: IpcWriteOptions,
2138    /// Whether the writer footer has been written, and the writer is finished
2139    finished: bool,
2140    /// Keeps track of dictionaries that have been written
2141    dictionary_tracker: DictionaryTracker,
2142
2143    data_gen: IpcDataGenerator,
2144
2145    /// Reusable scratch state shared across all messages.
2146    ipc_write_context: IpcWriteContext,
2147}
2148
2149impl<W: Write> StreamWriter<BufWriter<W>> {
2150    /// Try to create a new stream writer with the writer wrapped in a BufWriter.
2151    ///
2152    /// See [`StreamWriter::try_new`] for an unbuffered version.
2153    pub fn try_new_buffered(writer: W, schema: &Schema) -> Result<Self, ArrowError> {
2154        Self::try_new(BufWriter::new(writer), schema)
2155    }
2156}
2157
2158impl<W: Write> StreamWriter<W> {
2159    /// Try to create a new writer, with the schema written as part of the header.
2160    ///
2161    /// Note that there is no internal buffering. See also [`StreamWriter::try_new_buffered`].
2162    ///
2163    /// # Errors
2164    ///
2165    /// An [`Err`] may be returned if writing the header to the writer fails.
2166    pub fn try_new(writer: W, schema: &Schema) -> Result<Self, ArrowError> {
2167        let write_options = IpcWriteOptions::default();
2168        Self::try_new_with_options(writer, schema, write_options)
2169    }
2170
2171    /// Try to create a new writer with [`IpcWriteOptions`].
2172    ///
2173    /// # Errors
2174    ///
2175    /// An [`Err`] may be returned if writing the header to the writer fails.
2176    pub fn try_new_with_options(
2177        mut writer: W,
2178        schema: &Schema,
2179        write_options: IpcWriteOptions,
2180    ) -> Result<Self, ArrowError> {
2181        ensure_supported_ipc_schema(schema)?;
2182
2183        let data_gen = IpcDataGenerator::default();
2184        let mut dictionary_tracker = DictionaryTracker::new(false);
2185
2186        // write the schema, set the written bytes to the schema
2187        let encoded_message = data_gen.schema_to_bytes_with_dictionary_tracker(
2188            schema,
2189            &mut dictionary_tracker,
2190            &write_options,
2191        );
2192        write_message(&mut writer, encoded_message, &write_options)?;
2193        Ok(Self {
2194            writer,
2195            write_options,
2196            finished: false,
2197            dictionary_tracker,
2198            data_gen,
2199            ipc_write_context: IpcWriteContext::default(),
2200        })
2201    }
2202
2203    /// Write a record batch to the stream
2204    pub fn write(&mut self, batch: &RecordBatch) -> Result<(), ArrowError> {
2205        if self.finished {
2206            return Err(ArrowError::IpcError(
2207                "Cannot write record batch to stream writer as it is closed".to_string(),
2208            ));
2209        }
2210
2211        self.data_gen.write(
2212            batch,
2213            &mut self.dictionary_tracker,
2214            &self.write_options,
2215            &mut self.ipc_write_context,
2216            &mut self.writer,
2217        )?;
2218        Ok(())
2219    }
2220
2221    /// Write continuation bytes, and mark the stream as done
2222    pub fn finish(&mut self) -> Result<(), ArrowError> {
2223        if self.finished {
2224            return Err(ArrowError::IpcError(
2225                "Cannot write footer to stream writer as it is closed".to_string(),
2226            ));
2227        }
2228
2229        self.writer.write_eos(&self.write_options)?;
2230        self.writer.flush()?;
2231
2232        self.finished = true;
2233
2234        Ok(())
2235    }
2236
2237    /// Gets a reference to the underlying writer.
2238    pub fn get_ref(&self) -> &W {
2239        &self.writer
2240    }
2241
2242    /// Gets a mutable reference to the underlying writer.
2243    ///
2244    /// It is inadvisable to directly write to the underlying writer.
2245    pub fn get_mut(&mut self) -> &mut W {
2246        &mut self.writer
2247    }
2248
2249    /// Flush the underlying writer.
2250    ///
2251    /// Both the BufWriter and the underlying writer are flushed.
2252    pub fn flush(&mut self) -> Result<(), ArrowError> {
2253        self.writer.flush()?;
2254        Ok(())
2255    }
2256
2257    /// Unwraps the the underlying writer.
2258    ///
2259    /// The writer is flushed and the StreamWriter is finished before returning.
2260    ///
2261    /// # Errors
2262    ///
2263    /// An [`Err`] may be returned if an error occurs while finishing the StreamWriter
2264    /// or while flushing the writer.
2265    ///
2266    /// # Example
2267    ///
2268    /// ```
2269    /// # use arrow_ipc::writer::{StreamWriter, IpcWriteOptions};
2270    /// # use arrow_ipc::MetadataVersion;
2271    /// # use arrow_schema::{ArrowError, Schema};
2272    /// # fn main() -> Result<(), ArrowError> {
2273    /// // The result we expect from an empty schema
2274    /// let expected = vec![
2275    ///     255, 255, 255, 255,  48,   0,   0,   0,
2276    ///      16,   0,   0,   0,   0,   0,  10,   0,
2277    ///      12,   0,  10,   0,   9,   0,   4,   0,
2278    ///      10,   0,   0,   0,  16,   0,   0,   0,
2279    ///       0,   1,   4,   0,   8,   0,   8,   0,
2280    ///       0,   0,   4,   0,   8,   0,   0,   0,
2281    ///       4,   0,   0,   0,   0,   0,   0,   0,
2282    ///     255, 255, 255, 255,   0,   0,   0,   0
2283    /// ];
2284    ///
2285    /// let schema = Schema::empty();
2286    /// let buffer: Vec<u8> = Vec::new();
2287    /// let options = IpcWriteOptions::try_new(8, false, MetadataVersion::V5)?;
2288    /// let stream_writer = StreamWriter::try_new_with_options(buffer, &schema, options)?;
2289    ///
2290    /// assert_eq!(stream_writer.into_inner()?, expected);
2291    /// # Ok(())
2292    /// # }
2293    /// ```
2294    pub fn into_inner(mut self) -> Result<W, ArrowError> {
2295        if !self.finished {
2296            // `finish` flushes.
2297            self.finish()?;
2298        }
2299        Ok(self.writer)
2300    }
2301}
2302
2303impl<W: Write> RecordBatchWriter for StreamWriter<W> {
2304    fn write(&mut self, batch: &RecordBatch) -> Result<(), ArrowError> {
2305        self.write(batch)
2306    }
2307
2308    fn close(mut self) -> Result<(), ArrowError> {
2309        self.finish()
2310    }
2311}
2312
2313/// Stores the encoded data, which is an crate::Message, and optional Arrow data
2314pub struct EncodedData {
2315    /// An encoded crate::Message
2316    pub ipc_message: Vec<u8>,
2317    /// Arrow buffers to be written, should be an empty vec for schema messages
2318    pub arrow_data: Vec<u8>,
2319}
2320
2321/// Write a message's IPC data and buffers, returning metadata and buffer data lengths written
2322pub fn write_message<W: Write>(
2323    mut writer: W,
2324    encoded: EncodedData,
2325    write_options: &IpcWriteOptions,
2326) -> Result<(usize, usize), ArrowError> {
2327    writer.write_encoded_data(encoded, write_options, 0)
2328}
2329
2330/// In V4, null and run end encoded types have no validity bitmap
2331/// In V5 and later, null, union and run end encoded types have no validity bitmap
2332fn has_validity_bitmap(data_type: &DataType, write_options: &IpcWriteOptions) -> bool {
2333    if write_options.metadata_version < crate::MetadataVersion::V5 {
2334        !matches!(data_type, DataType::Null | DataType::RunEndEncoded(_, _))
2335    } else {
2336        !matches!(
2337            data_type,
2338            DataType::Null | DataType::Union(_, _) | DataType::RunEndEncoded(_, _)
2339        )
2340    }
2341}
2342
2343/// Whether to truncate the buffer
2344#[inline]
2345fn buffer_need_truncate(
2346    array_offset: usize,
2347    buffer: &Buffer,
2348    spec: &BufferSpec,
2349    min_length: usize,
2350) -> bool {
2351    spec != &BufferSpec::AlwaysNull && (array_offset != 0 || min_length < buffer.len())
2352}
2353
2354/// Returns byte width for a buffer spec. Only for `BufferSpec::FixedWidth`.
2355#[inline]
2356fn get_buffer_element_width(spec: &BufferSpec) -> usize {
2357    match spec {
2358        BufferSpec::FixedWidth { byte_width, .. } => *byte_width,
2359        _ => 0,
2360    }
2361}
2362
2363/// Common functionality for re-encoding offsets. Returns the new offsets as well as
2364/// original start offset and length for use in slicing child data.
2365fn reencode_offsets<O: OffsetSizeTrait>(
2366    offsets: &Buffer,
2367    data: &ArrayData,
2368) -> (Buffer, usize, usize) {
2369    let offsets_slice: &[O] = offsets.typed_data::<O>();
2370    let offset_slice = &offsets_slice[data.offset()..data.offset() + data.len() + 1];
2371
2372    let start_offset = offset_slice.first().unwrap();
2373    let end_offset = offset_slice.last().unwrap();
2374
2375    let offsets = match start_offset.as_usize() {
2376        0 => {
2377            let size = size_of::<O>();
2378            offsets.slice_with_length(data.offset() * size, (data.len() + 1) * size)
2379        }
2380        _ => offset_slice.iter().map(|x| *x - *start_offset).collect(),
2381    };
2382
2383    let start_offset = start_offset.as_usize();
2384    let end_offset = end_offset.as_usize();
2385
2386    (offsets, start_offset, end_offset - start_offset)
2387}
2388
2389/// Returns the values and offsets [`Buffer`] for a ByteArray with offset type `O`
2390///
2391/// In particular, this handles re-encoding the offsets if they don't start at `0`,
2392/// slicing the values buffer as appropriate. This helps reduce the encoded
2393/// size of sliced arrays, as values that have been sliced away are not encoded
2394/// Returns the offsets and values buffers, in that order.
2395fn get_byte_array_buffers<O: OffsetSizeTrait>(data: &ArrayData) -> [Buffer; 2] {
2396    if data.is_empty() {
2397        // As per specification, offsets buffer has N+1 elements.
2398        // So an empty array should still be encoded with a single 0 offset.
2399        let mut offsets = MutableBuffer::new(size_of::<O>());
2400        offsets.extend_from_slice(O::usize_as(0).to_byte_slice());
2401        return [offsets.into(), MutableBuffer::new(0).into()];
2402    }
2403
2404    let (offsets, original_start_offset, len) = reencode_offsets::<O>(&data.buffers()[0], data);
2405    let values = data.buffers()[1].slice_with_length(original_start_offset, len);
2406    [offsets, values]
2407}
2408
2409/// Similar logic as [`get_byte_array_buffers()`] but slices the child array instead
2410/// of a values buffer.
2411fn get_list_array_buffers<O: OffsetSizeTrait>(data: &ArrayData) -> (Buffer, ArrayData) {
2412    if data.is_empty() {
2413        // As per specification, offsets buffer has N+1 elements.
2414        // So an empty array should still be encoded with a single 0 offset.
2415        let mut offsets = MutableBuffer::new(size_of::<O>());
2416        offsets.extend_from_slice(O::usize_as(0).to_byte_slice());
2417        return (offsets.into(), data.child_data()[0].slice(0, 0));
2418    }
2419
2420    let (offsets, original_start_offset, len) = reencode_offsets::<O>(&data.buffers()[0], data);
2421    let child_data = data.child_data()[0].slice(original_start_offset, len);
2422    (offsets, child_data)
2423}
2424
2425/// Returns the offsets, sizes, and child data buffers for a ListView array.
2426///
2427/// Unlike List arrays, ListView arrays store both offsets and sizes explicitly,
2428/// and offsets can be non-monotonic. When slicing, we simply pass through the
2429/// offsets and sizes without re-encoding, and do not slice the child data.
2430fn get_list_view_array_buffers<O: OffsetSizeTrait>(
2431    data: &ArrayData,
2432) -> (Buffer, Buffer, ArrayData) {
2433    if data.is_empty() {
2434        return (
2435            MutableBuffer::new(0).into(),
2436            MutableBuffer::new(0).into(),
2437            data.child_data()[0].slice(0, 0),
2438        );
2439    }
2440
2441    let offsets = &data.buffers()[0];
2442    let sizes = &data.buffers()[1];
2443
2444    let element_size = std::mem::size_of::<O>();
2445    let offsets_slice =
2446        offsets.slice_with_length(data.offset() * element_size, data.len() * element_size);
2447    let sizes_slice =
2448        sizes.slice_with_length(data.offset() * element_size, data.len() * element_size);
2449
2450    let child_data = data.child_data()[0].clone();
2451
2452    (offsets_slice, sizes_slice, child_data)
2453}
2454
2455/// Returns the sliced views [`Buffer`] for a BinaryView/Utf8View array.
2456///
2457/// The views buffer is sliced to only include views in the valid range based on
2458/// the array's offset and length. This helps reduce the encoded size of sliced
2459/// arrays
2460///
2461fn get_or_truncate_buffer(array_data: &ArrayData) -> Buffer {
2462    let buffer = &array_data.buffers()[0];
2463    let layout = layout(array_data.data_type());
2464    let spec = &layout.buffers[0];
2465
2466    let byte_width = get_buffer_element_width(spec);
2467    let min_length = array_data.len() * byte_width;
2468    if buffer_need_truncate(array_data.offset(), buffer, spec, min_length) {
2469        let byte_offset = array_data.offset() * byte_width;
2470        let buffer_length = min(min_length, buffer.len() - byte_offset);
2471        buffer.slice_with_length(byte_offset, buffer_length)
2472    } else {
2473        buffer.clone()
2474    }
2475}
2476
2477/// Recursively encodes `array_data` into its IPC representation.
2478///
2479/// Output goes to two separate channels:
2480/// - `meta`: accumulates IPC metadata (`nodes` and `buffers`) for the flatbuffer header.
2481/// - `sink`: the raw Arrow data bytes that form the IPC message body.
2482fn write_array_data(
2483    array_data: &ArrayData,
2484    meta: &mut IpcMetadataBuilder,
2485    sink: &mut IpcBodySink<'_>,
2486    offset: i64,
2487    compression_codec: Option<CompressionCodec>,
2488    ipc_write_context: &mut IpcWriteContext,
2489    write_options: &IpcWriteOptions,
2490) -> Result<i64, ArrowError> {
2491    let mut offset = offset;
2492    let num_rows = array_data.len();
2493    let null_count = array_data.null_count();
2494    if !matches!(array_data.data_type(), DataType::Null) {
2495        meta.nodes
2496            .push(crate::FieldNode::new(num_rows as i64, null_count as i64));
2497    } else {
2498        // NullArray's null_count equals to len, but ArrayData null_count is always 0.
2499        meta.nodes
2500            .push(crate::FieldNode::new(num_rows as i64, num_rows as i64));
2501    }
2502    if has_validity_bitmap(array_data.data_type(), write_options) {
2503        // Fields with null_count == 0 may write a 0-length validity buffer
2504        // instead of a materialized bitmap (see FieldNode in Message.fbs)
2505        let null_buffer = match array_data.nulls() {
2506            Some(buffer) if null_count > 0 => buffer.inner().sliced(),
2507            _ => MutableBuffer::new(0).into(),
2508        };
2509
2510        offset = encode_sink_buffer(
2511            null_buffer,
2512            meta,
2513            sink,
2514            offset,
2515            compression_codec,
2516            ipc_write_context,
2517            write_options.alignment,
2518        )?;
2519    }
2520
2521    let data_type = array_data.data_type();
2522    if matches!(data_type, DataType::Binary | DataType::Utf8) {
2523        for buffer in get_byte_array_buffers::<i32>(array_data) {
2524            offset = encode_sink_buffer(
2525                buffer,
2526                meta,
2527                sink,
2528                offset,
2529                compression_codec,
2530                ipc_write_context,
2531                write_options.alignment,
2532            )?;
2533        }
2534    } else if matches!(data_type, DataType::BinaryView | DataType::Utf8View) {
2535        // Slicing the views buffer is safe and easy,
2536        // but pruning unneeded data buffers is much more nuanced since it's complicated to prove that no views reference the pruned buffers
2537        //
2538        // Current implementation just serialize the raw arrays as given and not try to optimize anything.
2539        // If users wants to "compact" the arrays prior to sending them over IPC,
2540        // they should consider the gc API suggested in #5513
2541        let views = get_or_truncate_buffer(array_data);
2542        offset = encode_sink_buffer(
2543            views,
2544            meta,
2545            sink,
2546            offset,
2547            compression_codec,
2548            ipc_write_context,
2549            write_options.alignment,
2550        )?;
2551
2552        for buffer in array_data.buffers().iter().skip(1) {
2553            offset = encode_sink_buffer(
2554                buffer.clone(),
2555                meta,
2556                sink,
2557                offset,
2558                compression_codec,
2559                ipc_write_context,
2560                write_options.alignment,
2561            )?;
2562        }
2563    } else if matches!(data_type, DataType::LargeBinary | DataType::LargeUtf8) {
2564        for buffer in get_byte_array_buffers::<i64>(array_data) {
2565            offset = encode_sink_buffer(
2566                buffer,
2567                meta,
2568                sink,
2569                offset,
2570                compression_codec,
2571                ipc_write_context,
2572                write_options.alignment,
2573            )?;
2574        }
2575    } else if DataType::is_numeric(data_type)
2576        || DataType::is_temporal(data_type)
2577        || matches!(
2578            array_data.data_type(),
2579            DataType::FixedSizeBinary(_) | DataType::Dictionary(_, _)
2580        )
2581    {
2582        // Truncate values
2583        assert_eq!(array_data.buffers().len(), 1);
2584
2585        let buffer = get_or_truncate_buffer(array_data);
2586        offset = encode_sink_buffer(
2587            buffer,
2588            meta,
2589            sink,
2590            offset,
2591            compression_codec,
2592            ipc_write_context,
2593            write_options.alignment,
2594        )?;
2595    } else if matches!(data_type, DataType::Boolean) {
2596        // Bools are special because the payload (= 1 bit) is smaller than the physical container elements (= bytes).
2597        // The array data may not start at the physical boundary of the underlying buffer, so we need to shift bits around.
2598        assert_eq!(array_data.buffers().len(), 1);
2599
2600        let buffer = &array_data.buffers()[0];
2601        let buffer = buffer.bit_slice(array_data.offset(), array_data.len());
2602        offset = encode_sink_buffer(
2603            buffer,
2604            meta,
2605            sink,
2606            offset,
2607            compression_codec,
2608            ipc_write_context,
2609            write_options.alignment,
2610        )?;
2611    } else if matches!(
2612        data_type,
2613        DataType::List(_) | DataType::LargeList(_) | DataType::Map(_, _)
2614    ) {
2615        assert_eq!(array_data.buffers().len(), 1);
2616        assert_eq!(array_data.child_data().len(), 1);
2617
2618        // Truncate offsets and the child data to avoid writing unnecessary data
2619        let (offsets, sliced_child_data) = match data_type {
2620            DataType::List(_) => get_list_array_buffers::<i32>(array_data),
2621            DataType::Map(_, _) => get_list_array_buffers::<i32>(array_data),
2622            DataType::LargeList(_) => get_list_array_buffers::<i64>(array_data),
2623            _ => unreachable!(),
2624        };
2625        offset = encode_sink_buffer(
2626            offsets,
2627            meta,
2628            sink,
2629            offset,
2630            compression_codec,
2631            ipc_write_context,
2632            write_options.alignment,
2633        )?;
2634        offset = write_array_data(
2635            &sliced_child_data,
2636            meta,
2637            sink,
2638            offset,
2639            compression_codec,
2640            ipc_write_context,
2641            write_options,
2642        )?;
2643        return Ok(offset);
2644    } else if matches!(
2645        data_type,
2646        DataType::ListView(_) | DataType::LargeListView(_)
2647    ) {
2648        assert_eq!(array_data.buffers().len(), 2); // offsets + sizes
2649        assert_eq!(array_data.child_data().len(), 1);
2650
2651        let (offsets, sizes, child_data) = match data_type {
2652            DataType::ListView(_) => get_list_view_array_buffers::<i32>(array_data),
2653            DataType::LargeListView(_) => get_list_view_array_buffers::<i64>(array_data),
2654            _ => unreachable!(),
2655        };
2656
2657        offset = encode_sink_buffer(
2658            offsets,
2659            meta,
2660            sink,
2661            offset,
2662            compression_codec,
2663            ipc_write_context,
2664            write_options.alignment,
2665        )?;
2666        offset = encode_sink_buffer(
2667            sizes,
2668            meta,
2669            sink,
2670            offset,
2671            compression_codec,
2672            ipc_write_context,
2673            write_options.alignment,
2674        )?;
2675
2676        offset = write_array_data(
2677            &child_data,
2678            meta,
2679            sink,
2680            offset,
2681            compression_codec,
2682            ipc_write_context,
2683            write_options,
2684        )?;
2685        return Ok(offset);
2686    } else if let DataType::FixedSizeList(_, fixed_size) = data_type {
2687        assert_eq!(array_data.child_data().len(), 1);
2688        let fixed_size = *fixed_size as usize;
2689
2690        let child_offset = array_data.offset() * fixed_size;
2691        let child_length = array_data.len() * fixed_size;
2692        let child_data = array_data.child_data()[0].slice(child_offset, child_length);
2693
2694        offset = write_array_data(
2695            &child_data,
2696            meta,
2697            sink,
2698            offset,
2699            compression_codec,
2700            ipc_write_context,
2701            write_options,
2702        )?;
2703        return Ok(offset);
2704    } else if matches!(data_type, DataType::Union(_, _)) {
2705        for (buffer, byte_width) in array_data
2706            .buffers()
2707            .iter()
2708            .zip([size_of::<i8>(), size_of::<i32>()])
2709        {
2710            let buffer =
2711                buffer.slice_with_length(array_data.offset() * byte_width, num_rows * byte_width);
2712            offset = encode_sink_buffer(
2713                buffer,
2714                meta,
2715                sink,
2716                offset,
2717                compression_codec,
2718                ipc_write_context,
2719                write_options.alignment,
2720            )?;
2721        }
2722    } else {
2723        for buffer in array_data.buffers() {
2724            offset = encode_sink_buffer(
2725                buffer.clone(),
2726                meta,
2727                sink,
2728                offset,
2729                compression_codec,
2730                ipc_write_context,
2731                write_options.alignment,
2732            )?;
2733        }
2734    }
2735
2736    match array_data.data_type() {
2737        DataType::Dictionary(_, _) => {}
2738        DataType::RunEndEncoded(_, _) => {
2739            // unslice the run encoded array.
2740            let arr = unslice_run_array(array_data.clone())?;
2741            // recursively write out nested structures
2742            for data_ref in arr.child_data() {
2743                // write the nested data (e.g list data)
2744                offset = write_array_data(
2745                    data_ref,
2746                    meta,
2747                    sink,
2748                    offset,
2749                    compression_codec,
2750                    ipc_write_context,
2751                    write_options,
2752                )?;
2753            }
2754        }
2755        DataType::Union(_, UnionMode::Sparse) => {
2756            for data_ref in array_data.child_data() {
2757                let child_data = data_ref.slice(array_data.offset(), num_rows);
2758                offset = write_array_data(
2759                    &child_data,
2760                    meta,
2761                    sink,
2762                    offset,
2763                    compression_codec,
2764                    ipc_write_context,
2765                    write_options,
2766                )?;
2767            }
2768        }
2769        _ => {
2770            // recursively write out nested structures
2771            for data_ref in array_data.child_data() {
2772                // write the nested data (e.g list data)
2773                offset = write_array_data(
2774                    data_ref,
2775                    meta,
2776                    sink,
2777                    offset,
2778                    compression_codec,
2779                    ipc_write_context,
2780                    write_options,
2781                )?;
2782            }
2783        }
2784    }
2785    Ok(offset)
2786}
2787
2788/// Encodes a single Arrow [`Buffer`] into the IPC body and records its metadata.
2789///
2790/// - `buffer`: the Arrow data buffer to encode (validity bitmap, offsets, values, etc.)
2791/// - `buffers`: in-progress list of IPC `Buffer` metadata entries (body offset + length) that
2792///   will eventually be serialised into the flatbuffer `RecordBatch` header.
2793/// - `sink`: destination for the actual encoded bytes; either a contiguous `Vec<u8>` for
2794///   in-memory writes, or a list of [`EncodedBuffer`] segments for deferred zero-copy streaming.
2795/// - `offset`: running byte offset into the IPC message body, used to compute the metadata entry.
2796/// - `compression_codec` / `ipc_write_context`: if `Some`, the buffer is compressed before
2797///   writing; `ipc_write_context` provides reusable scratch space across calls.
2798/// - `alignment`: each buffer is padded to this many bytes so the next buffer starts aligned.
2799///
2800/// Returns the updated `offset` (advanced by the encoded length plus any alignment padding).
2801fn encode_sink_buffer(
2802    buffer: Buffer,
2803    ipc_meta_data: &mut IpcMetadataBuilder,
2804    sink: &mut IpcBodySink<'_>,
2805    offset: i64,
2806    compression_codec: Option<CompressionCodec>,
2807    ipc_write_context: &mut IpcWriteContext,
2808    alignment: u8,
2809) -> Result<i64, ArrowError> {
2810    let (encoded, len) = match compression_codec {
2811        None => {
2812            let len = buffer.len() as i64;
2813            (EncodedBuffer::Raw(buffer), len)
2814        }
2815        Some(codec) => {
2816            let mut scratch = Vec::new();
2817            let written =
2818                codec.compress_to_vec(buffer.as_slice(), &mut scratch, ipc_write_context)?;
2819            let len = i64::try_from(written)
2820                .map_err(|e| ArrowError::InvalidArgumentError(format!("{e}")))?;
2821            (EncodedBuffer::Compressed(scratch), len)
2822        }
2823    };
2824
2825    let pad_len = pad_to_alignment(alignment, len as usize);
2826    sink.write(pad_len, encoded);
2827    ipc_meta_data.buffers.push(crate::Buffer::new(offset, len));
2828    Ok(offset + len + pad_len as i64)
2829}
2830
2831const PADDING: [u8; 64] = [0; 64];
2832
2833/// Estimates the number of [`EncodedBuffer`] segments that [`write_array_data`]
2834/// will produce for a column of the given type.
2835///
2836/// Based on the Arrow IPC buffer layout
2837/// (<https://arrow.apache.org/docs/format/Columnar.html#recordbatch-message>):
2838#[inline]
2839fn estimate_encoded_buffer_count(dt: &DataType) -> usize {
2840    match dt {
2841        DataType::Null => 0,
2842
2843        DataType::Binary | DataType::Utf8 | DataType::LargeBinary | DataType::LargeUtf8 => 3,
2844
2845        DataType::BinaryView | DataType::Utf8View => 3,
2846
2847        DataType::List(f) | DataType::LargeList(f) | DataType::Map(f, _) => {
2848            2 + estimate_encoded_buffer_count(f.data_type())
2849        }
2850
2851        DataType::ListView(f) | DataType::LargeListView(f) => {
2852            3 + estimate_encoded_buffer_count(f.data_type())
2853        }
2854
2855        DataType::FixedSizeList(f, _) => 1 + estimate_encoded_buffer_count(f.data_type()),
2856
2857        DataType::Struct(fields) => {
2858            1 + fields
2859                .iter()
2860                .map(|f| estimate_encoded_buffer_count(f.data_type()))
2861                .sum::<usize>()
2862        }
2863
2864        // Dictionary indices only; dictionary body is a separate IPC message.
2865        DataType::Dictionary(_, _) => 2,
2866
2867        DataType::Union(fields, UnionMode::Sparse) => {
2868            1 + fields
2869                .iter()
2870                .map(|(_, f)| estimate_encoded_buffer_count(f.data_type()))
2871                .sum::<usize>()
2872        }
2873        DataType::Union(fields, UnionMode::Dense) => {
2874            2 + fields
2875                .iter()
2876                .map(|(_, f)| estimate_encoded_buffer_count(f.data_type()))
2877                .sum::<usize>()
2878        }
2879
2880        DataType::RunEndEncoded(run_ends, values) => {
2881            estimate_encoded_buffer_count(run_ends.data_type())
2882                + estimate_encoded_buffer_count(values.data_type())
2883        }
2884        // Primitive, Bool, temporal, Decimal*, FixedSizeBinary: validity + values.
2885        _ => 2,
2886    }
2887}
2888
2889/// Calculate an alignment boundary and return the number of bytes needed to pad to the alignment boundary
2890#[inline]
2891fn pad_to_alignment(alignment: u8, len: usize) -> usize {
2892    let a = usize::from(alignment - 1);
2893    ((len + a) & !a) - len
2894}
2895
2896#[cfg(test)]
2897mod tests {
2898    use std::hash::Hasher;
2899    use std::io::Cursor;
2900    use std::io::Seek;
2901
2902    use arrow_array::builder::FixedSizeListBuilder;
2903    use arrow_array::builder::Float32Builder;
2904    use arrow_array::builder::Int64Builder;
2905    use arrow_array::builder::MapBuilder;
2906    use arrow_array::builder::StringViewBuilder;
2907    use arrow_array::builder::UnionBuilder;
2908    use arrow_array::builder::{
2909        GenericListBuilder, GenericListViewBuilder, ListBuilder, StringBuilder,
2910    };
2911    use arrow_array::builder::{PrimitiveRunBuilder, UInt32Builder};
2912    use arrow_array::types::*;
2913    use arrow_buffer::ScalarBuffer;
2914
2915    use crate::MetadataVersion;
2916    use crate::convert::try_fb_to_schema;
2917    use crate::reader::*;
2918    use crate::root_as_footer;
2919
2920    use super::*;
2921
2922    #[test]
2923    fn test_roundtrip_sliced_list_of_union() {
2924        fn decoded(array: &ArrayRef) -> Vec<Vec<Option<i32>>> {
2925            (0..array.len())
2926                .map(|row| {
2927                    let values = array.as_list::<i32>().value(row);
2928                    let union = values.as_union();
2929                    (0..union.len())
2930                        .map(|index| {
2931                            union
2932                                .value(index)
2933                                .as_primitive::<Int32Type>()
2934                                .iter()
2935                                .next()
2936                                .unwrap()
2937                        })
2938                        .collect()
2939                })
2940                .collect()
2941        }
2942
2943        for mode in [UnionMode::Dense, UnionMode::Sparse] {
2944            let fields = UnionFields::try_new(
2945                [3, 7],
2946                [
2947                    Field::new("a", DataType::Int32, true),
2948                    Field::new("b", DataType::Int32, true),
2949                ],
2950            )
2951            .unwrap();
2952            let offsets = (mode == UnionMode::Dense).then(|| vec![2, 0, 1].into());
2953            let union: ArrayRef = Arc::new(
2954                UnionArray::try_new(
2955                    fields,
2956                    vec![3_i8, 7, 3].into(),
2957                    offsets,
2958                    vec![
2959                        Arc::new(Int32Array::from(vec![Some(11), None, Some(33)])),
2960                        Arc::new(Int32Array::from(vec![Some(101), Some(202), None])),
2961                    ],
2962                )
2963                .unwrap(),
2964            );
2965            let item = Arc::new(Field::new("item", union.data_type().clone(), true));
2966            let list: ArrayRef = Arc::new(ListArray::new(
2967                item,
2968                arrow_buffer::OffsetBuffer::from_lengths([1, 2]),
2969                union,
2970                None,
2971            ));
2972            for (offset, len) in [(0, 2), (1, 1), (2, 0)] {
2973                let array = list.slice(offset, len);
2974                array.to_data().validate_full().unwrap();
2975                let expected = decoded(&array);
2976                let schema = Arc::new(Schema::new(vec![Field::new(
2977                    "v",
2978                    array.data_type().clone(),
2979                    true,
2980                )]));
2981                let batch = RecordBatch::try_new(schema, vec![array]).unwrap();
2982                for output in [
2983                    deserialize_file(serialize_file(&batch)),
2984                    deserialize_stream(serialize_stream(&batch)),
2985                ] {
2986                    output.column(0).to_data().validate_full().unwrap();
2987                    assert_eq!(decoded(output.column(0)), expected);
2988                }
2989            }
2990        }
2991    }
2992
2993    fn serialize_file(rb: &RecordBatch) -> Vec<u8> {
2994        let mut writer = FileWriter::try_new(vec![], rb.schema_ref()).unwrap();
2995        writer.write(rb).unwrap();
2996        writer.finish().unwrap();
2997        writer.into_inner().unwrap()
2998    }
2999
3000    fn deserialize_file(bytes: Vec<u8>) -> RecordBatch {
3001        let mut reader = FileReader::try_new(Cursor::new(bytes), None).unwrap();
3002        reader.next().unwrap().unwrap()
3003    }
3004
3005    fn serialize_stream(record: &RecordBatch) -> Vec<u8> {
3006        // Use 8-byte alignment so that the various `truncate_*` tests can be compactly written,
3007        // without needing to construct a giant array to spill over the 64-byte default alignment
3008        // boundary.
3009        const IPC_ALIGNMENT: usize = 8;
3010
3011        let mut stream_writer = StreamWriter::try_new_with_options(
3012            vec![],
3013            record.schema_ref(),
3014            IpcWriteOptions::try_new(IPC_ALIGNMENT, false, MetadataVersion::V5).unwrap(),
3015        )
3016        .unwrap();
3017        stream_writer.write(record).unwrap();
3018        stream_writer.finish().unwrap();
3019        stream_writer.into_inner().unwrap()
3020    }
3021
3022    fn deserialize_stream(bytes: Vec<u8>) -> RecordBatch {
3023        let mut stream_reader = StreamReader::try_new(Cursor::new(bytes), None).unwrap();
3024        stream_reader.next().unwrap().unwrap()
3025    }
3026
3027    /// Encodes record batches with [`StreamEncoder`] into one contiguous byte vector.
3028    ///
3029    /// This still exercises the sans-IO encoder path; `Vec<u8>` is only used
3030    /// as a convenient [`Write`] sink for comparing the resulting byte stream.
3031    fn encode_stream(
3032        schema: &Schema,
3033        batches: &[RecordBatch],
3034        options: IpcWriteOptions,
3035    ) -> Vec<u8> {
3036        let mut encoder = StreamEncoder::try_new_with_options(schema, options).unwrap();
3037        let mut bytes = Vec::new();
3038        for batch in batches {
3039            for buffer in encoder.encode(batch).unwrap() {
3040                bytes.write_all(buffer.as_slice()).unwrap();
3041            }
3042        }
3043        for buffer in encoder.finish().unwrap() {
3044            bytes.write_all(buffer.as_slice()).unwrap();
3045        }
3046        bytes
3047    }
3048
3049    fn write_stream(schema: &Schema, batches: &[RecordBatch], options: IpcWriteOptions) -> Vec<u8> {
3050        let mut bytes = Vec::new();
3051        let mut writer = StreamWriter::try_new_with_options(&mut bytes, schema, options).unwrap();
3052        for batch in batches {
3053            writer.write(batch).unwrap();
3054        }
3055        writer.finish().unwrap();
3056        bytes
3057    }
3058
3059    // StreamEncoder and StreamWriter currently use separate encoding paths, so these tests
3060    // verify the new sans-IO API preserves the existing IPC stream byte layout.
3061    #[tokio::test]
3062    async fn test_stream_encoder_async_writer_matches_stream_writer() {
3063        use tokio::io::{AsyncReadExt, AsyncWriteExt};
3064
3065        let batch = record_batch!(("a", Int32, [1, 2, 3]), ("b", Utf8, ["x", "y", "z"])).unwrap();
3066        let options = IpcWriteOptions::default();
3067        let expected = write_stream(
3068            batch.schema_ref(),
3069            std::slice::from_ref(&batch),
3070            options.clone(),
3071        );
3072
3073        let (mut sink, mut source) = tokio::io::duplex(64);
3074        let read = tokio::spawn(async move {
3075            let mut bytes = Vec::new();
3076            source.read_to_end(&mut bytes).await.unwrap();
3077            bytes
3078        });
3079
3080        let mut encoder = StreamEncoder::try_new_with_options(batch.schema_ref(), options).unwrap();
3081        for buffer in encoder.encode(&batch).unwrap() {
3082            sink.write_all(buffer.as_slice()).await.unwrap();
3083        }
3084        for buffer in encoder.finish().unwrap() {
3085            sink.write_all(buffer.as_slice()).await.unwrap();
3086        }
3087        sink.shutdown().await.unwrap();
3088
3089        let encoded = read.await.unwrap();
3090        assert_eq!(encoded, expected);
3091
3092        let mut reader = StreamReader::try_new(Cursor::new(encoded), None).unwrap();
3093        assert_eq!(reader.next().unwrap().unwrap(), batch);
3094        assert!(reader.next().is_none());
3095    }
3096
3097    #[test]
3098    fn test_stream_encoder_empty_stream_matches_stream_writer() {
3099        let schema = Schema::new(vec![Field::new("a", DataType::Int32, true)]);
3100        let options = IpcWriteOptions::default();
3101        let encoded = encode_stream(&schema, &[], options.clone());
3102        let written = write_stream(&schema, &[], options);
3103
3104        assert_eq!(encoded, written);
3105
3106        let mut reader = StreamReader::try_new(Cursor::new(encoded), None).unwrap();
3107        assert!(reader.next().is_none());
3108    }
3109
3110    #[test]
3111    fn test_stream_encoder_dictionary_batches_match_stream_writer() {
3112        let schema = Arc::new(Schema::new(vec![Field::new(
3113            "a",
3114            DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Utf8)),
3115            false,
3116        )]));
3117        let batch = RecordBatch::try_new(
3118            schema.clone(),
3119            vec![Arc::new(DictionaryArray::new(
3120                UInt8Array::from_iter_values([0, 1, 0]),
3121                Arc::new(StringArray::from_iter_values(["a", "b"])),
3122            ))],
3123        )
3124        .unwrap();
3125        let options = IpcWriteOptions::default();
3126        let encoded = encode_stream(&schema, std::slice::from_ref(&batch), options.clone());
3127        let written = write_stream(&schema, std::slice::from_ref(&batch), options);
3128
3129        assert_eq!(encoded, written);
3130
3131        let mut reader = StreamReader::try_new(Cursor::new(encoded), None).unwrap();
3132        assert_eq!(reader.next().unwrap().unwrap(), batch);
3133        assert!(reader.next().is_none());
3134    }
3135
3136    #[test]
3137    #[cfg(feature = "lz4")]
3138    fn test_write_empty_record_batch_lz4_compression() {
3139        let schema = Schema::new(vec![Field::new("field1", DataType::Int32, true)]);
3140        let values: Vec<Option<i32>> = vec![];
3141        let array = Int32Array::from(values);
3142        let record_batch =
3143            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(array)]).unwrap();
3144
3145        let mut file = tempfile::tempfile().unwrap();
3146
3147        {
3148            let write_option = IpcWriteOptions::try_new(8, false, crate::MetadataVersion::V5)
3149                .unwrap()
3150                .try_with_compression(Some(crate::CompressionType::LZ4_FRAME))
3151                .unwrap();
3152
3153            let mut writer =
3154                FileWriter::try_new_with_options(&mut file, &schema, write_option).unwrap();
3155            writer.write(&record_batch).unwrap();
3156            writer.finish().unwrap();
3157        }
3158        file.rewind().unwrap();
3159        {
3160            // read file
3161            let reader = FileReader::try_new(file, None).unwrap();
3162            for read_batch in reader {
3163                read_batch
3164                    .unwrap()
3165                    .columns()
3166                    .iter()
3167                    .zip(record_batch.columns())
3168                    .for_each(|(a, b)| {
3169                        assert_eq!(a.data_type(), b.data_type());
3170                        assert_eq!(a.len(), b.len());
3171                        assert_eq!(a.null_count(), b.null_count());
3172                    });
3173            }
3174        }
3175    }
3176
3177    #[test]
3178    #[cfg(feature = "lz4")]
3179    fn test_write_file_with_lz4_compression() {
3180        let schema = Schema::new(vec![Field::new("field1", DataType::Int32, true)]);
3181        let values: Vec<Option<i32>> = vec![Some(12), Some(1)];
3182        let array = Int32Array::from(values);
3183        let record_batch =
3184            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(array)]).unwrap();
3185
3186        let mut file = tempfile::tempfile().unwrap();
3187        {
3188            let write_option = IpcWriteOptions::try_new(8, false, crate::MetadataVersion::V5)
3189                .unwrap()
3190                .try_with_compression(Some(crate::CompressionType::LZ4_FRAME))
3191                .unwrap();
3192
3193            let mut writer =
3194                FileWriter::try_new_with_options(&mut file, &schema, write_option).unwrap();
3195            writer.write(&record_batch).unwrap();
3196            writer.finish().unwrap();
3197        }
3198        file.rewind().unwrap();
3199        {
3200            // read file
3201            let reader = FileReader::try_new(file, None).unwrap();
3202            for read_batch in reader {
3203                read_batch
3204                    .unwrap()
3205                    .columns()
3206                    .iter()
3207                    .zip(record_batch.columns())
3208                    .for_each(|(a, b)| {
3209                        assert_eq!(a.data_type(), b.data_type());
3210                        assert_eq!(a.len(), b.len());
3211                        assert_eq!(a.null_count(), b.null_count());
3212                    });
3213            }
3214        }
3215    }
3216
3217    /// Batch exercising nulls, a dictionary column, and enough bytes that lz4 emits several
3218    /// blocks even at the smallest configurable block size.
3219    fn lz4_block_size_batch() -> RecordBatch {
3220        let schema = Schema::new(vec![
3221            Field::new("ints", DataType::Int32, true),
3222            Field::new(
3223                "words",
3224                DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
3225                false,
3226            ),
3227        ]);
3228        let ints = Int32Array::from(
3229            (0..30_000)
3230                .map(|i| if i % 13 == 0 { None } else { Some(i) })
3231                .collect::<Vec<Option<i32>>>(),
3232        );
3233        let keys = Int32Array::from((0..30_000).map(|i| i % 5).collect::<Vec<i32>>());
3234        let values = StringArray::from(vec!["zero", "one", "two", "three", "four"]);
3235        let words = DictionaryArray::new(keys, Arc::new(values));
3236        RecordBatch::try_new(Arc::new(schema), vec![Arc::new(ints), Arc::new(words)]).unwrap()
3237    }
3238
3239    #[test]
3240    fn test_lz4_block_size_options() {
3241        let options = || IpcWriteOptions::try_new(8, false, MetadataVersion::V5).unwrap();
3242
3243        assert_eq!(options().lz4_block_size(), Lz4BlockSize::DEFAULT);
3244        assert_eq!(
3245            options()
3246                .try_with_lz4_block_size(None)
3247                .unwrap()
3248                .lz4_block_size(),
3249            Lz4BlockSize::DEFAULT
3250        );
3251        assert_eq!(
3252            options()
3253                .try_with_lz4_block_size(Some(1024 * 1024))
3254                .unwrap()
3255                .lz4_block_size(),
3256            Lz4BlockSize::Max1MiB
3257        );
3258
3259        for block_size in [0, 32 * 1024, 128 * 1024, 2 * 1024 * 1024, 8 * 1024 * 1024] {
3260            let err = options()
3261                .try_with_lz4_block_size(Some(block_size))
3262                .expect_err("unsupported block size must be rejected");
3263            assert!(
3264                err.to_string().contains("Unsupported lz4 block size"),
3265                "unexpected error: {err}"
3266            );
3267        }
3268
3269        let options = IpcWriteOptions::try_new(8, false, MetadataVersion::V4).unwrap();
3270        let err = options
3271            .try_with_lz4_block_size(Some(64 * 1024))
3272            .expect_err("block size below metadata V5 must be rejected");
3273        assert!(
3274            err.to_string().contains("metadata v5"),
3275            "unexpected error: {err}"
3276        );
3277
3278        let options = IpcWriteOptions::try_new(8, false, MetadataVersion::V5)
3279            .unwrap()
3280            .try_with_compression(Some(crate::CompressionType::ZSTD))
3281            .unwrap();
3282        let err = options
3283            .try_with_lz4_block_size(Some(64 * 1024))
3284            .expect_err("lz4 block size must be rejected for ZSTD");
3285        assert!(err.to_string().contains("ZSTD"), "unexpected error: {err}");
3286
3287        let err = IpcWriteOptions::try_new(8, false, MetadataVersion::V5)
3288            .unwrap()
3289            .try_with_lz4_block_size(Some(64 * 1024))
3290            .unwrap()
3291            .try_with_compression(Some(crate::CompressionType::ZSTD))
3292            .expect_err("ZSTD must be rejected after setting an lz4 block size");
3293        assert!(err.to_string().contains("ZSTD"), "unexpected error: {err}");
3294    }
3295
3296    #[test]
3297    #[cfg(feature = "lz4")]
3298    fn test_lz4_block_size_configurable_end_to_end() {
3299        let batch = lz4_block_size_batch();
3300        let schema = batch.schema();
3301        let data_gen = IpcDataGenerator::default();
3302        let mut ipc_write_context = IpcWriteContext::default();
3303
3304        let sizes: [Option<usize>; 5] = [
3305            None,
3306            Some(64 * 1024),
3307            Some(256 * 1024),
3308            Some(1024 * 1024),
3309            Some(4 * 1024 * 1024),
3310        ];
3311        let mut outputs = Vec::with_capacity(sizes.len());
3312        for block_size in sizes {
3313            let options = IpcWriteOptions::try_new(8, false, MetadataVersion::V5)
3314                .unwrap()
3315                .try_with_compression(Some(crate::CompressionType::LZ4_FRAME))
3316                .unwrap()
3317                .try_with_lz4_block_size(block_size)
3318                .unwrap();
3319
3320            let mut dictionary_tracker = DictionaryTracker::new(false);
3321            let mut encoded = Vec::new();
3322            let schema_data = data_gen.schema_to_bytes_with_dictionary_tracker(
3323                &schema,
3324                &mut dictionary_tracker,
3325                &options,
3326            );
3327            write_message(&mut encoded, schema_data, &options).unwrap();
3328
3329            let (encoded_dictionaries, encoded_batch) = data_gen
3330                .encode(
3331                    &batch,
3332                    &mut dictionary_tracker,
3333                    &options,
3334                    &mut ipc_write_context,
3335                )
3336                .unwrap();
3337            for dictionary in encoded_dictionaries {
3338                write_message(&mut encoded, dictionary, &options).unwrap();
3339            }
3340            write_message(&mut encoded, encoded_batch, &options).unwrap();
3341
3342            // Reading must not depend on the block size the writer chose.
3343            let mut reader = StreamReader::try_new(Cursor::new(encoded.as_slice()), None).unwrap();
3344            assert_eq!(reader.next().unwrap().unwrap(), batch, "{block_size:?}");
3345            assert!(reader.next().is_none());
3346
3347            outputs.push(encoded);
3348        }
3349
3350        // The option must reach the encoder: an explicitly configured default is byte
3351        // identical to the untouched default, while every other size changes the frame
3352        // header and therefore the output.
3353        assert_eq!(
3354            outputs[0], outputs[2],
3355            "explicit 256 KiB must match the default"
3356        );
3357        assert_ne!(outputs[0], outputs[1], "64 KiB must differ from default");
3358        assert_ne!(outputs[0], outputs[3], "1 MiB must differ from default");
3359        assert_ne!(outputs[0], outputs[4], "4 MiB must differ from default");
3360    }
3361
3362    #[test]
3363    #[cfg(feature = "zstd")]
3364    fn test_write_file_with_zstd_compression() {
3365        let schema = Schema::new(vec![Field::new("field1", DataType::Int32, true)]);
3366        let values: Vec<Option<i32>> = vec![Some(12), Some(1)];
3367        let array = Int32Array::from(values);
3368        let record_batch =
3369            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(array)]).unwrap();
3370        let mut file = tempfile::tempfile().unwrap();
3371        {
3372            let write_option = IpcWriteOptions::try_new(8, false, crate::MetadataVersion::V5)
3373                .unwrap()
3374                .try_with_compression(Some(crate::CompressionType::ZSTD))
3375                .unwrap()
3376                .try_with_compression_level(Some(1))
3377                .unwrap();
3378
3379            let mut writer =
3380                FileWriter::try_new_with_options(&mut file, &schema, write_option).unwrap();
3381            writer.write(&record_batch).unwrap();
3382            writer.finish().unwrap();
3383        }
3384        file.rewind().unwrap();
3385        {
3386            // read file
3387            let reader = FileReader::try_new(file, None).unwrap();
3388            for read_batch in reader {
3389                read_batch
3390                    .unwrap()
3391                    .columns()
3392                    .iter()
3393                    .zip(record_batch.columns())
3394                    .for_each(|(a, b)| {
3395                        assert_eq!(a.data_type(), b.data_type());
3396                        assert_eq!(a.len(), b.len());
3397                        assert_eq!(a.null_count(), b.null_count());
3398                    });
3399            }
3400        }
3401    }
3402
3403    #[test]
3404    fn test_write_file() {
3405        let schema = Schema::new(vec![Field::new("field1", DataType::UInt32, true)]);
3406        let values: Vec<Option<u32>> = vec![
3407            Some(999),
3408            None,
3409            Some(235),
3410            Some(123),
3411            None,
3412            None,
3413            None,
3414            None,
3415            None,
3416        ];
3417        let array1 = UInt32Array::from(values);
3418        let batch =
3419            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(array1) as ArrayRef])
3420                .unwrap();
3421        let mut file = tempfile::tempfile().unwrap();
3422        {
3423            let mut writer = FileWriter::try_new(&mut file, &schema).unwrap();
3424
3425            writer.write(&batch).unwrap();
3426            writer.finish().unwrap();
3427        }
3428        file.rewind().unwrap();
3429
3430        {
3431            let mut reader = FileReader::try_new(file, None).unwrap();
3432            while let Some(Ok(read_batch)) = reader.next() {
3433                read_batch
3434                    .columns()
3435                    .iter()
3436                    .zip(batch.columns())
3437                    .for_each(|(a, b)| {
3438                        assert_eq!(a.data_type(), b.data_type());
3439                        assert_eq!(a.len(), b.len());
3440                        assert_eq!(a.null_count(), b.null_count());
3441                    });
3442            }
3443        }
3444    }
3445
3446    #[test]
3447    fn test_empty_utf8_ipc_writes_nonempty_offsets_buffer() {
3448        let name = StringArray::from(Vec::<String>::new());
3449        let [offsets, values] = get_byte_array_buffers::<i32>(&name.to_data());
3450
3451        assert_eq!(name.len(), 0);
3452        assert_eq!(
3453            offsets.len(),
3454            std::mem::size_of::<i32>(),
3455            "offsets buffer should contain one zero i32 offset"
3456        );
3457        assert_eq!(values.len(), 0, "values buffer should remain empty");
3458    }
3459
3460    #[test]
3461    fn test_empty_large_utf8_ipc_writes_nonempty_offsets_buffer() {
3462        let name = LargeStringArray::from(Vec::<String>::new());
3463        let [offsets, values] = get_byte_array_buffers::<i64>(&name.to_data());
3464
3465        assert_eq!(name.len(), 0);
3466        assert_eq!(
3467            offsets.len(),
3468            std::mem::size_of::<i64>(),
3469            "offsets buffer should contain one zero i64 offset"
3470        );
3471        assert_eq!(values.len(), 0, "values buffer should remain empty");
3472    }
3473
3474    #[test]
3475    fn test_empty_list_ipc_writes_nonempty_offsets_buffer() {
3476        let list = GenericListBuilder::<i32, _>::new(UInt32Builder::new()).finish();
3477        let (offsets, child_data) = get_list_array_buffers::<i32>(&list.to_data());
3478
3479        assert_eq!(list.len(), 0);
3480        assert_eq!(
3481            offsets.len(),
3482            std::mem::size_of::<i32>(),
3483            "offsets buffer should contain one zero i32 offset"
3484        );
3485        assert_eq!(child_data.len(), 0, "child data should remain empty");
3486    }
3487
3488    #[test]
3489    fn test_empty_large_list_ipc_writes_nonempty_offsets_buffer() {
3490        let list = GenericListBuilder::<i64, _>::new(UInt32Builder::new()).finish();
3491        let (offsets, child_data) = get_list_array_buffers::<i64>(&list.to_data());
3492
3493        assert_eq!(list.len(), 0);
3494        assert_eq!(
3495            offsets.len(),
3496            std::mem::size_of::<i64>(),
3497            "offsets buffer should contain one zero i64 offset"
3498        );
3499        assert_eq!(child_data.len(), 0, "child data should remain empty");
3500    }
3501
3502    fn write_null_file(options: IpcWriteOptions) {
3503        let schema = Schema::new(vec![
3504            Field::new("nulls", DataType::Null, true),
3505            Field::new("int32s", DataType::Int32, false),
3506            Field::new("nulls2", DataType::Null, true),
3507            Field::new("f64s", DataType::Float64, false),
3508        ]);
3509        let array1 = NullArray::new(32);
3510        let array2 = Int32Array::from(vec![1; 32]);
3511        let array3 = NullArray::new(32);
3512        let array4 = Float64Array::from(vec![f64::NAN; 32]);
3513        let batch = RecordBatch::try_new(
3514            Arc::new(schema.clone()),
3515            vec![
3516                Arc::new(array1) as ArrayRef,
3517                Arc::new(array2) as ArrayRef,
3518                Arc::new(array3) as ArrayRef,
3519                Arc::new(array4) as ArrayRef,
3520            ],
3521        )
3522        .unwrap();
3523        let mut file = tempfile::tempfile().unwrap();
3524        {
3525            let mut writer = FileWriter::try_new_with_options(&mut file, &schema, options).unwrap();
3526
3527            writer.write(&batch).unwrap();
3528            writer.finish().unwrap();
3529        }
3530
3531        file.rewind().unwrap();
3532
3533        {
3534            let reader = FileReader::try_new(file, None).unwrap();
3535            reader.for_each(|maybe_batch| {
3536                maybe_batch
3537                    .unwrap()
3538                    .columns()
3539                    .iter()
3540                    .zip(batch.columns())
3541                    .for_each(|(a, b)| {
3542                        assert_eq!(a.data_type(), b.data_type());
3543                        assert_eq!(a.len(), b.len());
3544                        assert_eq!(a.null_count(), b.null_count());
3545                    });
3546            });
3547        }
3548    }
3549    #[test]
3550    fn test_write_null_file_v4() {
3551        write_null_file(IpcWriteOptions::try_new(8, false, MetadataVersion::V4).unwrap());
3552        write_null_file(IpcWriteOptions::try_new(8, true, MetadataVersion::V4).unwrap());
3553        write_null_file(IpcWriteOptions::try_new(64, false, MetadataVersion::V4).unwrap());
3554        write_null_file(IpcWriteOptions::try_new(64, true, MetadataVersion::V4).unwrap());
3555    }
3556
3557    #[test]
3558    fn test_write_null_file_v5() {
3559        write_null_file(IpcWriteOptions::try_new(8, false, MetadataVersion::V5).unwrap());
3560        write_null_file(IpcWriteOptions::try_new(64, false, MetadataVersion::V5).unwrap());
3561    }
3562
3563    #[test]
3564    fn track_union_nested_dict() {
3565        let inner: DictionaryArray<Int32Type> = vec!["a", "b", "a"].into_iter().collect();
3566
3567        let array = Arc::new(inner) as ArrayRef;
3568
3569        // Dict field with id 2
3570        #[expect(deprecated)]
3571        let dctfield = Field::new_dict("dict", array.data_type().clone(), false, 0, false);
3572        let union_fields = std::iter::once((0, Arc::new(dctfield))).collect();
3573
3574        let types = [0, 0, 0].into_iter().collect::<ScalarBuffer<i8>>();
3575        let offsets = [0, 1, 2].into_iter().collect::<ScalarBuffer<i32>>();
3576
3577        let union = UnionArray::try_new(union_fields, types, Some(offsets), vec![array]).unwrap();
3578
3579        let schema = Arc::new(Schema::new(vec![Field::new(
3580            "union",
3581            union.data_type().clone(),
3582            false,
3583        )]));
3584
3585        let r#gen = IpcDataGenerator::default();
3586        let mut dict_tracker = DictionaryTracker::new(false);
3587        r#gen.schema_to_bytes_with_dictionary_tracker(
3588            &schema,
3589            &mut dict_tracker,
3590            &IpcWriteOptions::default(),
3591        );
3592
3593        let batch = RecordBatch::try_new(schema, vec![Arc::new(union)]).unwrap();
3594
3595        r#gen
3596            .encode(
3597                &batch,
3598                &mut dict_tracker,
3599                &Default::default(),
3600                &mut Default::default(),
3601            )
3602            .unwrap();
3603
3604        // The encoder will assign dict IDs itself to ensure uniqueness and ignore the dict ID in the schema
3605        // so we expect the dict will be keyed to 0
3606        assert!(dict_tracker.written.contains_key(&0));
3607    }
3608
3609    #[test]
3610    fn track_struct_nested_dict() {
3611        let inner: DictionaryArray<Int32Type> = vec!["a", "b", "a"].into_iter().collect();
3612
3613        let array = Arc::new(inner) as ArrayRef;
3614
3615        // Dict field with id 2
3616        #[expect(deprecated)]
3617        let dctfield = Arc::new(Field::new_dict(
3618            "dict",
3619            array.data_type().clone(),
3620            false,
3621            2,
3622            false,
3623        ));
3624
3625        let s = StructArray::from(vec![(dctfield, array)]);
3626        let struct_array = Arc::new(s) as ArrayRef;
3627
3628        let schema = Arc::new(Schema::new(vec![Field::new(
3629            "struct",
3630            struct_array.data_type().clone(),
3631            false,
3632        )]));
3633
3634        let r#gen = IpcDataGenerator::default();
3635        let mut dict_tracker = DictionaryTracker::new(false);
3636        r#gen.schema_to_bytes_with_dictionary_tracker(
3637            &schema,
3638            &mut dict_tracker,
3639            &IpcWriteOptions::default(),
3640        );
3641
3642        let batch = RecordBatch::try_new(schema, vec![struct_array]).unwrap();
3643
3644        r#gen
3645            .encode(
3646                &batch,
3647                &mut dict_tracker,
3648                &Default::default(),
3649                &mut Default::default(),
3650            )
3651            .unwrap();
3652
3653        assert!(dict_tracker.written.contains_key(&0));
3654    }
3655
3656    fn write_union_file(options: IpcWriteOptions) {
3657        let schema = Schema::new(vec![Field::new_union(
3658            "union",
3659            vec![0, 1],
3660            vec![
3661                Field::new("a", DataType::Int32, false),
3662                Field::new("c", DataType::Float64, false),
3663            ],
3664            UnionMode::Sparse,
3665        )]);
3666        let mut builder = UnionBuilder::with_capacity_sparse(5);
3667        builder.append::<Int32Type>("a", 1).unwrap();
3668        builder.append_null::<Int32Type>("a").unwrap();
3669        builder.append::<Float64Type>("c", 3.0).unwrap();
3670        builder.append_null::<Float64Type>("c").unwrap();
3671        builder.append::<Int32Type>("a", 4).unwrap();
3672        let union = builder.build().unwrap();
3673
3674        let batch =
3675            RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(union) as ArrayRef])
3676                .unwrap();
3677
3678        let mut file = tempfile::tempfile().unwrap();
3679        {
3680            let mut writer = FileWriter::try_new_with_options(&mut file, &schema, options).unwrap();
3681
3682            writer.write(&batch).unwrap();
3683            writer.finish().unwrap();
3684        }
3685        file.rewind().unwrap();
3686
3687        {
3688            let reader = FileReader::try_new(file, None).unwrap();
3689            reader.for_each(|maybe_batch| {
3690                maybe_batch
3691                    .unwrap()
3692                    .columns()
3693                    .iter()
3694                    .zip(batch.columns())
3695                    .for_each(|(a, b)| {
3696                        assert_eq!(a.data_type(), b.data_type());
3697                        assert_eq!(a.len(), b.len());
3698                        assert_eq!(a.null_count(), b.null_count());
3699                    });
3700            });
3701        }
3702    }
3703
3704    #[test]
3705    fn test_write_union_file_v4_v5() {
3706        write_union_file(IpcWriteOptions::try_new(8, false, MetadataVersion::V4).unwrap());
3707        write_union_file(IpcWriteOptions::try_new(8, false, MetadataVersion::V5).unwrap());
3708    }
3709
3710    #[test]
3711    fn test_write_view_types() {
3712        const LONG_TEST_STRING: &str =
3713            "This is a long string to make sure binary view array handles it";
3714        let schema = Schema::new(vec![
3715            Field::new("field1", DataType::BinaryView, true),
3716            Field::new("field2", DataType::Utf8View, true),
3717        ]);
3718        let values: Vec<Option<&[u8]>> = vec![
3719            Some(b"foo"),
3720            Some(b"bar"),
3721            Some(LONG_TEST_STRING.as_bytes()),
3722        ];
3723        let binary_array = BinaryViewArray::from_iter(values);
3724        let utf8_array =
3725            StringViewArray::from_iter(vec![Some("foo"), Some("bar"), Some(LONG_TEST_STRING)]);
3726        let record_batch = RecordBatch::try_new(
3727            Arc::new(schema.clone()),
3728            vec![Arc::new(binary_array), Arc::new(utf8_array)],
3729        )
3730        .unwrap();
3731
3732        let mut file = tempfile::tempfile().unwrap();
3733        {
3734            let mut writer = FileWriter::try_new(&mut file, &schema).unwrap();
3735            writer.write(&record_batch).unwrap();
3736            writer.finish().unwrap();
3737        }
3738        file.rewind().unwrap();
3739        {
3740            let mut reader = FileReader::try_new(&file, None).unwrap();
3741            let read_batch = reader.next().unwrap().unwrap();
3742            read_batch
3743                .columns()
3744                .iter()
3745                .zip(record_batch.columns())
3746                .for_each(|(a, b)| {
3747                    assert_eq!(a, b);
3748                });
3749        }
3750        file.rewind().unwrap();
3751        {
3752            let mut reader = FileReader::try_new(&file, Some(vec![0])).unwrap();
3753            let read_batch = reader.next().unwrap().unwrap();
3754            assert_eq!(read_batch.num_columns(), 1);
3755            let read_array = read_batch.column(0);
3756            let write_array = record_batch.column(0);
3757            assert_eq!(read_array, write_array);
3758        }
3759    }
3760
3761    #[test]
3762    #[cfg_attr(miri, ignore)] // Takes too long
3763    fn truncate_ipc_record_batch() {
3764        fn create_batch(rows: usize) -> RecordBatch {
3765            let schema = Schema::new(vec![
3766                Field::new("a", DataType::Int32, false),
3767                Field::new("b", DataType::Utf8, false),
3768            ]);
3769
3770            let a = Int32Array::from_iter_values(0..rows as i32);
3771            let b = StringArray::from_iter_values((0..rows).map(|i| i.to_string()));
3772
3773            RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a), Arc::new(b)]).unwrap()
3774        }
3775
3776        let big_record_batch = create_batch(65536);
3777
3778        let length = 5;
3779        let small_record_batch = create_batch(length);
3780
3781        let offset = 2;
3782        let record_batch_slice = big_record_batch.slice(offset, length);
3783        assert!(
3784            serialize_stream(&big_record_batch).len() > serialize_stream(&small_record_batch).len()
3785        );
3786        assert_eq!(
3787            serialize_stream(&small_record_batch).len(),
3788            serialize_stream(&record_batch_slice).len()
3789        );
3790
3791        assert_eq!(
3792            deserialize_stream(serialize_stream(&record_batch_slice)),
3793            record_batch_slice
3794        );
3795    }
3796
3797    #[test]
3798    fn truncate_ipc_record_batch_with_nulls() {
3799        fn create_batch() -> RecordBatch {
3800            let schema = Schema::new(vec![
3801                Field::new("a", DataType::Int32, true),
3802                Field::new("b", DataType::Utf8, true),
3803            ]);
3804
3805            let a = Int32Array::from(vec![Some(1), None, Some(1), None, Some(1)]);
3806            let b = StringArray::from(vec![None, Some("a"), Some("a"), None, Some("a")]);
3807
3808            RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a), Arc::new(b)]).unwrap()
3809        }
3810
3811        let record_batch = create_batch();
3812        let record_batch_slice = record_batch.slice(1, 2);
3813        let deserialized_batch = deserialize_stream(serialize_stream(&record_batch_slice));
3814
3815        assert!(
3816            serialize_stream(&record_batch).len() > serialize_stream(&record_batch_slice).len()
3817        );
3818
3819        assert!(deserialized_batch.column(0).is_null(0));
3820        assert!(deserialized_batch.column(0).is_valid(1));
3821        assert!(deserialized_batch.column(1).is_valid(0));
3822        assert!(deserialized_batch.column(1).is_valid(1));
3823
3824        assert_eq!(record_batch_slice, deserialized_batch);
3825    }
3826
3827    #[test]
3828    fn test_write_empty_validity_buffer_without_nulls() {
3829        let batch = RecordBatch::try_from_iter([
3830            ("a", Arc::new(Int32Array::from(vec![1, 2])) as _),
3831            // Keeps a null buffer, but the slice has no nulls
3832            (
3833                "b",
3834                Arc::new(Int32Array::from(vec![None, Some(2), Some(3)]).slice(1, 2)) as _,
3835            ),
3836            ("c", Arc::new(Int32Array::from(vec![Some(1), None])) as _),
3837        ])
3838        .unwrap();
3839        assert_eq!(batch.column(1).nulls().map(|n| n.null_count()), Some(0));
3840
3841        let (_, encoded) = IpcDataGenerator::default()
3842            .encode(
3843                &batch,
3844                &mut DictionaryTracker::new(false),
3845                &Default::default(),
3846                &mut Default::default(),
3847            )
3848            .unwrap();
3849        let message = crate::root_as_message(&encoded.ipc_message).unwrap();
3850        let buffers = message.header_as_record_batch().unwrap().buffers().unwrap();
3851        // Each column writes a validity buffer, then a values buffer
3852        let validity_lengths: Vec<_> = buffers.iter().step_by(2).map(|b| b.length()).collect();
3853        assert_eq!(validity_lengths, [0, 0, 1]);
3854
3855        assert_eq!(deserialize_stream(serialize_stream(&batch)), batch);
3856    }
3857
3858    #[test]
3859    fn truncate_ipc_dictionary_array() {
3860        fn create_batch() -> RecordBatch {
3861            let values: StringArray = [Some("foo"), Some("bar"), Some("baz")]
3862                .into_iter()
3863                .collect();
3864            let keys: Int32Array = [Some(0), Some(2), None, Some(1)].into_iter().collect();
3865
3866            let array = DictionaryArray::new(keys, Arc::new(values));
3867
3868            let schema = Schema::new(vec![Field::new("dict", array.data_type().clone(), true)]);
3869
3870            RecordBatch::try_new(Arc::new(schema), vec![Arc::new(array)]).unwrap()
3871        }
3872
3873        let record_batch = create_batch();
3874        let record_batch_slice = record_batch.slice(1, 2);
3875        let deserialized_batch = deserialize_stream(serialize_stream(&record_batch_slice));
3876
3877        assert!(
3878            serialize_stream(&record_batch).len() > serialize_stream(&record_batch_slice).len()
3879        );
3880
3881        assert!(deserialized_batch.column(0).is_valid(0));
3882        assert!(deserialized_batch.column(0).is_null(1));
3883
3884        assert_eq!(record_batch_slice, deserialized_batch);
3885    }
3886
3887    #[test]
3888    fn truncate_ipc_struct_array() {
3889        fn create_batch() -> RecordBatch {
3890            let strings: StringArray = [Some("foo"), None, Some("bar"), Some("baz")]
3891                .into_iter()
3892                .collect();
3893            let ints: Int32Array = [Some(0), Some(2), None, Some(1)].into_iter().collect();
3894
3895            let struct_array = StructArray::from(vec![
3896                (
3897                    Arc::new(Field::new("s", DataType::Utf8, true)),
3898                    Arc::new(strings) as ArrayRef,
3899                ),
3900                (
3901                    Arc::new(Field::new("c", DataType::Int32, true)),
3902                    Arc::new(ints) as ArrayRef,
3903                ),
3904            ]);
3905
3906            let schema = Schema::new(vec![Field::new(
3907                "struct_array",
3908                struct_array.data_type().clone(),
3909                true,
3910            )]);
3911
3912            RecordBatch::try_new(Arc::new(schema), vec![Arc::new(struct_array)]).unwrap()
3913        }
3914
3915        let record_batch = create_batch();
3916        let record_batch_slice = record_batch.slice(1, 2);
3917        let deserialized_batch = deserialize_stream(serialize_stream(&record_batch_slice));
3918
3919        assert!(
3920            serialize_stream(&record_batch).len() > serialize_stream(&record_batch_slice).len()
3921        );
3922
3923        let structs = deserialized_batch
3924            .column(0)
3925            .as_any()
3926            .downcast_ref::<StructArray>()
3927            .unwrap();
3928
3929        assert!(structs.column(0).is_null(0));
3930        assert!(structs.column(0).is_valid(1));
3931        assert!(structs.column(1).is_valid(0));
3932        assert!(structs.column(1).is_null(1));
3933        assert_eq!(record_batch_slice, deserialized_batch);
3934    }
3935
3936    #[test]
3937    fn truncate_ipc_string_array_with_all_empty_string() {
3938        fn create_batch() -> RecordBatch {
3939            let schema = Schema::new(vec![Field::new("a", DataType::Utf8, true)]);
3940            let a = StringArray::from(vec![Some(""), Some(""), Some(""), Some(""), Some("")]);
3941            RecordBatch::try_new(Arc::new(schema), vec![Arc::new(a)]).unwrap()
3942        }
3943
3944        let record_batch = create_batch();
3945        let record_batch_slice = record_batch.slice(0, 1);
3946        let deserialized_batch = deserialize_stream(serialize_stream(&record_batch_slice));
3947
3948        assert!(
3949            serialize_stream(&record_batch).len() > serialize_stream(&record_batch_slice).len()
3950        );
3951        assert_eq!(record_batch_slice, deserialized_batch);
3952    }
3953
3954    #[test]
3955    fn test_stream_writer_writes_array_slice() {
3956        let array = UInt32Array::from(vec![Some(1), Some(2), Some(3)]);
3957        assert_eq!(
3958            vec![Some(1), Some(2), Some(3)],
3959            array.iter().collect::<Vec<_>>()
3960        );
3961
3962        let sliced = array.slice(1, 2);
3963        assert_eq!(vec![Some(2), Some(3)], sliced.iter().collect::<Vec<_>>());
3964
3965        let batch = RecordBatch::try_new(
3966            Arc::new(Schema::new(vec![Field::new("a", DataType::UInt32, true)])),
3967            vec![Arc::new(sliced)],
3968        )
3969        .expect("new batch");
3970
3971        let mut writer = StreamWriter::try_new(vec![], batch.schema_ref()).expect("new writer");
3972        writer.write(&batch).expect("write");
3973        let outbuf = writer.into_inner().expect("inner");
3974
3975        let mut reader = StreamReader::try_new(&outbuf[..], None).expect("new reader");
3976        let read_batch = reader.next().unwrap().expect("read batch");
3977
3978        let read_array: &UInt32Array = read_batch.column(0).as_primitive();
3979        assert_eq!(
3980            vec![Some(2), Some(3)],
3981            read_array.iter().collect::<Vec<_>>()
3982        );
3983    }
3984
3985    #[test]
3986    fn test_large_slice_uint32() {
3987        ensure_roundtrip(Arc::new(UInt32Array::from_iter(
3988            (0..8000).map(|i| if i % 2 == 0 { Some(i) } else { None }),
3989        )));
3990    }
3991
3992    #[test]
3993    #[cfg_attr(miri, ignore)] // Takes too long
3994    fn test_large_slice_string() {
3995        let strings: Vec<_> = (0..8000)
3996            .map(|i| {
3997                if i % 2 == 0 {
3998                    Some(format!("value{i}"))
3999                } else {
4000                    None
4001                }
4002            })
4003            .collect();
4004
4005        ensure_roundtrip(Arc::new(StringArray::from(strings)));
4006    }
4007
4008    #[test]
4009    #[cfg_attr(miri, ignore)] // Takes too long
4010    fn test_large_slice_string_list() {
4011        let mut ls = ListBuilder::new(StringBuilder::new());
4012
4013        let mut s = String::new();
4014        for row_number in 0..8000 {
4015            if row_number % 2 == 0 {
4016                for list_element in 0..1000 {
4017                    s.clear();
4018                    use std::fmt::Write;
4019                    write!(&mut s, "value{row_number}-{list_element}").unwrap();
4020                    ls.values().append_value(&s);
4021                }
4022                ls.append(true)
4023            } else {
4024                ls.append(false); // null
4025            }
4026        }
4027
4028        ensure_roundtrip(Arc::new(ls.finish()));
4029    }
4030
4031    #[test]
4032    #[cfg_attr(miri, ignore)] // Takes too long
4033    fn test_large_slice_string_list_of_lists() {
4034        // The reason for the special test is to verify reencode_offsets which looks both at
4035        // the starting offset and the data offset.  So need a dataset where the starting_offset
4036        // is zero but the data offset is not.
4037        let mut ls = ListBuilder::new(ListBuilder::new(StringBuilder::new()));
4038
4039        for _ in 0..4000 {
4040            ls.values().append(true);
4041            ls.append(true)
4042        }
4043
4044        let mut s = String::new();
4045        for row_number in 0..4000 {
4046            if row_number % 2 == 0 {
4047                for list_element in 0..1000 {
4048                    s.clear();
4049                    use std::fmt::Write;
4050                    write!(&mut s, "value{row_number}-{list_element}").unwrap();
4051                    ls.values().values().append_value(&s);
4052                }
4053                ls.values().append(true);
4054                ls.append(true)
4055            } else {
4056                ls.append(false); // null
4057            }
4058        }
4059
4060        ensure_roundtrip(Arc::new(ls.finish()));
4061    }
4062
4063    /// Read/write a record batch to a File and Stream and ensure it is the same at the output
4064    fn ensure_roundtrip(array: ArrayRef) {
4065        let num_rows = array.len();
4066        let orig_batch = RecordBatch::try_from_iter(vec![("a", array)]).unwrap();
4067        // take off the first element
4068        let sliced_batch = orig_batch.slice(1, num_rows - 1);
4069
4070        let schema = orig_batch.schema();
4071        let stream_data = {
4072            let mut writer = StreamWriter::try_new(vec![], &schema).unwrap();
4073            writer.write(&sliced_batch).unwrap();
4074            writer.into_inner().unwrap()
4075        };
4076        let read_batch = {
4077            let projection = None;
4078            let mut reader = StreamReader::try_new(Cursor::new(stream_data), projection).unwrap();
4079            reader
4080                .next()
4081                .expect("expect no errors reading batch")
4082                .expect("expect batch")
4083        };
4084        assert_eq!(sliced_batch, read_batch);
4085
4086        let file_data = {
4087            let mut writer = FileWriter::try_new_buffered(vec![], &schema).unwrap();
4088            writer.write(&sliced_batch).unwrap();
4089            writer.into_inner().unwrap().into_inner().unwrap()
4090        };
4091        let read_batch = {
4092            let projection = None;
4093            let mut reader = FileReader::try_new(Cursor::new(file_data), projection).unwrap();
4094            reader
4095                .next()
4096                .expect("expect no errors reading batch")
4097                .expect("expect batch")
4098        };
4099        assert_eq!(sliced_batch, read_batch);
4100
4101        // TODO test file writer/reader
4102    }
4103
4104    #[test]
4105    fn encode_bools_slice() {
4106        // Test case for https://github.com/apache/arrow-rs/issues/3496
4107        assert_bool_roundtrip([true, false], 1, 1);
4108
4109        // slice somewhere in the middle
4110        assert_bool_roundtrip(
4111            [
4112                true, false, true, true, false, false, true, true, true, false, false, false, true,
4113                true, true, true, false, false, false, false, true, true, true, true, true, false,
4114                false, false, false, false,
4115            ],
4116            13,
4117            17,
4118        );
4119
4120        // start at byte boundary, end in the middle
4121        assert_bool_roundtrip(
4122            [
4123                true, false, true, true, false, false, true, true, true, false, false, false,
4124            ],
4125            8,
4126            2,
4127        );
4128
4129        // start and stop and byte boundary
4130        assert_bool_roundtrip(
4131            [
4132                true, false, true, true, false, false, true, true, true, false, false, false, true,
4133                true, true, true, true, false, false, false, false, false,
4134            ],
4135            8,
4136            8,
4137        );
4138    }
4139
4140    fn assert_bool_roundtrip<const N: usize>(bools: [bool; N], offset: usize, length: usize) {
4141        let val_bool_field = Field::new("val", DataType::Boolean, false);
4142
4143        let schema = Arc::new(Schema::new(vec![val_bool_field]));
4144
4145        let bools = BooleanArray::from(bools.to_vec());
4146
4147        let batch = RecordBatch::try_new(Arc::clone(&schema), vec![Arc::new(bools)]).unwrap();
4148        let batch = batch.slice(offset, length);
4149
4150        let data = serialize_stream(&batch);
4151        let batch2 = deserialize_stream(data);
4152        assert_eq!(batch, batch2);
4153    }
4154
4155    fn assert_empty_run_array_roundtrip<R: RunEndIndexType>() {
4156        let run_ends = PrimitiveArray::<R>::from_iter_values(
4157            [2, 5]
4158                .into_iter()
4159                .map(|v| R::Native::from_usize(v).unwrap()),
4160        );
4161        let values = Int32Array::from(vec![10, 20]);
4162        let array = RunArray::<R>::try_new(&run_ends, &values).unwrap();
4163        let empty = RunArray::<R>::from(ArrayData::new_empty(array.data_type()));
4164
4165        for source in [&array, &empty] {
4166            for offset in 0..=source.len() {
4167                let sliced = source.slice(offset, 0);
4168                let batch = RecordBatch::try_from_iter(vec![("run", Arc::new(sliced) as ArrayRef)])
4169                    .unwrap();
4170                for decoded in [
4171                    deserialize_stream(serialize_stream(&batch)),
4172                    deserialize_file(serialize_file(&batch)),
4173                ] {
4174                    assert_eq!(decoded, batch);
4175                    let data = decoded.column(0).to_data();
4176                    data.validate_full().unwrap();
4177                    assert_eq!(data.offset(), 0);
4178                    assert!(data.child_data().iter().all(ArrayData::is_empty));
4179                }
4180
4181                let normalized = into_zero_offset_run_array(source.slice(offset, 0)).unwrap();
4182                normalized.to_data().validate_full().unwrap();
4183                assert_eq!(normalized.offset(), 0);
4184                assert!(normalized.run_ends().values().is_empty());
4185                assert!(normalized.values().is_empty());
4186            }
4187        }
4188    }
4189
4190    #[test]
4191    fn test_empty_run_array_roundtrip_i16() {
4192        assert_empty_run_array_roundtrip::<Int16Type>();
4193    }
4194
4195    #[test]
4196    fn test_empty_run_array_roundtrip_i32() {
4197        assert_empty_run_array_roundtrip::<Int32Type>();
4198    }
4199
4200    #[test]
4201    fn test_empty_run_array_roundtrip_i64() {
4202        assert_empty_run_array_roundtrip::<Int64Type>();
4203    }
4204
4205    #[test]
4206    fn test_run_array_unslice() {
4207        let total_len = 80;
4208        let vals: Vec<Option<i32>> = vec![Some(1), None, Some(2), Some(3), Some(4), None, Some(5)];
4209        let repeats: Vec<usize> = vec![3, 4, 1, 2];
4210        let mut input_array: Vec<Option<i32>> = Vec::with_capacity(total_len);
4211        for ix in 0_usize..32 {
4212            let repeat: usize = repeats[ix % repeats.len()];
4213            let val: Option<i32> = vals[ix % vals.len()];
4214            input_array.resize(input_array.len() + repeat, val);
4215        }
4216
4217        // Encode the input_array to run array
4218        let mut builder =
4219            PrimitiveRunBuilder::<Int16Type, Int32Type>::with_capacity(input_array.len());
4220        builder.extend(input_array.iter().copied());
4221        let run_array = builder.finish();
4222
4223        // test for all slice lengths.
4224        for slice_len in 1..=total_len {
4225            // test for offset = 0, slice length = slice_len
4226            let sliced_run_array: RunArray<Int16Type> =
4227                run_array.slice(0, slice_len).into_data().into();
4228
4229            // Create unsliced run array.
4230            let unsliced_run_array = into_zero_offset_run_array(sliced_run_array).unwrap();
4231            let typed = unsliced_run_array
4232                .downcast::<PrimitiveArray<Int32Type>>()
4233                .unwrap();
4234            let expected: Vec<Option<i32>> = input_array.iter().take(slice_len).copied().collect();
4235            let actual: Vec<Option<i32>> = typed.into_iter().collect();
4236            assert_eq!(expected, actual);
4237
4238            // test for offset = total_len - slice_len, length = slice_len
4239            let sliced_run_array: RunArray<Int16Type> = run_array
4240                .slice(total_len - slice_len, slice_len)
4241                .into_data()
4242                .into();
4243
4244            // Create unsliced run array.
4245            let unsliced_run_array = into_zero_offset_run_array(sliced_run_array).unwrap();
4246            let typed = unsliced_run_array
4247                .downcast::<PrimitiveArray<Int32Type>>()
4248                .unwrap();
4249            let expected: Vec<Option<i32>> = input_array
4250                .iter()
4251                .skip(total_len - slice_len)
4252                .copied()
4253                .collect();
4254            let actual: Vec<Option<i32>> = typed.into_iter().collect();
4255            assert_eq!(expected, actual);
4256        }
4257    }
4258
4259    fn generate_list_data<O: OffsetSizeTrait>() -> GenericListArray<O> {
4260        let mut ls = GenericListBuilder::<O, _>::new(UInt32Builder::new());
4261
4262        for i in 0..100_000 {
4263            for value in [i, i, i] {
4264                ls.values().append_value(value);
4265            }
4266            ls.append(true)
4267        }
4268
4269        ls.finish()
4270    }
4271
4272    fn generate_utf8view_list_data<O: OffsetSizeTrait>() -> GenericListArray<O> {
4273        let mut ls = GenericListBuilder::<O, _>::new(StringViewBuilder::new());
4274
4275        for i in 0..100_000 {
4276            for value in [
4277                format!("value{i}"),
4278                format!("value{i}"),
4279                format!("value{i}"),
4280            ] {
4281                ls.values().append_value(&value);
4282            }
4283            ls.append(true)
4284        }
4285
4286        ls.finish()
4287    }
4288
4289    fn generate_string_list_data<O: OffsetSizeTrait>() -> GenericListArray<O> {
4290        let mut ls = GenericListBuilder::<O, _>::new(StringBuilder::new());
4291
4292        for i in 0..100_000 {
4293            for value in [
4294                format!("value{i}"),
4295                format!("value{i}"),
4296                format!("value{i}"),
4297            ] {
4298                ls.values().append_value(&value);
4299            }
4300            ls.append(true)
4301        }
4302
4303        ls.finish()
4304    }
4305
4306    fn generate_nested_list_data<O: OffsetSizeTrait>() -> GenericListArray<O> {
4307        let mut ls =
4308            GenericListBuilder::<O, _>::new(GenericListBuilder::<O, _>::new(UInt32Builder::new()));
4309
4310        for _i in 0..10_000 {
4311            for j in 0..10 {
4312                for value in [j, j, j, j] {
4313                    ls.values().values().append_value(value);
4314                }
4315                ls.values().append(true)
4316            }
4317            ls.append(true);
4318        }
4319
4320        ls.finish()
4321    }
4322
4323    fn generate_nested_list_data_starting_at_zero<O: OffsetSizeTrait>() -> GenericListArray<O> {
4324        let mut ls =
4325            GenericListBuilder::<O, _>::new(GenericListBuilder::<O, _>::new(UInt32Builder::new()));
4326
4327        for _i in 0..999 {
4328            ls.values().append(true);
4329            ls.append(true);
4330        }
4331
4332        for j in 0..10 {
4333            for value in [j, j, j, j] {
4334                ls.values().values().append_value(value);
4335            }
4336            ls.values().append(true)
4337        }
4338        ls.append(true);
4339
4340        for i in 0..9_000 {
4341            for j in 0..10 {
4342                for value in [i + j, i + j, i + j, i + j] {
4343                    ls.values().values().append_value(value);
4344                }
4345                ls.values().append(true)
4346            }
4347            ls.append(true);
4348        }
4349
4350        ls.finish()
4351    }
4352
4353    fn generate_map_array_data() -> MapArray {
4354        let keys_builder = UInt32Builder::new();
4355        let values_builder = UInt32Builder::new();
4356
4357        let mut builder = MapBuilder::new(None, keys_builder, values_builder);
4358
4359        for i in 0..100_000 {
4360            for _j in 0..3 {
4361                builder.keys().append_value(i);
4362                builder.values().append_value(i * 2);
4363            }
4364            builder.append(true).unwrap();
4365        }
4366
4367        builder.finish()
4368    }
4369
4370    #[test]
4371    #[cfg_attr(miri, ignore)] // Takes too long
4372    fn reencode_offsets_when_first_offset_is_not_zero() {
4373        let original_list = generate_list_data::<i32>();
4374        let original_data = original_list.into_data();
4375        let slice_data = original_data.slice(75, 7);
4376        let (new_offsets, original_start, length) =
4377            reencode_offsets::<i32>(&slice_data.buffers()[0], &slice_data);
4378        assert_eq!(
4379            vec![0, 3, 6, 9, 12, 15, 18, 21],
4380            new_offsets.typed_data::<i32>()
4381        );
4382        assert_eq!(225, original_start);
4383        assert_eq!(21, length);
4384    }
4385
4386    #[test]
4387    fn reencode_offsets_when_first_offset_is_zero() {
4388        let mut ls = GenericListBuilder::<i32, _>::new(UInt32Builder::new());
4389        // ls = [[], [35, 42]
4390        ls.append(true);
4391        ls.values().append_value(35);
4392        ls.values().append_value(42);
4393        ls.append(true);
4394        let original_list = ls.finish();
4395        let original_data = original_list.into_data();
4396
4397        let slice_data = original_data.slice(1, 1);
4398        let (new_offsets, original_start, length) =
4399            reencode_offsets::<i32>(&slice_data.buffers()[0], &slice_data);
4400        assert_eq!(vec![0, 2], new_offsets.typed_data::<i32>());
4401        assert_eq!(0, original_start);
4402        assert_eq!(2, length);
4403    }
4404
4405    /// Ensure when serde full & sliced versions they are equal to original input.
4406    /// Also ensure serialized sliced version is significantly smaller than serialized full.
4407    fn roundtrip_ensure_sliced_smaller(in_batch: RecordBatch, expected_size_factor: usize) {
4408        // test both full and sliced versions
4409        let in_sliced = in_batch.slice(999, 1);
4410
4411        let bytes_batch = serialize_file(&in_batch);
4412        let bytes_sliced = serialize_file(&in_sliced);
4413
4414        // serializing 1 row should be significantly smaller than serializing 100,000
4415        assert!(bytes_sliced.len() < (bytes_batch.len() / expected_size_factor));
4416
4417        // ensure both are still valid and equal to originals
4418        let out_batch = deserialize_file(bytes_batch);
4419        assert_eq!(in_batch, out_batch);
4420
4421        let out_sliced = deserialize_file(bytes_sliced);
4422        assert_eq!(in_sliced, out_sliced);
4423    }
4424
4425    #[test]
4426    #[cfg_attr(miri, ignore)] // Takes too long
4427    fn encode_lists() {
4428        let val_inner = Field::new_list_field(DataType::UInt32, true);
4429        let val_list_field = Field::new("val", DataType::List(Arc::new(val_inner)), false);
4430        let schema = Arc::new(Schema::new(vec![val_list_field]));
4431
4432        let values = Arc::new(generate_list_data::<i32>());
4433
4434        let in_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
4435        roundtrip_ensure_sliced_smaller(in_batch, 1000);
4436    }
4437
4438    #[test]
4439    #[cfg_attr(miri, ignore)] // Takes too long
4440    fn encode_empty_list() {
4441        let val_inner = Field::new_list_field(DataType::UInt32, true);
4442        let val_list_field = Field::new("val", DataType::List(Arc::new(val_inner)), false);
4443        let schema = Arc::new(Schema::new(vec![val_list_field]));
4444
4445        let values = Arc::new(generate_list_data::<i32>());
4446
4447        let in_batch = RecordBatch::try_new(schema, vec![values])
4448            .unwrap()
4449            .slice(999, 0);
4450        let out_batch = deserialize_file(serialize_file(&in_batch));
4451        assert_eq!(in_batch, out_batch);
4452    }
4453
4454    #[test]
4455    #[cfg_attr(miri, ignore)] // Takes too long
4456    fn encode_large_lists() {
4457        let val_inner = Field::new_list_field(DataType::UInt32, true);
4458        let val_list_field = Field::new("val", DataType::LargeList(Arc::new(val_inner)), false);
4459        let schema = Arc::new(Schema::new(vec![val_list_field]));
4460
4461        let values = Arc::new(generate_list_data::<i64>());
4462
4463        // ensure when serde full & sliced versions they are equal to original input
4464        // also ensure serialized sliced version is significantly smaller than serialized full
4465        let in_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
4466        roundtrip_ensure_sliced_smaller(in_batch, 1000);
4467    }
4468
4469    #[test]
4470    #[cfg_attr(miri, ignore)] // Takes too long
4471    fn encode_large_lists_non_zero_offset() {
4472        let val_inner = Field::new_list_field(DataType::UInt32, true);
4473        let val_list_field = Field::new("val", DataType::LargeList(Arc::new(val_inner)), false);
4474        let schema = Arc::new(Schema::new(vec![val_list_field]));
4475
4476        let values = Arc::new(generate_list_data::<i64>());
4477
4478        check_sliced_list_array(schema, values);
4479    }
4480
4481    #[test]
4482    #[cfg_attr(miri, ignore)] // Takes too long
4483    fn encode_large_lists_string_non_zero_offset() {
4484        let val_inner = Field::new_list_field(DataType::Utf8, true);
4485        let val_list_field = Field::new("val", DataType::LargeList(Arc::new(val_inner)), false);
4486        let schema = Arc::new(Schema::new(vec![val_list_field]));
4487
4488        let values = Arc::new(generate_string_list_data::<i64>());
4489
4490        check_sliced_list_array(schema, values);
4491    }
4492
4493    #[test]
4494    #[cfg_attr(miri, ignore)] // Takes too long
4495    fn encode_large_list_string_view_non_zero_offset() {
4496        let val_inner = Field::new_list_field(DataType::Utf8View, true);
4497        let val_list_field = Field::new("val", DataType::LargeList(Arc::new(val_inner)), false);
4498        let schema = Arc::new(Schema::new(vec![val_list_field]));
4499
4500        let values = Arc::new(generate_utf8view_list_data::<i64>());
4501
4502        check_sliced_list_array(schema, values);
4503    }
4504
4505    fn check_sliced_list_array(schema: Arc<Schema>, values: Arc<GenericListArray<i64>>) {
4506        for (offset, len) in [(999, 1), (0, 13), (47, 12), (values.len() - 13, 13)] {
4507            let in_batch = RecordBatch::try_new(schema.clone(), vec![values.clone()])
4508                .unwrap()
4509                .slice(offset, len);
4510            let out_batch = deserialize_file(serialize_file(&in_batch));
4511            assert_eq!(in_batch, out_batch);
4512        }
4513    }
4514
4515    #[test]
4516    #[cfg_attr(miri, ignore)] // Takes too long
4517    fn encode_nested_lists() {
4518        let inner_int = Arc::new(Field::new_list_field(DataType::UInt32, true));
4519        let inner_list_field = Arc::new(Field::new_list_field(DataType::List(inner_int), true));
4520        let list_field = Field::new("val", DataType::List(inner_list_field), true);
4521        let schema = Arc::new(Schema::new(vec![list_field]));
4522
4523        let values = Arc::new(generate_nested_list_data::<i32>());
4524
4525        let in_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
4526        roundtrip_ensure_sliced_smaller(in_batch, 1000);
4527    }
4528
4529    #[test]
4530    #[cfg_attr(miri, ignore)] // Takes too long
4531    fn encode_nested_lists_starting_at_zero() {
4532        let inner_int = Arc::new(Field::new("item", DataType::UInt32, true));
4533        let inner_list_field = Arc::new(Field::new("item", DataType::List(inner_int), true));
4534        let list_field = Field::new("val", DataType::List(inner_list_field), true);
4535        let schema = Arc::new(Schema::new(vec![list_field]));
4536
4537        let values = Arc::new(generate_nested_list_data_starting_at_zero::<i32>());
4538
4539        let in_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
4540        roundtrip_ensure_sliced_smaller(in_batch, 1);
4541    }
4542
4543    #[test]
4544    #[cfg_attr(miri, ignore)] // Takes too long
4545    fn encode_map_array() {
4546        let keys = Arc::new(Field::new(
4547            Field::MAP_KEY_FIELD_DEFAULT_NAME,
4548            DataType::UInt32,
4549            false,
4550        ));
4551        let values = Arc::new(Field::new(
4552            Field::MAP_VALUE_FIELD_DEFAULT_NAME,
4553            DataType::UInt32,
4554            true,
4555        ));
4556        let map_field = Field::new_map(
4557            "map",
4558            Field::MAP_ENTRIES_FIELD_DEFAULT_NAME,
4559            keys,
4560            values,
4561            false,
4562            true,
4563        );
4564        let schema = Arc::new(Schema::new(vec![map_field]));
4565
4566        let values = Arc::new(generate_map_array_data());
4567
4568        let in_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
4569        roundtrip_ensure_sliced_smaller(in_batch, 1000);
4570    }
4571
4572    fn generate_list_view_data<O: OffsetSizeTrait>() -> GenericListViewArray<O> {
4573        let mut builder = GenericListViewBuilder::<O, _>::new(UInt32Builder::new());
4574
4575        for i in 0u32..100_000 {
4576            if i.is_multiple_of(10_000) {
4577                builder.append(false);
4578                continue;
4579            }
4580            for value in [i, i, i] {
4581                builder.values().append_value(value);
4582            }
4583            builder.append(true);
4584        }
4585
4586        builder.finish()
4587    }
4588
4589    #[test]
4590    #[cfg_attr(miri, ignore)] // Takes too long
4591    fn encode_list_view_arrays() {
4592        let val_inner = Field::new_list_field(DataType::UInt32, true);
4593        let val_field = Field::new("val", DataType::ListView(Arc::new(val_inner)), true);
4594        let schema = Arc::new(Schema::new(vec![val_field]));
4595
4596        let values = Arc::new(generate_list_view_data::<i32>());
4597
4598        let in_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
4599        let out_batch = deserialize_file(serialize_file(&in_batch));
4600        assert_eq!(in_batch, out_batch);
4601    }
4602
4603    #[test]
4604    #[cfg_attr(miri, ignore)] // Takes too long
4605    fn encode_large_list_view_arrays() {
4606        let val_inner = Field::new_list_field(DataType::UInt32, true);
4607        let val_field = Field::new("val", DataType::LargeListView(Arc::new(val_inner)), true);
4608        let schema = Arc::new(Schema::new(vec![val_field]));
4609
4610        let values = Arc::new(generate_list_view_data::<i64>());
4611
4612        let in_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
4613        let out_batch = deserialize_file(serialize_file(&in_batch));
4614        assert_eq!(in_batch, out_batch);
4615    }
4616
4617    #[test]
4618    #[cfg_attr(miri, ignore)] // Takes too long
4619    fn check_sliced_list_view_array() {
4620        let inner = Field::new_list_field(DataType::UInt32, true);
4621        let field = Field::new("val", DataType::ListView(Arc::new(inner)), true);
4622        let schema = Arc::new(Schema::new(vec![field]));
4623        let values = Arc::new(generate_list_view_data::<i32>());
4624
4625        for (offset, len) in [(999, 1), (0, 13), (47, 12), (values.len() - 13, 13)] {
4626            let in_batch = RecordBatch::try_new(schema.clone(), vec![values.clone()])
4627                .unwrap()
4628                .slice(offset, len);
4629            let out_batch = deserialize_file(serialize_file(&in_batch));
4630            assert_eq!(in_batch, out_batch);
4631        }
4632    }
4633
4634    #[test]
4635    #[cfg_attr(miri, ignore)] // Takes too long
4636    fn check_sliced_large_list_view_array() {
4637        let inner = Field::new_list_field(DataType::UInt32, true);
4638        let field = Field::new("val", DataType::LargeListView(Arc::new(inner)), true);
4639        let schema = Arc::new(Schema::new(vec![field]));
4640        let values = Arc::new(generate_list_view_data::<i64>());
4641
4642        for (offset, len) in [(999, 1), (0, 13), (47, 12), (values.len() - 13, 13)] {
4643            let in_batch = RecordBatch::try_new(schema.clone(), vec![values.clone()])
4644                .unwrap()
4645                .slice(offset, len);
4646            let out_batch = deserialize_file(serialize_file(&in_batch));
4647            assert_eq!(in_batch, out_batch);
4648        }
4649    }
4650
4651    fn generate_nested_list_view_data<O: OffsetSizeTrait>() -> GenericListViewArray<O> {
4652        let inner_builder = UInt32Builder::new();
4653        let middle_builder = GenericListViewBuilder::<O, _>::new(inner_builder);
4654        let mut outer_builder = GenericListViewBuilder::<O, _>::new(middle_builder);
4655
4656        for i in 0u32..10_000 {
4657            if i.is_multiple_of(1_000) {
4658                outer_builder.append(false);
4659                continue;
4660            }
4661
4662            for _ in 0..3 {
4663                for value in [i, i + 1, i + 2] {
4664                    outer_builder.values().values().append_value(value);
4665                }
4666                outer_builder.values().append(true);
4667            }
4668            outer_builder.append(true);
4669        }
4670
4671        outer_builder.finish()
4672    }
4673
4674    #[test]
4675    #[cfg_attr(miri, ignore)] // Takes too long
4676    fn encode_nested_list_views() {
4677        let inner_int = Arc::new(Field::new_list_field(DataType::UInt32, true));
4678        let inner_list_field = Arc::new(Field::new_list_field(DataType::ListView(inner_int), true));
4679        let list_field = Field::new("val", DataType::ListView(inner_list_field), true);
4680        let schema = Arc::new(Schema::new(vec![list_field]));
4681
4682        let values = Arc::new(generate_nested_list_view_data::<i32>());
4683
4684        let in_batch = RecordBatch::try_new(schema, vec![values]).unwrap();
4685        let out_batch = deserialize_file(serialize_file(&in_batch));
4686        assert_eq!(in_batch, out_batch);
4687    }
4688
4689    fn test_roundtrip_list_view_of_dict_impl<OffsetSize: OffsetSizeTrait, U: ArrowNativeType>(
4690        list_data_type: DataType,
4691        offsets: &[U; 5],
4692        sizes: &[U; 4],
4693    ) {
4694        let values = StringArray::from(vec![Some("alpha"), None, Some("beta"), Some("gamma")]);
4695        let keys = Int32Array::from_iter_values([0, 0, 1, 2, 3, 0, 2]);
4696        let dict_array = DictionaryArray::new(keys, Arc::new(values));
4697        let dict_data = dict_array.to_data();
4698
4699        let value_offsets = Buffer::from_slice_ref(offsets);
4700        let value_sizes = Buffer::from_slice_ref(sizes);
4701
4702        let list_data = ArrayData::builder(list_data_type)
4703            .len(4)
4704            .add_buffer(value_offsets)
4705            .add_buffer(value_sizes)
4706            .add_child_data(dict_data)
4707            .build()
4708            .unwrap();
4709        let list_view_array = GenericListViewArray::<OffsetSize>::from(list_data);
4710
4711        let schema = Arc::new(Schema::new(vec![Field::new(
4712            "f1",
4713            list_view_array.data_type().clone(),
4714            false,
4715        )]));
4716        let input_batch = RecordBatch::try_new(schema, vec![Arc::new(list_view_array)]).unwrap();
4717
4718        let output_batch = deserialize_file(serialize_file(&input_batch));
4719        assert_eq!(input_batch, output_batch);
4720
4721        let output_batch = deserialize_stream(serialize_stream(&input_batch));
4722        assert_eq!(input_batch, output_batch);
4723    }
4724
4725    #[test]
4726    fn test_roundtrip_list_view_of_dict() {
4727        #[expect(deprecated)]
4728        let list_data_type = DataType::ListView(Arc::new(Field::new_dict(
4729            "item",
4730            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4731            true,
4732            1,
4733            false,
4734        )));
4735        let offsets: &[i32; 5] = &[0, 2, 4, 4, 7];
4736        let sizes: &[i32; 4] = &[2, 2, 0, 3];
4737        test_roundtrip_list_view_of_dict_impl::<i32, i32>(list_data_type, offsets, sizes);
4738    }
4739
4740    #[test]
4741    fn test_roundtrip_large_list_view_of_dict() {
4742        #[expect(deprecated)]
4743        let list_data_type = DataType::LargeListView(Arc::new(Field::new_dict(
4744            "item",
4745            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4746            true,
4747            2,
4748            false,
4749        )));
4750        let offsets: &[i64; 5] = &[0, 2, 4, 4, 7];
4751        let sizes: &[i64; 4] = &[2, 2, 0, 3];
4752        test_roundtrip_list_view_of_dict_impl::<i64, i64>(list_data_type, offsets, sizes);
4753    }
4754
4755    #[test]
4756    fn test_roundtrip_sliced_list_view_of_dict() {
4757        #[expect(deprecated)]
4758        let list_data_type = DataType::ListView(Arc::new(Field::new_dict(
4759            "item",
4760            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4761            true,
4762            3,
4763            false,
4764        )));
4765
4766        let values = StringArray::from(vec![Some("alpha"), None, Some("beta"), Some("gamma")]);
4767        let keys = Int32Array::from_iter_values([0, 0, 1, 2, 3, 0, 2, 1, 0, 3, 2, 1]);
4768        let dict_array = DictionaryArray::new(keys, Arc::new(values));
4769        let dict_data = dict_array.to_data();
4770
4771        let offsets: &[i32; 7] = &[0, 2, 4, 4, 7, 9, 12];
4772        let sizes: &[i32; 6] = &[2, 2, 0, 3, 2, 3];
4773        let value_offsets = Buffer::from_slice_ref(offsets);
4774        let value_sizes = Buffer::from_slice_ref(sizes);
4775
4776        let list_data = ArrayData::builder(list_data_type)
4777            .len(6)
4778            .add_buffer(value_offsets)
4779            .add_buffer(value_sizes)
4780            .add_child_data(dict_data)
4781            .build()
4782            .unwrap();
4783        let list_view_array = GenericListViewArray::<i32>::from(list_data);
4784
4785        let schema = Arc::new(Schema::new(vec![Field::new(
4786            "f1",
4787            list_view_array.data_type().clone(),
4788            false,
4789        )]));
4790        let input_batch = RecordBatch::try_new(schema, vec![Arc::new(list_view_array)]).unwrap();
4791
4792        let sliced_batch = input_batch.slice(1, 4);
4793
4794        let output_batch = deserialize_file(serialize_file(&sliced_batch));
4795        assert_eq!(sliced_batch, output_batch);
4796
4797        let output_batch = deserialize_stream(serialize_stream(&sliced_batch));
4798        assert_eq!(sliced_batch, output_batch);
4799    }
4800
4801    #[test]
4802    fn test_roundtrip_dense_union_of_dict() {
4803        let values = StringArray::from(vec![Some("alpha"), None, Some("beta"), Some("gamma")]);
4804        let keys = Int32Array::from_iter_values([0, 0, 1, 2, 3, 0, 2]);
4805        let dict_array = DictionaryArray::new(keys, Arc::new(values));
4806
4807        #[expect(deprecated)]
4808        let dict_field = Arc::new(Field::new_dict(
4809            "dict",
4810            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4811            true,
4812            1,
4813            false,
4814        ));
4815        let int_field = Arc::new(Field::new("int", DataType::Int32, false));
4816        let union_fields = UnionFields::try_new(vec![0, 1], vec![dict_field, int_field]).unwrap();
4817
4818        let types = ScalarBuffer::from(vec![0i8, 0, 1, 0, 1, 0, 0]);
4819        let offsets = ScalarBuffer::from(vec![0i32, 1, 0, 2, 1, 3, 4]);
4820
4821        let int_array = Int32Array::from(vec![100, 200]);
4822
4823        let union = UnionArray::try_new(
4824            union_fields.clone(),
4825            types,
4826            Some(offsets),
4827            vec![Arc::new(dict_array), Arc::new(int_array)],
4828        )
4829        .unwrap();
4830
4831        let schema = Arc::new(Schema::new(vec![Field::new(
4832            "union",
4833            DataType::Union(union_fields, UnionMode::Dense),
4834            false,
4835        )]));
4836        let input_batch = RecordBatch::try_new(schema, vec![Arc::new(union)]).unwrap();
4837
4838        let output_batch = deserialize_file(serialize_file(&input_batch));
4839        assert_eq!(input_batch, output_batch);
4840
4841        let output_batch = deserialize_stream(serialize_stream(&input_batch));
4842        assert_eq!(input_batch, output_batch);
4843    }
4844
4845    #[test]
4846    fn test_roundtrip_sparse_union_of_dict() {
4847        let values = StringArray::from(vec![Some("alpha"), None, Some("beta"), Some("gamma")]);
4848        let keys = Int32Array::from_iter_values([0, 0, 1, 2, 3, 0, 2]);
4849        let dict_array = DictionaryArray::new(keys, Arc::new(values));
4850
4851        #[expect(deprecated)]
4852        let dict_field = Arc::new(Field::new_dict(
4853            "dict",
4854            DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4855            true,
4856            2,
4857            false,
4858        ));
4859        let int_field = Arc::new(Field::new("int", DataType::Int32, false));
4860        let union_fields = UnionFields::try_new(vec![0, 1], vec![dict_field, int_field]).unwrap();
4861
4862        let types = ScalarBuffer::from(vec![0i8, 0, 1, 0, 1, 0, 0]);
4863
4864        let int_array = Int32Array::from(vec![0, 0, 100, 0, 200, 0, 0]);
4865
4866        let union = UnionArray::try_new(
4867            union_fields.clone(),
4868            types,
4869            None,
4870            vec![Arc::new(dict_array), Arc::new(int_array)],
4871        )
4872        .unwrap();
4873
4874        let schema = Arc::new(Schema::new(vec![Field::new(
4875            "union",
4876            DataType::Union(union_fields, UnionMode::Sparse),
4877            false,
4878        )]));
4879        let input_batch = RecordBatch::try_new(schema, vec![Arc::new(union)]).unwrap();
4880
4881        let output_batch = deserialize_file(serialize_file(&input_batch));
4882        assert_eq!(input_batch, output_batch);
4883
4884        let output_batch = deserialize_stream(serialize_stream(&input_batch));
4885        assert_eq!(input_batch, output_batch);
4886    }
4887
4888    #[test]
4889    fn test_roundtrip_map_with_dict_keys() {
4890        // Building a map array is a bit involved. We first build a struct arary that has a key and
4891        // value field and then use that to build the actual map array.
4892        let key_values = StringArray::from(vec!["key_a", "key_b", "key_c"]);
4893        let keys = Int32Array::from_iter_values([0, 1, 2, 0, 1, 0]);
4894        let dict_keys = DictionaryArray::new(keys, Arc::new(key_values));
4895
4896        let values = Int32Array::from(vec![1, 2, 3, 4, 5, 6]);
4897
4898        #[expect(deprecated)]
4899        let entries_field = Arc::new(Field::new(
4900            Field::MAP_ENTRIES_FIELD_DEFAULT_NAME,
4901            DataType::Struct(
4902                vec![
4903                    Field::new_dict(
4904                        Field::MAP_KEY_FIELD_DEFAULT_NAME,
4905                        DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4906                        false,
4907                        1,
4908                        false,
4909                    ),
4910                    Field::new(Field::MAP_VALUE_FIELD_DEFAULT_NAME, DataType::Int32, true),
4911                ]
4912                .into(),
4913            ),
4914            false,
4915        ));
4916
4917        let entries = StructArray::from(vec![
4918            (
4919                Arc::new(Field::new(
4920                    Field::MAP_KEY_FIELD_DEFAULT_NAME,
4921                    DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4922                    false,
4923                )),
4924                Arc::new(dict_keys) as ArrayRef,
4925            ),
4926            (
4927                Arc::new(Field::new(
4928                    Field::MAP_VALUE_FIELD_DEFAULT_NAME,
4929                    DataType::Int32,
4930                    true,
4931                )),
4932                Arc::new(values) as ArrayRef,
4933            ),
4934        ]);
4935
4936        let offsets = Buffer::from_slice_ref([0i32, 2, 4, 6]);
4937
4938        let map_data = ArrayData::builder(DataType::Map(entries_field, false))
4939            .len(3)
4940            .add_buffer(offsets)
4941            .add_child_data(entries.into_data())
4942            .build()
4943            .unwrap();
4944        let map_array = MapArray::from(map_data);
4945
4946        let schema = Arc::new(Schema::new(vec![Field::new(
4947            "map",
4948            map_array.data_type().clone(),
4949            false,
4950        )]));
4951        let input_batch = RecordBatch::try_new(schema, vec![Arc::new(map_array)]).unwrap();
4952
4953        let output_batch = deserialize_file(serialize_file(&input_batch));
4954        assert_eq!(input_batch, output_batch);
4955
4956        let output_batch = deserialize_stream(serialize_stream(&input_batch));
4957        assert_eq!(input_batch, output_batch);
4958    }
4959
4960    #[test]
4961    fn test_roundtrip_map_with_dict_values() {
4962        // Building a map array is a bit involved. We first build a struct arary that has a key and
4963        // value field and then use that to build the actual map array.
4964        let keys = StringArray::from(vec!["a", "b", "c", "d", "e", "f"]);
4965
4966        let value_values = StringArray::from(vec!["val_x", "val_y", "val_z"]);
4967        let value_keys = Int32Array::from_iter_values([0, 1, 2, 0, 1, 0]);
4968        let dict_values = DictionaryArray::new(value_keys, Arc::new(value_values));
4969
4970        #[expect(deprecated)]
4971        let entries_field = Arc::new(Field::new(
4972            Field::MAP_ENTRIES_FIELD_DEFAULT_NAME,
4973            DataType::Struct(
4974                vec![
4975                    Field::new(Field::MAP_KEY_FIELD_DEFAULT_NAME, DataType::Utf8, false),
4976                    Field::new_dict(
4977                        Field::MAP_VALUE_FIELD_DEFAULT_NAME,
4978                        DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
4979                        true,
4980                        2,
4981                        false,
4982                    ),
4983                ]
4984                .into(),
4985            ),
4986            false,
4987        ));
4988
4989        let entries = StructArray::from(vec![
4990            (
4991                Arc::new(Field::new(
4992                    Field::MAP_KEY_FIELD_DEFAULT_NAME,
4993                    DataType::Utf8,
4994                    false,
4995                )),
4996                Arc::new(keys) as ArrayRef,
4997            ),
4998            (
4999                Arc::new(Field::new(
5000                    Field::MAP_VALUE_FIELD_DEFAULT_NAME,
5001                    DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)),
5002                    true,
5003                )),
5004                Arc::new(dict_values) as ArrayRef,
5005            ),
5006        ]);
5007
5008        let offsets = Buffer::from_slice_ref([0i32, 2, 4, 6]);
5009
5010        let map_data = ArrayData::builder(DataType::Map(entries_field, false))
5011            .len(3)
5012            .add_buffer(offsets)
5013            .add_child_data(entries.into_data())
5014            .build()
5015            .unwrap();
5016        let map_array = MapArray::from(map_data);
5017
5018        let schema = Arc::new(Schema::new(vec![Field::new(
5019            "map",
5020            map_array.data_type().clone(),
5021            false,
5022        )]));
5023        let input_batch = RecordBatch::try_new(schema, vec![Arc::new(map_array)]).unwrap();
5024
5025        let output_batch = deserialize_file(serialize_file(&input_batch));
5026        assert_eq!(input_batch, output_batch);
5027
5028        let output_batch = deserialize_stream(serialize_stream(&input_batch));
5029        assert_eq!(input_batch, output_batch);
5030    }
5031
5032    #[test]
5033    fn test_decimal128_alignment16_is_sufficient() {
5034        const IPC_ALIGNMENT: usize = 16;
5035
5036        // Test a bunch of different dimensions to ensure alignment is never an issue.
5037        // For example, if we only test `num_cols = 1` then even with alignment 8 this
5038        // test would _happen_ to pass, even though for different dimensions like
5039        // `num_cols = 2` it would fail.
5040        for num_cols in [1, 2, 3, 17, 50, 73, 99] {
5041            let num_rows = (num_cols * 7 + 11) % 100; // Deterministic swizzle
5042
5043            let mut fields = Vec::new();
5044            let mut arrays = Vec::new();
5045            for i in 0..num_cols {
5046                let field = Field::new(format!("col_{i}"), DataType::Decimal128(38, 10), true);
5047                let array = Decimal128Array::from(vec![num_cols as i128; num_rows]);
5048                fields.push(field);
5049                arrays.push(Arc::new(array) as Arc<dyn Array>);
5050            }
5051            let schema = Schema::new(fields);
5052            let batch = RecordBatch::try_new(Arc::new(schema), arrays).unwrap();
5053
5054            let mut writer = FileWriter::try_new_with_options(
5055                Vec::new(),
5056                batch.schema_ref(),
5057                IpcWriteOptions::try_new(IPC_ALIGNMENT, false, MetadataVersion::V5).unwrap(),
5058            )
5059            .unwrap();
5060            writer.write(&batch).unwrap();
5061            writer.finish().unwrap();
5062
5063            let out: Vec<u8> = writer.into_inner().unwrap();
5064
5065            let buffer = Buffer::from_slice_ref(out);
5066            let trailer_start = buffer.len() - 10;
5067            let footer_len =
5068                read_footer_length(buffer[trailer_start..].try_into().unwrap()).unwrap();
5069            let footer =
5070                root_as_footer(&buffer[trailer_start - footer_len..trailer_start]).unwrap();
5071
5072            let schema = try_fb_to_schema(footer.schema().unwrap()).unwrap();
5073
5074            // Importantly we set `require_alignment`, checking that 16-byte alignment is sufficient
5075            // for `read_record_batch` later on to read the data in a zero-copy manner.
5076            let decoder =
5077                FileDecoder::new(Arc::new(schema), footer.version()).with_require_alignment(true);
5078
5079            let batches = footer.recordBatches().unwrap();
5080
5081            let block = batches.get(0);
5082            let block_len = block.bodyLength() as usize + block.metaDataLength() as usize;
5083            let data = buffer.slice_with_length(block.offset() as _, block_len);
5084
5085            let batch2 = decoder.read_record_batch(block, &data).unwrap().unwrap();
5086
5087            assert_eq!(batch, batch2);
5088        }
5089    }
5090
5091    #[test]
5092    fn test_decimal128_alignment8_is_unaligned() {
5093        const IPC_ALIGNMENT: usize = 8;
5094
5095        let num_cols = 2;
5096
5097        let mut fields = Vec::new();
5098        let mut arrays = Vec::new();
5099        for i in 0..num_cols {
5100            let field = Field::new(format!("col_{i}"), DataType::Decimal128(38, 10), true);
5101            // The null makes the writer emit a 1-byte validity buffer. With IPC_ALIGNMENT = 8,
5102            // the writer pads that buffer to 8 bytes, so the decimal values that follow start
5103            // at offset 8 of the body, which is not a multiple of 16.
5104            let array = Decimal128Array::from(vec![Some(num_cols as i128), None]);
5105            fields.push(field);
5106            arrays.push(Arc::new(array) as Arc<dyn Array>);
5107        }
5108        let schema = Schema::new(fields);
5109        let batch = RecordBatch::try_new(Arc::new(schema), arrays).unwrap();
5110
5111        let mut writer = FileWriter::try_new_with_options(
5112            Vec::new(),
5113            batch.schema_ref(),
5114            IpcWriteOptions::try_new(IPC_ALIGNMENT, false, MetadataVersion::V5).unwrap(),
5115        )
5116        .unwrap();
5117        writer.write(&batch).unwrap();
5118        writer.finish().unwrap();
5119
5120        let out: Vec<u8> = writer.into_inner().unwrap();
5121
5122        let buffer = Buffer::from_slice_ref(out);
5123        let trailer_start = buffer.len() - 10;
5124        let footer_len = read_footer_length(buffer[trailer_start..].try_into().unwrap()).unwrap();
5125        let footer = root_as_footer(&buffer[trailer_start - footer_len..trailer_start]).unwrap();
5126        let schema = try_fb_to_schema(footer.schema().unwrap()).unwrap();
5127
5128        // Importantly we set `require_alignment`, otherwise the error later is suppressed due to copying
5129        // to an aligned buffer in `ArrayDataBuilder.build_aligned`.
5130        let decoder =
5131            FileDecoder::new(Arc::new(schema), footer.version()).with_require_alignment(true);
5132
5133        let batches = footer.recordBatches().unwrap();
5134
5135        let block = batches.get(0);
5136        let block_len = block.bodyLength() as usize + block.metaDataLength() as usize;
5137        let data = buffer.slice_with_length(block.offset() as _, block_len);
5138
5139        let result = decoder.read_record_batch(block, &data);
5140
5141        let error = result.unwrap_err();
5142        assert_eq!(
5143            error.to_string(),
5144            "Invalid argument error: Misaligned buffers[0] in array of type Decimal128(38, 10), \
5145             offset from expected alignment of 16 by 8"
5146        );
5147    }
5148
5149    #[test]
5150    fn test_file_embeds_stream() {
5151        let dict = DictionaryArray::<Int32Type>::from_iter(["a", "b", "a"]);
5152        let decimal = Decimal128Array::from(vec![Some(1), None, Some(3)]);
5153        let batch = RecordBatch::try_from_iter([
5154            ("dict", Arc::new(dict) as ArrayRef),
5155            ("decimal", Arc::new(decimal) as ArrayRef),
5156        ])
5157        .unwrap();
5158
5159        for (alignment, legacy, version) in [
5160            (8, false, MetadataVersion::V5),
5161            (16, false, MetadataVersion::V5),
5162            (32, false, MetadataVersion::V5),
5163            (64, false, MetadataVersion::V5),
5164            (64, true, MetadataVersion::V4),
5165        ] {
5166            let options = IpcWriteOptions::try_new(alignment, legacy, version).unwrap();
5167            let mut writer =
5168                FileWriter::try_new_with_options(vec![], batch.schema_ref(), options).unwrap();
5169            writer.write(&batch).unwrap();
5170            writer.write(&batch).unwrap();
5171            let file = writer.into_inner().unwrap();
5172
5173            // An IPC file is `ARROW1`, padding to 8 bytes, then an IPC stream
5174            let stream = StreamReader::try_new(&file[8..], None).unwrap();
5175            let from_stream = stream.collect::<Result<Vec<_>, _>>().unwrap();
5176            let reader = FileReader::try_new(Cursor::new(&file), None).unwrap();
5177            let from_file = reader.collect::<Result<Vec<_>, _>>().unwrap();
5178            assert_eq!(from_stream, [batch.clone(), batch.clone()]);
5179            assert_eq!(from_file, from_stream);
5180
5181            // The dictionary and record batch messages, and so their bodies, stay aligned
5182            let trailer_start = file.len() - 10;
5183            let footer_len = read_footer_length(file[trailer_start..].try_into().unwrap()).unwrap();
5184            let footer = root_as_footer(&file[trailer_start - footer_len..trailer_start]).unwrap();
5185            let dictionaries = footer.dictionaries().unwrap();
5186            let record_batches = footer.recordBatches().unwrap();
5187            assert_eq!((dictionaries.len(), record_batches.len()), (1, 2));
5188            for block in dictionaries.iter().chain(record_batches.iter()) {
5189                assert_eq!(block.offset() as usize % alignment, 0);
5190                assert_eq!(block.metaDataLength() as usize % alignment, 0);
5191            }
5192        }
5193    }
5194
5195    #[test]
5196    fn test_flush() {
5197        // We write a schema which is small enough to fit into a buffer and not get flushed,
5198        // and then force the write with .flush().
5199        let num_cols = 2;
5200        let mut fields = Vec::new();
5201        let options = IpcWriteOptions::try_new(8, false, MetadataVersion::V5).unwrap();
5202        for i in 0..num_cols {
5203            let field = Field::new(format!("col_{i}"), DataType::Decimal128(38, 10), true);
5204            fields.push(field);
5205        }
5206        let schema = Schema::new(fields);
5207        let inner_stream_writer = BufWriter::with_capacity(1024, Vec::new());
5208        let inner_file_writer = BufWriter::with_capacity(1024, Vec::new());
5209        let mut stream_writer =
5210            StreamWriter::try_new_with_options(inner_stream_writer, &schema, options.clone())
5211                .unwrap();
5212        let mut file_writer =
5213            FileWriter::try_new_with_options(inner_file_writer, &schema, options).unwrap();
5214
5215        let stream_bytes_written_on_new = stream_writer.get_ref().get_ref().len();
5216        let file_bytes_written_on_new = file_writer.get_ref().get_ref().len();
5217        stream_writer.flush().unwrap();
5218        file_writer.flush().unwrap();
5219        let stream_bytes_written_on_flush = stream_writer.get_ref().get_ref().len();
5220        let file_bytes_written_on_flush = file_writer.get_ref().get_ref().len();
5221        let stream_out = stream_writer.into_inner().unwrap().into_inner().unwrap();
5222        // Finishing a stream writes the continuation bytes in MetadataVersion::V5 (4 bytes)
5223        // and then a length of 0 (4 bytes) for a total of 8 bytes.
5224        // Everything before that should have been flushed in the .flush() call.
5225        let expected_stream_flushed_bytes = stream_out.len() - 8;
5226        // A file write is the same as the stream write except for the leading magic string
5227        // ARROW1 plus padding, which is 8 bytes.
5228        let expected_file_flushed_bytes = expected_stream_flushed_bytes + 8;
5229
5230        assert!(
5231            stream_bytes_written_on_new < stream_bytes_written_on_flush,
5232            "this test makes no sense if flush is not actually required"
5233        );
5234        assert!(
5235            file_bytes_written_on_new < file_bytes_written_on_flush,
5236            "this test makes no sense if flush is not actually required"
5237        );
5238        assert_eq!(stream_bytes_written_on_flush, expected_stream_flushed_bytes);
5239        assert_eq!(file_bytes_written_on_flush, expected_file_flushed_bytes);
5240    }
5241
5242    #[test]
5243    fn test_roundtrip_list_of_fixed_list() -> Result<(), ArrowError> {
5244        let l1_type =
5245            DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Float32, false)), 3);
5246        let l2_type = DataType::List(Arc::new(Field::new("item", l1_type.clone(), false)));
5247
5248        let l0_builder = Float32Builder::new();
5249        let l1_builder = FixedSizeListBuilder::new(l0_builder, 3).with_field(Arc::new(Field::new(
5250            "item",
5251            DataType::Float32,
5252            false,
5253        )));
5254        let mut l2_builder =
5255            ListBuilder::new(l1_builder).with_field(Arc::new(Field::new("item", l1_type, false)));
5256
5257        for point in [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]] {
5258            l2_builder.values().values().append_value(point[0]);
5259            l2_builder.values().values().append_value(point[1]);
5260            l2_builder.values().values().append_value(point[2]);
5261
5262            l2_builder.values().append(true);
5263        }
5264        l2_builder.append(true);
5265
5266        let point = [10., 11., 12.];
5267        l2_builder.values().values().append_value(point[0]);
5268        l2_builder.values().values().append_value(point[1]);
5269        l2_builder.values().values().append_value(point[2]);
5270
5271        l2_builder.values().append(true);
5272        l2_builder.append(true);
5273
5274        let array = Arc::new(l2_builder.finish()) as ArrayRef;
5275
5276        let schema = Arc::new(Schema::new_with_metadata(
5277            vec![Field::new("points", l2_type, false)],
5278            HashMap::default(),
5279        ));
5280
5281        // Test a variety of combinations that include 0 and non-zero offsets
5282        // and also portions or the rest of the array
5283        test_slices(&array, &schema, 0, 1)?;
5284        test_slices(&array, &schema, 0, 2)?;
5285        test_slices(&array, &schema, 1, 1)?;
5286
5287        Ok(())
5288    }
5289
5290    #[test]
5291    fn test_roundtrip_list_of_fixed_list_w_nulls() -> Result<(), ArrowError> {
5292        let l0_builder = Float32Builder::new();
5293        let l1_builder = FixedSizeListBuilder::new(l0_builder, 3);
5294        let mut l2_builder = ListBuilder::new(l1_builder);
5295
5296        for point in [
5297            [Some(1.0), Some(2.0), None],
5298            [Some(4.0), Some(5.0), Some(6.0)],
5299            [None, Some(8.0), Some(9.0)],
5300        ] {
5301            for p in point {
5302                match p {
5303                    Some(p) => l2_builder.values().values().append_value(p),
5304                    None => l2_builder.values().values().append_null(),
5305                }
5306            }
5307
5308            l2_builder.values().append(true);
5309        }
5310        l2_builder.append(true);
5311
5312        let point = [Some(10.), None, None];
5313        for p in point {
5314            match p {
5315                Some(p) => l2_builder.values().values().append_value(p),
5316                None => l2_builder.values().values().append_null(),
5317            }
5318        }
5319
5320        l2_builder.values().append(true);
5321        l2_builder.append(true);
5322
5323        let array = Arc::new(l2_builder.finish()) as ArrayRef;
5324
5325        let schema = Arc::new(Schema::new_with_metadata(
5326            vec![Field::new(
5327                "points",
5328                DataType::List(Arc::new(Field::new(
5329                    "item",
5330                    DataType::FixedSizeList(
5331                        Arc::new(Field::new("item", DataType::Float32, true)),
5332                        3,
5333                    ),
5334                    true,
5335                ))),
5336                true,
5337            )],
5338            HashMap::default(),
5339        ));
5340
5341        // Test a variety of combinations that include 0 and non-zero offsets
5342        // and also portions or the rest of the array
5343        test_slices(&array, &schema, 0, 1)?;
5344        test_slices(&array, &schema, 0, 2)?;
5345        test_slices(&array, &schema, 1, 1)?;
5346
5347        Ok(())
5348    }
5349
5350    fn test_slices(
5351        parent_array: &ArrayRef,
5352        schema: &SchemaRef,
5353        offset: usize,
5354        length: usize,
5355    ) -> Result<(), ArrowError> {
5356        let subarray = parent_array.slice(offset, length);
5357        let original_batch = RecordBatch::try_new(schema.clone(), vec![subarray])?;
5358
5359        let mut bytes = Vec::new();
5360        let mut writer = StreamWriter::try_new(&mut bytes, schema)?;
5361        writer.write(&original_batch)?;
5362        writer.finish()?;
5363
5364        let mut cursor = std::io::Cursor::new(bytes);
5365        let mut reader = StreamReader::try_new(&mut cursor, None)?;
5366        let returned_batch = reader.next().unwrap()?;
5367
5368        assert_eq!(original_batch, returned_batch);
5369
5370        Ok(())
5371    }
5372
5373    #[test]
5374    fn test_roundtrip_fixed_list() -> Result<(), ArrowError> {
5375        let int_builder = Int64Builder::new();
5376        let mut fixed_list_builder = FixedSizeListBuilder::new(int_builder, 3)
5377            .with_field(Arc::new(Field::new("item", DataType::Int64, false)));
5378
5379        for point in [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] {
5380            fixed_list_builder.values().append_value(point[0]);
5381            fixed_list_builder.values().append_value(point[1]);
5382            fixed_list_builder.values().append_value(point[2]);
5383
5384            fixed_list_builder.append(true);
5385        }
5386
5387        let array = Arc::new(fixed_list_builder.finish()) as ArrayRef;
5388
5389        let schema = Arc::new(Schema::new_with_metadata(
5390            vec![Field::new(
5391                "points",
5392                DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Int64, false)), 3),
5393                false,
5394            )],
5395            HashMap::default(),
5396        ));
5397
5398        // Test a variety of combinations that include 0 and non-zero offsets
5399        // and also portions or the rest of the array
5400        test_slices(&array, &schema, 0, 4)?;
5401        test_slices(&array, &schema, 0, 2)?;
5402        test_slices(&array, &schema, 1, 3)?;
5403        test_slices(&array, &schema, 2, 1)?;
5404
5405        Ok(())
5406    }
5407
5408    #[test]
5409    fn test_roundtrip_fixed_list_w_nulls() -> Result<(), ArrowError> {
5410        let int_builder = Int64Builder::new();
5411        let mut fixed_list_builder = FixedSizeListBuilder::new(int_builder, 3);
5412
5413        for point in [
5414            [Some(1), Some(2), None],
5415            [Some(4), Some(5), Some(6)],
5416            [None, Some(8), Some(9)],
5417            [Some(10), None, None],
5418        ] {
5419            for p in point {
5420                match p {
5421                    Some(p) => fixed_list_builder.values().append_value(p),
5422                    None => fixed_list_builder.values().append_null(),
5423                }
5424            }
5425
5426            fixed_list_builder.append(true);
5427        }
5428
5429        let array = Arc::new(fixed_list_builder.finish()) as ArrayRef;
5430
5431        let schema = Arc::new(Schema::new_with_metadata(
5432            vec![Field::new(
5433                "points",
5434                DataType::FixedSizeList(Arc::new(Field::new("item", DataType::Int64, true)), 3),
5435                true,
5436            )],
5437            HashMap::default(),
5438        ));
5439
5440        // Test a variety of combinations that include 0 and non-zero offsets
5441        // and also portions or the rest of the array
5442        test_slices(&array, &schema, 0, 4)?;
5443        test_slices(&array, &schema, 0, 2)?;
5444        test_slices(&array, &schema, 1, 3)?;
5445        test_slices(&array, &schema, 2, 1)?;
5446
5447        Ok(())
5448    }
5449
5450    #[test]
5451    fn test_metadata_encoding_ordering() {
5452        fn create_hash() -> u64 {
5453            let metadata: HashMap<String, String> = [
5454                ("a", "1"), //
5455                ("b", "2"), //
5456                ("c", "3"), //
5457                ("d", "4"), //
5458                ("e", "5"), //
5459            ]
5460            .into_iter()
5461            .map(|(k, v)| (k.to_owned(), v.to_owned()))
5462            .collect();
5463
5464            // Set metadata on both the schema and a field within it.
5465            let schema = Arc::new(
5466                Schema::new(vec![
5467                    Field::new("a", DataType::Int64, true).with_metadata(metadata.clone()),
5468                ])
5469                .with_metadata(metadata)
5470                .clone(),
5471            );
5472            let batch = RecordBatch::new_empty(schema.clone());
5473
5474            let mut bytes = Vec::new();
5475            let mut w = StreamWriter::try_new(&mut bytes, batch.schema_ref()).unwrap();
5476            w.write(&batch).unwrap();
5477            w.finish().unwrap();
5478
5479            let mut h = std::hash::DefaultHasher::new();
5480            h.write(&bytes);
5481            h.finish()
5482        }
5483
5484        let expected = create_hash();
5485
5486        // Since there is randomness in the HashMap and we cannot specify our
5487        // own Hasher for the implementation used for metadata, run the above
5488        // code 20x and verify it does not change. This is not perfect but it
5489        // should be good enough.
5490        let all_passed = (0..20).all(|_| create_hash() == expected);
5491        assert!(all_passed);
5492    }
5493
5494    #[test]
5495    fn test_dictionary_tracker_reset() {
5496        let data_gen = IpcDataGenerator::default();
5497        let mut dictionary_tracker = DictionaryTracker::new(false);
5498        let writer_options = IpcWriteOptions::default();
5499        let mut compression_ctx = IpcWriteContext::default();
5500
5501        let schema = Arc::new(Schema::new(vec![Field::new(
5502            "a",
5503            DataType::Dictionary(Box::new(DataType::UInt8), Box::new(DataType::Utf8)),
5504            false,
5505        )]));
5506
5507        let mut write_single_batch_stream =
5508            |batch: RecordBatch, dict_tracker: &mut DictionaryTracker| -> Vec<u8> {
5509                let mut buffer = Vec::new();
5510
5511                // create a new IPC stream:
5512                let stream_header = data_gen.schema_to_bytes_with_dictionary_tracker(
5513                    &schema,
5514                    dict_tracker,
5515                    &writer_options,
5516                );
5517                _ = write_message(&mut buffer, stream_header, &writer_options).unwrap();
5518
5519                let (encoded_dicts, encoded_batch) = data_gen
5520                    .encode(&batch, dict_tracker, &writer_options, &mut compression_ctx)
5521                    .unwrap();
5522                for encoded_dict in encoded_dicts {
5523                    _ = write_message(&mut buffer, encoded_dict, &writer_options).unwrap();
5524                }
5525                _ = write_message(&mut buffer, encoded_batch, &writer_options).unwrap();
5526
5527                buffer
5528            };
5529
5530        let batch1 = RecordBatch::try_new(
5531            schema.clone(),
5532            vec![Arc::new(DictionaryArray::new(
5533                UInt8Array::from_iter_values([0]),
5534                Arc::new(StringArray::from_iter_values(["a"])),
5535            ))],
5536        )
5537        .unwrap();
5538        let buffer = write_single_batch_stream(batch1.clone(), &mut dictionary_tracker);
5539
5540        // ensure we can read the stream back
5541        let mut reader = StreamReader::try_new(Cursor::new(buffer), None).unwrap();
5542        let read_batch = reader.next().unwrap().unwrap();
5543        assert_eq!(read_batch, batch1);
5544
5545        // reset the dictionary tracker so it can be used for next stream
5546        dictionary_tracker.clear();
5547
5548        // now write a 2nd stream and ensure we can also read it:
5549        let batch2 = RecordBatch::try_new(
5550            schema.clone(),
5551            vec![Arc::new(DictionaryArray::new(
5552                UInt8Array::from_iter_values([0]),
5553                Arc::new(StringArray::from_iter_values(["a"])),
5554            ))],
5555        )
5556        .unwrap();
5557        let buffer = write_single_batch_stream(batch2.clone(), &mut dictionary_tracker);
5558        let mut reader = StreamReader::try_new(Cursor::new(buffer), None).unwrap();
5559        let read_batch = reader.next().unwrap().unwrap();
5560        assert_eq!(read_batch, batch2);
5561    }
5562}