-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory.go
80 lines (66 loc) · 1.51 KB
/
memory.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
package dbeval
import (
"sort"
"sync"
"time"
_ "github.com/lib/pq"
)
type Memory struct {
sync.RWMutex
authors map[int64]*Author
authorsByName map[string][]*Author
articles map[int64]*Article
articlesByDate []*Article
}
func (m *Memory) Connect(ds string, connLifetime time.Duration, idleConns, openConns int) {
// Noop
}
func (m *Memory) CreateDatabase() {
m.Lock()
defer m.Unlock()
m.authors = map[int64]*Author{}
m.authorsByName = map[string][]*Author{}
m.articles = map[int64]*Article{}
m.articlesByDate = nil
}
func (m *Memory) DropDatabase() {
m.CreateDatabase()
}
func (m *Memory) CreateSchema() {
// Noop
}
func (m *Memory) InsertAuthors(as []*Author) {
m.Lock()
defer m.Unlock()
for _, a := range as {
m.authors[a.ID] = a
m.authorsByName[a.Name] = append(m.authorsByName[a.Name], a)
}
}
func (m *Memory) InsertArticles(as []*Article) {
m.Lock()
defer m.Unlock()
for _, a := range as {
m.articles[a.ID] = a
}
m.articlesByDate = append(m.articlesByDate, as...)
sort.Slice(m.articlesByDate, func(i, j int) bool {
return m.articlesByDate[i].PublishedAt.After(m.articlesByDate[j].PublishedAt)
})
}
func (m *Memory) FindAuthorByID(id int64) *Author {
m.RLock()
defer m.RUnlock()
return m.authors[id]
}
func (m *Memory) FindAuthorsByName(name string) []*Author {
m.RLock()
defer m.RUnlock()
return m.authorsByName[name]
}
func (m *Memory) RecentArticles(n int) []*Article {
m.RLock()
defer m.RUnlock()
return m.articlesByDate[0:n]
}
var _ Implementation = &Memory{}