tesap_std/
vector.rs

1use std::fmt::Display;
2use std::ptr;
3use std::ops::{Index, IndexMut};
4use std::ops::{Deref, DerefMut};
5use crate::chunks as my;
6
7#[derive(Debug)]
8pub struct Vector<T: Display + Clone> {
9    data: my::Chunks<T>,
10    pub len: usize,
11}
12
13
14impl<T: Display + Clone + Copy> Vector<T> {
15    // Constructor
16    pub fn new_copy(value: T, len: usize) -> Self {
17        // Allocate at least something
18        let capacity = if len > 0 { len } else { 1 };
19
20        let chunks = my::Chunks::filled_copy(value, capacity);
21        Vector {
22            data: chunks,
23            len: len
24        }
25    }
26
27    // Constructor
28    pub fn from_slice_copy(from: &[T]) -> Self {
29        Self {
30            data: my::Chunks::from_slice_copy(from),
31            len: from.len()
32        }
33    }
34
35}
36
37impl<T: Display + Clone> Vector<T> {
38    pub fn new() -> Self {
39        Self {
40            data: my::Chunks::alloc(1),
41            len: 0
42        }
43    }
44
45    // Constructor
46    pub fn new_clone(value: T, len: usize) -> Self {
47        // Allocate at least something
48        let capacity = if len > 0 { len } else { 1 };
49
50        let chunks: my::Chunks<T> = my::Chunks::filled_clone(value, capacity);
51        Self {
52            data: chunks,
53            len: len
54        }
55    }
56
57    // Constructor
58    pub fn from_slice_clone(from: &[T]) -> Self {
59        Self {
60            data: my::Chunks::from_slice_clone(from),
61            len: from.len()
62        }
63    }
64
65    // Constructor
66    pub fn from_raw_parts(ptr: *mut T, len: usize, capacity: usize) -> Self {
67        Self {
68            data: my::Chunks {
69                ptr: ptr,
70                count: capacity,
71            },
72            len: len
73        }
74    }
75
76    pub fn len_bytes(&self) -> usize {
77        self.len * size_of::<T>()
78    }
79
80    pub fn as_ptr(&self) -> *const T {
81        self.data.as_ptr()
82    }
83
84    pub fn as_mut_ptr(&self) -> *mut T {
85        self.data.as_mut_ptr()
86    }
87
88    pub fn as_slice(&self) -> &[T] {
89        // Does it have overhead?
90        // &self.data.as_slice()[0..self.len]
91
92        // Works also. Is it better?
93        // self.as_mut_slice() as &[T]
94
95        unsafe {
96            std::slice::from_raw_parts(
97                self.as_ptr(),
98                // Bound by len, not by data.count
99                self.len
100            )
101        }
102    }
103
104    pub fn as_mut_slice(&mut self) -> &mut [T] {
105        unsafe {
106            std::slice::from_raw_parts_mut(
107                self.as_mut_ptr(),
108                // Bound by len, not by data.count
109                self.len
110            )
111        }
112    }
113
114    pub fn push(&mut self, elem: T) -> bool {
115        if self.len == self.data.count {
116            self.data.grow(1);
117        }
118
119        self.data.write_index(self.len, elem);
120        self.len += 1;
121        true
122    }
123
124    pub fn insert(&mut self, index: usize, elem: T) -> bool {
125        if self.len <= index {
126            return false;
127        }
128
129        if self.len == self.data.count {
130            self.data.grow(self.grow_strategy());
131        }
132
133        // TODO Safety: ?
134        // TODO Why it introduces overhead if used in append()?
135        unsafe {
136            ptr::copy(
137                &mut self.data[index],
138                &mut self.data[index + 1],
139                self.len - index,
140            );
141        }
142
143        // self.data[index] = elem;
144        self.data.write_index(index, elem);
145        self.len += 1;
146        true
147    }
148
149    pub fn pop(&mut self) -> Option<T> {
150        if self.len > 0 {
151            self.len -= 1;
152            // Interesting: we can copy by reference, this is done automatically by compiler
153            // (bad design!)
154            Some(self.data[self.len].clone())
155        } else {
156            None
157        }
158    }
159
160    pub fn capacity(&self) -> usize {
161        self.data.count
162    }
163
164    // ===== Private =====
165
166    fn bounds(&self, index: usize) -> bool {
167        // TODO Turn BOUNDS_CHECK off for self.data
168        0 <= index && index < self.len
169    }
170
171    /// Given the current capacity & size of an elem, returns new capacity to grow by
172    fn grow_strategy(&self) -> usize {
173        match self.capacity() {
174            0..3 => 4,
175            _ => self.capacity() * 2
176        }
177    }
178}
179
180// ======== CONSEC ========
181
182pub trait ConsecConstrucor {
183    fn consec(len: usize) -> Self;
184}
185
186impl<T: Display + From<usize> + Clone> ConsecConstrucor for Vector<T> {
187    // Constructor
188    fn consec(len: usize) -> Self {
189        let mut obj = Self {
190            data: my::Chunks::alloc(len),
191            len: len
192        };
193
194        for i in 0..len {
195            // non-primitive cast: `usize` as `T`
196            // Why does it occur?
197            // obj[i] = (i + 1) as T;
198            obj[i] = T::from(i + 1);
199        }
200        obj
201    }
202}
203
204// ======== INDEX ========
205
206impl<
207    T: Display + Clone,
208> Index<usize> for Vector<T> {
209    type Output = T;
210
211    fn index(&self, index: usize) -> &Self::Output {
212        if !self.bounds(index) {
213            panic!("Index out of bounds");
214        }
215
216        self.data.index(index)
217    }
218}
219
220impl<
221    T: Display + Clone,
222> IndexMut<usize> for Vector<T> {
223    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
224        if !self.bounds(index) {
225            panic!("Index out of bounds");
226        }
227
228        self.data.index_mut(index)
229    }
230}
231
232// ======== DEREF ========
233// Automatically implements iter(). How it works?
234
235impl<T: Display + Clone> Deref for Vector<T> {
236    type Target = [T];
237
238    fn deref(&self) -> &[T] {
239        self.as_slice()
240    }
241}
242
243impl<T: Display + Clone> DerefMut for Vector<T> {
244    fn deref_mut(&mut self) -> &mut [T] {
245        self.as_mut_slice()
246    }
247}
248
249// ======== ITERATOR ========
250
251impl<T: Display + Clone> FromIterator<T> for Vector<T> {
252    fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> Self {
253        let mut c = Self::new();
254
255        for i in iter {
256            c.push(i);
257        }
258
259        c
260    }
261}