aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/gregtech/api/util/extensions/ArrayExt.java
blob: b6ebb07d38b398fde33e98b5eb437b3c479d4f32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package gregtech.api.util.extensions;

import java.util.function.IntFunction;

public class ArrayExt {

    public static int[] of(int... objects) {
        return objects;
    }

    public static float[] of(float... objects) {
        return objects;
    }

    public static double[] of(double... objects) {
        return objects;
    }

    public static char[] of(char... objects) {
        return objects;
    }

    public static byte[] of(byte... objects) {
        return objects;
    }

    public static long[] of(long... objects) {
        return objects;
    }

    @SafeVarargs
    public static <T> T[] of(T... objects) {
        return objects;
    }

    @SuppressWarnings("ForLoopReplaceableByForEach")
    public static <T> T[] withoutNulls(T[] array, IntFunction<T[]> arrayFactory) {
        int count = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i] != null) {
                count++;
            }
        }

        T[] newArr = arrayFactory.apply(count);
        if (count == 0) return newArr;

        int j = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i] != null) {
                newArr[j] = array[i];
                j++;
            }
        }

        return newArr;
    }

    public static <T> T[] withoutTrailingNulls(T[] array, IntFunction<T[]> arrayFactory) {
        int firstNull = -1;
        for (int i = array.length - 1; i >= 0; i--) {
            if (array[i] == null) {
                firstNull = i;
            } else {
                break;
            }
        }

        if (firstNull == -1) {
            T[] newArray = arrayFactory.apply(array.length);
            System.arraycopy(array, 0, newArray, 0, array.length);
            return newArray;
        } else if (firstNull == 0) {
            return arrayFactory.apply(0);
        } else {
            T[] newArray = arrayFactory.apply(firstNull);
            System.arraycopy(array, 0, newArray, 0, firstNull);
            return newArray;
        }
    }
}