blob: 70bd977d6241f9692ab5430e7917f30a41210531 [file] [log] [blame]
William Kurkianea869482019-04-09 15:16:11 -04001/*
2 * Copyright 2018-present Open Networking Foundation
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 kvstore
17
serkant.uluderya7b8211e2021-02-24 16:39:18 +030018import (
19 "bytes"
20 "fmt"
21)
William Kurkianea869482019-04-09 15:16:11 -040022
23// ToString converts an interface value to a string. The interface should either be of
24// a string type or []byte. Otherwise, an error is returned.
25func ToString(value interface{}) (string, error) {
26 switch t := value.(type) {
27 case []byte:
28 return string(value.([]byte)), nil
29 case string:
30 return value.(string), nil
31 default:
32 return "", fmt.Errorf("unexpected-type-%T", t)
33 }
34}
35
36// ToByte converts an interface value to a []byte. The interface should either be of
37// a string type or []byte. Otherwise, an error is returned.
38func ToByte(value interface{}) ([]byte, error) {
39 switch t := value.(type) {
40 case []byte:
41 return value.([]byte), nil
42 case string:
43 return []byte(value.(string)), nil
44 default:
45 return nil, fmt.Errorf("unexpected-type-%T", t)
46 }
47}
serkant.uluderya7b8211e2021-02-24 16:39:18 +030048
49// Helper function to verify mostly whether the content of two interface types are the same. Focus is []byte and
50// string types
51func isEqual(val1 interface{}, val2 interface{}) bool {
52 b1, err := ToByte(val1)
53 b2, er := ToByte(val2)
54 if err == nil && er == nil {
55 return bytes.Equal(b1, b2)
56 }
57 return val1 == val2
58}