vortex_array/array/display/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod tree;
5
6use std::fmt::Display;
7
8use itertools::Itertools as _;
9use tree::TreeDisplayWrapper;
10
11use crate::Array;
12
13/// Describe how to convert an array to a string.
14///
15/// See also:
16/// [Array::display_as](../trait.Array.html#method.display_as)
17/// and [DisplayArrayAs].
18pub enum DisplayOptions {
19    /// Only the top-level encoding id and limited metadata: `vortex.primitive(i16, len=5)`.
20    ///
21    /// ```
22    /// # use vortex_array::display::DisplayOptions;
23    /// # use vortex_array::IntoArray;
24    /// # use vortex_buffer::buffer;
25    /// let array = buffer![0_i16, 1, 2, 3, 4].into_array();
26    /// assert_eq!(
27    ///     format!("{}", array.display_as(DisplayOptions::MetadataOnly)),
28    ///     "vortex.primitive(i16, len=5)",
29    /// );
30    /// ```
31    MetadataOnly,
32    /// Only the logical values of the array: `[0i16, 1i16, 2i16, 3i16, 4i16]`.
33    ///
34    /// ```
35    /// # use vortex_array::display::DisplayOptions;
36    /// # use vortex_array::IntoArray;
37    /// # use vortex_buffer::buffer;
38    /// let array = buffer![0_i16, 1, 2, 3, 4].into_array();
39    /// assert_eq!(
40    ///     format!("{}", array.display_as(DisplayOptions::default())),
41    ///     "[0i16, 1i16, 2i16, 3i16, 4i16]",
42    /// );
43    /// assert_eq!(
44    ///     format!("{}", array.display_as(DisplayOptions::default())),
45    ///     format!("{}", array.display_values()),
46    /// );
47    /// ```
48    CommaSeparatedScalars { omit_comma_after_space: bool },
49    /// The tree of encodings and all metadata but no values.
50    ///
51    /// ```
52    /// # use vortex_array::display::DisplayOptions;
53    /// # use vortex_array::IntoArray;
54    /// # use vortex_buffer::buffer;
55    /// let array = buffer![0_i16, 1, 2, 3, 4].into_array();
56    /// let expected = "root: vortex.primitive(i16, len=5) nbytes=10 B (100.00%)
57    ///   metadata: EmptyMetadata
58    ///   buffer (align=2): 10 B (100.00%)
59    /// ";
60    /// assert_eq!(format!("{}", array.display_as(DisplayOptions::TreeDisplay)), expected);
61    /// ```
62    TreeDisplay,
63    /// Display values in a formatted table with columns.
64    ///
65    /// For struct arrays, displays a column for each field in the struct.
66    /// For regular arrays, displays a single column with values.
67    ///
68    /// ```
69    /// # use vortex_array::display::DisplayOptions;
70    /// # use vortex_array::arrays::StructArray;
71    /// # use vortex_array::IntoArray;
72    /// # use vortex_buffer::buffer;
73    /// let s = StructArray::from_fields(&[
74    ///     ("x", buffer![1, 2].into_array()),
75    ///     ("y", buffer![3, 4].into_array()),
76    /// ]).unwrap().into_array();
77    /// let expected = "
78    /// ┌──────┬──────┐
79    /// │  x   │  y   │
80    /// ├──────┼──────┤
81    /// │ 1i32 │ 3i32 │
82    /// ├──────┼──────┤
83    /// │ 2i32 │ 4i32 │
84    /// └──────┴──────┘".trim();
85    /// assert_eq!(format!("{}", s.display_as(DisplayOptions::TableDisplay)), expected);
86    /// ```
87    #[cfg(feature = "table-display")]
88    TableDisplay,
89}
90
91impl Default for DisplayOptions {
92    fn default() -> Self {
93        Self::CommaSeparatedScalars {
94            omit_comma_after_space: false,
95        }
96    }
97}
98
99/// A shim used to display an array as specified in the options.
100///
101/// See also:
102/// [Array::display_as](../trait.Array.html#method.display_as)
103/// and [DisplayOptions].
104pub struct DisplayArrayAs<'a>(pub &'a dyn Array, pub DisplayOptions);
105
106impl Display for DisplayArrayAs<'_> {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        self.0.fmt_as(f, &self.1)
109    }
110}
111
112/// Display the encoding and limited metadata of this array.
113///
114/// # Examples
115/// ```
116/// # use vortex_array::IntoArray;
117/// # use vortex_buffer::buffer;
118/// let array = buffer![0_i16, 1, 2, 3, 4].into_array();
119/// assert_eq!(
120///     format!("{}", array),
121///     "vortex.primitive(i16, len=5)",
122/// );
123/// ```
124impl Display for dyn Array + '_ {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        self.fmt_as(f, &DisplayOptions::MetadataOnly)
127    }
128}
129
130impl dyn Array + '_ {
131    /// Display logical values of the array
132    ///
133    /// For example, an `i16` typed array containing the first five non-negative integers is displayed
134    /// as: `[0i16, 1i16, 2i16, 3i16, 4i16]`.
135    ///
136    /// # Examples
137    ///
138    /// ```
139    /// # use vortex_array::IntoArray;
140    /// # use vortex_buffer::buffer;
141    /// let array = buffer![0_i16, 1, 2, 3, 4].into_array();
142    /// assert_eq!(
143    ///     format!("{}", array.display_values()),
144    ///     "[0i16, 1i16, 2i16, 3i16, 4i16]",
145    /// )
146    /// ```
147    ///
148    /// See also:
149    /// [Array::display_as](..//trait.Array.html#method.display_as),
150    /// [DisplayArrayAs], and [DisplayOptions].
151    pub fn display_values(&self) -> impl Display {
152        DisplayArrayAs(
153            self,
154            DisplayOptions::CommaSeparatedScalars {
155                omit_comma_after_space: false,
156            },
157        )
158    }
159
160    /// Display the array as specified by the options.
161    ///
162    /// See [DisplayOptions] for examples.
163    pub fn display_as(&self, options: DisplayOptions) -> impl Display {
164        DisplayArrayAs(self, options)
165    }
166
167    /// Display the tree of encodings of this array as an indented lists.
168    ///
169    /// While some metadata (such as length, bytes and validity-rate) are included, the logical
170    /// values of the array are not displayed. To view the logical values see
171    /// [Array::display_as](../trait.Array.html#method.display_as)
172    /// and [DisplayOptions].
173    ///
174    /// # Examples
175    /// ```
176    /// # use vortex_array::display::DisplayOptions;
177    /// # use vortex_array::IntoArray;
178    /// # use vortex_buffer::buffer;
179    /// let array = buffer![0_i16, 1, 2, 3, 4].into_array();
180    /// let expected = "root: vortex.primitive(i16, len=5) nbytes=10 B (100.00%)
181    ///   metadata: EmptyMetadata
182    ///   buffer (align=2): 10 B (100.00%)
183    /// ";
184    /// assert_eq!(format!("{}", array.display_tree()), expected);
185    /// ```
186    pub fn display_tree(&self) -> impl Display {
187        DisplayArrayAs(self, DisplayOptions::TreeDisplay)
188    }
189
190    /// Display the array as a formatted table.
191    ///
192    /// For struct arrays, displays a column for each field in the struct.
193    /// For regular arrays, displays a single column with values.
194    ///
195    /// # Examples
196    /// ```
197    /// # #[cfg(feature = "table-display")]
198    /// # {
199    /// # use vortex_array::arrays::StructArray;
200    /// # use vortex_array::IntoArray;
201    /// # use vortex_buffer::buffer;
202    /// let s = StructArray::from_fields(&[
203    ///     ("x", buffer![1, 2].into_array()),
204    ///     ("y", buffer![3, 4].into_array()),
205    /// ]).unwrap().into_array();
206    /// let expected = "
207    /// ┌──────┬──────┐
208    /// │  x   │  y   │
209    /// ├──────┼──────┤
210    /// │ 1i32 │ 3i32 │
211    /// ├──────┼──────┤
212    /// │ 2i32 │ 4i32 │
213    /// └──────┴──────┘".trim();
214    /// assert_eq!(format!("{}", s.display_table()), expected);
215    /// # }
216    /// ```
217    #[cfg(feature = "table-display")]
218    pub fn display_table(&self) -> impl Display {
219        DisplayArrayAs(self, DisplayOptions::TableDisplay)
220    }
221
222    fn fmt_as(&self, f: &mut std::fmt::Formatter, options: &DisplayOptions) -> std::fmt::Result {
223        match options {
224            DisplayOptions::MetadataOnly => {
225                write!(
226                    f,
227                    "{}({}, len={})",
228                    self.encoding_id(),
229                    self.dtype(),
230                    self.len()
231                )
232            }
233            DisplayOptions::CommaSeparatedScalars {
234                omit_comma_after_space,
235            } => {
236                write!(f, "[")?;
237                let sep = if *omit_comma_after_space { "," } else { ", " };
238                write!(
239                    f,
240                    "{}",
241                    (0..self.len()).map(|i| self.scalar_at(i)).format(sep)
242                )?;
243                write!(f, "]")
244            }
245            DisplayOptions::TreeDisplay => write!(f, "{}", TreeDisplayWrapper(self.to_array())),
246            #[cfg(feature = "table-display")]
247            DisplayOptions::TableDisplay => {
248                use vortex_dtype::DType;
249
250                use crate::canonical::ToCanonical;
251
252                let mut builder = tabled::builder::Builder::default();
253
254                // Special logic for struct arrays.
255                let DType::Struct(sf, _) = self.dtype() else {
256                    // For non-struct arrays, simply display a single column table without header.
257                    for row_idx in 0..self.len() {
258                        let value = self.scalar_at(row_idx);
259                        builder.push_record([value.to_string()]);
260                    }
261
262                    let mut table = builder.build();
263                    table.with(tabled::settings::Style::modern());
264
265                    return write!(f, "{table}");
266                };
267
268                let struct_ = self.to_struct();
269                builder.push_record(sf.names().iter().map(|name| name.to_string()));
270
271                for row_idx in 0..self.len() {
272                    if !self.is_valid(row_idx) {
273                        let null_row = vec!["null".to_string(); sf.names().len()];
274                        builder.push_record(null_row);
275                    } else {
276                        let mut row = Vec::new();
277                        for field_array in struct_.fields() {
278                            let value = field_array.scalar_at(row_idx);
279                            row.push(value.to_string());
280                        }
281                        builder.push_record(row);
282                    }
283                }
284
285                let mut table = builder.build();
286                table.with(tabled::settings::Style::modern());
287
288                // Center headers
289                for col_idx in 0..sf.names().len() {
290                    table.modify((0, col_idx), tabled::settings::Alignment::center());
291                }
292
293                for row_idx in 0..self.len() {
294                    if !self.is_valid(row_idx) {
295                        table.modify(
296                            (1 + row_idx, 0),
297                            tabled::settings::Span::column(sf.names().len() as isize),
298                        );
299                        table.modify((1 + row_idx, 0), tabled::settings::Alignment::center());
300                    }
301                }
302
303                write!(f, "{table}")
304            }
305        }
306    }
307}
308
309#[cfg(test)]
310mod test {
311    use vortex_buffer::{Buffer, buffer};
312    use vortex_dtype::FieldNames;
313
314    use crate::IntoArray as _;
315    use crate::arrays::{BoolArray, ListArray, StructArray};
316    use crate::validity::Validity;
317
318    #[test]
319    fn test_primitive() {
320        let x = Buffer::<u32>::empty().into_array();
321        assert_eq!(x.display_values().to_string(), "[]");
322
323        let x = buffer![1].into_array();
324        assert_eq!(x.display_values().to_string(), "[1i32]");
325
326        let x = buffer![1, 2, 3, 4].into_array();
327        assert_eq!(x.display_values().to_string(), "[1i32, 2i32, 3i32, 4i32]");
328    }
329
330    #[test]
331    fn test_empty_struct() {
332        let s = StructArray::try_new(
333            FieldNames::from(vec![]),
334            vec![],
335            3,
336            Validity::Array(BoolArray::from_iter([true, false, true]).into_array()),
337        )
338        .unwrap()
339        .into_array();
340        assert_eq!(s.display_values().to_string(), "[{}, null, {}]");
341    }
342
343    #[test]
344    fn test_simple_struct() {
345        let s = StructArray::from_fields(&[
346            ("x", buffer![1, 2, 3, 4].into_array()),
347            ("y", buffer![-1, -2, -3, -4].into_array()),
348        ])
349        .unwrap()
350        .into_array();
351        assert_eq!(
352            s.display_values().to_string(),
353            "[{x: 1i32, y: -1i32}, {x: 2i32, y: -2i32}, {x: 3i32, y: -3i32}, {x: 4i32, y: -4i32}]"
354        );
355    }
356
357    #[test]
358    fn test_list() {
359        let x = ListArray::try_new(
360            buffer![1, 2, 3, 4].into_array(),
361            buffer![0, 0, 1, 1, 2, 4].into_array(),
362            Validity::Array(BoolArray::from_iter([true, true, false, true, true]).into_array()),
363        )
364        .unwrap()
365        .into_array();
366        assert_eq!(
367            x.display_values().to_string(),
368            "[[], [1i32], null, [2i32], [3i32, 4i32]]"
369        );
370    }
371
372    #[test]
373    #[cfg(feature = "table-display")]
374    fn test_table_display_primitive() {
375        use crate::display::DisplayOptions;
376
377        let array = buffer![1, 2, 3, 4].into_array();
378        let table_display = array.display_as(DisplayOptions::TableDisplay);
379        assert_eq!(
380            table_display.to_string(),
381            r"
382┌──────┐
383│ 1i32 │
384├──────┤
385│ 2i32 │
386├──────┤
387│ 3i32 │
388├──────┤
389│ 4i32 │
390└──────┘"
391                .trim()
392        );
393    }
394
395    #[test]
396    #[cfg(feature = "table-display")]
397    fn test_table_display() {
398        use crate::display::DisplayOptions;
399
400        let array = crate::arrays::PrimitiveArray::from_option_iter(vec![
401            Some(-1),
402            Some(-2),
403            Some(-3),
404            None,
405        ])
406        .into_array();
407
408        let struct_ = StructArray::try_from_iter_with_validity(
409            [("x", buffer![1, 2, 3, 4].into_array()), ("y", array)],
410            Validity::Array(BoolArray::from_iter([true, false, true, true]).into_array()),
411        )
412        .unwrap()
413        .into_array();
414
415        let table_display = struct_.display_as(DisplayOptions::TableDisplay);
416        assert_eq!(
417            table_display.to_string(),
418            r"
419┌──────┬───────┐
420│  x   │   y   │
421├──────┼───────┤
422│ 1i32 │ -1i32 │
423├──────┼───────┤
424│     null     │
425├──────┼───────┤
426│ 3i32 │ -3i32 │
427├──────┼───────┤
428│ 4i32 │ null  │
429└──────┴───────┘"
430                .trim()
431        );
432    }
433}