forked from ovn-org/libovsdb
-
Notifications
You must be signed in to change notification settings - Fork 10
/
set.go
54 lines (47 loc) · 1.42 KB
/
set.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
package libovsdb
import (
"encoding/json"
"errors"
"reflect"
)
// RFC 7047 has a wierd (but understandable) notation for set as described as :
// Either an <atom>, representing a set with exactly one element, or
// a 2-element JSON array that represents a database set value. The
// first element of the array must be the string "set", and the
// second element must be an array of zero or more <atom>s giving the
// values in the set. All of the <atom>s must have the same type.
type OvsSet struct {
GoSet []interface{}
}
// <set> notation requires special handling
func NewOvsSet(goSlice interface{}) (*OvsSet, error) {
v := reflect.ValueOf(goSlice)
if v.Kind() != reflect.Slice {
return nil, errors.New("OvsSet supports only Go Slice types")
}
var ovsSet []interface{}
for i := 0; i < v.Len(); i++ {
ovsSet = append(ovsSet, v.Index(i).Interface())
}
return &OvsSet{ovsSet}, nil
}
// <set> notation requires special marshaling
func (o OvsSet) MarshalJSON() ([]byte, error) {
var oSet []interface{}
oSet = append(oSet, "set")
oSet = append(oSet, o.GoSet)
return json.Marshal(oSet)
}
func (o *OvsSet) UnmarshalJSON(b []byte) (err error) {
var oSet []interface{}
if err = json.Unmarshal(b, &oSet); err == nil && len(oSet) > 1 {
innerSet := oSet[1].([]interface{})
for _, val := range innerSet {
goVal, err := ovsSliceToGoNotation(val)
if err == nil {
o.GoSet = append(o.GoSet, goVal)
}
}
}
return err
}