ugorji / go

idiomatic codec and rpc lib for msgpack, cbor, json, etc. msgpack.org[Go]
MIT License
1.86k stars 295 forks source link

NewDecoderBytes/NewEncoderBytes cannot execute success #172

Closed alex023 closed 8 years ago

alex023 commented 8 years ago

Env

use bytes.Buffer{} ok. but use []byte as buffer of encoder/decoder , cannot execute success.

Code

func TestString_MsgPack(t *testing.T) {
    var (
        //buf = bytes.NewBuffer(nil)
        b   []byte
        mh  codec.MsgpackHandle
        src string = "jiangcheng"
        dst string
        //dec = codec.NewDecoder(buf, &mh)
        dec = codec.NewDecoderBytes(b, &mh)
        //enc = codec.NewEncoder(buf, &mh)
        enc = codec.NewEncoderBytes(&b, &mh)
    )
    err1 := enc.Encode(src)
    if err1 != nil {
        t.Error(err1)
    }
    err2 := dec.Decode(&dst)
    if err2 != nil {
        t.Error(err2)
    }
    if !reflect.DeepEqual(src, dst) {
        t.Errorf("src!=dst.\n src=%v \n bytes=%v \n dst=%v \n", src, b, dst)
    }
}

Output:

src=jiangcheng 
bytes=[170 106 105 97 110 103 99 104 101 110 103] 
dst= 
ugorji commented 8 years ago

Huh?

superfell commented 8 years ago

@alex023 Encode changes the bytes var (notice how NewEncoderBytes takes &b) so you need to construct your decoder after you've called Encode.

ugorji commented 8 years ago

Thanks @superfell .

alex023 commented 8 years ago

Oh,got it.thanks @superfell @ugorji