github.com/osdi23p228/fabric@v0.0.0-20221218062954-77808885f5db/common/ledger/blkstorage/protobuf_util.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package blkstorage
     8  
     9  import (
    10  	"github.com/golang/protobuf/proto"
    11  	"github.com/pkg/errors"
    12  )
    13  
    14  // buffer provides a wrapper on top of proto.Buffer.
    15  // The purpose of this wrapper is to get to know the current position in the []byte
    16  type buffer struct {
    17  	buf      *proto.Buffer
    18  	position int
    19  }
    20  
    21  // newBuffer constructs a new instance of Buffer
    22  func newBuffer(b []byte) *buffer {
    23  	return &buffer{proto.NewBuffer(b), 0}
    24  }
    25  
    26  // DecodeVarint wraps the actual method and updates the position
    27  func (b *buffer) DecodeVarint() (uint64, error) {
    28  	val, err := b.buf.DecodeVarint()
    29  	if err == nil {
    30  		b.position += proto.SizeVarint(val)
    31  	} else {
    32  		err = errors.Wrap(err, "error decoding varint with proto.Buffer")
    33  	}
    34  	return val, err
    35  }
    36  
    37  // DecodeRawBytes wraps the actual method and updates the position
    38  func (b *buffer) DecodeRawBytes(alloc bool) ([]byte, error) {
    39  	val, err := b.buf.DecodeRawBytes(alloc)
    40  	if err == nil {
    41  		b.position += proto.SizeVarint(uint64(len(val))) + len(val)
    42  	} else {
    43  		err = errors.Wrap(err, "error decoding raw bytes with proto.Buffer")
    44  	}
    45  	return val, err
    46  }
    47  
    48  // GetBytesConsumed returns the offset of the current position in the underlying []byte
    49  func (b *buffer) GetBytesConsumed() int {
    50  	return b.position
    51  }