-
Notifications
You must be signed in to change notification settings - Fork 81
/
memory_store.go
79 lines (64 loc) · 1.77 KB
/
memory_store.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package match
import (
"sync"
"github.com/jmartin82/mmock/definition"
)
//MemoryStore stores all received request and their matches in memory until the last reset
type MemoryStore struct {
matches []definition.Match
sync.Mutex
checker Checker
}
//Save store a match information
func (mrs *MemoryStore) Save(req definition.Match) {
mrs.Lock()
mrs.matches = append(mrs.matches, req)
mrs.Unlock()
}
//Reset clean the request stored in memory
func (mrs *MemoryStore) Reset() {
mrs.Lock()
mrs.matches = make([]definition.Match, 0, 100)
mrs.Unlock()
}
//ResetMatch clean the request stored in memory that matches a particular criteria
func (mrs *MemoryStore) ResetMatch(req definition.Request) {
matches := mrs.GetAll()
mrs.Lock()
var r = []definition.Match{}
for _, e := range matches {
if c, _ := mrs.checker.Check(e.Request, &definition.Mock{Request: req}, false); c == false {
r = append(r, e)
}
}
mrs.matches = r
mrs.Unlock()
}
//GetAll return current matches (positive and negative) in memory
func (mrs *MemoryStore) GetAll() []definition.Match {
mrs.Lock()
r := make([]definition.Match, len(mrs.matches))
copy(r, mrs.matches)
mrs.Unlock()
return r
}
//Get return an subset of current matches (positive and negative) in memory
func (mrs *MemoryStore) Get(limit uint, offset uint) []definition.Match {
mrs.Lock()
defer mrs.Unlock()
max := offset + limit
if max > uint(len(mrs.matches)) {
max = uint(len(mrs.matches))
}
if offset >= max {
return []definition.Match{}
}
r := make([]definition.Match, max-offset)
copy(r, mrs.matches[offset:max])
return r
}
//NewMemoryStore is the MemoryStore constructor
func NewMemoryStore(checker Checker) *MemoryStore {
reqs := make([]definition.Match, 0, 100)
return &MemoryStore{matches: reqs, checker: checker}
}