github.com/sykesm/fabric@v1.1.0-preview.0.20200129034918-2aa12b1a0181/common/ledger/util/protobuf_util.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  		 http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package util
    18  
    19  import (
    20  	"github.com/golang/protobuf/proto"
    21  	"github.com/pkg/errors"
    22  )
    23  
    24  // Buffer provides a wrapper on top of proto.Buffer.
    25  // The purpose of this wrapper is to get to know the current position in the []byte
    26  type Buffer struct {
    27  	buf      *proto.Buffer
    28  	position int
    29  }
    30  
    31  // NewBuffer constructs a new instance of Buffer
    32  func NewBuffer(b []byte) *Buffer {
    33  	return &Buffer{proto.NewBuffer(b), 0}
    34  }
    35  
    36  // DecodeVarint wraps the actual method and updates the position
    37  func (b *Buffer) DecodeVarint() (uint64, error) {
    38  	val, err := b.buf.DecodeVarint()
    39  	if err == nil {
    40  		b.position += proto.SizeVarint(val)
    41  	} else {
    42  		err = errors.Wrap(err, "error decoding varint with proto.Buffer")
    43  	}
    44  	return val, err
    45  }
    46  
    47  // DecodeRawBytes wraps the actual method and updates the position
    48  func (b *Buffer) DecodeRawBytes(alloc bool) ([]byte, error) {
    49  	val, err := b.buf.DecodeRawBytes(alloc)
    50  	if err == nil {
    51  		b.position += proto.SizeVarint(uint64(len(val))) + len(val)
    52  	} else {
    53  		err = errors.Wrap(err, "error decoding raw bytes with proto.Buffer")
    54  	}
    55  	return val, err
    56  }
    57  
    58  // GetBytesConsumed returns the offset of the current position in the underlying []byte
    59  func (b *Buffer) GetBytesConsumed() int {
    60  	return b.position
    61  }