Skip to content

Commit

Permalink
Fix confusion between slice capacity and length
Browse files Browse the repository at this point in the history
  • Loading branch information
Antoine Pelisse committed Sep 9, 2019
1 parent 8d8355d commit e86a61c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
24 changes: 24 additions & 0 deletions proto/table_marshal.go
Expand Up @@ -2930,10 +2930,23 @@ func Size(pb Message) int {
return info.Size(pb)
}

type reverseMarshaler interface {
MarshalToSizedBuffer([]byte) (int, error)
Size() int
}

// Marshal takes a protocol buffer message
// and encodes it into the wire format, returning the data.
// This is the main entry point.
func Marshal(pb Message) ([]byte, error) {
if m, ok := pb.(reverseMarshaler); ok {
b := make([]byte, m.Size())
n, err := m.MarshalToSizedBuffer(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
if m, ok := pb.(newMarshaler); ok {
siz := m.XXX_Size()
b := make([]byte, 0, siz)
Expand Down Expand Up @@ -2965,6 +2978,17 @@ func (p *Buffer) Marshal(pb Message) error {
if _, ok := pb.(Marshaler); ok {
return fmt.Errorf("proto: deterministic not supported by the Marshal method of %T", pb)
}
if _, ok := pb.(reverseMarshaler); ok {
return fmt.Errorf("proto: deterministic not supported by the Marshal method of %T", pb)
}

}
if m, ok := pb.(reverseMarshaler); ok {
siz := m.Size()
p.grow(siz) // make sure buf has enough capacity
n, err := m.MarshalToSizedBuffer(p.buf[len(p.buf) : len(p.buf)+siz])
p.buf = p.buf[:len(p.buf)+n]
return err
}
if m, ok := pb.(newMarshaler); ok {
siz := m.XXX_Size()
Expand Down
6 changes: 2 additions & 4 deletions protoc-gen-gogo/generator/generator.go
Expand Up @@ -2717,8 +2717,7 @@ func (g *Generator) generateCommonMethods(mc *msgCtx) {
if gogoproto.IsMarshaler(g.file.FileDescriptorProto, mc.message.DescriptorProto) ||
gogoproto.IsUnsafeMarshaler(g.file.FileDescriptorProto, mc.message.DescriptorProto) {
if gogoproto.IsStableMarshaler(g.file.FileDescriptorProto, mc.message.DescriptorProto) {
g.P("b = b[:cap(b)]")
g.P("n, err := m.MarshalToSizedBuffer(b)")
g.P("n, err := m.MarshalTo(b)")
g.P("if err != nil {")
g.In()
g.P("return nil, err")
Expand All @@ -2731,8 +2730,7 @@ func (g *Generator) generateCommonMethods(mc *msgCtx) {
g.P("return xxx_messageInfo_", mc.goName, ".Marshal(b, m, deterministic)")
g.P("} else {")
g.In()
g.P("b = b[:cap(b)]")
g.P("n, err := m.MarshalToSizedBuffer(b)")
g.P("n, err := m.MarshalTo(b)")
g.P("if err != nil {")
g.In()
g.P("return nil, err")
Expand Down

0 comments on commit e86a61c

Please sign in to comment.