-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
49 lines (42 loc) · 907 Bytes
/
db.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
package main
import (
"sync"
maelstrom "github.com/jepsen-io/maelstrom/demo/go"
)
type Db struct {
Entries map[int]int
mu sync.Mutex
}
func NewDb() *Db {
return &Db{
Entries: make(map[int]int),
}
}
func (db *Db) Get(key int) (int, error) {
db.mu.Lock()
defer db.mu.Unlock()
val, ok := db.Entries[key]
if !ok {
return 0, maelstrom.NewRPCError(maelstrom.KeyDoesNotExist, "Key does not exist")
}
return val, nil
}
func (db *Db) Set(key int, val int) error {
db.mu.Lock()
defer db.mu.Unlock()
db.Entries[key] = val
return nil
}
func (db *Db) Cas(key int, from int, to int) error {
db.mu.Lock()
defer db.mu.Unlock()
val, ok := db.Entries[key]
if !ok {
return maelstrom.NewRPCError(maelstrom.KeyDoesNotExist, "Key does not exist")
}
if val != from {
return maelstrom.NewRPCError(maelstrom.PreconditionFailed, "Precondition failed")
}
db.Entries[key] = to
return nil
}