arraylist/
arl.rs

1#![allow(unused, dead_code)]
2
3use std::cell::{Cell, RefCell};
4use std::cmp::PartialEq;
5use std::fmt;
6use std::iter::FromIterator;
7use std::iter::IntoIterator;
8use std::rc::Rc;
9
10// === MACRO SECTION ===
11//
12#[macro_export]
13macro_rules! arraylist {
14    () => {
15    {
16         let al = ArrayList::default();
17         al
18    }
19    };
20    ($($x:expr), *) => {{
21        let al = ArrayList::new();
22        $(al.push($x);) *
23        al
24    }};
25}
26
27#[macro_export]
28macro_rules! remove {
29    ($x: expr, $y: expr) => {
30        for (ind, val) in $x.to_vec().iter().enumerate() {
31            if *val == $y {
32                $x.remove(ind);
33                break;
34            }
35        }
36    };
37}
38
39#[macro_export]
40macro_rules! for_each {
41    ($x: expr, $y: expr) => {
42        ArrayList::start_with(&$x.into_iter().map($y).collect::<Vec<_>>());
43    };
44}
45//
46// === END OF MACRO SECTION ===
47
48#[derive(Debug, Copy, Clone, PartialEq)]
49struct ArrayListParams {
50    count: usize,
51    len: usize,
52    capacity: usize,
53}
54
55impl Default for ArrayListParams {
56    fn default() -> Self {
57        Self::new(0, 0, 0)
58    }
59}
60
61impl ArrayListParams {
62    fn new(count: usize, len: usize, capacity: usize) -> Self {
63        Self {
64            count,
65            len,
66            capacity,
67        }
68    }
69
70    fn update(&mut self, count: usize, len: usize, cap: usize) {
71        self.count = count;
72        self.len = len;
73        self.capacity = cap;
74    }
75}
76
77#[derive(Debug, PartialEq)]
78pub struct ArrayList<T> {
79    vec: Rc<RefCell<Vec<T>>>,
80    count: Cell<ArrayListParams>,
81}
82
83impl<T: std::fmt::Debug + Clone + PartialEq> Default for ArrayList<T> {
84    fn default() -> Self {
85        Self::new()
86    }
87}
88
89impl<T: std::fmt::Debug + Clone + PartialEq> ArrayList<T> {
90    pub fn new() -> Self {
91        ArrayList {
92            vec: Rc::new(RefCell::new(vec![])),
93            count: Cell::new(ArrayListParams::new(0, 0, 0)),
94        }
95    }
96
97    pub fn start_with(collection: &[T]) -> Self {
98        ArrayList {
99            vec: Rc::new(RefCell::new(collection.to_vec())),
100            count: Cell::new(ArrayListParams::new(
101                // count, len, capacity
102                collection.len(),
103                collection.len(),
104                collection.to_vec().capacity(),
105            )),
106        }
107    }
108
109    fn update_count(&self) -> ArrayListParams {
110        let ncounter = self.vec.borrow().len();
111        let mut new_array_list_count = self.count.get();
112        new_array_list_count.update(ncounter, ncounter, self.vec.borrow().capacity());
113        new_array_list_count
114    }
115
116    pub fn push(&self, value: T) -> bool {
117        self.vec.borrow_mut().push(value);
118        self.count.set(self.update_count());
119        true
120    }
121
122    pub fn push_on_index(&self, index: usize, value: T) {
123        let arr = &self.vec.borrow().clone()[index..].to_vec();
124        self.vec.borrow_mut()[index] = value;
125        let ori = self.vec.borrow()[..=index].to_vec();
126        self.vec.borrow_mut().clear();
127        self.vec.borrow_mut().extend(ori);
128        self.vec.borrow_mut().extend(arr.clone());
129        self.count.set(self.update_count());
130    }
131
132    pub fn insert(&self, index: usize, value: T) {
133        self.vec.borrow_mut().insert(index, value);
134        self.count.set(self.update_count());
135    }
136
137    pub fn add_all(&self, collection: &[T]) {
138        self.vec.borrow_mut().extend(collection.to_vec());
139        self.count.set(self.update_count());
140    }
141
142    fn add_all_at_start(&self, collection: &[T]) {
143        for (idx, val) in collection.iter().enumerate() {
144            self.insert(idx, val.clone())
145        }
146        self.count.set(self.update_count());
147    }
148
149    pub fn add_all_at_index(&self, idx: usize, collection: &[T]) {
150        if idx == 0 {
151            self.add_all_at_start(collection);
152        } else if idx <= self.len() {
153            let mut counter = idx;
154
155            for val in collection.iter() {
156                self.insert(counter, val.clone());
157                counter += 1;
158            }
159        } else {
160            panic!("Invalid Index {:?}", self.vec.borrow());
161        }
162        self.count.set(self.update_count());
163    }
164
165    pub fn replace(&self, index: usize, value: T) {
166        self.vec.borrow_mut()[index] = value;
167    }
168
169    pub fn clear(&self) {
170        self.vec.borrow_mut().clear();
171        self.count.set(ArrayListParams::default());
172    }
173
174    pub fn clone(&self) -> Self {
175        ArrayList {
176            vec: Rc::new(RefCell::new(self.vec.borrow().clone())),
177            count: Cell::new(self.count.get()),
178        }
179    }
180
181    pub fn copy(&self) -> &Self {
182        self
183    }
184
185    pub fn add(&mut self, value: T) -> &mut Self {
186        self.push(value);
187        self
188    }
189
190    pub fn finish(&self) -> Self {
191        Self {
192            vec: self.vec.clone(),
193            count: Cell::new(self.count.get()),
194        }
195    }
196
197    pub fn ensure_capacity(size: usize) -> Self {
198        Self {
199            vec: Rc::new(RefCell::new(Vec::with_capacity(size))),
200            count: Cell::new(ArrayListParams::new(0, 0, size)),
201        }
202    }
203
204    pub fn contains(&self, value: T) -> bool {
205        self.vec.borrow().contains(&value)
206    }
207
208    pub fn cap(&self) -> usize {
209        self.count.set(self.update_count());
210        self.vec.borrow().capacity()
211    }
212
213    pub fn len(&self) -> usize {
214        self.vec.borrow().len()
215    }
216
217    pub fn size(&self) -> usize {
218        self.vec.borrow().len()
219    }
220
221    pub fn is_empty(&self) -> bool {
222        self.vec.borrow().is_empty()
223    }
224
225    pub fn pop(&self) -> Option<T> {
226        let result = self.vec.borrow_mut().pop();
227        self.count.set(self.update_count());
228        result
229    }
230
231    pub fn remove(&self, index: usize) -> T {
232        let result = self.vec.borrow_mut().remove(index);
233        self.count.set(self.update_count());
234        result
235    }
236
237    pub fn remove_if(&self, f: fn(T) -> bool) {
238        let result = self
239            .vec
240            .borrow_mut()
241            .clone()
242            .into_iter()
243            .filter(|a| !f(a.clone()))
244            .collect::<Vec<_>>();
245        self.clear();
246        self.add_all(&result);
247    }
248
249    pub fn to_vec(&self) -> Vec<T> {
250        self.vec.borrow().clone().into_iter().collect::<Vec<_>>()
251    }
252
253    pub fn from_slice(collection: &[T]) -> Self {
254        ArrayList::start_with(collection)
255    }
256
257    pub fn for_each(&self, f: fn(T)) {
258        let result = self.vec.borrow_mut().clone().into_iter().for_each(f);
259    }
260
261    pub fn get(&self, index: usize) -> Option<T> {
262        if index > self.vec.borrow().len() {
263            return None;
264        }
265        Some(self.vec.borrow()[index].clone())
266    }
267
268    pub fn sub_list(&self, start: usize, stop: usize) -> Option<ArrayList<T>> {
269        if !(start <= stop && stop <= self.len()) {
270            return None;
271        }
272
273        let sub_list = ArrayList::new();
274        for ind in start..stop {
275            sub_list
276                .vec
277                .borrow_mut()
278                .push(self.vec.borrow()[ind].clone());
279        }
280
281        sub_list.count.set(sub_list.update_count());
282
283        Some(sub_list)
284    }
285
286    pub fn index_of(&self, value: T) -> Option<usize> {
287        if self.contains(value.clone()) {
288            for (ind, val) in self.vec.borrow().iter().enumerate() {
289                if *val == value {
290                    return Some(ind);
291                }
292            }
293        }
294        None
295    }
296
297    pub fn index_of_all(&self, value: T) -> Vec<usize> {
298        self.clone()
299            .into_iter()
300            .enumerate()
301            .map(|a| if a.1 == value { a.0 as i32 } else { -1 })
302            .filter(|a| *a != -1)
303            .map(|a| a as usize)
304            .collect::<Vec<_>>()
305    }
306
307    pub fn index_in(&self, value: usize) -> Option<T> {
308        self.get(value)
309    }
310
311    pub fn print(&self) {
312        println!("{:?}", self.vec.borrow());
313    }
314} // end of ArrayList Implementation
315
316impl<T: std::fmt::Display + Clone> fmt::Display for ArrayList<T> {
317    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
318        write!(
319            f,
320            "[{}]",
321            self.vec
322                .borrow()
323                .clone()
324                .into_iter()
325                .map(|a| a.to_string())
326                .collect::<Vec<String>>()
327                .join(", ")
328        )
329    }
330}
331
332impl<T: Clone> IntoIterator for ArrayList<T> {
333    type Item = T;
334    type IntoIter = std::vec::IntoIter<T>;
335
336    fn into_iter(self) -> Self::IntoIter {
337        self.vec.borrow().clone().into_iter()
338    }
339}
340
341impl<T: Clone + PartialEq + std::fmt::Debug> FromIterator<T> for ArrayList<T> {
342    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
343        let ns = arraylist![];
344        for val in iter {
345            ns.push(val);
346        }
347        ns
348    }
349}
350
351#[cfg(test)]
352mod tests;