arr_rs/core/operations/
display.rs

1use crate::{
2    core::prelude::*,
3    errors::prelude::*,
4    extensions::prelude::*,
5};
6
7impl <T: ArrayElement> std::fmt::Display for Array<T> {
8
9    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10        write!(f, "{}", build_string(self, f.precision(), f.alternate(), 1))
11    }
12}
13
14fn build_string<T: ArrayElement>(arr: &Array<T>, precision: Option<usize>, alternate: bool, prefix: usize) -> String {
15    if arr.is_empty().unwrap_or(true) {
16        "[]".to_string()
17    } else if arr.len().unwrap_or(0) == 1 {
18        format!("[{}]", arr.get_elements().unwrap()[0])
19    } else if arr.ndim().unwrap_or(0) == 1 {
20        let elements = arr.get_elements().unwrap().into_iter()
21            .map(|e| format_with_precision(&e, precision))
22            .collect::<Vec<String>>()
23            .join(", ");
24        format!("[{elements}]")
25    } else {
26        let arrays = arr.split_axis(0).unwrap_or_default().into_iter()
27            .map(|arr| arr.reshape(&arr.get_shape().unwrap().remove_at(0)).unwrap())
28            .map(|arr| build_string(&arr, precision, alternate, prefix + 1))
29            .collect::<Vec<String>>();
30        let separator_alt = format!(",\n{}", " ".repeat(prefix));
31        format!("[{}]", arrays.join(if alternate { &separator_alt } else { ", " }))
32    }
33}
34
35fn format_with_precision<T: ArrayElement>(elem: &T, precision: Option<usize>) -> String {
36    if precision.is_some() {
37        format!("{elem:.p$}", elem = elem, p = precision.unwrap())
38    } else {
39        format!("{elem}")
40    }
41}
42
43/// Wrapper for `Result<Array<T>, ArrayError>` for implementation of Display trait
44#[derive(Clone, Debug)]
45pub struct PrintableResult<T: ArrayElement> {
46    /// inner field - result to print
47    pub result: Result<Array<T>, ArrayError>,
48}
49
50impl <T: ArrayElement> std::fmt::Display for PrintableResult<T> {
51
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        let result = self.result.clone();
54        if self.result.is_err() {
55            write!(f, "Err({})", result.unwrap_err())
56        } else {
57            write!(f, "Ok({})", build_string(&result.unwrap(), f.precision(), f.alternate(), 1))
58        }
59    }
60}