-
Notifications
You must be signed in to change notification settings - Fork 1
/
tasks.go
75 lines (58 loc) · 1.36 KB
/
tasks.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
package tasks
import "sync"
// Storage is a simple RWLock protected map
type Storage struct {
storage map[string]*Task
sync.RWMutex
}
// Get returns task from the storage
func (s *Storage) Get(id string) *Task {
s.RLock()
defer s.RUnlock()
return s.storage[id]
}
// Add adds task to the sorage
func (s *Storage) Add(task *Task) {
s.Lock()
defer s.Unlock()
s.storage[task.id] = task
}
// Restore adds task to the sorage with respect to the sequence internal variable
func (s *Storage) Restore(task *Task) {
s.Lock()
defer s.Unlock()
s.storage[task.id] = task
if sequence < task.Sequence {
sequence = task.Sequence
}
}
// Del deletes task to the sorage
func (s *Storage) Del(id string) {
s.Lock()
defer s.Unlock()
delete(s.storage, id)
}
// NewStorage creates a new task storage struct with the internal map initialised
func NewStorage() *Storage {
return &Storage{
storage: make(map[string]*Task),
}
}
// ForeachFunc is a type of func to be passed to Foreach method
type ForeachFunc func(id string, task *Task) (found bool, stop bool)
// Foreach executes the function provided for each task in the storage
func (s *Storage) Foreach(f ForeachFunc) int {
s.RLock()
defer s.RUnlock()
totalFound := 0
for id, task := range s.storage {
found, stop := f(id, task)
if found {
totalFound++
}
if stop {
return totalFound
}
}
return totalFound
}