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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
use crate::{
    fragment::transformations::{fragment_from_raw, fragment_into_raw},
    range_helpers::{range_end, range_start},
    Doubling, Fragment, GrowthWithConstantTimeAccess, SplitVec,
};
use alloc::vec::Vec;
use core::cell::UnsafeCell;
use core::ops::RangeBounds;
use core::sync::atomic::{AtomicUsize, Ordering};
use orx_pinned_vec::{ConcurrentPinnedVec, PinnedVec};

struct FragmentData {
    f: usize,
    len: usize,
    capacity: usize,
}

/// Concurrent wrapper ([`orx_pinned_vec::ConcurrentPinnedVec`]) for the `SplitVec`.
pub struct ConcurrentSplitVec<T, G: GrowthWithConstantTimeAccess = Doubling> {
    growth: G,
    data: Vec<UnsafeCell<*mut T>>,
    capacity: AtomicUsize,
    maximum_capacity: usize,
    max_num_fragments: usize,
    pinned_vec_len: usize,
}

impl<T, G: GrowthWithConstantTimeAccess> Drop for ConcurrentSplitVec<T, G> {
    fn drop(&mut self) {
        let mut take_fragment = |_fragment: Fragment<T>| {};
        unsafe { self.process_into_fragments(self.pinned_vec_len, &mut take_fragment) };
        self.zero();
    }
}

impl<T, G: GrowthWithConstantTimeAccess> ConcurrentSplitVec<T, G> {
    unsafe fn get_raw_mut_unchecked_fi(&self, f: usize, i: usize) -> *mut T {
        let p = *self.data[f].get();
        p.add(i)
    }

    unsafe fn get_raw_mut_unchecked_idx(&self, idx: usize) -> *mut T {
        let (f, i) = self.growth.get_fragment_and_inner_indices_unchecked(idx);
        self.get_raw_mut_unchecked_fi(f, i)
    }

    fn capacity_of(&self, f: usize) -> usize {
        self.growth.fragment_capacity_of(f)
    }

    fn layout(len: usize) -> alloc::alloc::Layout {
        alloc::alloc::Layout::array::<T>(len).expect("len must not overflow")
    }

    unsafe fn to_fragment(&self, data: FragmentData) -> Fragment<T> {
        let ptr = *self.data[data.f].get();
        fragment_from_raw(ptr, data.len, data.capacity)
    }

    unsafe fn process_into_fragments<F>(&mut self, len: usize, take_fragment: &mut F)
    where
        F: FnMut(Fragment<T>),
    {
        let mut process_in_cap = |x: FragmentData| {
            let _fragment_to_drop = self.to_fragment(x);
        };
        let mut process_in_len = |x: FragmentData| {
            let fragment = self.to_fragment(x);
            take_fragment(fragment);
        };

        self.process_fragments(len, &mut process_in_len, &mut process_in_cap);
    }

    unsafe fn process_fragments<P, Q>(
        &self,
        len: usize,
        process_in_len: &mut P,
        process_in_cap: &mut Q,
    ) where
        P: FnMut(FragmentData),
        Q: FnMut(FragmentData),
    {
        let capacity = self.capacity();
        assert!(capacity >= len);

        let mut remaining_len = len;
        let mut f = 0;
        let mut taken_out_capacity = 0;

        while remaining_len > 0 {
            let capacity = self.capacity_of(f);
            taken_out_capacity += capacity;

            let len = match remaining_len <= capacity {
                true => remaining_len,
                false => capacity,
            };

            let fragment = FragmentData { f, len, capacity };
            process_in_len(fragment);
            remaining_len -= len;
            f += 1;
        }

        while capacity > taken_out_capacity {
            let capacity = self.capacity_of(f);
            taken_out_capacity += capacity;
            let len = 0;
            let fragment = FragmentData { f, len, capacity };
            process_in_cap(fragment);
            f += 1;
        }
    }

    fn zero(&mut self) {
        self.capacity = 0.into();
        self.maximum_capacity = 0;
        self.max_num_fragments = 0;
        self.pinned_vec_len = 0;
    }

    fn num_fragments_for_capacity(&self, capacity: usize) -> usize {
        match capacity {
            0 => 0,
            _ => {
                self.growth
                    .get_fragment_and_inner_indices_unchecked(capacity - 1)
                    .0
                    + 1
            }
        }
    }
}

