Skip to content

Commit 6f2db3e

Browse files
committed
refactor(unit): consolidate AsByte32 trait
Signed-off-by: Ricky Saechao <[email protected]>
1 parent 0ca7fc8 commit 6f2db3e

File tree

1 file changed

+16
-20
lines changed

1 file changed

+16
-20
lines changed

src/contract/contract_function_parameters.rs

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use num_bigint::{
77
Sign,
88
};
99

10+
use self::private::Sealed;
1011
use crate::contract::contract_function_selector::ContractFunctionSelector;
1112
use crate::ethereum::SolidityAddress;
1213

@@ -23,25 +24,20 @@ struct Argument {
2324
is_dynamic: bool,
2425
}
2526

26-
trait IntoBytes32 {
27-
fn get_bytes_32(&self) -> Vec<u8>;
27+
mod private {
28+
pub trait Sealed {}
29+
impl Sealed for String {}
30+
impl Sealed for str {}
31+
impl Sealed for [u8; 32] {}
2832
}
2933

30-
impl IntoBytes32 for &[u8; 32] {
31-
fn get_bytes_32(&self) -> Vec<u8> {
32-
self.to_vec()
33-
}
34+
pub trait AsBytes32: Sealed {
35+
fn as_bytes32(&self) -> &[u8];
3436
}
3537

36-
impl IntoBytes32 for String {
37-
fn get_bytes_32(&self) -> Vec<u8> {
38-
self.as_bytes().to_vec()
39-
}
40-
}
41-
42-
impl IntoBytes32 for &str {
43-
fn get_bytes_32(&self) -> Vec<u8> {
44-
self.as_bytes().to_vec()
38+
impl<T: Sealed + AsRef<[u8]> + ?Sized> AsBytes32 for T {
39+
fn as_bytes32(&self) -> &[u8] {
40+
self.as_ref()
4541
}
4642
}
4743

@@ -212,7 +208,7 @@ impl ContractFunctionParameters {
212208
}
213209

214210
/// Add a `bytes32` argument to the `ContractFunctionParameters`
215-
fn add_bytes32<T: IntoBytes32>(&mut self, val: T) -> &mut Self {
211+
pub fn add_bytes32<T: AsBytes32 + ?Sized>(&mut self, val: &T) -> &mut Self {
216212
self.args.push(Argument {
217213
type_name: "bytes32",
218214
value_bytes: encode_array_of_32_byte(val),
@@ -1035,13 +1031,13 @@ where
10351031
out_bytes
10361032
}
10371033

1038-
fn encode_array_of_32_byte<T: IntoBytes32>(elements: T) -> Vec<u8> {
1039-
let slice = elements.get_bytes_32();
1034+
fn encode_array_of_32_byte<T: AsBytes32 + ?Sized>(elements: &T) -> Vec<u8> {
1035+
let slice = elements.as_bytes32();
10401036
if slice.len() > 32 {
10411037
panic!("32 bytes exceeded in contract function call")
10421038
}
10431039

1044-
let mut new_bytes = slice;
1040+
let mut new_bytes = slice.to_vec();
10451041
right_pad_32_bytes(&mut new_bytes);
10461042
new_bytes
10471043
}
@@ -1215,7 +1211,7 @@ mod tests {
12151211
fn string_to_bytes32() {
12161212
let s = "alice".to_string();
12171213

1218-
let bytes = ContractFunctionParameters::new().add_bytes32(s).to_bytes(None);
1214+
let bytes = ContractFunctionParameters::new().add_bytes32(&s).to_bytes(None);
12191215

12201216
// sigh, the things we do to not have to manually format.
12211217
let mut buf = String::with_capacity(bytes.len() * 2 + ((bytes.len() * 2) / 64));

0 commit comments

Comments
 (0)