github.com/insolar/vanilla@v0.0.0-20201023172447-248fdf805322/merkler/utils.go (about) 1 // Copyright 2020 Insolar Network Ltd. 2 // All rights reserved. 3 // This material is licensed under the Insolar License version 1.0, 4 // available at https://github.com/insolar/assured-ledger/blob/master/LICENSE.md. 5 6 package merkler 7 8 import ( 9 "math" 10 "math/bits" 11 ) 12 13 // Returns a level at which the unbalanced node will connect to the rightmost branch. 14 // It trims from left all consequent 1's starting from (bitCount) and returns a number of remaining bits. 15 // Doesn't panic, but result is meaningless when (maxPairLevel) is not in [0, 64] or (index) >= 1<<(maxPairLevel) 16 func UnbalancedBitCount(index uint, bitCount uint8) uint8 { 17 if bitCount == 0 { 18 return 0 19 } 20 return uint8(bits.Len(^(index | math.MaxInt64<<bitCount))) 21 } 22 23 func StackSequenceUnused(count uint) uint8 { 24 if count == 0 { 25 return 0 26 } 27 return uint8(bits.Len(count+1)) - 1 28 } 29 30 //func AlignedNodeCount(leafCount uint, stubbed bool) uint { 31 // if stubbed { 32 // depth := uint8(bits.Len(leafCount - 1)) 33 // // TODO stubbed node count 34 // return leafCount + uint(depth - 1) 35 // } 36 // return leafCount + uint(StackSequenceUnused(leafCount)) - 1 37 //} 38 39 func AdjustStackSequenceIndexByUnused(index uint) uint { 40 switch index { 41 case 0: 42 return 0 43 case 1: 44 panic("illegal value") 45 } 46 b := uint(bits.Len(index)) 47 switch skip := uint(1)<<b - 3; { 48 case index < skip: 49 index++ 50 case index == skip: 51 panic("illegal value") 52 } 53 index -= b - 1 54 return index 55 }