From fe66d7b5e03382b1662b0d6a562925e75e90232b Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Thu, 16 Jun 2016 17:08:35 +0200 Subject: Error handling --- bencode/bencode.go | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) (limited to 'bencode/bencode.go') 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) { -- cgit v1.2.3