1- pub struct HexDisplay ( [ u8 ; 32 ] ) ;
1+ pub struct U256Hex ( [ u8 ; 64 ] ) ;
22
3- impl core:: fmt:: Debug for HexDisplay {
4- fn fmt ( & self , f : & mut core:: fmt:: Formatter < ' _ > ) -> core:: fmt:: Result {
5- std:: fmt:: Display :: fmt ( self , f)
6- }
7- }
8-
9- impl core:: fmt:: Display for HexDisplay {
10- fn fmt ( & self , f : & mut core:: fmt:: Formatter < ' _ > ) -> core:: fmt:: Result {
3+ impl U256Hex {
4+ fn new ( bytes : [ u8 ; 32 ] ) -> Self {
115 // this implementation avoids any heap allocations and is optimized by
126 // the compiler to use vectorized instructions where available.
137 //
148 // with O3, the loop is unrolled and vectorized to use SIMD instructions
159 //
1610 // https://rust.godbolt.org/z/seM19zEfv
17-
1811 let mut buf = [ 0u8 ; 64 ] ;
1912 // SAFETY: 64 is evenly divisible by 2
2013 unsafe { buf. as_chunks_unchecked_mut :: < 2 > ( ) }
2114 . iter_mut ( )
22- . zip ( self . 0 . as_ref ( ) )
23- . for_each ( |( slot, & byte) | {
15+ . zip ( bytes )
16+ . for_each ( |( slot, byte) | {
2417 * slot = byte_to_hex ( byte) ;
2518 } ) ;
19+ Self ( buf)
20+ }
2621
22+ fn as_str ( & self ) -> & str {
2723 // SAFETY: buf only contains valid ASCII hex characters
28- let buf = unsafe { core:: str:: from_utf8_unchecked ( & buf) } ;
24+ unsafe { core:: str:: from_utf8_unchecked ( & self . 0 ) }
25+ }
26+ }
2927
30- f. pad ( buf)
28+ impl core:: fmt:: Debug for U256Hex {
29+ fn fmt ( & self , f : & mut core:: fmt:: Formatter < ' _ > ) -> core:: fmt:: Result {
30+ f. pad ( self . as_str ( ) )
31+ }
32+ }
33+
34+ impl core:: fmt:: Display for U256Hex {
35+ fn fmt ( & self , f : & mut core:: fmt:: Formatter < ' _ > ) -> core:: fmt:: Result {
36+ f. pad ( self . as_str ( ) )
3137 }
3238}
3339
@@ -45,12 +51,12 @@ const fn byte_to_hex(byte: u8) -> [u8; 2] {
4551 unsafe { [ nibble_to_hex ( byte >> 4 ) , nibble_to_hex ( byte & 0x0F ) ] }
4652}
4753
48- pub trait HexDisplayExt {
49- fn hex_display ( self ) -> HexDisplay ;
54+ pub trait IntoU256Hex {
55+ fn into_u256_hex ( self ) -> U256Hex ;
5056}
5157
52- impl < T : Into < [ u8 ; 32 ] > > HexDisplayExt for T {
53- fn hex_display ( self ) -> HexDisplay {
54- HexDisplay ( self . into ( ) )
58+ impl < T : Into < [ u8 ; 32 ] > > IntoU256Hex for T {
59+ fn into_u256_hex ( self ) -> U256Hex {
60+ U256Hex :: new ( self . into ( ) )
5561 }
5662}
0 commit comments