github.com/tilt-dev/tilt@v0.33.15-0.20240515162809-0a22ed45d8a0/internal/hud/server/websocketlist.go (about)

     1  package server
     2  
     3  import (
     4  	"sync"
     5  )
     6  
     7  type WebsocketList struct {
     8  	items []*WebsocketSubscriber
     9  	mu    sync.RWMutex
    10  }
    11  
    12  func NewWebsocketList() *WebsocketList {
    13  	return &WebsocketList{}
    14  }
    15  
    16  func (l *WebsocketList) Add(w *WebsocketSubscriber) {
    17  	l.mu.Lock()
    18  	defer l.mu.Unlock()
    19  	l.items = append(l.items, w)
    20  }
    21  
    22  func (l *WebsocketList) Remove(w *WebsocketSubscriber) {
    23  	l.mu.Lock()
    24  	defer l.mu.Unlock()
    25  	for i, item := range l.items {
    26  		if item == w {
    27  			l.items = append(l.items[:i], l.items[i+1:]...)
    28  			return
    29  		}
    30  	}
    31  }
    32  
    33  // Operate on all websockets in the list.
    34  //
    35  // While the ForEach is running, the list may not be modified.
    36  //
    37  // In the future, it might make sense allow modification of the list while the
    38  // foreach runs, but then we'd need additional synchronization to make sure
    39  // we don't get websocket send() after removal.
    40  func (l *WebsocketList) ForEach(f func(w *WebsocketSubscriber)) {
    41  	l.mu.RLock()
    42  	defer l.mu.RUnlock()
    43  
    44  	for _, item := range l.items {
    45  		f(item)
    46  	}
    47  }