stratus/eth/primitives/
index.rs

1use alloy_primitives::U64;
2use alloy_primitives::U256;
3use display_json::DebugAsJson;
4
5use crate::ext::RuintExt;
6
7/// Represents a transaction index or log index.
8#[derive(
9    DebugAsJson, derive_more::Display, Clone, Copy, PartialEq, Eq, fake::Dummy, serde::Serialize, serde::Deserialize, derive_more::Add, Hash, PartialOrd, Ord,
10)]
11pub struct Index(pub u64);
12
13impl Index {
14    pub const ZERO: Index = Index(0u64);
15    pub const ONE: Index = Index(1u64);
16
17    pub fn new(inner: u64) -> Self {
18        Index(inner)
19    }
20}
21
22// -----------------------------------------------------------------------------
23// Conversions: Other -> Self
24// -----------------------------------------------------------------------------
25
26impl From<u64> for Index {
27    fn from(value: u64) -> Self {
28        Self(value)
29    }
30}
31
32impl TryFrom<U256> for Index {
33    type Error = anyhow::Error;
34
35    fn try_from(value: U256) -> Result<Self, Self::Error> {
36        let u64_value = u64::try_from(value).map_err(|_| anyhow::anyhow!("U256 value too large for Index"))?;
37        Ok(Self(u64_value))
38    }
39}
40
41impl TryFrom<i64> for Index {
42    type Error = anyhow::Error;
43
44    fn try_from(value: i64) -> Result<Self, Self::Error> {
45        if value < 0 {
46            return Err(anyhow::anyhow!("Index cannot be negative"));
47        }
48        Ok(Self(value as u64))
49    }
50}
51
52impl From<U64> for Index {
53    fn from(value: U64) -> Self {
54        Index(value.as_u64())
55    }
56}
57
58// -----------------------------------------------------------------------------
59// Conversions: Self -> Other
60// -----------------------------------------------------------------------------
61
62impl From<Index> for u64 {
63    fn from(value: Index) -> u64 {
64        value.0
65    }
66}
67
68impl From<Index> for U64 {
69    fn from(value: Index) -> U64 {
70        U64::from(value.0)
71    }
72}
73
74impl From<Index> for U256 {
75    fn from(value: Index) -> U256 {
76        U256::from(value.0)
77    }
78}