zeebo/bencode

nil not being decoded correctly

euforia opened this issue · 4 comments

Seems like a nil values are not properly decoded. Rather than the decoded value being nil, it is initialized with the given type.

Here's a test case to re-produce:

import (
	"testing"
	"github.com/zeebo/bencode"
)

type TT struct {
	Name string
}

type TestStruct struct {
	T *TT
}

func Test_Bencode(t *testing.T) {
	var val TestStruct
	b, err := bencode.EncodeBytes(&val)
	if err != nil {
		t.Fatal(err)
	}

	var v1 TestStruct
	if err = bencode.DecodeBytes(b, &v1); err != nil {
		t.Fatal(err)
	}

	if v1.T != nil {
		t.Fatalf("v1.T should be nil. got: %#v", v1.T)
	}
}
zeebo commented

So the value that gets encoded there is d1:Td4:Name0:ee which in json is something like {"T":{"Name":""}} and if you pass in de (json {}) to decode then it properly keeps the value nil. So it's decoding properly.

I guess the question is should we skip encoding nil values? What if I had a map[string]*int{"foo": nil}? Is that encoded as de or d3:fooi0ee? Would we only skip encoding keys if the value is a nil pointer, or any zero value?

How did this bug cause you problems? That might help in deciding how to resolve how eager the encoding is.

zeebo commented

Sorry for the delay in the response by the way. The holiday season and all :)

No worries. Thanx for the response.

My use case is the same as the above example. The struct nested in another struct is nil when being encoded. When decoding the value back the nested struct is instantiated .

My gut would say to not encode nil's from an efficiency/performance standpoint but I don't know what the actual RFC has to say.

Works great. Thanx for the quick fix.