blob: 32eeed8db622e285546cce17f0a8f6738d1d3413 [file] [log] [blame]
Girish Gowdra041dcb32020-11-16 16:54:30 -08001/*
2 * Copyright 2020-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 */
16
17//Package adaptercoreonu provides the utility for onu devices, flows and statistics
18package adaptercoreonu
19
20import (
ozgecanetsia4b232302020-11-11 10:58:10 +030021 "encoding/binary"
Girish Gowdra041dcb32020-11-16 16:54:30 -080022 "errors"
ozgecanetsia4b232302020-11-11 10:58:10 +030023 "net"
Girish Gowdra041dcb32020-11-16 16:54:30 -080024 "regexp"
25 "strconv"
26 "strings"
27)
28
29// GetTpIDFromTpPath extracts TpID from the TpPath.
30// On success it returns a valid TpID and nil error.
31// On failure it returns TpID as 0 and the error.
32func GetTpIDFromTpPath(tpPath string) (uint8, error) {
33 // tpPath is of the format <technology>/<table_id>/olt-{}/pon-{}/onu-{}/uni-{}
34 // A sample tpPath is ==> XGS-PON/64/olt-{12345abcd}/pon-{0}/onu-{1}/uni-{1}
35 var tpPathFormat = regexp.MustCompile(`^[a-zA-Z\-_]+/[0-9]+/olt-{[a-z0-9\-]+}/pon-{[0-9]+}/onu-{[0-9]+}/uni-{[0-9]+}$`)
36
37 // Ensure tpPath is of the format <technology>/<table_id>/<uni_port_name>
38 if !tpPathFormat.Match([]byte(tpPath)) {
39 return 0, errors.New("tp-path-not-confirming-to-format")
40 }
41 // Extract the TP table-id field.
42 tpID, err := strconv.Atoi(strings.Split(tpPath, "/")[1])
43 // Atoi returns uint64 and need to be type-casted to uint8 as tpID is uint8 size.
44 return uint8(tpID), err
45}
ozgecanetsia4b232302020-11-11 10:58:10 +030046
47//IPToInt32 transforms an IP of net.Ip type to int32
48func IPToInt32(ip net.IP) uint32 {
49 if len(ip) == 16 {
50 return binary.BigEndian.Uint32(ip[12:16])
51 }
52 return binary.BigEndian.Uint32(ip)
53}
ozgecanetsiab5000ef2020-11-27 14:38:20 +030054
55//AsByteSlice transforms a string of manually set bits to a byt array
56func AsByteSlice(bitString string) []byte {
57 var out []byte
58 var str string
59
60 for i := len(bitString); i > 0; i -= 8 {
61 if i-8 < 0 {
62 str = bitString[0:i]
63 } else {
64 str = bitString[i-8 : i]
65 }
66 v, err := strconv.ParseUint(str, 2, 8)
67 if err != nil {
68 panic(err)
69 }
70 out = append([]byte{byte(v)}, out...)
71 }
72 return out
73}