Skip to main content

miden_protocol/asset/
asset_callbacks_flag.rs

1use alloc::string::ToString;
2
3use crate::errors::AssetError;
4use crate::utils::serde::{
5    ByteReader,
6    ByteWriter,
7    Deserializable,
8    DeserializationError,
9    Serializable,
10};
11
12/// The flag in an [`AssetVaultKey`](super::AssetVaultKey) that indicates whether
13/// [`AssetCallbacks`](super::AssetCallbacks) are enabled for this asset.
14#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
15#[repr(u8)]
16pub enum AssetCallbackFlag {
17    #[default]
18    Disabled = Self::DISABLED,
19
20    Enabled = Self::ENABLED,
21}
22
23impl AssetCallbackFlag {
24    const DISABLED: u8 = 0;
25    const ENABLED: u8 = 1;
26
27    /// The serialized size of an [`AssetCallbackFlag`] in bytes.
28    pub const SERIALIZED_SIZE: usize = core::mem::size_of::<AssetCallbackFlag>();
29
30    /// Encodes the callbacks setting as a `u8`.
31    pub const fn as_u8(&self) -> u8 {
32        *self as u8
33    }
34}
35
36impl TryFrom<u8> for AssetCallbackFlag {
37    type Error = AssetError;
38
39    /// Decodes a callbacks setting from a `u8`.
40    ///
41    /// # Errors
42    ///
43    /// Returns an error if the value is not a valid callbacks encoding.
44    fn try_from(value: u8) -> Result<Self, Self::Error> {
45        match value {
46            Self::DISABLED => Ok(Self::Disabled),
47            Self::ENABLED => Ok(Self::Enabled),
48            _ => Err(AssetError::InvalidAssetCallbackFlag(value)),
49        }
50    }
51}
52
53impl Serializable for AssetCallbackFlag {
54    fn write_into<W: ByteWriter>(&self, target: &mut W) {
55        target.write_u8(self.as_u8());
56    }
57
58    fn get_size_hint(&self) -> usize {
59        AssetCallbackFlag::SERIALIZED_SIZE
60    }
61}
62
63impl Deserializable for AssetCallbackFlag {
64    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
65        Self::try_from(source.read_u8()?)
66            .map_err(|err| DeserializationError::InvalidValue(err.to_string()))
67    }
68}