github.com/turingchain2020/turingchain@v1.1.21/util/calcbitmap.go (about) 1 // Copyright Turing Corp. 2018 All Rights Reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package util 6 7 import ( 8 "math/big" 9 10 "github.com/turingchain2020/turingchain/types" 11 ) 12 13 //CalcBitMap subs are align with subData,get the bases' tx's bitmap from subs result 14 // if the tx ty is OK in subs, find the tx in base and set the index to 1, this function return base's bitmap 15 //if all tx failed, the setBit will normalize result and just return nil slice 16 func CalcBitMap(bases, subs [][]byte, subData []*types.ReceiptData) []byte { 17 rst := big.NewInt(0) 18 19 subMap := make(map[string]bool) 20 for i, sub := range subs { 21 if subData[i].Ty == types.ExecOk { 22 subMap[string(sub)] = true 23 } 24 } 25 26 for i, base := range bases { 27 if _, exist := subMap[string(base)]; exist { 28 rst.SetBit(rst, i, 1) 29 } 30 } 31 32 return rst.Bytes() 33 } 34 35 //CalcSingleBitMap calc bitmap to bases by data 36 func CalcSingleBitMap(bases [][]byte, data []*types.ReceiptData) []byte { 37 rst := big.NewInt(0) 38 39 for i := range bases { 40 if data[i].Ty == types.ExecOk { 41 rst.SetBit(rst, i, 1) 42 } 43 } 44 45 return rst.Bytes() 46 } 47 48 //CalcBitMapByBitMap bitmap align with subs 49 func CalcBitMapByBitMap(bases, subs [][]byte, bitmap []byte) []byte { 50 rst := big.NewInt(0) 51 bit := big.NewInt(0).SetBytes(bitmap) 52 53 subMap := make(map[string]bool) 54 for i, sub := range subs { 55 if bit.Bit(i) == uint(0x1) { 56 subMap[string(sub)] = true 57 } 58 } 59 60 for i, base := range bases { 61 if _, exist := subMap[string(base)]; exist { 62 rst.SetBit(rst, i, 1) 63 } 64 } 65 66 return rst.Bytes() 67 } 68 69 //SetAddrsBitMap 设置addrGroup范围内的bitmap,如果addrs在addrGroup不存在,也不设置,返回未命中的addrs 70 func SetAddrsBitMap(addrGroup, addrs []string) ([]byte, map[string]bool) { 71 rst := big.NewInt(0) 72 addrsMap := make(map[string]bool) 73 for _, n := range addrs { 74 addrsMap[n] = true 75 } 76 77 for i, a := range addrGroup { 78 if _, exist := addrsMap[a]; exist { 79 rst.SetBit(rst, i, 1) 80 delete(addrsMap, a) 81 } 82 } 83 return rst.Bytes(), addrsMap 84 } 85 86 //GetAddrsByBitMap 根据bitmap获取addrGroup范围内的addrs, 87 func GetAddrsByBitMap(addrGroup []string, bitmap []byte) []string { 88 rst := big.NewInt(0).SetBytes(bitmap) 89 addrs := make([]string, 0) 90 91 for i, a := range addrGroup { 92 if rst.Bit(i) == uint(0x1) { 93 addrs = append(addrs, a) 94 } 95 } 96 return addrs 97 } 98 99 //BitMapBit :index begin from 0, find the index bit, 1 or 0 100 func BitMapBit(bitmap []byte, index uint32) bool { 101 rst := big.NewInt(0).SetBytes(bitmap) 102 return rst.Bit(int(index)) == uint(0x1) 103 }