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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
use std::marker::PhantomData;
use std::ops::{Index, IndexMut};
use std::ptr;

use fera_fun::vec;

// TODO: Should Array be called AbstractArray (https://en.wikipedia.org/wiki/Array_data_type)?
/// A simple trait for array like structs.
pub trait Array<T>: IndexMut<usize, Output = T> {
    /// Creates a new array with `n` repeated `value`.
    fn with_value(value: T, n: usize) -> Self
    where
        Self: Sized,
        T: Clone;

    /// Returns the number of elements in the array.
    fn len(&self) -> usize;

    /// Returns `true` if the array contains `value`, `false` otherwise.
    fn contains(&self, value: &T) -> bool
    where
        T: PartialEq,
    {
        for i in 0..self.len() {
            if unsafe { self.get_unchecked(i) } == value {
                return true;
            }
        }
        false
    }

    /// Returns `true` if the length of the array is 0, otherwise `false`.
    #[inline]
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns a reference to the element of the array at `index`, or `None` if the index is out
    /// of bounds.
    fn get(&self, index: usize) -> Option<&T> {
        if index < self.len() {
            Some(unsafe { self.get_unchecked(index) })
        } else {
            None
        }
    }

    /// Returns a mutable reference to the element of the array at `index`, or `None` if the index
    /// is out of bounds.
    fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        if index < self.len() {
            Some(unsafe { self.get_unchecked_mut(index) })
        } else {
            None
        }
    }

    /// Returns a reference to the element of the array at `index`, without doing bounds checking.
    unsafe fn get_unchecked(&self, index: usize) -> &T;

    /// Returns a mutable reference to the element of the array at `index`, without doing bounds
    /// checking.
    unsafe fn get_unchecked_mut(&mut self, index: usize) -> &mut T;

    // TODO: Allow each implementation to specify the iterator
    /// Returns a iterator over the array.
    fn iter(&self) -> Iter<T, Self>
    where
        Self: Sized,
    {
        Iter {
            cur: 0,
            len: self.len(),
            array: self,
            _marker: PhantomData,
        }
    }
}

/// A simple trait for a dynamic array like struct.
pub trait DynamicArray<T>: Array<T> {
    /// Creates a array with the specified capacity.
    ///
    /// The implementation is free to choose if the array can grow beyond this capacity or not.
    fn with_capacity(capacity: usize) -> Self
    where
        Self: Sized;

    /// Returns the capacity of the array.
    fn capacity(&self) -> usize;

    // TODO: see Vec docs and add some fundamentals methods, like shrink_to_fit, reserve_exact

    /// Change the length of the array.
    unsafe fn set_len(&mut self, len: usize);

    /// Reserve capacity for at least `additional` more elements.
    ///
    /// # Panics
    ///
    /// If the array cannot satisfy the request.
    ///
    /// The default implementation panics if `additional > (self.capacity() - self.len())`.
    #[inline]
    fn reserve(&mut self, additional: usize) {
        if additional > (self.capacity() - self.len()) {
            panic!(
                "cannot grow: cap {}, len {}, additional {}",
                self.capacity(),
                self.len(),
                additional
            )
        }
    }

    /// Write value to the end of the array and increment the length.
    ///
    /// This method is used in the default implementation of `push`, `extend_with_element` and
    /// `extend_from_slice`.
    ///
    /// # Safety
    ///
    /// It's unsafe because the capacity is not checked.
    #[inline]
    unsafe fn push_unchecked(&mut self, value: T) {
        let len = self.len();
        ptr::write(self.get_unchecked_mut(len), value);
        self.set_len(len + 1);
    }

    /// Appends the `value` to the array.
    ///
    /// # Panics
    ///
    /// If the array is full and cannot grow.
    #[inline]
    fn push(&mut self, value: T) {
        self.reserve(1);
        unsafe {
            self.push_unchecked(value);
        }
    }

    // TODO: remove this method, should implement Extend
    /// Appends all elements of `iter` to the array.
    ///
    /// # Panics
    ///
    /// If the array cannot grow to accommodate all elements.
    fn extend<I>(&mut self, iter: I)
    where
        Self: Sized,
        I: IntoIterator<Item = T>,
    {
        let iter = iter.into_iter();
        self.reserve(iter.size_hint().0);
        for value in iter {
            self.push(value);
        }
    }

