1/*
2 * Copyright (C) 2018 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 android.util;
17
18/**
19 * A sparse array of ArraySets, which is suitable to hold userid->packages association.
20 *
21 * @hide
22 */
23public class SparseSetArray<T> {
24    private final SparseArray<ArraySet<T>> mData = new SparseArray<>();
25
26    public SparseSetArray() {
27    }
28
29    /**
30     * Add a value at index n.
31     * @return FALSE when the value already existed at the given index, TRUE otherwise.
32     */
33    public boolean add(int n, T value) {
34        ArraySet<T> set = mData.get(n);
35        if (set == null) {
36            set = new ArraySet<>();
37            mData.put(n, set);
38        }
39        if (set.contains(value)) {
40            return true;
41        }
42        set.add(value);
43        return false;
44    }
45
46    /**
47     * @return whether a value exists at index n.
48     */
49    public boolean contains(int n, T value) {
50        final ArraySet<T> set = mData.get(n);
51        if (set == null) {
52            return false;
53        }
54        return set.contains(value);
55    }
56
57    /**
58     * Remove a value from index n.
59     * @return TRUE when the value existed at the given index and removed, FALSE otherwise.
60     */
61    public boolean remove(int n, T value) {
62        final ArraySet<T> set = mData.get(n);
63        if (set == null) {
64            return false;
65        }
66        final boolean ret = set.remove(value);
67        if (set.size() == 0) {
68            mData.remove(n);
69        }
70        return ret;
71    }
72
73    /**
74     * Remove all values from index n.
75     */
76    public void remove(int n) {
77        mData.remove(n);
78    }
79    public int size() {
80        return mData.size();
81    }
82
83    public int keyAt(int index) {
84        return mData.keyAt(index);
85    }
86
87    public int sizeAt(int index) {
88        final ArraySet<T> set = mData.valueAt(index);
89        if (set == null) {
90            return 0;
91        }
92        return set.size();
93    }
94
95    public T valueAt(int intIndex, int valueIndex) {
96        return mData.valueAt(intIndex).valueAt(valueIndex);
97    }
98}
99