File size: 6,983 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use std::{
    ptr::null_mut,
    slice::from_raw_parts_mut,
    sync::{
        Mutex,
        atomic::{AtomicPtr, Ordering},
    },
};

const BUCKETS: usize = (usize::BITS + 1) as usize;

/// An `Option`-like type that guarantees that a fully zeroed value is a valid
/// `None` variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
enum COption<T> {
    // TODO(alexkirsz) We need a way to guarantee that a fully zeroed value is a
    // valid `None` variant. This is theoretically possible when the wrapped
    // type has no valid value that can be represented by all zeros, but there
    // is no way to enforce this at the type level. For now, we just use a custom
    // option type with explicit discriminant for the `None` variant.
    // The issue with this implementation is that it disables niche optimization.
    None = 0,
    Some(T),
}

impl<T> Default for COption<T> {
    fn default() -> Self {
        Self::None
    }
}

impl<T> COption<T> {
    /// Returns a slice of the given size filled with the `None` variant.
    fn new_none_slice(size: usize) -> Box<[Self]> {
        let slice = Box::<[COption<T>]>::new_zeroed_slice(size);
        // Safety:
        // We know that a zeroed COption<T> is a valid COption::None value.
        unsafe { slice.assume_init() }
    }

    /// Returns a reference to the contained value, or `None` if it is `None`.
    fn as_option_ref(&self) -> Option<&T> {
        match self {
            COption::None => None,
            COption::Some(t) => Some(t),
        }
    }
}

pub struct NoMoveVec<T, const INITIAL_CAPACITY_BITS: u32 = 6> {
    buckets: [(AtomicPtr<COption<T>>, Mutex<()>); BUCKETS],
}

fn get_bucket_index<const INITIAL_CAPACITY_BITS: u32>(idx: usize) -> u32 {
    (usize::BITS - idx.leading_zeros()).saturating_sub(INITIAL_CAPACITY_BITS)
}

fn get_bucket_size<const INITIAL_CAPACITY_BITS: u32>(bucket_index: u32) -> usize {
    if bucket_index != 0 {
        1 << (bucket_index + INITIAL_CAPACITY_BITS - 1)
    } else {
        1 << INITIAL_CAPACITY_BITS
    }
}

fn get_index_in_bucket<const INITIAL_CAPACITY_BITS: u32>(idx: usize, bucket_index: u32) -> usize {
    if bucket_index != 0 {
        idx ^ (1 << (bucket_index + INITIAL_CAPACITY_BITS - 1))
    } else {
        idx
    }
}

/// Allocates a new bucket of `COption<T>`s, all initialized to `None`.
fn allocate_bucket<const INITIAL_CAPACITY_BITS: u32, T>(bucket_index: u32) -> *mut COption<T> {
    let size = get_bucket_size::<INITIAL_CAPACITY_BITS>(bucket_index);
    let slice = COption::<T>::new_none_slice(size);
    Box::into_raw(slice) as *mut COption<T>
}

impl<T, const INITIAL_CAPACITY_BITS: u32> Default for NoMoveVec<T, INITIAL_CAPACITY_BITS> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T, const INITIAL_CAPACITY_BITS: u32> NoMoveVec<T, INITIAL_CAPACITY_BITS> {
    pub fn new() -> Self {
        let mut buckets = [null_mut(); BUCKETS];
        buckets[0] = allocate_bucket::<INITIAL_CAPACITY_BITS, T>(0);
        let buckets = buckets.map(|p| (AtomicPtr::new(p), Mutex::new(())));
        NoMoveVec { buckets }
    }

    pub fn get(&self, idx: usize) -> Option<&T> {
        let bucket_idx = get_bucket_index::<INITIAL_CAPACITY_BITS>(idx);
        let bucket_ptr = unsafe { self.buckets.get_unchecked(bucket_idx as usize) }
            .0
            .load(Ordering::Acquire);
        if bucket_ptr.is_null() {
            return None;
        }
        let index = get_index_in_bucket::<INITIAL_CAPACITY_BITS>(idx, bucket_idx);
        unsafe { &*bucket_ptr.add(index) }.as_option_ref()
    }

    /// # Safety
    /// There must not be a concurrent operation to this idx
    pub unsafe fn insert(&self, idx: usize, value: T) -> &T {
        let bucket_idx = get_bucket_index::<INITIAL_CAPACITY_BITS>(idx);
        let bucket = unsafe { self.buckets.get_unchecked(bucket_idx as usize) };
        // SAFETY: This is safe to be relaxed as the bucket will never become null
        // again. We perform a acquire load when it's null.
        let mut bucket_ptr = bucket.0.load(Ordering::Relaxed);
        if bucket_ptr.is_null() {
            bucket_ptr = bucket.0.load(Ordering::Acquire);
            if bucket_ptr.is_null() {
                let lock = bucket.1.lock();
                let guarded_bucket_ptr = bucket.0.load(Ordering::Acquire);
                if guarded_bucket_ptr.is_null() {
                    let new_bucket = allocate_bucket::<INITIAL_CAPACITY_BITS, T>(bucket_idx);
                    bucket_ptr = match bucket.0.compare_exchange(
                        null_mut(),
                        new_bucket,
                        Ordering::AcqRel,
                        Ordering::Relaxed,
                    ) {
                        Ok(_) => new_bucket,
                        Err(current_bucket) => {
                            drop(unsafe { Box::from_raw(new_bucket) });
                            current_bucket
                        }
                    };
                    drop(lock);
                } else {
                    bucket_ptr = guarded_bucket_ptr;
                }
            }
        }
        let index = get_index_in_bucket::<INITIAL_CAPACITY_BITS>(idx, bucket_idx);
        let item = unsafe { &mut *bucket_ptr.add(index) };
        *item = COption::Some(value);
        // To sync with any acquire load of the bucket ptr
        bucket.0.store(bucket_ptr, Ordering::Release);
        item.as_option_ref().unwrap()
    }
}

impl<T, const INITIAL_CAPACITY_BITS: u32> Drop for NoMoveVec<T, INITIAL_CAPACITY_BITS> {
    fn drop(&mut self) {
        for (bucket_index, (bucket, _)) in self.buckets.iter_mut().enumerate() {
            if bucket_index < (usize::BITS + 1 - INITIAL_CAPACITY_BITS) as usize {
                let bucket_size = get_bucket_size::<INITIAL_CAPACITY_BITS>(bucket_index as u32);
                let bucket_ptr = *bucket.get_mut();

                if !bucket_ptr.is_null() {
                    drop(unsafe { Box::from_raw(from_raw_parts_mut(bucket_ptr, bucket_size)) });
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::NoMoveVec;

    #[test]
    fn basic_operations() {
        let v = NoMoveVec::<(usize, usize)>::new();
        assert_eq!(v.get(0), None);
        assert_eq!(v.get(1), None);
        assert_eq!(v.get(8), None);
        assert_eq!(v.get(9), None);
        assert_eq!(v.get(15), None);
        assert_eq!(v.get(16), None);
        assert_eq!(v.get(100), None);
        assert_eq!(v.get(1000), None);

        for i in 0..1000 {
            unsafe {
                v.insert(i, (i, i));
            }
            assert_eq!(v.get(i), Some(&(i, i)));
        }
        for i in 0..1000 {
            assert_eq!(v.get(i), Some(&(i, i)));
        }
        assert_eq!(v.get(1001), None);

        unsafe {
            v.insert(1000000, (0, 0));
        }
        assert_eq!(v.get(1000000), Some(&(0, 0)));
        assert_eq!(v.get(10000), None);
    }
}