1/*
2 * Copyright (C) 2017 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 */
16package androidx.slice;
17
18
19import androidx.annotation.RestrictTo;
20import androidx.annotation.RestrictTo.Scope;
21import androidx.core.util.ObjectsCompat;
22
23import java.lang.reflect.Array;
24
25/**
26 * @hide
27 */
28@RestrictTo(Scope.LIBRARY)
29class ArrayUtils {
30
31    public static <T> boolean contains(T[] array, T item) {
32        for (T t : array) {
33            if (ObjectsCompat.equals(t, item)) {
34                return true;
35            }
36        }
37        return false;
38    }
39
40    public static <T> T[] appendElement(Class<T> kind, T[] array, T element) {
41        final T[] result;
42        final int end;
43        if (array != null) {
44            end = array.length;
45            result = (T[]) Array.newInstance(kind, end + 1);
46            System.arraycopy(array, 0, result, 0, end);
47        } else {
48            end = 0;
49            result = (T[]) Array.newInstance(kind, 1);
50        }
51        result[end] = element;
52        return result;
53    }
54
55    public static <T> T[] removeElement(Class<T> kind, T[] array, T element) {
56        if (array != null) {
57            if (!contains(array, element)) {
58                return array;
59            }
60            final int length = array.length;
61            for (int i = 0; i < length; i++) {
62                if (ObjectsCompat.equals(array[i], element)) {
63                    if (length == 1) {
64                        return null;
65                    }
66                    T[] result = (T[]) Array.newInstance(kind, length - 1);
67                    System.arraycopy(array, 0, result, 0, i);
68                    System.arraycopy(array, i + 1, result, i, length - i - 1);
69                    return result;
70                }
71            }
72        }
73        return array;
74    }
75
76    private ArrayUtils() {
77    }
78}
79