001/*
002 * Copyright 2021 Global Biodiversity Information Facility (GBIF)
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.gbif.utils.collection;
017
018import java.lang.reflect.Array;
019
020public class ArrayUtils {
021
022  public static <T> T[] arrayMerge(T[]... arrays) {
023    // Determine required size of new array
024    int count = 0;
025    for (T[] array : arrays) {
026      count += array.length;
027    }
028
029    // create new array of required class
030    T[] mergedArray = (T[]) Array.newInstance(arrays[0][0].getClass(), count);
031
032    // Merge each array into new array
033    int start = 0;
034    for (T[] array : arrays) {
035      System.arraycopy(array, 0, mergedArray, start, array.length);
036      start += array.length;
037    }
038    return mergedArray;
039  }
040
041  public static byte[] arrayMerge(byte[]... arrays) {
042    // Determine required size of new array
043    int count = 0;
044    for (byte[] array : arrays) {
045      count += array.length;
046    }
047
048    // create new array of required class
049    byte[] mergedArray = new byte[count];
050
051    // Merge each array into new array
052    int start = 0;
053    for (byte[] array : arrays) {
054      System.arraycopy(array, 0, mergedArray, start, array.length);
055      start += array.length;
056    }
057    return mergedArray;
058  }
059
060  public static byte[] intToByteArray(int value) {
061    byte[] b = new byte[4];
062    for (int i = 0; i < 4; i++) {
063      int offset = (b.length - 1 - i) * 8;
064      b[i] = (byte) ((value >>> offset) & 0xFF);
065    }
066    return b;
067  }
068
069  public static int byteArrayToInt(byte[] b) {
070    return (b[0] << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8) + (b[3] & 0xFF);
071  }
072
073  private ArrayUtils() {
074    throw new UnsupportedOperationException("Can't initialize class");
075  }
076}