github.com/darrenli6/fabric-sdk-example@v0.0.0-20220109053535-94b13b56df8c/common/ledger/util/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 "encoding/binary" 21 "fmt" 22 23 "github.com/golang/protobuf/proto" 24 ) 25 26 // EncodeOrderPreservingVarUint64 returns a byte-representation for a uint64 number such that 27 // all zero-bits starting bytes are trimmed in order to reduce the length of the array 28 // For preserving the order in a default bytes-comparison, first byte contains the number of remaining bytes. 29 // The presence of first byte also allows to use the returned bytes as part of other larger byte array such as a 30 // composite-key representation in db 31 func EncodeOrderPreservingVarUint64(number uint64) []byte { 32 bytes := make([]byte, 8) 33 binary.BigEndian.PutUint64(bytes, number) 34 startingIndex := 0 35 size := 0 36 for i, b := range bytes { 37 if b != 0x00 { 38 startingIndex = i 39 size = 8 - i 40 break 41 } 42 } 43 sizeBytes := proto.EncodeVarint(uint64(size)) 44 if len(sizeBytes) > 1 { 45 panic(fmt.Errorf("[]sizeBytes should not be more than one byte because the max number it needs to hold is 8. size=%d", size)) 46 } 47 encodedBytes := make([]byte, size+1) 48 encodedBytes[0] = sizeBytes[0] 49 copy(encodedBytes[1:], bytes[startingIndex:]) 50 return encodedBytes 51 } 52 53 // DecodeOrderPreservingVarUint64 decodes the number from the bytes obtained from method 'EncodeOrderPreservingVarUint64'. 54 // Also, returns the number of bytes that are consumed in the process 55 func DecodeOrderPreservingVarUint64(bytes []byte) (uint64, int) { 56 s, _ := proto.DecodeVarint(bytes) 57 size := int(s) 58 decodedBytes := make([]byte, 8) 59 copy(decodedBytes[8-size:], bytes[1:size+1]) 60 numBytesConsumed := size + 1 61 return binary.BigEndian.Uint64(decodedBytes), numBytesConsumed 62 }