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
32const 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
52pub 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
79pub 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
97fn parse_env_var<T: FromStr>(name: &str) -> Option<T> {
99 std::env::var(name).ok().and_then(|v| v.parse().ok())
100}
101fn 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 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().to_storage() {
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 #[cfg(feature = "dtype-extension")]
447 DataType::Extension(_, _) => {
448 let dt = format!("{}", self.dtype());
449 format_array!(f, self.ext().unwrap(), &dt, self.name(), "Series")
450 },
451 dt => panic!("{dt:?} not impl"),
452 }
453 }
454}
455
456impl Display for Series {
457 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
458 Debug::fmt(self, f)
459 }
460}
461
462impl Debug for DataFrame {
463 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
464 Display::fmt(self, f)
465 }
466}
467#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
468fn make_str_val(v: &str, truncate: usize, ellipsis: &String) -> String {
469 let v_trunc = &v[..v
470 .char_indices()
471 .take(truncate)
472 .last()
473 .map(|(i, c)| i + c.len_utf8())
474 .unwrap_or(0)];
475 if v == v_trunc {
476 v.to_string()
477 } else {
478 format!("{v_trunc}{ellipsis}")
479 }
480}
481
482#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
483fn field_to_str(
484 f: &Field,
485 str_truncate: usize,
486 ellipsis: &String,
487 padding: usize,
488) -> (String, usize) {
489 let name = make_str_val(f.name(), str_truncate, ellipsis);
490 let name_length = estimate_string_width(name.as_str());
491 let mut column_name = name;
492 if env_is_true(FMT_TABLE_HIDE_COLUMN_NAMES) {
493 column_name = "".to_string();
494 }
495 let column_dtype = if env_is_true(FMT_TABLE_HIDE_COLUMN_DATA_TYPES) {
496 "".to_string()
497 } else if env_is_true(FMT_TABLE_INLINE_COLUMN_DATA_TYPE)
498 | env_is_true(FMT_TABLE_HIDE_COLUMN_NAMES)
499 {
500 format!("{}", f.dtype())
501 } else {
502 format!("\n{}", f.dtype())
503 };
504 let mut dtype_length = column_dtype.trim_start().len();
505 let mut separator = "\n---";
506 if env_is_true(FMT_TABLE_HIDE_COLUMN_SEPARATOR)
507 | env_is_true(FMT_TABLE_HIDE_COLUMN_NAMES)
508 | env_is_true(FMT_TABLE_HIDE_COLUMN_DATA_TYPES)
509 {
510 separator = ""
511 }
512 let s = if env_is_true(FMT_TABLE_INLINE_COLUMN_DATA_TYPE)
513 & !env_is_true(FMT_TABLE_HIDE_COLUMN_DATA_TYPES)
514 {
515 let inline_name_dtype = format!("{column_name} ({column_dtype})");
516 dtype_length = inline_name_dtype.len();
517 inline_name_dtype
518 } else {
519 format!("{column_name}{separator}{column_dtype}")
520 };
521 let mut s_len = std::cmp::max(name_length, dtype_length);
522 let separator_length = estimate_string_width(separator.trim());
523 if s_len < separator_length {
524 s_len = separator_length;
525 }
526 (s, s_len + padding)
527}
528
529#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
530fn prepare_row(
531 row: Vec<Cow<'_, str>>,
532 n_first: usize,
533 n_last: usize,
534 str_truncate: usize,
535 max_elem_lengths: &mut [usize],
536 ellipsis: &String,
537 padding: usize,
538) -> Vec<String> {
539 let reduce_columns = n_first + n_last < row.len();
540 let n_elems = n_first + n_last + reduce_columns as usize;
541 let mut row_strings = Vec::with_capacity(n_elems);
542
543 for (idx, v) in row[0..n_first].iter().enumerate() {
544 let elem_str = make_str_val(v, str_truncate, ellipsis);
545 let elem_len = estimate_string_width(elem_str.as_str()) + padding;
546 if max_elem_lengths[idx] < elem_len {
547 max_elem_lengths[idx] = elem_len;
548 };
549 row_strings.push(elem_str);
550 }
551 if reduce_columns {
552 row_strings.push(ellipsis.to_string());
553 max_elem_lengths[n_first] = ellipsis.chars().count() + padding;
554 }
555 let elem_offset = n_first + reduce_columns as usize;
556 for (idx, v) in row[row.len() - n_last..].iter().enumerate() {
557 let elem_str = make_str_val(v, str_truncate, ellipsis);
558 let elem_len = estimate_string_width(elem_str.as_str()) + padding;
559 let elem_idx = elem_offset + idx;
560 if max_elem_lengths[elem_idx] < elem_len {
561 max_elem_lengths[elem_idx] = elem_len;
562 };
563 row_strings.push(elem_str);
564 }
565 row_strings
566}
567
568#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
569fn env_is_true(varname: &str) -> bool {
570 std::env::var(varname).as_deref().unwrap_or("0") == "1"
571}
572
573#[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
574fn fmt_df_shape((shape0, shape1): &(usize, usize)) -> String {
575 format!(
577 "({}, {})",
578 fmt_int_string_custom(&shape0.to_string(), 3, "_"),
579 fmt_int_string_custom(&shape1.to_string(), 3, "_")
580 )
581}
582
583impl Display for DataFrame {
584 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
585 #[cfg(any(feature = "fmt", feature = "fmt_no_tty"))]
586 {
587 let height = self.height();
588 assert!(
589 self.columns.iter().all(|s| s.len() == height),
590 "The column lengths in the DataFrame are not equal."
591 );
592
593 let table_style = std::env::var(FMT_TABLE_FORMATTING).unwrap_or("DEFAULT".to_string());
594 let is_utf8 = !table_style.starts_with("ASCII");
595 let preset = match table_style.as_str() {
596 "ASCII_FULL" => ASCII_FULL,
597 "ASCII_FULL_CONDENSED" => ASCII_FULL_CONDENSED,
598 "ASCII_NO_BORDERS" => ASCII_NO_BORDERS,
599 "ASCII_BORDERS_ONLY" => ASCII_BORDERS_ONLY,
600 "ASCII_BORDERS_ONLY_CONDENSED" => ASCII_BORDERS_ONLY_CONDENSED,
601 "ASCII_HORIZONTAL_ONLY" => ASCII_HORIZONTAL_ONLY,
602 "ASCII_MARKDOWN" | "MARKDOWN" => ASCII_MARKDOWN,
603 "UTF8_FULL" => UTF8_FULL,
604 "UTF8_FULL_CONDENSED" => UTF8_FULL_CONDENSED,
605 "UTF8_NO_BORDERS" => UTF8_NO_BORDERS,
606 "UTF8_BORDERS_ONLY" => UTF8_BORDERS_ONLY,
607 "UTF8_HORIZONTAL_ONLY" => UTF8_HORIZONTAL_ONLY,
608 "NOTHING" => NOTHING,
609 _ => UTF8_FULL_CONDENSED,
610 };
611 let ellipsis = get_ellipsis().to_string();
612 let ellipsis_len = ellipsis.chars().count();
613 let max_n_cols = get_col_limit();
614 let max_n_rows = get_row_limit();
615 let str_truncate = get_str_len_limit();
616 let padding = 2; let (n_first, n_last) = if self.width() > max_n_cols {
619 (max_n_cols.div_ceil(2), max_n_cols / 2)
620 } else {
621 (self.width(), 0)
622 };
623 let reduce_columns = n_first + n_last < self.width();
624 let n_tbl_cols = n_first + n_last + reduce_columns as usize;
625 let mut names = Vec::with_capacity(n_tbl_cols);
626 let mut name_lengths = Vec::with_capacity(n_tbl_cols);
627
628 let fields = self.fields();
629 for field in fields[0..n_first].iter() {
630 let (s, l) = field_to_str(field, str_truncate, &ellipsis, padding);
631 names.push(s);
632 name_lengths.push(l);
633 }
634 if reduce_columns {
635 names.push(ellipsis.clone());
636 name_lengths.push(ellipsis_len);
637 }
638 for field in fields[self.width() - n_last..].iter() {
639 let (s, l) = field_to_str(field, str_truncate, &ellipsis, padding);
640 names.push(s);
641 name_lengths.push(l);
642 }
643
644 let mut table = Table::new();
645 table
646 .load_preset(preset)
647 .set_content_arrangement(ContentArrangement::Dynamic);
648
649 if is_utf8 && env_is_true(FMT_TABLE_ROUNDED_CORNERS) {
650 table.apply_modifier(UTF8_ROUND_CORNERS);
651 }
652 let mut constraints = Vec::with_capacity(n_tbl_cols);
653 let mut max_elem_lengths: Vec<usize> = vec![0; n_tbl_cols];
654
655 if max_n_rows > 0 {
656 if height > max_n_rows {
657 let mut rows = Vec::with_capacity(std::cmp::max(max_n_rows, 2));
660 let half = max_n_rows / 2;
661 let rest = max_n_rows % 2;
662
663 for i in 0..(half + rest) {
664 let row = self
665 .get_columns()
666 .iter()
667 .map(|c| c.str_value(i).unwrap())
668 .collect();
669
670 let row_strings = prepare_row(
671 row,
672 n_first,
673 n_last,
674 str_truncate,
675 &mut max_elem_lengths,
676 &ellipsis,
677 padding,
678 );
679 rows.push(row_strings);
680 }
681 let dots = vec![ellipsis.clone(); rows[0].len()];
682 rows.push(dots);
683
684 for i in (height - half)..height {
685 let row = self
686 .get_columns()
687 .iter()
688 .map(|c| c.str_value(i).unwrap())
689 .collect();
690
691 let row_strings = prepare_row(
692 row,
693 n_first,
694 n_last,
695 str_truncate,
696 &mut max_elem_lengths,
697 &ellipsis,
698 padding,
699 );
700 rows.push(row_strings);
701 }
702 table.add_rows(rows);
703 } else {
704 for i in 0..height {
705 if self.width() > 0 {
706 let row = self
707 .materialized_column_iter()
708 .map(|s| s.str_value(i).unwrap())
709 .collect();
710
711 let row_strings = prepare_row(
712 row,
713 n_first,
714 n_last,
715 str_truncate,
716 &mut max_elem_lengths,
717 &ellipsis,
718 padding,
719 );
720 table.add_row(row_strings);
721 } else {
722 break;
723 }
724 }
725 }
726 } else if height > 0 {
727 let dots: Vec<String> = vec![ellipsis; self.columns.len()];
728 table.add_row(dots);
729 }
730 let tbl_fallback_width = 100;
731 let tbl_width = std::env::var("POLARS_TABLE_WIDTH")
732 .map(|s| {
733 let n = s
734 .parse::<i64>()
735 .expect("could not parse table width argument");
736 let w = if n < 0 {
737 u16::MAX
738 } else {
739 u16::try_from(n).expect("table width argument does not fit in u16")
740 };
741 Some(w)
742 })
743 .unwrap_or(None);
744
745 let col_width_exact =
747 |w: usize| ColumnConstraint::Absolute(comfy_table::Width::Fixed(w as u16));
748 let col_width_bounds = |l: usize, u: usize| ColumnConstraint::Boundaries {
749 lower: Width::Fixed(l as u16),
750 upper: Width::Fixed(u as u16),
751 };
752 let min_col_width = std::cmp::max(5, 3 + padding);
753 for (idx, elem_len) in max_elem_lengths.iter().enumerate() {
754 let mx = std::cmp::min(
755 str_truncate + ellipsis_len + padding,
756 std::cmp::max(name_lengths[idx], *elem_len),
757 );
758 if (mx <= min_col_width) && !(max_n_rows > 0 && height > max_n_rows) {
759 constraints.push(col_width_exact(mx));
761 } else if mx <= min_col_width {
762 constraints.push(col_width_bounds(mx, min_col_width));
764 } else {
765 constraints.push(col_width_bounds(min_col_width, mx));
766 }
767 }
768
769 if !(env_is_true(FMT_TABLE_HIDE_COLUMN_NAMES)
771 && env_is_true(FMT_TABLE_HIDE_COLUMN_DATA_TYPES))
772 {
773 table.set_header(names).set_constraints(constraints);
774 }
775
776 if let Some(w) = tbl_width {
778 table.set_width(w);
779 } else {
780 #[cfg(feature = "fmt")]
783 if table.width().is_none() && !table.is_tty() {
784 table.set_width(tbl_fallback_width);
785 }
786 #[cfg(feature = "fmt_no_tty")]
787 if table.width().is_none() {
788 table.set_width(tbl_fallback_width);
789 }
790 }
791
792 if std::env::var(FMT_TABLE_CELL_ALIGNMENT).is_ok()
794 | std::env::var(FMT_TABLE_CELL_NUMERIC_ALIGNMENT).is_ok()
795 {
796 let str_preset = std::env::var(FMT_TABLE_CELL_ALIGNMENT)
797 .unwrap_or_else(|_| "DEFAULT".to_string());
798 let num_preset = std::env::var(FMT_TABLE_CELL_NUMERIC_ALIGNMENT)
799 .unwrap_or_else(|_| str_preset.to_string());
800 for (column_index, column) in table.column_iter_mut().enumerate() {
801 let dtype = fields[column_index].dtype();
802 let mut preset = str_preset.as_str();
803 if dtype.is_primitive_numeric() || dtype.is_decimal() {
804 preset = num_preset.as_str();
805 }
806 match preset {
807 "RIGHT" => column.set_cell_alignment(CellAlignment::Right),
808 "LEFT" => column.set_cell_alignment(CellAlignment::Left),
809 "CENTER" => column.set_cell_alignment(CellAlignment::Center),
810 _ => {},
811 }
812 }
813 }
814
815 if env_is_true(FMT_TABLE_HIDE_DATAFRAME_SHAPE_INFORMATION) {
817 write!(f, "{table}")?;
818 } else {
819 let shape_str = fmt_df_shape(&self.shape());
820 if env_is_true(FMT_TABLE_DATAFRAME_SHAPE_BELOW) {
821 write!(f, "{table}\nshape: {shape_str}")?;
822 } else {
823 write!(f, "shape: {shape_str}\n{table}")?;
824 }
825 }
826 }
827 #[cfg(not(any(feature = "fmt", feature = "fmt_no_tty")))]
828 {
829 write!(
830 f,
831 "shape: {:?}\nto see more, compile with the 'fmt' or 'fmt_no_tty' feature",
832 self.shape()
833 )?;
834 }
835 Ok(())
836 }
837}
838
839fn fmt_int_string_custom(num: &str, group_size: u8, group_separator: &str) -> String {
840 if group_size == 0 || num.len() <= 1 {
841 num.to_string()
842 } else {
843 let mut out = String::new();
844 let sign_offset = if num.starts_with('-') || num.starts_with('+') {
845 out.push(num.chars().next().unwrap());
846 1
847 } else {
848 0
849 };
850 let int_body = &num.as_bytes()[sign_offset..]
851 .rchunks(group_size as usize)
852 .rev()
853 .map(str::from_utf8)
854 .collect::<Result<Vec<&str>, _>>()
855 .unwrap()
856 .join(group_separator);
857 out.push_str(int_body);
858 out
859 }
860}
861
862fn fmt_int_string(num: &str) -> String {
863 fmt_int_string_custom(num, 3, &get_thousands_separator())
864}
865
866fn fmt_float_string_custom(
867 num: &str,
868 group_size: u8,
869 group_separator: &str,
870 decimal: char,
871) -> String {
872 if num.len() <= 1 || (group_size == 0 && decimal == '.') {
874 num.to_string()
875 } else {
876 let (idx, has_fractional) = match num.find('.') {
879 Some(i) => (i, true),
880 None => (num.len(), false),
881 };
882 let mut out = String::new();
883 let integer_part = &num[..idx];
884
885 out.push_str(&fmt_int_string_custom(
886 integer_part,
887 group_size,
888 group_separator,
889 ));
890 if has_fractional {
891 out.push(decimal);
892 out.push_str(&num[idx + 1..]);
893 };
894 out
895 }
896}
897
898fn fmt_float_string(num: &str) -> String {
899 fmt_float_string_custom(num, 3, &get_thousands_separator(), get_decimal_separator())
900}
901
902fn fmt_integer<T: Num + NumCast + Display>(
903 f: &mut Formatter<'_>,
904 width: usize,
905 v: T,
906) -> fmt::Result {
907 write!(f, "{:>width$}", fmt_int_string(&v.to_string()))
908}
909
910const SCIENTIFIC_BOUND: f64 = 999999.0;
911
912fn fmt_float<T: Num + NumCast>(f: &mut Formatter<'_>, width: usize, v: T) -> fmt::Result {
913 let v: f64 = NumCast::from(v).unwrap();
914
915 let float_precision = get_float_precision();
916
917 if let Some(precision) = float_precision {
918 if format!("{v:.precision$}").len() > 19 {
919 return write!(f, "{v:>width$.precision$e}");
920 }
921 let s = format!("{v:>width$.precision$}");
922 return write!(f, "{}", fmt_float_string(s.as_str()));
923 }
924
925 if matches!(get_float_fmt(), FloatFmt::Full) {
926 let s = format!("{v:>width$}");
927 return write!(f, "{}", fmt_float_string(s.as_str()));
928 }
929
930 if v.fract() == 0.0 && v.abs() < SCIENTIFIC_BOUND {
932 let s = format!("{v:>width$.1}");
933 write!(f, "{}", fmt_float_string(s.as_str()))
934 } else if format!("{v}").len() > 9 {
935 if (!(0.000001..=SCIENTIFIC_BOUND).contains(&v.abs()) | (v.abs() > SCIENTIFIC_BOUND))
938 && get_thousands_separator().is_empty()
939 {
940 let s = format!("{v:>width$.4e}");
941 write!(f, "{}", fmt_float_string(s.as_str()))
942 } else {
943 let s = format!("{v:>width$.6}");
946
947 if s.ends_with('0') {
948 let mut s = s.as_str();
949 let mut len = s.len() - 1;
950
951 while s.ends_with('0') {
952 s = &s[..len];
953 len -= 1;
954 }
955 let s = if s.ends_with('.') {
956 format!("{s}0")
957 } else {
958 s.to_string()
959 };
960 write!(f, "{}", fmt_float_string(s.as_str()))
961 } else {
962 let s = format!("{v:>width$.6}");
966 write!(f, "{}", fmt_float_string(s.as_str()))
967 }
968 }
969 } else {
970 let s = if v.fract() == 0.0 {
971 format!("{v:>width$e}")
972 } else {
973 format!("{v:>width$}")
974 };
975 write!(f, "{}", fmt_float_string(s.as_str()))
976 }
977}
978
979#[cfg(feature = "dtype-datetime")]
980fn fmt_datetime(
981 f: &mut Formatter<'_>,
982 v: i64,
983 tu: TimeUnit,
984 tz: Option<&self::datatypes::TimeZone>,
985) -> fmt::Result {
986 let ndt = match tu {
987 TimeUnit::Nanoseconds => timestamp_ns_to_datetime(v),
988 TimeUnit::Microseconds => timestamp_us_to_datetime(v),
989 TimeUnit::Milliseconds => timestamp_ms_to_datetime(v),
990 };
991 match tz {
992 None => std::fmt::Display::fmt(&ndt, f),
993 Some(tz) => PlTzAware::new(ndt, tz).fmt(f),
994 }
995}
996
997#[cfg(feature = "dtype-duration")]
998const DURATION_PARTS: [&str; 4] = ["d", "h", "m", "s"];
999#[cfg(feature = "dtype-duration")]
1000const ISO_DURATION_PARTS: [&str; 4] = ["D", "H", "M", "S"];
1001#[cfg(feature = "dtype-duration")]
1002const SIZES_NS: [i64; 4] = [
1003 86_400_000_000_000, 3_600_000_000_000, 60_000_000_000, 1_000_000_000, ];
1008#[cfg(feature = "dtype-duration")]
1009const SIZES_US: [i64; 4] = [86_400_000_000, 3_600_000_000, 60_000_000, 1_000_000];
1010#[cfg(feature = "dtype-duration")]
1011const SIZES_MS: [i64; 4] = [86_400_000, 3_600_000, 60_000, 1_000];
1012
1013#[cfg(feature = "dtype-duration")]
1014pub fn fmt_duration_string<W: Write>(f: &mut W, v: i64, unit: TimeUnit) -> fmt::Result {
1015 if v == 0 {
1018 return match unit {
1019 TimeUnit::Nanoseconds => f.write_str("0ns"),
1020 TimeUnit::Microseconds => f.write_str("0µs"),
1021 TimeUnit::Milliseconds => f.write_str("0ms"),
1022 };
1023 };
1024 let sizes = match unit {
1027 TimeUnit::Nanoseconds => SIZES_NS.as_slice(),
1028 TimeUnit::Microseconds => SIZES_US.as_slice(),
1029 TimeUnit::Milliseconds => SIZES_MS.as_slice(),
1030 };
1031 let mut buffer = itoa::Buffer::new();
1032 for (i, &size) in sizes.iter().enumerate() {
1033 let whole_num = if i == 0 {
1034 v / size
1035 } else {
1036 (v % sizes[i - 1]) / size
1037 };
1038 if whole_num != 0 {
1039 f.write_str(buffer.format(whole_num))?;
1040 f.write_str(DURATION_PARTS[i])?;
1041 if v % size != 0 {
1042 f.write_char(' ')?;
1043 }
1044 }
1045 }
1046 let (v, units) = match unit {
1048 TimeUnit::Nanoseconds => (v % 1_000_000_000, ["ns", "µs", "ms"]),
1049 TimeUnit::Microseconds => (v % 1_000_000, ["µs", "ms", ""]),
1050 TimeUnit::Milliseconds => (v % 1_000, ["ms", "", ""]),
1051 };
1052 if v != 0 {
1053 let (value, suffix) = if v % 1_000 != 0 {
1054 (v, units[0])
1055 } else if v % 1_000_000 != 0 {
1056 (v / 1_000, units[1])
1057 } else {
1058 (v / 1_000_000, units[2])
1059 };
1060 f.write_str(buffer.format(value))?;
1061 f.write_str(suffix)?;
1062 }
1063 Ok(())
1064}
1065
1066#[cfg(feature = "dtype-duration")]
1067pub fn iso_duration_string(s: &mut String, mut v: i64, unit: TimeUnit) {
1068 if v == 0 {
1069 s.push_str("PT0S");
1070 return;
1071 }
1072 let mut buffer = itoa::Buffer::new();
1073 let mut wrote_part = false;
1074 if v < 0 {
1075 s.push_str("-P");
1077 v = v.abs();
1078 } else {
1079 s.push('P');
1080 }
1081 let sizes = match unit {
1084 TimeUnit::Nanoseconds => SIZES_NS.as_slice(),
1085 TimeUnit::Microseconds => SIZES_US.as_slice(),
1086 TimeUnit::Milliseconds => SIZES_MS.as_slice(),
1087 };
1088 for (i, &size) in sizes.iter().enumerate() {
1089 let whole_num = if i == 0 {
1090 v / size
1091 } else {
1092 (v % sizes[i - 1]) / size
1093 };
1094 if whole_num != 0 || i == 3 {
1095 if i != 3 {
1096 s.push_str(buffer.format(whole_num));
1098 s.push_str(ISO_DURATION_PARTS[i]);
1099 } else {
1100 let fractional_part = v % size;
1104 if whole_num == 0 && fractional_part == 0 {
1105 if !wrote_part {
1106 s.push_str("0S")
1107 }
1108 } else {
1109 s.push_str(buffer.format(whole_num));
1110 if fractional_part != 0 {
1111 let secs = match unit {
1112 TimeUnit::Nanoseconds => format!(".{fractional_part:09}"),
1113 TimeUnit::Microseconds => format!(".{fractional_part:06}"),
1114 TimeUnit::Milliseconds => format!(".{fractional_part:03}"),
1115 };
1116 s.push_str(secs.trim_end_matches('0'));
1117 }
1118 s.push_str(ISO_DURATION_PARTS[i]);
1119 }
1120 }
1121 if i == 0 {
1124 s.push('T');
1125 }
1126 wrote_part = true;
1127 } else if i == 0 {
1128 s.push('T');
1131 }
1132 }
1133 if s.ends_with('T') {
1135 s.pop();
1136 }
1137}
1138
1139fn format_blob(f: &mut Formatter<'_>, bytes: &[u8]) -> fmt::Result {
1140 let ellipsis = get_ellipsis();
1141 let width = get_str_len_limit() * 2;
1142 write!(f, "b\"")?;
1143
1144 for b in bytes.iter().take(width) {
1145 if b.is_ascii_alphanumeric() || b.is_ascii_punctuation() {
1146 write!(f, "{}", *b as char)?;
1147 } else {
1148 write!(f, "\\x{b:02x}")?;
1149 }
1150 }
1151 if bytes.len() > width {
1152 write!(f, "\"{ellipsis}")?;
1153 } else {
1154 f.write_str("\"")?;
1155 }
1156 Ok(())
1157}
1158
1159impl Display for AnyValue<'_> {
1160 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1161 let width = 0;
1162 match self {
1163 AnyValue::Null => write!(f, "null"),
1164 AnyValue::UInt8(v) => fmt_integer(f, width, *v),
1165 AnyValue::UInt16(v) => fmt_integer(f, width, *v),
1166 AnyValue::UInt32(v) => fmt_integer(f, width, *v),
1167 AnyValue::UInt64(v) => fmt_integer(f, width, *v),
1168 AnyValue::UInt128(v) => feature_gated!("dtype-u128", fmt_integer(f, width, *v)),
1169 AnyValue::Int8(v) => fmt_integer(f, width, *v),
1170 AnyValue::Int16(v) => fmt_integer(f, width, *v),
1171 AnyValue::Int32(v) => fmt_integer(f, width, *v),
1172 AnyValue::Int64(v) => fmt_integer(f, width, *v),
1173 AnyValue::Int128(v) => feature_gated!("dtype-i128", fmt_integer(f, width, *v)),
1174 AnyValue::Float32(v) => fmt_float(f, width, *v),
1175 AnyValue::Float64(v) => fmt_float(f, width, *v),
1176 AnyValue::Boolean(v) => write!(f, "{}", *v),
1177 AnyValue::String(v) => write!(f, "{}", format_args!("\"{v}\"")),
1178 AnyValue::StringOwned(v) => write!(f, "{}", format_args!("\"{v}\"")),
1179 AnyValue::Binary(d) => format_blob(f, d),
1180 AnyValue::BinaryOwned(d) => format_blob(f, d),
1181 #[cfg(feature = "dtype-date")]
1182 AnyValue::Date(v) => write!(f, "{}", date32_to_date(*v)),
1183 #[cfg(feature = "dtype-datetime")]
1184 AnyValue::Datetime(v, tu, tz) => fmt_datetime(f, *v, *tu, *tz),
1185 #[cfg(feature = "dtype-datetime")]
1186 AnyValue::DatetimeOwned(v, tu, tz) => {
1187 fmt_datetime(f, *v, *tu, tz.as_ref().map(|v| v.as_ref()))
1188 },
1189 #[cfg(feature = "dtype-duration")]
1190 AnyValue::Duration(v, tu) => fmt_duration_string(f, *v, *tu),
1191 #[cfg(feature = "dtype-time")]
1192 AnyValue::Time(_) => {
1193 let nt: chrono::NaiveTime = self.into();
1194 write!(f, "{nt}")
1195 },
1196 #[cfg(feature = "dtype-categorical")]
1197 AnyValue::Categorical(_, _)
1198 | AnyValue::CategoricalOwned(_, _)
1199 | AnyValue::Enum(_, _)
1200 | AnyValue::EnumOwned(_, _) => {
1201 let s = self.get_str().unwrap();
1202 write!(f, "\"{s}\"")
1203 },
1204 #[cfg(feature = "dtype-array")]
1205 AnyValue::Array(s, _size) => write!(f, "{}", s.fmt_list()),
1206 AnyValue::List(s) => write!(f, "{}", s.fmt_list()),
1207 #[cfg(feature = "object")]
1208 AnyValue::Object(v) => write!(f, "{v}"),
1209 #[cfg(feature = "object")]
1210 AnyValue::ObjectOwned(v) => write!(f, "{}", v.0.as_ref()),
1211 #[cfg(feature = "dtype-struct")]
1212 av @ AnyValue::Struct(_, _, _) => {
1213 let mut avs = vec![];
1214 av._materialize_struct_av(&mut avs);
1215 fmt_struct(f, &avs)
1216 },
1217 #[cfg(feature = "dtype-struct")]
1218 AnyValue::StructOwned(payload) => fmt_struct(f, &payload.0),
1219 #[cfg(feature = "dtype-decimal")]
1220 AnyValue::Decimal(v, _prec, scale) => fmt_decimal(f, *v, *scale),
1221 }
1222 }
1223}
1224
1225#[allow(dead_code)]
1227#[cfg(feature = "dtype-datetime")]
1228pub struct PlTzAware<'a> {
1229 ndt: NaiveDateTime,
1230 tz: &'a str,
1231}
1232#[cfg(feature = "dtype-datetime")]
1233impl<'a> PlTzAware<'a> {
1234 pub fn new(ndt: NaiveDateTime, tz: &'a str) -> Self {
1235 Self { ndt, tz }
1236 }
1237}
1238
1239#[cfg(feature = "dtype-datetime")]
1240impl Display for PlTzAware<'_> {
1241 #[allow(unused_variables)]
1242 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
1243 #[cfg(feature = "timezones")]
1244 match self.tz.parse::<chrono_tz::Tz>() {
1245 Ok(tz) => {
1246 let dt_utc = chrono::Utc.from_local_datetime(&self.ndt).unwrap();
1247 let dt_tz_aware = dt_utc.with_timezone(&tz);
1248 write!(f, "{dt_tz_aware}")
1249 },
1250 Err(_) => write!(f, "invalid timezone"),
1251 }
1252 #[cfg(not(feature = "timezones"))]
1253 {
1254 panic!("activate 'timezones' feature")
1255 }
1256 }
1257}
1258
1259#[cfg(feature = "dtype-struct")]
1260fn fmt_struct(f: &mut Formatter<'_>, vals: &[AnyValue]) -> fmt::Result {
1261 write!(f, "{{")?;
1262 if !vals.is_empty() {
1263 for v in &vals[..vals.len() - 1] {
1264 write!(f, "{v},")?;
1265 }
1266 write!(f, "{}", vals[vals.len() - 1])?;
1268 }
1269 write!(f, "}}")
1270}
1271
1272impl Series {
1273 pub fn fmt_list(&self) -> String {
1274 assert!(
1275 !self.dtype().is_object(),
1276 "nested Objects are not allowed\n\nYou probably got here by not setting a `return_dtype` on a UDF on Objects."
1277 );
1278 if self.is_empty() {
1279 return "[]".to_owned();
1280 }
1281 let mut result = "[".to_owned();
1282 let max_items = get_list_len_limit();
1283 let ellipsis = get_ellipsis();
1284
1285 match max_items {
1286 0 => write!(result, "{ellipsis}]").unwrap(),
1287 _ if max_items >= self.len() => {
1288 for item in self.rechunk().iter() {
1291 write!(result, "{item}, ").unwrap();
1292 }
1293 result.truncate(result.len() - 2);
1295 result.push(']');
1296 },
1297 _ => {
1298 let s = self.slice(0, max_items).rechunk();
1299 for (i, item) in s.iter().enumerate() {
1300 if i == max_items.saturating_sub(1) {
1301 write!(result, "{ellipsis} {}", self.get(self.len() - 1).unwrap()).unwrap();
1302 break;
1303 } else {
1304 write!(result, "{item}, ").unwrap();
1305 }
1306 }
1307 result.push(']');
1308 },
1309 };
1310 result
1311 }
1312}
1313
1314#[inline]
1315#[cfg(feature = "dtype-decimal")]
1316fn fmt_decimal(f: &mut Formatter<'_>, v: i128, scale: usize) -> fmt::Result {
1317 let mut fmt_buf = polars_compute::decimal::DecimalFmtBuffer::new();
1318 let trim_zeros = get_trim_decimal_zeros();
1319 f.write_str(fmt_float_string(fmt_buf.format_dec128(v, scale, trim_zeros, false)).as_str())
1320}
1321
1322#[cfg(all(
1323 test,
1324 feature = "temporal",
1325 feature = "dtype-date",
1326 feature = "dtype-datetime"
1327))]
1328#[allow(unsafe_op_in_unsafe_fn)]
1329mod test {
1330 use crate::prelude::*;
1331
1332 #[test]
1333 fn test_fmt_list() {
1334 let mut builder = ListPrimitiveChunkedBuilder::<Int32Type>::new(
1335 PlSmallStr::from_static("a"),
1336 10,
1337 10,
1338 DataType::Int32,
1339 );
1340 builder.append_opt_slice(Some(&[1, 2, 3, 4, 5, 6]));
1341 builder.append_opt_slice(None);
1342 let list_long = builder.finish().into_series();
1343
1344 assert_eq!(
1345 r#"shape: (2,)
1346Series: 'a' [list[i32]]
1347[
1348 [1, 2, … 6]
1349 null
1350]"#,
1351 format!("{list_long:?}")
1352 );
1353
1354 unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "10") };
1355
1356 assert_eq!(
1357 r#"shape: (2,)
1358Series: 'a' [list[i32]]
1359[
1360 [1, 2, 3, 4, 5, 6]
1361 null
1362]"#,
1363 format!("{list_long:?}")
1364 );
1365
1366 unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "-1") };
1367
1368 assert_eq!(
1369 r#"shape: (2,)
1370Series: 'a' [list[i32]]
1371[
1372 [1, 2, 3, 4, 5, 6]
1373 null
1374]"#,
1375 format!("{list_long:?}")
1376 );
1377
1378 unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "0") };
1379
1380 assert_eq!(
1381 r#"shape: (2,)
1382Series: 'a' [list[i32]]
1383[
1384 […]
1385 null
1386]"#,
1387 format!("{list_long:?}")
1388 );
1389
1390 unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "1") };
1391
1392 assert_eq!(
1393 r#"shape: (2,)
1394Series: 'a' [list[i32]]
1395[
1396 [… 6]
1397 null
1398]"#,
1399 format!("{list_long:?}")
1400 );
1401
1402 unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "4") };
1403
1404 assert_eq!(
1405 r#"shape: (2,)
1406Series: 'a' [list[i32]]
1407[
1408 [1, 2, 3, … 6]
1409 null
1410]"#,
1411 format!("{list_long:?}")
1412 );
1413
1414 let mut builder = ListPrimitiveChunkedBuilder::<Int32Type>::new(
1415 PlSmallStr::from_static("a"),
1416 10,
1417 10,
1418 DataType::Int32,
1419 );
1420 builder.append_opt_slice(Some(&[1]));
1421 builder.append_opt_slice(None);
1422 let list_short = builder.finish().into_series();
1423
1424 unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "") };
1425
1426 assert_eq!(
1427 r#"shape: (2,)
1428Series: 'a' [list[i32]]
1429[
1430 [1]
1431 null
1432]"#,
1433 format!("{list_short:?}")
1434 );
1435
1436 unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "0") };
1437
1438 assert_eq!(
1439 r#"shape: (2,)
1440Series: 'a' [list[i32]]
1441[
1442 […]
1443 null
1444]"#,
1445 format!("{list_short:?}")
1446 );
1447
1448 unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "-1") };
1449
1450 assert_eq!(
1451 r#"shape: (2,)
1452Series: 'a' [list[i32]]
1453[
1454 [1]
1455 null
1456]"#,
1457 format!("{list_short:?}")
1458 );
1459
1460 let mut builder = ListPrimitiveChunkedBuilder::<Int32Type>::new(
1461 PlSmallStr::from_static("a"),
1462 10,
1463 10,
1464 DataType::Int32,
1465 );
1466 builder.append_opt_slice(Some(&[]));
1467 builder.append_opt_slice(None);
1468 let list_empty = builder.finish().into_series();
1469
1470 unsafe { std::env::set_var("POLARS_FMT_TABLE_CELL_LIST_LEN", "") };
1471
1472 assert_eq!(
1473 r#"shape: (2,)
1474Series: 'a' [list[i32]]
1475[
1476 []
1477 null
1478]"#,
1479 format!("{list_empty:?}")
1480 );
1481 }
1482
1483 #[test]
1484 fn test_fmt_temporal() {
1485 let s = Int32Chunked::new(PlSmallStr::from_static("Date"), &[Some(1), None, Some(3)])
1486 .into_date();
1487 assert_eq!(
1488 r#"shape: (3,)
1489Series: 'Date' [date]
1490[
1491 1970-01-02
1492 null
1493 1970-01-04
1494]"#,
1495 format!("{:?}", s.into_series())
1496 );
1497
1498 let s = Int64Chunked::new(PlSmallStr::EMPTY, &[Some(1), None, Some(1_000_000_000_000)])
1499 .into_datetime(TimeUnit::Nanoseconds, None);
1500 assert_eq!(
1501 r#"shape: (3,)
1502Series: '' [datetime[ns]]
1503[
1504 1970-01-01 00:00:00.000000001
1505 null
1506 1970-01-01 00:16:40
1507]"#,
1508 format!("{:?}", s.into_series())
1509 );
1510 }
1511
1512 #[test]
1513 fn test_fmt_chunkedarray() {
1514 let ca = Int32Chunked::new(PlSmallStr::from_static("Date"), &[Some(1), None, Some(3)]);
1515 assert_eq!(
1516 r#"shape: (3,)
1517ChunkedArray: 'Date' [i32]
1518[
1519 1
1520 null
1521 3
1522]"#,
1523 format!("{ca:?}")
1524 );
1525 let ca = StringChunked::new(PlSmallStr::from_static("name"), &["a", "b"]);
1526 assert_eq!(
1527 r#"shape: (2,)
1528ChunkedArray: 'name' [str]
1529[
1530 "a"
1531 "b"
1532]"#,
1533 format!("{ca:?}")
1534 );
1535 }
1536}