hex_renderer/pattern_utils/
dynamic_list.rs

1use std::mem;
2
3pub struct DynamicList<T> {
4    lower_bound: i32,
5    contents: Vec<Option<T>>,
6}
7
8const DEFAULT_BOUND: i32 = 10;
9impl<T> DynamicList<T> {
10    pub fn new() -> DynamicList<T> {
11        let mut contents = Vec::new();
12        for _ in 0..DEFAULT_BOUND * 2 {
13            contents.push(None);
14        }
15        DynamicList {
16            lower_bound: -DEFAULT_BOUND,
17            contents,
18        }
19    }
20    pub fn set(&mut self, index: i32, val: T) {
21        let upper_bound = self.lower_bound + self.contents.len() as i32;
22        let offset_index = (index - self.lower_bound) as usize;
23
24        if index >= self.lower_bound && index < upper_bound {
25            self.contents[offset_index] = Some(val);
26        } else if index < self.lower_bound {
27            let mut old_contents = Vec::new();
28
29            mem::swap(&mut old_contents, &mut self.contents);
30
31            let new_bound = index - DEFAULT_BOUND;
32            for _ in 0..self.lower_bound - new_bound {
33                self.contents.push(None);
34            }
35            self.lower_bound = new_bound;
36
37            for item in old_contents {
38                self.contents.push(item);
39            }
40
41            self.contents[(index - self.lower_bound) as usize] = Some(val);
42        } else {
43            for _ in 0..index - upper_bound + DEFAULT_BOUND {
44                self.contents.push(None);
45            }
46            self.contents[offset_index] = Some(val);
47        }
48    }
49    pub fn get(&self, index: i32) -> &Option<T> {
50        let offset_index = (index - self.lower_bound) as usize;
51
52        if offset_index >= self.contents.len() {
53            &None
54        } else {
55            &self.contents[offset_index]
56        }
57    }
58    pub fn into_vector(self) -> Vec<T> {
59        self.contents.into_iter().flatten().collect()
60    }
61}