-
Notifications
You must be signed in to change notification settings - Fork 2
/
lwwregister.go
58 lines (48 loc) · 1.15 KB
/
lwwregister.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
package rapport
import (
"fmt"
"time"
)
type LWWRegister struct {
t time.Time
value string
}
func CreateLWWRegister(initialValue string) *LWWRegister {
return &LWWRegister{
value: initialValue,
t: time.Now().UTC(),
}
}
func (l *LWWRegister) Set(value string, t time.Time) error {
if t.Before(l.t) {
return fmt.Errorf("Cannot set register to a value from the past: %v < %v", t, l.t)
}
l.t = t
l.value = value
return nil
}
func (l *LWWRegister) Get() string {
return l.value
}
func (l *LWWRegister) Merge(crdt CRDT) {
otherReg := crdt.(*LWWRegister)
if l.t.Before(otherReg.t) {
l.value = otherReg.value
l.t = otherReg.t
} else if l.t == otherReg.t && otherReg.value != l.value {
// This is bad...
panic("Merge found the same timestamp but different values, registers have diverged")
}
}
// Marshal serialises the register data to bytes
func (l *LWWRegister) Marshal() ([]*Segment, error) {
segment := &Segment{
Value: []byte(l.value),
}
return []*Segment{segment}, nil
}
// Marshal deserialises the register data from bytes
func (l *LWWRegister) Unmarshal(data []*Segment) error {
l.value = string(data[0].Value)
return nil
}