forked from veraison/corim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrel.go
132 lines (102 loc) · 2.06 KB
/
rel.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
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
// Copyright 2021-2024 Contributors to the Veraison project.
// SPDX-License-Identifier: Apache-2.0
package comid
import (
"encoding/json"
"errors"
"fmt"
)
type Rel int64
const (
RelSupplements Rel = iota
RelReplaces
RelUnset = ^Rel(0)
)
var (
relToString = map[Rel]string{
RelReplaces: "replaces",
RelSupplements: "supplements",
}
stringToRel = map[string]Rel{
"replaces": RelReplaces,
"supplements": RelSupplements,
}
)
// RegisterRel creates a new Rel association between the provided value and
// name. An error is returned if either clashes with any of the existing roles.
func RegisterRel(val int64, name string) error {
rel := Rel(val)
if _, ok := relToString[rel]; ok {
return fmt.Errorf("rel with value %d already exists", val)
}
if _, ok := stringToRel[name]; ok {
return fmt.Errorf("rel with name %q already exists", name)
}
relToString[rel] = name
stringToRel[name] = rel
return nil
}
func NewRel() *Rel {
r := RelUnset
return &r
}
func (o *Rel) Set(r Rel) *Rel {
if o != nil {
*o = r
}
return o
}
func (o Rel) Get() Rel {
return o
}
func (o Rel) Valid() error {
if o == RelUnset {
return errors.New("rel is unset")
}
return nil
}
func (o Rel) String() string {
ret, ok := relToString[o]
if ok {
return ret
}
return fmt.Sprintf("rel(%d)", o)
}
func (o Rel) ToCBOR() ([]byte, error) {
if err := o.Valid(); err != nil {
return nil, err
}
data, err := em.Marshal(o)
if err != nil {
return nil, err
}
return data, nil
}
func (o *Rel) FromCBOR(data []byte) error {
err := dm.Unmarshal(data, o)
if err != nil {
return err
}
return o.Valid()
}
func (o *Rel) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return fmt.Errorf("cannot unmarshal rel: %w", err)
}
if s == "" {
return fmt.Errorf("empty rel")
}
switch s {
case "supplements":
*o = RelSupplements
case "replaces":
*o = RelReplaces
default:
return fmt.Errorf("unknown rel '%s'", s)
}
return nil
}
func (o Rel) MarshalJSON() ([]byte, error) {
return json.Marshal(o.String())
}