Skip to main content

miden_protocol/account/patch/storage/
patch_operation.rs

1use crate::errors::AccountError;
2
3// STORAGE PATCH OPERATION
4// ================================================================================================
5
6/// Describes whether a storage slot was created, updated or removed in an
7/// [`AccountStoragePatch`](crate::account::AccountStoragePatch).
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9#[repr(u8)]
10pub enum StoragePatchOperation {
11    /// The slot was created.
12    Create = Self::CREATE,
13
14    /// An existing slot was updated.
15    Update = Self::UPDATE,
16
17    /// An existing slot was removed.
18    Remove = Self::REMOVE,
19}
20
21impl StoragePatchOperation {
22    const CREATE: u8 = 0;
23    const UPDATE: u8 = 1;
24    const REMOVE: u8 = 2;
25
26    /// Encodes the patch operation as a `u8`.
27    pub const fn as_u8(&self) -> u8 {
28        *self as u8
29    }
30
31    /// Returns `true` if this is a [`StoragePatchOperation::Create`], `false` otherwise.
32    pub const fn is_create(&self) -> bool {
33        matches!(self, Self::Create)
34    }
35
36    /// Returns `true` if this is a [`StoragePatchOperation::Update`], `false` otherwise.
37    pub const fn is_update(&self) -> bool {
38        matches!(self, Self::Update)
39    }
40
41    /// Returns `true` if this is a [`StoragePatchOperation::Remove`], `false` otherwise.
42    pub const fn is_remove(&self) -> bool {
43        matches!(self, Self::Remove)
44    }
45}
46
47impl TryFrom<u8> for StoragePatchOperation {
48    type Error = AccountError;
49
50    /// Decodes a patch operation from a `u8`.
51    ///
52    /// # Errors
53    ///
54    /// Returns an error if the value is not a valid patch operation.
55    fn try_from(value: u8) -> Result<Self, Self::Error> {
56        match value {
57            Self::CREATE => Ok(Self::Create),
58            Self::UPDATE => Ok(Self::Update),
59            Self::REMOVE => Ok(Self::Remove),
60            other => Err(AccountError::UnknownStoragePatchOperation(other)),
61        }
62    }
63}