github.com/myafeier/fabric@v1.0.1-0.20170722181825-3a4b1f2bce86/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 ) 22 23 // Buffer provides a wrapper on top of proto.Buffer. 24 // The purpose of this wrapper is to get to know the current position in the []byte 25 type Buffer struct { 26 buf *proto.Buffer 27 position int 28 } 29 30 // NewBuffer constructs a new instance of Buffer 31 func NewBuffer(b []byte) *Buffer { 32 return &Buffer{proto.NewBuffer(b), 0} 33 } 34 35 // DecodeVarint wraps the actual method and updates the position 36 func (b *Buffer) DecodeVarint() (uint64, error) { 37 val, err := b.buf.DecodeVarint() 38 if err == nil { 39 b.position += proto.SizeVarint(val) 40 } 41 return val, err 42 } 43 44 // DecodeRawBytes wraps the actual method and updates the position 45 func (b *Buffer) DecodeRawBytes(alloc bool) ([]byte, error) { 46 val, err := b.buf.DecodeRawBytes(alloc) 47 if err == nil { 48 b.position += proto.SizeVarint(uint64(len(val))) + len(val) 49 } 50 return val, err 51 } 52 53 // GetBytesConsumed returns the offset of the current position in the underlying []byte 54 func (b *Buffer) GetBytesConsumed() int { 55 return b.position 56 }