HONEYCOMB-58 - Routing Api
[honeycomb.git] / vpp-common / vpp-translate-utils / src / main / java / io / fd / honeycomb / translate / vpp / util / ByteDataTranslator.java
1 /*
2  * Copyright (c) 2016 Cisco and/or its affiliates.
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 io.fd.honeycomb.translate.vpp.util;
18
19 import javax.annotation.Nonnull;
20 import javax.annotation.Nullable;
21
22 /**
23  * Trait providing logic for working with binary-based data
24  */
25 public interface ByteDataTranslator {
26
27     /**
28      * Returns 0 if argument is null or false, 1 otherwise.
29      *
30      * @param value Boolean value to be converted
31      * @return byte value equal to 0 or 1
32      */
33     default byte booleanToByte(@Nullable final Boolean value) {
34         return value != null && value
35                 ? (byte) 1
36                 : (byte) 0;
37     }
38
39     /**
40      * Returns Boolean.TRUE if argument is 0, Boolean.FALSE otherwise.
41      *
42      * @param value byte value to be converted
43      * @return Boolean value
44      * @throws IllegalArgumentException if argument is neither 0 nor 1
45      */
46     @Nonnull
47     default Boolean byteToBoolean(final byte value) {
48         if (value == 0) {
49             return Boolean.FALSE;
50         } else if (value == 1) {
51             return Boolean.TRUE;
52         }
53         throw new IllegalArgumentException(String.format("0 or 1 was expected but was %d", value));
54     }
55
56     /**
57      * Reverses bytes in the byte array
58      *
59      * @param bytes input array
60      * @return reversed array
61      */
62     default byte[] reverseBytes(final byte[] bytes) {
63         final byte[] reversed = new byte[bytes.length];
64         int i = 1;
65         for (byte aByte : bytes) {
66             reversed[bytes.length - i++] = aByte;
67         }
68
69         return reversed;
70     }
71
72     /**
73      * Return (interned) string from byte array while removing \u0000. Strings represented as fixed length byte[] from
74      * vpp contain \u0000.
75      */
76     default String toString(final byte[] cString) {
77         return new String(cString).replaceAll("\\u0000", "").intern();
78     }
79 }