aboutsummaryrefslogtreecommitdiff
path: root/bencode
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2016-06-16 17:08:35 +0200
committerDimitri Sokolyuk <demon@dim13.org>2016-06-16 17:08:35 +0200
commitfe66d7b5e03382b1662b0d6a562925e75e90232b (patch)
tree7fe418d290ce5a087eaaab0feaebd3af5e7b5fbb /bencode
parent8af0c2402ec16a85242de4bdbc6282bb1cf0276b (diff)
Error handling
Diffstat (limited to 'bencode')
-rw-r--r--bencode/bencode.go28
1 files changed, 17 insertions, 11 deletions
diff --git a/bencode/bencode.go b/bencode/bencode.go
index 0592d5b..8d65701 100644
--- a/bencode/bencode.go
+++ b/bencode/bencode.go
@@ -17,6 +17,8 @@ import (
// dict -> struct
// list -> aray of same type
+var ErrValue = errors.New("Unexpected value")
+
func Marshal(v interface{}) ([]byte, error) {
var out bytes.Buffer
val := reflect.ValueOf(v)
@@ -144,15 +146,15 @@ func Unmarshal(data []byte, v interface{}) error {
func (d *decodeState) unmarshalField(v reflect.Value) error {
switch d.data[d.off] {
case 'd':
- d.unmarshalDict(v)
+ return d.unmarshalDict(v)
case 'i':
- d.unmarshalInt(v)
+ return d.unmarshalInt(v)
case 'l':
- d.unmarshalList(v)
+ return d.unmarshalList(v)
case 'e':
- panic("unexpected end")
+ return ErrValue
default:
- d.unmarshalString(v)
+ return d.unmarshalString(v)
}
return nil
}
@@ -172,9 +174,9 @@ func findKey(key string, v reflect.Value) reflect.Value {
return reflect.Value{}
}
-func (d *decodeState) unmarshalDict(v reflect.Value) {
+func (d *decodeState) unmarshalDict(v reflect.Value) error {
if d.data[d.off] != 'd' {
- panic("not a dict")
+ return ErrValue
}
d.off++
@@ -199,11 +201,12 @@ func (d *decodeState) unmarshalDict(v reflect.Value) {
}
}
d.off++
+ return nil
}
-func (d *decodeState) unmarshalList(v reflect.Value) {
+func (d *decodeState) unmarshalList(v reflect.Value) error {
if d.data[d.off] != 'l' {
- panic("not a list")
+ return ErrValue
}
d.off++
@@ -227,9 +230,10 @@ func (d *decodeState) unmarshalList(v reflect.Value) {
}
}
d.off++
+ return nil
}
-func (d *decodeState) unmarshalString(v reflect.Value) {
+func (d *decodeState) unmarshalString(v reflect.Value) error {
s, n := parseString(d.data[d.off:])
d.off += n
if v.CanSet() {
@@ -240,6 +244,7 @@ func (d *decodeState) unmarshalString(v reflect.Value) {
v.SetString(s)
}
}
+ return nil
}
func parseString(data []byte) (string, int) {
@@ -260,7 +265,7 @@ func parseString(data []byte) (string, int) {
return string(data[i+1 : end]), end
}
-func (d *decodeState) unmarshalInt(v reflect.Value) {
+func (d *decodeState) unmarshalInt(v reflect.Value) error {
i, n := parseInt(d.data[d.off:])
d.off += n
if v.CanSet() {
@@ -274,6 +279,7 @@ func (d *decodeState) unmarshalInt(v reflect.Value) {
v.SetInt(i)
}
}
+ return nil
}
func parseInt(data []byte) (int64, int) {