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
use core::fmt::Debug;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::ptr::{self, NonNull};

use crate::error::StorageError;
use crate::index::{Grow, GrowDoubling, GrowExact, Index};
use crate::storage::alloc::{
    AllocHandle, AllocHandleParts, FatAllocHandle, FixedAlloc, SpillAlloc, ThinAllocHandle,
};
use crate::storage::{
    ArrayStorage, Global, Inline, InlineBuffer, RawAlloc, RawAllocIn, RawAllocNew, SpillStorage,
    Thin, WithAlloc,
};

use super::buffer::{VecBuffer, VecBufferNew, VecBufferSpawn, VecData, VecHeader};

pub trait VecAlloc {
    type RawAlloc: RawAlloc;
    type AllocHandle<T, I: Index>: AllocHandle<Alloc = Self::RawAlloc, Meta = VecData<T, I>>;
}

impl<A: RawAlloc> VecAlloc for A {
    type RawAlloc = A;
    type AllocHandle<T, I: Index> = FatAllocHandle<VecData<T, I>, A>;
}

pub trait VecConfig {
    type Buffer<T>: VecBuffer<Data = T, Index = Self::Index>;
    type Grow: Grow;
    type Index: Index;
}

impl<C: VecAlloc> VecConfig for C {
    type Buffer<T> = C::AllocHandle<T, Self::Index>;
    type Grow = GrowDoubling;
    type Index = usize;
}

pub trait VecConfigAlloc<T>: VecConfig {
    type Alloc: RawAlloc;

    fn allocator(buf: &Self::Buffer<T>) -> &Self::Alloc;
}

impl<T, C: VecConfig> VecConfigAlloc<T> for C
where
    C::Buffer<T>: AllocHandle<Meta = VecData<T, Self::Index>>,
{
    type Alloc = <C::Buffer<T> as AllocHandle>::Alloc;

    #[inline]
    fn allocator(buf: &Self::Buffer<T>) -> &Self::Alloc {
        buf.allocator()
    }
}

pub trait VecConfigAllocParts<T>: VecConfigAlloc<T> {
    fn vec_from_parts(
        data: NonNull<T>,
        length: Self::Index,
        capacity: Self::Index,
        alloc: Self::Alloc,
    ) -> Self::Buffer<T>;

    fn vec_into_parts(
        buffer: Self::Buffer<T>,
    ) -> (NonNull<T>, Self::Index, Self::Index, Self::Alloc);
}

impl<T, C: VecConfigAlloc<T>> VecConfigAllocParts<T> for C
where
    C::Buffer<T>: AllocHandleParts<Alloc = Self::Alloc, Meta = VecData<T, Self::Index>>,
{
    #[inline]
    fn vec_from_parts(
        data: NonNull<T>,
        length: Self::Index,
        capacity: Self::Index,
        alloc: Self::Alloc,
    ) -> Self::Buffer<T> {
        Self::Buffer::<T>::handle_from_parts(VecHeader { capacity, length }, data, alloc)
    }

    #[inline]
    fn vec_into_parts(
        buffer: Self::Buffer<T>,
    ) -> (NonNull<T>, Self::Index, Self::Index, Self::Alloc) {
        let (header, data, alloc) = buffer.handle_into_parts();
        (data, header.length, header.capacity, alloc)
    }
}

pub trait VecConfigNew<T>: VecConfigSpawn<T> {
    const NEW: Self::Buffer<T>;

    fn vec_try_new(capacity: Self::Index, exact: bool) -> Result<Self::Buffer<T>, StorageError>;
}

impl<T, C: VecConfigSpawn<T>> VecConfigNew<T> for C
where
    Self::Buffer<T>: VecBufferNew,
{
    const NEW: Self::Buffer<T> = Self::Buffer::<T>::NEW;

    #[inline]
    fn vec_try_new(capacity: Self::Index, exact: bool) -> Result<Self::Buffer<T>, StorageError> {
        Self::Buffer::<T>::vec_try_new(capacity, exact)
    }
}

