github.com/ari-anchor/sei-tendermint@v0.0.0-20230519144642-dc826b7b56bb/libs/bytes/bytes.go (about)

     1  package bytes
     2  
     3  import (
     4  	"encoding/base64"
     5  	"encoding/hex"
     6  	"fmt"
     7  	"strings"
     8  )
     9  
    10  // HexBytes is a wrapper around []byte that encodes data as hexadecimal strings
    11  // for use in JSON.
    12  type HexBytes []byte
    13  
    14  // Marshal needed for protobuf compatibility
    15  func (bz HexBytes) Marshal() ([]byte, error) {
    16  	return bz, nil
    17  }
    18  
    19  // Unmarshal needed for protobuf compatibility
    20  func (bz *HexBytes) Unmarshal(data []byte) error {
    21  	*bz = data
    22  	return nil
    23  }
    24  
    25  // MarshalText encodes a HexBytes value as hexadecimal digits.
    26  // This method is used by json.Marshal.
    27  func (bz HexBytes) MarshalText() ([]byte, error) {
    28  	enc := hex.EncodeToString([]byte(bz))
    29  	return []byte(strings.ToUpper(enc)), nil
    30  }
    31  
    32  // UnmarshalText handles decoding of HexBytes from JSON strings.
    33  // This method is used by json.Unmarshal.
    34  // It allows decoding of both hex and base64-encoded byte arrays.
    35  func (bz *HexBytes) UnmarshalText(data []byte) error {
    36  	input := string(data)
    37  	if input == "" || input == "null" {
    38  		return nil
    39  	}
    40  	dec, err := hex.DecodeString(input)
    41  	if err != nil {
    42  		dec, err = base64.StdEncoding.DecodeString(input)
    43  
    44  		if err != nil {
    45  			return err
    46  		}
    47  	}
    48  	*bz = HexBytes(dec)
    49  	return nil
    50  }
    51  
    52  // Bytes fulfills various interfaces in light-client, etc...
    53  func (bz HexBytes) Bytes() []byte {
    54  	return bz
    55  }
    56  
    57  func (bz HexBytes) String() string {
    58  	return strings.ToUpper(hex.EncodeToString(bz))
    59  }
    60  
    61  // Format writes either address of 0th element in a slice in base 16 notation,
    62  // with leading 0x (%p), or casts HexBytes to bytes and writes as hexadecimal
    63  // string to s.
    64  func (bz HexBytes) Format(s fmt.State, verb rune) {
    65  	switch verb {
    66  	case 'p':
    67  		s.Write([]byte(fmt.Sprintf("%p", bz)))
    68  	default:
    69  		s.Write([]byte(fmt.Sprintf("%X", []byte(bz))))
    70  	}
    71  }