Skip to content

Commit

Permalink
fix: support larger num/denom for CBOR rational numbers (#792)
Browse files Browse the repository at this point in the history
  • Loading branch information
agaffney authored Nov 16, 2024
1 parent f2064fa commit 68d9395
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
12 changes: 10 additions & 2 deletions cbor/tags.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,19 @@ type Rat struct {
}

func (r *Rat) UnmarshalCBOR(cborData []byte) error {
tmpRat := []int64{}
tmpRat := []uint64{}
if _, err := Decode(cborData, &tmpRat); err != nil {
return err
}
r.Rat = big.NewRat(tmpRat[0], tmpRat[1])
// Convert numerator and denominator to big.Int
// It's necessary to do this to support num/denom larger than int64 (up to uint64)
tmpNum := new(big.Int)
tmpNum.SetUint64(tmpRat[0])
tmpDenom := new(big.Int)
tmpDenom.SetUint64(tmpRat[1])
// Create new big.Rat with num/denom set to big.Int values above
r.Rat = new(big.Rat)
r.Rat.SetFrac(tmpNum, tmpDenom)
return nil
}

Expand Down
9 changes: 9 additions & 0 deletions cbor/tags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,15 @@ var tagsTestDefs = []struct {
},
),
},
{
cborHex: "d81e821b80000000000000011b8ac7230489e80000",
object: cbor.Rat{
Rat: new(big.Rat).SetFrac(
new(big.Int).SetUint64(9223372036854775809),
new(big.Int).SetUint64(10000000000000000000),
),
},
},
}

func TestTagsDecode(t *testing.T) {
Expand Down

0 comments on commit 68d9395

Please sign in to comment.