Skip to main content

casperlabs_types/
phase.rs

1// Can be removed once https://github.com/rust-lang/rustfmt/issues/3362 is resolved.
2#[rustfmt::skip]
3use alloc::vec;
4use alloc::vec::Vec;
5
6use num_derive::{FromPrimitive, ToPrimitive};
7use num_traits::{FromPrimitive, ToPrimitive};
8
9use crate::{
10    bytesrepr::{Error, FromBytes, ToBytes},
11    CLType, CLTyped,
12};
13
14/// The number of bytes in a serialized [`Phase`].
15pub const PHASE_SERIALIZED_LENGTH: usize = 1;
16
17/// The phase in which a given contract is executing.
18#[derive(Debug, PartialEq, Eq, Clone, Copy, FromPrimitive, ToPrimitive)]
19#[repr(u8)]
20pub enum Phase {
21    /// Set while committing the genesis or upgrade configurations.
22    System = 0,
23    /// Set while executing the payment code of a deploy.
24    Payment = 1,
25    /// Set while executing the session code of a deploy.
26    Session = 2,
27    /// Set while finalizing payment at the end of a deploy.
28    FinalizePayment = 3,
29}
30
31impl ToBytes for Phase {
32    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
33        let id = self.to_u8().expect("Phase is represented as a u8");
34
35        Ok(vec![id])
36    }
37
38    fn serialized_length(&self) -> usize {
39        PHASE_SERIALIZED_LENGTH
40    }
41}
42
43impl FromBytes for Phase {
44    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
45        let (id, rest) = u8::from_bytes(bytes)?;
46        let phase = FromPrimitive::from_u8(id).ok_or(Error::Formatting)?;
47        Ok((phase, rest))
48    }
49}
50
51impl CLTyped for Phase {
52    fn cl_type() -> CLType {
53        CLType::U8
54    }
55}