initial commit
[govpp.git] / adapter / mock / binapi_reflect / binapi_reflect.go
1 // Copyright (c) 2017 Cisco and/or its affiliates.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at:
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package binapi_reflect is a helper package for generic handling of VPP binary API messages
16 // in the mock adapter and integration tests.
17 package binapi_reflect
18
19 import (
20         "reflect"
21 )
22
23 const SwIfIndex = "SwIfIndex"
24 const Retval = "Retval"
25 const Reply = "_reply"
26
27 // TODO comment
28 func FindFieldOfType(reply reflect.Type, fieldName string) (reflect.StructField, bool) {
29         if reply.Kind() == reflect.Struct {
30                 field, found := reply.FieldByName(fieldName)
31                 return field, found
32         } else if reply.Kind() == reflect.Ptr && reply.Elem().Kind() == reflect.Struct {
33                 field, found := reply.Elem().FieldByName(fieldName)
34                 return field, found
35         }
36         return reflect.StructField{}, false
37 }
38
39 // TODO comment
40 func FindFieldOfValue(reply reflect.Value, fieldName string) (reflect.Value, bool) {
41         if reply.Kind() == reflect.Struct {
42                 field := reply.FieldByName(fieldName)
43                 return field, field.IsValid()
44         } else if reply.Kind() == reflect.Ptr && reply.Elem().Kind() == reflect.Struct {
45                 field := reply.Elem().FieldByName(fieldName)
46                 return field, field.IsValid()
47         }
48         return reflect.Value{}, false
49 }
50
51 // TODO comment
52 func IsReplySwIfIdx(reply reflect.Type) bool {
53         _, found := FindFieldOfType(reply, SwIfIndex)
54         return found
55 }
56
57 // TODO comment
58 func SetSwIfIdx(reply reflect.Value, swIfIndex uint32) {
59         if field, found := FindFieldOfValue(reply, SwIfIndex); found {
60                 field.Set(reflect.ValueOf(swIfIndex))
61         }
62 }
63
64 // TODO comment
65 func SetRetVal(reply reflect.Value, retVal int32) {
66         if field, found := FindFieldOfValue(reply, Retval); found {
67                 field.Set(reflect.ValueOf(retVal))
68         }
69 }
70
71 // TODO comment
72 func ReplyNameFor(request string) (string, bool) {
73         return request + Reply, true
74 }