Lines
100 %
Functions
78.57 %
Branches
//! The Accounts tab's Balance column cells.
use std::collections::HashMap;
const LOADING: &str = "…";
const MORE: &str = "+";
const ZERO: &str = "0";
const SEPARATOR: &str = ", ";
/// What the Balance column knows: each account's amounts, as whole `10.00 USD` texts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Balances {
Loading,
Failed,
Ready(HashMap<String, Vec<String>>),
}
impl Balances {
/// The cell of account `id` in a column `width` characters wide.
pub fn cell(&self, id: Option<&String>, width: usize) -> String {
match self {
Self::Loading => LOADING.to_string(),
Self::Failed => String::new(),
Self::Ready(cells) => match id.and_then(|id| cells.get(id)) {
Some(parts) if !parts.is_empty() => fit(parts, width),
_ => ZERO.to_string(),
},
fn width_of(text: &str) -> usize {
text.chars().count()
/// Whole amounts only; `+N` counts the amounts that do not fit.
fn fit(parts: &[String], width: usize) -> String {
let all = parts.join(SEPARATOR);
if width_of(&all) <= width {
return all;
let mut shown = String::new();
let mut count = 0;
for part in parts {
let next = if shown.is_empty() {
part.clone()
} else {
format!("{shown}{SEPARATOR}{part}")
};
let hidden = parts.len() - count - 1;
if width_of(&next) + width_of(SEPARATOR) + width_of(&more(hidden)) > width {
break;
shown = next;
count += 1;
let hidden = more(parts.len() - count);
if shown.is_empty() {
hidden
format!("{shown}{SEPARATOR}{hidden}")
fn more(hidden: usize) -> String {
format!("{MORE}{hidden}")
#[cfg(test)]
mod tests {
use super::*;
fn parts(texts: &[&str]) -> Vec<String> {
texts.iter().map(ToString::to_string).collect()
#[test]
fn whole_amounts_that_fit_are_joined() {
assert_eq!(fit(&parts(&["1 EUR", "2 USD"]), 20), "1 EUR, 2 USD");
fn an_amount_is_never_cut() {
let both = parts(&["12345.50 EUR", "5678.25 USD"]);
assert_eq!(fit(&both, 19), "12345.50 EUR, +1");
assert_eq!(fit(&both, 13), "+2");
assert_eq!(fit(&parts(&["12345678901234567890 USD"]), 10), "+1");
fn cells_distinguish_loading_failed_and_zero() {
let id = "a".to_string();
assert_eq!(Balances::Loading.cell(Some(&id), 10), "…");
assert_eq!(Balances::Failed.cell(Some(&id), 10), "");
let ready = Balances::Ready(HashMap::new());
assert_eq!(ready.cell(Some(&id), 10), "0");
assert_eq!(ready.cell(None, 10), "0");