-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
87 lines (63 loc) · 1.53 KB
/
database.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
82
83
84
85
86
87
package main
import (
"context"
"errors"
"sync"
)
type Database interface {
Create(ctx context.Context, val string) error
Find(ctx context.Context, index int) (string, error)
FindAll(ctx context.Context) ([]string, error)
Update(ctx context.Context, kindex int, val string) error
Delete(ctx context.Context, index int) error
}
type database struct {
data []string
rw sync.RWMutex
}
func NewDatabase() *database {
return &database{
data: make([]string, 0),
rw: sync.RWMutex{},
}
}
func (d *database) FindAll(ctx context.Context) ([]string, error) {
d.rw.RLock()
defer d.rw.RUnlock()
res := make([]string, len(d.data))
copy(res, d.data)
return res, nil
}
func (d *database) Create(ctx context.Context, val string) error {
d.rw.Lock()
defer d.rw.Unlock()
d.data = append(d.data, val)
return nil
}
func (d *database) Find(ctx context.Context, key int) (string, error) {
d.rw.RLock()
defer d.rw.RUnlock()
if key > len(d.data)-1 {
return "", errors.New("index out of range")
}
return d.data[key], errors.New("not found")
}
func (d *database) Update(ctx context.Context, index int, val string) error {
d.rw.Lock()
defer d.rw.Unlock()
if index > len(d.data)-1 {
return errors.New("index out of range")
}
d.data[index] = val
return nil
}
func (d *database) Delete(ctx context.Context, index int) error {
d.rw.Lock()
defer d.rw.Unlock()
if index > len(d.data)-1 {
return errors.New("index out of range")
}
d.data = append(d.data[:index], d.data[index+1:]...)
return nil
}
var _ Database = (*database)(nil)