zenoh_sync/
object_pool.rs1use std::{
15 any::Any,
16 fmt,
17 ops::{Deref, DerefMut, Drop},
18 sync::{Arc, Weak},
19};
20
21use zenoh_buffers::ZSliceBuffer;
22
23use super::LifoQueue;
24
25pub struct RecyclingObjectPool<T, F>
28where
29 F: Fn() -> T,
30{
31 inner: Arc<LifoQueue<T>>,
32 f: F,
33}
34
35impl<T, F: Fn() -> T> RecyclingObjectPool<T, F> {
36 pub fn new(num: usize, f: F) -> RecyclingObjectPool<T, F> {
37 let inner: Arc<LifoQueue<T>> = Arc::new(LifoQueue::new(num));
38 for _ in 0..num {
39 let obj = (f)();
40 inner.try_push(obj);
41 }
42 RecyclingObjectPool { inner, f }
43 }
44
45 pub fn alloc(&self) -> RecyclingObject<T> {
46 RecyclingObject::new((self.f)(), Weak::new())
47 }
48
49 pub fn try_take(&self) -> Option<RecyclingObject<T>> {
50 self.inner
51 .try_pull()
52 .map(|obj| RecyclingObject::new(obj, Arc::downgrade(&self.inner)))
53 }
54
55 pub fn take(&self) -> RecyclingObject<T> {
56 let obj = self.inner.pull();
57 RecyclingObject::new(obj, Arc::downgrade(&self.inner))
58 }
59}
60
61#[derive(Clone)]
62pub struct RecyclingObject<T> {
63 pool: Weak<LifoQueue<T>>,
64 object: Option<T>,
65}
66
67impl<T> RecyclingObject<T> {
68 pub fn new(obj: T, pool: Weak<LifoQueue<T>>) -> RecyclingObject<T> {
69 RecyclingObject {
70 pool,
71 object: Some(obj),
72 }
73 }
74
75 pub fn recycle(mut self) {
76 if let Some(pool) = self.pool.upgrade() {
77 if let Some(obj) = self.object.take() {
78 pool.push(obj);
79 }
80 }
81 }
82}
83
84impl<T: PartialEq> Eq for RecyclingObject<T> {}
85
86impl<T: PartialEq> PartialEq for RecyclingObject<T> {
87 fn eq(&self, other: &Self) -> bool {
88 self.object == other.object
89 }
90}
91
92impl<T> Deref for RecyclingObject<T> {
93 type Target = T;
94 #[inline]
95 fn deref(&self) -> &Self::Target {
96 self.object.as_ref().unwrap()
97 }
98}
99
100impl<T> DerefMut for RecyclingObject<T> {
101 #[inline]
102 fn deref_mut(&mut self) -> &mut Self::Target {
103 self.object.as_mut().unwrap()
104 }
105}
106
107impl<T> From<T> for RecyclingObject<T> {
108 fn from(obj: T) -> RecyclingObject<T> {
109 RecyclingObject::new(obj, Weak::new())
110 }
111}
112
113impl<T> Drop for RecyclingObject<T> {
114 fn drop(&mut self) {
115 if let Some(pool) = self.pool.upgrade() {
116 if let Some(obj) = self.object.take() {
117 pool.push(obj);
118 }
119 }
120 }
121}
122
123impl<T: fmt::Debug> fmt::Debug for RecyclingObject<T> {
124 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
125 f.debug_struct("").field("inner", &self.object).finish()
126 }
127}
128
129impl AsRef<[u8]> for RecyclingObject<Box<[u8]>> {
131 fn as_ref(&self) -> &[u8] {
132 self.deref()
133 }
134}
135
136impl AsMut<[u8]> for RecyclingObject<Box<[u8]>> {
137 fn as_mut(&mut self) -> &mut [u8] {
138 self.deref_mut()
139 }
140}
141
142impl ZSliceBuffer for RecyclingObject<Box<[u8]>> {
143 fn as_slice(&self) -> &[u8] {
144 self.as_ref()
145 }
146
147 fn as_any(&self) -> &dyn Any {
148 self
149 }
150
151 fn as_any_mut(&mut self) -> &mut dyn Any {
152 self
153 }
154}