aboutsummaryrefslogtreecommitdiff
path: root/bencode
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2016-06-12 06:57:17 +0200
committerDimitri Sokolyuk <demon@dim13.org>2016-06-12 06:57:17 +0200
commitda795ea9b35368a97d63ffe3e1b6866bec23727c (patch)
tree57648b33c0d8091ed68e5d841078d81b82f560e2 /bencode
parentf5b44cf1811c768dc268f6097422bb50133ce913 (diff)
Use special field instead of return value
Diffstat (limited to 'bencode')
-rw-r--r--bencode/bencode.go25
-rw-r--r--bencode/bencode_test.go4
2 files changed, 17 insertions, 12 deletions
diff --git a/bencode/bencode.go b/bencode/bencode.go
index f4f6a85..58527a0 100644
--- a/bencode/bencode.go
+++ b/bencode/bencode.go
@@ -107,21 +107,18 @@ func parseTag(tag string) (string, string) {
}
type decodeState struct {
- data []byte
- off int
- infoOff int
- infoEnd int
+ data []byte
+ off int
}
-func Unmarshal(data []byte, v interface{}) ([]byte, error) {
+func Unmarshal(data []byte, v interface{}) error {
val := reflect.ValueOf(v)
if val.Kind() != reflect.Ptr {
- return nil, errors.New("non-pointer passed to Unmarshal")
+ return errors.New("non-pointer passed to Unmarshal")
}
d := decodeState{data: data}
err := d.unmarshalField(val.Elem())
- sum := sha1.Sum(d.data[d.infoOff:d.infoEnd])
- return sum[:], err
+ return err
}
func (d *decodeState) unmarshalField(v reflect.Value) error {
@@ -146,6 +143,8 @@ func (d *decodeState) unmarshalDict(v reflect.Value) {
}
d.off++
+ var infoOff, infoEnd int
+
for d.data[d.off] != 'e' {
key, n := parseString(d.data[d.off:])
d.off += n
@@ -156,16 +155,22 @@ func (d *decodeState) unmarshalDict(v reflect.Value) {
name, _ := parseTag(tag)
if name == key || f.Name == key {
if key == "info" {
- d.infoOff = d.off
+ infoOff = d.off
}
d.unmarshalField(v.Field(i))
if key == "info" {
- d.infoEnd = d.off
+ infoEnd = d.off
}
break
}
}
}
+ if ih := v.FieldByName("InfoHash"); ih.IsValid() {
+ if infoEnd > infoOff {
+ sum := sha1.Sum(d.data[infoOff:infoEnd])
+ ih.SetBytes(sum[:])
+ }
+ }
d.off++
}
diff --git a/bencode/bencode_test.go b/bencode/bencode_test.go
index 41c1bff..497cd6f 100644
--- a/bencode/bencode_test.go
+++ b/bencode/bencode_test.go
@@ -70,11 +70,11 @@ func TestUnmarshal(t *testing.T) {
if err != nil {
t.Error(err)
}
- sum, err := Unmarshal(body, &tor)
+ err = Unmarshal(body, &tor)
if err != nil {
t.Error(err)
}
- h := hex.EncodeToString(sum)
+ h := hex.EncodeToString(tor.InfoHash)
if h != tc.InfoHash {
t.Error("got", h, "expected", tc.InfoHash)
}