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