Skip to content

Commit

Permalink
add back MarshalJSON and UnmarshalJSON
Browse files Browse the repository at this point in the history
  • Loading branch information
jewei1997 committed Jul 12, 2024
1 parent 8d571df commit a199035
Showing 1 changed file with 19 additions and 23 deletions.
42 changes: 19 additions & 23 deletions libs/bytes/bytes.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,27 +70,23 @@ func (bz HexBytes) Format(s fmt.State, verb rune) {
}
}

// // This is the point of Bytes.
// func (bz HexBytes) MarshalJSON() ([]byte, error) {
// fmt.Println("In MarshalJSON")
// s := strings.ToUpper(hex.EncodeToString(bz))
// jbz := make([]byte, len(s)+2)
// jbz[0] = '"'
// copy(jbz[1:], s)
// jbz[len(jbz)-1] = '"'
// return jbz, nil
// }
func (bz HexBytes) MarshalJSON() ([]byte, error) {
s := strings.ToUpper(hex.EncodeToString(bz))
jbz := make([]byte, len(s)+2)
jbz[0] = '"'
copy(jbz[1:], s)
jbz[len(jbz)-1] = '"'
return jbz, nil
}

// // This is the point of Bytes.
// func (bz *HexBytes) UnmarshalJSON(data []byte) error {
// fmt.Println("In UnmarshalJSON, data: ", string(data))
// if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
// return fmt.Errorf("invalid hex string: %s", data)
// }
// bz2, err := hex.DecodeString(string(data[1 : len(data)-1]))
// if err != nil {
// return err
// }
// *bz = bz2
// return nil
// }
func (bz *HexBytes) UnmarshalJSON(data []byte) error {
if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
return fmt.Errorf("invalid hex string: %s", data)
}
bz2, err := hex.DecodeString(string(data[1 : len(data)-1]))
if err != nil {
return err
}
*bz = bz2
return nil
}

0 comments on commit a199035

Please sign in to comment.