-
Notifications
You must be signed in to change notification settings - Fork 1
/
type.go
138 lines (116 loc) · 2.5 KB
/
type.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
133
134
135
136
137
138
// Copyright 2023 Contributors to the Veraison project.
// SPDX-License-Identifier: Apache-2.0
package cmw
import (
"encoding/json"
"fmt"
"strconv"
"github.com/fxamacker/cbor/v2"
)
type Type struct {
val any
}
func mtFromCf(cf uint16) string {
mt, ok := cf2mt[cf]
if ok {
return mt
}
return strconv.FormatUint(uint64(cf), 10)
}
func (o Type) String() string {
switch v := o.val.(type) {
case string:
return v
case uint16:
return mtFromCf(v)
case uint64:
cf, err := CF(v)
if err != nil {
return ""
}
return mtFromCf(cf)
default:
return ""
}
}
func (o Type) MarshalJSON() ([]byte, error) { return typeEncode(json.Marshal, &o) }
func (o Type) MarshalCBOR() ([]byte, error) { return typeEncode(cbor.Marshal, &o) }
func (o *Type) UnmarshalJSON(b []byte) error { return typeDecode(json.Unmarshal, b, o) }
func (o *Type) UnmarshalCBOR(b []byte) error { return typeDecode(cbor.Unmarshal, b, o) }
type (
typeDecoder func([]byte, any) error
typeEncoder func(any) ([]byte, error)
)
func typeDecode(dec typeDecoder, b []byte, o *Type) error {
var v any
if err := dec(b, &v); err != nil {
return fmt.Errorf("cannot unmarshal JSON type: %w", err)
}
switch t := v.(type) {
case string:
o.val = t
case float64: // JSON
if t == float64(uint16(t)) {
o.val = uint16(t)
} else {
return fmt.Errorf("cannot unmarshal %f into uint16", t)
}
case uint64: // CBOR
if t == uint64(uint16(t)) {
o.val = uint16(t)
} else {
return fmt.Errorf("cannot unmarshal %d into uint16", t)
}
default:
return fmt.Errorf("expecting string or uint16, got %T", t)
}
return nil
}
func typeEncode(enc typeEncoder, o *Type) ([]byte, error) {
switch t := o.val.(type) {
case string:
case uint16:
break
default:
return nil, fmt.Errorf("wrong type for Type (%T)", t)
}
return enc(o.val)
}
func (o Type) TagNumber() (uint64, error) {
switch v := o.val.(type) {
case string:
cf, ok := mt2cf[v]
if !ok {
return 0, fmt.Errorf("media type %q has no registered CoAP Content-Format", v)
}
return TN(cf), nil
case uint16:
return TN(v), nil
case uint64:
return v, nil
default:
return 0, fmt.Errorf("cannot get tag number for %T", v)
}
}
func (o Type) IsSet() bool {
if o.val == nil {
return false
}
switch t := o.val.(type) {
case string:
if t == "" {
return false
}
}
return true
}
func (o *Type) Set(v any) error {
switch t := v.(type) {
case string, uint16, uint64:
break
default:
return fmt.Errorf("unsupported type %T for CMW type", t)
}
o.val = v
return nil
}