pub trait VecConfigSpawn<T>: VecConfig {
    fn vec_try_spawn(
        buf: &Self::Buffer<T>,
        capacity: Self::Index,
        exact: bool,
    ) -> Result<Self::Buffer<T>, StorageError>;
}

impl<T, C: VecConfig> VecConfigSpawn<T> for C
where
    Self::Buffer<T>: VecBufferSpawn,
{
    #[inline]
    fn vec_try_spawn(
        buf: &Self::Buffer<T>,
        capacity: Self::Index,
        exact: bool,
    ) -> Result<Self::Buffer<T>, StorageError> {
        Self::Buffer::<T>::vec_try_spawn(buf, capacity, exact)
    }
}

#[derive(Debug, Default)]
pub struct Custom<C: VecAlloc, I: Index = usize, G: Grow = GrowExact>(
    C::RawAlloc,
    PhantomData<(I, G)>,
);

// FIXME add generic ConstDefault trait
impl<C: RawAllocNew, I: Index, G: Grow> Custom<C, I, G> {
    #[inline]
    pub const fn new() -> Self {
        Self(C::NEW, PhantomData)
    }
}

impl<C: VecAlloc, I: Index, G: Grow> VecConfig for Custom<C, I, G> {
    type Buffer<T> = C::AllocHandle<T, Self::Index>;
    type Grow = G;
    type Index = I;
}

// impl<'a> VecAlloc for Fixed<'a> {
//     type RawAlloc = FixedAlloc<'a>;
//     type AllocHandle<T, I: Index> = FatAllocHandle<VecData<T, I>, Self::RawAlloc>;
// }

impl<const N: usize> VecConfig for Inline<N> {
    type Buffer<T> = InlineBuffer<T, N>;
    type Index = usize;
    type Grow = GrowExact;
}

impl VecAlloc for Thin {
    type RawAlloc = Global;
    type AllocHandle<T, I: Index> = ThinAllocHandle<VecData<T, I>, Global>;
}

pub trait VecNewIn<T> {
    type Config: VecConfig;

    fn vec_try_new_in(
        self,
        capacity: <Self::Config as VecConfig>::Index,
        exact: bool,
    ) -> Result<<Self::Config as VecConfig>::Buffer<T>, StorageError>;
}

impl<T, C: RawAllocIn> VecNewIn<T> for C {
    type Config = C::RawAlloc;

    #[inline]
    fn vec_try_new_in(
        self,
        capacity: <Self::Config as VecConfig>::Index,
        exact: bool,
    ) -> Result<<Self::Config as VecConfig>::Buffer<T>, StorageError> {
        <Self::Config as VecConfig>::Buffer::<T>::alloc_handle_in(
            self,
            VecHeader {
                capacity,
                length: Index::ZERO,
            },
            exact,
        )
    }
}

impl<T, C: VecAlloc, I: Index, G: Grow> VecNewIn<T> for Custom<C, I, G> {
    type Config = Self;

    #[inline]
    fn vec_try_new_in(
        self,
        capacity: <Self::Config as VecConfig>::Index,
        exact: bool,
    ) -> Result<<Self::Config as VecConfig>::Buffer<T>, StorageError> {
        C::AllocHandle::alloc_handle_in(
            self.0,
            VecHeader {
                capacity,
                length: Index::ZERO,
            },
            exact,
        )
    }
}

impl<'a, T> VecNewIn<T> for ArrayStorage<&'a mut [MaybeUninit<T>]> {
    type Config = FixedAlloc<'a>;

    #[inline]
    fn vec_try_new_in(
        self,
        mut capacity: <Self::Config as VecConfig>::Index,
        exact: bool,
    ) -> Result<<Self::Config as VecConfig>::Buffer<T>, StorageError> {
        let len = self.0.len();
        if capacity.to_usize() > len {
            return Err(StorageError::CapacityLimit);
        }
        if !exact {
            capacity = Index::from_usize(len.min(<Self::Config as VecConfig>::Index::MAX_USIZE));
        }
        Ok(<Self::Config as VecConfig>::Buffer::<T>::handle_from_parts(
            VecHeader {
                capacity,
                length: Index::ZERO,
            },
            unsafe { NonNull::new_unchecked(self.0.as_mut_ptr()) }.cast(),
            FixedAlloc::default(),
        ))
    }
}