    /// Appends all elements in a slice to the array.
    ///
    /// # Panics
    ///
    /// If the array cannot grow to accommodate all elements.
    fn extend_from_slice(&mut self, other: &[T])
    where
        T: Clone,
    {
        self.reserve(other.len());

        for i in 0..other.len() {
            unsafe { self.push_unchecked(other.get_unchecked(i).clone()) }
        }
    }

    /// Extend the array by `n` additional clones of `value`.
    ///
    /// # Panics
    ///
    /// If the array cannot grow to accommodate all elements.
    fn extend_with_element(&mut self, value: T, n: usize)
    where
        T: Clone,
    {
        self.reserve(n);

        for _ in 1..n {
            unsafe {
                self.push_unchecked(value.clone());
            }
        }

        if n > 0 {
            // do not clone the last one
            unsafe {
                self.push_unchecked(value);
            }
        }
    }
}

/// An iterator over `Array`.
pub struct Iter<'a, T, A: 'a + Array<T>> {
    cur: usize,
    len: usize,
    array: &'a A,
    _marker: PhantomData<*const T>,
}

impl<'a, T, A> Iterator for Iter<'a, T, A>
where
    A: 'a + Array<T>,
    T: 'a,
{
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.cur == self.len {
            None
        } else {
            let item = unsafe { self.array.get_unchecked(self.cur) };
            self.cur += 1;
            Some(item)
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        (self.len(), Some(self.len()))
    }
}

impl<'a, T, A> ExactSizeIterator for Iter<'a, T, A>
where
    A: 'a + Array<T>,
    T: 'a,
{
    fn len(&self) -> usize {
        self.len - self.cur
    }
}

/// A set of tests for `Array` implementations.
#[doc(hidden)]
pub trait ArrayTests {
    type A: Array<usize>;

    fn basic_0() {
        Self::basic(0);
    }

    fn basic_001k() {
        Self::basic(1024);
    }

    fn basic_100k() {
        Self::basic(100 * 1024);
    }

    fn clone_001k()
    where
        Self::A: Clone,
    {
        Self::clone(1024);
    }

    fn clone_100k()
    where
        Self::A: Clone,
    {
        Self::clone(100 * 1024);
    }

    fn basic(n: usize) {
        let mut exp = vec![0; n];
        let mut actual = Self::A::with_value(0, n);

        Self::assert_all(&exp, &mut actual);

        for i in 0..n {
            actual[i] = i;
            exp[i] = i;
        }
        Self::assert_all(&exp, &mut actual);

        for i in 0..n {
            *actual.get_mut(i).unwrap() = i + 1;
            *exp.index_mut(i) = i + 1;
        }
        Self::assert_all(&exp, &mut actual);

        for i in 0..n {
            unsafe {
                *actual.get_unchecked_mut(i) = i + 2;
            }
            *exp.index_mut(i) = i + 2;
        }
        Self::assert_all(&exp, &mut actual);
    }

    fn clone(n: usize)
    where
        Self::A: Clone,
    {
        let mut exp1 = vec![0; n];
        let mut exp2 = vec![0; n];
        let mut actual1 = Self::A::with_value(0, n);
        let mut actual2 = actual1.clone();

        actual1[0] = 10;
        exp1[0] = 10;
        Self::assert_all(&exp1, &mut actual1);
        Self::assert_all(&exp2, &mut actual2);

        actual2[0] = 20;
        exp2[0] = 20;
        Self::assert_all(&exp1, &mut actual1);
        Self::assert_all(&exp2, &mut actual2);

        actual1[n / 2] = 30;
        exp1[n / 2] = 30;
        actual2[n / 2] = 40;
        exp2[n / 2] = 40;
        Self::assert_all(&exp1, &mut actual1);
        Self::assert_all(&exp2, &mut actual2);
    }

