aboutsummaryrefslogtreecommitdiff
path: root/bencode
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2016-06-15 23:12:18 +0200
committerDimitri Sokolyuk <demon@dim13.org>2016-06-15 23:12:18 +0200
commita84ee4bfd94ff3c7aac29f5f9a438f5e8adcfd18 (patch)
treef0905d8d8b38db46c3a019dadcbd175e7a0e6bbe /bencode
parentbd5f86a67cdc9c17b5bade36ffd2c3099e31741a (diff)
parent4da1a590c21a81ea166d4cfef5d51088a15fea3c (diff)
Merge branch 'master' of dim13.org:btget
Diffstat (limited to 'bencode')
-rw-r--r--bencode/bencode.go25
1 files changed, 19 insertions, 6 deletions
diff --git a/bencode/bencode.go b/bencode/bencode.go
index c8840fd..2521287 100644
--- a/bencode/bencode.go
+++ b/bencode/bencode.go
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"reflect"
+ "sort"
"strconv"
"strings"
"time"
@@ -58,28 +59,40 @@ func isEmpty(v reflect.Value) bool {
return false
}
+type byName []reflect.StructField
+
+func (n byName) Len() int { return len(n) }
+func (n byName) Less(i, j int) bool { return n[i].Name < n[j].Name }
+func (n byName) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
+
func marshalDict(out io.Writer, v reflect.Value) {
switch val := v.Interface().(type) {
case time.Time:
marshalInt(out, val.Unix())
default:
t := v.Type()
- io.WriteString(out, "d")
+ fields := make([]reflect.StructField, t.NumField())
for i := 0; i < t.NumField(); i++ {
- f := t.Field(i)
- tag := f.Tag.Get("bencode")
+ fields[i] = t.Field(i)
+ }
+ sort.Sort(byName(fields))
+
+ io.WriteString(out, "d")
+ for _, n := range fields {
+ tag := n.Tag.Get("bencode")
if tag == "-" {
continue
}
name, param := parseTag(tag)
if name == "" {
- name = f.Name
+ name = n.Name
}
- if param == "optional" && isEmpty(v.Field(i)) {
+ vf := v.FieldByIndex(n.Index)
+ if param == "optional" && isEmpty(vf) {
continue
}
marshalString(out, name)
- marshalField(out, v.Field(i))
+ marshalField(out, vf)
}
io.WriteString(out, "e")
}