From ba37eae00a70516c1df4aced7b8d94caac77d30b Mon Sep 17 00:00:00 2001 From: Vincent Batts Date: Thu, 14 Aug 2014 15:27:07 -0400 Subject: [PATCH] switching bencode.Marshal to match other encoders --- bencode/bencode_test.go | 6 +++--- bencode/struct.go | 12 +++++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/bencode/bencode_test.go b/bencode/bencode_test.go index f633638..550fda4 100644 --- a/bencode/bencode_test.go +++ b/bencode/bencode_test.go @@ -11,11 +11,11 @@ import ( type any interface{} func checkMarshal(expected string, data any) (err error) { - var b bytes.Buffer - if err = Marshal(&b, data); err != nil { + var b []byte + if b, err = Marshal(data); err != nil { return } - s := b.String() + s := string(b) if expected != s { err = errors.New(fmt.Sprintf("Expected %s got %s", expected, s)) return diff --git a/bencode/struct.go b/bencode/struct.go index 4746cb3..94a0620 100644 --- a/bencode/struct.go +++ b/bencode/struct.go @@ -10,6 +10,7 @@ package bencode import ( + "bytes" "errors" "fmt" "io" @@ -283,6 +284,9 @@ func (b *structBuilder) Key(k string) builder { // slice of the correct type. // func Unmarshal(r io.Reader, val interface{}) (err error) { + // TODO match other encoders, like encoding/json ... + // func Unmarshal(data []byte, v interface{}) error + // If e represents a value, the answer won't get back to the // caller. Make sure it's a pointer. if reflect.TypeOf(val).Kind() != reflect.Ptr { @@ -516,7 +520,7 @@ func isValueNil(val reflect.Value) bool { // Field int // // // Field appears in bencode as key "myName". -// Field int "myName" +// Field int `bencode:"myName"` // // Anonymous struct fields are ignored. // @@ -533,8 +537,10 @@ func isValueNil(val reflect.Value) bool { // handle them. Passing cyclic structures to Marshal will result in // an infinite recursion. // -func Marshal(w io.Writer, val interface{}) error { +func Marshal(val interface{}) ([]byte, error) { // TODO match other encoders, like encoding/json ... // func Marshal(v interface{}) ([]byte, error) - return writeValue(w, reflect.ValueOf(val)) + buf := bytes.Buffer{} + err := writeValue(&buf, reflect.ValueOf(val)) + return buf.Bytes(), err }