ecb_rates/table/
table_owned.rs

1use std::fmt::Display;
2
3use smol_str::SmolStr;
4
5use crate::DEFAULT_WIDTH;
6use crate::cli::SortBy;
7use crate::models::ExchangeRateResult;
8
9use super::table_display::helper_table_print;
10use super::{TableGet, TableTrait};
11
12pub struct Table {
13    pub(super) header: Option<SmolStr>,
14    pub(super) column_left: SmolStr,
15    pub(super) column_right: SmolStr,
16    pub(super) rows: Vec<(SmolStr, f64)>,
17    pub color: bool,
18    pub width: usize,
19    pub left_offset: usize,
20}
21
22impl<'a> TableTrait<'a> for Table {
23    type Header = SmolStr;
24    type ColumnLeft = SmolStr;
25    type ColumnRight = SmolStr;
26    type RowLeft = SmolStr;
27
28    fn new(
29        header: Option<Self::Header>,
30        column_left: Self::ColumnLeft,
31        column_right: Self::ColumnRight,
32    ) -> Self {
33        Self {
34            header,
35            column_left,
36            column_right,
37            rows: Vec::new(),
38            color: false,
39            width: DEFAULT_WIDTH,
40            left_offset: 1,
41        }
42    }
43
44    fn disable_header(&mut self) {
45        self.header = None;
46    }
47
48    fn set_header(&mut self, header: Self::Header) {
49        self.header = Some(header);
50    }
51
52    fn add_row(&mut self, row_left: Self::RowLeft, row_right: f64) {
53        self.rows.push((row_left, row_right));
54    }
55
56    fn sort(&mut self, sort_by: &SortBy) {
57        let comparer = sort_by.get_comparer();
58        self.rows
59            .sort_by(|a, b| comparer(&(&a.0, a.1), &(&b.0, b.1)));
60    }
61}
62
63impl TableGet for Table {
64    type RowLeftRef = SmolStr;
65    type RowRightRef = SmolStr;
66
67    fn get_header(&self) -> Option<&str> {
68        self.header.as_deref()
69    }
70    fn get_column_left(&self) -> &str {
71        &self.column_left
72    }
73    fn get_column_right(&self) -> &str {
74        &self.column_right
75    }
76    fn get_rows(&self) -> &Vec<(Self::RowLeftRef, f64)> {
77        &self.rows
78    }
79    fn get_width(&self) -> usize {
80        self.width
81    }
82
83    fn get_left_offset(&self) -> usize {
84        self.left_offset
85    }
86}
87
88impl From<ExchangeRateResult> for Table {
89    fn from(value: ExchangeRateResult) -> Self {
90        let mut table = Table::new(Some(value.time), "Currency".into(), "Rate".into());
91        for (key, val) in value.rates.into_iter() {
92            table.add_row(key, val);
93        }
94
95        table
96    }
97}
98
99impl Display for Table {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        helper_table_print(f, self)
102    }
103}