/
versioned.go
58 lines (47 loc) · 1.29 KB
/
versioned.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 cbor
import (
"errors"
"math"
"github.com/fxamacker/cbor/v2"
)
const invalidVersion = math.MaxUint16
var (
// ErrInvalidVersion is the error returned when a versioned
// serialized blob is either missing, or has an invalid version.
ErrInvalidVersion = errors.New("cbor: missing or invalid version")
decOptionsVersioned = decOptions
decModeVersioned cbor.DecMode
)
// Versioned is a generic versioned serializable data structure.
type Versioned struct {
V uint16 `json:"v"`
}
// GetVersion returns the version of a versioned serializable data
// structure, if any.
func GetVersion(data []byte) (uint16, error) {
vblob := Versioned{
V: invalidVersion,
}
if err := decModeVersioned.Unmarshal(data, &vblob); err != nil {
return 0, err
}
if vblob.V == invalidVersion {
return 0, ErrInvalidVersion
}
return vblob.V, nil
}
// NewVersioned creates a new Versioned structure with the specified version.
func NewVersioned(v uint16) Versioned {
if v == invalidVersion {
panic("cbor: invalid version specified")
}
return Versioned{V: v}
}
func init() {
// Use the untrusted decode options, but ignore unknown fields.
decOptionsVersioned.ExtraReturnErrors = cbor.ExtraDecErrorNone
var err error
if decModeVersioned, err = decOptionsVersioned.DecMode(); err != nil {
panic(err)
}
}