fluffl/
collections.rs

1use serde::{Deserialize, Serialize};
2use std::fmt::Display;
3
4//custom data structures I've written for various purposes
5pub mod binary_tree;
6pub mod bitarray;
7pub mod fixed_stack;
8pub mod flat_nary_tree;
9pub mod linked_list;
10pub mod nary_forest;
11pub mod segment_tree;
12
13
14/// ## Description
15/// The Official Pseudo Pointer type for this module
16/// ### comments
17/// - Most of the collections are vector-based or 'arena based' because they are:
18///     - Easy to serialize
19///     - Cache local
20///     - less likely to segfault when bounds checks are off
21///     - easier to implement
22#[derive(Copy, Clone, PartialEq, Debug, Hash, Eq, Serialize, Deserialize)]
23pub struct Ptr {
24    idx: u64,
25}
26impl Ptr {
27    pub fn as_usize(&self) -> usize {
28        self.idx as usize
29    }
30
31    pub const fn null() -> Self {
32        Self { idx: !0 }
33    }
34
35    pub fn is_null(&self) -> bool {
36        *self == Self::null()
37    }
38}
39impl Default for Ptr {
40    fn default() -> Self {
41        Self::null()
42    }
43}
44impl From<usize> for Ptr {
45    fn from(idx: usize) -> Self {
46        Self { idx: idx as u64 }
47    }
48}
49
50impl Display for Ptr {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        write!(f, "{}", self.idx)
53    }
54}
55
56impl<T> std::ops::Index<Ptr> for Vec<T> {
57    type Output = T;
58    fn index(&self, index: Ptr) -> &Self::Output {
59        &self[index.as_usize()]
60    }
61}
62
63impl<T> std::ops::IndexMut<Ptr> for Vec<T> {
64    fn index_mut(&mut self, index: Ptr) -> &mut Self::Output {
65        &mut self[index.as_usize()]
66    }
67}
68
69impl<T> std::ops::Add<T> for Ptr
70where
71    i64: From<T>,
72{
73    type Output = Self;
74    fn add(self, rhs: T) -> Self::Output {
75        Self {
76            idx: self.idx + i64::from(rhs) as u64,
77        }
78    }
79}
80
81impl<T> std::ops::AddAssign<T> for Ptr
82where
83    i64: From<T>,
84{
85    fn add_assign(&mut self, rhs: T) {
86        self.idx += i64::from(rhs) as u64;
87    }
88}