    fn assert_all(exp: &[usize], actual: &mut Self::A) {
        let n = actual.len();
        assert_eq!(exp.len(), actual.len());
        assert_eq!(exp.is_empty(), actual.is_empty());
        assert_eq!(exp, &*vec(actual.iter().cloned()));
        assert_eq!(exp, &*vec((0..n).map(|i| *actual.index(i))));
        assert_eq!(exp, &*vec((0..n).map(|i| *actual.get(i).unwrap())));
        assert_eq!(
            exp,
            &*vec((0..n).map(|i| unsafe { *actual.get_unchecked(i) }))
        );
        assert_eq!(exp, &*vec((0..n).map(|i| *actual.index_mut(i))));
        assert_eq!(exp, &*vec((0..n).map(|i| *actual.get_mut(i).unwrap())));
        assert_eq!(
            exp,
            &*vec((0..n).map(|i| unsafe { *actual.get_unchecked_mut(i) }))
        );

        assert_eq!(None, actual.get(n));
        assert_eq!(None, actual.get_mut(n));
    }
}

/// A set of tests for `Array` implementations.
#[doc(hidden)]
pub trait DynamicArrayTests: ArrayTests
where
    Self::A: DynamicArray<usize>,
{
    fn push_1k() {
        Self::push(1024);
    }

    fn capacity() {
        assert_eq!(0, Self::A::with_capacity(0).len());

        assert!(1000 <= Self::A::with_capacity(1000).capacity());
        assert_eq!(0, Self::A::with_capacity(0).len());
    }

    fn clone_push()
    where
        Self::A: Clone,
    {
        let mut a = Self::A::with_capacity(10);
        let b = a.clone();
        a.push(100);
        assert_eq!(1, a.len());
        assert_eq!(0, b.len());
    }

    fn push(n: usize) {
        let mut actual = Self::A::with_capacity(n);
        let mut exp = Vec::with_capacity(n);

        for i in 0..n {
            Self::assert_all(&exp, &mut actual);
            actual.push(i);
            exp.push(i);
        }

        Self::assert_all(&*exp, &mut actual)
    }
}

#[cfg(all(feature = "nightly", test))]
use test::Bencher;

/// A set of benchmarks for `Array` implementations.
#[cfg(all(feature = "nightly", test))]
pub trait ArrayBenchs: ArrayTests
where
    Self::A: Clone,
{
    fn fold_xor_0001k(b: &mut Bencher) {
        Self::fold_xor(b, 1024)
    }

    fn fold_xor_0010k(b: &mut Bencher) {
        Self::fold_xor(b, 10 * 1024)
    }

    fn fold_xor_0100k(b: &mut Bencher) {
        Self::fold_xor(b, 100 * 1024)
    }

    fn fold_xor_1000k(b: &mut Bencher) {
        Self::fold_xor(b, 1000 * 1024)
    }

    fn fold_xor(b: &mut Bencher, n: usize) {
        let mut v = Self::A::with_value(0, n);
        for i in 0..n {
            v[i] = i;
        }
        b.iter(|| v.iter().fold(0, |acc, e| acc ^ e))
    }

    fn clone_change_0001k(b: &mut Bencher) {
        Self::clone_change(b, 1024, 1);
    }

    fn clone_change_0010k(b: &mut Bencher) {
        Self::clone_change(b, 10 * 1024, 1);
    }

    fn clone_change_0100k(b: &mut Bencher) {
        Self::clone_change(b, 100 * 1024, 1);
    }

    fn clone_change_1000k(b: &mut Bencher) {
        Self::clone_change(b, 1000 * 1024, 1);
    }

    fn clone_change(b: &mut Bencher, n: usize, ins: usize) {
        fn setup<A: Array<usize>>(n: usize, ins: usize) -> (Vec<A>, Vec<usize>, Vec<usize>) {
            use rand::{Rng, SeedableRng, XorShiftRng};
            let mut rng =
                XorShiftRng::from_seed([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]);
            let mut arrays = Vec::with_capacity(ins + 1);
            arrays.push(A::with_value(0, n));
            let ii = vec((0..ins).map(|e| rng.gen_range(0, e + 1)));
            let jj = vec((0..ins).map(|_| rng.gen_range(0, n)));
            (arrays, ii, jj)
        }

        let (mut arrays, ii, jj) = setup::<Self::A>(n, ins);
        b.iter(|| {
            for (&i, &j) in ii.iter().zip(jj.iter()) {
                let mut new = arrays[i].clone();
                new[j] = j + i;
                arrays.push(new);
            }
        });
    }
}