1use std::any::Any;
4
5use crate::base::constraint::{SameNumberOfColumns, SameNumberOfRows, ShapeConstraint};
6use crate::base::dimension::{Dim, U1};
7use crate::base::{DefaultAllocator, Scalar};
8use crate::storage::{IsContiguous, RawStorageMut};
9use crate::StorageMut;
10use std::fmt::Debug;
11use std::mem::MaybeUninit;
12
13pub trait Allocator<T, R: Dim, C: Dim = U1>: Any + Sized {
23 type Buffer: StorageMut<T, R, C> + IsContiguous + Clone + Debug;
25 type BufferUninit: RawStorageMut<MaybeUninit<T>, R, C> + IsContiguous;
27
28 fn allocate_uninit(nrows: R, ncols: C) -> Self::BufferUninit;
30
31 unsafe fn assume_init(uninit: Self::BufferUninit) -> Self::Buffer;
37
38 fn allocate_from_iterator<I: IntoIterator<Item = T>>(
40 nrows: R,
41 ncols: C,
42 iter: I,
43 ) -> Self::Buffer;
44}
45
46pub trait Reallocator<T: Scalar, RFrom: Dim, CFrom: Dim, RTo: Dim, CTo: Dim>:
49 Allocator<T, RFrom, CFrom> + Allocator<T, RTo, CTo>
50{
51 unsafe fn reallocate_copy(
60 nrows: RTo,
61 ncols: CTo,
62 buf: <Self as Allocator<T, RFrom, CFrom>>::Buffer,
63 ) -> <Self as Allocator<T, RTo, CTo>>::BufferUninit;
64}
65
66pub type SameShapeR<R1, R2> = <ShapeConstraint as SameNumberOfRows<R1, R2>>::Representative;
68
69pub type SameShapeC<C1, C2> = <ShapeConstraint as SameNumberOfColumns<C1, C2>>::Representative;
71
72pub trait SameShapeAllocator<T, R1, C1, R2, C2>:
75 Allocator<T, R1, C1> + Allocator<T, SameShapeR<R1, R2>, SameShapeC<C1, C2>>
76where
77 R1: Dim,
78 R2: Dim,
79 C1: Dim,
80 C2: Dim,
81 ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2>,
82{
83}
84
85impl<T, R1, R2, C1, C2> SameShapeAllocator<T, R1, C1, R2, C2> for DefaultAllocator
86where
87 R1: Dim,
88 R2: Dim,
89 C1: Dim,
90 C2: Dim,
91 DefaultAllocator: Allocator<T, R1, C1> + Allocator<T, SameShapeR<R1, R2>, SameShapeC<C1, C2>>,
92 ShapeConstraint: SameNumberOfRows<R1, R2> + SameNumberOfColumns<C1, C2>,
93{
94}
95
96pub trait SameShapeVectorAllocator<T, R1, R2>:
99 Allocator<T, R1> + Allocator<T, SameShapeR<R1, R2>> + SameShapeAllocator<T, R1, U1, R2, U1>
100where
101 R1: Dim,
102 R2: Dim,
103 ShapeConstraint: SameNumberOfRows<R1, R2>,
104{
105}
106
107impl<T, R1, R2> SameShapeVectorAllocator<T, R1, R2> for DefaultAllocator
108where
109 R1: Dim,
110 R2: Dim,
111 DefaultAllocator: Allocator<T, R1, U1> + Allocator<T, SameShapeR<R1, R2>>,
112 ShapeConstraint: SameNumberOfRows<R1, R2>,
113{
114}