tractor.dev/toolkit-go@v0.0.0-20241010005851-214d91207d07/duplex/mux/util_chanlist.go (about) 1 package mux 2 3 import "sync" 4 5 // chanList is a thread safe channel list. 6 type chanList struct { 7 // protects concurrent access to chans 8 sync.Mutex 9 10 // chans are indexed by the local id of the channel, which the 11 // other side should send in the PeersId field. 12 chans []*channel 13 } 14 15 // Assigns a channel ID to the given channel. 16 func (c *chanList) add(ch *channel) uint32 { 17 c.Lock() 18 defer c.Unlock() 19 for i := range c.chans { 20 if c.chans[i] == nil { 21 c.chans[i] = ch 22 return uint32(i) 23 } 24 } 25 c.chans = append(c.chans, ch) 26 return uint32(len(c.chans) - 1) 27 } 28 29 // getChan returns the channel for the given ID. 30 func (c *chanList) getChan(id uint32) *channel { 31 c.Lock() 32 defer c.Unlock() 33 if id < uint32(len(c.chans)) { 34 return c.chans[id] 35 } 36 return nil 37 } 38 39 func (c *chanList) remove(id uint32) { 40 c.Lock() 41 if id < uint32(len(c.chans)) { 42 c.chans[id] = nil 43 } 44 c.Unlock() 45 } 46 47 // dropAll forgets all channels it knows, returning them in a slice. 48 func (c *chanList) dropAll() []*channel { 49 c.Lock() 50 defer c.Unlock() 51 var r []*channel 52 53 for _, ch := range c.chans { 54 if ch == nil { 55 continue 56 } 57 r = append(r, ch) 58 } 59 c.chans = nil 60 return r 61 }