1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
use crate::abi::{InvalidOutputType, Tokenizable, TokenizableItem};
use ethabi::{ethereum_types::U256, Token};
use serde::{Deserialize, Serialize};
use std::ops::{Add, Sub};
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default, Ord, PartialOrd)]
#[repr(transparent)]
#[serde(transparent)]
pub struct Uint8(u8);
impl From<u8> for Uint8 {
fn from(val: u8) -> Self {
Uint8(val)
}
}
impl From<Uint8> for u8 {
fn from(val: Uint8) -> Self {
val.0
}
}
impl From<Uint8> for U256 {
fn from(val: Uint8) -> Self {
U256::from(val.0)
}
}
impl PartialEq<u8> for Uint8 {
fn eq(&self, other: &u8) -> bool {
self.0 == *other
}
}
impl Add for Uint8 {
type Output = Self;
fn add(self, rhs: Self) -> Self::Output {
Uint8(self.0 + rhs.0)
}
}
impl Sub for Uint8 {
type Output = Self;
fn sub(self, rhs: Self) -> Self::Output {
Uint8(self.0 - rhs.0)
}
}
impl Add<u8> for Uint8 {
type Output = Self;
fn add(self, rhs: u8) -> Self::Output {
Uint8(self.0 + rhs)
}
}
impl Sub<u8> for Uint8 {
type Output = Self;
fn sub(self, rhs: u8) -> Self::Output {
Uint8(self.0 - rhs)
}
}
impl Tokenizable for Uint8 {
fn from_token(token: Token) -> Result<Self, InvalidOutputType> {
match token {
Token::Int(data) | Token::Uint(data) => {
if data > U256::from(u8::MAX) {
return Err(InvalidOutputType("Integer overflow when casting to u8".to_string()))
}
Ok(Uint8(data.low_u32() as u8))
}
other => Err(InvalidOutputType(format!("Expected `uint8`, got {other:?}"))),
}
}
fn into_token(self) -> Token {
Token::Uint(self.into())
}
}
impl TokenizableItem for Uint8 {}
#[cfg(test)]
mod tests {
use super::*;
use crate::abi::AbiType;
use ethabi::ParamType;
#[test]
fn uint8_array() {
assert_eq!(
<[Uint8; 8usize]>::param_type(),
ParamType::FixedArray(Box::new(ParamType::Uint(8),), 8)
);
}
}