dynamic_pooling/
reset.rs

1use alloc::{
2	boxed::Box,
3	collections::{BinaryHeap, VecDeque},
4	string::String,
5	vec::Vec,
6};
7#[cfg(feature = "std")]
8use std::{
9	collections::{HashMap, HashSet},
10	ffi::OsString,
11	path::PathBuf,
12};
13
14/// Trait for types that can be reset to their [`Default`] while keeping allocated memory.
15///
16/// Types should not implement this trait if memory is deallocated when reset, such as
17/// [`BTreeMap`](alloc::collections::BTreeMap).
18///
19/// ```
20/// # use dynamic_pooling::Reset;
21/// struct MyEpicStruct {
22/// 	vec: Vec<bool>,
23/// 	option: Option<bool>,
24/// }
25///
26/// impl Reset for MyEpicStruct {
27/// 	fn reset(&mut self) {
28/// 		self.vec.clear();
29/// 		self.option = None;
30/// 	}
31/// }
32/// ```
33pub trait Reset {
34	/// Reset to the default state while keeping allocated memory.
35	fn reset(&mut self);
36}
37
38impl<T> Reset for &mut T
39where
40	T: Reset,
41{
42	fn reset(&mut self) {
43		Reset::reset(&mut **self);
44	}
45}
46
47impl<T> Reset for Box<T>
48where
49	T: Reset,
50{
51	fn reset(&mut self) {
52		Reset::reset(&mut **self);
53	}
54}
55
56impl<T> Reset for Vec<T> {
57	fn reset(&mut self) {
58		self.clear();
59	}
60}
61
62impl Reset for String {
63	fn reset(&mut self) {
64		self.clear();
65	}
66}
67
68impl<T> Reset for VecDeque<T> {
69	fn reset(&mut self) {
70		self.clear();
71	}
72}
73
74impl<T> Reset for BinaryHeap<T> {
75	fn reset(&mut self) {
76		self.clear();
77	}
78}
79
80#[cfg(feature = "std")]
81impl Reset for PathBuf {
82	fn reset(&mut self) {
83		self.clear();
84	}
85}
86
87#[cfg(feature = "std")]
88impl Reset for OsString {
89	fn reset(&mut self) {
90		self.clear();
91	}
92}
93
94#[cfg(feature = "std")]
95impl<T, U> Reset for HashMap<T, U> {
96	fn reset(&mut self) {
97		self.clear();
98	}
99}
100
101#[cfg(feature = "std")]
102impl<T, U> Reset for HashSet<T, U> {
103	fn reset(&mut self) {
104		self.clear();
105	}
106}
107
108macro_rules! tuple_hell {
109	($(($($letter:ident:$number:tt),+$(,)?))+) => {$(
110		impl<$($letter),+> Reset for ($($letter),+,) where $($letter: Reset),+ {
111			fn reset(&mut self) {
112				$(self.$number.reset();)+
113			}
114		}
115	)+}
116}
117
118tuple_hell! {
119	(A:0)
120	(A:0, B:1)
121	(A:0, B:1, C:2)
122	(A:0, B:1, C:2, D:3)
123	(A:0, B:1, C:2, D:3, E:4)
124	(A:0, B:1, C:2, D:3, E:4, F:5)
125	(A:0, B:1, C:2, D:3, E:4, F:5, G:6)
126	(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7)
127	(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8)
128	(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9)
129	(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10)
130	(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11)
131	(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12)
132}