Skip to content

Commit

Permalink
Cleanup uint128 encoding/decoding
Browse files Browse the repository at this point in the history
  • Loading branch information
gagliardetto committed Feb 1, 2022
1 parent 521b336 commit c15d9aa
Showing 1 changed file with 21 additions and 25 deletions.
46 changes: 21 additions & 25 deletions u128.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ import (
"fmt"
"math/big"
"strings"

"github.com/shopspring/decimal"
)

// uint128
Expand Down Expand Up @@ -105,13 +103,29 @@ func ReverseBytes(s []byte) {
}
}

func (i *Uint128) unmarshalJSON_decimal(s string) error {
func (i *Uint128) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
return nil
}

orderID, err := decimal.NewFromString(s)
if err != nil {
panic(err)
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}

if strings.HasPrefix(s, "0x") || strings.HasPrefix(s, "0X") {
return i.unmarshalJSON_hex(s)
}

return i.unmarshalJSON_decimal(s)
}

func (i *Uint128) unmarshalJSON_decimal(s string) error {
parsed, ok := (&big.Int{}).SetString(s, 0)
if !ok {
return fmt.Errorf("could not parse %q", s)
}
oo := orderID.BigInt().FillBytes(make([]byte, 16))
oo := parsed.FillBytes(make([]byte, 16))
ReverseBytes(oo)

dec := NewBinDecoder(oo)
Expand All @@ -127,7 +141,6 @@ func (i *Uint128) unmarshalJSON_decimal(s string) error {
}

func (i *Uint128) unmarshalJSON_hex(s string) error {

truncatedVal := s[2:]
if len(truncatedVal) != 16 {
return fmt.Errorf("uint128 expects 16 characters after 0x, had %v", len(truncatedVal))
Expand All @@ -150,23 +163,6 @@ func (i *Uint128) unmarshalJSON_hex(s string) error {
return nil
}

func (i *Uint128) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
return nil
}

var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}

if strings.HasPrefix(s, "0x") || strings.HasPrefix(s, "0X") {
return i.unmarshalJSON_hex(s)
}

return i.unmarshalJSON_decimal(s)
}

func (i *Uint128) UnmarshalWithDecoder(dec *Decoder) error {
var order binary.ByteOrder
if dec != nil && dec.currentFieldOpt != nil {
Expand Down

0 comments on commit c15d9aa

Please sign in to comment.