surrealcs_kernel/
allocator.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
//! An allocator for mapping an index to a value T.
use std::collections::VecDeque;

use nanoservices_utils::errors::{NanoServiceError, NanoServiceErrorStatus};

/// An allocator for mapping an index to a value T.
///
/// # Fields
/// * `connection_pool` - A vector of optional values of type T that can be allocated and deallocated, and accessed by index.
/// * `free_connections` - A queue of indices that have been deallocated and are available for allocation.
/// * `allocated_connections` - A queue of indices that have been allocated and are currently in use.
#[derive(Debug)]
pub struct Allocator<T: Clone> {
	pub connection_pool: Vec<Option<T>>,
	pub free_connections: VecDeque<usize>,
	pub allocated_connections: VecDeque<usize>,
}

impl<T: Clone> Default for Allocator<T> {
	fn default() -> Self {
		Self::new()
	}
}

impl<T: Clone> Allocator<T> {
	/// The constructor for the Allocator struct.
	///
	/// # Returns
	/// A new instance of the Allocator struct.
	pub fn new() -> Self {
		Self {
			connection_pool: Vec::new(),
			free_connections: VecDeque::new(),
			allocated_connections: VecDeque::new(),
		}
	}

	/// Allocates a connection in the connection pool.
	///
	/// # Arguments
	/// * `connection` - The connection to be allocated.
	///
	/// # Returns
	/// The index of the allocated connection to be used to access the connection in the connection pool.
	pub fn allocate(&mut self, connection: T) -> usize {
		if let Some(index) = self.free_connections.pop_front() {
			self.connection_pool[index] = Some(connection);
			self.allocated_connections.push_back(index);
			index
		} else {
			self.connection_pool.push(Some(connection));
			self.allocated_connections.push_back(self.connection_pool.len() - 1);
			self.connection_pool.len() - 1
		}
	}

	/// Yields the next allocated index in the connection pool.
	///
	/// # Returns
	/// The next allocated index in the connection pool. (empty if thee is no allocated connection available)
	pub fn yield_next_allocated_index(&mut self) -> Option<usize> {
		// for some reason this line throws a warning, however, the index is not
		// unused
		#[allow(unused_assignments)]
		let mut index: Option<usize> = None;

		loop {
			index = self.allocated_connections.pop_front();
			if index.is_none() {
				break;
			}
			let i = index.unwrap();
			let connection = self.connection_pool[i].as_ref();
			match connection {
				Some(_) => {
					self.allocated_connections.push_back(i);
					break;
				}
				None => continue,
			}
		}
		index
	}

	/// Extracts a connection from the connection pool.
	///
	/// # Arguments
	/// * `index` - The index of the connection to be extracted.
	///
	/// # Returns
	/// The connection at the specified index.
	pub fn extract_connection(&self, index: usize) -> Result<(T, usize), NanoServiceError> {
		if index + 1 > self.connection_pool.len() {
			return Err(NanoServiceError::new(
				format!("Connection at index {index} is unavailable"),
				NanoServiceErrorStatus::Unknown,
			));
		}
		let connection = self.connection_pool[index].as_ref();
		match connection {
			Some(c) => Ok((c.clone(), index)),
			None => Err(NanoServiceError::new(
				format!("Connection at index {index} is deallocated"),
				NanoServiceErrorStatus::Unknown,
			)),
		}
	}

	/// Deallocates a connection in the connection pool.
	///
	/// # Arguments
	/// * `index` - The index of the connection to be deallocated.
	pub fn deallocate(&mut self, index: usize) -> Result<T, NanoServiceError> {
		if index + 1 > self.connection_pool.len() {
			return Err(NanoServiceError::new(
				format!("Connection at index {index} is unavailable"),
				NanoServiceErrorStatus::Unknown,
			));
		}
		let placeholder = self.connection_pool[index].take();
		if placeholder.is_none() {
			return Err(NanoServiceError::new(
				format!("Connection at index {index} is already deallocated"),
				NanoServiceErrorStatus::Unknown,
			));
		}
		self.free_connections.push_back(index);
		Ok(placeholder.unwrap())
	}

	/// Yields all the connections in the connection pool.
	///
	/// # Returns
	/// A vector of all the connections in the connection pool.
	pub fn yield_connections(&self) -> Vec<T> {
		let mut connections = Vec::new();
		for i in &self.allocated_connections {
			let connection = self.connection_pool[*i].as_ref();
			match connection {
				Some(c) => connections.push(c.clone()),
				None => continue,
			}
		}
		connections
	}
}

#[cfg(test)]
mod tests {

	use super::*;

	#[test]
	fn test_new() {
		let allocator = Allocator::<usize>::new();
		assert_eq!(allocator.connection_pool.len(), 0);
		assert_eq!(allocator.free_connections.len(), 0);
		assert_eq!(allocator.allocated_connections.len(), 0);
	}

