util.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package testing
  14. import (
  15. "fmt"
  16. "sync"
  17. )
  18. // MemStore is an implementation of CheckpointStore interface which stores checkpoint in memory.
  19. type MemStore struct {
  20. mem map[string][]byte
  21. sync.Mutex
  22. }
  23. // NewMemStore returns an instance of MemStore
  24. func NewMemStore() *MemStore {
  25. return &MemStore{mem: make(map[string][]byte)}
  26. }
  27. // Write writes the data to the store
  28. func (mstore *MemStore) Write(key string, data []byte) error {
  29. mstore.Lock()
  30. defer mstore.Unlock()
  31. mstore.mem[key] = data
  32. return nil
  33. }
  34. // Read returns data read from store
  35. func (mstore *MemStore) Read(key string) ([]byte, error) {
  36. mstore.Lock()
  37. defer mstore.Unlock()
  38. data, ok := mstore.mem[key]
  39. if !ok {
  40. return nil, fmt.Errorf("checkpoint is not found")
  41. }
  42. return data, nil
  43. }
  44. // Delete deletes data from the store
  45. func (mstore *MemStore) Delete(key string) error {
  46. mstore.Lock()
  47. defer mstore.Unlock()
  48. delete(mstore.mem, key)
  49. return nil
  50. }
  51. // List returns all the keys from the store
  52. func (mstore *MemStore) List() ([]string, error) {
  53. mstore.Lock()
  54. defer mstore.Unlock()
  55. keys := make([]string, 0)
  56. for key := range mstore.mem {
  57. keys = append(keys, key)
  58. }
  59. return keys, nil
  60. }