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
#![allow(unused, dead_code)]

use std::cell::{Cell, RefCell};
use std::cmp::PartialEq;
use std::fmt;
use std::iter::FromIterator;
use std::iter::IntoIterator;
use std::rc::Rc;

// === MACRO SECTION ===
//
#[macro_export]
macro_rules! arraylist {
    () => {
    {
         let al = ArrayList::default();
         al
    }
    };
    ($($x:expr), *) => {{
        let al = ArrayList::new();
        $(al.push($x);) *
        al
    }};
}

#[macro_export]
macro_rules! remove {
    ($x: expr, $y: expr) => {
        for (ind, val) in $x.to_vec().iter().enumerate() {
            if *val == $y {
                $x.remove(ind);
                break;
            }
        }
    };
}

#[macro_export]
macro_rules! for_each {
    ($x: expr, $y: expr) => {
        ArrayList::start_with(&$x.into_iter().map($y).collect::<Vec<_>>());
    };
}
//
// === END OF MACRO SECTION ===

#[derive(Debug, Copy, Clone, PartialEq)]
struct ArrayListParams {
    count: usize,
    len: usize,
    capacity: usize,
}

impl Default for ArrayListParams {
    fn default() -> Self {
        Self::new(0, 0, 0)
    }
}

impl ArrayListParams {
    fn new(count: usize, len: usize, capacity: usize) -> Self {
        Self {
            count,
            len,
            capacity,
        }
    }

    fn update(&mut self, count: usize, len: usize, cap: usize) {
        self.count = count;
        self.len = len;
        self.capacity = cap;
    }
}

#[derive(Debug, PartialEq)]
pub struct ArrayList<T> {
    vec: Rc<RefCell<Vec<T>>>,
    count: Cell<ArrayListParams>,
}

impl<T: std::fmt::Debug + Clone + PartialEq> Default for ArrayList<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: std::fmt::Debug + Clone + PartialEq> ArrayList<T> {
    pub fn new() -> Self {
        ArrayList {
            vec: Rc::new(RefCell::new(vec![])),
            count: Cell::new(ArrayListParams::new(0, 0, 0)),
        }
    }

    pub fn start_with(collection: &[T]) -> Self {
        ArrayList {
            vec: Rc::new(RefCell::new(collection.to_vec())),
            count: Cell::new(ArrayListParams::new(
                // count, len, capacity
                collection.len(),
                collection.len(),
                collection.to_vec().capacity(),
            )),
        }
    }

    fn update_count(&self) -> ArrayListParams {
        let ncounter = self.vec.borrow().len();
        let mut new_array_list_count = self.count.get();
        new_array_list_count.update(ncounter, ncounter, self.vec.borrow().capacity());
        new_array_list_count
    }

    pub fn push(&self, value: T) -> bool {
        self.vec.borrow_mut().push(value);
        self.count.set(self.update_count());
        true
    }

    pub fn push_on_index(&self, index: usize, value: T) {
        let arr = &self.vec.borrow().clone()[index..].to_vec();
        self.vec.borrow_mut()[index] = value;
        let ori = self.vec.borrow()[..=index].to_vec();
        self.vec.borrow_mut().clear();
        self.vec.borrow_mut().extend(ori);
        self.vec.borrow_mut().extend(arr.clone());
        self.count.set(self.update_count());
    }

    pub fn insert(&self, index: usize, value: T) {
        self.vec.borrow_mut().insert(index, value);
        self.count.set(self.update_count());
    }

    pub fn add_all(&self, collection: &[T]) {
        self.vec.borrow_mut().extend(collection.to_vec());
        self.count.set(self.update_count());
    }

    fn add_all_at_start(&self, collection: &[T]) {
        for (idx, val) in collection.iter().enumerate() {
            self.insert(idx, val.clone())
        }
        self.count.set(self.update_count());
    }

    pub fn add_all_at_index(&self, idx: usize, collection: &[T]) {
        if idx == 0 {
            self.add_all_at_start(collection);
        } else if idx <= self.len() {
            let mut counter = idx;

            for val in collection.iter() {
                self.insert(counter, val.clone());
                counter += 1;
            }
        } else {
            panic!("Invalid Index {:?}", self.vec.borrow());
        }
        self.count.set(self.update_count());
    }

    pub fn replace(&self, index: usize, value: T) {
        self.vec.borrow_mut()[index] = value;
    }

