wings/server/collection.go

78 lines
1.3 KiB
Go
Raw Normal View History

package server
2019-12-22 07:23:56 +00:00
import "sync"
type Collection struct {
items []*Server
2020-04-11 01:03:35 +00:00
sync.RWMutex
2019-12-22 07:23:56 +00:00
}
// Create a new collection from a slice of servers.
func NewCollection(servers []*Server) *Collection {
return &Collection{
items: servers,
}
}
// Return all of the items in the collection.
func (c *Collection) All() []*Server {
c.RLock()
defer c.RUnlock()
return c.items
}
// Adds an item to the collection store.
func (c *Collection) Add(s *Server) {
2020-04-11 01:03:35 +00:00
c.Lock()
c.items = append(c.items, s)
2020-04-11 01:03:35 +00:00
c.Unlock()
}
// Returns only those items matching the filter criteria.
2019-12-22 07:23:56 +00:00
func (c *Collection) Filter(filter func(*Server) bool) []*Server {
2020-04-11 01:03:35 +00:00
c.RLock()
defer c.RUnlock()
2019-12-22 07:23:56 +00:00
r := make([]*Server, 0)
for _, v := range c.items {
if filter(v) {
r = append(r, v)
}
}
return r
}
// Returns a single element from the collection matching the filter. If nothing is
// found a nil result is returned.
2019-12-22 07:23:56 +00:00
func (c *Collection) Find(filter func(*Server) bool) *Server {
2020-04-11 01:03:35 +00:00
c.RLock()
defer c.RUnlock()
for _, v := range c.items {
if filter(v) {
return v
}
}
return nil
2019-12-22 07:23:56 +00:00
}
// Removes all items from the collection that match the filter function.
//
// TODO: cancel the context?
2019-12-22 07:23:56 +00:00
func (c *Collection) Remove(filter func(*Server) bool) {
2020-04-11 01:03:35 +00:00
c.Lock()
defer c.Unlock()
2019-12-22 07:23:56 +00:00
r := make([]*Server, 0)
for _, v := range c.items {
if !filter(v) {
r = append(r, v)
}
}
c.items = r
}