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
#![deny(missing_docs)]
//! Append-only concurrent vector
extern crate parking_lot;
use std::cell::UnsafeCell;
use std::ops::Index;

use parking_lot::RwLock;

/// A concurrent vector, only supporting push and indexed access
pub struct Aovec<T> {
    len: RwLock<usize>,
    allocations: [UnsafeCell<Vec<T>>; 16],
    base: usize,
}

unsafe impl<T> Sync for Aovec<T> {}
unsafe impl<T> Send for Aovec<T> {}

impl<T> Aovec<T> {
    /// Creates a new `Aovec`
    ///
    /// The `base` of the vector is how many elements the first allocation
    /// fits. When this value is exceeded, another vector is allocated
    /// with twice the size. Up to 16 allocations are supported, after which
    /// the push will panic.
    ///
    /// A base of 16 gives a maximum number of 104856 elements.
    pub fn new(base: usize) -> Self {
        assert!(base > 0, "Base must be non-zero");
        Aovec {
            len: RwLock::new(0),
            allocations: [
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
                UnsafeCell::new(vec![]),
            ],
            base,
        }
    }

    // get the allocation and offset within it.
    fn allocation(&self, mut offset: usize) -> (usize, usize) {
        let mut compare = self.base;
        let mut allocation = 0;
        loop {
            if compare > offset {
                return (allocation, offset);
            } else {
                offset -= compare;
            }
            compare = compare << 1;
            allocation += 1;
        }
    }

    #[inline]
    fn _get(&self, idx: usize) -> &T {
        let (index, offset) = self.allocation(idx);
        unsafe { &(*self.allocations[index].get())[offset] }
    }

    #[inline]
    fn valid_index(&self, idx: usize) -> bool {
        *self.len.read() > idx
    }

    /// Returns the length of the `Aovec`.
    pub fn len(&self) -> usize {
        *self.len.read()
    }

    /// Get value at index `idx`
    pub fn get(&self, idx: usize) -> Option<&T> {
        if self.valid_index(idx) {
            Some(self._get(idx))
        } else {
            None
        }
    }

    /// Get value at index `idx`, without checking bounds
    pub unsafe fn get_unchecked(&self, idx: usize) -> &T {
        self._get(idx)
    }

    /// Adds an element to the `Aovec`, returning its index.
    pub fn push(&self, t: T) -> usize {
        let mut guard = self.len.write();
        let idx = *guard;
        *guard += 1;
        let (index, _) = self.allocation(idx);
        unsafe {
            let allocation = self.allocations[index].get();
            if (*allocation).len() == 0 {
                *allocation = Vec::with_capacity(self.base << index);
            }
            (*allocation).push(t);
        }
        idx
    }
}

impl<T> Index<usize> for Aovec<T> {
    type Output = T;
    fn index(&self, idx: usize) -> &Self::Output {
        if self.valid_index(idx) {
            self._get(idx)
        } else {
            panic!("Index out of range");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::collections::HashSet;

    #[test]
    fn base_one() {
        let vec = Aovec::new(1);
        let n = 1024;

        for i in 0..n {
            vec.push(i);
        }

        for i in 0..n {
            assert_eq!(vec[i], i);
        }
    }

    #[test]
    fn base_thirtytwo() {
        let vec = Aovec::new(32);
        let n = 1_000_000;

        for i in 0..n {
            vec.push(i);
        }

        for i in 0..n {
            assert_eq!(vec[i], i);
            assert_eq!(vec.get(i), Some(&i));
            unsafe {
                assert_eq!(vec.get_unchecked(i), &i);
            }
        }
    }

    #[test]
    fn multithreading() {
        let vec = Arc::new(Aovec::new(32));
        let n = 100_000;

        let n_threads = 16;

        let mut handles = vec![];

        for t in 0..n_threads {
            let vec = vec.clone();
            handles.push(std::thread::spawn(move || for i in 0..n {
                if i % n_threads == t {
                    vec.push(i);
                }
            }))
        }

        for h in handles {
            h.join().unwrap();
        }

        let mut set = HashSet::new();

        for i in 0..n {
            set.insert(vec[i]);
        }

        assert_eq!(set.len(), n);
    }
}