RICPLT-2910
[ric-plt/submgr.git] / e2ap / pkg / conv / bcd.go
1 /*
2 ==================================================================================
3   Copyright (c) 2019 AT&T Intellectual Property.
4   Copyright (c) 2019 Nokia
5
6    Licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8    You may obtain a copy of the License at
9
10        http://www.apache.org/licenses/LICENSE-2.0
11
12    Unless required by applicable law or agreed to in writing, software
13    distributed under the License is distributed on an "AS IS" BASIS,
14    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15    See the License for the specific language governing permissions and
16    limitations under the License.
17 ==================================================================================
18 */
19
20 package conv
21
22 type Bcd struct {
23         ConvTbl string
24 }
25
26 func NewBcd(convTbl string) *Bcd {
27         b := &Bcd{}
28         b.ConvTbl = convTbl
29         return b
30 }
31
32 func (bcd *Bcd) index(c byte) int {
33         for cpos, cchar := range bcd.ConvTbl {
34                 if cchar == rune(c) {
35                         return cpos
36                 }
37         }
38         return -1
39 }
40
41 func (bcd *Bcd) byte(i int) byte {
42         if i < 0 && i > 15 {
43                 return '?'
44         }
45         return bcd.ConvTbl[i]
46 }
47
48 func (bcd *Bcd) Encode(str string) []byte {
49         buf := make([]byte, len(str)/2+len(str)%2)
50         for i := 0; i < len(str); i++ {
51                 var schar int = bcd.index(str[i])
52                 if schar < 0 {
53                         return nil
54                 }
55                 if i%2 > 0 {
56                         buf[i/2] &= 0x0f
57                         buf[i/2] |= (uint8)(schar) << 4
58                 } else {
59                         buf[i/2] = 0xf0 | ((uint8)(schar) & 0x0f)
60                 }
61         }
62         return buf
63 }
64
65 func (bcd *Bcd) Decode(buf []byte) string {
66         var strbytes []byte
67         for i := 0; i < len(buf); i++ {
68                 var b byte
69                 b = bcd.byte(int(buf[i] & 0x0f))
70                 //if b == '?' {
71                 //      return ""
72                 //}
73                 strbytes = append(strbytes, b)
74
75                 b = bcd.byte(int(buf[i] >> 4))
76                 //if b == '?' {
77                 //      return ""
78                 //}
79                 strbytes = append(strbytes, b)
80         }
81         return string(strbytes)
82 }