github.com/devwanda/aphelion-staking@v0.33.9/libs/bytes/bytes.go (about)

     1  package bytes
     2  
     3  import (
     4  	"encoding/hex"
     5  	"fmt"
     6  	"strings"
     7  )
     8  
     9  // The main purpose of HexBytes is to enable HEX-encoding for json/encoding.
    10  type HexBytes []byte
    11  
    12  // Marshal needed for protobuf compatibility
    13  func (bz HexBytes) Marshal() ([]byte, error) {
    14  	return bz, nil
    15  }
    16  
    17  // Unmarshal needed for protobuf compatibility
    18  func (bz *HexBytes) Unmarshal(data []byte) error {
    19  	*bz = data
    20  	return nil
    21  }
    22  
    23  // This is the point of Bytes.
    24  func (bz HexBytes) MarshalJSON() ([]byte, error) {
    25  	s := strings.ToUpper(hex.EncodeToString(bz))
    26  	jbz := make([]byte, len(s)+2)
    27  	jbz[0] = '"'
    28  	copy(jbz[1:], []byte(s))
    29  	jbz[len(jbz)-1] = '"'
    30  	return jbz, nil
    31  }
    32  
    33  // This is the point of Bytes.
    34  func (bz *HexBytes) UnmarshalJSON(data []byte) error {
    35  	if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
    36  		return fmt.Errorf("invalid hex string: %s", data)
    37  	}
    38  	bz2, err := hex.DecodeString(string(data[1 : len(data)-1]))
    39  	if err != nil {
    40  		return err
    41  	}
    42  	*bz = bz2
    43  	return nil
    44  }
    45  
    46  // Allow it to fulfill various interfaces in light-client, etc...
    47  func (bz HexBytes) Bytes() []byte {
    48  	return bz
    49  }
    50  
    51  func (bz HexBytes) String() string {
    52  	return strings.ToUpper(hex.EncodeToString(bz))
    53  }
    54  
    55  func (bz HexBytes) Format(s fmt.State, verb rune) {
    56  	switch verb {
    57  	case 'p':
    58  		s.Write([]byte(fmt.Sprintf("%p", bz)))
    59  	default:
    60  		s.Write([]byte(fmt.Sprintf("%X", []byte(bz))))
    61  	}
    62  }