-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswcomponents.go
104 lines (79 loc) · 2.19 KB
/
swcomponents.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
// Copyright 2024 Contributors to the Veraison project.
// SPDX-License-Identifier: Apache-2.0
package psatoken
import (
"encoding/json"
"fmt"
"reflect"
)
// SwComponents is the generic implementation of ISwComponents interface that
// should suffice for most purposes. This provides a container of concrete
// types for marashaling purposes (we can't unmarshal a slice of interfaces,
// such as []ISwComponent, with specifying a concrete type to use).
type SwComponents[I ISwComponent] struct {
values []I // nolint:structcheck
}
func (o SwComponents[I]) Validate() error {
for i, sc := range o.values {
if err := sc.Validate(); err != nil {
return fmt.Errorf("failed at index %d: %w", i, err)
}
}
return nil
}
func (o SwComponents[I]) Values() ([]ISwComponent, error) {
ret := make([]ISwComponent, len(o.values))
for i, sc := range o.values {
if err := sc.Validate(); err != nil {
return nil, fmt.Errorf("failed at index %d: %w", i, err)
}
ret[i] = sc
}
return ret, nil
}
func (o *SwComponents[I]) Add(vals ...ISwComponent) error {
toAdd, err := validateAndConvert[I](vals)
if err != nil {
return err
}
o.values = append(o.values, toAdd...)
return nil
}
func (o *SwComponents[I]) Replace(vals []ISwComponent) error {
newVals, err := validateAndConvert[I](vals)
if err != nil {
return err
}
o.values = newVals
return nil
}
func (o SwComponents[I]) IsEmpty() bool {
return len(o.values) == 0
}
func (o SwComponents[I]) MarshalCBOR() ([]byte, error) {
return em.Marshal(o.values)
}
func (o *SwComponents[I]) UnmarshalCBOR(v []byte) error {
return dm.Unmarshal(v, &o.values)
}
func (o SwComponents[I]) MarshalJSON() ([]byte, error) {
return json.Marshal(o.values)
}
func (o *SwComponents[I]) UnmarshalJSON(v []byte) error {
return json.Unmarshal(v, &o.values)
}
func validateAndConvert[I ISwComponent](vals []ISwComponent) ([]I, error) {
ret := make([]I, len(vals))
for i, sc := range vals {
if err := sc.Validate(); err != nil {
return nil, fmt.Errorf("failed at index %d: %w", i, err)
}
ta, ok := sc.(I)
if !ok {
return nil, fmt.Errorf("incorrect type at index %d; must be %s",
i, reflect.TypeOf(*new(I)).Name())
}
ret[i] = ta
}
return ret, nil
}