stratus/eth/primitives/
gas.rs

1use alloy_primitives::U64;
2use anyhow::bail;
3use display_json::DebugAsJson;
4#[cfg(test)]
5use fake::Dummy;
6#[cfg(test)]
7use fake::Faker;
8
9use crate::ext::RuintExt;
10
11#[derive(DebugAsJson, derive_more::Display, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
12#[serde(transparent)]
13pub struct Gas(U64);
14
15impl Gas {
16    pub const ZERO: Gas = Gas(U64::ZERO);
17    pub const MAX: Gas = Gas(U64::MAX);
18
19    pub fn as_u64(&self) -> u64 {
20        self.0.as_u64()
21    }
22}
23
24#[cfg(test)]
25impl Dummy<Faker> for Gas {
26    fn dummy_with_rng<R: rand::Rng + ?Sized>(_: &Faker, rng: &mut R) -> Self {
27        rng.next_u64().into()
28    }
29}
30
31// -----------------------------------------------------------------------------
32// Conversions: Other -> Self
33// -----------------------------------------------------------------------------
34
35impl From<u8> for Gas {
36    fn from(value: u8) -> Self {
37        Self(U64::from(value))
38    }
39}
40
41impl From<u16> for Gas {
42    fn from(value: u16) -> Self {
43        Self(U64::from(value))
44    }
45}
46
47impl From<u32> for Gas {
48    fn from(value: u32) -> Self {
49        Self(U64::from(value))
50    }
51}
52
53impl From<u64> for Gas {
54    fn from(value: u64) -> Self {
55        Self(U64::from(value))
56    }
57}
58
59impl TryFrom<i32> for Gas {
60    type Error = anyhow::Error;
61
62    fn try_from(value: i32) -> Result<Self, Self::Error> {
63        if value < 0 {
64            bail!("Gas cannot be negative");
65        }
66        Ok(Self(U64::from(value as u32)))
67    }
68}
69
70// -----------------------------------------------------------------------------
71// Conversions: Self -> Other
72// ----------------------------------------------------------------------------
73
74impl From<Gas> for u64 {
75    fn from(value: Gas) -> Self {
76        value.as_u64()
77    }
78}