stratus/eth/primitives/
index.rs

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