Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions cbor/tags.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package cbor

import (
"encoding/json"
"errors"
"fmt"
"math/big"
Expand Down Expand Up @@ -150,6 +151,24 @@ func (r *Rat) MarshalCBOR() ([]byte, error) {
return Encode(&tmpData)
}

func (r *Rat) UnmarshalJSON(data []byte) error {
// Try as ratio
var tmpData struct {
Numerator int64 `json:"numerator"`
Denominator int64 `json:"denominator"`
}
if err := json.Unmarshal(data, &tmpData); err == nil {
r.Rat = big.NewRat(tmpData.Numerator, tmpData.Denominator)
return nil
}
// Try as decimal value
r.Rat = new(big.Rat)
if _, ok := r.SetString(string(data)); !ok {
return fmt.Errorf("math/big: cannot unmarshal %q into a *big.Rat", data)
}
return nil
}

func (r *Rat) ToBigRat() *big.Rat {
return r.Rat
}
Expand Down
30 changes: 30 additions & 0 deletions cbor/tags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ package cbor_test

import (
"encoding/hex"
"encoding/json"
"math/big"
"reflect"
"testing"

"github.com/blinklabs-io/gouroboros/cbor"
"github.com/blinklabs-io/gouroboros/ledger/common"
)

var tagsTestDefs = []struct {
Expand Down Expand Up @@ -109,3 +111,31 @@ func TestTagsEncode(t *testing.T) {
}
}
}

func TestRatJsonUnmarshalNumDenom(t *testing.T) {
jsonData := `{"testRat": { "numerator": 721, "denominator": 10000 }}`
expectedRat := big.NewRat(721, 10000)
var testData struct {
TestRat common.GenesisRat `json:"testRat"`
}
if err := json.Unmarshal([]byte(jsonData), &testData); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if testData.TestRat.Cmp(expectedRat) != 0 {
t.Errorf("did not get expected value: got %s, wanted %s", testData.TestRat.String(), expectedRat.String())
}
}

func TestRatJsonUnmarshalFloat(t *testing.T) {
jsonData := `{"testRat": 0.0721}`
expectedRat := big.NewRat(721, 10000)
var testData struct {
TestRat common.GenesisRat `json:"testRat"`
}
if err := json.Unmarshal([]byte(jsonData), &testData); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if testData.TestRat.Cmp(expectedRat) != 0 {
t.Errorf("did not get expected value: got %s, wanted %s", testData.TestRat.String(), expectedRat.String())
}
}
3 changes: 3 additions & 0 deletions ledger/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -439,3 +439,6 @@ type ExUnits struct {
Memory uint64
Steps uint64
}

// GenesisRat is a convenience type for cbor.Rat
type GenesisRat = cbor.Rat
44 changes: 0 additions & 44 deletions ledger/common/genesis.go

This file was deleted.

59 changes: 0 additions & 59 deletions ledger/common/genesis_test.go

This file was deleted.