use std::collections::HashMap;
use crate::concord::MootId;
#[derive(Clone, Debug, Default)]
pub struct Reciprocity {
given: HashMap<(MootId, MootId), u64>,
}
impl Reciprocity {
pub fn new() -> Self {
Self::default()
}
pub fn record(&mut self, provider: MootId, beneficiary: MootId, amount: u64) {
*self.given.entry((provider, beneficiary)).or_default() += amount;
}
fn provided(&self, provider: MootId, beneficiary: MootId) -> u64 {
self.given
.get(&(provider, beneficiary))
.copied()
.unwrap_or(0)
}
pub fn balance(&self, a: MootId, b: MootId) -> i64 {
self.provided(a, b) as i64 - self.provided(b, a) as i64
}
pub fn may_request(&self, requester: MootId, from: MootId, tolerance: u64) -> bool {
self.balance(from, requester) <= tolerance as i64
}
}
#[cfg(test)]
mod tests {
use super::*;
fn moot(n: u8) -> MootId {
MootId([n; 32])
}
#[test]
fn provided_work_sets_the_balance() {
let (a, b) = (moot(1), moot(2));
let mut r = Reciprocity::new();
r.record(a, b, 10);
assert_eq!(r.balance(a, b), 10, "B is in A's debt");
assert_eq!(r.balance(b, a), -10);
}
#[test]
fn reciprocation_nets_out() {
let (a, b) = (moot(1), moot(2));
let mut r = Reciprocity::new();
r.record(a, b, 10);
r.record(b, a, 10);
assert_eq!(r.balance(a, b), 0);
}
#[test]
fn a_reciprocating_peer_may_keep_requesting() {
let (a, b) = (moot(1), moot(2));
let mut r = Reciprocity::new();
r.record(a, b, 30);
r.record(b, a, 25);
assert!(r.may_request(b, a, 10));
}
#[test]
fn a_freeloader_is_cut_off_until_it_reciprocates() {
let (a, b) = (moot(1), moot(2));
let mut r = Reciprocity::new();
r.record(a, b, 50);
assert!(!r.may_request(b, a, 10));
r.record(b, a, 45);
assert!(r.may_request(b, a, 10));
}
}