github.com/iotexproject/iotex-core@v1.14.1-rc1/blocksync/uniqueue.go (about)

     1  // Copyright (c) 2021 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 blocksync
     7  
     8  import (
     9  	"github.com/iotexproject/go-pkgs/hash"
    10  )
    11  
    12  // uniQueue is not threadsafe
    13  type uniQueue struct {
    14  	blocks []*peerBlock
    15  	hashes map[hash.Hash256]struct{}
    16  }
    17  
    18  func newUniQueue() *uniQueue {
    19  	return &uniQueue{
    20  		blocks: []*peerBlock{},
    21  		hashes: map[hash.Hash256]struct{}{},
    22  	}
    23  }
    24  
    25  func (uq *uniQueue) enque(blk *peerBlock) {
    26  	h := blk.block.HashBlock()
    27  	if _, ok := uq.hashes[h]; ok {
    28  		return
    29  	}
    30  	uq.hashes[h] = struct{}{}
    31  	uq.blocks = append(uq.blocks, blk)
    32  }
    33  
    34  func (uq *uniQueue) dequeAll() []*peerBlock {
    35  	blks := uq.blocks
    36  	if len(uq.blocks) > 0 {
    37  		uq.blocks = []*peerBlock{}
    38  		uq.hashes = map[hash.Hash256]struct{}{}
    39  	}
    40  	return blks
    41  }