/
mutex_byte.go
79 lines (69 loc) · 1.67 KB
/
mutex_byte.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
package sus
import(
`sync`
)
type Marshaler func(src Version) ([]byte, error)
type Unmarshaler func(data []byte, dst Version) error
type ByteGetter func(id string) ([]byte, error)
type BytePutter func(id string, d []byte) error
type Deleter func(id string) error
// Creates and configures a store that stores entities by converting them to and from []byte and ensures versioning correctness with mutex locks.
func NewMutexByteStore(bg ByteGetter, bp BytePutter, d Deleter, m Marshaler, un Unmarshaler, idf IdFactory, vf VersionFactory, ei EntityInitializer, inee IsNonExtantError) Store {
mtx := sync.Mutex{}
getMulti := func(ids []string) ([]Version, error) {
var err error
var d []byte
count := len(ids)
vs := make([]Version, count, count)
for i := 0; i < count; i++{
d, err = bg(ids[i])
if err != nil {
break
}
vs[i] = vf()
err = un(d, vs[i])
if err != nil {
break
}
}
if err != nil {
vs = nil
}
return vs, err
}
putMulti := func(ids []string, vs []Version) error {
var err error
var d []byte
count := len(ids)
for i := 0; i < count; i++{
d, err = m(vs[i])
if err != nil {
break
}
err = bp(ids[i], d)
}
return err
}
delMulti := func(ids []string) (err error) {
count := len(ids)
for i := 0; i < count; i++ {
err = d(ids[i])
if err != nil {
break
}
}
return
}
rit := func(tran Transaction) error {
mtx.Lock()
defer mtx.Unlock()
return tran()
}
return NewStore(getMulti, putMulti, delMulti, idf, vf, ei, inee, rit)
}
type localEntityDoesNotExistError struct{
id string
}
func (e localEntityDoesNotExistError) Error() string{
return `entity with id "`+e.id+`" does not exist`
}