github.com/tenywen/fabric@v1.0.0-beta.0.20170620030522-a5b1ed380643/core/ledger/kvledger/txmgmt/version/version.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 version
    18  
    19  import "github.com/hyperledger/fabric/common/ledger/util"
    20  
    21  // Height represents the height of a transaction in blockchain
    22  type Height struct {
    23  	BlockNum uint64
    24  	TxNum    uint64
    25  }
    26  
    27  // NewHeight constructs a new instance of Height
    28  func NewHeight(blockNum, txNum uint64) *Height {
    29  	return &Height{blockNum, txNum}
    30  }
    31  
    32  // NewHeightFromBytes constructs a new instance of Height from serialized bytes
    33  func NewHeightFromBytes(b []byte) (*Height, int) {
    34  	blockNum, n1 := util.DecodeOrderPreservingVarUint64(b)
    35  	txNum, n2 := util.DecodeOrderPreservingVarUint64(b[n1:])
    36  	return NewHeight(blockNum, txNum), n1 + n2
    37  }
    38  
    39  // ToBytes serializes the Height
    40  func (h *Height) ToBytes() []byte {
    41  	blockNumBytes := util.EncodeOrderPreservingVarUint64(h.BlockNum)
    42  	txNumBytes := util.EncodeOrderPreservingVarUint64(h.TxNum)
    43  	return append(blockNumBytes, txNumBytes...)
    44  }
    45  
    46  // Compare return a -1, zero, or +1 based on whether this height is
    47  // less than, equals to, or greater than the specified height respectively.
    48  func (h *Height) Compare(h1 *Height) int {
    49  	res := 0
    50  	switch {
    51  	case h.BlockNum != h1.BlockNum:
    52  		res = int(h.BlockNum - h1.BlockNum)
    53  		break
    54  	case h.TxNum != h1.TxNum:
    55  		res = int(h.TxNum - h1.TxNum)
    56  		break
    57  	default:
    58  		return 0
    59  	}
    60  	if res > 0 {
    61  		return 1
    62  	}
    63  	return -1
    64  }
    65  
    66  // AreSame returns true if both the heights are either nil or equal
    67  func AreSame(h1 *Height, h2 *Height) bool {
    68  	if h1 == nil {
    69  		return h2 == nil
    70  	}
    71  	if h2 == nil {
    72  		return false
    73  	}
    74  	return h1.Compare(h2) == 0
    75  }