memory_store.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package container
  2. import "sync"
  3. // memoryStore implements a Store in memory.
  4. type memoryStore struct {
  5. s map[string]*Container
  6. sync.RWMutex
  7. }
  8. // NewMemoryStore initializes a new memory store.
  9. func NewMemoryStore() Store {
  10. return &memoryStore{
  11. s: make(map[string]*Container),
  12. }
  13. }
  14. // Add appends a new container to the memory store.
  15. // It overrides the id if it existed before.
  16. func (c *memoryStore) Add(id string, cont *Container) {
  17. c.Lock()
  18. c.s[id] = cont
  19. c.Unlock()
  20. }
  21. // Get returns a container from the store by id.
  22. func (c *memoryStore) Get(id string) *Container {
  23. c.RLock()
  24. res := c.s[id]
  25. c.RUnlock()
  26. return res
  27. }
  28. // Delete removes a container from the store by id.
  29. func (c *memoryStore) Delete(id string) {
  30. c.Lock()
  31. delete(c.s, id)
  32. c.Unlock()
  33. }
  34. // List returns a sorted list of containers from the store.
  35. // The containers are ordered by creation date.
  36. func (c *memoryStore) List() []*Container {
  37. containers := History(c.all())
  38. containers.sort()
  39. return containers
  40. }
  41. // Size returns the number of containers in the store.
  42. func (c *memoryStore) Size() int {
  43. c.RLock()
  44. defer c.RUnlock()
  45. return len(c.s)
  46. }
  47. // First returns the first container found in the store by a given filter.
  48. func (c *memoryStore) First(filter StoreFilter) *Container {
  49. for _, cont := range c.all() {
  50. if filter(cont) {
  51. return cont
  52. }
  53. }
  54. return nil
  55. }
  56. // ApplyAll calls the reducer function with every container in the store.
  57. // This operation is asyncronous in the memory store.
  58. // NOTE: Modifications to the store MUST NOT be done by the StoreReducer.
  59. func (c *memoryStore) ApplyAll(apply StoreReducer) {
  60. wg := new(sync.WaitGroup)
  61. for _, cont := range c.all() {
  62. wg.Add(1)
  63. go func(container *Container) {
  64. apply(container)
  65. wg.Done()
  66. }(cont)
  67. }
  68. wg.Wait()
  69. }
  70. func (c *memoryStore) all() []*Container {
  71. c.RLock()
  72. containers := make([]*Container, 0, len(c.s))
  73. for _, cont := range c.s {
  74. containers = append(containers, cont)
  75. }
  76. c.RUnlock()
  77. return containers
  78. }
  79. var _ Store = &memoryStore{}