    pub fn clear(&self) {
        self.vec.borrow_mut().clear();
        self.count.set(ArrayListParams::default());
    }

    pub fn clone(&self) -> Self {
        ArrayList {
            vec: Rc::new(RefCell::new(self.vec.borrow().clone())),
            count: Cell::new(self.count.get()),
        }
    }

    pub fn copy(&self) -> &Self {
        self
    }

    pub fn add(&mut self, value: T) -> &mut Self {
        self.push(value);
        self
    }

    pub fn finish(&self) -> Self {
        Self {
            vec: self.vec.clone(),
            count: Cell::new(self.count.get()),
        }
    }

    pub fn ensure_capacity(size: usize) -> Self {
        Self {
            vec: Rc::new(RefCell::new(Vec::with_capacity(size))),
            count: Cell::new(ArrayListParams::new(0, 0, size)),
        }
    }

    pub fn contains(&self, value: T) -> bool {
        self.vec.borrow().contains(&value)
    }

    pub fn cap(&self) -> usize {
        self.count.set(self.update_count());
        self.vec.borrow().capacity()
    }

    pub fn len(&self) -> usize {
        self.vec.borrow().len()
    }

    pub fn size(&self) -> usize {
        self.vec.borrow().len()
    }

    pub fn is_empty(&self) -> bool {
        self.vec.borrow().is_empty()
    }

    pub fn pop(&self) -> Option<T> {
        let result = self.vec.borrow_mut().pop();
        self.count.set(self.update_count());
        result
    }

    pub fn remove(&self, index: usize) -> T {
        let result = self.vec.borrow_mut().remove(index);
        self.count.set(self.update_count());
        result
    }

    pub fn remove_if(&self, f: fn(T) -> bool) {
        let result = self
            .vec
            .borrow_mut()
            .clone()
            .into_iter()
            .filter(|a| !f(a.clone()))
            .collect::<Vec<_>>();
        self.clear();
        self.add_all(&result);
    }

    pub fn to_vec(&self) -> Vec<T> {
        self.vec.borrow().clone().into_iter().collect::<Vec<_>>()
    }

    pub fn from_slice(collection: &[T]) -> Self {
        ArrayList::start_with(collection)
    }

    pub fn for_each(&self, f: fn(T)) {
        let result = self.vec.borrow_mut().clone().into_iter().for_each(f);
    }

    pub fn get(&self, index: usize) -> Option<T> {
        if index > self.vec.borrow().len() {
            return None;
        }
        Some(self.vec.borrow()[index].clone())
    }

    pub fn sub_list(&self, start: usize, stop: usize) -> Option<ArrayList<T>> {
        if !(start <= stop && stop <= self.len()) {
            return None;
        }

        let sub_list = ArrayList::new();
        for ind in start..stop {
            sub_list
                .vec
                .borrow_mut()
                .push(self.vec.borrow()[ind].clone());
        }

        sub_list.count.set(sub_list.update_count());

        Some(sub_list)
    }

    pub fn index_of(&self, value: T) -> Option<usize> {
        if self.contains(value.clone()) {
            for (ind, val) in self.vec.borrow().iter().enumerate() {
                if *val == value {
                    return Some(ind);
                }
            }
        }
        None
    }

    pub fn index_of_all(&self, value: T) -> Vec<usize> {
        self.clone()
            .into_iter()
            .enumerate()
            .map(|a| if a.1 == value { a.0 as i32 } else { -1 })
            .filter(|a| *a != -1)
            .map(|a| a as usize)
            .collect::<Vec<_>>()
    }

    pub fn index_in(&self, value: usize) -> Option<T> {
        self.get(value)
    }

    pub fn print(&self) {
        println!("{:?}", self.vec.borrow());
    }
} // end of ArrayList Implementation

impl<T: std::fmt::Display + Clone> fmt::Display for ArrayList<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "[{}]",
            self.vec
                .borrow()
                .clone()
                .into_iter()
                .map(|a| a.to_string())
                .collect::<Vec<String>>()
                .join(", ")
        )
    }
}

impl<T: Clone> IntoIterator for ArrayList<T> {
    type Item = T;
    type IntoIter = std::vec::IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.vec.borrow().clone().into_iter()
    }
}

impl<T: Clone + PartialEq + std::fmt::Debug> FromIterator<T> for ArrayList<T> {
    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
        let ns = arraylist![];
        for val in iter {
            ns.push(val);
        }
        ns
    }
}

#[cfg(test)]
mod tests;