1 /* 2 * Copyright (C) 2022 The Android Open Source Project 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 com.android.net.module.util; 18 19 import android.annotation.NonNull; 20 21 /** 22 * Byte utility functions. 23 * @hide 24 */ 25 public class ByteUtils { 26 /** 27 * Returns the index of the first appearance of the value {@code target} in {@code array}. 28 * 29 * @param array an array of {@code byte} values, possibly empty 30 * @param target a primitive {@code byte} value 31 * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no 32 * such index exists. 33 */ indexOf(@onNull byte[] array, byte target)34 public static int indexOf(@NonNull byte[] array, byte target) { 35 return indexOf(array, target, 0, array.length); 36 } 37 indexOf(byte[] array, byte target, int start, int end)38 private static int indexOf(byte[] array, byte target, int start, int end) { 39 for (int i = start; i < end; i++) { 40 if (array[i] == target) { 41 return i; 42 } 43 } 44 return -1; 45 } 46 47 /** 48 * Returns the values from each provided array combined into a single array. For example, {@code 49 * concat(new byte[] {a, b}, new byte[] {}, new byte[] {c}} returns the array {@code {a, b, c}}. 50 * 51 * @param arrays zero or more {@code byte} arrays 52 * @return a single array containing all the values from the source arrays, in order 53 */ concat(@onNull byte[]... arrays)54 public static byte[] concat(@NonNull byte[]... arrays) { 55 int length = 0; 56 for (byte[] array : arrays) { 57 length += array.length; 58 } 59 byte[] result = new byte[length]; 60 int pos = 0; 61 for (byte[] array : arrays) { 62 System.arraycopy(array, 0, result, pos, array.length); 63 pos += array.length; 64 } 65 return result; 66 } 67 } 68