impl<'a, T: 'a> WithAlloc<'a> for ArrayStorage<&'a mut [MaybeUninit<T>]> {
    type NewIn<A: 'a> = SpillStorage<'a, &'a mut [MaybeUninit<T>], A>;

    #[inline]
    fn with_alloc_in<A: RawAlloc + 'a>(self, alloc: A) -> Self::NewIn<A> {
        SpillStorage::new_in(self.0, alloc)
    }
}

impl<'a, T, const N: usize> VecNewIn<T> for &'a mut ArrayStorage<[MaybeUninit<T>; N]> {
    type Config = FixedAlloc<'a>;

    #[inline]
    fn vec_try_new_in(
        self,
        mut capacity: <Self::Config as VecConfig>::Index,
        exact: bool,
    ) -> Result<<Self::Config as VecConfig>::Buffer<T>, StorageError> {
        if capacity > N {
            return Err(StorageError::CapacityLimit);
        }
        if !exact {
            capacity = N;
        }
        Ok(<Self::Config as VecConfig>::Buffer::<T>::handle_from_parts(
            VecHeader {
                capacity,
                length: Index::ZERO,
            },
            unsafe { NonNull::new_unchecked(self.0.as_mut_ptr()) }.cast(),
            FixedAlloc::default(),
        ))
    }
}

impl<'a, T: 'a, const N: usize> WithAlloc<'a> for &'a mut ArrayStorage<[MaybeUninit<T>; N]> {
    type NewIn<A: 'a> = SpillStorage<'a, &'a mut [MaybeUninit<T>], A>;

    #[inline]
    fn with_alloc_in<A: RawAlloc + 'a>(self, alloc: A) -> Self::NewIn<A> {
        SpillStorage::new_in(&mut self.0, alloc)
    }
}

impl<'a, T, A: RawAlloc> VecNewIn<T> for SpillStorage<'a, &'a mut [MaybeUninit<T>], A> {
    type Config = SpillAlloc<'a, A>;

    fn vec_try_new_in(
        self,
        mut capacity: <Self::Config as VecConfig>::Index,
        exact: bool,
    ) -> Result<<Self::Config as VecConfig>::Buffer<T>, StorageError> {
        if capacity > self.buffer.len() {
            return <Self::Config as VecConfig>::Buffer::<T>::alloc_handle_in(
                SpillAlloc::new(self.alloc, ptr::null()),
                VecHeader {
                    capacity,
                    length: Index::ZERO,
                },
                exact,
            );
        }
        if !exact {
            capacity = self.buffer.len();
        }
        let ptr = self.buffer.as_mut_ptr();
        Ok(<Self::Config as VecConfig>::Buffer::<T>::handle_from_parts(
            VecHeader {
                capacity,
                length: Index::ZERO,
            },
            unsafe { NonNull::new_unchecked(ptr) }.cast(),
            SpillAlloc::new(self.alloc, ptr.cast()),
        ))
    }
}

impl<T, const N: usize> VecNewIn<T> for Inline<N> {
    type Config = Inline<N>;

    #[inline]
    fn vec_try_new_in(
        self,
        capacity: <Self::Config as VecConfig>::Index,
        exact: bool,
    ) -> Result<<Self::Config as VecConfig>::Buffer<T>, StorageError> {
        if capacity > N || (capacity < N && exact) {
            return Err(StorageError::CapacityLimit);
        }
        Ok(InlineBuffer::new())
    }
}

impl<T> VecNewIn<T> for Thin {
    type Config = Thin;

    #[inline]
    fn vec_try_new_in(
        self,
        capacity: <Self::Config as VecConfig>::Index,
        exact: bool,
    ) -> Result<<Self::Config as VecConfig>::Buffer<T>, StorageError> {
        <Self::Config as VecConfig>::Buffer::<T>::alloc_handle_in(
            Global,
            VecHeader {
                capacity,
                length: Index::ZERO,
            },
            exact,
        )
    }
}