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
#![deny(missing_docs)]
//! An append-only, concurrent arena

use std::cell::UnsafeCell;
use std::mem;

use arrayvec::ArrayVec;
use parking_lot::Mutex;

const N_LANES: usize = 64;
const USIZE_BITS: usize = mem::size_of::<usize>() * 8;

#[inline(always)]
fn lane_size(n: usize) -> usize {
    2_usize.pow(n as u32) * 2
}

#[inline(always)]
fn lane_offset(offset: usize) -> (usize, usize) {
    let i = offset / 2 + 1;
    let lane = USIZE_BITS - i.leading_zeros() as usize - 1;
    let offset = offset - (2usize.pow(lane as u32) - 1) * 2;
    (lane, offset)
}

impl<T> Default for Bunch<T> {
    fn default() -> Self {
        Bunch {
            lanes: Default::default(),
            len: Default::default(),
        }
    }
}

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

/// The main Arena type
pub struct Bunch<T> {
    lanes: UnsafeCell<ArrayVec<[Vec<T>; N_LANES]>>,
    len: Mutex<usize>,
}

impl<T> Bunch<T> {
    /// Creates a new arena
    pub fn new() -> Self {
        Self::default()
    }

    /// Pushes to the arena, returning a reference to the pushed element
    pub fn push(&self, t: T) -> &T {
        let len = &mut *self.len.lock();
        let (lane, offset) = lane_offset(*len);

        if offset == 0 {
            unsafe {
                let lanes = &mut *self.lanes.get();
                let size = lane_size(lane);
                lanes.push(Vec::with_capacity(size));
            }
        }

        unsafe {
            let lanes = &mut *self.lanes.get();
            lanes[lane].push(t);
            *len += 1;
            lanes[lane].get(offset).expect("just pushed")
        }
    }

    /// Gets a reference into the arena
    pub fn get(&self, idx: usize) -> &T {
        let (lane, offset) = lane_offset(idx);
        unsafe { &(*self.lanes.get())[lane][offset] }
    }

    /// Returns the number of elements in the Bunch
    pub fn len(&self) -> usize {
        *self.len.lock()
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use std::sync::Arc;

    #[test]
    fn it_works() {
        let p = Bunch::new();

        assert_eq!(p.push(3), &3);

        assert_eq!(p.get(0), &3);
    }

    #[test]
    fn multiple() {
        let p = Bunch::new();

        for i in 0..10_000 {
            let r = p.push(i);
            assert_eq!(r, &i);
        }

        for i in 0..10_000 {
            assert_eq!(p.get(i), &i);
        }
    }

    #[test]
    fn multithreading() {
        let vec = Arc::new(Bunch::new());
        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 result = vec![];

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

        result.sort();

        for i in 0..n {
            assert_eq!(result[i], &i)
        }
    }

    #[test]
    fn dropping() {
        let n = 100_000;
        let n_threads = 16;

        let mut arcs = vec![];

        for i in 0..n {
            arcs.push(Arc::new(i));
        }

        for i in 0..n {
            assert_eq!(Arc::strong_count(&arcs[i]), 1);
        }

        let wrapped_arcs = Arc::new(arcs);

        {
            let vec = Arc::new(Bunch::new());

            let mut handles = vec![];

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

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

            for i in 0..n {
                assert_eq!(Arc::strong_count(&wrapped_arcs[i]), 2);
            }
        }
        // Bunch dropped here
        for i in 0..n {
            assert_eq!(Arc::strong_count(&wrapped_arcs[i]), 1);
        }
    }

    #[test]
    #[should_panic]
    fn out_of_bounds_access() {
        let bunch = Bunch::new();
        bunch.push("hello");

        bunch.get(1);
    }
}