]> Sergey Matveev's repositories - btrtrc.git/commitdiff
bencode: Handle encoding big.Ints
authorMatt Joiner <anacrolix@gmail.com>
Wed, 8 Nov 2017 10:34:24 +0000 (21:34 +1100)
committerMatt Joiner <anacrolix@gmail.com>
Wed, 8 Nov 2017 10:34:24 +0000 (21:34 +1100)
bencode/encode.go
bencode/encode_test.go

index 57f0b80513189e957bfff416d18d93fce4b5f63e..8cbaf29f1f1435a8f4764c12ba794a0e8eb60e94 100644 (file)
@@ -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() {
index a913a1c40427638a6ee9566cedf3afbd9c5237d3..bdb0d991a698e473465e6258a78b66cc6c120024 100644 (file)
@@ -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) {