github.com/MetalBlockchain/metalgo@v1.11.9/pubsub/connections.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package pubsub
     5  
     6  import (
     7  	"sync"
     8  
     9  	"github.com/MetalBlockchain/metalgo/utils/set"
    10  )
    11  
    12  type connections struct {
    13  	lock      sync.RWMutex
    14  	conns     set.Set[*connection]
    15  	connsList []Filter
    16  }
    17  
    18  func newConnections() *connections {
    19  	return &connections{}
    20  }
    21  
    22  func (c *connections) Conns() []Filter {
    23  	c.lock.RLock()
    24  	defer c.lock.RUnlock()
    25  
    26  	return append([]Filter{}, c.connsList...)
    27  }
    28  
    29  func (c *connections) Remove(conn *connection) {
    30  	c.lock.Lock()
    31  	defer c.lock.Unlock()
    32  
    33  	c.conns.Remove(conn)
    34  	c.createConnsList()
    35  }
    36  
    37  func (c *connections) Add(conn *connection) {
    38  	c.lock.Lock()
    39  	defer c.lock.Unlock()
    40  
    41  	c.conns.Add(conn)
    42  	c.createConnsList()
    43  }
    44  
    45  func (c *connections) createConnsList() {
    46  	resp := make([]Filter, 0, len(c.conns))
    47  	for c := range c.conns {
    48  		resp = append(resp, c)
    49  	}
    50  	c.connsList = resp
    51  }