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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/// Module providing buffer types
pub mod buf {
use std::{
error::Error,
fmt::Display,
ops::{Index, IndexMut},
};
/// A fixed-size circular buffer implementation.
///
/// This buffer can store a fixed number of elements in a circular fashion,
/// where new elements overwrite old ones when the buffer is full.
#[derive(Clone, Debug)]
pub struct CircularBuffer<T> {
buffer: Vec<Option<T>>,
read_pos: usize,
write_pos: usize,
size: usize,
}
impl<T> CircularBuffer<T> {
/// Creates a new `CircularBuffer` with the specified capacity.
///
/// # Arguments
///
/// * `capacity` - The fixed size of the buffer
///
/// # Errors
///
/// Returns `BufError::InvalidCapacity` if capacity is 0
pub fn new(capacity: usize) -> Result<Self, BufError> {
if capacity == 0 {
return Err(BufError::InvalidCapacity);
}
let mut buffer = Vec::with_capacity(capacity);
buffer.resize_with(capacity, || None);
Ok(Self {
buffer,
read_pos: 0,
write_pos: 0,
size: capacity,
})
}
/// Pushes an item to the back of the buffer.
///
/// # Arguments
///
/// * `item` - The item to push
///
/// # Errors
///
/// Returns `BufError::BufFull` if the buffer is full
pub fn push(&mut self, item: T) -> Result<(), BufError> {
if self.is_full() {
return Err(BufError::BufFull(self.size));
}
self.buffer[self.write_pos] = Some(item);
self.write_pos = (self.write_pos + 1) % self.size;
Ok(())
}
/// Removes and returns the first item in the buffer.
///
/// # Returns
///
/// * `Some(T)` - The first item if the buffer is not empty
/// * `None` - If the buffer is empty
pub fn pop(&mut self) -> Option<T> {
if self.is_empty() {
return None;
}
let item = self.buffer[self.read_pos].take();
self.read_pos = (self.read_pos + 1) % self.size;
item
}
/// Returns a reference to the first item without removing it.
///
/// # Returns
///
/// * `Some(&T)` - Reference to the first item if buffer is not empty
/// * `None` - If the buffer is empty
pub fn peek(&self) -> Option<&T> {
self.buffer.get(self.read_pos).unwrap_or(&None).as_ref()
}
/// Checks if the buffer is at full capacity.
pub fn is_full(&self) -> bool {
self.available() == self.size
}
/// Checks if the buffer is empty.
pub fn is_empty(&self) -> bool {
self.available() == 0
}
/// Returns the total capacity of the buffer.
pub fn capacity(&self) -> usize {
self.size
}
/// Returns the current number of elements in the buffer
pub fn len(&self) -> usize {
self.available()
}
/// Clears the buffer, removing all elements
pub fn clear(&mut self) {
self.buffer.clear();
self.read_pos = 0;
self.write_pos = 0;
}
/// Returns the number of elements currently in the buffer
pub fn available(&self) -> usize {
if self.write_pos >= self.read_pos {
self.write_pos - self.read_pos
} else {
self.size - (self.read_pos - self.write_pos)
}
}
/// Returns the amount of free space in the buffer
pub fn free_space(&self) -> usize {
self.size - self.available()
}
/// Returns an iterator over references to the elements in the buffer.
pub fn iter(&self) -> impl Iterator<Item = &T> {
self.buffer.iter().filter_map(|x| x.as_ref())
}
/// Attempts to extend the buffer with elements from an iterator
pub fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) -> Result<(), BufError> {
for item in iter {
self.push(item)?;
}
Ok(())
}
/// Gets a reference to the element at the specified index.
///
/// # Arguments
///
/// * `index` - The index of the element to retrieve
///
/// # Returns
///
/// * `Some(&T)` - Reference to the element if index is valid
/// * `None` - If index is out of bounds
pub fn get(&self, index: usize) -> Option<&T> {
if index >= self.len() {
return None;
}
let actual_index = (self.read_pos + index) % self.size;
self.buffer[actual_index].as_ref()
}
/// Overwrites the oldest element in the buffer with a new item.
///
/// If the buffer is full, the read position is adjusted to maintain
/// the circular nature of the buffer.
///
/// # Arguments
///
/// * `item` - The item to write
pub fn overwrite(&mut self, item: T) {
self.buffer[self.write_pos] = Some(item);
self.write_pos = (self.write_pos + 1) % self.size;
if self.is_full() {
self.read_pos = self.write_pos;
}
}
/// Rotates the buffer left by n positions
pub fn rotate_left(&mut self, n: usize) {
if self.is_empty() || n == 0 {
return;
}
self.read_pos = (self.read_pos + n) % self.size;
self.write_pos = (self.write_pos + n) % self.size;
}
/// Rotates the buffer right by n positions
pub fn rotate_right(&mut self, n: usize) {
if self.is_empty() || n == 0 {
return;
}
self.read_pos = (self.size + self.read_pos - n) % self.size;
self.write_pos = (self.size + self.write_pos - n) % self.size;
}
/// Removes and returns the element at index while preserving order
pub fn remove(&mut self, index: usize) -> Option<T> {
if index >= self.available() {
return None;
}
let actual_index = (self.read_pos + index) % self.size;
let item = self.buffer[actual_index].take();
// Shift elements
for i in actual_index..self.write_pos {
self.buffer[i] = self.buffer[(i + 1) % self.size].take();
}
self.write_pos = (self.size + self.write_pos - 1) % self.size;
item
}
}
impl<T: Clone> CircularBuffer<T> {
/// Returns two vectors containing the buffer's contents
/// The first vector contains elements from read_pos to the end
/// The second vector contains any remaining elements from start to write_pos
pub fn as_slices(&self) -> (Vec<T>, Vec<T>) {
if self.is_empty() {
return (Vec::new(), Vec::new());
}
let buf: Vec<T> = self.iter().cloned().collect();
if self.write_pos <= self.read_pos {
// Data wraps around
// First slice: from read_pos to end
// Second slice: from start to write_pos
(
buf[self.read_pos..].to_vec(),
buf[..self.write_pos].to_vec(),
)
} else {
// Data is contiguous
// First slice: from read_pos to write_pos
// Second slice: empty
(buf[self.read_pos..self.write_pos].to_vec(), Vec::new())
}
}
}
impl<T> Default for CircularBuffer<T> {
fn default() -> Self {
Self::new(16).expect("This message physically cannot be shown")
}
}
impl<T> IntoIterator for CircularBuffer<T> {
type Item = T;
type IntoIter = std::vec::IntoIter<T>;
fn into_iter(self) -> Self::IntoIter {
self.buffer
.into_iter()
.filter_map(|x| x)
.collect::<Vec<_>>()
.into_iter()
}
}
impl<T> FromIterator<T> for CircularBuffer<T> {
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
let iter = iter.into_iter();
let (lower, _) = iter.size_hint();
let mut buffer =
CircularBuffer::new(lower.max(16)).expect("Failed to create buffer from iterator");
for item in iter {
buffer.push(item).ok();
}
buffer
}
}
impl<T> Index<usize> for CircularBuffer<T> {
type Output = Option<T>;
fn index(&self, index: usize) -> &Self::Output {
&self.buffer[index]
}
}
impl<T> IndexMut<usize> for CircularBuffer<T> {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.buffer[index]
}
}
/// Error types for buffer operations
#[derive(Debug)]
pub enum BufError {
/// Buffer is full, contains the capacity
BufFull(usize),
/// Attempted to create buffer with invalid capacity
InvalidCapacity,
/// Other buffer-related errors with description
Other(String),
}
impl Error for BufError {}
impl Display for BufError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::BufFull(cap) => write!(f, "Buffer is full. Capacity: {}", cap),
Self::InvalidCapacity => write!(f, "Requested capacity is invalid"),
Self::Other(message) => write!(f, "An unknown error occurred: {}", message),
}
}
}
}
/// Module providing various list type containers
pub mod list {
/// Module for sorting containers
pub mod sorted {
use std::{
ops::{Index, IndexMut},
random,
};
/// A list that maintains its elements in sorted order according to a provided sorting function
pub struct SortedList<T> {
pub list: Vec<T>,
sort: Box<dyn Fn(&[T]) -> Vec<T>>,
}
impl<T> SortedList<T> {
/// Creates a new SortedList with the specified sorting function
pub fn new(sort_function: impl Fn(&[T]) -> Vec<T> + 'static) -> Self {
Self {
list: Vec::new(),
sort: Box::new(sort_function),
}
}
/// Adds an item to the list and sorts it according to the sorting function
pub fn push(&mut self, item: T) {
self.list.push(item);
self.list = (self.sort)(&self.list);
}
/// Removes and returns the last element from the list, then re-sorts
pub fn pop(&mut self) -> Option<T> {
let out = self.list.pop();
self.list = (self.sort)(&self.list);
out
}
/// Adds an item to the list without sorting
pub fn push_no_sort(&mut self, item: T) {
self.list.push(item);
}
/// Removes and returns the last element from the list without sorting
pub fn pop_no_sort(&mut self) -> Option<T> {
self.list.pop()
}
/// Manually triggers a sort of the list
pub fn man_sort(&mut self) {
self.list = (self.sort)(&self.list);
}
/// Returns a reference to the element at the specified index
pub fn get(&self, index: usize) -> Option<&T> {
self.list.get(index)
}
/// Changes the sorting function used by the list
pub fn set_sort(&mut self, sort_function: impl Fn(&[T]) -> Vec<T> + 'static) {
self.sort = Box::new(sort_function);
}
}
impl<T> Index<usize> for SortedList<T> {
type Output = T;
fn index(&self, index: usize) -> &Self::Output {
&self.list[index]
}
}
impl<T> IndexMut<usize> for SortedList<T> {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
&mut self.list[index]
}
}
pub struct DefaultSorts;
impl DefaultSorts {
/// Returns a sorting function that sorts elements in descending order
pub fn descending<T: Ord + Clone>() -> impl Fn(&[T]) -> Vec<T> {
|slice: &[T]| {
let mut vec = slice.to_vec();
vec.sort_by(|a, b| b.cmp(a));
vec
}
}
/// Returns a sorting function that sorts elements in ascending order
pub fn ascending<T: Ord + Clone>() -> impl Fn(&[T]) -> Vec<T> {
|slice: &[T]| {
let mut vec = slice.to_vec();
vec.sort_by(|a, b| a.cmp(b));
vec
}
}
/// Returns a sorting function that randomly shuffles elements
pub fn random<T: Ord + Clone>() -> impl Fn(&[T]) -> Vec<T> {
move |slice: &[T]| {
let mut vec = slice.to_vec();
vec.sort_by(|a, b| {
// Get the memory addresses of elements and use them as a source of randomness
let addr_a = (a as *const T) as usize;
let addr_b = (b as *const T) as usize;
// XOR with some prime numbers to distribute values better
let mut hash_a = addr_a.wrapping_mul(2654435761);
let mut hash_b = addr_b.wrapping_mul(2654435761);
hash_a = hash_a
.checked_add(random::random::<usize>())
.unwrap_or(hash_a);
hash_b = hash_b
.checked_add(random::random::<usize>())
.unwrap_or(hash_b);
// Use the difference to determine ordering
if hash_a < hash_b {
std::cmp::Ordering::Less
} else if hash_a > hash_b {
std::cmp::Ordering::Greater
} else {
std::cmp::Ordering::Equal
}
});
vec
}
}
}
}
}