use once_cell::sync::Lazy;
use prettytable::format::{FormatBuilder, LinePosition, LineSeparator, TableFormat};
use prettytable::{Cell, Row, Table};
use serde::{Serialize, Serializer};
use serde_json::Value;
use std::collections::HashMap;
static TABLE_FORMAT: Lazy<TableFormat> = Lazy::new(|| {
FormatBuilder::new()
.column_separator('│')
.borders('│')
.separators(&[LinePosition::Top], LineSeparator::new('─', '┬', '┌', '┐'))
.separators(
&[LinePosition::Bottom],
LineSeparator::new('─', '┴', '└', '┘'),
)
.padding(1, 1)
.build()
});
pub static CLEAN_FORMAT: Lazy<TableFormat> =
Lazy::new(|| FormatBuilder::new().padding(0, 3).build());
#[derive(Debug, Serialize)]
pub struct Entry {
pub label: &'static str,
pub value: String,
pub json_label: &'static str,
pub json_value: Value,
}
#[derive(Debug)]
pub struct Metrics(pub Vec<Entry>);
impl Metrics {
pub fn build_table(&self) -> String {
let mut table = Table::new();
table.set_format(*TABLE_FORMAT);
for entry in &self.0 {
table.add_row(Row::new(vec![
Cell::new(entry.label),
Cell::new(&entry.value),
]));
}
table.to_string()
}
}
impl Serialize for Metrics {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let map: HashMap<_, _> = self
.0
.iter()
.map(|entry| (entry.json_label, entry.json_value.clone()))
.collect();
map.serialize(serializer)
}
}