wfxiang08 / goprotobuf

Automatically exported from code.google.com/p/goprotobuf
Other
0 stars 0 forks source link

Varint encoding of Large uint32 values take 10 bytes instead of 5 #39

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?

This causes a problem when precalculating the marshalled size of a protocol 
buffer struct.

Create this struct in test.proto

message MyUint32 {
  optional uint32 u = 1;
}

Create this test in all_test.go

func TestUint32(t *testing.T) {
    u := &MyUint32{}
    temp := uint32(math.MaxUint32)
    u.U = &temp
    data, err := Marshal(u)
    if err != nil {
        panic(err)
    }
    t.Logf("%#v", data)
    t.Logf("%#v", EncodeVarint(uint64(temp)))
    protoBuf := NewBuffer(nil)
    if err := protoBuf.EncodeVarint(uint64(temp)); err != nil {
        panic(err)
    }
    t.Logf("%#v", protoBuf.Bytes())
    t.Logf("%#v", EncodeVarint(uint64(int32(temp))))
}

What is the expected output? What do you see instead?

Expected

=== RUN TestUint32
--- PASS: TestUint32 (0.00 seconds)
    all_test.go:1702: []byte{0x8, 0xff, 0xff, 0xff, 0xff, 0xf}
    all_test.go:1703: []byte{0xff, 0xff, 0xff, 0xff, 0xf}
    all_test.go:1708: []byte{0xff, 0xff, 0xff, 0xff, 0xf}
    all_test.go:1709: []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1}

Instead

=== RUN TestUint32
--- PASS: TestUint32 (0.00 seconds)
    all_test.go:1702: []byte{0x8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1}
    all_test.go:1703: []byte{0xff, 0xff, 0xff, 0xff, 0xf}
    all_test.go:1708: []byte{0xff, 0xff, 0xff, 0xff, 0xf}
    all_test.go:1709: []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1}

What version of the product are you using? On what operating system?

Close to newest
c80422e14e2a

Please provide any additional information below.

Removing the cast to an int32 in enc_int32 should fix this, see the line with 
p.valEnc

// Encode an int32.
func (o *Buffer) enc_int32(p *Properties, base structPointer) error {
    v := structPointer_Word32(base, p.field)
    if word32_IsNil(v) {
        return ErrNil
    }
    x := word32_Get(v)
    o.buf = append(o.buf, p.tagcode...)
    p.valEnc(o, uint64(x))
    return nil
}

Original issue reported on code.google.com by awalterschulze on 21 Jun 2013 at 7:54

GoogleCodeExporter commented 9 years ago
I checked what C++ produces, and it encodes to the short version too.

Original comment by dsymo...@golang.org on 21 Jun 2013 at 9:28

GoogleCodeExporter commented 9 years ago
This issue was closed by revision cdb4bcf0740d.

Original comment by dsymo...@golang.org on 22 Jun 2013 at 7:57