casper_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        // NOTE: Assumed safe as [`Phase`] is represented as u8.
34        let id = self.to_u8().expect("Phase is represented as a u8");
35
36        Ok(vec![id])
37    }
38
39    fn serialized_length(&self) -> usize {
40        PHASE_SERIALIZED_LENGTH
41    }
42}
43
44impl FromBytes for Phase {
45    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
46        let (id, rest) = u8::from_bytes(bytes)?;
47        let phase = FromPrimitive::from_u8(id).ok_or(Error::Formatting)?;
48        Ok((phase, rest))
49    }
50}
51
52impl CLTyped for Phase {
53    fn cl_type() -> CLType {
54        CLType::U8
55    }
56}