use std::sync::Arc;
use foundation_core::io::buffer_pool::{BytesPool, PooledBuffer};
#[test]
fn test_pool_reuses_buffers() {
let pool = Arc::new(BytesPool::new(1024, 2));
let stats = pool.stats();
assert_eq!(stats.allocations, 0);
assert_eq!(stats.pool_hits, 0);
let buf1 = pool.acquire();
let stats1 = pool.stats();
assert_eq!(stats1.pool_hits, 1);
assert_eq!(stats1.allocations, 0);
let _buf2 = pool.acquire();
let stats2 = pool.stats();
assert_eq!(stats2.pool_hits, 2);
assert_eq!(stats2.allocations, 0);
let _buf3 = pool.acquire();
let stats3 = pool.stats();
assert_eq!(stats3.pool_hits, 2);
assert_eq!(stats3.allocations, 1);
drop(buf1);
let _buf4 = pool.acquire();
let stats4 = pool.stats();
assert_eq!(stats4.pool_hits, 3);
assert_eq!(stats4.allocations, 1);
}
#[test]
fn test_buffer_cleared_on_return() {
let pool = Arc::new(BytesPool::new(1024, 1));
{
let mut buf = pool.acquire();
buf.extend_from_slice(b"hello world");
assert_eq!(&buf[..], b"hello world");
}
let buf2 = pool.acquire();
assert!(buf2.is_empty());
assert_eq!(buf2.capacity(), 1024); }
#[test]
fn test_concurrent_access() {
use std::thread;
let pool = Arc::new(BytesPool::new(1024, 10));
let mut handles = vec![];
for i in 0..10 {
let pool_clone = Arc::clone(&pool);
let handle = thread::spawn(move || {
let mut buf = pool_clone.acquire();
buf.extend_from_slice(format!("thread {}", i).as_bytes());
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
let stats = pool.stats();
assert_eq!(stats.pool_hits, 10);
}
#[test]
fn test_hit_ratio() {
let pool = Arc::new(BytesPool::new(1024, 1));
let buf1 = pool.acquire(); drop(buf1);
let _buf2 = pool.acquire(); let _buf3 = pool.acquire(); let _buf4 = pool.acquire();
let stats = pool.stats();
assert_eq!(stats.pool_hits, 2);
assert_eq!(stats.allocations, 2);
assert!((stats.hit_ratio() - 0.5).abs() < f64::EPSILON);
}
#[test]
fn test_hit_ratio_empty() {
let pool = Arc::new(BytesPool::new(1024, 0));
let stats = pool.stats();
assert_eq!(stats.hit_ratio(), 1.0);
}
#[test]
fn test_pooled_buffer_deref() {
let pool = Arc::new(BytesPool::new(1024, 1));
let mut buf = pool.acquire();
buf.push(42);
buf.extend_from_slice(&[1, 2, 3]);
assert_eq!(buf.len(), 4);
assert_eq!(buf[0], 42);
}
#[test]
fn test_owned_buffer() {
let pool = Arc::new(BytesPool::new(1024, 1));
let stats_before = pool.stats();
let mut owned = PooledBuffer::owned(Vec::with_capacity(512));
owned.push(1);
let stats_after = pool.stats();
assert_eq!(stats_before.allocations, stats_after.allocations);
assert_eq!(stats_before.pool_hits, stats_after.pool_hits);
}
#[test]
fn test_acquire_with_capacity() {
let pool = Arc::new(BytesPool::new(1024, 1));
let buf = pool.acquire_with_capacity(4096);
assert!(buf.capacity() >= 4096);
}