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  */
16 package com.android.launcher3.util;
17 
18 import java.util.Arrays;
19 
20 /**
21  * A wrapper over IntArray implementing a growing set of int primitives.
22  */
23 public class IntSet {
24 
25     final IntArray mArray = new IntArray();
26 
27     /**
28      * Appends the specified value to the set if it does not exist.
29      */
add(int value)30     public void add(int value) {
31         int index = Arrays.binarySearch(mArray.mValues, 0, mArray.mSize, value);
32         if (index < 0) {
33             mArray.add(-index - 1, value);
34         }
35     }
36 
contains(int value)37     public boolean contains(int value) {
38         return Arrays.binarySearch(mArray.mValues, 0, mArray.mSize, value) >= 0;
39     }
40 
isEmpty()41     public boolean isEmpty() {
42         return mArray.isEmpty();
43     }
44 
45     /**
46      * Returns the number of values in this set.
47      */
size()48     public int size() {
49         return mArray.size();
50     }
51 
clear()52     public void clear() {
53         mArray.clear();
54     }
55 
56     @Override
equals(Object obj)57     public boolean equals(Object obj) {
58         if (obj == this) {
59             return true;
60         }
61         return (obj instanceof IntSet) && ((IntSet) obj).mArray.equals(mArray);
62     }
63 
getArray()64     public IntArray getArray() {
65         return mArray;
66     }
67 
68     /**
69      * Sets this set to be same as {@param other}
70      */
copyFrom(IntSet other)71     public void copyFrom(IntSet other) {
72         mArray.copyFrom(other.mArray);
73     }
74 
wrap(IntArray array)75     public static IntSet wrap(IntArray array) {
76         IntSet set = new IntSet();
77         set.mArray.addAll(array);
78         Arrays.sort(set.mArray.mValues, 0, set.mArray.mSize);
79         return set;
80     }
81 }
82