Lines
100 %
Functions
Branches
use num_rational::Rational64;
use num_traits::{CheckedAdd, CheckedSub};
use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
/// Absolute value for ordering; any `i64::MIN` numerator has no positive counterpart and sorts as
/// the largest.
pub fn magnitude(v: Rational64) -> Rational64 {
if v >= Rational64::ZERO {
return v;
}
Rational64::ZERO
.checked_sub(&v)
.unwrap_or(Rational64::from_integer(i64::MAX))
fn size_by_symbol<'a>(amounts: &[(&'a str, Rational64)]) -> BTreeMap<&'a str, Rational64> {
let mut sizes = BTreeMap::new();
for (symbol, amount) in amounts {
let size = sizes.entry(*symbol).or_insert(Rational64::ZERO);
*size = size
.checked_add(&magnitude(*amount))
.unwrap_or(Rational64::from_integer(i64::MAX));
sizes
/// Ascending by size. Commodities are compared one by one in symbol order,
/// a missing one counts as 0, and different commodities are never added.
pub fn cmp_size(a: &[(&str, Rational64)], b: &[(&str, Rational64)]) -> Ordering {
let (left, right) = (size_by_symbol(a), size_by_symbol(b));
let symbols: BTreeSet<_> = left.keys().chain(right.keys()).copied().collect();
symbols
.into_iter()
.map(|s| {
let zero = Rational64::ZERO;
left.get(s)
.unwrap_or(&zero)
.cmp(right.get(s).unwrap_or(&zero))
})
.find(|o| o.is_ne())
.unwrap_or(Ordering::Equal)
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_magnitude_of_i64_min_is_the_largest_size_not_a_wrap() {
let min = Rational64::from_integer(i64::MIN);
assert_eq!(magnitude(min), Rational64::from_integer(i64::MAX));
assert_eq!(
cmp_size(&[("USD", min)], &[("USD", Rational64::from_integer(5))]),
Ordering::Greater
);