anchored_pool/
other_utils.rs1use std::mem;
2use std::error::Error;
3use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
4
5#[cfg(feature = "clone-behavior")]
6use clone_behavior::{DeepClone, MirroredClone, Speed};
7
8
9#[derive(Debug, Clone, Copy)]
12pub struct ResourcePoolEmpty;
13
14impl Display for ResourcePoolEmpty {
15 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
16 write!(
17 f,
18 "a bounded resource pool operation was not performed \
19 because there were no `Resource`s available",
20 )
21 }
22}
23
24impl Error for ResourcePoolEmpty {}
25
26#[derive(Debug, Clone, Copy)]
29pub struct OutOfBuffers;
30
31impl Display for OutOfBuffers {
32 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
33 write!(
34 f,
35 "a bounded buffer pool operation was not performed \
36 because there were no available buffers",
37 )
38 }
39}
40
41impl Error for OutOfBuffers {}
42
43pub trait ResetResource<Resource> {
45 fn reset(&self, resource: &mut Resource);
49}
50
51impl<Resource, F: Fn(&mut Resource)> ResetResource<Resource> for F {
52 #[inline]
53 fn reset(&self, resource: &mut Resource) {
54 self(resource);
55 }
56}
57
58#[derive(Default, Debug, Clone, Copy)]
61pub struct ResetNothing;
62
63impl<Resource> ResetResource<Resource> for ResetNothing {
64 fn reset(&self, _resource: &mut Resource) {}
66}
67
68#[cfg(feature = "clone-behavior")]
69impl<S: Speed> DeepClone<S> for ResetNothing {
70 #[inline]
71 fn deep_clone(&self) -> Self {
72 *self
73 }
74}
75
76#[cfg(feature = "clone-behavior")]
77impl<S: Speed> MirroredClone<S> for ResetNothing {
78 #[inline]
79 fn mirrored_clone(&self) -> Self {
80 *self
81 }
82}
83
84#[derive(Debug, Clone, Copy)]
90pub struct ResetBuffer {
91 max_buffer_capacity: usize,
94}
95
96impl ResetBuffer {
97 #[inline]
103 #[must_use]
104 pub const fn new(max_buffer_capacity: usize) -> Self {
105 Self {
106 max_buffer_capacity,
107 }
108 }
109}
110
111impl ResetResource<Vec<u8>> for ResetBuffer {
112 #[inline]
113 fn reset(&self, resource: &mut Vec<u8>) {
114 if resource.capacity() > self.max_buffer_capacity {
115 let _large_buf = mem::take(resource);
117 } else {
118 resource.clear();
119 }
120 }
121}
122
123#[cfg(feature = "clone-behavior")]
124impl<S: Speed> DeepClone<S> for ResetBuffer {
125 #[inline]
126 fn deep_clone(&self) -> Self {
127 *self
128 }
129}
130
131#[cfg(feature = "clone-behavior")]
132impl<S: Speed> MirroredClone<S> for ResetBuffer {
133 #[inline]
134 fn mirrored_clone(&self) -> Self {
135 *self
136 }
137}