-
Notifications
You must be signed in to change notification settings - Fork 3
/
queue.go
81 lines (60 loc) · 1.2 KB
/
queue.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
80
81
package main
import "sync"
type TaskQueue struct {
mu sync.Mutex
tasks []*Task
users map[int64]*Task
Limit int
Count int
}
func NewTaskQueue(limit int) *TaskQueue {
return &TaskQueue{
tasks: make([]*Task, 0),
users: make(map[int64]*Task, 0),
Limit: limit,
}
}
// Get task by UserID and its count in queue
func (q *TaskQueue) Load(userId int64) (*Task, int) {
q.mu.Lock()
defer q.mu.Unlock()
for n, task := range q.tasks {
if task.UserID == userId {
return task, n
}
}
return nil, -1
}
func (q *TaskQueue) Enqueue(task *Task) (int, error) {
q.mu.Lock()
defer q.mu.Unlock()
t, exists := q.users[task.UserID]
if exists {
// update existing
if t.MessageID == task.MessageID {
t.Question = task.Question
return q.Count, nil
}
return q.Count, ErrOnePerUser
}
if q.Count == q.Limit {
return q.Count, ErrQueueLimit
}
q.tasks = append(q.tasks, task)
q.users[task.UserID] = task
q.Count++
return q.Count, nil
}
func (q *TaskQueue) Dequeue() (*Task, error) {
q.mu.Lock()
defer q.mu.Unlock()
if q.Count == 0 {
return nil, ErrQueueEmpty
}
task := q.tasks[0]
q.tasks[0] = nil
q.tasks = q.tasks[1:]
delete(q.users, task.UserID)
q.Count--
return task, nil
}