glycin_utils/memory/
fungible.rs1use std::ops::{Deref, DerefMut};
2
3use crate::{ByteData, MemoryAllocationError};
4
5#[derive(Debug)]
6pub enum FungibleMemory {
7 #[cfg(feature = "external")]
8 SharedMemory(crate::SharedMemory),
9 LocalMemory(Vec<u8>),
10}
11
12impl FungibleMemory {
13 pub fn from_vec(vec: Vec<u8>) -> Self {
14 FungibleMemory::LocalMemory(vec)
15 }
16}
17
18impl ByteData for FungibleMemory {
19 fn new(size: u64) -> std::io::Result<Self> {
20 Ok(Self::LocalMemory(vec![0; size as usize]))
21 }
22
23 fn into_fungible(self) -> FungibleMemory {
24 self
25 }
26
27 #[cfg(feature = "external")]
28 fn from_shared(shared: crate::SharedMemory) -> Self {
29 FungibleMemory::SharedMemory(shared)
30 }
31
32 fn into_other<O: ByteData>(self) -> Result<O, MemoryAllocationError> {
33 match self {
34 Self::LocalMemory(local) => O::try_from_vec(local),
35 #[cfg(feature = "external")]
36 Self::SharedMemory(shared) => Ok(O::from_shared(shared)),
37 }
38 }
39
40 fn try_from_vec(value: Vec<u8>) -> Result<Self, MemoryAllocationError> {
41 Ok(Self::LocalMemory(value))
42 }
43
44 fn try_from_slice(value: &[u8]) -> Result<Self, MemoryAllocationError> {
45 Ok(Self::LocalMemory(value.to_vec()))
46 }
47
48 async fn initial_seal(&mut self) -> Result<(), MemoryAllocationError> {
49 #[cfg(feature = "external")]
50 if let Self::SharedMemory(shared) = self {
51 shared.initial_seal().await?;
52 }
53
54 Ok(())
55 }
56
57 async fn final_seal(&mut self) -> Result<(), MemoryAllocationError> {
58 #[cfg(feature = "external")]
59 if let Self::SharedMemory(shared) = self {
60 shared.final_seal().await?;
61 }
62
63 Ok(())
64 }
65
66 #[cfg(feature = "glib")]
67 fn into_gbytes(self) -> Result<glib::Bytes, MemoryAllocationError> {
68 match self {
69 FungibleMemory::LocalMemory(local) => Ok(glib::Bytes::from_owned(local)),
70 #[cfg(feature = "external")]
71 FungibleMemory::SharedMemory(shared) => shared.into_gbytes(),
72 }
73 }
74}
75
76impl Deref for FungibleMemory {
77 type Target = [u8];
78
79 fn deref(&self) -> &[u8] {
80 match self {
81 Self::LocalMemory(local) => local,
82 #[cfg(feature = "external")]
83 Self::SharedMemory(shared) => shared,
84 }
85 }
86}
87
88impl DerefMut for FungibleMemory {
89 fn deref_mut(&mut self) -> &mut [u8] {
90 match self {
91 Self::LocalMemory(local) => local,
92 #[cfg(feature = "external")]
93 Self::SharedMemory(shared) => shared,
94 }
95 }
96}
97
98impl From<Vec<u8>> for FungibleMemory {
99 fn from(value: Vec<u8>) -> Self {
100 Self::LocalMemory(value)
101 }
102}