github.com/lmittmann/w3@v0.20.0/internal/hexutil/hash.go (about)

     1  package hexutil
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/hex"
     6  
     7  	"github.com/ethereum/go-ethereum/common"
     8  )
     9  
    10  // Hash is a wrapper type for [common.Hash] that marshals and unmarshals hex strings.
    11  // It can decode hex strings with or without the 0x prefix and with or without leading
    12  // zeros and encodes hashes without leading zeros.
    13  type Hash common.Hash
    14  
    15  func (h *Hash) UnmarshalText(text []byte) error {
    16  	if len(text) >= 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X') {
    17  		text = text[2:]
    18  	}
    19  	if len(text)%2 != 0 {
    20  		text = append([]byte{'0'}, text...)
    21  	}
    22  
    23  	bytes, _ := hex.DecodeString(string(text))
    24  	*h = Hash(common.BytesToHash(bytes))
    25  	return nil
    26  }
    27  
    28  func (h Hash) MarshalText() ([]byte, error) {
    29  	bytes := bytes.TrimLeft(h[:], "\x00")
    30  	if len(bytes) == 0 {
    31  		return []byte("0x0"), nil
    32  	}
    33  	hexStr := hex.EncodeToString(bytes)
    34  	if bytes[0]&0xf0 == 0 {
    35  		hexStr = hexStr[1:]
    36  	}
    37  	return []byte("0x" + hexStr), nil
    38  }