1use bytes::Bytes;
2
3#[derive(Debug, thiserror::Error)]
4pub enum Error {
5 #[error("Mem error")]
6 CpuAllocationError,
7}
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub enum MemoryType {
11 Cpu,
12 Gpu(u32),
13}
14
15pub trait MemBlock {
16 fn to_cpu_bytes(&self) -> Bytes;
17}
18
19pub trait MemoryAllocator {
20 type Data: MemBlock;
21 type Error: std::error::Error + Send + Sync + 'static;
22
23 fn memory_type(&self) -> MemoryType;
24 fn alloc_frame(&self, data: &[u8]) -> Result<Self::Data, Self::Error>;
25}
26
27impl<A: MemoryAllocator> MemoryAllocator for std::sync::Arc<A> {
28 type Data = A::Data;
29 type Error = A::Error;
30
31 fn memory_type(&self) -> MemoryType {
32 (**self).memory_type()
33 }
34
35 fn alloc_frame(&self, data: &[u8]) -> Result<Self::Data, Self::Error> {
36 (**self).alloc_frame(data)
37 }
38}
39
40pub struct CpuMemBlock(Bytes);
41impl MemBlock for CpuMemBlock {
42 fn to_cpu_bytes(&self) -> Bytes {
43 self.0.clone()
44 }
45}
46
47pub struct CpuAllocator;
48
49impl MemoryAllocator for CpuAllocator {
50 type Data = CpuMemBlock;
51 type Error = Error;
52
53 fn memory_type(&self) -> MemoryType {
54 MemoryType::Cpu
55 }
56
57 fn alloc_frame(&self, data: &[u8]) -> Result<Self::Data, Self::Error> {
58 Ok(CpuMemBlock(Bytes::from_owner(data.to_vec())))
59 }
60}