From 28c1536daff0e33714235aa1961bece3f3f46930 Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Fri, 2 Oct 2015 00:13:43 +1000 Subject: [PATCH] bencode: When decoding a dict, if the final key is missing its value, don't treat that as an error. I think I'm swayed here by the robustness principle/Postel's Law. --- bencode/decode.go | 19 +++++-------------- bencode/decode_test.go | 12 ++++++++---- 2 files changed, 13 insertions(+), 18 deletions(-) diff --git a/bencode/decode.go b/bencode/decode.go index 2d27d683..f9078341 100644 --- a/bencode/decode.go +++ b/bencode/decode.go @@ -264,10 +264,7 @@ func (d *decoder) parse_dict(v reflect.Value) { } else { _, ok := d.parse_value_interface() if !ok { - panic(&SyntaxError{ - Offset: d.offset, - What: errors.New("unexpected end of dict, no matching value for a given key"), - }) + return } continue } @@ -275,10 +272,7 @@ func (d *decoder) parse_dict(v reflect.Value) { // now we need to actually parse it if !d.parse_value(valuev) { - panic(&SyntaxError{ - Offset: d.offset, - What: errors.New("unexpected end of dict, no matching value for a given key"), - }) + return } if v.Kind() == reflect.Map { @@ -414,8 +408,8 @@ func (d *decoder) parse_unmarshaler(v reflect.Value) bool { return false } -// returns true if there was a value and it's now stored in 'v', otherwise there -// was an end symbol ("e") and no value was stored +// Returns true if there was a value and it's now stored in 'v', otherwise +// there was an end symbol ("e") and no value was stored. func (d *decoder) parse_value(v reflect.Value) bool { // we support one level of indirection at the moment if v.Kind() == reflect.Ptr { @@ -576,10 +570,7 @@ func (d *decoder) parse_dict_interface() interface{} { valuei, ok := d.parse_value_interface() if !ok { - panic(&SyntaxError{ - Offset: d.offset, - What: errors.New("unexpected end of dict, no matching value for a given key"), - }) + break } dict[key] = valuei diff --git a/bencode/decode_test.go b/bencode/decode_test.go index a4bf84b4..d519b8a6 100644 --- a/bencode/decode_test.go +++ b/bencode/decode_test.go @@ -7,6 +7,7 @@ import ( "reflect" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -29,6 +30,12 @@ var random_decode_tests = []random_decode_test{ ret, _ := big.NewInt(-1).SetString("604919719469385652980544193299329427705624352086", 10) return ret }()}, + {"d1:rd6:\xd4/\xe2F\x00\x01e1:t3:\x9a\x87\x011:v4:TR%=1:y1:re", map[string]interface{}{ + "r": map[string]interface{}{}, + "t": "\x9a\x87\x01", + "v": "TR%=", + "y": "r", + }}, } func TestRandomDecode(t *testing.T) { @@ -39,10 +46,7 @@ func TestRandomDecode(t *testing.T) { t.Error(err, test.data) continue } - if !reflect.DeepEqual(test.expected, value) { - t.Errorf("got: %v (%T), expected: %v (%T)\n", - value, value, test.expected, test.expected) - } + assert.EqualValues(t, test.expected, value) } }