use super::QuotaRef;
use crate::{Quota, pool_buffer::QuotaPoolBuffer};
use std::time::Duration;

#[test]
fn quota_ref_consumes_quota_from_buffer() {
    let mut buffer = QuotaPoolBuffer::new();
    let id = buffer.push(Quota::with_initial_tokens(10));
    let quota = QuotaRef::new(&buffer, id);

    let mut accepted = 0;
    let mut rejected = 0;

    for _ in 0..100 {
        match quota.consume(1) {
            Ok(Ok(_)) => accepted += 1,
            Ok(Err(_)) => rejected += 1,
            Err(_) => panic!("quota ref became stale while buffer was still alive"),
        }
    }

    assert_eq!(accepted, 10);
    assert_eq!(rejected, 90);
}

#[test]
fn quota_ref_reads_buffer_timestamps() {
    let mut buffer = QuotaPoolBuffer::new();
    let id = buffer.push(Quota::with_initial_tokens(1));

    *buffer.last_access_time_ns_mut(id).unwrap() = 7;
    *buffer.elapsed_since_refill_ns_mut(id).unwrap() = 11;

    let quota = QuotaRef::new(&buffer, id);

    assert_eq!(quota.last_read_time().unwrap(), Duration::from_nanos(7));
    assert_eq!(
        quota.elapsed_since_refill().unwrap(),
        Duration::from_nanos(11)
    );
}