impl<T, G: GrowthWithConstantTimeAccess> From<SplitVec<T, G>> for ConcurrentSplitVec<T, G> {
    fn from(value: SplitVec<T, G>) -> Self {
        let (fragments, growth, pinned_vec_len) = (value.fragments, value.growth, value.len);

        let num_fragments = fragments.len();
        let max_num_fragments = fragments.capacity();

        let mut data = Vec::with_capacity(max_num_fragments);
        let mut total_len = 0;
        let mut maximum_capacity = 0;

        for (f, fragment) in fragments.into_iter().enumerate() {
            let (p, len, cap) = fragment_into_raw(fragment);

            let expected_cap = growth.fragment_capacity_of(f);
            assert_eq!(cap, expected_cap);

            total_len += len;
            maximum_capacity += cap;

            data.push(UnsafeCell::new(p));
        }
        assert_eq!(total_len, pinned_vec_len);
        let capacity = maximum_capacity;

        for f in num_fragments..data.capacity() {
            let expected_cap = growth.fragment_capacity_of(f);
            maximum_capacity += expected_cap;

            data.push(UnsafeCell::new(core::ptr::null_mut()));
        }

        Self {
            growth,
            data,
            capacity: capacity.into(),
            maximum_capacity,
            max_num_fragments,
            pinned_vec_len,
        }
    }
}

impl<T, G: GrowthWithConstantTimeAccess> ConcurrentPinnedVec<T> for ConcurrentSplitVec<T, G> {
    type P = SplitVec<T, G>;

    unsafe fn into_inner(mut self, len: usize) -> Self::P {
        let mut fragments = Vec::with_capacity(self.max_num_fragments);
        let mut take_fragment = |fragment| fragments.push(fragment);
        self.process_into_fragments(len, &mut take_fragment);

        self.zero();
        SplitVec::from_raw_parts(len, fragments, self.growth.clone())
    }

    unsafe fn clone_with_len(&self, len: usize) -> Self
    where
        T: Clone,
    {
        let mut fragments = Vec::with_capacity(self.max_num_fragments);
        let mut clone_fragment = |x: FragmentData| {
            let mut fragment = Fragment::new(x.capacity);
            let dst: *mut T = fragment.data.as_mut_ptr();
            let src = *self.data[x.f].get();
            for i in 0..x.len {
                let value = src.add(i).as_ref().expect("must be some");
                dst.add(i).write(value.clone());
            }
            fragment.set_len(x.len);
            fragments.push(fragment);
        };

        self.process_fragments(len, &mut clone_fragment, &mut |_| {});

        let split_vec = SplitVec::from_raw_parts(len, fragments, self.growth.clone());
        split_vec.into()
    }

    fn slices<R: RangeBounds<usize>>(&self, range: R) -> <Self::P as PinnedVec<T>>::SliceIter<'_> {
        use core::slice::from_raw_parts;

        let fragment_and_inner_indices =
            |i| self.growth.get_fragment_and_inner_indices_unchecked(i);

        let a = range_start(&range);
        let b = range_end(&range, self.capacity());

