flex_alloc/vec/
config.rs

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
//! `Vec` configuration types and trait definitions.

use core::fmt::Debug;
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::ptr::{self, NonNull};

use const_default::ConstDefault;

use crate::alloc::{AllocateIn, Allocator, AllocatorDefault, Fixed, Global, Spill};
use crate::capacity::{Grow, GrowDoubling, GrowExact, Index};
use crate::error::StorageError;
use crate::storage::{ArrayStorage, FatBuffer, Inline, InlineBuffer, SpillStorage, ThinBuffer};

use super::buffer::{VecBuffer, VecHeader};

/// Define the associated types for `Vec` instances.
pub trait VecConfig {
    /// The internal buffer type.
    type Buffer<T>: VecBuffer<Item = T, Index = Self::Index>;

    /// The growth strategy.
    type Grow: Grow;

    /// The index type used to define the capacity and length.
    type Index: Index;
}

impl<A: Allocator> VecConfig for A {
    type Buffer<T> = FatBuffer<T, VecHeader<usize>, A>;
    type Grow = GrowDoubling;
    type Index = usize;
}

/// Configuration for `Vec` types supporting an allocator.
pub trait VecConfigAlloc<T>: VecConfig {
    /// The allocator instance type.
    type Alloc: Allocator;

    /// Get a reference to the allocator instance.
    fn allocator(buf: &Self::Buffer<T>) -> &Self::Alloc;

    /// Create a `Vec` buffer instance from its constituent parts.
    fn buffer_from_parts(
        data: NonNull<T>,
        length: Self::Index,
        capacity: Self::Index,
        alloc: Self::Alloc,
    ) -> Self::Buffer<T>;

    /// Disassemble a `Vec` buffer instance into its constituent parts.
    fn buffer_into_parts(
        buffer: Self::Buffer<T>,
    ) -> (NonNull<T>, Self::Index, Self::Index, Self::Alloc);
}

impl<T, A: Allocator> VecConfigAlloc<T> for A {
    type Alloc = A;

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

    #[inline]
    fn buffer_from_parts(
        data: NonNull<T>,
        length: Self::Index,
        capacity: Self::Index,
        alloc: Self::Alloc,
    ) -> Self::Buffer<T> {
        FatBuffer::from_parts(VecHeader { capacity, length }, data, alloc)
    }

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

/// Support creation of new `Vec` instances without a storage reference.
pub trait VecConfigNew<T>: VecConfigSpawn<T> {
    /// Constant initializer for an empty buffer.
    const EMPTY_BUFFER: Self::Buffer<T>;

    /// Try to create a new buffer instance with a given capacity.
    fn buffer_try_new(capacity: Self::Index, exact: bool) -> Result<Self::Buffer<T>, StorageError>;
}

impl<T, A: AllocatorDefault> VecConfigNew<T> for A {
    const EMPTY_BUFFER: Self::Buffer<T> = FatBuffer::<T, VecHeader<usize>, A>::DEFAULT;

    #[inline]
    fn buffer_try_new(capacity: Self::Index, exact: bool) -> Result<Self::Buffer<T>, StorageError> {
        FatBuffer::allocate_in(
            VecHeader {
                capacity,
                length: Self::Index::ZERO,
            },
            A::DEFAULT,
            exact,
        )
    }
}

/// Support creation of new `Vec` buffer instances from an existing instance.
pub trait VecConfigSpawn<T>: VecConfig {
    /// Try to create a new buffer instance with a given capacity.
    fn buffer_try_spawn(
        buf: &Self::Buffer<T>,
        capacity: Self::Index,
        exact: bool,
    ) -> Result<Self::Buffer<T>, StorageError>;
}

impl<T, A: Allocator + Clone> VecConfigSpawn<T> for A {
    #[inline]
    fn buffer_try_spawn(
        buf: &Self::Buffer<T>,
        capacity: Self::Index,
        exact: bool,
    ) -> Result<Self::Buffer<T>, StorageError> {
        FatBuffer::allocate_in(
            VecHeader {
                capacity,
                length: Index::ZERO,
            },
            buf.alloc.clone(),
            exact,
        )
    }
}

/// Support creation of a new `Vec` instance within an allocation target.
pub trait VecNewIn<T> {
    /// The associated `Vec` configuration type.
    type Config: VecConfig;

    /// Try to create a new buffer given an allocation target.
    fn buffer_try_new_in(
        self,
        capacity: <Self::Config as VecConfig>::Index,
        exact: bool,
    ) -> Result<<Self::Config as VecConfig>::Buffer<T>, StorageError>;
}

/// Parameterize `Vec` with a custom index type or growth behavior.
#[derive(Debug, Default)]
pub struct Custom<A: Allocator, I: Index = usize, G: Grow = GrowExact> {
    alloc: A,
    _pd: PhantomData<(I, G)>,
}

impl<A: AllocatorDefault, I: Index, G: Grow> ConstDefault for Custom<A, I, G> {
    /// An instance of this custom `Vec` definition, which may be used as an allocation target.
    const DEFAULT: Self = Self {
        alloc: A::DEFAULT,
        _pd: PhantomData,
    };
}

impl<A: Allocator, I: Index, G: Grow> VecConfig for Custom<A, I, G> {
    type Buffer<T> = FatBuffer<T, VecHeader<I>, A>;
    type Grow = G;
    type Index = I;
}

impl<T, A: AllocatorDefault, I: Index, G: Grow> VecConfigNew<T> for Custom<A, I, G> {
    const EMPTY_BUFFER: Self::Buffer<T> = FatBuffer::DEFAULT;

