arbos/util/
serialization.rs1use alloy_primitives::{Address, B256, U256};
2use std::io::{self, Read, Write};
3
4pub fn hash_from_reader<R: Read>(r: &mut R) -> io::Result<B256> {
6 let mut buf = [0u8; 32];
7 r.read_exact(&mut buf)?;
8 Ok(B256::from(buf))
9}
10
11pub fn hash_to_writer<W: Write>(w: &mut W, hash: &B256) -> io::Result<()> {
13 w.write_all(hash.as_slice())
14}
15
16pub fn uint256_from_reader<R: Read>(r: &mut R) -> io::Result<U256> {
18 let hash = hash_from_reader(r)?;
19 Ok(U256::from_be_bytes(hash.0))
20}
21
22pub fn address_from_reader<R: Read>(r: &mut R) -> io::Result<Address> {
24 let mut buf = [0u8; 20];
25 r.read_exact(&mut buf)?;
26 Ok(Address::from(buf))
27}
28
29pub fn address_to_writer<W: Write>(w: &mut W, addr: &Address) -> io::Result<()> {
31 w.write_all(addr.as_slice())
32}
33
34pub fn address_from_256_from_reader<R: Read>(r: &mut R) -> io::Result<Address> {
36 let hash = hash_from_reader(r)?;
37 Ok(Address::from_slice(&hash[12..]))
38}
39
40pub fn address_to_256_to_writer<W: Write>(w: &mut W, addr: &Address) -> io::Result<()> {
42 let mut buf = [0u8; 32];
43 buf[12..].copy_from_slice(addr.as_slice());
44 w.write_all(&buf)
45}
46
47pub fn uint64_from_reader<R: Read>(r: &mut R) -> io::Result<u64> {
49 let mut buf = [0u8; 8];
50 r.read_exact(&mut buf)?;
51 Ok(u64::from_be_bytes(buf))
52}
53
54pub fn uint64_to_writer<W: Write>(w: &mut W, val: u64) -> io::Result<()> {
56 w.write_all(&val.to_be_bytes())
57}
58
59pub fn bytestring_from_reader<R: Read>(r: &mut R) -> io::Result<Vec<u8>> {
61 let len = uint64_from_reader(r)? as usize;
62 let mut buf = vec![0u8; len];
63 r.read_exact(&mut buf)?;
64 Ok(buf)
65}
66
67pub fn bytestring_to_writer<W: Write>(w: &mut W, data: &[u8]) -> io::Result<()> {
69 uint64_to_writer(w, data.len() as u64)?;
70 w.write_all(data)
71}
72
73pub fn int_to_hash(val: i64) -> B256 {
75 let mut buf = [0u8; 32];
76 if val >= 0 {
77 buf[24..].copy_from_slice(&(val as u64).to_be_bytes());
78 } else {
79 buf.fill(0xFF);
81 buf[24..].copy_from_slice(&(val as u64).to_be_bytes());
82 }
83 B256::from(buf)
84}
85
86pub fn uint_to_hash(val: u64) -> B256 {
88 let mut buf = [0u8; 32];
89 buf[24..].copy_from_slice(&val.to_be_bytes());
90 B256::from(buf)
91}
92
93pub fn address_to_hash(addr: &Address) -> B256 {
95 let mut buf = [0u8; 32];
96 buf[12..].copy_from_slice(addr.as_slice());
97 B256::from(buf)
98}