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 lamport
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
type Persisted struct {
Clock
filePath string
}
func NewPersisted(filePath string) (*Persisted, error) {
clock := &Persisted{
Clock: NewClock(),
filePath: filePath,
}
dir := filepath.Dir(filePath)
err := os.MkdirAll(dir, 0777)
if err != nil {
return nil, err
}
return clock, nil
}
func LoadPersisted(filePath string) (*Persisted, error) {
clock := &Persisted{
filePath: filePath,
}
err := clock.read()
if err != nil {
return nil, err
}
return clock, nil
}
func (c *Persisted) Increment() (Time, error) {
time := c.Clock.Increment()
return time, c.Write()
}
func (c *Persisted) Witness(time Time) error {
// TODO: rework so that we write only when the clock was actually updated
c.Clock.Witness(time)
return c.Write()
}
func (c *Persisted) read() error {
content, err := ioutil.ReadFile(c.filePath)
if err != nil {
return err
}
var value uint64
n, err := fmt.Sscanf(string(content), "%d", &value)
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("could not read the clock")
}
c.Clock = NewClockWithTime(value)
return nil
}
func (c *Persisted) Write() error {
data := []byte(fmt.Sprintf("%d", c.counter))
return ioutil.WriteFile(c.filePath, data, 0644)
}
|