aboutsummaryrefslogtreecommitdiff
path: root/bencode
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2016-06-12 03:05:14 +0200
committerDimitri Sokolyuk <demon@dim13.org>2016-06-12 03:05:14 +0200
commitdc538d136a61e5ab174de5fd1f4e5e651d4525c3 (patch)
treede6431def424c532fa411b0897a8fe02dd950249 /bencode
parent2d142f149320d05a0012c528114d94e171f69171 (diff)
Unmarshal string/int
Diffstat (limited to 'bencode')
-rw-r--r--bencode/bencode.go25
-rw-r--r--bencode/bencode_test.go20
2 files changed, 43 insertions, 2 deletions
diff --git a/bencode/bencode.go b/bencode/bencode.go
index f8e72ec..6b0913d 100644
--- a/bencode/bencode.go
+++ b/bencode/bencode.go
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"reflect"
+ "strconv"
"strings"
"time"
)
@@ -123,3 +124,27 @@ func Unmarshal(data []byte, v interface{}) error {
}
return nil
}
+
+func unmarshalString(data []byte) string {
+ if i := bytes.IndexByte(data, ':'); i != -1 {
+ len, err := strconv.Atoi(string(data[:i]))
+ if err != nil {
+ return ""
+ }
+ return string(data[i+1 : i+1+len])
+ }
+ return ""
+}
+
+func unmarshalInt(data []byte) int {
+ pos := 0
+ if data[pos] == 'i' {
+ pos++
+ }
+ end := bytes.IndexByte(data, 'e')
+ i, err := strconv.Atoi(string(data[pos:end]))
+ if err != nil {
+ return 0
+ }
+ return i
+}
diff --git a/bencode/bencode_test.go b/bencode/bencode_test.go
index a5512e7..a7c534c 100644
--- a/bencode/bencode_test.go
+++ b/bencode/bencode_test.go
@@ -15,8 +15,8 @@ func TestMarshal(t *testing.T) {
Info: torrent.Info{
Length: 1000,
Files: []torrent.File{
- {Path: "A"},
- {Path: "B"},
+ {Path: []string{"A"}},
+ {Path: []string{"B"}},
},
},
}
@@ -26,3 +26,19 @@ func TestMarshal(t *testing.T) {
}
t.Logf("%q\n", string(out))
}
+
+func TestUnmarshalString(t *testing.T) {
+ in := "4:testZZZ"
+ s := unmarshalString([]byte(in))
+ if s != "test" {
+ t.Error("expected test, got", s)
+ }
+}
+
+func TestUnmarshalInt(t *testing.T) {
+ in := "i12345e999"
+ i := unmarshalInt([]byte(in))
+ if i != 12345 {
+ t.Error("expected 12345, got", i)
+ }
+}