polars_core/
fmt.rs

1#![allow(unsafe_op_in_unsafe_fn)]
2#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
3use std::borrow::Cow;
4use std::fmt::{Debug, Display, Formatter, Write};
5use std::str::FromStr;
6use std::sync::RwLock;
7use std::{fmt, str};
8
9#[cfg(any(
10    feature = "dtype-date",
11    feature = "dtype-datetime",
12    feature = "dtype-time"
13))]
14use arrow::temporal_conversions::*;
15#[cfg(feature = "dtype-datetime")]
16use chrono::NaiveDateTime;
17#[cfg(feature = "timezones")]
18use chrono::TimeZone;
19#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
20use comfy_table::modifiers::*;
21#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
22use comfy_table::presets::*;
23#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
24use comfy_table::*;
25use num_traits::{Num, NumCast};
26use polars_error::feature_gated;
27use polars_utils::relaxed_cell::RelaxedCell;
28
29use crate::config::*;
30use crate::prelude::*;
31
32// Note: see https://github.com/pola-rs/polars/pull/13699 for the rationale
33// behind choosing 10 as the default value for default number of rows displayed
34const DEFAULT_ROW_LIMIT: usize = 10;
35#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
36const DEFAULT_COL_LIMIT: usize = 8;
37const DEFAULT_STR_LEN_LIMIT: usize = 30;
38const DEFAULT_LIST_LEN_LIMIT: usize = 3;
39
40#[derive(Copy, Clone)]
41#[repr(u8)]
42pub enum FloatFmt {
43    Mixed,
44    Full,
45}
46static FLOAT_PRECISION: RwLock<Option<usize>> = RwLock::new(None);
47static FLOAT_FMT: RelaxedCell<u8> = RelaxedCell::new_u8(FloatFmt::Mixed as u8);
48
49static THOUSANDS_SEPARATOR: RelaxedCell<u8> = RelaxedCell::new_u8(b'\0');
50static DECIMAL_SEPARATOR: RelaxedCell<u8> = RelaxedCell::new_u8(b'.');
51
52// Numeric formatting getters
53pub fn get_float_fmt() -> FloatFmt {
54    match FLOAT_FMT.load() {
55        0 => FloatFmt::Mixed,
56        1 => FloatFmt::Full,
57        _ => panic!(),
58    }
59}
60pub fn get_float_precision() -> Option<usize> {
61    *FLOAT_PRECISION.read().unwrap()
62}
63pub fn get_decimal_separator() -> char {
64    DECIMAL_SEPARATOR.load() as char
65}
66pub fn get_thousands_separator() -> String {
67    let sep = THOUSANDS_SEPARATOR.load() as char;
68    if sep == '\0' {
69        "".to_string()
70    } else {
71        sep.to_string()
72    }
73}
74#[cfg(feature = "dtype-decimal")]
75pub fn get_trim_decimal_zeros() -> bool {
76    arrow::compute::decimal::get_trim_decimal_zeros()
77}
78
79// Numeric formatting setters
80pub fn set_float_fmt(fmt: FloatFmt) {
81    FLOAT_FMT.store(fmt as u8)
82}
83pub fn set_float_precision(precision: Option<usize>) {
84    *FLOAT_PRECISION.write().unwrap() = precision;
85}
86pub fn set_decimal_separator(dec: Option<char>) {
87    DECIMAL_SEPARATOR.store(dec.unwrap_or('.') as u8)
88}
89pub fn set_thousands_separator(sep: Option<char>) {
90    THOUSANDS_SEPARATOR.store(sep.unwrap_or('\0') as u8)
91}
92#[cfg(feature = "dtype-decimal")]
93pub fn set_trim_decimal_zeros(trim: Option<bool>) {
94    arrow::compute::decimal::set_trim_decimal_zeros(trim)
95}
96
97/// Parses an environment variable value.
98fn parse_env_var<T: FromStr>(name: &str) -> Option<T> {
99    std::env::var(name).ok().and_then(|v| v.parse().ok())
100}
101/// Parses an environment variable value as a limit or set a default.
102///
103/// Negative values (e.g. -1) are parsed as 'no limit' or [`usize::MAX`].
104fn parse_env_var_limit(name: &str, default: usize) -> usize {
105    parse_env_var(name).map_or(
106        default,
107        |n: i64| {
108            if n < 0 { usize::MAX } else { n as usize }
109        },
110    )
111}
112
113fn get_row_limit() -> usize {
114    parse_env_var_limit(FMT_MAX_ROWS, DEFAULT_ROW_LIMIT)
115}
116#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
117fn get_col_limit() -> usize {
118    parse_env_var_limit(FMT_MAX_COLS, DEFAULT_COL_LIMIT)
119}
120fn get_str_len_limit() -> usize {
121    parse_env_var_limit(FMT_STR_LEN, DEFAULT_STR_LEN_LIMIT)
122}
123fn get_list_len_limit() -> usize {
124    parse_env_var_limit(FMT_TABLE_CELL_LIST_LEN, DEFAULT_LIST_LEN_LIMIT)
125}
126#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
127fn get_ellipsis() -> &'static str {
128    match std::env::var(FMT_TABLE_FORMATTING).as_deref().unwrap_or("") {
129        preset if preset.starts_with("ASCII") => "...",
130        _ => "…",
131    }
132}
133#[cfg(not(any(feature = "fmt", feature = "fmt_no_tty")))]
134fn get_ellipsis() -> &'static str {
135    "…"
136}
137
138fn estimate_string_width(s: &str) -> usize {
139    // get a slightly more accurate estimate of a string's screen
140    // width, accounting (very roughly) for multibyte characters
141    let n_chars = s.chars().count();
142    let n_bytes = s.len();
143    if n_bytes == n_chars {
144        n_chars
145    } else {
146        let adjust = n_bytes as f64 / n_chars as f64;
147        std::cmp::min(n_chars * 2, (n_chars as f64 * adjust).ceil() as usize)
148    }
149}
150
151macro_rules! format_array {
152    ($f:ident, $a:expr, $dtype:expr, $name:expr, $array_type:expr) => {{
153        write!(
154            $f,
155            "shape: ({},)\n{}: '{}' [{}]\n[\n",
156            fmt_int_string_custom(&$a.len().to_string(), 3, "_"),
157            $array_type,
158            $name,
159            $dtype
160        )?;
161
162        let ellipsis = get_ellipsis();
163        let truncate = match $a.dtype() {
164            DataType::String => true,
165            #[cfg(feature = "dtype-categorical")]
166            DataType::Categorical(_, _) | DataType::Enum(_, _) => true,
167            _ => false,
168        };
169        let truncate_len = if truncate { get_str_len_limit() } else { 0 };
170
171        let write_fn = |v, f: &mut Formatter| -> fmt::Result {
172            if truncate {
173                let v = format!("{}", v);
174                let v_no_quotes = &v[1..v.len() - 1];
175                let v_trunc = &v_no_quotes[..v_no_quotes
176                    .char_indices()
177                    .take(truncate_len)
178                    .last()
179                    .map(|(i, c)| i + c.len_utf8())
180                    .unwrap_or(0)];
181                if v_no_quotes == v_trunc {
182                    write!(f, "\t{}\n", v)?;
183                } else {
184                    write!(f, "\t\"{v_trunc}{ellipsis}\n")?;
185                }
186            } else {
187                write!(f, "\t{v}\n")?;
188            };
189            Ok(())
190        };
191
192        let limit = get_row_limit();
193
194        if $a.len() > limit {
195            let half = limit / 2;
196            let rest = limit % 2;
197
198            for i in 0..(half + rest) {
199                let v = $a.get_any_value(i).unwrap();
200                write_fn(v, $f)?;
201            }
202            write!($f, "\t{ellipsis}\n")?;
203            for i in ($a.len() - half)..$a.len() {
204                let v = $a.get_any_value(i).unwrap();
205                write_fn(v, $f)?;
206            }
207        } else {
208            for i in 0..$a.len() {
209                let v = $a.get_any_value(i).unwrap();
210                write_fn(v, $f)?;
211            }
212        }
213
214        write!($f, "]")
215    }};
216}
217
218#[cfg(feature = "object")]
219fn format_object_array(
220    f: &mut Formatter<'_>,
221    object: &Series,
222    name: &str,
223    array_type: &str,
224) -> fmt::Result {
225    match object.dtype() {
226        DataType::Object(inner_type) => {
227            let limit = std::cmp::min(DEFAULT_ROW_LIMIT, object.len());
228            write!(
229                f,
230                "shape: ({},)\n{}: '{}' [o][{}]\n[\n",
231                fmt_int_string_custom(&object.len().to_string(), 3, "_"),
232                array_type,
233                name,
234                inner_type
235            )?;
236            for i in 0..limit {
237                let v = object.str_value(i);
238                writeln!(f, "\t{}", v.unwrap())?;
239            }
240            write!(f, "]")
241        },
242        _ => unreachable!(),
243    }
244}
245
246impl<T> Debug for ChunkedArray<T>
247where
248    T: PolarsNumericType,
249{
250    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
251        let dt = format!("{}", T::get_static_dtype());
252        format_array!(f, self, dt, self.name(), "ChunkedArray")
253    }
254}
255
256impl Debug for ChunkedArray<BooleanType> {
257    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
258        format_array!(f, self, "bool", self.name(), "ChunkedArray")
259    }
260}
261
262impl Debug for StringChunked {
263    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
264        format_array!(f, self, "str", self.name(), "ChunkedArray")
265    }
266}
267
268impl Debug for BinaryChunked {
269    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
270        format_array!(f, self, "binary", self.name(), "ChunkedArray")
271    }
272}
273
274impl Debug for ListChunked {
275    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
276        format_array!(f, self, "list", self.name(), "ChunkedArray")
277    }
278}
279
280#[cfg(feature = "dtype-array")]
281impl Debug for ArrayChunked {
282    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
283        format_array!(f, self, "fixed size list", self.name(), "ChunkedArray")
284    }
285}
286
287#[cfg(feature = "object")]
288impl<T> Debug for ObjectChunked<T>
289where
290    T: PolarsObject,
291{
292    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
293        let limit = std::cmp::min(DEFAULT_ROW_LIMIT, self.len());
294        let ellipsis = get_ellipsis();
295        let inner_type = T::type_name();
296        write!(
297            f,
298            "ChunkedArray: '{}' [o][{}]\n[\n",
299            self.name(),
300            inner_type
301        )?;
302
303        if limit < self.len() {
304            for i in 0..limit / 2 {
305                match self.get(i) {
306                    None => writeln!(f, "\tnull")?,
307                    Some(val) => writeln!(f, "\t{val}")?,
308                };
309            }
310            writeln!(f, "\t{ellipsis}")?;
311            for i in (0..limit / 2).rev() {
312                match self.get(self.len() - i - 1) {
313                    None => writeln!(f, "\tnull")?,
314                    Some(val) => writeln!(f, "\t{val}")?,
315                };
316            }
317        } else {
318            for i in 0..limit {
319                match self.get(i) {
320                    None => writeln!(f, "\tnull")?,
321                    Some(val) => writeln!(f, "\t{val}")?,
322                };
323            }
324        }
325        Ok(())
326    }
327}
328
329impl Debug for Series {
330    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
331        match self.dtype() {
332            DataType::Boolean => {
333                format_array!(f, self.bool().unwrap(), "bool", self.name(), "Series")
334            },
335            DataType::String => {
336                format_array!(f, self.str().unwrap(), "str", self.name(), "Series")
337            },
338            DataType::UInt8 => {
339                format_array!(f, self.u8().unwrap(), "u8", self.name(), "Series")
340            },
341            DataType::UInt16 => {
342                format_array!(f, self.u16().unwrap(), "u16", self.name(), "Series")
343            },
344            DataType::UInt32 => {
345                format_array!(f, self.u32().unwrap(), "u32", self.name(), "Series")
346            },
347            DataType::UInt64 => {
348                format_array!(f, self.u64().unwrap(), "u64", self.name(), "Series")
349            },
350            DataType::UInt128 => {
351                feature_gated!(
352                    "dtype-u128",
353                    format_array!(f, self.u128().unwrap(), "u128", self.name(), "Series")
354                )
355            },
356            DataType::Int8 => {
357                format_array!(f, self.i8().unwrap(), "i8", self.name(), "Series")
358            },
359            DataType::Int16 => {
360                format_array!(f, self.i16().unwrap(), "i16", self.name(), "Series")
361            },
362            DataType::Int32 => {
363                format_array!(f, self.i32().unwrap(), "i32", self.name(), "Series")
364            },
365            DataType::Int64 => {
366                format_array!(f, self.i64().unwrap(), "i64", self.name(), "Series")
367            },
368            DataType::Int128 => {
369                feature_gated!(
370                    "dtype-i128",
371                    format_array!(f, self.i128().unwrap(), "i128", self.name(), "Series")
372                )
373            },
374            DataType::Float32 => {
375                format_array!(f, self.f32().unwrap(), "f32", self.name(), "Series")
376            },
377            DataType::Float64 => {
378                format_array!(f, self.f64().unwrap(), "f64", self.name(), "Series")
379            },
380            #[cfg(feature = "dtype-date")]
381            DataType::Date => format_array!(f, self.date().unwrap(), "date", self.name(), "Series"),
382            #[cfg(feature = "dtype-datetime")]
383            DataType::Datetime(_, _) => {
384                let dt = format!("{}", self.dtype());
385                format_array!(f, self.datetime().unwrap(), &dt, self.name(), "Series")
386            },
387            #[cfg(feature = "dtype-time")]
388            DataType::Time => format_array!(f, self.time().unwrap(), "time", self.name(), "Series"),
389            #[cfg(feature = "dtype-duration")]
390            DataType::Duration(_) => {
391                let dt = format!("{}", self.dtype());
392                format_array!(f, self.duration().unwrap(), &dt, self.name(), "Series")
393            },
394            #[cfg(feature = "dtype-decimal")]
395            DataType::Decimal(_, _) => {
396                let dt = format!("{}", self.dtype());
397                format_array!(f, self.decimal().unwrap(), &dt, self.name(), "Series")
398            },
399            #[cfg(feature = "dtype-array")]
400            DataType::Array(_, _) => {
401                let dt = format!("{}", self.dtype());
402                format_array!(f, self.array().unwrap(), &dt, self.name(), "Series")
403            },
404            DataType::List(_) => {
405                let dt = format!("{}", self.dtype());
406                format_array!(f, self.list().unwrap(), &dt, self.name(), "Series")
407            },
408            #[cfg(feature = "object")]
409            DataType::Object(_) => format_object_array(f, self, self.name(), "Series"),
410            #[cfg(feature = "dtype-categorical")]
411            DataType::Categorical(cats, _) => {
412                with_match_categorical_physical_type!(cats.physical(), |$C| {
413                    format_array!(f, self.cat::<$C>().unwrap(), "cat", self.name(), "Series")
414                })
415            },
416
417            #[cfg(feature = "dtype-categorical")]
418            DataType::Enum(fcats, _) => {
419                with_match_categorical_physical_type!(fcats.physical(), |$C| {
420                    format_array!(f, self.cat::<$C>().unwrap(), "enum", self.name(), "Series")
421                })
422            },
423            #[cfg(feature = "dtype-struct")]
424            dt @ DataType::Struct(_) => format_array!(
425                f,
426                self.struct_().unwrap(),
427                format!("{dt}"),
428                self.name(),
429                "Series"
430            ),
431            DataType::Null => {
432                format_array!(f, self.null().unwrap(), "null", self.name(), "Series")
433            },
434            DataType::Binary => {
435                format_array!(f, self.binary().unwrap(), "binary", self.name(), "Series")
436            },
437            DataType::BinaryOffset => {
438                format_array!(
439                    f,
440                    self.binary_offset().unwrap(),
441                    "binary[offset]",
442                    self.name(),
443                    "Series"
444                )
445            },
446            dt => panic!("{dt:?} not impl"),
447        }
448    }
449}
450
451impl Display for Series {
452    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
453        Debug::fmt(self, f)
454    }
455}
456
457impl Debug for DataFrame {
458    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
459        Display::fmt(self, f)
460    }
461}
462#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
463fn make_str_val(v: &str, truncate: usize, ellipsis: &String) -> String {
464    let v_trunc = &v[..v
465        .char_indices()
466        .take(truncate)
467        .last()
468        .map(|(i, c)| i + c.len_utf8())
469        .unwrap_or(0)];
470    if v == v_trunc {
471        v.to_string()
472    } else {
473        format!("{v_trunc}{ellipsis}")
474    }
475}
476
477#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
478fn field_to_str(
479    f: &Field,
480    str_truncate: usize,
481    ellipsis: &String,
482    padding: usize,
483) -> (String, usize) {
484    let name = make_str_val(f.name(), str_truncate, ellipsis);
485    let name_length = estimate_string_width(name.as_str());
486    let mut column_name = name;
487    if env_is_true(FMT_TABLE_HIDE_COLUMN_NAMES) {
488        column_name = "".to_string();
489    }
490    let column_dtype = if env_is_true(FMT_TABLE_HIDE_COLUMN_DATA_TYPES) {
491        "".to_string()
492    } else if env_is_true(FMT_TABLE_INLINE_COLUMN_DATA_TYPE)
493        | env_is_true(FMT_TABLE_HIDE_COLUMN_NAMES)
494    {
495        format!("{}", f.dtype())
496    } else {
497        format!("\n{}", f.dtype())
498    };
499    let mut dtype_length = column_dtype.trim_start().len();
500    let mut separator = "\n---";
501    if env_is_true(FMT_TABLE_HIDE_COLUMN_SEPARATOR)
502        | env_is_true(FMT_TABLE_HIDE_COLUMN_NAMES)
503        | env_is_true(FMT_TABLE_HIDE_COLUMN_DATA_TYPES)
504    {
505        separator = ""
506    }
507    let s = if env_is_true(FMT_TABLE_INLINE_COLUMN_DATA_TYPE)
508        & !env_is_true(FMT_TABLE_HIDE_COLUMN_DATA_TYPES)
509    {
510        let inline_name_dtype = format!("{column_name} ({column_dtype})");
511        dtype_length = inline_name_dtype.len();
512        inline_name_dtype
513    } else {
514        format!("{column_name}{separator}{column_dtype}")
515    };
516    let mut s_len = std::cmp::max(name_length, dtype_length);
517    let separator_length = estimate_string_width(separator.trim());
518    if s_len < separator_length {
519        s_len = separator_length;
520    }
521    (s, s_len + padding)
522}
523
524#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
525fn prepare_row(
526    row: Vec<Cow<'_, str>>,
527    n_first: usize,
528    n_last: usize,
529    str_truncate: usize,
530    max_elem_lengths: &mut [usize],
531    ellipsis: &String,
532    padding: usize,
533) -> Vec<String> {
534    let reduce_columns = n_first + n_last < row.len();
535    let n_elems = n_first + n_last + reduce_columns as usize;
536    let mut row_strings = Vec::with_capacity(n_elems);
537
538    for (idx, v) in row[0..n_first].iter().enumerate() {
539        let elem_str = make_str_val(v, str_truncate, ellipsis);
540        let elem_len = estimate_string_width(elem_str.as_str()) + padding;
541        if max_elem_lengths[idx] < elem_len {
542            max_elem_lengths[idx] = elem_len;
543        };
544        row_strings.push(elem_str);
545    }
546    if reduce_columns {
547        row_strings.push(ellipsis.to_string());
548        max_elem_lengths[n_first] = ellipsis.chars().count() + padding;
549    }
550    let elem_offset = n_first + reduce_columns as usize;
551    for (idx, v) in row[row.len() - n_last..].iter().enumerate() {
552        let elem_str = make_str_val(v, str_truncate, ellipsis);
553        let elem_len = estimate_string_width(elem_str.as_str()) + padding;
554        let elem_idx = elem_offset + idx;
555        if max_elem_lengths[elem_idx] < elem_len {
556            max_elem_lengths[elem_idx] = elem_len;
557        };
558        row_strings.push(elem_str);
559    }
560    row_strings
561}
562
563#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
564fn env_is_true(varname: &str) -> bool {
565    std::env::var(varname).as_deref().unwrap_or("0") == "1"
566}
567
568#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
569fn fmt_df_shape((shape0, shape1): &(usize, usize)) -> String {
570    // e.g. (1_000_000, 4_000)
571    format!(
572        "({}, {})",
573        fmt_int_string_custom(&shape0.to_string(), 3, "_"),
574        fmt_int_string_custom(&shape1.to_string(), 3, "_")
575    )
576}
577
578impl Display for DataFrame {
579    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
580        #[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
581        {
582            let height = self.height();
583            assert!(
584                self.columns.iter().all(|s| s.len() == height),
585                "The column lengths in the DataFrame are not equal."
586            );
587
588            let table_style = std::env::var(FMT_TABLE_FORMATTING).unwrap_or("DEFAULT".to_string());
589            let is_utf8 = !table_style.starts_with("ASCII");
590            let preset = match table_style.as_str() {
591                "ASCII_FULL" => ASCII_FULL,
592                "ASCII_FULL_CONDENSED" => ASCII_FULL_CONDENSED,
593                "ASCII_NO_BORDERS" => ASCII_NO_BORDERS,
594                "ASCII_BORDERS_ONLY" => ASCII_BORDERS_ONLY,
595                "ASCII_BORDERS_ONLY_CONDENSED" => ASCII_BORDERS_ONLY_CONDENSED,
596                "ASCII_HORIZONTAL_ONLY" => ASCII_HORIZONTAL_ONLY,
597                "ASCII_MARKDOWN" | "MARKDOWN" => ASCII_MARKDOWN,
598                "UTF8_FULL" => UTF8_FULL,
599                "UTF8_FULL_CONDENSED" => UTF8_FULL_CONDENSED,
600                "UTF8_NO_BORDERS" => UTF8_NO_BORDERS,
601                "UTF8_BORDERS_ONLY" => UTF8_BORDERS_ONLY,
602                "UTF8_HORIZONTAL_ONLY" => UTF8_HORIZONTAL_ONLY,
603                "NOTHING" => NOTHING,
604                _ => UTF8_FULL_CONDENSED,
605            };
606            let ellipsis = get_ellipsis().to_string();
607            let ellipsis_len = ellipsis.chars().count();
608            let max_n_cols = get_col_limit();
609            let max_n_rows = get_row_limit();
610            let str_truncate = get_str_len_limit();
611            let padding = 2; // eg: one char either side of the value
612
613            let (n_first, n_last) = if self.width() > max_n_cols {
614                (max_n_cols.div_ceil(2), max_n_cols / 2)
615            } else {
616                (self.width(), 0)
617            };
618            let reduce_columns = n_first + n_last < self.width();
619            let n_tbl_cols = n_first + n_last + reduce_columns as usize;
620            let mut names = Vec::with_capacity(n_tbl_cols);
621            let mut name_lengths = Vec::with_capacity(n_tbl_cols);
622
623            let fields = self.fields();
624            for field in fields[0..n_first].iter() {
625                let (s, l) = field_to_str(field, str_truncate, &ellipsis, padding);
626                names.push(s);
627                name_lengths.push(l);
628            }
629            if reduce_columns {
630                names.push(ellipsis.clone());
631                name_lengths.push(ellipsis_len);
632            }
633            for field in fields[self.width() - n_last..].iter() {
634                let (s, l) = field_to_str(field, str_truncate, &ellipsis, padding);
635                names.push(s);
636                name_lengths.push(l);
637            }
638
639            let mut table = Table::new();
640            table
641                .load_preset(preset)
642                .set_content_arrangement(ContentArrangement::Dynamic);
643
644            if is_utf8 && env_is_true(FMT_TABLE_ROUNDED_CORNERS) {
645                table.apply_modifier(UTF8_ROUND_CORNERS);
646            }
647            let mut constraints = Vec::with_capacity(n_tbl_cols);
648            let mut max_elem_lengths: Vec<usize> = vec![0; n_tbl_cols];
649
650            if max_n_rows > 0 {
651                if height > max_n_rows {
652                    // Truncate the table if we have more rows than the
653                    // configured maximum number of rows
654                    let mut rows = Vec::with_capacity(std::cmp::max(max_n_rows, 2));
655                    let half = max_n_rows / 2;
656                    let rest = max_n_rows % 2;
657
658                    for i in 0..(half + rest) {
659                        let row = self
660                            .get_columns()
661                            .iter()
662                            .map(|c| c.str_value(i).unwrap())
663                            .collect();
664
665                        let row_strings = prepare_row(
666                            row,
667                            n_first,
668                            n_last,
669                            str_truncate,
670                            &mut max_elem_lengths,
671                            &ellipsis,
672                            padding,
673                        );
674                        rows.push(row_strings);
675                    }
676                    let dots = vec![ellipsis.clone(); rows[0].len()];
677                    rows.push(dots);
678
679                    for i in (height - half)..height {
680                        let row = self
681                            .get_columns()
682                            .iter()
683                            .map(|c| c.str_value(i).unwrap())
684                            .collect();
685
686                        let row_strings = prepare_row(
687                            row,
688                            n_first,
689                            n_last,
690                            str_truncate,
691                            &mut max_elem_lengths,
692                            &ellipsis,
693                            padding,
694                        );
695                        rows.push(row_strings);
696                    }
697                    table.add_rows(rows);
698                } else {
699                    for i in 0..height {
700                        if self.width() > 0 {
701                            let row = self
702                                .materialized_column_iter()
703                                .map(|s| s.str_value(i).unwrap())
704                                .collect();
705
706                            let row_strings = prepare_row(
707                                row,
708                                n_first,
709                                n_last,
710                                str_truncate,
711                                &mut max_elem_lengths,
712                                &ellipsis,
713                                padding,
714                            );
715                            table.add_row(row_strings);
716                        } else {
717                            break;
718                        }
719                    }
720                }
721            } else if height > 0 {
722                let dots: Vec<String> = vec![ellipsis; self.columns.len()];
723                table.add_row(dots);
724            }
725            let tbl_fallback_width = 100;
726            let tbl_width = std::env::var("POLARS_TABLE_WIDTH")
727                .map(|s| {
728                    let n = s
729                        .parse::<i64>()
730                        .expect("could not parse table width argument");
731                    let w = if n < 0 {
732                        u16::MAX
733                    } else {
734                        u16::try_from(n).expect("table width argument does not fit in u16")
735                    };
736                    Some(w)
737                })
738                .unwrap_or(None);
739
740            // column width constraints
741            let col_width_exact =
742                |w: usize| ColumnConstraint::Absolute(comfy_table::Width::Fixed(w as u16));
743            let col_width_bounds = |l: usize, u: usize| ColumnConstraint::Boundaries {
744                lower: Width::Fixed(l as u16),
745                upper: Width::Fixed(u as u16),
746            };
747            let min_col_width = std::cmp::max(5, 3 + padding);
748            for (idx, elem_len) in max_elem_lengths.iter().enumerate() {
749                let mx = std::cmp::min(
750                    str_truncate + ellipsis_len + padding,
751                    std::cmp::max(name_lengths[idx], *elem_len),
752                );
753                if (mx <= min_col_width) && !(max_n_rows > 0 && height > max_n_rows) {
754                    // col width is less than min width + table is not truncated
755                    constraints.push(col_width_exact(mx));
756                } else if mx <= min_col_width {
757                    // col width is less than min width + table is truncated (w/ ellipsis)
758                    constraints.push(col_width_bounds(mx, min_col_width));
759                } else {
760                    constraints.push(col_width_bounds(min_col_width, mx));
761                }
762            }
763
764            // insert a header row, unless both column names and dtypes are hidden
765            if !(env_is_true(FMT_TABLE_HIDE_COLUMN_NAMES)
766                && env_is_true(FMT_TABLE_HIDE_COLUMN_DATA_TYPES))
767            {
768                table.set_header(names).set_constraints(constraints);
769            }
770
771            // if tbl_width is explicitly set, use it
772            if let Some(w) = tbl_width {
773                table.set_width(w);
774            } else {
775                // if no tbl_width (it's not tty && width not explicitly set), apply
776                // a default value; this is needed to support non-tty applications
777                #[cfg(feature = "fmt")]
778                if table.width().is_none() && !table.is_tty() {
779                    table.set_width(tbl_fallback_width);
780                }
781                #[cfg(feature = "fmt_no_tty")]
782                if table.width().is_none() {
783                    table.set_width(tbl_fallback_width);
784                }
785            }
786
787            // set alignment of cells, if defined
788            if std::env::var(FMT_TABLE_CELL_ALIGNMENT).is_ok()
789                | std::env::var(FMT_TABLE_CELL_NUMERIC_ALIGNMENT).is_ok()
790            {
791                let str_preset = std::env::var(FMT_TABLE_CELL_ALIGNMENT)
792                    .unwrap_or_else(|_| "DEFAULT".to_string());
793                let num_preset = std::env::var(FMT_TABLE_CELL_NUMERIC_ALIGNMENT)
794                    .unwrap_or_else(|_| str_preset.to_string());
795                for (column_index, column) in table.column_iter_mut().enumerate() {
796                    let dtype = fields[column_index].dtype();
797                    let mut preset = str_preset.as_str();
798                    if dtype.is_primitive_numeric() || dtype.is_decimal() {
799                        preset = num_preset.as_str();
800                    }
801                    match preset {
802                        "RIGHT" => column.set_cell_alignment(CellAlignment::Right),
803                        "LEFT" => column.set_cell_alignment(CellAlignment::Left),
804                        "CENTER" => column.set_cell_alignment(CellAlignment::Center),
805                        _ => {},
806                    }
807                }
808            }
809
810            // establish 'shape' information (above/below/hidden)
811            if env_is_true(FMT_TABLE_HIDE_DATAFRAME_SHAPE_INFORMATION) {
812                write!(f, "{table}")?;
813            } else {
814                let shape_str = fmt_df_shape(&self.shape());
815                if env_is_true(FMT_TABLE_DATAFRAME_SHAPE_BELOW) {
816                    write!(f, "{table}\nshape: {shape_str}")?;
817                } else {
818                    write!(f, "shape: {shape_str}\n{table}")?;
819                }
820            }
821        }
822        #[cfg(not(any(feature = "fmt", feature = "fmt_no_tty")))]
823        {
824            write!(
825                f,
826                "shape: {:?}\nto see more, compile with the 'fmt' or 'fmt_no_tty' feature",
827                self.shape()
828            )?;
829        }
830        Ok(())
831    }
832}
833
834fn fmt_int_string_custom(num: &str, group_size: u8, group_separator: &str) -> String {
835    if group_size == 0 || num.len() <= 1 {
836        num.to_string()
837    } else {
838        let mut out = String::new();
839        let sign_offset = if num.starts_with('-') || num.starts_with('+') {
840            out.push(num.chars().next().unwrap());
841            1
842        } else {
843            0
844        };
845        let int_body = &num.as_bytes()[sign_offset..]
846            .rchunks(group_size as usize)
847            .rev()
848            .map(str::from_utf8)
849            .collect::<Result<Vec<&str>, _>>()
850            .unwrap()
851            .join(group_separator);
852        out.push_str(int_body);
853        out
854    }
855}
856
857fn fmt_int_string(num: &str) -> String {
858    fmt_int_string_custom(num, 3, &get_thousands_separator())
859}
860
861fn fmt_float_string_custom(
862    num: &str,
863    group_size: u8,
864    group_separator: &str,
865    decimal: char,
866) -> String {
867    // Quick exit if no formatting would be applied
868    if num.len() <= 1 || (group_size == 0 && decimal == '.') {
869        num.to_string()
870    } else {
871        // Take existing numeric string and apply digit grouping & separator/decimal chars
872        // e.g. "1000000" → "1_000_000", "-123456.798" → "-123,456.789", etc
873        let (idx, has_fractional) = match num.find('.') {
874            Some(i) => (i, true),
875            None => (num.len(), false),
876        };
877        let mut out = String::new();
878        let integer_part = &num[..idx];
879
880        out.push_str(&fmt_int_string_custom(
881            integer_part,
882            group_size,
883            group_separator,
884        ));
885        if has_fractional {
886            out.push(decimal);
887            out.push_str(&num[idx + 1..]);
888        };
889        out
890    }
891}
892
893fn fmt_float_string(num: &str) -> String {
894    fmt_float_string_custom(num, 3, &get_thousands_separator(), get_decimal_separator())
895}
896
897fn fmt_integer<T: Num + NumCast + Display>(
898    f: &mut Formatter<'_>,
899    width: usize,
900    v: T,
901) -> fmt::Result {
902    write!(f, "{:>width$}", fmt_int_string(&v.to_string()))
903}
904
905const SCIENTIFIC_BOUND: f64 = 999999.0;
906
907fn fmt_float<T: Num + NumCast>(f: &mut Formatter<'_>, width: usize, v: T) -> fmt::Result {
908    let v: f64 = NumCast::from(v).unwrap();
909
910    let float_precision = get_float_precision();
911
912    if let Some(precision) = float_precision {
913        if format!("{v:.precision$}").len() > 19 {
914            return write!(f, "{v:>width$.precision$e}");
915        }
916        let s = format!("{v:>width$.precision$}");
917        return write!(f, "{}", fmt_float_string(s.as_str()));
918    }
919
920    if matches!(get_float_fmt(), FloatFmt::Full) {
921        let s = format!("{v:>width$}");
922        return write!(f, "{}", fmt_float_string(s.as_str()));
923    }
924
925    // show integers as 0.0, 1.0 ... 101.0
926    if v.fract() == 0.0 && v.abs() < SCIENTIFIC_BOUND {
927        let s = format!("{v:>width$.1}");
928        write!(f, "{}", fmt_float_string(s.as_str()))
929    } else if format!("{v}").len() > 9 {
930        // large and small floats in scientific notation.
931        // (note: scientific notation does not play well with digit grouping)
932        if (!(0.000001..=SCIENTIFIC_BOUND).contains(&v.abs()) | (v.abs() > SCIENTIFIC_BOUND))
933            && get_thousands_separator().is_empty()
934        {
935            let s = format!("{v:>width$.4e}");
936            write!(f, "{}", fmt_float_string(s.as_str()))
937        } else {
938            // this makes sure we don't write 12.00000 in case of a long flt that is 12.0000000001
939            // instead we write 12.0
940            let s = format!("{v:>width$.6}");
941
942            if s.ends_with('0') {
943                let mut s = s.as_str();
944                let mut len = s.len() - 1;
945
946                while s.ends_with('0') {
947                    s = &s[..len];
948                    len -= 1;
949                }
950                let s = if s.ends_with('.') {
951                    format!("{s}0")
952                } else {
953                    s.to_string()
954                };
955                write!(f, "{}", fmt_float_string(s.as_str()))
956            } else {
957                // 12.0934509341243124
958                // written as
959                // 12.09345
960                let s = format!("{v:>width$.6}");
961                write!(f, "{}", fmt_float_string(s.as_str()))
962            }
963        }
964    } else {
965        let s = if v.fract() == 0.0 {
966            format!("{v:>width$e}")
967        } else {
968            format!("{v:>width$}")
969        };
970        write!(f, "{}", fmt_float_string(s.as_str()))
971    }
972}
973
974#[cfg(feature = "dtype-datetime")]
975fn fmt_datetime(
976    f: &mut Formatter<'_>,
977    v: i64,
978    tu: TimeUnit,
979    tz: Option<&self::datatypes::TimeZone>,
980) -> fmt::Result {
981    let ndt = match tu {
982        TimeUnit::Nanoseconds => timestamp_ns_to_datetime(v),
983        TimeUnit::Microseconds => timestamp_us_to_datetime(v),
984        TimeUnit::Milliseconds => timestamp_ms_to_datetime(v),
985    };
986    match tz {
987        None => std::fmt::Display::fmt(&ndt, f),
988        Some(tz) => PlTzAware::new(ndt, tz).fmt(f),
989    }
990}
991
992#[cfg(feature = "dtype-duration")]
993const DURATION_PARTS: [&str; 4] = ["d", "h", "m", "s"];
994#[cfg(feature = "dtype-duration")]
995const ISO_DURATION_PARTS: [&str; 4] = ["D", "H", "M", "S"];
996#[cfg(feature = "dtype-duration")]
997const SIZES_NS: [i64; 4] = [
998    86_400_000_000_000, // per day
999    3_600_000_000_000,  // per hour
1000    60_000_000_000,     // per minute
1001    1_000_000_000,      // per second
1002];
1003#[cfg(feature = "dtype-duration")]
1004const SIZES_US: [i64; 4] = [86_400_000_000, 3_600_000_000, 60_000_000, 1_000_000];
1005#[cfg(feature = "dtype-duration")]
1006const SIZES_MS: [i64; 4] = [86_400_000, 3_600_000, 60_000, 1_000];
1007
1008#[cfg(feature = "dtype-duration")]
1009pub fn fmt_duration_string<W: Write>(f: &mut W, v: i64, unit: TimeUnit) -> fmt::Result {
1010    // take the physical/integer duration value and return a
1011    // friendly/readable duration string, eg: "3d 22m 55s 1ms"
1012    if v == 0 {
1013        return match unit {
1014            TimeUnit::Nanoseconds => f.write_str("0ns"),
1015            TimeUnit::Microseconds => f.write_str("0µs"),
1016            TimeUnit::Milliseconds => f.write_str("0ms"),
1017        };
1018    };
1019    // iterate over dtype-specific sizes to appropriately scale
1020    // and extract 'days', 'hours', 'minutes', and 'seconds' parts.
1021    let sizes = match unit {
1022        TimeUnit::Nanoseconds => SIZES_NS.as_slice(),
1023        TimeUnit::Microseconds => SIZES_US.as_slice(),
1024        TimeUnit::Milliseconds => SIZES_MS.as_slice(),
1025    };
1026    let mut buffer = itoa::Buffer::new();
1027    for (i, &size) in sizes.iter().enumerate() {
1028        let whole_num = if i == 0 {
1029            v / size
1030        } else {
1031            (v % sizes[i - 1]) / size
1032        };
1033        if whole_num != 0 {
1034            f.write_str(buffer.format(whole_num))?;
1035            f.write_str(DURATION_PARTS[i])?;
1036            if v % size != 0 {
1037                f.write_char(' ')?;
1038            }
1039        }
1040    }
1041    // write fractional seconds as integer nano/micro/milliseconds.
1042    let (v, units) = match unit {
1043        TimeUnit::Nanoseconds => (v % 1_000_000_000, ["ns", "µs", "ms"]),
1044        TimeUnit::Microseconds => (v % 1_000_000, ["µs", "ms", ""]),
1045        TimeUnit::Milliseconds => (v % 1_000, ["ms", "", ""]),
1046    };
1047    if v != 0 {
1048        let (value, suffix) = if v % 1_000 != 0 {
1049            (v, units[0])
1050        } else if v % 1_000_000 != 0 {
1051            (v / 1_000, units[1])
1052        } else {
1053            (v / 1_000_000, units[2])
1054        };
1055        f.write_str(buffer.format(value))?;
1056        f.write_str(suffix)?;
1057    }
1058    Ok(())
1059}
1060
1061#[cfg(feature = "dtype-duration")]
1062pub fn iso_duration_string(s: &mut String, mut v: i64, unit: TimeUnit) {
1063    if v == 0 {
1064        s.push_str("PT0S");
1065        return;
1066    }
1067    let mut buffer = itoa::Buffer::new();
1068    let mut wrote_part = false;
1069    if v < 0 {
1070        // negative sign before "P" indicates entire ISO duration is negative.
1071        s.push_str("-P");
1072        v = v.abs();
1073    } else {
1074        s.push('P');
1075    }
1076    // iterate over dtype-specific sizes to appropriately scale
1077    // and extract 'days', 'hours', 'minutes', and 'seconds' parts.
1078    let sizes = match unit {
1079        TimeUnit::Nanoseconds => SIZES_NS.as_slice(),
1080        TimeUnit::Microseconds => SIZES_US.as_slice(),
1081        TimeUnit::Milliseconds => SIZES_MS.as_slice(),
1082    };
1083    for (i, &size) in sizes.iter().enumerate() {
1084        let whole_num = if i == 0 {
1085            v / size
1086        } else {
1087            (v % sizes[i - 1]) / size
1088        };
1089        if whole_num != 0 || i == 3 {
1090            if i != 3 {
1091                // days, hours, minutes
1092                s.push_str(buffer.format(whole_num));
1093                s.push_str(ISO_DURATION_PARTS[i]);
1094            } else {
1095                // (index 3 => 'seconds' part): the ISO version writes
1096                // fractional seconds, not integer nano/micro/milliseconds.
1097                // if zero, only write out if no other parts written yet.
1098                let fractional_part = v % size;
1099                if whole_num == 0 && fractional_part == 0 {
1100                    if !wrote_part {
1101                        s.push_str("0S")
1102                    }
1103                } else {
1104                    s.push_str(buffer.format(whole_num));
1105                    if fractional_part != 0 {
1106                        let secs = match unit {
1107                            TimeUnit::Nanoseconds => format!(".{fractional_part:09}"),
1108                            TimeUnit::Microseconds => format!(".{fractional_part:06}"),
1109                            TimeUnit::Milliseconds => format!(".{fractional_part:03}"),
1110                        };
1111                        s.push_str(secs.trim_end_matches('0'));
1112                    }
1113                    s.push_str(ISO_DURATION_PARTS[i]);
1114                }
1115            }
1116            // (index 0 => 'days' part): after writing days above (if non-zero)
1117            // the ISO duration string requires a `T` before the time part.
1118            if i == 0 {
1119                s.push('T');
1120            }
1121            wrote_part = true;
1122        } else if i == 0 {
1123            // always need to write the `T` separator for ISO
1124            // durations, even if there is no 'days' part.
1125            s.push('T');
1126        }
1127    }
1128    // if there was only a 'days' component, no need for time separator.
1129    if s.ends_with('T') {
1130        s.pop();
1131    }
1132}
1133
1134fn format_blob(f: &mut Formatter<'_>, bytes: &[u8]) -> fmt::Result {
1135    let ellipsis = get_ellipsis();
1136    let width = get_str_len_limit() * 2;
1137    write!(f, "b\"")?;
1138
1139    for b in bytes.iter().take(width) {
1140        if b.is_ascii_alphanumeric() || b.is_ascii_punctuation() {
1141            write!(f, "{}", *b as char)?;
1142        } else {
1143            write!(f, "\\x{b:02x}")?;
1144        }
1145    }
1146    if bytes.len() > width {
1147        write!(f, "\"{ellipsis}")?;
1148    } else {
1149        f.write_str("\"")?;
1150    }
1151    Ok(())
1152}
1153
1154impl Display for AnyValue<'_> {
1155    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1156        let width = 0;
1157        match self {
1158            AnyValue::Null => write!(f, "null"),
1159            AnyValue::UInt8(v) => fmt_integer(f, width, *v),
1160            AnyValue::UInt16(v) => fmt_integer(f, width, *v),
1161            AnyValue::UInt32(v) => fmt_integer(f, width, *v),
1162            AnyValue::UInt64(v) => fmt_integer(f, width, *v),
1163            AnyValue::UInt128(v) => feature_gated!("dtype-u128", fmt_integer(f, width, *v)),
1164            AnyValue::Int8(v) => fmt_integer(f, width, *v),
1165            AnyValue::Int16(v) => fmt_integer(f, width, *v),
1166            AnyValue::Int32(v) => fmt_integer(f, width, *v),
1167            AnyValue::Int64(v) => fmt_integer(f, width, *v),
1168            AnyValue::Int128(v) => feature_gated!("dtype-i128", fmt_integer(f, width, *v)),
1169            AnyValue::Float32(v) => fmt_float(f, width, *v),
1170            AnyValue::Float64(v) => fmt_float(f, width, *v),
1171            AnyValue::Boolean(v) => write!(f, "{}", *v),
1172            AnyValue::String(v) => write!(f, "{}", format_args!("\"{v}\"")),
1173            AnyValue::StringOwned(v) => write!(f, "{}", format_args!("\"{v}\"")),
1174            AnyValue::Binary(d) => format_blob(f, d),
1175            AnyValue::BinaryOwned(d) => format_blob(f, d),
1176            #[cfg(feature = "dtype-date")]
1177            AnyValue::Date(v) => write!(f, "{}", date32_to_date(*v)),
1178            #[cfg(feature = "dtype-datetime")]
1179            AnyValue::Datetime(v, tu, tz) => fmt_datetime(f, *v, *tu, *tz),
1180            #[cfg(feature = "dtype-datetime")]
1181            AnyValue::DatetimeOwned(v, tu, tz) => {
1182                fmt_datetime(f, *v, *tu, tz.as_ref().map(|v| v.as_ref()))
1183            },
1184            #[cfg(feature = "dtype-duration")]
1185            AnyValue::Duration(v, tu) => fmt_duration_string(f, *v, *tu),
1186            #[cfg(feature = "dtype-time")]
1187            AnyValue::Time(_) => {
1188                let nt: chrono::NaiveTime = self.into();
1189                write!(f, "{nt}")
1190            },
1191            #[cfg(feature = "dtype-categorical")]
1192            AnyValue::Categorical(_, _)
1193            | AnyValue::CategoricalOwned(_, _)
1194            | AnyValue::Enum(_, _)
1195            | AnyValue::EnumOwned(_, _) => {
1196                let s = self.get_str().unwrap();
1197                write!(f, "\"{s}\"")
1198            },
1199            #[cfg(feature = "dtype-array")]
1200            AnyValue::Array(s, _size) => write!(f, "{}", s.fmt_list()),
1201            AnyValue::List(s) => write!(f, "{}", s.fmt_list()),
1202            #[cfg(feature = "object")]
1203            AnyValue::Object(v) => write!(f, "{v}"),
1204            #[cfg(feature = "object")]
1205            AnyValue::ObjectOwned(v) => write!(f, "{}", v.0.as_ref()),
1206            #[cfg(feature = "dtype-struct")]
1207            av @ AnyValue::Struct(_, _, _) => {
1208                let mut avs = vec![];
1209                av._materialize_struct_av(&mut avs);
1210                fmt_struct(f, &avs)
1211            },
1212            #[cfg(feature = "dtype-struct")]
1213            AnyValue::StructOwned(payload) => fmt_struct(f, &payload.0),
1214            #[cfg(feature = "dtype-decimal")]
1215            AnyValue::Decimal(v, _prec, scale) => fmt_decimal(f, *v, *scale),
1216        }
1217    }
1218}
1219
1220/// Utility struct to format a timezone aware datetime.
1221#[allow(dead_code)]
1222#[cfg(feature = "dtype-datetime")]
1223pub struct PlTzAware<'a> {
1224    ndt: NaiveDateTime,
1225    tz: &'a str,
1226}
1227#[cfg(feature = "dtype-datetime")]
1228impl<'a> PlTzAware<'a> {
1229    pub fn new(ndt: NaiveDateTime, tz: &'a str) -> Self {
1230        Self { ndt, tz }
1231    }
1232}
1233
1234#[cfg(feature = "dtype-datetime")]
1235impl Display for PlTzAware<'_> {
1236    #[allow(unused_variables)]
1237    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1238        #[cfg(feature = "timezones")]
1239        match self.tz.parse::<chrono_tz::Tz>() {
1240            Ok(tz) => {
1241                let dt_utc = chrono::Utc.from_local_datetime(&self.ndt).unwrap();
1242                let dt_tz_aware = dt_utc.with_timezone(&tz);
1243                write!(f, "{dt_tz_aware}")
1244            },
1245            Err(_) => write!(f, "invalid timezone"),
1246        }
1247        #[cfg(not(feature = "timezones"))]
1248        {
1249            panic!("activate 'timezones' feature")
1250        }
1251    }
1252}
1253
1254#[cfg(feature = "dtype-struct")]
1255fn fmt_struct(f: &mut Formatter<'_>, vals: &[AnyValue]) -> fmt::Result {
1256    write!(f, "{{")?;
1257    if !vals.is_empty() {
1258        for v in &vals[..vals.len() - 1] {
1259            write!(f, "{v},")?;
1260        }
1261        // last value has no trailing comma
1262        write!(f, "{}", vals[vals.len() - 1])?;
1263    }
1264    write!(f, "}}")
1265}
1266
1267impl Series {
1268    pub fn fmt_list(&self) -> String {
1269        assert!(
1270            !self.dtype().is_object(),
1271            "nested Objects are not allowed\n\nYou probably got here by not setting a `return_dtype` on a UDF on Objects."
1272        );
1273        if self.is_empty() {
1274            return "[]".to_owned();
1275        }
1276        let mut result = "[".to_owned();
1277        let max_items = get_list_len_limit();
1278        let ellipsis = get_ellipsis();
1279
1280        match max_items {
1281            0 => write!(result, "{ellipsis}]").unwrap(),
1282            _ if max_items >= self.len() => {
1283                // this will always leave a trailing ", " after the last item
1284                // but for long lists, this is faster than checking against the length each time
1285                for item in self.rechunk().iter() {
1286                    write!(result, "{item}, ").unwrap();
1287                }
1288                // remove trailing ", " and replace with closing brace
1289                result.truncate(result.len() - 2);
1290                result.push(']');
1291            },
1292            _ => {
1293                let s = self.slice(0, max_items).rechunk();
1294                for (i, item) in s.iter().enumerate() {
1295                    if i == max_items.saturating_sub(1) {
1296                        write!(result, "{ellipsis} {}", self.get(self.len() - 1).unwrap()).unwrap();
1297                        break;
1298                    } else {
1299                        write!(result, "{item}, ").unwrap();
1300                    }
1301                }
1302                result.push(']');
1303            },
1304        };
1305        result
1306    }
1307}
1308
1309#[inline]
1310#[cfg(feature = "dtype-decimal")]
1311fn fmt_decimal(f: &mut Formatter<'_>, v: i128, scale: usize) -> fmt::Result {
1312    let mut fmt_buf = polars_compute::decimal::DecimalFmtBuffer::new();
1313    let trim_zeros = get_trim_decimal_zeros();
1314    f.write_str(fmt_float_string(fmt_buf.format_dec128(v, scale, trim_zeros)).as_str())
1315}
1316
1317#[cfg(all(
1318    test,
1319    feature = "temporal",
1320    feature = "dtype-date",
1321    feature = "dtype-datetime"
1322))]
1323#[allow(unsafe_op_in_unsafe_fn)]
1324mod test {
1325    use crate::prelude::*;
1326
1327    #[test]
1328    fn test_fmt_list() {
1329        let mut builder = ListPrimitiveChunkedBuilder::<Int32Type>::new(
1330            PlSmallStr::from_static("a"),
1331            10,
1332            10,
1333            DataType::Int32,
1334        );
1335        builder.append_opt_slice(Some(&[1, 2, 3, 4, 5, 6]));
1336        builder.append_opt_slice(None);
1337        let list_long = builder.finish().into_series();
1338
1339        assert_eq!(
1340            r#"shape: (2,)
1341Series: 'a' [list[i32]]
1342[
1343	[1, 2, … 6]
1344	null
1345]"#,
1346            format!("{list_long:?}")
1347        );
1348
1349        unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "10") };
1350
1351        assert_eq!(
1352            r#"shape: (2,)
1353Series: 'a' [list[i32]]
1354[
1355	[1, 2, 3, 4, 5, 6]
1356	null
1357]"#,
1358            format!("{list_long:?}")
1359        );
1360
1361        unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "-1") };
1362
1363        assert_eq!(
1364            r#"shape: (2,)
1365Series: 'a' [list[i32]]
1366[
1367	[1, 2, 3, 4, 5, 6]
1368	null
1369]"#,
1370            format!("{list_long:?}")
1371        );
1372
1373        unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "0") };
1374
1375        assert_eq!(
1376            r#"shape: (2,)
1377Series: 'a' [list[i32]]
1378[
1379	[…]
1380	null
1381]"#,
1382            format!("{list_long:?}")
1383        );
1384
1385        unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "1") };
1386
1387        assert_eq!(
1388            r#"shape: (2,)
1389Series: 'a' [list[i32]]
1390[
1391	[… 6]
1392	null
1393]"#,
1394            format!("{list_long:?}")
1395        );
1396
1397        unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "4") };
1398
1399        assert_eq!(
1400            r#"shape: (2,)
1401Series: 'a' [list[i32]]
1402[
1403	[1, 2, 3, … 6]
1404	null
1405]"#,
1406            format!("{list_long:?}")
1407        );
1408
1409        let mut builder = ListPrimitiveChunkedBuilder::<Int32Type>::new(
1410            PlSmallStr::from_static("a"),
1411            10,
1412            10,
1413            DataType::Int32,
1414        );
1415        builder.append_opt_slice(Some(&[1]));
1416        builder.append_opt_slice(None);
1417        let list_short = builder.finish().into_series();
1418
1419        unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "") };
1420
1421        assert_eq!(
1422            r#"shape: (2,)
1423Series: 'a' [list[i32]]
1424[
1425	[1]
1426	null
1427]"#,
1428            format!("{list_short:?}")
1429        );
1430
1431        unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "0") };
1432
1433        assert_eq!(
1434            r#"shape: (2,)
1435Series: 'a' [list[i32]]
1436[
1437	[…]
1438	null
1439]"#,
1440            format!("{list_short:?}")
1441        );
1442
1443        unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "-1") };
1444
1445        assert_eq!(
1446            r#"shape: (2,)
1447Series: 'a' [list[i32]]
1448[
1449	[1]
1450	null
1451]"#,
1452            format!("{list_short:?}")
1453        );
1454
1455        let mut builder = ListPrimitiveChunkedBuilder::<Int32Type>::new(
1456            PlSmallStr::from_static("a"),
1457            10,
1458            10,
1459            DataType::Int32,
1460        );
1461        builder.append_opt_slice(Some(&[]));
1462        builder.append_opt_slice(None);
1463        let list_empty = builder.finish().into_series();
1464
1465        unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "") };
1466
1467        assert_eq!(
1468            r#"shape: (2,)
1469Series: 'a' [list[i32]]
1470[
1471	[]
1472	null
1473]"#,
1474            format!("{list_empty:?}")
1475        );
1476    }
1477
1478    #[test]
1479    fn test_fmt_temporal() {
1480        let s = Int32Chunked::new(PlSmallStr::from_static("Date"), &[Some(1), None, Some(3)])
1481            .into_date();
1482        assert_eq!(
1483            r#"shape: (3,)
1484Series: 'Date' [date]
1485[
1486	1970-01-02
1487	null
1488	1970-01-04
1489]"#,
1490            format!("{:?}", s.into_series())
1491        );
1492
1493        let s = Int64Chunked::new(PlSmallStr::EMPTY, &[Some(1), None, Some(1_000_000_000_000)])
1494            .into_datetime(TimeUnit::Nanoseconds, None);
1495        assert_eq!(
1496            r#"shape: (3,)
1497Series: '' [datetime[ns]]
1498[
1499	1970-01-01 00:00:00.000000001
1500	null
1501	1970-01-01 00:16:40
1502]"#,
1503            format!("{:?}", s.into_series())
1504        );
1505    }
1506
1507    #[test]
1508    fn test_fmt_chunkedarray() {
1509        let ca = Int32Chunked::new(PlSmallStr::from_static("Date"), &[Some(1), None, Some(3)]);
1510        assert_eq!(
1511            r#"shape: (3,)
1512ChunkedArray: 'Date' [i32]
1513[
1514	1
1515	null
1516	3
1517]"#,
1518            format!("{ca:?}")
1519        );
1520        let ca = StringChunked::new(PlSmallStr::from_static("name"), &["a", "b"]);
1521        assert_eq!(
1522            r#"shape: (2,)
1523ChunkedArray: 'name' [str]
1524[
1525	"a"
1526	"b"
1527]"#,
1528            format!("{ca:?}")
1529        );
1530    }
1531}