musli_core/alloc/allocator.rs
1use super::RawVec;
2
3/// An allocator that can be used in combination with a context.
4pub trait Allocator {
5 /// The type of an allocated buffer.
6 type RawVec<'this, T>: RawVec<T>
7 where
8 Self: 'this,
9 T: 'this;
10
11 /// Construct an empty uninitialized raw vector with an alignment matching
12 /// that of `T` that is associated with this allocator.
13 ///
14 /// ## Examples
15 ///
16 /// ```
17 /// use musli::alloc::{Allocator, RawVec};
18 ///
19 /// let values: [u32; 4] = [1, 2, 3, 4];
20 ///
21 /// musli::alloc::default!(|alloc| {
22 /// let mut buf = alloc.new_raw_vec::<u32>();
23 /// let mut len = 0;
24 ///
25 /// for value in values {
26 /// if !buf.resize(len, 1) {
27 /// panic!("Allocation failed");
28 /// }
29 ///
30 /// // SAFETY: We've just resized the above buffer.
31 /// unsafe {
32 /// buf.as_mut_ptr().add(len).write(value);
33 /// }
34 ///
35 /// len += 1;
36 /// }
37 ///
38 /// // SAFETY: Slice does not outlive the buffer it references.
39 /// let bytes = unsafe { core::slice::from_raw_parts(buf.as_ptr(), len) };
40 /// assert_eq!(bytes, values);
41 /// });
42 /// ```
43 fn new_raw_vec<'a, T>(&'a self) -> Self::RawVec<'a, T>
44 where
45 T: 'a;
46}
47
48impl<A> Allocator for &A
49where
50 A: ?Sized + Allocator,
51{
52 type RawVec<'this, T> = A::RawVec<'this, T> where Self: 'this, T: 'this;
53
54 #[inline(always)]
55 fn new_raw_vec<'a, T>(&'a self) -> Self::RawVec<'a, T>
56 where
57 T: 'a,
58 {
59 (*self).new_raw_vec::<T>()
60 }
61}