github.com/iotexproject/iotex-core@v1.14.1-rc1/action/protocol/staking/bucket_index.go (about) 1 // Copyright (c) 2022 IoTeX Foundation 2 // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability 3 // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed. 4 // This source code is governed by Apache License 2.0 that can be found in the LICENSE file. 5 6 package staking 7 8 import ( 9 "github.com/pkg/errors" 10 "google.golang.org/protobuf/proto" 11 12 "github.com/iotexproject/iotex-address/address" 13 14 "github.com/iotexproject/iotex-core/action/protocol/staking/stakingpb" 15 ) 16 17 type ( 18 // BucketIndices defines the array of bucket index for a 19 BucketIndices []uint64 20 ) 21 22 // Proto converts bucket indices to protobuf 23 func (bis *BucketIndices) Proto() *stakingpb.BucketIndices { 24 bucketIndicesPb := make([]uint64, 0, len(*bis)) 25 for _, bi := range *bis { 26 bucketIndicesPb = append(bucketIndicesPb, bi) 27 } 28 return &stakingpb.BucketIndices{Indices: bucketIndicesPb} 29 } 30 31 // LoadProto converts protobuf to bucket indices 32 func (bis *BucketIndices) LoadProto(bucketIndicesPb *stakingpb.BucketIndices) error { 33 if bucketIndicesPb == nil { 34 return errors.New("bucket indices protobuf cannot be nil") 35 } 36 *bis = bucketIndicesPb.Indices 37 return nil 38 } 39 40 // Deserialize deserializes bytes into bucket indices 41 func (bis *BucketIndices) Deserialize(data []byte) error { 42 bucketIndicesPb := &stakingpb.BucketIndices{} 43 if err := proto.Unmarshal(data, bucketIndicesPb); err != nil { 44 return errors.Wrap(err, "failed to unmarshal bucket indices") 45 } 46 return bis.LoadProto(bucketIndicesPb) 47 } 48 49 // Serialize serializes bucket indices into bytes 50 func (bis *BucketIndices) Serialize() ([]byte, error) { 51 return proto.Marshal(bis.Proto()) 52 } 53 54 func (bis *BucketIndices) addBucketIndex(index uint64) { 55 *bis = append(*bis, index) 56 } 57 58 func (bis *BucketIndices) deleteBucketIndex(index uint64) { 59 oldBis := *bis 60 for i, bucketIndex := range oldBis { 61 if bucketIndex == index { 62 *bis = append(oldBis[:i], oldBis[i+1:]...) 63 break 64 } 65 } 66 } 67 68 // AddrKeyWithPrefix returns address key with prefix 69 func AddrKeyWithPrefix(addr address.Address, prefix byte) []byte { 70 k := addr.Bytes() 71 key := make([]byte, len(k)+1) 72 key[0] = prefix 73 copy(key[1:], k) 74 return key 75 }