	#[test]
	fn test_allocate() {
		let mut allocator = Allocator::<usize>::new();
		let index = allocator.allocate(5);
		assert_eq!(index, 0);
		assert_eq!(allocator.connection_pool[index], Some(5));
		assert_eq!(allocator.allocated_connections.len(), 1);
		assert_eq!(allocator.free_connections.len(), 0);
		assert_eq!(allocator.connection_pool.len(), 1);

		// ensures that there is only one connection in the pool
		assert_eq!(allocator.yield_next_allocated_index(), Some(0));
		assert_eq!(allocator.yield_next_allocated_index(), Some(0));
		assert_eq!(allocator.yield_next_allocated_index(), Some(0));

		let index = allocator.allocate(6);
		assert_eq!(index, 1);
		assert_eq!(allocator.connection_pool[index], Some(6));
		assert_eq!(allocator.allocated_connections.len(), 2);
		assert_eq!(allocator.free_connections.len(), 0);

		// ensures that we cycle between the two connections
		assert_eq!(allocator.yield_next_allocated_index(), Some(0));
		assert_eq!(allocator.yield_next_allocated_index(), Some(1));
		assert_eq!(allocator.yield_next_allocated_index(), Some(0));
		assert_eq!(allocator.yield_next_allocated_index(), Some(1));
	}

	#[test]
	fn test_deallocate() {
		let mut allocator = Allocator::<usize>::new();
		let index = allocator.allocate(5);
		let index_two = allocator.allocate(6);

		assert_eq!(index, 0);
		assert_eq!(index_two, 1);
		assert_eq!(allocator.connection_pool[index_two], Some(6));
		assert_eq!(allocator.allocated_connections.len(), 2);
		assert_eq!(allocator.free_connections.len(), 0);

		// ensures that we cycle between the two connections
		assert_eq!(allocator.yield_next_allocated_index(), Some(0));
		assert_eq!(allocator.yield_next_allocated_index(), Some(1));
		assert_eq!(allocator.yield_next_allocated_index(), Some(0));
		assert_eq!(allocator.yield_next_allocated_index(), Some(1));

		assert_eq!(Ok(5), allocator.deallocate(0));
		assert_eq!(allocator.connection_pool[0], None);
		assert_eq!(allocator.allocated_connections.len(), 2);
		assert_eq!(allocator.free_connections.len(), 1);
		assert_eq!(allocator.free_connections[0], 0);

		// only yields the second connection
		assert_eq!(allocator.yield_next_allocated_index(), Some(1));
		assert_eq!(allocator.yield_next_allocated_index(), Some(1));
		assert_eq!(allocator.yield_next_allocated_index(), Some(1));
		assert_eq!(allocator.yield_next_allocated_index(), Some(1));
		assert_eq!(allocator.yield_next_allocated_index(), Some(1));

		// ensure that the first dead connection is recycled
		let index = allocator.allocate(7);
		assert_eq!(index, 0);
		assert_eq!(allocator.connection_pool[index], Some(7));

		// ensures that we cycle between the two connections
		assert_eq!(allocator.yield_next_allocated_index(), Some(1));
		assert_eq!(allocator.yield_next_allocated_index(), Some(0));
		assert_eq!(allocator.yield_next_allocated_index(), Some(1));
		assert_eq!(allocator.yield_next_allocated_index(), Some(0));
		assert_eq!(allocator.yield_next_allocated_index(), Some(1));

		// test an allocation that is out of bounds
		let result = allocator.deallocate(20);
		assert!(result.is_err());
		if let Err(e) = result {
			assert_eq!(e.message, "Connection at index 20 is unavailable");
		}
	}

	#[test]
	fn test_double_deallocate() {
		let mut allocator = Allocator::<usize>::new();
		let _ = allocator.allocate(5);
		let _ = allocator.allocate(6);

		assert_eq!(Ok(5), allocator.deallocate(0));
		assert_eq!(Ok(6), allocator.deallocate(1));

		assert_eq!(allocator.connection_pool[0], None);
		assert_eq!(allocator.connection_pool[1], None);
		assert_eq!(allocator.allocated_connections.len(), 2);
		assert_eq!(allocator.free_connections.len(), 2);
		assert_eq!(allocator.free_connections[0], 0);
		assert_eq!(allocator.free_connections[1], 1);

		// deallocate something that has already been deallocated
		let result = allocator.deallocate(0);
		assert!(result.is_err());
		if let Err(e) = result {
			assert_eq!(e.message, "Connection at index 0 is already deallocated");
		}
	}

	#[test]
	fn test_extract_connection() {
		let mut allocator = Allocator::<usize>::new();

		let outcome = allocator.extract_connection(20);
		assert!(outcome.is_err());
		if let Err(e) = outcome {
			assert_eq!(e.message, "Connection at index 20 is unavailable");
		}

		let index = allocator.allocate(5);
		let connection = allocator.extract_connection(index);
		let result = connection.unwrap();
		assert_eq!(result.0, 5);
		assert_eq!(result.1, 0);

		let _ = allocator.deallocate(index);
		let outcome = allocator.extract_connection(index);
		assert!(outcome.is_err());
		if let Err(e) = outcome {
			assert_eq!(e.message, "Connection at index 0 is deallocated");
		}
	}

	#[test]
	fn test_yield_connections() {
		let mut allocator = Allocator::<usize>::new();
		let _ = allocator.allocate(5);
		let _ = allocator.allocate(6);

		let connections = allocator.yield_connections();
		assert_eq!(connections.len(), 2);
		assert_eq!(connections[0], 5);
		assert_eq!(connections[1], 6);

		let _ = allocator.deallocate(0);
		let connections = allocator.yield_connections();
		assert_eq!(connections.len(), 1);
		assert_eq!(connections[0], 6);
	}
}