/
value_state.go
55 lines (44 loc) · 1 KB
/
value_state.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
package storage
import (
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
)
type ValueState struct {
tx StateTransaction
}
func NewValueState(tx StateTransaction) *ValueState {
return &ValueState{
tx: tx,
}
}
func (vs *ValueState) Set(value proto.Message) error {
byteValue, err := proto.Marshal(value)
if err != nil {
return errors.Wrap(err, "couldn't marshal value")
}
return vs.setBytes(byteValue)
}
func (vs *ValueState) setBytes(b []byte) error {
err := vs.tx.Set(nil, b)
if err != nil {
return errors.Wrap(err, "couldn't set value")
}
return nil
}
func (vs *ValueState) Get(value proto.Message) error {
data, err := vs.tx.Get(nil)
if err == ErrNotFound {
return ErrNotFound
} else if err != nil {
return errors.Wrap(err, "an error occurred while reading the value")
}
err = proto.Unmarshal(data, value)
return err
}
func (vs *ValueState) Clear() error {
err := vs.tx.Delete(nil)
if err != nil {
return errors.Wrap(err, "couldn't clear value state")
}
return nil
}