From 74c5d425fbecc45e24bf62a3ca3ee935d36b67b4 Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Wed, 8 Nov 2017 21:34:24 +1100 Subject: [PATCH] bencode: Handle encoding big.Ints --- bencode/encode.go | 9 +++++++++ bencode/encode_test.go | 11 +++++++++++ 2 files changed, 20 insertions(+) diff --git a/bencode/encode.go b/bencode/encode.go index 57f0b805..8cbaf29f 100644 --- a/bencode/encode.go +++ b/bencode/encode.go @@ -2,6 +2,7 @@ package bencode import ( "io" + "math/big" "reflect" "runtime" "sort" @@ -110,6 +111,14 @@ func (e *Encoder) reflectValue(v reflect.Value) { return } + switch t := v.Interface().(type) { + case big.Int: + e.writeString("i") + e.writeString(t.String()) + e.writeString("e") + return + } + switch v.Kind() { case reflect.Bool: if v.Bool() { diff --git a/bencode/encode_test.go b/bencode/encode_test.go index a913a1c4..bdb0d991 100644 --- a/bencode/encode_test.go +++ b/bencode/encode_test.go @@ -3,6 +3,7 @@ package bencode import ( "bytes" "fmt" + "math/big" "testing" "github.com/stretchr/testify/assert" @@ -68,6 +69,16 @@ var random_encode_tests = []random_encode_test{ {struct { A *string `bencode:",omitempty"` }{new(string)}, "d1:A0:e"}, + {bigIntFromString("62208002200000000000"), "i62208002200000000000e"}, + {*bigIntFromString("62208002200000000000"), "i62208002200000000000e"}, +} + +func bigIntFromString(s string) *big.Int { + bi, ok := new(big.Int).SetString(s, 10) + if !ok { + panic(s) + } + return bi } func TestRandomEncode(t *testing.T) { -- 2.48.1