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

     1  package hexutil
     2  
     3  import (
     4  	"encoding/hex"
     5  )
     6  
     7  // Bytes is a byte slice that marshals/unmarshals from a hex-encoded string.
     8  type Bytes []byte
     9  
    10  // UnmarshalText decodes a hex string (with or without 0x prefix) into Bytes.
    11  func (b *Bytes) UnmarshalText(data []byte) error {
    12  	if len(data) >= 2 && data[0] == '0' && (data[1] == 'x' || data[1] == 'X') {
    13  		data = data[2:]
    14  	}
    15  
    16  	*b = make([]byte, hex.DecodedLen(len(data)))
    17  	_, err := hex.Decode(*b, data)
    18  	return err
    19  }
    20  
    21  // MarshalText encodes Bytes into a hex string with a 0x prefix.
    22  func (b Bytes) MarshalText() ([]byte, error) {
    23  	result := make([]byte, 2+hex.EncodedLen(len(b)))
    24  	copy(result, `0x`)
    25  	hex.Encode(result[2:], b)
    26  	return result, nil
    27  }