        match b.saturating_sub(a) {
            0 => alloc::vec![],
            _ => {
                let (sf, si) = fragment_and_inner_indices(a);
                let (ef, ei) = fragment_and_inner_indices(b - 1);

                match sf == ef {
                    true => {
                        let p = unsafe { self.get_raw_mut_unchecked_fi(sf, si) };
                        let slice = unsafe { from_raw_parts(p, ei - si + 1) };
                        alloc::vec![slice]
                    }
                    false => {
                        let mut vec = Vec::with_capacity(ef - sf + 1);

                        let slice_len = self.capacity_of(sf) - si;
                        let p = unsafe { self.get_raw_mut_unchecked_fi(sf, si) };
                        let slice = unsafe { from_raw_parts(p, slice_len) };
                        vec.push(slice);

                        for f in (sf + 1)..ef {
                            let slice_len = self.capacity_of(f);
                            let p = unsafe { self.get_raw_mut_unchecked_fi(f, 0) };
                            let slice = unsafe { from_raw_parts(p, slice_len) };
                            vec.push(slice);
                        }

                        let slice_len = ei + 1;
                        let p = unsafe { self.get_raw_mut_unchecked_fi(ef, 0) };
                        let slice = unsafe { from_raw_parts(p, slice_len) };
                        vec.push(slice);

                        vec
                    }
                }
            }
        }
    }

    unsafe fn iter<'a>(&'a self, len: usize) -> impl Iterator<Item = &'a T> + 'a
    where
        T: 'a,
    {
        self.slices(0..len).into_iter().flat_map(|x| x.iter())
    }

    unsafe fn iter_over_range<'a, R: RangeBounds<usize>>(
        &'a self,
        range: R,
    ) -> impl Iterator<Item = &'a T> + 'a
    where
        T: 'a,
    {
        let [a, b] = orx_pinned_vec::utils::slice::vec_range_limits(&range, None);
        self.slices(a..b).into_iter().flat_map(|x| x.iter())
    }

    unsafe fn slices_mut<R: RangeBounds<usize>>(
        &self,
        range: R,
    ) -> <Self::P as PinnedVec<T>>::SliceMutIter<'_> {
        use core::slice::from_raw_parts_mut;

        let fragment_and_inner_indices =
            |i| self.growth.get_fragment_and_inner_indices_unchecked(i);

        let a = range_start(&range);
        let b = range_end(&range, self.capacity());

        match b.saturating_sub(a) {
            0 => alloc::vec![],
            _ => {
                let (sf, si) = fragment_and_inner_indices(a);
                let (ef, ei) = fragment_and_inner_indices(b - 1);

                match sf == ef {
                    true => {
                        let p = unsafe { self.get_raw_mut_unchecked_fi(sf, si) };
                        let slice = unsafe { from_raw_parts_mut(p, ei - si + 1) };
                        alloc::vec![slice]
                    }
                    false => {
                        let mut vec = Vec::with_capacity(ef - sf + 1);

                        let slice_len = self.capacity_of(sf) - si;
                        let p = unsafe { self.get_raw_mut_unchecked_fi(sf, si) };
                        let slice = unsafe { from_raw_parts_mut(p, slice_len) };
                        vec.push(slice);

                        for f in (sf + 1)..ef {
                            let slice_len = self.capacity_of(f);
                            let p = unsafe { self.get_raw_mut_unchecked_fi(f, 0) };
                            let slice = unsafe { from_raw_parts_mut(p, slice_len) };
                            vec.push(slice);
                        }

                        let slice_len = ei + 1;
                        let p = unsafe { self.get_raw_mut_unchecked_fi(ef, 0) };
                        let slice = unsafe { from_raw_parts_mut(p, slice_len) };
                        vec.push(slice);

                        vec
                    }
                }
            }
        }
    }

    unsafe fn iter_mut<'a>(&'a mut self, len: usize) -> impl Iterator<Item = &'a mut T> + 'a
    where
        T: 'a,
    {
        self.slices_mut(0..len)
            .into_iter()
            .flat_map(|x| x.iter_mut())
    }

    unsafe fn get(&self, index: usize) -> Option<&T> {
        match index < self.capacity() {
            true => {
                let p = self.get_raw_mut_unchecked_idx(index);
                Some(&*p)
            }
            false => None,
        }
    }

    unsafe fn get_mut(&mut self, index: usize) -> Option<&mut T> {
        match index < self.capacity() {
            true => {
                let p = self.get_raw_mut_unchecked_idx(index);
                Some(&mut *p)
            }
            false => None,
        }
    }

    unsafe fn get_ptr_mut(&self, index: usize) -> *mut T {
        self.get_raw_mut_unchecked_idx(index)
    }

    fn max_capacity(&self) -> usize {
        self.maximum_capacity
    }

    fn capacity(&self) -> usize {
        self.capacity.load(Ordering::Acquire)
    }

    fn grow_to(&self, new_capacity: usize) -> Result<usize, orx_pinned_vec::PinnedVecGrowthError> {
        let capacity = self.capacity.load(Ordering::Acquire);
        match new_capacity <= capacity {
            true => Ok(capacity),
            false => {
                let mut f = self.num_fragments_for_capacity(capacity);
                let mut current_capacity = capacity;

                while new_capacity > current_capacity {
                    let new_fragment_capacity = self.capacity_of(f);
                    let layout = Self::layout(new_fragment_capacity);
                    let ptr = unsafe { alloc::alloc::alloc(layout) } as *mut T;
                    unsafe { *self.data[f].get() = ptr };

                    f += 1;
                    current_capacity += new_fragment_capacity;
                }

                self.capacity.store(current_capacity, Ordering::Release);

                Ok(current_capacity)
            }
        }
    }

    fn grow_to_and_fill_with<F>(
        &self,
        new_capacity: usize,
        fill_with: F,
    ) -> Result<usize, orx_pinned_vec::PinnedVecGrowthError>
    where
        F: Fn() -> T,
    {
        let capacity = self.capacity.load(Ordering::Acquire);
        match new_capacity <= capacity {
            true => Ok(capacity),
            false => {
                let mut f = self.num_fragments_for_capacity(capacity);

                let mut current_capacity = capacity;

                while new_capacity > current_capacity {
                    let new_fragment_capacity = self.capacity_of(f);
                    let layout = Self::layout(new_fragment_capacity);
                    let ptr = unsafe { alloc::alloc::alloc(layout) } as *mut T;

                    for i in 0..new_fragment_capacity {
                        unsafe { ptr.add(i).write(fill_with()) };
                    }

                    unsafe { *self.data[f].get() = ptr };

                    f += 1;
                    current_capacity += new_fragment_capacity;
                }

                self.capacity.store(current_capacity, Ordering::Release);

                Ok(current_capacity)
            }
        }
    }

    fn fill_with<F>(&self, range: core::ops::Range<usize>, fill_with: F)
    where
        F: Fn() -> T,
    {
        for i in range {
            unsafe { self.get_ptr_mut(i).write(fill_with()) };
        }
    }

    unsafe fn reserve_maximum_concurrent_capacity(
        &mut self,
        _current_len: usize,
        new_maximum_capacity: usize,
    ) -> usize {
        assert_eq!(self.max_num_fragments, self.data.len());
        assert_eq!(self.max_num_fragments, self.data.capacity());

        let mut num_required_fragments = 0;
        let mut max_cap = self.maximum_capacity;
        let f = self.data.len();

        while max_cap < new_maximum_capacity {
            max_cap += self.capacity_of(f);
            num_required_fragments += 1;
        }

        if num_required_fragments > 0 {
            self.data.reserve_exact(num_required_fragments);
        }

        for _ in self.max_num_fragments..self.data.capacity() {
            self.data.push(UnsafeCell::new(core::ptr::null_mut()));
        }

        self.maximum_capacity = (0..self.data.len()).map(|f| self.capacity_of(f)).sum();
        self.max_num_fragments = self.data.len();

        while self.maximum_capacity < new_maximum_capacity {
            let f = self.data.len();
            self.data.push(UnsafeCell::new(core::ptr::null_mut()));

            let capacity = self.capacity_of(f);
            self.maximum_capacity += capacity;
            self.max_num_fragments += 1;
        }

        assert_eq!(self.max_num_fragments, self.data.len());
        assert_eq!(self.max_num_fragments, self.data.capacity());

        self.maximum_capacity
    }

    unsafe fn reserve_maximum_concurrent_capacity_fill_with<F>(
        &mut self,
        current_len: usize,
        new_maximum_capacity: usize,
        _fill_with: F,
    ) -> usize
    where
        F: Fn() -> T,
    {
        self.reserve_maximum_concurrent_capacity(current_len, new_maximum_capacity)
    }

    unsafe fn set_pinned_vec_len(&mut self, len: usize) {
        self.pinned_vec_len = len;
    }

    unsafe fn clear(&mut self, len: usize) {
        let mut take_fragment = |_fragment: Fragment<T>| {};
        unsafe { self.process_into_fragments(len, &mut take_fragment) };
        self.zero();

        let max_num_fragments = self.data.len();
        self.data.clear();

        for _ in 0..max_num_fragments {
            self.data.push(UnsafeCell::new(core::ptr::null_mut()));
        }

        self.maximum_capacity = (0..self.data.len()).map(|f| self.capacity_of(f)).sum();
        self.pinned_vec_len = 0;
    }
}