    fn buffer_try_new(capacity: Self::Index, exact: bool) -> Result<Self::Buffer<T>, StorageError> {
        FatBuffer::allocate_in(
            VecHeader {
                capacity,
                length: Self::Index::ZERO,
            },
            A::DEFAULT,
            exact,
        )
    }
}

impl<T, A: Allocator + Clone, I: Index, G: Grow> VecConfigSpawn<T> for Custom<A, I, G> {
    #[inline]
    fn buffer_try_spawn(
        buf: &Self::Buffer<T>,
        capacity: Self::Index,
        exact: bool,
    ) -> Result<Self::Buffer<T>, StorageError> {
        FatBuffer::allocate_in(
            VecHeader {
                capacity,
                length: Index::ZERO,
            },
            buf.alloc.clone(),
            exact,
        )
    }
}

/// Parameterize `Vec` with a custom index type or growth behavior.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Thin<A: Allocator = Global, I: Index = usize, G: Grow = GrowExact> {
    alloc: A,
    _pd: PhantomData<(I, G)>,
}

impl<A: Allocator, I: Index, G: Grow> VecConfig for Thin<A, I, G> {
    type Buffer<T> = ThinBuffer<T, VecHeader<usize>, A>;
    type Grow = GrowDoubling;
    type Index = usize;
}

impl<A: AllocatorDefault, I: Index, G: Grow> ConstDefault for Thin<A, I, G> {
    const DEFAULT: Self = Self {
        alloc: A::DEFAULT,
        _pd: PhantomData,
    };
}

impl<T, A: Allocator, I: Index, G: Grow> VecConfigAlloc<T> for Thin<A, I, G> {
    type Alloc = A;

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

    #[inline]
    fn buffer_from_parts(
        data: NonNull<T>,
        length: Self::Index,
        capacity: Self::Index,
        alloc: Self::Alloc,
    ) -> Self::Buffer<T> {
        ThinBuffer::from_parts(VecHeader { capacity, length }, data, alloc)
    }

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

impl<T, A: AllocatorDefault, I: Index, G: Grow> VecConfigNew<T> for Thin<A, I, G> {
    const EMPTY_BUFFER: Self::Buffer<T> = ThinBuffer::<T, VecHeader<usize>, A>::DEFAULT;

    #[inline]
    fn buffer_try_new(capacity: Self::Index, exact: bool) -> Result<Self::Buffer<T>, StorageError> {
        ThinBuffer::allocate_in(
            VecHeader {
                capacity,
                length: Self::Index::ZERO,
            },
            A::DEFAULT,
            exact,
        )
    }
}

impl<T, A: Allocator + Clone, I: Index, G: Grow> VecConfigSpawn<T> for Thin<A, I, G> {
    #[inline]
    fn buffer_try_spawn(
        buf: &Self::Buffer<T>,
        capacity: Self::Index,
        exact: bool,
    ) -> Result<Self::Buffer<T>, StorageError> {
        ThinBuffer::allocate_in(
            VecHeader {
                capacity,
                length: Index::ZERO,
            },
            buf.alloc.clone(),
            exact,
        )
    }
}

impl<T, A: AllocatorDefault, I: Index, G: Grow> VecNewIn<T> for Thin<A, I, G> {
    type Config = Thin<A, I, G>;

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

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

impl<T, const N: usize> VecConfigNew<T> for Inline<N> {
    const EMPTY_BUFFER: Self::Buffer<T> = InlineBuffer::<T, N>::DEFAULT;

    fn buffer_try_new(capacity: Self::Index, exact: bool) -> Result<Self::Buffer<T>, StorageError> {
        InlineBuffer::try_for_capacity(capacity, exact)
    }
}

impl<T, const N: usize> VecConfigSpawn<T> for Inline<N> {
    #[inline]
    fn buffer_try_spawn(
        _buf: &Self::Buffer<T>,
        capacity: Self::Index,
        exact: bool,
    ) -> Result<Self::Buffer<T>, StorageError> {
        InlineBuffer::try_for_capacity(capacity, exact)
    }
}

impl<T, C: AllocateIn> VecNewIn<T> for C {
    type Config = C::Alloc;

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

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

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

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

    #[inline]
    fn buffer_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(FatBuffer::from_parts(
            VecHeader {
                capacity,
                length: Index::ZERO,
            },
            NonNull::from(&mut self.0).cast(),
            Fixed::default(),
        ))
    }
}

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

    fn buffer_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 FatBuffer::allocate_in(
                VecHeader {
                    capacity,
                    length: Index::ZERO,
                },
                Spill::new(self.alloc, ptr::null(), Fixed::DEFAULT),
                exact,
            );
        }
        if !exact {
            capacity = self.buffer.len();
        }
        let data = NonNull::from(self.buffer).cast::<T>();
        Ok(FatBuffer::from_parts(
            VecHeader {
                capacity,
                length: Index::ZERO,
            },
            data,
            Spill::new(self.alloc, data.as_ptr().cast::<u8>(), Fixed::DEFAULT),
        ))
    }
}

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

    #[inline]
    fn buffer_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::DEFAULT)
    }
}