This repository was archived by the owner on Aug 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreference.go
More file actions
93 lines (79 loc) · 2.19 KB
/
reference.go
File metadata and controls
93 lines (79 loc) · 2.19 KB
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
88
89
90
91
92
93
package eventdb
import (
"bytes"
"strconv"
"strings"
"github.com/pkg/errors"
)
const refSeparator = ":"
// Reference is a versionned identifier
// A version identifier references a specific snapshot of an entity
type Reference string
// BuildReference returns a new Reference for id:version
func BuildReference(id string, version *uint64) Reference {
if version == nil {
return Reference(id)
}
return Reference(strings.Join(
[]string{
id,
strconv.FormatUint(*version, 10),
}, refSeparator,
))
}
// ID returns the identifier
func (r Reference) ID() string {
return strings.Split(string(r), refSeparator)[0]
}
// String returns a string representation of the whole reference
func (r Reference) String() string {
return string(r)
}
// Version returns the version of the snapshot (if any).
// If it returns false, you should assume that it references the latest version
// of the entity
func (r Reference) Version() (uint64, bool) {
parts := strings.Split(string(r), refSeparator)
if len(parts) > 1 {
v, err := strconv.ParseUint(parts[1], 10, 64)
if err != nil {
return 0, false
}
return v, true
}
return 0, false
}
// MarshalJSON implements the json.Marshaler interface.
func (r *Reference) MarshalJSON() ([]byte, error) {
return []byte(strings.Join([]string{"\"", r.String(), "\""}, "")), nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (r *Reference) UnmarshalJSON(data []byte) error {
return r.UnmarshalText(bytes.Trim(data, "\""))
}
// MarshalText implements the encoding.TextMarshaler interface
func (r Reference) MarshalText() (text []byte, err error) {
return []byte(r.String()), nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface
func (r *Reference) UnmarshalText(text []byte) error {
if len(text) == 0 {
return nil
}
parts := strings.Split(string(text), refSeparator)
if len(parts) > 1 {
// Parse version just to make sure it has the correct format
if _, err := strconv.ParseUint(parts[1], 10, 64); err != nil {
return errors.Wrap(err, "invalid reference version")
}
*r = Reference(strings.Join(
[]string{
parts[0],
parts[1],
}, refSeparator,
))
return nil
}
*r = Reference(parts[0])
return nil
}