rusty_common/pools/
order_pool.rs1use crate::pools::generic_pool::{GenericPool, PoolStats, Poolable};
7
8pub type OrderPoolTemplate<T> = GenericPool<T>;
15
16pub struct OrderPoolFactory;
20
21impl OrderPoolFactory {
22 #[must_use]
24 pub fn create<T: Poolable + Clone>() -> OrderPoolTemplate<T> {
25 OrderPoolTemplate::new()
26 }
27
28 #[must_use]
30 pub fn create_with_capacity<T: Poolable + Clone>(capacity: usize) -> OrderPoolTemplate<T> {
31 OrderPoolTemplate::with_capacity(capacity)
32 }
33}
34
35thread_local! {
37 static GLOBAL_POOL_HOLDER: std::cell::RefCell<Option<Box<dyn std::any::Any>>> =
38 std::cell::RefCell::new(None);
39}
40
41pub fn set_global_order_pool<T: Poolable + Clone + 'static>(pool: OrderPoolTemplate<T>) {
43 GLOBAL_POOL_HOLDER.with(|holder| {
44 *holder.borrow_mut() = Some(Box::new(pool));
45 });
46}
47
48pub fn with_global_order_pool<T: Poolable + Clone + 'static, R>(
50 f: impl FnOnce(&OrderPoolTemplate<T>) -> R,
51) -> Option<R> {
52 GLOBAL_POOL_HOLDER.with(|holder| {
53 holder
54 .borrow()
55 .as_ref()
56 .and_then(|any_pool| any_pool.downcast_ref::<OrderPoolTemplate<T>>().map(f))
57 })
58}
59
60pub fn borrow_from_global_pool<T: Poolable + Clone + 'static>() -> Option<T> {
64 with_global_order_pool(|pool: &OrderPoolTemplate<T>| pool.borrow())
65}
66
67pub fn return_to_global_pool<T: Poolable + Clone + 'static>(object: T) {
69 with_global_order_pool(|pool: &OrderPoolTemplate<T>| pool.return_object(object));
70}
71
72pub fn global_pool_stats<T: Poolable + Clone + 'static>() -> Option<PoolStats> {
74 with_global_order_pool(|pool: &OrderPoolTemplate<T>| pool.stats())
75}
76
77#[cfg(test)]
78mod tests {
79 use super::*;
80
81 #[derive(Debug, Default, Clone)]
82 #[allow(dead_code)]
83 struct MockOrder {
84 id: u32,
85 symbol: String,
86 quantity: f64,
87 }
88
89 impl Poolable for MockOrder {
90 fn new_for_pool() -> Self {
91 Self {
92 id: 0,
93 symbol: String::from("POOL-INVALID"),
94 quantity: 0.0,
95 }
96 }
97
98 fn reset_for_pool(&mut self) {
99 self.id = 0;
100 self.symbol = String::from("POOL-INVALID");
101 self.quantity = 0.0;
102 }
103 }
104
105 #[test]
106 fn test_order_pool_factory() {
107 let pool = OrderPoolFactory::create::<MockOrder>();
108
109 let order1 = pool.borrow();
110 let order2 = pool.borrow();
111
112 pool.return_object(order1);
113 pool.return_object(order2);
114
115 let stats = pool.stats();
116 assert_eq!(stats.total_borrowed, 2);
117 assert_eq!(stats.total_returned, 2);
118 }
119
120 #[test]
121 fn test_global_pool_operations() {
122 let pool = OrderPoolFactory::create::<MockOrder>();
123 set_global_order_pool(pool);
124
125 let order = borrow_from_global_pool::<MockOrder>().unwrap();
126 return_to_global_pool(order);
127
128 let stats = global_pool_stats::<MockOrder>().unwrap();
129 assert!(stats.total_borrowed >= 1);
130 assert!(stats.total_returned >= 1);
131 }
132}