use indexmap::IndexMap;
use crate::types::{Amount, TokenType};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Imbalances(IndexMap<TokenType, Amount>);
impl Imbalances {
#[inline]
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn from_entry(token: impl Into<TokenType>, value: impl Into<Amount>) -> Self {
let mut m = IndexMap::with_capacity(1);
m.insert(token.into(), value.into());
Self(m)
}
pub fn from_entries<I, K, V>(entries: I) -> Self
where
I: IntoIterator<Item = (K, V)>,
K: Into<TokenType>,
V: Into<Amount>,
{
let mut m: IndexMap<TokenType, Amount> = IndexMap::new();
for (k, v) in entries {
let key = k.into();
*m.entry(key).or_insert(Amount::ZERO) += v.into();
}
Self(m)
}
#[inline]
#[must_use]
pub fn get(&self, token: &TokenType) -> Amount {
self.0.get(token).copied().unwrap_or(Amount::ZERO)
}
#[inline]
pub fn set(&mut self, token: TokenType, value: impl Into<Amount>) {
self.0.insert(token, value.into());
}
pub fn ensure_zeros_for<'a, I>(&mut self, tokens: I)
where
I: IntoIterator<Item = &'a TokenType>,
{
for t in tokens {
self.0.entry(t.clone()).or_insert(Amount::ZERO);
}
}
#[inline]
pub fn iter(&self) -> impl Iterator<Item = (&TokenType, Amount)> {
self.0.iter().map(|(k, v)| (k, *v))
}
#[inline]
pub fn token_types(&self) -> impl Iterator<Item = &TokenType> {
self.0.keys()
}
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn merge_in(&mut self, other: &Imbalances) {
for (k, v) in &other.0 {
let slot = self.0.entry(k.clone()).or_insert(Amount::ZERO);
*slot += *v;
}
self.0.retain(|_, v| !v.is_zero());
}
}