2 * Copyright (c) 2016 Cisco and/or its affiliates.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package io.fd.hc2vpp.common.translate.util;
19 import javax.annotation.Nonnull;
20 import javax.annotation.Nullable;
23 * Trait providing logic for working with binary-based data
25 public interface ByteDataTranslator {
27 ByteDataTranslator INSTANCE = new ByteDataTranslator() {
34 * Returns 0 if argument is null or false, 1 otherwise.
36 * @param value Boolean value to be converted
37 * @return byte value equal to 0 or 1
39 default byte booleanToByte(@Nullable final Boolean value) {
40 return value != null && value
46 * Converts int to byte
48 default byte toByte(final int value) {
49 return Integer.valueOf(value).byteValue();
53 * Converts short to byte
55 default byte toByte(final short value) {
56 return Short.valueOf(value).byteValue();
60 * Returns Boolean.TRUE if argument is 0, Boolean.FALSE otherwise.
62 * @param value byte value to be converted
63 * @return Boolean value
64 * @throws IllegalArgumentException if argument is neither 0 nor 1
67 default Boolean byteToBoolean(final byte value) {
68 if (value == BYTE_FALSE) {
70 } else if (value == BYTE_TRUE) {
73 throw new IllegalArgumentException(String.format("0 or 1 was expected but was %d", value));
77 * Reverses bytes in the byte array
79 * @param bytes input array
80 * @return reversed array
82 default byte[] reverseBytes(final byte[] bytes) {
83 final byte[] reversed = new byte[bytes.length];
85 for (byte aByte : bytes) {
86 reversed[bytes.length - i++] = aByte;
93 * Return (interned) string from byte array while removing \u0000. Strings represented as fixed length byte[] from
96 default String toString(final byte[] cString) {
97 return new String(cString).replaceAll("\\u0000", "").intern();
101 * Converts signed byte(filled with unsigned value from vpp) to java integer
103 * For example unsigned C byte 128 is converted by jvpp to -128, this will return 128
105 default int toJavaByte(final byte vppByte) {
106 return Byte.toUnsignedInt(vppByte);