Skip to main content

arrow_cast/
display.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//! Functions for printing array values as human-readable strings.
6//!
7//! This is often used for debugging or logging purposes.
8//!
9//! See the [`pretty`] crate for additional functions for
10//! record batch pretty printing.
11//!
12//! [`pretty`]: crate::pretty
13use std::fmt::{Debug, Display, Formatter, Write};
14use std::hash::{Hash, Hasher};
15use std::ops::Range;
16
17use arrow_array::cast::*;
18use arrow_array::temporal_conversions::*;
19use arrow_array::timezone::Tz;
20use arrow_array::types::*;
21use arrow_array::*;
22use arrow_buffer::ArrowNativeType;
23use arrow_data::decimal::write_decimal;
24use arrow_schema::*;
25use chrono::format::{Item, StrftimeItems};
26use chrono::{NaiveDate, NaiveDateTime, Offset, SecondsFormat, TimeZone, Utc};
27use lexical_core::FormattedSize;
28
29type TimeFormat<'a> = Option<&'a str>;
30
31struct CompiledItems<'a>(Vec<Item<'a>>);
32
33enum CompiledTimeFormat<'a> {
34    Default,
35    Custom(Box<CompiledItems<'a>>),
36}
37
38impl<'a> CompiledTimeFormat<'a> {
39    fn new(format: TimeFormat<'a>) -> Self {
40        match format {
41            Some(format) => Self::Custom(Box::new(CompiledItems(
42                StrftimeItems::new(format).collect(),
43            ))),
44            None => Self::Default,
45        }
46    }
47}
48
49/// Format for displaying durations
50#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
51#[non_exhaustive]
52pub enum DurationFormat {
53    /// ISO 8601 - `P198DT72932.972880S`
54    ISO8601,
55    /// A human readable representation - `198 days 16 hours 34 mins 15.407810000 secs`
56    Pretty,
57}
58
59/// Options for formatting arrays
60///
61/// By default nulls are formatted as `""` and temporal types formatted
62/// according to RFC3339
63///
64/// # Equality
65///
66/// Most fields in [`FormatOptions`] are compared by value, except `formatter_factory`. As the trait
67/// does not require an [`Eq`] and [`Hash`] implementation, this struct only compares the pointer of
68/// the factories.
69#[derive(Debug, Clone)]
70pub struct FormatOptions<'a> {
71    /// If set to `true` any formatting errors will be written to the output
72    /// instead of being converted into a [`std::fmt::Error`]
73    safe: bool,
74    /// Format string for nulls
75    null: &'a str,
76    /// Date format for date arrays
77    date_format: TimeFormat<'a>,
78    /// Format for DateTime arrays
79    datetime_format: TimeFormat<'a>,
80    /// Timestamp format for timestamp arrays
81    timestamp_format: TimeFormat<'a>,
82    /// Timestamp format for timestamp with timezone arrays
83    timestamp_tz_format: TimeFormat<'a>,
84    /// Time format for time arrays
85    time_format: TimeFormat<'a>,
86    /// Duration format
87    duration_format: DurationFormat,
88    /// Show types in visual representation batches
89    types_info: bool,
90    /// Whether string values should be quoted
91    quoted_strings: bool,
92    /// Formatter factory used to instantiate custom [`ArrayFormatter`]s. This allows users to
93    /// provide custom formatters.
94    formatter_factory: Option<&'a dyn ArrayFormatterFactory>,
95}
96
97impl Default for FormatOptions<'_> {
98    fn default() -> Self {
99        Self::new()
100    }
101}
102
103impl PartialEq for FormatOptions<'_> {
104    fn eq(&self, other: &Self) -> bool {
105        self.safe == other.safe
106            && self.null == other.null
107            && self.date_format == other.date_format
108            && self.datetime_format == other.datetime_format
109            && self.timestamp_format == other.timestamp_format
110            && self.timestamp_tz_format == other.timestamp_tz_format
111            && self.time_format == other.time_format
112            && self.duration_format == other.duration_format
113            && self.types_info == other.types_info
114            && self.quoted_strings == other.quoted_strings
115            && match (self.formatter_factory, other.formatter_factory) {
116                (Some(f1), Some(f2)) => std::ptr::eq(f1, f2),
117                (None, None) => true,
118                _ => false,
119            }
120    }
121}
122
123impl Eq for FormatOptions<'_> {}
124
125impl Hash for FormatOptions<'_> {
126    fn hash<H: Hasher>(&self, state: &mut H) {
127        self.safe.hash(state);
128        self.null.hash(state);
129        self.date_format.hash(state);
130        self.datetime_format.hash(state);
131        self.timestamp_format.hash(state);
132        self.timestamp_tz_format.hash(state);
133        self.time_format.hash(state);
134        self.duration_format.hash(state);
135        self.types_info.hash(state);
136        self.quoted_strings.hash(state);
137        self.formatter_factory
138            .map(std::ptr::from_ref::<dyn ArrayFormatterFactory>)
139            .hash(state);
140    }
141}
142
143impl<'a> FormatOptions<'a> {
144    /// Creates a new set of format options
145    pub const fn new() -> Self {
146        Self {
147            safe: true,
148            null: "",
149            date_format: None,
150            datetime_format: None,
151            timestamp_format: None,
152            timestamp_tz_format: None,
153            time_format: None,
154            duration_format: DurationFormat::ISO8601,
155            types_info: false,
156            quoted_strings: false,
157            formatter_factory: None,
158        }
159    }
160
161    /// If set to `true` any formatting errors will be written to the output
162    /// instead of being converted into a [`std::fmt::Error`]
163    pub const fn with_display_error(mut self, safe: bool) -> Self {
164        self.safe = safe;
165        self
166    }
167
168    /// Overrides the string used to represent a null
169    ///
170    /// Defaults to `""`
171    pub const fn with_null(self, null: &'a str) -> Self {
172        Self { null, ..self }
173    }
174
175    /// Overrides the format used for [`DataType::Date32`] columns
176    pub const fn with_date_format(self, date_format: Option<&'a str>) -> Self {
177        Self {
178            date_format,
179            ..self
180        }
181    }
182
183    /// Overrides the format used for [`DataType::Date64`] columns
184    pub const fn with_datetime_format(self, datetime_format: Option<&'a str>) -> Self {
185        Self {
186            datetime_format,
187            ..self
188        }
189    }
190
191    /// Overrides the format used for [`DataType::Timestamp`] columns without a timezone
192    pub const fn with_timestamp_format(self, timestamp_format: Option<&'a str>) -> Self {
193        Self {
194            timestamp_format,
195            ..self
196        }
197    }
198
199    /// Overrides the format used for [`DataType::Timestamp`] columns with a timezone
200    pub const fn with_timestamp_tz_format(self, timestamp_tz_format: Option<&'a str>) -> Self {
201        Self {
202            timestamp_tz_format,
203            ..self
204        }
205    }
206
207    /// Overrides the format used for [`DataType::Time32`] and [`DataType::Time64`] columns
208    pub const fn with_time_format(self, time_format: Option<&'a str>) -> Self {
209        Self {
210            time_format,
211            ..self
212        }
213    }
214
215    /// Overrides the format used for duration columns
216    ///
217    /// Defaults to [`DurationFormat::ISO8601`]
218    pub const fn with_duration_format(self, duration_format: DurationFormat) -> Self {
219        Self {
220            duration_format,
221            ..self
222        }
223    }
224
225    /// Overrides if types should be shown
226    ///
227    /// Defaults to [`false`]
228    pub const fn with_types_info(self, types_info: bool) -> Self {
229        Self { types_info, ..self }
230    }
231
232    /// Sets whether string values should be quoted
233    ///
234    /// When `true`, strings are formatted using [`Debug`]-style with double quotes and escaping.
235    /// Defaults to `false`
236    pub const fn with_quoted_strings(self, quoted_strings: bool) -> Self {
237        Self {
238            quoted_strings,
239            ..self
240        }
241    }
242
243    /// Overrides the [`ArrayFormatterFactory`] used to instantiate custom [`ArrayFormatter`]s.
244    ///
245    /// Using [`None`] causes pretty-printers to use the default [`ArrayFormatter`]s.
246    pub const fn with_formatter_factory(
247        self,
248        formatter_factory: Option<&'a dyn ArrayFormatterFactory>,
249    ) -> Self {
250        Self {
251            formatter_factory,
252            ..self
253        }
254    }
255
256    /// Returns whether formatting errors should be written to the output instead of being converted
257    /// into a [`std::fmt::Error`].
258    pub const fn safe(&self) -> bool {
259        self.safe
260    }
261
262    /// Returns the string used for displaying nulls.
263    pub const fn null(&self) -> &'a str {
264        self.null
265    }
266
267    /// Returns the format used for [`DataType::Date32`] columns.
268    pub const fn date_format(&self) -> TimeFormat<'a> {
269        self.date_format
270    }
271
272    /// Returns the format used for [`DataType::Date64`] columns.
273    pub const fn datetime_format(&self) -> TimeFormat<'a> {
274        self.datetime_format
275    }
276
277    /// Returns the format used for [`DataType::Timestamp`] columns without a timezone.
278    pub const fn timestamp_format(&self) -> TimeFormat<'a> {
279        self.timestamp_format
280    }
281
282    /// Returns the format used for [`DataType::Timestamp`] columns with a timezone.
283    pub const fn timestamp_tz_format(&self) -> TimeFormat<'a> {
284        self.timestamp_tz_format
285    }
286
287    /// Returns the format used for [`DataType::Time32`] and [`DataType::Time64`] columns.
288    pub const fn time_format(&self) -> TimeFormat<'a> {
289        self.time_format
290    }
291
292    /// Returns the [`DurationFormat`] used for duration columns.
293    pub const fn duration_format(&self) -> DurationFormat {
294        self.duration_format
295    }
296
297    /// Returns true if type info should be included in a visual representation of batches.
298    pub const fn types_info(&self) -> bool {
299        self.types_info
300    }
301
302    /// Returns whether string values should be quoted.
303    pub const fn quoted_strings(&self) -> bool {
304        self.quoted_strings
305    }
306
307    /// Returns the [`ArrayFormatterFactory`] used to instantiate custom [`ArrayFormatter`]s.
308    pub const fn formatter_factory(&self) -> Option<&'a dyn ArrayFormatterFactory> {
309        self.formatter_factory
310    }
311}
312
313/// Allows creating a new [`ArrayFormatter`] for a given [`Array`] and an optional [`Field`].
314///
315/// # Example
316///
317/// The example below shows how to create a custom formatter for a custom type `my_money`. Note that
318/// this example requires the `prettyprint` feature.
319///
320/// ```rust
321/// # #[cfg(feature = "prettyprint")]{
322/// use std::fmt::Write;
323/// use arrow_array::{cast::AsArray, Array, Int32Array};
324/// use arrow_cast::display::{ArrayFormatter, ArrayFormatterFactory, DisplayIndex, FormatOptions, FormatResult};
325/// use arrow_cast::pretty::pretty_format_batches_with_options;
326/// use arrow_schema::{ArrowError, Field};
327///
328/// /// A custom formatter factory that can create a formatter for the special type `my_money`.
329/// ///
330/// /// This struct could have access to some kind of extension type registry that can lookup the
331/// /// correct formatter for an extension type on-demand.
332/// #[derive(Debug)]
333/// struct MyFormatters {}
334///
335/// impl ArrayFormatterFactory for MyFormatters {
336///     fn create_array_formatter<'formatter>(
337///         &self,
338///         array: &'formatter dyn Array,
339///         options: &FormatOptions<'formatter>,
340///         field: Option<&'formatter Field>,
341///     ) -> Result<Option<ArrayFormatter<'formatter>>, ArrowError> {
342///         // check if this is the money type
343///         if field
344///             .map(|f| f.extension_type_name() == Some("my_money"))
345///             .unwrap_or(false)
346///         {
347///             // We assume that my_money always is an Int32.
348///             let array = array.as_primitive();
349///             let display_index = Box::new(MyMoneyFormatter { array, options: options.clone() });
350///             return Ok(Some(ArrayFormatter::new(display_index, options.safe())));
351///         }
352///
353///         Ok(None) // None indicates that the default formatter should be used.
354///     }
355/// }
356///
357/// /// A formatter for the type `my_money` that wraps a specific array and has access to the
358/// /// formatting options.
359/// struct MyMoneyFormatter<'a> {
360///     array: &'a Int32Array,
361///     options: FormatOptions<'a>,
362/// }
363///
364/// impl<'a> DisplayIndex for MyMoneyFormatter<'a> {
365///     fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
366///         match self.array.is_valid(idx) {
367///             true => write!(f, "{} €", self.array.value(idx))?,
368///             false => write!(f, "{}", self.options.null())?,
369///         }
370///
371///         Ok(())
372///     }
373/// }
374///
375/// // Usually, here you would provide your record batches.
376/// let my_batches = vec![];
377///
378/// // Call the pretty printer with the custom formatter factory.
379/// pretty_format_batches_with_options(
380///        &my_batches,
381///        &FormatOptions::new().with_formatter_factory(Some(&MyFormatters {}))
382/// );
383/// # }
384/// ```
385pub trait ArrayFormatterFactory: Debug + Send + Sync {
386    /// Creates a new [`ArrayFormatter`] for the given [`Array`] and an optional [`Field`]. If the
387    /// default implementation should be used, return [`None`].
388    ///
389    /// The field shall be used to look up metadata about the `array` while `options` provide
390    /// information on formatting, for example, dates and times which should be considered by an
391    /// implementor.
392    fn create_array_formatter<'formatter>(
393        &self,
394        array: &'formatter dyn Array,
395        options: &FormatOptions<'formatter>,
396        field: Option<&'formatter Field>,
397    ) -> Result<Option<ArrayFormatter<'formatter>>, ArrowError>;
398}
399
400/// Used to create a new [`ArrayFormatter`] from the given `array`, while also checking whether
401/// there is an override available in the [`ArrayFormatterFactory`].
402pub(crate) fn make_array_formatter<'a>(
403    array: &'a dyn Array,
404    options: &FormatOptions<'a>,
405    field: Option<&'a Field>,
406) -> Result<ArrayFormatter<'a>, ArrowError> {
407    match options.formatter_factory() {
408        None => ArrayFormatter::try_new(array, options),
409        Some(formatters) => formatters
410            .create_array_formatter(array, options, field)
411            .transpose()
412            .unwrap_or_else(|| ArrayFormatter::try_new(array, options)),
413    }
414}
415
416/// Implements [`Display`] for a specific array value
417pub struct ValueFormatter<'a> {
418    idx: usize,
419    formatter: &'a ArrayFormatter<'a>,
420}
421
422impl ValueFormatter<'_> {
423    /// Writes this value to the provided [`Write`]
424    ///
425    /// Note: this ignores [`FormatOptions::with_display_error`] and
426    /// will return an error on formatting issue
427    pub fn write(&self, s: &mut dyn Write) -> Result<(), ArrowError> {
428        match self.formatter.format.write(self.idx, s) {
429            Ok(()) => Ok(()),
430            Err(FormatError::Arrow(e)) => Err(e),
431            Err(FormatError::Format(_)) => Err(ArrowError::CastError("Format error".to_string())),
432        }
433    }
434
435    /// Fallibly converts this to a string
436    pub fn try_to_string(&self) -> Result<String, ArrowError> {
437        let mut s = String::new();
438        self.write(&mut s)?;
439        Ok(s)
440    }
441}
442
443impl Display for ValueFormatter<'_> {
444    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
445        match self.formatter.format.write(self.idx, f) {
446            Ok(()) => Ok(()),
447            Err(FormatError::Arrow(e)) if self.formatter.safe => {
448                write!(f, "ERROR: {e}")
449            }
450            Err(_) => Err(std::fmt::Error),
451        }
452    }
453}
454
455/// A string formatter for an [`Array`]
456///
457/// This can be used with [`std::write`] to write type-erased `dyn Array`
458///
459/// ```
460/// # use std::fmt::{Display, Formatter, Write};
461/// # use arrow_array::{Array, ArrayRef, Int32Array};
462/// # use arrow_cast::display::{ArrayFormatter, FormatOptions};
463/// # use arrow_schema::ArrowError;
464/// struct MyContainer {
465///     values: ArrayRef,
466/// }
467///
468/// impl Display for MyContainer {
469///     fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
470///         let options = FormatOptions::default();
471///         let formatter = ArrayFormatter::try_new(self.values.as_ref(), &options)
472///             .map_err(|_| std::fmt::Error)?;
473///
474///         let mut iter = 0..self.values.len();
475///         if let Some(idx) = iter.next() {
476///             write!(f, "{}", formatter.value(idx))?;
477///         }
478///         for idx in iter {
479///             write!(f, ", {}", formatter.value(idx))?;
480///         }
481///         Ok(())
482///     }
483/// }
484/// ```
485///
486/// [`ValueFormatter::write`] can also be used to get a semantic error, instead of the
487/// opaque [`std::fmt::Error`]
488///
489/// ```
490/// # use std::fmt::Write;
491/// # use arrow_array::Array;
492/// # use arrow_cast::display::{ArrayFormatter, FormatOptions};
493/// # use arrow_schema::ArrowError;
494/// fn format_array(
495///     f: &mut dyn Write,
496///     array: &dyn Array,
497///     options: &FormatOptions,
498/// ) -> Result<(), ArrowError> {
499///     let formatter = ArrayFormatter::try_new(array, options)?;
500///     for i in 0..array.len() {
501///         formatter.value(i).write(f)?
502///     }
503///     Ok(())
504/// }
505/// ```
506///
507pub struct ArrayFormatter<'a> {
508    format: Box<dyn DisplayIndex + 'a>,
509    safe: bool,
510}
511
512impl<'a> ArrayFormatter<'a> {
513    /// Returns an [`ArrayFormatter`] using the provided formatter.
514    pub fn new(format: Box<dyn DisplayIndex + 'a>, safe: bool) -> Self {
515        Self { format, safe }
516    }
517
518    /// Returns an [`ArrayFormatter`] that can be used to format `array`
519    ///
520    /// This returns an error if an array of the given data type cannot be formatted
521    pub fn try_new(array: &'a dyn Array, options: &FormatOptions<'a>) -> Result<Self, ArrowError> {
522        Ok(Self::new(
523            make_default_display_index(array, options)?,
524            options.safe,
525        ))
526    }
527
528    /// Returns a [`ValueFormatter`] that implements [`Display`] for
529    /// the value of the array at `idx`
530    pub fn value(&self, idx: usize) -> ValueFormatter<'_> {
531        ValueFormatter {
532            formatter: self,
533            idx,
534        }
535    }
536}
537
538fn make_default_display_index<'a>(
539    array: &'a dyn Array,
540    options: &FormatOptions<'a>,
541) -> Result<Box<dyn DisplayIndex + 'a>, ArrowError> {
542    downcast_primitive_array! {
543        array => array_format(array, options),
544        DataType::Null => array_format(as_null_array(array), options),
545        DataType::Boolean => array_format(as_boolean_array(array), options),
546        DataType::Utf8 => array_format(array.as_string::<i32>(), options),
547        DataType::LargeUtf8 => array_format(array.as_string::<i64>(), options),
548        DataType::Utf8View => array_format(array.as_string_view(), options),
549        DataType::Binary => array_format(array.as_binary::<i32>(), options),
550        DataType::BinaryView => array_format(array.as_binary_view(), options),
551        DataType::LargeBinary => array_format(array.as_binary::<i64>(), options),
552        DataType::FixedSizeBinary(_) => {
553            let a = array.as_any().downcast_ref::<FixedSizeBinaryArray>().unwrap();
554            array_format(a, options)
555        }
556        DataType::Dictionary(_, _) => downcast_dictionary_array! {
557            array => array_format(array, options),
558            _ => unreachable!()
559        }
560        DataType::List(_) => array_format(as_generic_list_array::<i32>(array), options),
561        DataType::LargeList(_) => array_format(as_generic_list_array::<i64>(array), options),
562        DataType::ListView(_) => array_format(array.as_list_view::<i32>(), options),
563        DataType::LargeListView(_) => array_format(array.as_list_view::<i64>(), options),
564        DataType::FixedSizeList(_, _) => {
565            let a = array.as_any().downcast_ref::<FixedSizeListArray>().unwrap();
566            array_format(a, options)
567        }
568        DataType::Struct(_) => array_format(as_struct_array(array), options),
569        DataType::Map(_, _) => array_format(as_map_array(array), options),
570        DataType::Union(_, _) => array_format(as_union_array(array), options),
571        DataType::RunEndEncoded(_, _) => downcast_run_array! {
572            array => array_format(array, options),
573            _ => unreachable!()
574        },
575        d => Err(ArrowError::NotYetImplemented(format!("formatting {d} is not yet supported"))),
576    }
577}
578
579/// Either an [`ArrowError`] or [`std::fmt::Error`]
580pub enum FormatError {
581    /// An error occurred while formatting the array
582    Format(std::fmt::Error),
583    /// An Arrow error occurred while formatting the array.
584    Arrow(ArrowError),
585}
586
587/// The result of formatting an array element via [`DisplayIndex::write`].
588pub type FormatResult = Result<(), FormatError>;
589
590impl From<std::fmt::Error> for FormatError {
591    fn from(value: std::fmt::Error) -> Self {
592        Self::Format(value)
593    }
594}
595
596impl From<ArrowError> for FormatError {
597    fn from(value: ArrowError) -> Self {
598        Self::Arrow(value)
599    }
600}
601
602/// [`Display`] but accepting an index
603pub trait DisplayIndex {
604    /// Write the value of the underlying array at `idx` to `f`.
605    fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult;
606}
607
608/// [`DisplayIndex`] with additional state
609trait DisplayIndexState<'a> {
610    type State;
611
612    fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError>;
613
614    fn write(&self, state: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult;
615}
616
617impl<'a, T: DisplayIndex> DisplayIndexState<'a> for T {
618    type State = ();
619
620    fn prepare(&self, _options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
621        Ok(())
622    }
623
624    fn write(&self, (): &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
625        DisplayIndex::write(self, idx, f)
626    }
627}
628
629struct ArrayFormat<'a, F: DisplayIndexState<'a>> {
630    state: F::State,
631    array: F,
632    null: &'a str,
633}
634
635fn array_format<'a, F>(
636    array: F,
637    options: &FormatOptions<'a>,
638) -> Result<Box<dyn DisplayIndex + 'a>, ArrowError>
639where
640    F: DisplayIndexState<'a> + Array + 'a,
641{
642    let state = array.prepare(options)?;
643    Ok(Box::new(ArrayFormat {
644        state,
645        array,
646        null: options.null,
647    }))
648}
649
650impl<'a, F: DisplayIndexState<'a> + Array> DisplayIndex for ArrayFormat<'a, F> {
651    fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
652        if self.array.is_null(idx) {
653            if !self.null.is_empty() {
654                f.write_str(self.null)?
655            }
656            return Ok(());
657        }
658        DisplayIndexState::write(&self.array, &self.state, idx, f)
659    }
660}
661
662impl DisplayIndex for &BooleanArray {
663    fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
664        f.write_str(if self.value(idx) { "true" } else { "false" })?;
665        Ok(())
666    }
667}
668
669impl<'a> DisplayIndexState<'a> for &'a NullArray {
670    type State = &'a str;
671
672    fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
673        Ok(options.null)
674    }
675
676    fn write(&self, state: &Self::State, _idx: usize, f: &mut dyn Write) -> FormatResult {
677        f.write_str(state)?;
678        Ok(())
679    }
680}
681
682macro_rules! primitive_display {
683    ($($t:ty),+) => {
684        $(impl<'a> DisplayIndex for &'a PrimitiveArray<$t>
685        {
686            fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
687                let value = self.value(idx);
688                let mut buffer = [0u8; <$t as ArrowPrimitiveType>::Native::FORMATTED_SIZE];
689                let b = lexical_core::write(value, &mut buffer);
690                // Lexical core produces valid UTF-8
691                let s = unsafe { std::str::from_utf8_unchecked(b) };
692                f.write_str(s)?;
693                Ok(())
694            }
695        })+
696    };
697}
698
699macro_rules! primitive_display_float {
700    ($($t:ty),+) => {
701        $(impl<'a> DisplayIndex for &'a PrimitiveArray<$t>
702        {
703            fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
704                let value = self.value(idx);
705                let mut buffer = ryu::Buffer::new();
706                f.write_str(buffer.format(value))?;
707                Ok(())
708            }
709        })+
710    };
711}
712
713primitive_display!(Int8Type, Int16Type, Int32Type, Int64Type);
714primitive_display!(UInt8Type, UInt16Type, UInt32Type, UInt64Type);
715primitive_display_float!(Float32Type, Float64Type);
716
717impl DisplayIndex for &PrimitiveArray<Float16Type> {
718    fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
719        write!(f, "{}", self.value(idx))?;
720        Ok(())
721    }
722}
723
724macro_rules! decimal_display {
725    ($($t:ty),+) => {
726        $(impl<'a> DisplayIndexState<'a> for &'a PrimitiveArray<$t> {
727            type State = i8;
728
729            fn prepare(&self, _options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
730                Ok(self.scale())
731            }
732
733            fn write(&self, scale: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
734                write_decimal(f, self.values()[idx], *scale)?;
735                Ok(())
736            }
737        })+
738    };
739}
740
741decimal_display!(Decimal32Type, Decimal64Type, Decimal128Type, Decimal256Type);
742
743fn write_timestamp(
744    f: &mut dyn Write,
745    naive: NaiveDateTime,
746    timezone: Option<Tz>,
747    format: &CompiledTimeFormat<'_>,
748) -> FormatResult {
749    match timezone {
750        Some(tz) => {
751            let utc = Utc.from_utc_datetime(&naive);
752            let date = utc.with_timezone(&tz);
753            match format {
754                CompiledTimeFormat::Custom(items) => {
755                    write!(f, "{}", date.format_with_items(items.0.iter()))?
756                }
757                // RFC 3339 offsets have no seconds and the arrow parser rejects them, so only Z round-trips
758                CompiledTimeFormat::Default if date.offset().fix().local_minus_utc() % 60 != 0 => {
759                    write!(f, "{}", utc.to_rfc3339_opts(SecondsFormat::AutoSi, true))?
760                }
761                CompiledTimeFormat::Default => {
762                    write!(f, "{}", date.to_rfc3339_opts(SecondsFormat::AutoSi, true))?
763                }
764            }
765        }
766        None => match format {
767            CompiledTimeFormat::Custom(items) => {
768                write!(f, "{}", naive.format_with_items(items.0.iter()))?
769            }
770            CompiledTimeFormat::Default => write!(f, "{naive:?}")?,
771        },
772    }
773    Ok(())
774}
775
776macro_rules! timestamp_display {
777    ($($t:ty),+) => {
778        $(impl<'a> DisplayIndexState<'a> for &'a PrimitiveArray<$t> {
779            type State = (Option<Tz>, CompiledTimeFormat<'a>);
780
781            fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
782                match self.data_type() {
783                    DataType::Timestamp(_, Some(tz)) => Ok((Some(tz.parse()?), CompiledTimeFormat::new(options.timestamp_tz_format))),
784                    DataType::Timestamp(_, None) => Ok((None, CompiledTimeFormat::new(options.timestamp_format))),
785                    _ => unreachable!(),
786                }
787            }
788
789            fn write(&self, s: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
790                let value = self.value(idx);
791                let naive = as_datetime::<$t>(value).ok_or_else(|| {
792                    ArrowError::CastError(format!(
793                        "Failed to convert {} to datetime for {}",
794                        value,
795                        self.data_type()
796                    ))
797                })?;
798
799                write_timestamp(f, naive, s.0, &s.1)
800            }
801        })+
802    };
803}
804
805timestamp_display!(
806    TimestampSecondType,
807    TimestampMillisecondType,
808    TimestampMicrosecondType,
809    TimestampNanosecondType
810);
811
812macro_rules! temporal_display {
813    ($convert:ident, $format:ident, $t:ty) => {
814        impl<'a> DisplayIndexState<'a> for &'a PrimitiveArray<$t> {
815            type State = CompiledTimeFormat<'a>;
816
817            fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
818                Ok(CompiledTimeFormat::new(options.$format))
819            }
820
821            fn write(&self, fmt: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
822                let value = self.value(idx);
823                let naive = $convert(value).ok_or_else(|| {
824                    ArrowError::CastError(format!(
825                        "Failed to convert {} to temporal for {}",
826                        value,
827                        self.data_type()
828                    ))
829                })?;
830
831                match fmt {
832                    CompiledTimeFormat::Custom(items) => {
833                        write!(f, "{}", naive.format_with_items(items.0.iter()))?
834                    }
835                    CompiledTimeFormat::Default => write!(f, "{naive:?}")?,
836                }
837                Ok(())
838            }
839        }
840    };
841}
842
843#[inline]
844fn date32_to_date(value: i32) -> Option<NaiveDate> {
845    Some(date32_to_datetime(value)?.date())
846}
847
848temporal_display!(date32_to_date, date_format, Date32Type);
849temporal_display!(date64_to_datetime, datetime_format, Date64Type);
850temporal_display!(time32s_to_time, time_format, Time32SecondType);
851temporal_display!(time32ms_to_time, time_format, Time32MillisecondType);
852temporal_display!(time64us_to_time, time_format, Time64MicrosecondType);
853temporal_display!(time64ns_to_time, time_format, Time64NanosecondType);
854
855/// Derive [`DisplayIndexState`] for `PrimitiveArray<$t>`
856///
857/// Arguments
858/// * `$convert` - function to convert the value to an `Duration`
859/// * `$t` - [`ArrowPrimitiveType`] of the array
860/// * `$scale` - scale of the duration (passed to `duration_fmt`)
861macro_rules! duration_display {
862    ($convert:ident, $t:ty, $scale:tt) => {
863        impl<'a> DisplayIndexState<'a> for &'a PrimitiveArray<$t> {
864            type State = DurationFormat;
865
866            fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
867                Ok(options.duration_format)
868            }
869
870            fn write(&self, fmt: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
871                let v = self.value(idx);
872                match fmt {
873                    DurationFormat::ISO8601 => write!(f, "{}", $convert(v))?,
874                    DurationFormat::Pretty => duration_fmt!(f, v, $scale)?,
875                }
876                Ok(())
877            }
878        }
879    };
880}
881
882/// Similar to [`duration_display`] but `$convert` returns an `Option`
883macro_rules! duration_option_display {
884    ($convert:ident, $t:ty, $scale:tt) => {
885        impl<'a> DisplayIndexState<'a> for &'a PrimitiveArray<$t> {
886            type State = DurationFormat;
887
888            fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
889                Ok(options.duration_format)
890            }
891
892            fn write(&self, fmt: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
893                let v = self.value(idx);
894                match fmt {
895                    DurationFormat::ISO8601 => match $convert(v) {
896                        Some(td) => write!(f, "{}", td)?,
897                        None => write!(f, "<invalid>")?,
898                    },
899                    DurationFormat::Pretty => match $convert(v) {
900                        Some(_) => duration_fmt!(f, v, $scale)?,
901                        None => write!(f, "<invalid>")?,
902                    },
903                }
904                Ok(())
905            }
906        }
907    };
908}
909
910macro_rules! duration_fmt {
911    ($f:ident, $v:expr, 0) => {{
912        let secs = $v;
913        let mins = secs / 60;
914        let hours = mins / 60;
915        let days = hours / 24;
916
917        let secs = secs - (mins * 60);
918        let mins = mins - (hours * 60);
919        let hours = hours - (days * 24);
920        write!($f, "{days} days {hours} hours {mins} mins {secs} secs")
921    }};
922    ($f:ident, $v:expr, $scale:tt) => {{
923        let subsec = $v;
924        let secs = subsec / 10_i64.pow($scale);
925        let mins = secs / 60;
926        let hours = mins / 60;
927        let days = hours / 24;
928
929        let subsec = subsec - (secs * 10_i64.pow($scale));
930        let secs = secs - (mins * 60);
931        let mins = mins - (hours * 60);
932        let hours = hours - (days * 24);
933        match subsec.is_negative() {
934            true => {
935                write!(
936                    $f,
937                    concat!("{} days {} hours {} mins -{}.{:0", $scale, "} secs"),
938                    days,
939                    hours,
940                    mins,
941                    secs.abs(),
942                    subsec.abs()
943                )
944            }
945            false => {
946                write!(
947                    $f,
948                    concat!("{} days {} hours {} mins {}.{:0", $scale, "} secs"),
949                    days, hours, mins, secs, subsec
950                )
951            }
952        }
953    }};
954}
955
956duration_option_display!(try_duration_s_to_duration, DurationSecondType, 0);
957duration_option_display!(try_duration_ms_to_duration, DurationMillisecondType, 3);
958duration_display!(duration_us_to_duration, DurationMicrosecondType, 6);
959duration_display!(duration_ns_to_duration, DurationNanosecondType, 9);
960
961impl DisplayIndex for &PrimitiveArray<IntervalYearMonthType> {
962    fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
963        let interval = self.value(idx) as f64;
964        let years = (interval / 12_f64).floor();
965        let month = interval - (years * 12_f64);
966
967        write!(f, "{years} years {month} mons")?;
968        Ok(())
969    }
970}
971
972impl DisplayIndex for &PrimitiveArray<IntervalDayTimeType> {
973    fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
974        let value = self.value(idx);
975
976        if value.is_zero() {
977            write!(f, "0 secs")?;
978            return Ok(());
979        }
980
981        let mut prefix = "";
982
983        if value.days != 0 {
984            write!(f, "{prefix}{} days", value.days)?;
985            prefix = " ";
986        }
987
988        if value.milliseconds != 0 {
989            let millis_fmt = MillisecondsFormatter {
990                milliseconds: value.milliseconds,
991                prefix,
992            };
993
994            f.write_fmt(format_args!("{millis_fmt}"))?;
995        }
996
997        Ok(())
998    }
999}
1000
1001impl DisplayIndex for &PrimitiveArray<IntervalMonthDayNanoType> {
1002    fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
1003        let value = self.value(idx);
1004
1005        if value.is_zero() {
1006            write!(f, "0 secs")?;
1007            return Ok(());
1008        }
1009
1010        let mut prefix = "";
1011
1012        if value.months != 0 {
1013            write!(f, "{prefix}{} mons", value.months)?;
1014            prefix = " ";
1015        }
1016
1017        if value.days != 0 {
1018            write!(f, "{prefix}{} days", value.days)?;
1019            prefix = " ";
1020        }
1021
1022        if value.nanoseconds != 0 {
1023            let nano_fmt = NanosecondsFormatter {
1024                nanoseconds: value.nanoseconds,
1025                prefix,
1026            };
1027            f.write_fmt(format_args!("{nano_fmt}"))?;
1028        }
1029
1030        Ok(())
1031    }
1032}
1033
1034struct NanosecondsFormatter<'a> {
1035    nanoseconds: i64,
1036    prefix: &'a str,
1037}
1038
1039impl Display for NanosecondsFormatter<'_> {
1040    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1041        let mut prefix = self.prefix;
1042
1043        let secs = self.nanoseconds / 1_000_000_000;
1044        let mins = secs / 60;
1045        let hours = mins / 60;
1046
1047        let secs = secs - (mins * 60);
1048        let mins = mins - (hours * 60);
1049
1050        let nanoseconds = self.nanoseconds % 1_000_000_000;
1051
1052        if hours != 0 {
1053            write!(f, "{prefix}{hours} hours")?;
1054            prefix = " ";
1055        }
1056
1057        if mins != 0 {
1058            write!(f, "{prefix}{mins} mins")?;
1059            prefix = " ";
1060        }
1061
1062        if secs != 0 || nanoseconds != 0 {
1063            let secs_sign = if secs < 0 || nanoseconds < 0 { "-" } else { "" };
1064            write!(
1065                f,
1066                "{prefix}{}{}.{:09} secs",
1067                secs_sign,
1068                secs.abs(),
1069                nanoseconds.abs()
1070            )?;
1071        }
1072
1073        Ok(())
1074    }
1075}
1076
1077struct MillisecondsFormatter<'a> {
1078    milliseconds: i32,
1079    prefix: &'a str,
1080}
1081
1082impl Display for MillisecondsFormatter<'_> {
1083    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1084        let mut prefix = self.prefix;
1085
1086        let secs = self.milliseconds / 1_000;
1087        let mins = secs / 60;
1088        let hours = mins / 60;
1089
1090        let secs = secs - (mins * 60);
1091        let mins = mins - (hours * 60);
1092
1093        let milliseconds = self.milliseconds % 1_000;
1094
1095        if hours != 0 {
1096            write!(f, "{prefix}{hours} hours")?;
1097            prefix = " ";
1098        }
1099
1100        if mins != 0 {
1101            write!(f, "{prefix}{mins} mins")?;
1102            prefix = " ";
1103        }
1104
1105        if secs != 0 || milliseconds != 0 {
1106            let secs_sign = if secs < 0 || milliseconds < 0 {
1107                "-"
1108            } else {
1109                ""
1110            };
1111
1112            write!(
1113                f,
1114                "{prefix}{}{}.{:03} secs",
1115                secs_sign,
1116                secs.abs(),
1117                milliseconds.abs()
1118            )?;
1119        }
1120
1121        Ok(())
1122    }
1123}
1124
1125impl<'a, O: OffsetSizeTrait> DisplayIndexState<'a> for &'a GenericStringArray<O> {
1126    type State = bool;
1127
1128    fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
1129        Ok(options.quoted_strings())
1130    }
1131
1132    fn write(&self, state: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
1133        let value = self.value(idx);
1134        if *state {
1135            write!(f, "{value:?}")?;
1136        } else {
1137            write!(f, "{value}")?;
1138        }
1139        Ok(())
1140    }
1141}
1142
1143impl<'a> DisplayIndexState<'a> for &'a StringViewArray {
1144    type State = bool;
1145
1146    fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
1147        Ok(options.quoted_strings())
1148    }
1149
1150    fn write(&self, state: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
1151        let value = self.value(idx);
1152        if *state {
1153            write!(f, "{value:?}")?;
1154        } else {
1155            write!(f, "{value}")?;
1156        }
1157        Ok(())
1158    }
1159}
1160
1161impl<O: OffsetSizeTrait> DisplayIndex for &GenericBinaryArray<O> {
1162    fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
1163        let v = self.value(idx);
1164        for byte in v {
1165            write!(f, "{byte:02x}")?;
1166        }
1167        Ok(())
1168    }
1169}
1170
1171impl DisplayIndex for &BinaryViewArray {
1172    fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
1173        let v = self.value(idx);
1174        for byte in v {
1175            write!(f, "{byte:02x}")?;
1176        }
1177        Ok(())
1178    }
1179}
1180
1181impl DisplayIndex for &FixedSizeBinaryArray {
1182    fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
1183        let v = self.value(idx);
1184        for byte in v {
1185            write!(f, "{byte:02x}")?;
1186        }
1187        Ok(())
1188    }
1189}
1190
1191impl<'a, K: ArrowDictionaryKeyType> DisplayIndexState<'a> for &'a DictionaryArray<K> {
1192    type State = Box<dyn DisplayIndex + 'a>;
1193
1194    fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
1195        make_default_display_index(self.values().as_ref(), options)
1196    }
1197
1198    fn write(&self, s: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
1199        let value_idx = self.keys().values()[idx].as_usize();
1200        s.as_ref().write(value_idx, f)
1201    }
1202}
1203
1204impl<'a, K: RunEndIndexType> DisplayIndexState<'a> for &'a RunArray<K> {
1205    type State = ArrayFormatter<'a>;
1206
1207    fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
1208        let DataType::RunEndEncoded(_, field) = (*self).data_type() else {
1209            unreachable!()
1210        };
1211        make_array_formatter(self.values().as_ref(), options, Some(field))
1212    }
1213
1214    fn write(&self, s: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
1215        let value_idx = self.get_physical_index(idx);
1216        write!(f, "{}", s.value(value_idx))?;
1217        Ok(())
1218    }
1219}
1220
1221fn write_list(
1222    f: &mut dyn Write,
1223    mut range: Range<usize>,
1224    values: &ArrayFormatter<'_>,
1225) -> FormatResult {
1226    f.write_char('[')?;
1227    if let Some(idx) = range.next() {
1228        write!(f, "{}", values.value(idx))?;
1229    }
1230    for idx in range {
1231        write!(f, ", {}", values.value(idx))?;
1232    }
1233    f.write_char(']')?;
1234    Ok(())
1235}
1236
1237impl<'a, O: OffsetSizeTrait> DisplayIndexState<'a> for &'a GenericListArray<O> {
1238    type State = ArrayFormatter<'a>;
1239
1240    fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
1241        let field = match (*self).data_type() {
1242            DataType::List(f) => f,
1243            DataType::LargeList(f) => f,
1244            _ => unreachable!(),
1245        };
1246        make_array_formatter(self.values().as_ref(), options, Some(field.as_ref()))
1247    }
1248
1249    fn write(&self, s: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
1250        let offsets = self.value_offsets();
1251        let end = offsets[idx + 1].as_usize();
1252        let start = offsets[idx].as_usize();
1253        write_list(f, start..end, s)
1254    }
1255}
1256
1257impl<'a, O: OffsetSizeTrait> DisplayIndexState<'a> for &'a GenericListViewArray<O> {
1258    type State = ArrayFormatter<'a>;
1259
1260    fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
1261        let field = match (*self).data_type() {
1262            DataType::ListView(f) => f,
1263            DataType::LargeListView(f) => f,
1264            _ => unreachable!(),
1265        };
1266        make_array_formatter(self.values().as_ref(), options, Some(field.as_ref()))
1267    }
1268
1269    fn write(&self, s: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
1270        let offsets = self.value_offsets();
1271        let sizes = self.value_sizes();
1272        let start = offsets[idx].as_usize();
1273        let end = start + sizes[idx].as_usize();
1274        write_list(f, start..end, s)
1275    }
1276}
1277
1278impl<'a> DisplayIndexState<'a> for &'a FixedSizeListArray {
1279    type State = (usize, ArrayFormatter<'a>);
1280
1281    fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
1282        let DataType::FixedSizeList(field, _) = (*self).data_type() else {
1283            unreachable!()
1284        };
1285        let formatter =
1286            make_array_formatter(self.values().as_ref(), options, Some(field.as_ref()))?;
1287        let length = self.value_length();
1288        Ok((length as usize, formatter))
1289    }
1290
1291    fn write(&self, s: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
1292        let start = idx * s.0;
1293        let end = start + s.0;
1294        write_list(f, start..end, &s.1)
1295    }
1296}
1297
1298/// Pairs an [`ArrayFormatter`] with its field name
1299type FieldDisplay<'a> = (&'a str, ArrayFormatter<'a>);
1300
1301impl<'a> DisplayIndexState<'a> for &'a StructArray {
1302    type State = Vec<FieldDisplay<'a>>;
1303
1304    fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
1305        let DataType::Struct(fields) = (*self).data_type() else {
1306            unreachable!()
1307        };
1308
1309        self.columns()
1310            .iter()
1311            .zip(fields)
1312            .map(|(a, f)| {
1313                let format = make_array_formatter(a.as_ref(), options, Some(f))?;
1314                Ok((f.name().as_str(), format))
1315            })
1316            .collect()
1317    }
1318
1319    fn write(&self, s: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
1320        let mut iter = s.iter();
1321        f.write_char('{')?;
1322        if let Some((name, display)) = iter.next() {
1323            write!(f, "{name}: {}", display.value(idx))?;
1324        }
1325        for (name, display) in iter {
1326            write!(f, ", {name}: {}", display.value(idx))?;
1327        }
1328        f.write_char('}')?;
1329        Ok(())
1330    }
1331}
1332
1333impl<'a> DisplayIndexState<'a> for &'a MapArray {
1334    type State = (ArrayFormatter<'a>, ArrayFormatter<'a>);
1335
1336    fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
1337        let (key_field, value_field) = (*self).entries_fields();
1338
1339        let keys = make_array_formatter(self.keys().as_ref(), options, Some(key_field))?;
1340        let values = make_array_formatter(self.values().as_ref(), options, Some(value_field))?;
1341        Ok((keys, values))
1342    }
1343
1344    fn write(&self, s: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
1345        let offsets = self.value_offsets();
1346        let end = offsets[idx + 1].as_usize();
1347        let start = offsets[idx].as_usize();
1348        let mut iter = start..end;
1349
1350        f.write_char('{')?;
1351        if let Some(idx) = iter.next() {
1352            write!(f, "{}: {}", s.0.value(idx), s.1.value(idx))?;
1353        }
1354
1355        for idx in iter {
1356            write!(f, ", {}", s.0.value(idx))?;
1357            write!(f, ": {}", s.1.value(idx))?;
1358        }
1359
1360        f.write_char('}')?;
1361        Ok(())
1362    }
1363}
1364
1365impl<'a> DisplayIndexState<'a> for &'a UnionArray {
1366    type State = (Vec<Option<FieldDisplay<'a>>>, UnionMode);
1367
1368    fn prepare(&self, options: &FormatOptions<'a>) -> Result<Self::State, ArrowError> {
1369        let DataType::Union(fields, mode) = (*self).data_type() else {
1370            unreachable!()
1371        };
1372
1373        let max_id = fields.iter().map(|(id, _)| id).max().unwrap_or_default() as usize;
1374        let mut out: Vec<Option<FieldDisplay>> = (0..max_id + 1).map(|_| None).collect();
1375        for (i, field) in fields.iter() {
1376            let formatter = make_array_formatter(self.child(i).as_ref(), options, Some(field))?;
1377            out[i as usize] = Some((field.name().as_str(), formatter))
1378        }
1379        Ok((out, *mode))
1380    }
1381
1382    fn write(&self, s: &Self::State, idx: usize, f: &mut dyn Write) -> FormatResult {
1383        let id = self.type_id(idx);
1384        let idx = match s.1 {
1385            UnionMode::Dense => self.value_offset(idx),
1386            UnionMode::Sparse => idx,
1387        };
1388        let (name, field) = s.0[id as usize].as_ref().unwrap();
1389
1390        write!(f, "{{{name}={}}}", field.value(idx))?;
1391        Ok(())
1392    }
1393}
1394
1395/// Get the value at the given row in an array as a String.
1396///
1397/// Note this function is quite inefficient and is unlikely to be
1398/// suitable for converting large arrays or record batches.
1399///
1400/// Please see [`ArrayFormatter`] for a more performant interface
1401pub fn array_value_to_string(column: &dyn Array, row: usize) -> Result<String, ArrowError> {
1402    let options = FormatOptions::default().with_display_error(true);
1403    let formatter = ArrayFormatter::try_new(column, &options)?;
1404    Ok(formatter.value(row).to_string())
1405}
1406
1407/// Converts numeric type to a `String`
1408pub fn lexical_to_string<N: lexical_core::ToLexical>(n: N) -> String {
1409    let mut buf = Vec::<u8>::with_capacity(N::FORMATTED_SIZE_DECIMAL);
1410    unsafe {
1411        // JUSTIFICATION
1412        //  Benefit
1413        //      Allows using the faster serializer lexical core and convert to string
1414        //  Soundness
1415        //      Length of buf is set as written length afterwards. lexical_core
1416        //      creates a valid string, so doesn't need to be checked.
1417        let slice = std::slice::from_raw_parts_mut(buf.as_mut_ptr(), buf.capacity());
1418        let len = lexical_core::write(n, slice).len();
1419        buf.set_len(len);
1420        String::from_utf8_unchecked(buf)
1421    }
1422}
1423
1424#[cfg(test)]
1425mod tests {
1426    use super::*;
1427    use arrow_array::builder::StringRunBuilder;
1428    /// Test to verify options can be constant. See #4580
1429    const TEST_CONST_OPTIONS: FormatOptions<'static> = FormatOptions::new()
1430        .with_date_format(Some("foo"))
1431        .with_timestamp_format(Some("404"));
1432
1433    #[test]
1434    fn test_const_options() {
1435        assert_eq!(TEST_CONST_OPTIONS.date_format, Some("foo"));
1436    }
1437
1438    /// See https://github.com/apache/arrow-rs/issues/8875
1439    #[test]
1440    fn test_options_send_sync() {
1441        fn assert_send_sync<T>()
1442        where
1443            T: Send + Sync,
1444        {
1445            // nothing – the compiler does the work
1446        }
1447
1448        assert_send_sync::<FormatOptions<'static>>();
1449    }
1450
1451    #[test]
1452    fn test_map_array_to_string() {
1453        let keys = vec!["a", "b", "c", "d", "e", "f", "g", "h"];
1454        let values_data = UInt32Array::from(vec![0u32, 10, 20, 30, 40, 50, 60, 70]);
1455
1456        // Construct a buffer for value offsets, for the nested array:
1457        //  [[a, b, c], [d, e, f], [g, h]]
1458        let entry_offsets = [0, 3, 6, 8];
1459
1460        let map_array =
1461            MapArray::new_from_strings(keys.clone().into_iter(), &values_data, &entry_offsets)
1462                .unwrap();
1463        assert_eq!(
1464            "{d: 30, e: 40, f: 50}",
1465            array_value_to_string(&map_array, 1).unwrap()
1466        );
1467    }
1468
1469    fn format_array(array: &dyn Array, fmt: &FormatOptions) -> Vec<String> {
1470        let fmt = ArrayFormatter::try_new(array, fmt).unwrap();
1471        (0..array.len()).map(|x| fmt.value(x).to_string()).collect()
1472    }
1473
1474    #[test]
1475    fn test_timestamp_tz_offset_with_seconds() {
1476        let options = FormatOptions::new();
1477        let cases = [
1478            ("Africa/Monrovia", "1960-06-01T12:00:00.250Z"),
1479            ("Europe/Paris", "1900-06-01T12:00:00.250Z"),
1480        ];
1481        for (tz, ts) in cases {
1482            let expected = crate::parse::string_to_datetime(&Utc, ts).unwrap();
1483            let array = TimestampMillisecondArray::from(vec![expected.timestamp_millis()])
1484                .with_timezone(tz);
1485            let formatted = format_array(&array, &options);
1486            assert_eq!(formatted, [ts]);
1487            let parsed = crate::parse::string_to_datetime(&Utc, &formatted[0]).unwrap();
1488            assert_eq!(parsed, expected);
1489        }
1490
1491        let array = TimestampSecondArray::from(vec![0]).with_timezone("Asia/Kolkata");
1492        assert_eq!(
1493            format_array(&array, &options),
1494            ["1970-01-01T05:30:00+05:30"]
1495        );
1496    }
1497
1498    #[test]
1499    fn test_temporal_custom_format() {
1500        let options = FormatOptions::new()
1501            .with_date_format(Some("%Y-%m-%d"))
1502            .with_datetime_format(Some("%Y-%m-%d %H:%M:%S"))
1503            .with_time_format(Some("%H:%M:%S"))
1504            .with_timestamp_format(Some("%Y-%m-%d %H:%M:%S"))
1505            .with_timestamp_tz_format(Some("%Y-%m-%d %H:%M:%S %:z"));
1506
1507        let date32 = Date32Array::from(vec![0]);
1508        assert_eq!(format_array(&date32, &options), ["1970-01-01"]);
1509
1510        let date64 = Date64Array::from(vec![0]);
1511        assert_eq!(format_array(&date64, &options), ["1970-01-01 00:00:00"]);
1512
1513        let time = Time32SecondArray::from(vec![3661]);
1514        assert_eq!(format_array(&time, &options), ["01:01:01"]);
1515
1516        let timestamp = TimestampSecondArray::from(vec![0]);
1517        assert_eq!(format_array(&timestamp, &options), ["1970-01-01 00:00:00"]);
1518
1519        let timestamp_tz = TimestampSecondArray::from(vec![0]).with_timezone("+08:00");
1520        assert_eq!(
1521            format_array(&timestamp_tz, &options),
1522            ["1970-01-01 08:00:00 +08:00"]
1523        );
1524
1525        let invalid_options = FormatOptions::new().with_datetime_format(Some("%"));
1526        let formatter = ArrayFormatter::try_new(&date64, &invalid_options).unwrap();
1527        assert!(formatter.value(0).try_to_string().is_err());
1528    }
1529
1530    #[test]
1531    fn test_array_value_to_string_duration() {
1532        let iso_fmt = FormatOptions::new();
1533        let pretty_fmt = FormatOptions::new().with_duration_format(DurationFormat::Pretty);
1534
1535        let array = DurationNanosecondArray::from(vec![
1536            1,
1537            -1,
1538            1000,
1539            -1000,
1540            (45 * 60 * 60 * 24 + 14 * 60 * 60 + 2 * 60 + 34) * 1_000_000_000 + 123456789,
1541            -(45 * 60 * 60 * 24 + 14 * 60 * 60 + 2 * 60 + 34) * 1_000_000_000 - 123456789,
1542        ]);
1543        let iso = format_array(&array, &iso_fmt);
1544        let pretty = format_array(&array, &pretty_fmt);
1545
1546        assert_eq!(iso[0], "PT0.000000001S");
1547        assert_eq!(pretty[0], "0 days 0 hours 0 mins 0.000000001 secs");
1548        assert_eq!(iso[1], "-PT0.000000001S");
1549        assert_eq!(pretty[1], "0 days 0 hours 0 mins -0.000000001 secs");
1550        assert_eq!(iso[2], "PT0.000001S");
1551        assert_eq!(pretty[2], "0 days 0 hours 0 mins 0.000001000 secs");
1552        assert_eq!(iso[3], "-PT0.000001S");
1553        assert_eq!(pretty[3], "0 days 0 hours 0 mins -0.000001000 secs");
1554        assert_eq!(iso[4], "PT3938554.123456789S");
1555        assert_eq!(pretty[4], "45 days 14 hours 2 mins 34.123456789 secs");
1556        assert_eq!(iso[5], "-PT3938554.123456789S");
1557        assert_eq!(pretty[5], "-45 days -14 hours -2 mins -34.123456789 secs");
1558
1559        let array = DurationMicrosecondArray::from(vec![
1560            1,
1561            -1,
1562            1000,
1563            -1000,
1564            (45 * 60 * 60 * 24 + 14 * 60 * 60 + 2 * 60 + 34) * 1_000_000 + 123456,
1565            -(45 * 60 * 60 * 24 + 14 * 60 * 60 + 2 * 60 + 34) * 1_000_000 - 123456,
1566        ]);
1567        let iso = format_array(&array, &iso_fmt);
1568        let pretty = format_array(&array, &pretty_fmt);
1569
1570        assert_eq!(iso[0], "PT0.000001S");
1571        assert_eq!(pretty[0], "0 days 0 hours 0 mins 0.000001 secs");
1572        assert_eq!(iso[1], "-PT0.000001S");
1573        assert_eq!(pretty[1], "0 days 0 hours 0 mins -0.000001 secs");
1574        assert_eq!(iso[2], "PT0.001S");
1575        assert_eq!(pretty[2], "0 days 0 hours 0 mins 0.001000 secs");
1576        assert_eq!(iso[3], "-PT0.001S");
1577        assert_eq!(pretty[3], "0 days 0 hours 0 mins -0.001000 secs");
1578        assert_eq!(iso[4], "PT3938554.123456S");
1579        assert_eq!(pretty[4], "45 days 14 hours 2 mins 34.123456 secs");
1580        assert_eq!(iso[5], "-PT3938554.123456S");
1581        assert_eq!(pretty[5], "-45 days -14 hours -2 mins -34.123456 secs");
1582
1583        let array = DurationMillisecondArray::from(vec![
1584            1,
1585            -1,
1586            1000,
1587            -1000,
1588            (45 * 60 * 60 * 24 + 14 * 60 * 60 + 2 * 60 + 34) * 1_000 + 123,
1589            -(45 * 60 * 60 * 24 + 14 * 60 * 60 + 2 * 60 + 34) * 1_000 - 123,
1590        ]);
1591        let iso = format_array(&array, &iso_fmt);
1592        let pretty = format_array(&array, &pretty_fmt);
1593
1594        assert_eq!(iso[0], "PT0.001S");
1595        assert_eq!(pretty[0], "0 days 0 hours 0 mins 0.001 secs");
1596        assert_eq!(iso[1], "-PT0.001S");
1597        assert_eq!(pretty[1], "0 days 0 hours 0 mins -0.001 secs");
1598        assert_eq!(iso[2], "PT1S");
1599        assert_eq!(pretty[2], "0 days 0 hours 0 mins 1.000 secs");
1600        assert_eq!(iso[3], "-PT1S");
1601        assert_eq!(pretty[3], "0 days 0 hours 0 mins -1.000 secs");
1602        assert_eq!(iso[4], "PT3938554.123S");
1603        assert_eq!(pretty[4], "45 days 14 hours 2 mins 34.123 secs");
1604        assert_eq!(iso[5], "-PT3938554.123S");
1605        assert_eq!(pretty[5], "-45 days -14 hours -2 mins -34.123 secs");
1606
1607        let array = DurationSecondArray::from(vec![
1608            1,
1609            -1,
1610            1000,
1611            -1000,
1612            45 * 60 * 60 * 24 + 14 * 60 * 60 + 2 * 60 + 34,
1613            -45 * 60 * 60 * 24 - 14 * 60 * 60 - 2 * 60 - 34,
1614        ]);
1615        let iso = format_array(&array, &iso_fmt);
1616        let pretty = format_array(&array, &pretty_fmt);
1617
1618        assert_eq!(iso[0], "PT1S");
1619        assert_eq!(pretty[0], "0 days 0 hours 0 mins 1 secs");
1620        assert_eq!(iso[1], "-PT1S");
1621        assert_eq!(pretty[1], "0 days 0 hours 0 mins -1 secs");
1622        assert_eq!(iso[2], "PT1000S");
1623        assert_eq!(pretty[2], "0 days 0 hours 16 mins 40 secs");
1624        assert_eq!(iso[3], "-PT1000S");
1625        assert_eq!(pretty[3], "0 days 0 hours -16 mins -40 secs");
1626        assert_eq!(iso[4], "PT3938554S");
1627        assert_eq!(pretty[4], "45 days 14 hours 2 mins 34 secs");
1628        assert_eq!(iso[5], "-PT3938554S");
1629        assert_eq!(pretty[5], "-45 days -14 hours -2 mins -34 secs");
1630    }
1631
1632    #[test]
1633    fn test_null() {
1634        let array = NullArray::new(2);
1635        let options = FormatOptions::new().with_null("NULL");
1636        let formatted = format_array(&array, &options);
1637        assert_eq!(formatted, &["NULL".to_string(), "NULL".to_string()])
1638    }
1639
1640    #[test]
1641    fn test_string_run_array_to_string() {
1642        let mut builder = StringRunBuilder::<Int32Type>::new();
1643
1644        builder.append_value("input_value");
1645        builder.append_value("input_value");
1646        builder.append_value("input_value");
1647        builder.append_value("input_value1");
1648
1649        let map_array = builder.finish();
1650        assert_eq!("input_value", array_value_to_string(&map_array, 1).unwrap());
1651        assert_eq!(
1652            "input_value1",
1653            array_value_to_string(&map_array, 3).unwrap()
1654        );
1655    }
1656
1657    #[test]
1658    fn test_list_view_to_string() {
1659        let list_view = ListViewArray::from_iter_primitive::<Int32Type, _, _>(vec![
1660            Some(vec![Some(1), Some(2), Some(3)]),
1661            None,
1662            Some(vec![Some(4), None, Some(6)]),
1663            Some(vec![]),
1664        ]);
1665
1666        assert_eq!("[1, 2, 3]", array_value_to_string(&list_view, 0).unwrap());
1667        assert_eq!("", array_value_to_string(&list_view, 1).unwrap());
1668        assert_eq!("[4, , 6]", array_value_to_string(&list_view, 2).unwrap());
1669        assert_eq!("[]", array_value_to_string(&list_view, 3).unwrap());
1670    }
1671
1672    #[test]
1673    fn test_large_list_view_to_string() {
1674        let list_view = LargeListViewArray::from_iter_primitive::<Int32Type, _, _>(vec![
1675            Some(vec![Some(1), Some(2), Some(3)]),
1676            None,
1677            Some(vec![Some(4), None, Some(6)]),
1678            Some(vec![]),
1679        ]);
1680
1681        assert_eq!("[1, 2, 3]", array_value_to_string(&list_view, 0).unwrap());
1682        assert_eq!("", array_value_to_string(&list_view, 1).unwrap());
1683        assert_eq!("[4, , 6]", array_value_to_string(&list_view, 2).unwrap());
1684        assert_eq!("[]", array_value_to_string(&list_view, 3).unwrap());
1685    }
1686}