github.com/keltia/go-ipfs@v0.3.8-0.20150909044612-210793031c63/blocks/key/key_set.go (about)

     1  package key
     2  
     3  import (
     4  	"sync"
     5  )
     6  
     7  type KeySet interface {
     8  	Add(Key)
     9  	Remove(Key)
    10  	Keys() []Key
    11  }
    12  
    13  type ks struct {
    14  	lock sync.RWMutex
    15  	data map[Key]struct{}
    16  }
    17  
    18  func NewKeySet() KeySet {
    19  	return &ks{
    20  		data: make(map[Key]struct{}),
    21  	}
    22  }
    23  
    24  func (wl *ks) Add(k Key) {
    25  	wl.lock.Lock()
    26  	defer wl.lock.Unlock()
    27  
    28  	wl.data[k] = struct{}{}
    29  }
    30  
    31  func (wl *ks) Remove(k Key) {
    32  	wl.lock.Lock()
    33  	defer wl.lock.Unlock()
    34  
    35  	delete(wl.data, k)
    36  }
    37  
    38  func (wl *ks) Keys() []Key {
    39  	wl.lock.RLock()
    40  	defer wl.lock.RUnlock()
    41  	keys := make([]Key, 0)
    42  	for k := range wl.data {
    43  		keys = append(keys, k)
    44  	}
    45  	return keys
    46  }