blob: 682b8d16ba346c8f7e32da422b7a49a89b198eda [file] [log] [blame]
Zack Williamse940c7a2019-08-21 14:25:39 -07001/*
2 * Copyright 2019-present Ciena Corporation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package model
17
18import (
Neha Sharma19ca2bf2020-05-11 15:34:17 +000019 "errors"
Zack Williamse940c7a2019-08-21 14:25:39 -070020 "github.com/jhump/protoreflect/dynamic"
21)
22
Neha Sharma19ca2bf2020-05-11 15:34:17 +000023func GetEnumValue(val *dynamic.Message, name string) (string, error) {
24 fd := val.FindFieldDescriptorByName(name)
25 if fd == nil {
26 return "", errors.New("fieldDescriptor is nil for " + name)
Scott Bakered4efab2020-01-13 19:12:25 -080027 }
Neha Sharma19ca2bf2020-05-11 15:34:17 +000028
29 enumType := fd.GetEnumType()
30 if enumType == nil {
31 return "", errors.New("enumType is nil for " + name)
32 }
33
34 field, ok := val.GetFieldByName(name).(int32)
35 if !ok {
36 return "", errors.New("Enum integer value not found for " + name)
37 }
38
39 eValue := enumType.FindValueByNumber(field)
40 if eValue == nil {
41 return "", errors.New("Value not found for " + name)
42 }
43
44 return eValue.GetName(), nil
45}
46
47func SetEnumValue(msg *dynamic.Message, name string, value string) error {
48 fd := msg.FindFieldDescriptorByName(name)
49 if fd == nil {
50 return errors.New("fieldDescriptor is nil for " + name)
51 }
52
53 enumType := fd.GetEnumType()
54 if enumType == nil {
55 return errors.New("enumType is nil for " + name)
56 }
57
58 eValue := enumType.FindValueByName(value)
59 if eValue == nil {
60 return errors.New("Value not found for " + name)
61 }
62
63 msg.SetFieldByName(name, eValue.GetNumber())
64 return nil
65}
66
67func GetEnumString(msg *dynamic.Message, name string, value int32) (string, error) {
68 fd := msg.FindFieldDescriptorByName(name)
69 if fd == nil {
70 return "", errors.New("fieldDescriptor is nil for " + name)
71 }
72
73 enumType := fd.GetEnumType()
74 if enumType == nil {
75 return "", errors.New("enumType is nil for " + name)
76 }
77
78 eValue := enumType.FindValueByNumber(value)
79 if eValue == nil {
80 return "", errors.New("Value not found for " + name)
81 }
82 return eValue.GetName(), nil
Scott Bakered4efab2020-01-13 19:12:25 -080083}