repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/BitVectorBase.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.io.Serializable;
import java.util.Arrays;
/** Abstract base class for implementations of bitvectors */
@SuppressWarnings("rawtypes")
public abstract class BitVectorBase<T extends BitVectorBase> implements Cloneable, Serializable {
private static final long serialVersionUID = 1151811022797406841L;
protected static final boolean DEBUG = false;
protected static final int LOG_BITS_PER_UNIT = 5;
protected static final int BITS_PER_UNIT = 32;
protected static final int MASK = 0xffffffff;
protected static final int LOW_MASK = 0x1f;
@SuppressWarnings("NullAway.Init")
protected int bits[];
public abstract void set(int bit);
public abstract void clear(int bit);
public abstract boolean get(int bit);
public abstract int length();
public abstract void and(T other);
public abstract void andNot(T other);
public abstract void or(T other);
public abstract void xor(T other);
public abstract boolean sameBits(T other);
public abstract boolean isSubset(T other);
public abstract boolean intersectionEmpty(T other);
/** Convert bitIndex to a subscript into the bits[] array. */
public static int subscript(int bitIndex) {
return bitIndex >> LOG_BITS_PER_UNIT;
}
/** Clears all bits. */
public final void clearAll() {
Arrays.fill(bits, 0);
}
@Override
public int hashCode() {
int h = 1234;
for (int i = bits.length - 1; i >= 0; ) {
h ^= bits[i] * (i + 1);
i--;
}
return h;
}
/** How many bits are set? */
public final int populationCount() {
int count = 0;
for (int bit : bits) {
count += Bits.populationCount(bit);
}
return count;
}
public boolean isZero() {
int setLength = bits.length;
for (int i = setLength - 1; i >= 0; ) {
if (bits[i] != 0) return false;
i--;
}
return true;
}
@Override
@SuppressWarnings("unchecked")
public Object clone() {
BitVectorBase<T> result = null;
try {
result = (BitVectorBase<T>) super.clone();
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
result.bits = new int[bits.length];
System.arraycopy(bits, 0, result.bits, 0, result.bits.length);
return result;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
boolean needSeparator = false;
buffer.append('{');
int limit = length();
for (int i = 0; i < limit; i++) {
if (get(i)) {
if (needSeparator) {
buffer.append(", ");
} else {
needSeparator = true;
}
buffer.append(i);
}
}
buffer.append('}');
return buffer.toString();
}
/** @see com.ibm.wala.util.intset.IntSet#contains(int) */
public boolean contains(int i) {
return get(i);
}
private static final int[][] masks =
new int[][] {
{0xFFFF0000},
{0xFF000000, 0x0000FF00},
{0xF0000000, 0x00F00000, 0x0000F000, 0x000000F0},
{
0xC0000000,
0x0C000000,
0x00C00000,
0x000C0000,
0x0000C000,
0x00000C00,
0x000000C0,
0x0000000C
},
{
0x80000000,
0x20000000,
0x08000000,
0x02000000,
0x00800000,
0x00200000,
0x00080000,
0x00020000,
0x00008000,
0x00002000,
0x00000800,
0x00000200,
0x00000080,
0x00000020,
0x00000008,
0x00000002
}
};
public int max() {
int lastWord = bits.length - 1;
while (lastWord >= 0 && bits[lastWord] == 0) lastWord--;
if (lastWord < 0) return -1;
int count = lastWord * BITS_PER_UNIT;
int top = bits[lastWord];
int j = 0;
for (int[] mask2 : masks) {
if ((top & mask2[j]) != 0) {
j <<= 1;
} else {
j <<= 1;
j++;
}
}
return count + (31 - j);
}
/** @return min j >= start s.t get(j) */
public int nextSetBit(int start) {
if (start < 0) {
throw new IllegalArgumentException("illegal start: " + start);
}
int word = subscript(start);
int bit = (1 << (start & LOW_MASK));
while (word < bits.length) {
if (bits[word] != 0) {
do {
if ((bits[word] & bit) != 0) return start;
bit <<= 1;
start++;
} while (bit != 0);
} else {
start += (BITS_PER_UNIT - (start & LOW_MASK));
}
word++;
bit = 1;
}
return -1;
}
/**
* Copies the values of the bits in the specified set into this set.
*
* @param set the bit set to copy the bits from
* @throws IllegalArgumentException if set is null
*/
public void copyBits(BitVectorBase set) {
if (set == null) {
throw new IllegalArgumentException("set is null");
}
int setLength = set.bits.length;
bits = new int[setLength];
for (int i = setLength - 1; i >= 0; ) {
bits[i] = set.bits[i];
i--;
}
}
}
| 5,518
| 22.28692
| 97
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/BitVectorIntSet.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/**
* A {@link BitVector} implementation of {@link MutableIntSet}.
*
* <p>Note that this is NOT a value with regard to hashCode and equals.
*/
public final class BitVectorIntSet implements MutableIntSet {
private static final long serialVersionUID = 7477243071826223843L;
// population count of -1 means needs to be computed again.
private int populationCount = 0;
private static final int UNDEFINED = -1;
private BitVector bitVector = new BitVector(0);
public BitVectorIntSet() {}
public BitVectorIntSet(BitVector v) {
if (v == null) {
throw new IllegalArgumentException("null v");
}
bitVector.or(v);
populationCount = UNDEFINED;
}
public BitVectorIntSet(@Nullable IntSet S) throws IllegalArgumentException {
if (S == null) {
throw new IllegalArgumentException("S == null");
}
copySet(S);
}
@Override
public void clear() {
bitVector.clearAll();
populationCount = 0;
}
@Override
public void copySet(IntSet set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (set instanceof BitVectorIntSet) {
BitVectorIntSet S = (BitVectorIntSet) set;
bitVector = new BitVector(S.bitVector);
populationCount = S.populationCount;
} else if (set instanceof MutableSharedBitVectorIntSet) {
BitVectorIntSet S = ((MutableSharedBitVectorIntSet) set).makeDenseCopy();
bitVector = new BitVector(S.bitVector);
populationCount = S.populationCount;
} else if (set instanceof SparseIntSet) {
SparseIntSet s = (SparseIntSet) set;
if (s.size == 0) {
populationCount = 0;
bitVector = new BitVector(0);
} else {
bitVector = new BitVector(s.max());
populationCount = s.size;
for (int i = 0; i < s.size; i++) {
bitVector.set(s.elements[i]);
}
}
} else if (set instanceof BimodalMutableIntSet) {
IntSet backing = ((BimodalMutableIntSet) set).getBackingStore();
copySet(backing);
} else {
bitVector.clearAll();
populationCount = set.size();
for (IntIterator it = set.intIterator(); it.hasNext(); ) {
bitVector.set(it.next());
}
}
}
@Override
public boolean addAll(@Nullable IntSet set) {
if (set instanceof BitVectorIntSet) {
BitVector B = ((BitVectorIntSet) set).bitVector;
int delta = bitVector.orWithDelta(B);
populationCount += delta;
populationCount = (populationCount == (delta + UNDEFINED)) ? UNDEFINED : populationCount;
return (delta != 0);
} else {
BitVectorIntSet other = new BitVectorIntSet(set);
return addAll(other);
}
}
/**
* this version of add all will likely be faster if the client doesn't care about the change or
* the population count.
*
* @throws IllegalArgumentException if set == null
*/
public void addAllOblivious(IntSet set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (set instanceof BitVectorIntSet) {
BitVector B = ((BitVectorIntSet) set).bitVector;
bitVector.or(B);
populationCount = UNDEFINED;
} else {
BitVectorIntSet other = new BitVectorIntSet(set);
addAllOblivious(other);
}
}
@Override
public boolean add(int i) {
if (bitVector.get(i)) {
return false;
} else {
bitVector.set(i);
populationCount++;
populationCount = (populationCount == (UNDEFINED + 1)) ? UNDEFINED : populationCount;
return true;
}
}
@Override
public boolean remove(int i) {
if (contains(i)) {
populationCount--;
populationCount = (populationCount == UNDEFINED - 1) ? UNDEFINED : populationCount;
bitVector.clear(i);
return true;
} else {
return false;
}
}
@Override
public void intersectWith(IntSet set) {
if (!(set instanceof BitVectorIntSet)) {
set = new BitVectorIntSet(set);
}
BitVector B = ((BitVectorIntSet) set).bitVector;
bitVector.and(B);
populationCount = UNDEFINED;
}
/** @see com.ibm.wala.util.intset.IntSet#intersection(com.ibm.wala.util.intset.IntSet) */
@Override
public BitVectorIntSet intersection(IntSet that) {
BitVectorIntSet newbie = new BitVectorIntSet();
newbie.copySet(this);
newbie.intersectWith(that);
return newbie;
}
/** @see com.ibm.wala.util.intset.IntSet#union(com.ibm.wala.util.intset.IntSet) */
@Override
public IntSet union(IntSet that) {
BitVectorIntSet temp = new BitVectorIntSet();
temp.addAll(this);
temp.addAll(that);
return temp;
}
/** @see com.ibm.wala.util.intset.IntSet#isEmpty() */
@Override
public boolean isEmpty() {
return size() == 0;
}
/** @see com.ibm.wala.util.intset.IntSet#size() */
@Override
public int size() {
populationCount =
(populationCount == UNDEFINED) ? bitVector.populationCount() : populationCount;
return populationCount;
}
/** Use with extreme care; doesn't detect ConcurrentModificationExceptions */
@Override
public IntIterator intIterator() {
populationCount =
(populationCount == UNDEFINED) ? bitVector.populationCount() : populationCount;
return new IntIterator() {
int count = 0;
int last = 0;
@Override
public boolean hasNext() {
assert populationCount == bitVector.populationCount();
return count < populationCount;
}
@Override
public int next() {
count++;
last = nextSetBit(last) + 1;
return last - 1;
}
};
}
/** @see com.ibm.wala.util.intset.IntSet#foreach(com.ibm.wala.util.intset.IntSetAction) */
@Override
public void foreach(IntSetAction action) {
if (action == null) {
throw new IllegalArgumentException("null action");
}
int nextBit = bitVector.nextSetBit(0);
populationCount =
(populationCount == UNDEFINED) ? bitVector.populationCount() : populationCount;
for (int i = 0; i < populationCount; i++) {
action.act(nextBit);
nextBit = bitVector.nextSetBit(nextBit + 1);
}
}
public SparseIntSet makeSparseCopy() {
populationCount =
(populationCount == UNDEFINED) ? bitVector.populationCount() : populationCount;
int[] elements = new int[populationCount];
int i = 0;
int nextBit = -1;
while (i < populationCount) elements[i++] = nextBit = bitVector.nextSetBit(nextBit + 1);
return new SparseIntSet(elements);
}
/** @see com.ibm.wala.util.intset.IntSet#foreach(com.ibm.wala.util.intset.IntSetAction) */
@Override
public void foreachExcluding(IntSet X, IntSetAction action) {
if (X instanceof BitVectorIntSet) {
fastForeachExcluding((BitVectorIntSet) X, action);
} else {
slowForeachExcluding(X, action);
}
}
private void slowForeachExcluding(IntSet X, IntSetAction action) {
populationCount =
(populationCount == UNDEFINED) ? bitVector.populationCount() : populationCount;
for (int i = 0, count = 0; count < populationCount; i++) {
if (contains(i)) {
if (!X.contains(i)) {
action.act(i);
}
count++;
}
}
}
/** internal optimized form */
private void fastForeachExcluding(BitVectorIntSet X, IntSetAction action) {
int[] bits = bitVector.bits;
int[] xbits = X.bitVector.bits;
int w = 0;
while (w < xbits.length && w < bits.length) {
int b = bits[w] & ~xbits[w];
actOnWord(action, w << 5, b);
w++;
}
while (w < bits.length) {
actOnWord(action, w << 5, bits[w]);
w++;
}
}
private static void actOnWord(IntSetAction action, int startingIndex, int word) {
if (word != 0) {
if ((word & 0x1) != 0) {
action.act(startingIndex);
}
for (int i = 0; i < 31; i++) {
startingIndex++;
word >>>= 1;
if ((word & 0x1) != 0) {
action.act(startingIndex);
}
}
}
}
@Override
public boolean contains(int i) {
if (i < 0) {
throw new IllegalArgumentException("invalid i: " + i);
}
return bitVector.get(i);
}
@Override
public int max() {
return bitVector.max();
}
@Override
public String toString() {
return bitVector.toString();
}
/** @return min j >= n s.t get(j) */
public int nextSetBit(int n) {
return bitVector.nextSetBit(n);
}
/** @see com.ibm.wala.util.intset.IntSet#sameValue(com.ibm.wala.util.intset.IntSet) */
@Override
public boolean sameValue(@Nullable IntSet that)
throws IllegalArgumentException, UnimplementedError {
if (that == null) {
throw new IllegalArgumentException("that == null");
}
if (that instanceof BitVectorIntSet) {
BitVectorIntSet b = (BitVectorIntSet) that;
return bitVector.sameBits(b.bitVector);
} else if (that instanceof BimodalMutableIntSet) {
return that.sameValue(this);
} else if (that instanceof SparseIntSet) {
return sameValueInternal((SparseIntSet) that);
} else if (that instanceof MutableSharedBitVectorIntSet) {
return sameValue(((MutableSharedBitVectorIntSet) that).makeDenseCopy());
} else {
Assertions.UNREACHABLE("unexpected argument type " + that.getClass());
return false;
}
}
/** */
private boolean sameValueInternal(SparseIntSet that) {
populationCount =
(populationCount == UNDEFINED) ? bitVector.populationCount() : populationCount;
if (populationCount != that.size()) {
return false;
}
for (int i = 0; i < that.size(); i++) {
int val = that.elementAt(i);
if (!bitVector.contains(val)) {
return false;
}
}
return true;
}
/** @see com.ibm.wala.util.intset.IntSet#isSubset(com.ibm.wala.util.intset.IntSet) */
@NullUnmarked
@Override
public boolean isSubset(@Nullable IntSet that) {
if (that instanceof BitVectorIntSet) {
return bitVector.isSubset(((BitVectorIntSet) that).bitVector);
} else if (that instanceof SparseIntSet) {
return isSubsetInternal((SparseIntSet) that);
} else {
// really slow. optimize as needed.
for (IntIterator it = intIterator(); it.hasNext(); ) {
int x = it.next();
if (!that.contains(x)) {
return false;
}
}
return true;
}
}
private boolean isSubsetInternal(SparseIntSet set) {
return toSparseIntSet().isSubset(set);
}
public BitVector getBitVector() {
return bitVector;
}
/** TODO: optimize */
public SparseIntSet toSparseIntSet() {
MutableSparseIntSet result = MutableSparseIntSet.makeEmpty();
for (IntIterator it = intIterator(); it.hasNext(); ) {
result.add(it.next());
}
return result;
}
/** @throws IllegalArgumentException if set is null */
public boolean removeAll(BitVectorIntSet set) {
if (set == null) {
throw new IllegalArgumentException("set is null");
}
int oldSize = size();
bitVector.andNot(set.bitVector);
populationCount = UNDEFINED;
return oldSize > size();
}
/** @see com.ibm.wala.util.intset.IntSet#containsAny(com.ibm.wala.util.intset.IntSet) */
@Override
public boolean containsAny(IntSet set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (set instanceof BitVectorIntSet) {
BitVectorIntSet b = (BitVectorIntSet) set;
return !bitVector.intersectionEmpty(b.bitVector);
} else {
// TODO: optimize
for (IntIterator it = set.intIterator(); it.hasNext(); ) {
if (contains(it.next())) {
return true;
}
}
return false;
}
}
@Override
public boolean addAllInIntersection(IntSet other, IntSet filter) throws IllegalArgumentException {
if (other == null) {
throw new IllegalArgumentException("other == null");
}
BitVectorIntSet o = new BitVectorIntSet(other);
o.intersectWith(filter);
return addAll(o);
}
public boolean containsAll(BitVectorIntSet other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
return other.isSubset(this);
}
}
| 12,850
| 27.749441
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/BitVectorIntSetFactory.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.util.TreeSet;
/** */
public class BitVectorIntSetFactory implements MutableIntSetFactory<BitVectorIntSet> {
/** @throws IllegalArgumentException if set is null */
@Override
public BitVectorIntSet make(int[] set) {
if (set == null) {
throw new IllegalArgumentException("set is null");
}
if (set.length == 0) {
return new BitVectorIntSet();
} else {
// XXX not very efficient.
TreeSet<Integer> T = new TreeSet<>();
for (int element : set) {
T.add(element);
}
BitVectorIntSet result = new BitVectorIntSet();
for (Integer I : T) {
result.add(I);
}
return result;
}
}
@Override
public BitVectorIntSet parse(String string) throws NumberFormatException {
int[] data = SparseIntSet.parseIntArray(string);
BitVectorIntSet result = new BitVectorIntSet();
for (int element : data) {
result.add(element);
}
return result;
}
@Override
public BitVectorIntSet makeCopy(IntSet x) throws IllegalArgumentException {
if (x == null) {
throw new IllegalArgumentException("x == null");
}
return new BitVectorIntSet(x);
}
@Override
public BitVectorIntSet make() {
return new BitVectorIntSet();
}
}
| 1,672
| 25.555556
| 86
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/BitVectorRepository.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.collections.HashMapFactory;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
/** A repository for shared bit vectors as described by Heintze */
@SuppressWarnings("Java8MapApi")
public class BitVectorRepository {
private static final boolean STATS = false;
private static final int STATS_WINDOW = 100;
private static int queries = 0;
private static int hits = 0;
private static final int SUBSET_DELTA = 5;
private static final Map<Integer, LinkedList<WeakReference<BitVectorIntSet>>> buckets =
HashMapFactory.make();
/**
* @return the BitVector in this repository which is the canonical shared subset representative of
* value; the result will have the same bits as value, except it may exclude up to
* SUBSET_DELTA bits.
* @throws IllegalArgumentException if value is null
*/
public static synchronized BitVectorIntSet findOrCreateSharedSubset(BitVectorIntSet value) {
if (value == null) {
throw new IllegalArgumentException("value is null");
}
if (STATS) {
queries++;
if (queries % STATS_WINDOW == 0) {
reportStats();
}
}
int size = value.size();
for (int i = size; i > size - SUBSET_DELTA; i--) {
LinkedList<WeakReference<BitVectorIntSet>> m = buckets.get(i);
if (m != null) {
Iterator<WeakReference<BitVectorIntSet>> it = m.iterator();
while (it.hasNext()) {
WeakReference<BitVectorIntSet> wr = it.next();
BitVectorIntSet bv = wr.get();
if (bv != null) {
if (bv.isSubset(value)) {
// FOUND ONE!
if (STATS) {
hits++;
}
return bv;
}
} else {
// remove the weak reference to avoid leaks
it.remove();
}
}
}
}
// didn't find one. create one.
LinkedList<WeakReference<BitVectorIntSet>> m;
m = buckets.get(size);
if (m == null) {
@SuppressWarnings("JdkObsolete") // performance-tuned
LinkedList<WeakReference<BitVectorIntSet>> tmp = new LinkedList<>();
m = tmp;
buckets.put(size, m);
}
BitVectorIntSet bv = new BitVectorIntSet(value);
m.add(new WeakReference<>(bv));
return bv;
}
/** */
private static void reportStats() {
double percent = 100.0 * hits / queries;
System.err.println(("BitVectorRepository: queries " + queries + " hits " + percent));
System.err.println((" entries " + countEntries()));
}
/** */
private static int countEntries() {
int result = 0;
for (LinkedList<WeakReference<BitVectorIntSet>> l : buckets.values()) {
// don't worry about cleared WeakReferences; count will be rough
result += l.size();
}
return result;
}
}
| 3,294
| 30.084906
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/Bits.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
/** utilities for manipulating values at the bit-level. */
public class Bits {
// there's no reason to instantiate this class.
private Bits() {}
/** Return the lower 8 bits (as an int) of an int */
public static int lower8(int value) {
return (value & 0xff);
}
/** Return the lower 16 bits (as an int) of an int */
public static int lower16(int value) {
return (value & 0xffff);
}
/** Return the upper 16 bits (as an int) of an int */
public static int upper16(int value) {
return value >>> 16;
}
/** Return the upper 24 bits (as an int) of an int */
public static int upper24(int value) {
return value >>> 8;
}
/** Return the lower 32 bits (as an int) of a long */
public static int lower32(long value) {
return (int) value;
}
/** Return the upper 32 bits (as an int) of a long */
public static int upper32(long value) {
return (int) (value >>> 32);
}
/** Does an int literal val fit in bits bits? */
public static boolean fits(int val, int bits) {
val >>= bits - 1;
return (val == 0 || val == -1);
}
/**
* Return the number of ones in the binary representation of an integer. Hank Warren's Hacker's
* Delight algorithm
*/
public static int populationCount(int value) {
int result = ((value & 0xAAAAAAAA) >>> 1) + (value & 0x55555555);
result = ((result & 0xCCCCCCCC) >>> 2) + (result & 0x33333333);
result = ((result & 0xF0F0F0F0) >>> 4) + (result & 0x0F0F0F0F);
result = ((result & 0xFF00FF00) >>> 8) + (result & 0x00FF00FF);
result = ((result & 0xFFFF0000) >>> 16) + (result & 0x0000FFFF);
return result;
}
}
| 2,049
| 29.147059
| 97
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/DebuggingMutableIntSet.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.debug.Assertions;
import java.util.Set;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/**
* This class wraps two concrete {@link MutableIntSet}s behind the standard interface, carrying out
* all operations on both of them and performing consistency checks at every step. The purpose of
* this is debugging bitset implementations.
*/
class DebuggingMutableIntSet implements MutableIntSet {
private static final long serialVersionUID = 6879912730471879687L;
final MutableIntSet primaryImpl;
final MutableIntSet secondaryImpl;
DebuggingMutableIntSet(MutableIntSet p, MutableIntSet s) {
primaryImpl = p;
secondaryImpl = s;
}
private void assertEquiv() {
assert primaryImpl.sameValue(secondaryImpl);
}
@Override
public void clear() {
primaryImpl.clear();
secondaryImpl.clear();
}
/** @return true iff this set contains integer i */
@Override
public boolean contains(int i) {
assert primaryImpl.contains(i) == secondaryImpl.contains(i);
return primaryImpl.contains(i);
}
/** */
@Override
public boolean isEmpty() {
if (primaryImpl.isEmpty() != secondaryImpl.isEmpty()) {
System.err.println(
primaryImpl
+ ".isEmpty() = "
+ primaryImpl.isEmpty()
+ " and "
+ secondaryImpl
+ ".isEmpty() = "
+ secondaryImpl.isEmpty());
Assertions.UNREACHABLE();
}
return primaryImpl.isEmpty();
}
/** */
@Override
public int size() {
if (primaryImpl.size() != secondaryImpl.size()) {
assert primaryImpl.size() == secondaryImpl.size()
: "size "
+ primaryImpl.size()
+ " of "
+ primaryImpl
+ " differs from "
+ "size "
+ secondaryImpl.size()
+ " of "
+ secondaryImpl;
}
return primaryImpl.size();
}
@Override
public int max() {
assert primaryImpl.max() == secondaryImpl.max();
return primaryImpl.max();
}
/**
* Add an integer value to this set.
*
* @return true iff the value of this changes.
*/
@Override
public boolean add(int i) {
boolean pr = primaryImpl.add(i);
boolean sr = secondaryImpl.add(i);
if (pr != sr) {
assert pr == sr
: "adding "
+ i
+ " to "
+ primaryImpl
+ " returns "
+ pr
+ ", but adding "
+ i
+ " to "
+ secondaryImpl
+ " returns "
+ sr;
}
return pr;
}
/** Remove an integer from this set. */
@Override
public boolean remove(int i) {
boolean result = primaryImpl.remove(i);
secondaryImpl.remove(i);
assertEquiv();
return result;
}
/** @return true iff this set contains integer i */
@Override
public boolean containsAny(IntSet set) {
if (set instanceof DebuggingMutableIntSet) {
DebuggingMutableIntSet db = (DebuggingMutableIntSet) set;
boolean ppr = primaryImpl.containsAny(db.primaryImpl);
boolean ssr = secondaryImpl.containsAny(db.secondaryImpl);
if (ppr != ssr) {
assert ppr == ssr : "containsAny " + this + ' ' + set + ' ' + ppr + ' ' + ssr;
}
return ppr;
} else {
Assertions.UNREACHABLE();
return false;
}
}
/**
* This implementation must not despoil the original value of "this"
*
* @return a new IntSet which is the intersection of this and that
*/
@NullUnmarked
@Nullable
@Override
public IntSet intersection(IntSet that) {
if (that instanceof DebuggingMutableIntSet) {
DebuggingMutableIntSet db = (DebuggingMutableIntSet) that;
IntSet ppr = primaryImpl.intersection(db.primaryImpl);
IntSet ssr = secondaryImpl.intersection(db.secondaryImpl);
assert ppr.sameValue(ssr);
return ppr;
} else {
Assertions.UNREACHABLE();
return null;
}
}
/** @see com.ibm.wala.util.intset.IntSet#union(com.ibm.wala.util.intset.IntSet) */
@Override
public IntSet union(IntSet that) {
MutableSparseIntSet temp = new MutableSparseIntSet();
temp.addAll(this);
temp.addAll(that);
return temp;
}
/** @return true iff {@code this} has the same value as {@code that}. */
@Override
public boolean sameValue(IntSet that) {
if (that instanceof DebuggingMutableIntSet) {
DebuggingMutableIntSet db = (DebuggingMutableIntSet) that;
boolean ppr = primaryImpl.sameValue(db.primaryImpl);
boolean ssr = secondaryImpl.sameValue(db.secondaryImpl);
assert ppr == ssr;
return ppr;
} else {
Assertions.UNREACHABLE();
return false;
}
}
/** @return true iff {@code this} is a subset of {@code that}. */
@Override
public boolean isSubset(IntSet that) {
if (that instanceof DebuggingMutableIntSet) {
DebuggingMutableIntSet db = (DebuggingMutableIntSet) that;
boolean ppr = primaryImpl.isSubset(db.primaryImpl);
boolean ssr = secondaryImpl.isSubset(db.secondaryImpl);
assert ppr == ssr;
return ppr;
} else {
Assertions.UNREACHABLE();
return false;
}
}
/** Set the value of this to be the same as the value of set */
@Override
public void copySet(IntSet set) {
if (set instanceof DebuggingMutableIntSet) {
DebuggingMutableIntSet db = (DebuggingMutableIntSet) set;
primaryImpl.copySet(db.primaryImpl);
secondaryImpl.copySet(db.secondaryImpl);
assert primaryImpl.sameValue(secondaryImpl);
} else {
Assertions.UNREACHABLE();
}
}
/**
* Add all members of set to this.
*
* @return true iff the value of this changes.
*/
@Override
public boolean addAll(IntSet set) {
if (set instanceof DebuggingMutableIntSet) {
DebuggingMutableIntSet db = (DebuggingMutableIntSet) set;
int ps = primaryImpl.size();
int ss = secondaryImpl.size();
boolean ppr = primaryImpl.addAll(db.primaryImpl);
boolean ssr = secondaryImpl.addAll(db.secondaryImpl);
if (ppr != ssr) {
System.err.println(
"ppr was "
+ ppr
+ " (should be "
+ (ps != primaryImpl.size())
+ ") but ssr was "
+ ssr
+ " (should be "
+ (ss != secondaryImpl.size())
+ ')');
System.err.println("adding " + set + " to " + this + " failed");
Assertions.UNREACHABLE();
}
return ppr;
} else {
Assertions.UNREACHABLE();
return false;
}
}
/** Intersect this with another set. */
@Override
public void intersectWith(IntSet set) {
if (set instanceof DebuggingMutableIntSet) {
DebuggingMutableIntSet db = (DebuggingMutableIntSet) set;
primaryImpl.intersectWith(db.primaryImpl);
secondaryImpl.intersectWith(db.secondaryImpl);
if (!primaryImpl.sameValue(secondaryImpl))
assert false
: this
+ " ("
+ primaryImpl.size()
+ ", "
+ secondaryImpl.size()
+ ") inconsistent after intersecting with "
+ set;
} else {
Assertions.UNREACHABLE();
}
}
/** */
@Override
public boolean addAllInIntersection(IntSet other, IntSet filter) {
if (other instanceof DebuggingMutableIntSet && filter instanceof DebuggingMutableIntSet) {
DebuggingMutableIntSet db = (DebuggingMutableIntSet) other;
DebuggingMutableIntSet df = (DebuggingMutableIntSet) filter;
boolean pr = primaryImpl.addAllInIntersection(db.primaryImpl, df.primaryImpl);
boolean sr = secondaryImpl.addAllInIntersection(db.secondaryImpl, df.secondaryImpl);
assert pr == sr;
return pr;
} else {
Assertions.UNREACHABLE();
return false;
}
}
/** @see com.ibm.wala.util.intset.IntSet#intIterator() */
@Override
public IntIterator intIterator() {
MutableSparseIntSet bits = MutableSparseIntSet.makeEmpty();
for (IntIterator pi = primaryImpl.intIterator(); pi.hasNext(); ) {
int x = pi.next();
assert !bits.contains(x);
bits.add(x);
}
for (IntIterator si = secondaryImpl.intIterator(); si.hasNext(); ) {
int x = si.next();
assert bits.contains(x);
bits.remove(x);
}
assert bits.isEmpty();
return primaryImpl.intIterator();
}
/** Invoke an action on each element of the Set */
@Override
public void foreach(IntSetAction action) {
final Set<Integer> bits = HashSetFactory.make();
primaryImpl.foreach(
x -> {
assert !bits.contains(x);
bits.add(x);
});
secondaryImpl.foreach(
x -> {
assert bits.contains(x);
bits.remove(x);
});
assert bits.isEmpty();
primaryImpl.foreach(action);
}
/** Invoke an action on each element of the Set, excluding elements of Set X */
@Override
public void foreachExcluding(IntSet X, IntSetAction action) {
final Set<Integer> bits = HashSetFactory.make();
primaryImpl.foreachExcluding(
X,
x -> {
assert !bits.contains(x);
bits.add(x);
});
secondaryImpl.foreachExcluding(
X,
x -> {
assert bits.contains(x);
bits.remove(x);
});
assert bits.isEmpty();
primaryImpl.foreachExcluding(X, action);
}
@Override
public String toString() {
return "[[P " + primaryImpl.toString() + ", S " + secondaryImpl.toString() + " ]]";
}
}
| 10,150
| 26.141711
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/DebuggingMutableIntSetFactory.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/**
* A debugging factory that creates debugging bitsets that are implemented as two bitsets that
* perform consistency checks for every operation.
*/
public class DebuggingMutableIntSetFactory implements MutableIntSetFactory<DebuggingMutableIntSet> {
private MutableIntSetFactory<?> primary;
private MutableIntSetFactory<?> secondary;
public DebuggingMutableIntSetFactory(MutableIntSetFactory<?> p, MutableIntSetFactory<?> s) {
primary = p;
secondary = s;
if (p == null) {
throw new IllegalArgumentException("null p");
}
if (s == null) {
throw new IllegalArgumentException("null s");
}
}
public DebuggingMutableIntSetFactory() {
this(new MutableSparseIntSetFactory(), new MutableSharedBitVectorIntSetFactory());
}
@Override
public DebuggingMutableIntSet make(int[] set) {
if (set == null) {
throw new IllegalArgumentException("null set");
}
return new DebuggingMutableIntSet(primary.make(set), secondary.make(set));
}
@Override
public DebuggingMutableIntSet parse(String string) {
int[] backingStore = SparseIntSet.parseIntArray(string);
return make(backingStore);
}
@NullUnmarked
@Nullable
@Override
public DebuggingMutableIntSet makeCopy(IntSet x) throws UnimplementedError {
if (x == null) {
throw new IllegalArgumentException("null x");
}
if (x instanceof DebuggingMutableIntSet) {
DebuggingMutableIntSet db = (DebuggingMutableIntSet) x;
MutableIntSet pr = primary.makeCopy(db.primaryImpl);
MutableIntSet sr = secondary.makeCopy(db.secondaryImpl);
assert pr.sameValue(db.primaryImpl);
assert sr.sameValue(db.secondaryImpl);
assert pr.sameValue(sr);
return new DebuggingMutableIntSet(pr, sr);
} else {
Assertions.UNREACHABLE();
return null;
}
}
@Override
public DebuggingMutableIntSet make() {
return new DebuggingMutableIntSet(primary.make(), secondary.make());
}
public void setPrimaryFactory(MutableIntSetFactory<?> x) {
if (x == null) {
throw new IllegalArgumentException("null x");
}
if (x == this) {
throw new IllegalArgumentException("bad recursion");
}
primary = x;
}
public void setSecondaryFactory(MutableIntSetFactory<?> x) {
if (x == null) {
throw new IllegalArgumentException("null x");
}
if (x == this) {
throw new IllegalArgumentException("bad recursion");
}
secondary = x;
}
}
| 3,067
| 28.219048
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/EmptyIntSet.java
|
/*
* Copyright (c) 2011 - IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.util.NoSuchElementException;
public class EmptyIntSet implements IntSet {
private static final long serialVersionUID = 5116475799916663164L;
public static EmptyIntSet instance = new EmptyIntSet();
@Override
public boolean contains(int i) {
return false;
}
@Override
public boolean containsAny(IntSet set) {
return false;
}
@Override
public IntSet intersection(IntSet that) {
return this;
}
@Override
public IntSet union(IntSet that) {
return that;
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public int size() {
return 0;
}
private static final IntIterator emptyIter =
new IntIterator() {
@Override
public boolean hasNext() {
return false;
}
@Override
public int next() {
throw new NoSuchElementException();
}
};
@Override
public IntIterator intIterator() {
return emptyIter;
}
@Override
public void foreach(IntSetAction action) {}
@Override
public void foreachExcluding(IntSet X, IntSetAction action) {}
@Override
public int max() {
throw new NoSuchElementException();
}
@Override
public boolean sameValue(IntSet that) {
return that.isEmpty();
}
@Override
public boolean isSubset(IntSet that) {
return true;
}
}
| 1,761
| 18.577778
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/FixedSizeBitVector.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.util.Arrays;
public final class FixedSizeBitVector implements Cloneable, java.io.Serializable {
public static final long serialVersionUID = 33181877746462822L;
private static final int LOG_BITS_PER_UNIT = 5;
private static final int MASK = 0xffffffff;
private static final int LOW_MASK = 0x1f;
private int bits[];
private final int nbits;
/** Convert bitIndex to a subscript into the bits[] array. */
private static int subscript(int bitIndex) {
return bitIndex >> LOG_BITS_PER_UNIT;
}
/**
* Creates an empty string with the specified size.
*
* @param nbits the size of the string
*/
public FixedSizeBitVector(int nbits) {
// subscript(nbits) is the length of the array needed to
// hold nbits
if (nbits < 0) {
throw new IllegalArgumentException("illegal nbits: " + nbits);
}
bits = new int[subscript(nbits) + 1];
this.nbits = nbits;
}
/**
* Creates a copy of a Bit String
*
* @param s the string to copy
* @throws IllegalArgumentException if s is null
*/
public FixedSizeBitVector(FixedSizeBitVector s) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
bits = new int[s.bits.length];
this.nbits = s.nbits;
copyBits(s);
}
/** Sets all bits. */
public void setAll() {
Arrays.fill(bits, MASK);
}
/**
* Sets a bit.
*
* @param bit the bit to be set
*/
public void set(int bit) {
try {
int shiftBits = bit & LOW_MASK;
bits[subscript(bit)] |= (1 << shiftBits);
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("invalid bit " + bit, e);
}
}
/** Clears all bits. */
public void clearAll() {
Arrays.fill(bits, 0);
}
/**
* Clears a bit.
*
* @param bit the bit to be cleared
*/
public void clear(int bit) {
try {
int shiftBits = bit & LOW_MASK;
bits[subscript(bit)] &= ~(1 << shiftBits);
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("invalid bit: " + bit, e);
}
}
/**
* Gets a bit.
*
* @param bit the bit to be gotten
*/
public boolean get(int bit) {
if (bit < 0) {
throw new IllegalArgumentException("illegal bit: " + bit);
}
int shiftBits = bit & LOW_MASK;
int n = subscript(bit);
try {
return ((bits[n] & (1 << shiftBits)) != 0);
} catch (ArrayIndexOutOfBoundsException e) {
return false;
}
}
/** Logically NOT this bit string */
public void not() {
for (int i = 0; i < bits.length; i++) {
bits[i] ^= MASK;
}
}
/** Return the NOT of a bit string */
public static FixedSizeBitVector not(FixedSizeBitVector s) {
FixedSizeBitVector b = new FixedSizeBitVector(s);
b.not();
return b;
}
/**
* Logically ANDs this bit set with the specified set of bits.
*
* @param set the bit set to be ANDed with
*/
public void and(FixedSizeBitVector set) {
if (set == null) {
throw new IllegalArgumentException("null set");
}
if (this == set) {
return;
}
int n = bits.length;
for (int i = n; i-- > 0; ) {
bits[i] &= set.bits[i];
}
}
/** Return a new bit string as the AND of two others. */
public static FixedSizeBitVector and(FixedSizeBitVector b1, FixedSizeBitVector b2) {
FixedSizeBitVector b = new FixedSizeBitVector(b1);
b.and(b2);
return b;
}
/**
* Logically ORs this bit set with the specified set of bits.
*
* @param set the bit set to be ORed with
* @throws IllegalArgumentException if set == null
*/
public void or(FixedSizeBitVector set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (this == set) { // should help alias analysis
return;
}
int setLength = set.bits.length;
for (int i = setLength; i-- > 0; ) {
bits[i] |= set.bits[i];
}
}
/**
* Return a new FixedSizeBitVector as the OR of two others
*
* @throws IllegalArgumentException if b2 == null
*/
public static FixedSizeBitVector or(FixedSizeBitVector b1, FixedSizeBitVector b2)
throws IllegalArgumentException {
if (b2 == null) {
throw new IllegalArgumentException("b2 == null");
}
FixedSizeBitVector b = new FixedSizeBitVector(b1);
b.or(b2);
return b;
}
/**
* Logically XORs this bit set with the specified set of bits.
*
* @param set the bit set to be XORed with
* @throws IllegalArgumentException if set is null
*/
public void xor(FixedSizeBitVector set) {
if (set == null) {
throw new IllegalArgumentException("set is null");
}
int setLength = set.bits.length;
for (int i = setLength; i-- > 0; ) {
bits[i] ^= set.bits[i];
}
}
/**
* Check if the intersection of the two sets is empty
*
* @param other the set to check intersection with
*/
public boolean intersectionEmpty(FixedSizeBitVector other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
int n = bits.length;
for (int i = n; i-- > 0; ) {
if ((bits[i] & other.bits[i]) != 0) return false;
}
return true;
}
/**
* Copies the values of the bits in the specified set into this set.
*
* @param set the bit set to copy the bits from
* @throws IllegalArgumentException if set is null
*/
public void copyBits(FixedSizeBitVector set) {
if (set == null) {
throw new IllegalArgumentException("set is null");
}
int setLength = set.bits.length;
for (int i = setLength; i-- > 0; ) {
bits[i] = set.bits[i];
}
}
/** Gets the hashcode. */
@Override
public int hashCode() {
int h = 1234;
for (int i = bits.length; --i >= 0; ) {
h ^= bits[i] * (i + 1);
}
return h;
}
/** How many bits are set? */
public int populationCount() {
int count = 0;
for (int bit : bits) {
count += Bits.populationCount(bit);
}
return count;
}
/**
* Calculates and returns the set's size in bits. The maximum element in the set is the size - 1st
* element.
*/
public int length() {
return bits.length << LOG_BITS_PER_UNIT;
}
/**
* Compares this object against the specified object.
*
* @param obj the object to compare with
* @return true if the objects are the same; false otherwise.
*/
@Override
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof FixedSizeBitVector)) {
if (this == obj) { // should help alias analysis
return true;
}
FixedSizeBitVector set = (FixedSizeBitVector) obj;
int n = bits.length;
if (n != set.bits.length) return false;
for (int i = n; i-- > 0; ) {
if (bits[i] != set.bits[i]) {
return false;
}
}
return true;
}
return false;
}
public boolean isZero() {
int setLength = bits.length;
for (int i = setLength; i-- > 0; ) {
if (bits[i] != 0) return false;
}
return true;
}
/** Clones the FixedSizeBitVector. */
@Override
public Object clone() {
FixedSizeBitVector result = null;
try {
result = (FixedSizeBitVector) super.clone();
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
result.bits = new int[bits.length];
System.arraycopy(bits, 0, result.bits, 0, result.bits.length);
return result;
}
/** Converts the FixedSizeBitVector to a String. */
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
boolean needSeparator = false;
buffer.append('{');
// int limit = length();
int limit = this.nbits;
for (int i = 0; i < limit; i++) {
if (get(i)) {
if (needSeparator) {
buffer.append(", ");
} else {
needSeparator = true;
}
buffer.append(i);
}
}
buffer.append('}');
return buffer.toString();
}
}
| 8,503
| 24.234421
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/IBinaryNaturalRelation.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.debug.VerboseAction;
/** a relation R(x,y) where x >= 0 */
public interface IBinaryNaturalRelation extends VerboseAction, Iterable<IntPair> {
/**
* Add (x,y) to the relation
*
* @return true iff the relation changes as a result of this call.
*/
boolean add(int x, int y);
/** @return IntSet of y s.t. R(x,y) or null if none. */
IntSet getRelated(int x);
/** @return number of y s.t. R(x,y) */
int getRelatedCount(int x);
/** @return true iff there exists pair (x,y) for some y */
boolean anyRelated(int x);
void remove(int x, int y);
void removeAll(int x);
/** @return true iff (x,y) \in R */
boolean contains(int x, int y);
int maxKeyValue();
}
| 1,130
| 25.928571
| 82
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/IntIterator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
/** a more efficient iterator for sets of integers */
public interface IntIterator {
/** @return true iff this iterator has a next element */
boolean hasNext();
/** @return next integer in the iteration */
int next();
}
| 640
| 28.136364
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/IntPair.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
/** A pair of ints. Note that an IntPair has value semantics. */
public class IntPair {
final int x;
final int y;
public IntPair(int x, int y) {
this.x = x;
this.y = y;
}
/** @return Returns the x. */
public int getX() {
return x;
}
/** @return Returns the y. */
public int getY() {
return y;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj.getClass() == this.getClass()) {
IntPair p = (IntPair) obj;
return p.getX() == x && p.getY() == y;
}
return false;
}
@Override
public int hashCode() {
return 8377 * x + y;
}
@Override
public String toString() {
return "[" + x + ',' + y + ']';
}
public static IntPair make(int x, int y) {
return new IntPair(x, y);
}
}
| 1,229
| 19.163934
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/IntSet.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.io.Serializable;
/** Set of integers; not necessary mutable TODO: extract a smaller interface? */
public interface IntSet extends Serializable {
/** @return true iff this set contains integer i */
boolean contains(int i);
/** @return true iff this set contains integer i */
boolean containsAny(IntSet set);
/**
* This implementation must not despoil the original value of "this"
*
* @return a new IntSet which is the intersection of this and that
*/
IntSet intersection(IntSet that);
/**
* This implementation must not despoil the original value of "this"
*
* @return a new IntSet containing all elements of this and that
*/
IntSet union(IntSet that);
/** @return true iff this set is empty */
boolean isEmpty();
/** @return the number of elements in this set */
int size();
/** @return a perhaps more efficient iterator */
IntIterator intIterator();
/** Invoke an action on each element of the Set */
void foreach(IntSetAction action);
/** Invoke an action on each element of the Set, excluding elements of Set X */
void foreachExcluding(IntSet X, IntSetAction action);
/** @return maximum integer in this set. */
int max();
/** @return true iff {@code this} has the same value as {@code that}. */
boolean sameValue(IntSet that);
/** @return true iff {@code this} is a subset of {@code that}. */
boolean isSubset(IntSet that);
}
| 1,837
| 28.645161
| 81
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/IntSetAction.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
public interface IntSetAction {
void act(int x);
}
| 465
| 24.888889
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/IntSetUtil.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import java.util.Set;
import org.jspecify.annotations.NullUnmarked;
/** Utilities for dealing with {@link IntSet}s */
public class IntSetUtil {
public static final String INT_SET_FACTORY_CONFIG_PROPERTY_NAME =
"com.ibm.wala.mutableIntSetFactory";
@SuppressWarnings("NullAway.Init")
private static MutableIntSetFactory<?> defaultIntSetFactory;
static {
MutableIntSetFactory<?> defaultFactory = new MutableSharedBitVectorIntSetFactory();
if (System.getProperty(INT_SET_FACTORY_CONFIG_PROPERTY_NAME) != null) {
try {
@SuppressWarnings("unchecked")
Class<? extends MutableIntSetFactory<?>> intSetFactoryClass =
(Class<? extends MutableIntSetFactory<?>>)
Class.forName(System.getProperty(INT_SET_FACTORY_CONFIG_PROPERTY_NAME));
MutableIntSetFactory<?> intSetFactory = intSetFactoryClass.getConstructor().newInstance();
setDefaultIntSetFactory(intSetFactory);
} catch (Exception e) {
System.err.println(
("Cannot use int set factory "
+ System.getProperty(INT_SET_FACTORY_CONFIG_PROPERTY_NAME)));
setDefaultIntSetFactory(defaultFactory);
}
} else {
setDefaultIntSetFactory(defaultFactory);
}
assert defaultIntSetFactory != null;
}
public static MutableIntSet make() {
return defaultIntSetFactory.make();
}
public static MutableIntSet make(int[] initial) {
return defaultIntSetFactory.make(initial);
}
public static IntSet make(Set<Integer> x) {
int[] vals = x.stream().mapToInt(Integer::intValue).toArray();
return make(vals);
}
private static final boolean DEBUG = false;
// there's no reason to instantiate this class
private IntSetUtil() {}
/**
* This method constructs an appropriate mutable copy of set.
*
* @return a new {@link MutableIntSet} object with the same value as set
* @throws UnimplementedError if we haven't supported the set type yet.
* @throws IllegalArgumentException if set == null
*/
@NullUnmarked
public static MutableIntSet makeMutableCopy(IntSet set)
throws IllegalArgumentException, UnimplementedError {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (set instanceof SparseIntSet) {
return MutableSparseIntSet.make(set);
} else if (set instanceof BitVectorIntSet) {
return new BitVectorIntSet(set);
} else if (set instanceof BimodalMutableIntSet) {
return BimodalMutableIntSet.makeCopy(set);
} else if (set instanceof MutableSharedBitVectorIntSet) {
return new MutableSharedBitVectorIntSet((MutableSharedBitVectorIntSet) set);
} else if (set instanceof SemiSparseMutableIntSet) {
return new SemiSparseMutableIntSet((SemiSparseMutableIntSet) set);
} else if (set instanceof DebuggingMutableIntSet) {
MutableIntSet pCopy = makeMutableCopy(((DebuggingMutableIntSet) set).primaryImpl);
MutableIntSet sCopy = makeMutableCopy(((DebuggingMutableIntSet) set).secondaryImpl);
return new DebuggingMutableIntSet(pCopy, sCopy);
} else if (set instanceof EmptyIntSet) {
return IntSetUtil.make();
} else {
Assertions.UNREACHABLE(set.getClass().toString());
return null;
}
}
/** Compute the asymmetric difference of two sets, a \ b. */
public static IntSet diff(IntSet A, IntSet B) {
if (A == null) {
throw new IllegalArgumentException("null A");
}
if (B == null) {
throw new IllegalArgumentException("null B");
}
return diff(A, B, IntSetUtil.getDefaultIntSetFactory());
}
private static IntSet defaultSlowDiff(IntSet A, IntSet B, MutableIntSetFactory<?> factory) {
// TODO: this is slow ... optimize please.
MutableIntSet result = factory.makeCopy(A);
if (DEBUG) {
System.err.println(("initial result " + result + ' ' + result.getClass()));
}
for (IntIterator it = B.intIterator(); it.hasNext(); ) {
int I = it.next();
result.remove(I);
if (DEBUG) {
System.err.println(("removed " + I + " now is " + result));
}
}
if (DEBUG) {
System.err.println(("return " + result));
}
return result;
}
/** Compute the asymmetric difference of two sets, a \ b. */
public static IntSet diff(IntSet A, IntSet B, MutableIntSetFactory<?> factory) {
if (factory == null) {
throw new IllegalArgumentException("null factory");
}
if (A == null) {
throw new IllegalArgumentException("null A");
}
if (B == null) {
throw new IllegalArgumentException("null B");
}
if (A instanceof SparseIntSet && B instanceof SparseIntSet) {
return SparseIntSet.diff((SparseIntSet) A, (SparseIntSet) B);
} else if (A instanceof SemiSparseMutableIntSet && B instanceof SemiSparseMutableIntSet) {
IntSet d =
SemiSparseMutableIntSet.diff((SemiSparseMutableIntSet) A, (SemiSparseMutableIntSet) B);
return d;
} else {
return defaultSlowDiff(A, B, factory);
}
}
/**
* Subtract two sets, i.e. a = a \ b.
*
* @throws IllegalArgumentException if B == null
*/
public static MutableIntSet removeAll(MutableIntSet A, IntSet B) throws IllegalArgumentException {
if (A == null) {
throw new IllegalArgumentException("A == null");
}
if (B == null) {
throw new IllegalArgumentException("B == null");
}
if (A instanceof SemiSparseMutableIntSet && B instanceof SemiSparseMutableIntSet) {
if (DEBUG) {
System.err.println("call SemiSparseMutableIntSet.removeAll");
}
return ((SemiSparseMutableIntSet) A).removeAll((SemiSparseMutableIntSet) B);
} else {
for (IntIterator it = B.intIterator(); it.hasNext(); ) {
int I = it.next();
A.remove(I);
if (DEBUG) {
System.err.println(("removed " + I + " now is " + A));
}
}
if (DEBUG) {
System.err.println(("return " + A));
}
return A;
}
}
/** @return index \in [low,high] s.t. data[index] = key, or -1 if not found */
public static int binarySearch(int[] data, int key, int low, int high)
throws IllegalArgumentException {
if (data == null) {
throw new IllegalArgumentException("null array");
}
if (data.length == 0) {
return -1;
}
if (low <= high && (low < 0 || high < 0)) {
throw new IllegalArgumentException("can't search negative indices " + low + ' ' + high);
}
if (high > data.length - 1) {
high = data.length - 1;
}
if (low <= high) {
int mid = (low + high) / 2;
int midValue = data[mid];
if (midValue == key) {
return mid;
} else if (midValue > key) {
return binarySearch(data, key, low, mid - 1);
} else {
return binarySearch(data, key, mid + 1, high);
}
} else {
return -1;
}
}
/** @return Returns the defaultIntSetFactory. */
public static MutableIntSetFactory<?> getDefaultIntSetFactory() {
return defaultIntSetFactory;
}
/** @param defaultIntSetFactory The defaultIntSetFactory to set. */
public static void setDefaultIntSetFactory(MutableIntSetFactory<?> defaultIntSetFactory) {
if (defaultIntSetFactory == null) {
throw new IllegalArgumentException("null defaultIntSetFactory");
}
IntSetUtil.defaultIntSetFactory = defaultIntSetFactory;
}
/**
* @return a new sparse int set which adds j to s
* @throws IllegalArgumentException if s == null
*/
public static IntSet add(IntSet s, int j) throws IllegalArgumentException {
if (s == null) {
throw new IllegalArgumentException("s == null");
}
if (s instanceof SparseIntSet) {
SparseIntSet sis = (SparseIntSet) s;
return SparseIntSet.add(sis, j);
} else {
// really slow. optimize as needed.
MutableSparseIntSet result = MutableSparseIntSet.make(s);
result.add(j);
return result;
}
}
public static int[] toArray(IntSet s) {
int i = 0;
int[] result = new int[s.size()];
IntIterator x = s.intIterator();
while (x.hasNext()) {
result[i++] = x.next();
}
assert !x.hasNext();
return result;
}
}
| 8,708
| 32.625483
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/IntVector.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
/** interface for array of integer */
public interface IntVector {
int get(int x);
void set(int x, int value);
/** @return max i s.t set(i) was called. */
int getMaxIndex();
}
| 597
| 25
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/IntegerUnionFind.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.util.Arrays;
/**
* An implementation of Tarjan's union-find, using path compression and balancing, for non-negative
* integers
*/
public class IntegerUnionFind {
private static final int MAX_VALUE = Integer.MAX_VALUE / 4;
private static final int DEFAULT_SIZE = 100;
/**
* parent[i+1] =
*
* <ul>
* <li>j > 0 if i is in the same equiv class as j
* <li>j <= 0 if i is the representative of a class of size -(j)+1
* </ul>
*
* we initialize parent[j] = 0, so each element is a class of size 1
*/
int[] parent;
public IntegerUnionFind() {
this(DEFAULT_SIZE);
}
/** @param size initial size of the tables */
public IntegerUnionFind(int size) {
if (size < 0 || size > MAX_VALUE) {
throw new IllegalArgumentException("illegal size: " + size);
}
parent = new int[size + 1];
}
/** union the equiv classes of x and y */
public void union(int x, int y) {
if (x < 0) {
throw new IllegalArgumentException("invalid x : " + x);
}
if (y < 0) {
throw new IllegalArgumentException("invalid y: " + y);
}
if (x > MAX_VALUE) {
throw new IllegalArgumentException("x is too big: " + x);
}
if (y > MAX_VALUE) {
throw new IllegalArgumentException("y is too big: " + y);
}
if (x >= size() || y >= size()) {
grow(2 * Math.max(x, y));
}
// shift by one to support sets including 0
x += 1;
y += 1;
x = findInternal(x);
y = findInternal(y);
if (x != y) {
// glue smaller tree onto larger tree (balancing)
if (parent[x] < parent[y]) {
// x's class has more elements
parent[x] += parent[y] - 1;
parent[y] = x;
} else {
// y's class has more elements (or the same number)
parent[y] += parent[x] - 1;
parent[x] = y;
}
}
}
private void grow(int size) {
parent = Arrays.copyOf(parent, size + 1);
}
/** @return representative of x's equivalence class */
public int find(int x) {
if (x < 0) {
throw new IllegalArgumentException("illegal x " + x);
}
if (x >= size()) {
return x;
}
// shift by one to support sets including 0
return findInternal(x + 1) - 1;
}
/** @return representative of x's equivalence class */
private int findInternal(int x) {
int root = x;
while (parent[root] > 0) {
root = parent[root];
}
// path compression
while (parent[x] > 0) {
int z = x;
x = parent[x];
parent[z] = root;
}
return root;
}
/** */
public int size() {
return parent.length - 1;
}
}
| 3,042
| 23.942623
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/LongIterator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
/** a more efficient iterator for sets of longs */
public interface LongIterator {
/** @return true iff this iterator has a next element */
boolean hasNext();
/** @return next integer in the iteration */
long next();
}
| 639
| 28.090909
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/LongSet.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import org.jspecify.annotations.Nullable;
/** Set of longs; not necessary mutable TODO: extract a smaller interface? */
public interface LongSet {
/** @return true iff this set contains long i */
boolean contains(long i);
/** @return true iff this set contains integer i */
boolean containsAny(LongSet set);
/**
* This implementation must not despoil the original value of "this"
*
* @return a new IntSet which is the intersection of this and that
*/
@Nullable
LongSet intersection(LongSet that);
/** @return true iff this set is empty */
boolean isEmpty();
/** @return the number of elements in this set */
int size();
/** @return maximum integer in this set. */
long max();
/** @return true iff {@code this} has the same value as {@code that}. */
boolean sameValue(LongSet that);
/** @return true iff {@code this} is a subset of {@code that}. */
boolean isSubset(LongSet that);
/** @return a perhaps more efficient iterator */
LongIterator longIterator();
/** Invoke an action on each element of the Set */
void foreach(LongSetAction action);
/** Invoke an action on each element of the Set, excluding elements of Set X */
void foreachExcluding(LongSet X, LongSetAction action);
}
| 1,663
| 28.714286
| 81
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/LongSetAction.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
public interface LongSetAction {
void act(long x);
}
| 467
| 25
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/LongSetUtil.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/** Utilities for dealing with LongSets */
public class LongSetUtil {
public static final String INT_SET_FACTORY_CONFIG_PROPERTY_NAME =
"com.ibm.wala.mutableLongSetFactory";
@Nullable private static MutableLongSetFactory defaultLongSetFactory;
static {
MutableLongSetFactory defaultFactory = new MutableSparseLongSetFactory();
if (System.getProperty(INT_SET_FACTORY_CONFIG_PROPERTY_NAME) != null) {
try {
Class<?> intSetFactoryClass =
Class.forName(System.getProperty(INT_SET_FACTORY_CONFIG_PROPERTY_NAME));
MutableLongSetFactory intSetFactory =
(MutableLongSetFactory) intSetFactoryClass.getDeclaredConstructor().newInstance();
setDefaultLongSetFactory(intSetFactory);
} catch (Exception e) {
System.err.println(
("Cannot use int set factory "
+ System.getProperty(INT_SET_FACTORY_CONFIG_PROPERTY_NAME)));
setDefaultLongSetFactory(defaultFactory);
}
} else {
setDefaultLongSetFactory(defaultFactory);
}
assert defaultLongSetFactory != null;
}
@NullUnmarked
public static MutableLongSet make() {
return defaultLongSetFactory.make();
}
private static final boolean DEBUG = false;
/**
* This method constructs an appropriate mutable copy of set.
*
* @return a new MutableLongSet object with the same value as set
* @throws UnimplementedError if (not ( set instanceof com.ibm.wala.util.intset.SparseLongSet ) )
* and (not ( set instanceof com.ibm.wala.util.intset.BitVectorLongSet ) ) and (not ( set
* instanceof com.ibm.wala.util.intset.BimodalMutableLongSet ) ) and (not ( set instanceof
* com.ibm.wala.util.intset.DebuggingMutableLongSet ) ) and (not ( set instanceof
* com.ibm.wala.util.intset.SemiSparseMutableLongSet ) ) and (not ( set instanceof
* com.ibm.wala.util.intset.MutableSharedBitVectorLongSet ) )
* @throws IllegalArgumentException if set == null
*/
@Nullable
public static MutableLongSet makeMutableCopy(LongSet set)
throws IllegalArgumentException, UnimplementedError {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (set instanceof SparseLongSet) {
return MutableSparseLongSet.make(set);
} else {
Assertions.UNREACHABLE(set.getClass().toString());
return null;
}
}
/** Compute the asymmetric difference of two sets, a \ b. */
public static LongSet diff(LongSet A, LongSet B) {
if (A == null) {
throw new IllegalArgumentException("null A");
}
if (B == null) {
throw new IllegalArgumentException("null B");
}
return diff(A, B, LongSetUtil.getDefaultLongSetFactory());
}
@NullUnmarked
private static LongSet defaultSlowDiff(
LongSet A, LongSet B, @Nullable MutableLongSetFactory factory) {
// TODO: this is slow ... optimize please.
MutableLongSet result = factory.makeCopy(A);
if (DEBUG) {
System.err.println(("initial result " + result + ' ' + result.getClass()));
}
for (LongIterator it = B.longIterator(); it.hasNext(); ) {
long I = it.next();
result.remove(I);
if (DEBUG) {
System.err.println(("removed " + I + " now is " + result));
}
}
if (DEBUG) {
System.err.println(("return " + result));
}
return result;
}
/** Compute the asymmetric difference of two sets, a \ b. */
public static LongSet diff(LongSet A, LongSet B, @Nullable MutableLongSetFactory factory) {
if (A == null) {
throw new IllegalArgumentException("null A");
}
if (B == null) {
throw new IllegalArgumentException("null B");
}
if (A instanceof SparseLongSet && B instanceof SparseLongSet) {
return SparseLongSet.diff((SparseLongSet) A, (SparseLongSet) B);
} else {
return defaultSlowDiff(A, B, factory);
}
}
/**
* Subtract two sets, i.e. a = a \ b.
*
* @throws IllegalArgumentException if A == null || B == null
*/
public static MutableLongSet removeAll(MutableLongSet A, LongSet B)
throws IllegalArgumentException {
if (A == null) {
throw new IllegalArgumentException("A == null");
}
if (B == null) {
throw new IllegalArgumentException("B == null");
}
for (LongIterator it = B.longIterator(); it.hasNext(); ) {
long I = it.next();
A.remove(I);
if (DEBUG) {
System.err.println(("removed " + I + " now is " + A));
}
}
if (DEBUG) {
System.err.println(("return " + A));
}
return A;
}
/** @return index \in [low,high] s.t. data[index] = key, or -1 if not found */
public static int binarySearch(long[] data, long key, int low, int high)
throws IllegalArgumentException {
if (data == null) {
throw new IllegalArgumentException("null array");
}
if (data.length == 0) {
return -1;
}
if (low <= high && (low < 0 || high < 0)) {
throw new IllegalArgumentException("can't search negative indices");
}
if (high > data.length - 1) {
high = data.length - 1;
}
if (low <= high) {
int mid = (low + high) / 2;
long midValue = data[mid];
if (midValue == key) {
return mid;
} else if (midValue > key) {
return binarySearch(data, key, low, mid - 1);
} else {
return binarySearch(data, key, mid + 1, high);
}
} else {
return -1;
}
}
@Nullable
public static MutableLongSetFactory getDefaultLongSetFactory() {
return defaultLongSetFactory;
}
public static void setDefaultLongSetFactory(MutableLongSetFactory defaultLongSetFactory) {
if (defaultLongSetFactory == null) {
throw new IllegalArgumentException("null defaultLongSetFactory");
}
LongSetUtil.defaultLongSetFactory = defaultLongSetFactory;
}
/**
* @return a new sparse int set which adds j to s
* @throws IllegalArgumentException if s == null
*/
public static LongSet add(LongSet s, int j) throws IllegalArgumentException {
if (s == null) {
throw new IllegalArgumentException("s == null");
}
if (s instanceof SparseLongSet) {
SparseLongSet sis = (SparseLongSet) s;
return SparseLongSet.add(sis, j);
} else {
// really slow. optimize as needed.
MutableSparseLongSet result = MutableSparseLongSet.make(s);
result.add(j);
return result;
}
}
}
| 7,023
| 31.82243
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/MultiModalIntVector.java
|
/*
* Copyright (c) 2009 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.util.Arrays;
/**
* an implementation of {@link IntVector} that uses a mix of backing arrays of type int, char, and
* byte array, in an attempt to save space for common data structures.
*/
public class MultiModalIntVector implements IntVector {
private static final float INITIAL_GROWTH_FACTOR = 1.5f;
private static final float MINIMUM_GROWTH_FACTOR = 1.1f;
private static final float DIFF_GROWTH_FACTOR = INITIAL_GROWTH_FACTOR - MINIMUM_GROWTH_FACTOR;
private float currentGrowthRate = INITIAL_GROWTH_FACTOR;
private static final int MAX_SIZE = 10000;
private static final int INITIAL_SIZE = 1;
int maxIndex = -1;
private int[] intStore = new int[0];
private short[] shortStore = new short[0];
private byte[] byteStore = new byte[0];
final int defaultValue;
public MultiModalIntVector(int defaultValue) {
this.defaultValue = defaultValue;
init(getInitialSize(), defaultValue);
}
private void init(int initialSize, int defaultValue) {
if (NumberUtility.isByte(defaultValue)) {
byteStore = new byte[initialSize];
byteStore[0] = (byte) defaultValue;
} else if (NumberUtility.isShort(defaultValue)) {
shortStore = new short[initialSize];
shortStore[0] = (short) defaultValue;
} else {
intStore = new int[initialSize];
intStore[0] = defaultValue;
}
}
public MultiModalIntVector(int defaultValue, int initialSize) {
if (initialSize <= 0) {
throw new IllegalArgumentException("invalid initialSize: " + initialSize);
}
this.defaultValue = defaultValue;
init(initialSize, defaultValue);
}
int getInitialSize() {
return INITIAL_SIZE;
}
float getGrowthFactor() {
return INITIAL_GROWTH_FACTOR;
}
/**
* Will determine a dynamic growth factor that depends on the current size of the array
*
* @return the new growth factor
*/
float getGrowthFactor(int size) {
if (currentGrowthRate >= MINIMUM_GROWTH_FACTOR) {
float val =
(float) (1 / (1 + Math.pow(Math.E, -1 * (((double) size / MAX_SIZE) * 12.0 - 6.0))));
currentGrowthRate = INITIAL_GROWTH_FACTOR - DIFF_GROWTH_FACTOR * val;
}
return currentGrowthRate;
}
@Override
public int get(int x) {
if (x < 0) {
throw new IllegalArgumentException("illegal x: " + x);
}
int index = x;
if (index < byteStore.length) {
return byteStore[index];
}
index -= byteStore.length;
if (index < shortStore.length) {
return shortStore[index];
}
index -= shortStore.length;
if (index < intStore.length) {
return intStore[index];
}
return defaultValue;
}
private int getStoreLength() {
return shortStore.length + byteStore.length + intStore.length;
}
@Override
public void set(int x, int value) {
if (x < 0) {
throw new IllegalArgumentException("illegal x: " + x);
}
if (x > MAX_SIZE) {
throw new IllegalArgumentException("x is too big: " + x);
}
maxIndex =
Math.max(maxIndex, x); // Find out if the new position is bigger than size of the array
handleMorph(x, value);
if (value == defaultValue) {
int length = getStoreLength();
if (x >= length) {
return;
} else {
add(value, x);
}
} else {
ensureCapacity(x, value);
add(value, x);
}
}
private void add(int value, int index) {
if (byteStore.length > index) {
byteStore[index] = (byte) value;
} else {
index -= byteStore.length;
if (shortStore.length > index) {
shortStore[index] = (short) value;
} else {
index -= shortStore.length;
intStore[index] = value;
}
}
}
private void handleMorph(int index, int value) {
if (NumberUtility.isShort(value)) {
if (index < byteStore.length) {
int newShortSize = byteStore.length - index + shortStore.length;
short[] newShortStore = new short[newShortSize];
byte[] newByteStore = new byte[index];
for (int i = index; i < byteStore.length; i++) {
newShortStore[i - index] = byteStore[i];
}
System.arraycopy(byteStore, 0, newByteStore, 0, index);
System.arraycopy(shortStore, 0, newShortStore, byteStore.length - index, shortStore.length);
byteStore = newByteStore;
shortStore = newShortStore;
}
} else if (!NumberUtility.isByte(value)) {
if (index < byteStore.length) {
int newShortSize = byteStore.length - index + intStore.length;
int[] newIntStore = new int[newShortSize];
for (int i = index; i < byteStore.length; i++) {
newIntStore[i - index] = byteStore[i];
}
byte[] newByteStore = new byte[index];
System.arraycopy(byteStore, 0, newByteStore, 0, index);
for (int i = 0; i < shortStore.length; i++) {
newIntStore[byteStore.length - 1 + i] = shortStore[i];
}
System.arraycopy(
intStore,
0,
newIntStore,
byteStore.length + shortStore.length - index,
intStore.length);
intStore = newIntStore;
byteStore = newByteStore;
shortStore = new short[0];
} else {
int newindex = index - byteStore.length;
if (newindex < shortStore.length) {
int newIntSize = shortStore.length - newindex + intStore.length;
int[] newIntStore = new int[newIntSize];
for (int i = newindex; i < shortStore.length; i++) {
newIntStore[i - newindex] = shortStore[i];
}
short[] newShortStore = new short[newindex];
System.arraycopy(shortStore, 0, newShortStore, 0, newindex);
System.arraycopy(intStore, 0, newIntStore, shortStore.length - newindex, intStore.length);
intStore = newIntStore;
shortStore = newShortStore;
}
}
}
}
/** make sure we can store to a particular index */
private void ensureCapacity(int capacity, int value) {
int length = getStoreLength();
// Value is an int
if (intStore.length > 0 || (!NumberUtility.isShort(value) && !NumberUtility.isByte(value))) {
// Need to increase the capacity of the array
if (capacity >= length) {
// Current array size
int[] old = intStore;
// New array size
int newSize =
1 + (int) (getGrowthFactor(length) * capacity) - byteStore.length - shortStore.length;
int[] newData = Arrays.copyOf(old, newSize);
Arrays.fill(newData, old.length, newSize, defaultValue);
intStore = newData;
}
} else if (shortStore.length > 0 || NumberUtility.isShort(value)) {
if (capacity >= length) {
short[] old = shortStore;
int newSize = 1 + (int) (getGrowthFactor(length) * capacity) - byteStore.length;
short[] newData = Arrays.copyOf(old, newSize);
Arrays.fill(newData, old.length, newSize, (short) defaultValue);
shortStore = newData;
}
} else {
if (capacity >= length) {
byte[] old = byteStore;
int newSize = 1 + (int) (getGrowthFactor(length) * capacity);
byte[] newData = Arrays.copyOf(old, newSize);
Arrays.fill(newData, old.length, newSize, (byte) defaultValue);
byteStore = newData;
}
}
}
@Override
public int getMaxIndex() {
return maxIndex;
}
public void print() {
final StringBuilder str = new StringBuilder();
for (byte element : byteStore) {
str.append(element).append(',');
}
for (short element : shortStore) {
str.append(element).append(',');
}
for (int element : intStore) {
str.append(element).append(',');
}
System.out.println(str);
}
}
| 8,171
| 30.430769
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/MutableIntSet.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
/** An {@link IntSet} that can be changed. */
public interface MutableIntSet extends IntSet {
/** Set the value of this to be the same as the value of set */
void copySet(IntSet set);
/**
* Add all members of set to this.
*
* @return true iff the value of this changes.
*/
boolean addAll(IntSet set);
/**
* Add an integer value to this set.
*
* @param i integer to add
* @return true iff the value of this changes.
*/
boolean add(int i);
/**
* Remove an integer from this set.
*
* @param i integer to remove
* @return true iff the value of this changes.
*/
boolean remove(int i);
/** remove all elements from this set */
void clear();
/** Intersect this with another set. */
void intersectWith(IntSet set);
/** */
boolean addAllInIntersection(IntSet other, IntSet filter);
}
| 1,263
| 23.307692
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/MutableIntSetFactory.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
/** An object that creates some flavor of mutable int set. */
public interface MutableIntSetFactory<T extends MutableIntSet> {
T make(int[] set);
T parse(String string);
T makeCopy(IntSet x);
T make();
}
| 625
| 26.217391
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/MutableLongSet.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
/** */
public interface MutableLongSet extends LongSet {
/** Set the value of this to be the same as the value of set */
void copySet(LongSet set);
/**
* Add all members of set to this.
*
* @return true iff the value of this changes.
*/
boolean addAll(LongSet set);
/**
* Add an integer value to this set.
*
* @return true iff the value of this changes.
*/
boolean add(long i);
/** Remove an integer from this set. */
void remove(long i);
/** Interset this with another set. */
void intersectWith(LongSet set);
}
| 972
| 23.948718
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/MutableLongSetFactory.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
/** An object that creates some flavor of mutable int set. */
public interface MutableLongSetFactory {
MutableLongSet make(long[] set);
MutableLongSet parse(String string);
MutableLongSet makeCopy(LongSet x);
MutableLongSet make();
}
| 656
| 26.375
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/MutableMapping.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.collections.HashMapFactory;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.stream.Stream;
import org.jspecify.annotations.Nullable;
/**
* A bit set mapping based on an object array. This is not terribly efficient, but is useful for
* prototyping.
*/
public class MutableMapping<T> implements OrdinalSetMapping<T>, Serializable {
private static final long serialVersionUID = 4011751404163534418L;
private static final int INITIAL_CAPACITY = 20;
private static final int MAX_SIZE = Integer.MAX_VALUE / 4;
public static <T> MutableMapping<T> make() {
return new MutableMapping<>();
}
private Object[] array;
private int nextIndex = 0;
/** A mapping from object to Integer. */
final HashMap<T, Integer> map = HashMapFactory.make();
/** @throws IllegalArgumentException if array is null */
@SuppressWarnings("unchecked")
public MutableMapping(final Object[] array) {
if (array == null) {
throw new IllegalArgumentException("array is null");
}
this.array = new Object[2 * array.length];
for (int i = 0; i < array.length; i++) {
this.array[i] = array[i];
map.put((T) array[i], i);
}
nextIndex = array.length;
}
protected MutableMapping() {
array = new Object[INITIAL_CAPACITY];
nextIndex = 0;
}
@Override
@SuppressWarnings("unchecked")
public T getMappedObject(int n) {
try {
return (T) array[n];
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("n out of range " + n, e);
}
}
@Override
public int getMappedIndex(@Nullable Object o) {
Integer I = map.get(o);
if (I == null) {
return -1;
} else {
return I;
}
}
@Override
public boolean hasMappedIndex(T o) {
return map.get(o) != null;
}
/**
* Add an object to the set of mapped objects.
*
* @return the integer to which the object is mapped.
*/
@Override
public int add(T o) {
Integer I = map.get(o);
if (I != null) {
return I;
}
map.put(o, nextIndex);
if (nextIndex >= array.length) {
array = Arrays.copyOf(array, 2 * array.length);
}
int result = nextIndex++;
array[result] = o;
return result;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
for (int i = 0; i < nextIndex; i++) {
result.append(i).append(" ").append(array[i]).append('\n');
}
return result.toString();
}
/** @see com.ibm.wala.util.intset.OrdinalSetMapping#iterator() */
@Override
public Iterator<T> iterator() {
return map.keySet().iterator();
}
@Override
public Stream<T> stream() {
return map.keySet().stream();
}
/** @see com.ibm.wala.util.intset.SparseIntSet#singleton(int) */
public OrdinalSet<T> makeSingleton(int i) {
return new OrdinalSet<>(SparseIntSet.singleton(i), this);
}
public void deleteMappedObject(T n) {
int index = getMappedIndex(n);
if (index != -1) {
array[index] = null;
map.remove(n);
}
}
public Collection<T> getObjects() {
return Collections.unmodifiableCollection(map.keySet());
}
/** Replace a in this mapping with b. */
public void replace(T a, T b) throws IllegalArgumentException {
int i = getMappedIndex(a);
if (i == -1) {
throw new IllegalArgumentException("first element does not exist in map");
}
map.remove(a);
map.put(b, i);
array[i] = b;
}
/** Add an object to the set of mapped objects at index i. */
public void put(int i, T o) {
if (i < 0 || i > MAX_SIZE) {
throw new IllegalArgumentException("invalid i: " + i);
}
Integer I = i;
map.put(o, I);
if (i >= array.length) {
array = Arrays.copyOf(array, 2 * i);
}
array[i] = o;
nextIndex = Math.max(nextIndex, i + 1);
}
@Override
public int getMaximumIndex() {
return nextIndex - 1;
}
@Override
public int getSize() {
return map.size();
}
}
| 4,533
| 23.775956
| 96
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/MutableSharedBitVectorIntSet.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.collections.CompoundIntIterator;
import com.ibm.wala.util.collections.EmptyIntIterator;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/**
* The shared bit vector implementation described by [Heintze 1999] TODO: much optimization
* possible.
*/
public class MutableSharedBitVectorIntSet implements MutableIntSet {
private static final long serialVersionUID = -6630888692508092370L;
private static final boolean DEBUG = false;
private static final boolean PARANOID = false;
private static final int OVERFLOW = 20;
@Nullable private MutableSparseIntSet privatePart;
@Nullable private BitVectorIntSet sharedPart;
/** */
public MutableSharedBitVectorIntSet() {}
/** @throws IllegalArgumentException if set is null */
public MutableSharedBitVectorIntSet(MutableSharedBitVectorIntSet set) {
if (set == null) {
throw new IllegalArgumentException("set is null");
}
if (set.privatePart != null) {
this.privatePart = MutableSparseIntSet.make(set.privatePart);
}
this.sharedPart = set.sharedPart;
}
/** @throws IllegalArgumentException if s is null */
public MutableSharedBitVectorIntSet(SparseIntSet s) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
if (s.size() == 0) {
return;
}
this.privatePart = MutableSparseIntSet.make(s);
checkOverflow();
if (PARANOID) {
checkIntegrity();
}
}
/** @throws IllegalArgumentException if s is null */
public MutableSharedBitVectorIntSet(BitVectorIntSet s) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
copyValue(s);
if (PARANOID) {
checkIntegrity();
}
}
private void copyValue(BitVectorIntSet s) {
if (s.size() == 0) {
sharedPart = null;
privatePart = null;
} else if (s.size() < OVERFLOW) {
sharedPart = null;
privatePart = MutableSparseIntSet.make(s);
} else {
sharedPart = BitVectorRepository.findOrCreateSharedSubset(s);
if (sharedPart.size() == s.size()) {
privatePart = null;
} else {
BitVectorIntSet temp = new BitVectorIntSet(s);
temp.removeAll(sharedPart);
if (!temp.isEmpty()) {
privatePart = MutableSparseIntSet.make(temp);
} else {
privatePart = null;
}
}
}
if (PARANOID) {
checkIntegrity();
}
}
/** */
private void checkIntegrity() {
assert privatePart == null || !privatePart.isEmpty();
//noinspection AssertWithSideEffects
assert sharedPart == null || !sharedPart.isEmpty();
if (privatePart != null && sharedPart != null) {
assert privatePart.intersection(sharedPart).isEmpty();
}
}
/** */
private void checkOverflow() {
if (PARANOID) {
checkIntegrity();
}
if (privatePart != null && privatePart.size() > OVERFLOW) {
BitVectorIntSet temp;
if (sharedPart == null) {
temp = new BitVectorIntSet(privatePart);
} else {
temp = new BitVectorIntSet(sharedPart);
// when we call findOrCreateSharedSubset, we will ask size() on temp.
// so use addAll instead of addAllOblivious: which incrementally
// updates the population count.
temp.addAll(privatePart);
}
sharedPart = BitVectorRepository.findOrCreateSharedSubset(temp);
temp.removeAll(sharedPart);
if (!temp.isEmpty()) privatePart = MutableSparseIntSet.make(temp);
else privatePart = null;
}
if (PARANOID) {
checkIntegrity();
}
}
/** @see com.ibm.wala.util.intset.IntSet#contains(int) */
@Override
public boolean contains(int i) {
if (privatePart != null && privatePart.contains(i)) {
return true;
}
if (sharedPart != null && sharedPart.contains(i)) {
return true;
}
return false;
}
/** @see com.ibm.wala.util.intset.IntSet#intersection(com.ibm.wala.util.intset.IntSet) */
@Override
public IntSet intersection(IntSet that) {
if (that == null) {
throw new IllegalArgumentException("null that");
}
if (that instanceof MutableSharedBitVectorIntSet) {
return intersection((MutableSharedBitVectorIntSet) that);
} else if (that instanceof BitVectorIntSet) {
MutableSharedBitVectorIntSet m = new MutableSharedBitVectorIntSet((BitVectorIntSet) that);
return intersection(m);
} else if (that instanceof SparseIntSet) {
BitVectorIntSet bv = new BitVectorIntSet(that);
return intersection(bv);
} else {
// really slow. optimize as needed.
BitVectorIntSet result = new BitVectorIntSet();
for (IntIterator it = intIterator(); it.hasNext(); ) {
int x = it.next();
if (that.contains(x)) {
result.add(x);
}
}
return result;
}
}
/** @see com.ibm.wala.util.intset.IntSet#union(com.ibm.wala.util.intset.IntSet) */
@Override
public IntSet union(IntSet that) {
MutableSharedBitVectorIntSet temp = new MutableSharedBitVectorIntSet();
temp.addAll(this);
temp.addAll(that);
return temp;
}
/** @see com.ibm.wala.util.intset.IntSet#intersection(com.ibm.wala.util.intset.IntSet) */
public IntSet intersection(MutableSharedBitVectorIntSet that) {
MutableSparseIntSet t = makeSparseCopy();
t.intersectWith(that);
MutableSharedBitVectorIntSet result = new MutableSharedBitVectorIntSet(t);
if (PARANOID) {
checkIntegrity();
}
return result;
}
/** @see com.ibm.wala.util.intset.IntSet#isEmpty() */
@Override
public boolean isEmpty() {
return privatePart == null && sharedPart == null;
}
/** @see com.ibm.wala.util.intset.IntSet#size() */
@Override
public int size() {
int result = 0;
result += (privatePart == null) ? 0 : privatePart.size();
result += (sharedPart == null) ? 0 : sharedPart.size();
return result;
}
/** @see IntSet#intIterator() */
@Override
public IntIterator intIterator() {
if (privatePart == null) {
return (sharedPart == null) ? EmptyIntIterator.instance() : sharedPart.intIterator();
} else {
return (sharedPart == null)
? privatePart.intIterator()
: new CompoundIntIterator(privatePart.intIterator(), sharedPart.intIterator());
}
}
/** @see com.ibm.wala.util.intset.IntSet#foreach(com.ibm.wala.util.intset.IntSetAction) */
@Override
public void foreach(IntSetAction action) {
if (privatePart != null) {
privatePart.foreach(action);
}
if (sharedPart != null) {
sharedPart.foreach(action);
}
}
/**
* @see com.ibm.wala.util.intset.IntSet#foreachExcluding(com.ibm.wala.util.intset.IntSet,
* com.ibm.wala.util.intset.IntSetAction)
*/
@Override
public void foreachExcluding(IntSet X, IntSetAction action) {
if (X instanceof MutableSharedBitVectorIntSet) {
foreachExcludingInternal((MutableSharedBitVectorIntSet) X, action);
} else {
foreachExcludingGeneral(X, action);
}
}
/**
* @see com.ibm.wala.util.intset.IntSet#foreachExcluding(com.ibm.wala.util.intset.IntSet,
* com.ibm.wala.util.intset.IntSetAction)
*/
private void foreachExcludingInternal(MutableSharedBitVectorIntSet X, IntSetAction action) {
if (sameSharedPart(this, X)) {
if (privatePart != null) {
if (X.privatePart != null) {
privatePart.foreachExcluding(X.privatePart, action);
} else {
privatePart.foreach(action);
}
}
} else {
if (privatePart != null) {
privatePart.foreachExcluding(X, action);
}
if (sharedPart != null) {
sharedPart.foreachExcluding(X.makeDenseCopy(), action);
}
}
}
/**
* @see com.ibm.wala.util.intset.IntSet#foreachExcluding(com.ibm.wala.util.intset.IntSet,
* com.ibm.wala.util.intset.IntSetAction)
*/
private void foreachExcludingGeneral(IntSet X, IntSetAction action) {
if (privatePart != null) {
privatePart.foreachExcluding(X, action);
}
if (sharedPart != null) {
sharedPart.foreachExcluding(X, action);
}
}
/** @see com.ibm.wala.util.intset.IntSet#max() */
@Override
public int max() {
int result = -1;
if (privatePart != null && privatePart.size() > 0) {
result = Math.max(result, privatePart.max());
}
if (sharedPart != null) {
result = Math.max(result, sharedPart.max());
}
return result;
}
/** @see com.ibm.wala.util.intset.IntSet#sameValue(com.ibm.wala.util.intset.IntSet) */
@Override
public boolean sameValue(IntSet that) throws IllegalArgumentException, UnimplementedError {
if (that == null) {
throw new IllegalArgumentException("that == null");
}
if (that instanceof MutableSharedBitVectorIntSet) {
return sameValue((MutableSharedBitVectorIntSet) that);
} else if (that instanceof SparseIntSet) {
return sameValue((SparseIntSet) that);
} else if (that instanceof BimodalMutableIntSet) {
return that.sameValue(makeSparseCopy());
} else if (that instanceof BitVectorIntSet) {
return sameValue((BitVectorIntSet) that);
} else if (that instanceof SemiSparseMutableIntSet) {
return that.sameValue(this);
} else {
Assertions.UNREACHABLE("unexpected class " + that.getClass());
return false;
}
}
/** @see com.ibm.wala.util.intset.IntSet#sameValue(com.ibm.wala.util.intset.IntSet) */
private boolean sameValue(SparseIntSet that) {
if (size() != that.size()) {
return false;
}
if (sharedPart == null) {
if (privatePart == null)
/* both parts empty, and that has same (i.e. 0) size */
return true;
else return privatePart.sameValue(that);
} else {
/* sharedPart != null */
return makeSparseCopy().sameValue(that);
}
}
private boolean sameValue(BitVectorIntSet that) {
if (size() != that.size()) {
return false;
}
if (sharedPart == null) {
if (privatePart == null)
/* both parts empty, and that has same (i.e. 0) size */
return true;
else
// shared part is null and size is same, so number of bits is low
return that.makeSparseCopy().sameValue(privatePart);
} else {
if (privatePart == null) return sharedPart.sameValue(that);
else
/* sharedPart != null */
return makeDenseCopy().sameValue(that);
}
}
/** @see com.ibm.wala.util.intset.IntSet#sameValue(com.ibm.wala.util.intset.IntSet) */
private boolean sameValue(MutableSharedBitVectorIntSet that) {
if (size() != that.size()) {
return false;
}
if (sharedPart == null) {
if (privatePart == null) {
/* we must have size() == that.size() == 0 */
return true;
} else {
/* sharedPart == null, privatePart != null */
if (that.sharedPart == null) {
if (that.privatePart == null) {
return privatePart.isEmpty();
} else {
return privatePart.sameValue(that.privatePart);
}
} else {
/* sharedPart = null, privatePart != null, that.sharedPart != null */
if (that.privatePart == null) {
return privatePart.sameValue(that.sharedPart);
} else {
BitVectorIntSet temp = new BitVectorIntSet(that.sharedPart);
temp.addAllOblivious(that.privatePart);
return privatePart.sameValue(temp);
}
}
}
} else {
/* sharedPart != null */
if (privatePart == null) {
if (that.privatePart == null) {
return sharedPart.sameValue(that.sharedPart);
} else {
/* privatePart == null, sharedPart != null, that.privatePart != null */
if (that.sharedPart == null) {
return sharedPart.sameValue(that.privatePart);
} else {
MutableSparseIntSet t = that.makeSparseCopy();
return sharedPart.sameValue(t);
}
}
} else {
/* sharedPart != null , privatePart != null */
if (that.sharedPart == null) {
Assertions.UNREACHABLE();
return false;
} else {
/* that.sharedPart != null */
if (that.privatePart == null) {
SparseIntSet s = makeSparseCopy();
return s.sameValue(that.sharedPart);
} else {
/* that.sharedPart != null, that.privatePart != null */
/* assume reference equality for canonical shared part */
if (sharedPart == that.sharedPart) {
return privatePart.sameValue(that.privatePart);
} else {
SparseIntSet s1 = makeSparseCopy();
SparseIntSet s2 = that.makeSparseCopy();
return s1.sameValue(s2);
}
}
}
}
}
}
/** @see com.ibm.wala.util.intset.IntSet#isSubset(com.ibm.wala.util.intset.IntSet) */
@Override
public boolean isSubset(IntSet that) {
if (that == null) {
throw new IllegalArgumentException("null that");
}
if (that instanceof MutableSharedBitVectorIntSet) {
return isSubset((MutableSharedBitVectorIntSet) that);
} else {
// really slow. optimize as needed.
for (IntIterator it = intIterator(); it.hasNext(); ) {
if (!that.contains(it.next())) {
return false;
}
}
return true;
}
}
/** @see com.ibm.wala.util.intset.IntSet#sameValue(com.ibm.wala.util.intset.IntSet) */
private boolean isSubset(MutableSharedBitVectorIntSet that) {
if (size() > that.size()) {
return false;
}
if (sharedPart == null) {
if (privatePart == null) {
return true;
} else {
if (that.sharedPart == null) {
return privatePart.isSubset(that.privatePart);
} else {
/* sharedPart == null, that.sharedPart != null */
if (that.privatePart == null) {
return privatePart.isSubset(that.sharedPart);
} else {
SparseIntSet s1 = that.makeSparseCopy();
return privatePart.isSubset(s1);
}
}
}
} else {
/* sharedPart != null */
if (privatePart == null) {
/* sharedPart != null, privatePart == null */
if (that.privatePart == null) {
if (that.sharedPart == null) {
return false;
} else {
return sharedPart.isSubset(that.sharedPart);
}
} else {
if (that.sharedPart == null) {
return sharedPart.isSubset(that.privatePart);
} else {
SparseIntSet s1 = that.makeSparseCopy();
return sharedPart.isSubset(s1);
}
}
} else {
/* sharedPart != null, privatePart != null */
if (that.privatePart == null) {
return privatePart.isSubset(that.sharedPart) && sharedPart.isSubset(that.sharedPart);
} else {
/* sharedPart != null, privatePart!= null, that.privatePart != null */
if (that.sharedPart == null) {
return privatePart.isSubset(that.privatePart) && sharedPart.isSubset(that.privatePart);
} else {
/*
* sharedPart != null, privatePart!= null, that.privatePart != null, that.sharedPart != null
*/
if (sharedPart.isSubset(that.sharedPart)) {
if (privatePart.isSubset(that.privatePart)) {
return true;
} else {
SparseIntSet s1 = that.makeSparseCopy();
return privatePart.isSubset(s1);
}
} else {
/* !sharedPart.isSubset(that.sharedPart) */
BitVectorIntSet temp = new BitVectorIntSet(sharedPart);
temp.removeAll(that.sharedPart);
if (temp.isSubset(that.privatePart)) {
/* sharedPart.isSubset(that) */
if (privatePart.isSubset(that.privatePart)) {
return true;
} else {
MutableSparseIntSet t = MutableSparseIntSet.make(privatePart);
t.removeAll(that.privatePart);
if (t.isSubset(that.sharedPart)) {
return true;
} else {
return false;
}
}
} else {
/*
* !((sharedPart-that.sharedPart).isSubset(that.privatePart)) i.e some bit in my shared part is in neither that's
* sharedPart nor that's privatePart, hence I am not a subset of that
*/
return false;
}
}
}
}
}
}
}
@Override
public void copySet(IntSet set) {
if (set instanceof MutableSharedBitVectorIntSet) {
MutableSharedBitVectorIntSet other = (MutableSharedBitVectorIntSet) set;
if (other.privatePart != null) {
this.privatePart = MutableSparseIntSet.make(other.privatePart);
} else {
this.privatePart = null;
}
this.sharedPart = other.sharedPart;
} else {
// really slow. optimize as needed.
clear();
addAll(set);
}
if (PARANOID) {
checkIntegrity();
}
}
@Override
public boolean addAll(IntSet set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (set instanceof MutableSharedBitVectorIntSet) {
boolean result = addAll((MutableSharedBitVectorIntSet) set);
if (PARANOID) {
checkIntegrity();
}
return result;
} else if (set instanceof SparseIntSet) {
boolean result = addAllInternal((SparseIntSet) set);
if (PARANOID) {
checkIntegrity();
}
return result;
} else if (set instanceof BitVectorIntSet) {
boolean result = addAllInternal((BitVectorIntSet) set);
if (PARANOID) {
checkIntegrity();
}
return result;
} else if (set instanceof DebuggingMutableIntSet) {
SparseIntSet temp = new SparseIntSet(set);
boolean result = addAllInternal(temp);
if (PARANOID) {
checkIntegrity();
}
return result;
} else {
// really slow. optimize as needed.
boolean result = false;
for (IntIterator it = set.intIterator(); it.hasNext(); ) {
int x = it.next();
if (!contains(x)) {
result = true;
add(x);
}
}
return result;
}
}
private boolean addAllInternal(BitVectorIntSet set) {
// should have hijacked this case before getting here!
assert sharedPart != set;
if (privatePart == null) {
if (sharedPart == null) {
copyValue(set);
return !set.isEmpty();
}
}
BitVectorIntSet temp = makeDenseCopy();
boolean result = temp.addAll(set);
copyValue(temp);
return result;
}
@NullUnmarked
private boolean addAllInternal(@Nullable SparseIntSet set) {
if (privatePart == null) {
if (sharedPart == null) {
if (!set.isEmpty()) {
privatePart = MutableSparseIntSet.make(set);
sharedPart = null;
checkOverflow();
return true;
} else {
return false;
}
} else {
privatePart = MutableSparseIntSet.make(set);
privatePart.removeAll(sharedPart);
if (privatePart.isEmpty()) {
privatePart = null;
return false;
} else {
checkOverflow();
return true;
}
}
} else {
/* privatePart != null */
if (sharedPart == null) {
boolean result = privatePart.addAll(set);
checkOverflow();
return result;
} else {
int oldSize = privatePart.size();
privatePart.addAll(set);
privatePart.removeAll(sharedPart);
boolean result = privatePart.size() > oldSize;
checkOverflow();
return result;
}
}
}
private boolean addAll(MutableSharedBitVectorIntSet set) {
if (set.isEmpty()) {
return false;
}
if (isEmpty()) {
if (set.privatePart != null) {
privatePart = MutableSparseIntSet.make(set.privatePart);
}
sharedPart = set.sharedPart;
return true;
}
if (set.sharedPart == null) {
return addAllInternal(set.privatePart);
} else {
// set.sharedPart != null
if (sameSharedPart(this, set)) {
if (set.privatePart == null) {
return false;
} else {
return addAllInternal(set.privatePart);
}
} else {
// !sameSharedPart
if (set.privatePart == null) {
if (sharedPart == null || sharedPart.isSubset(set.sharedPart)) {
// a heuristic that should be profitable if this condition usually
// holds.
int oldSize = size();
if (privatePart != null) {
privatePart.removeAll(set.sharedPart);
privatePart = privatePart.isEmpty() ? null : privatePart;
}
sharedPart = set.sharedPart;
return size() > oldSize;
} else {
BitVectorIntSet temp = makeDenseCopy();
boolean b = temp.addAll(set.sharedPart);
if (b) {
// a heuristic: many times these are the same value,
// so avoid looking up the shared subset in the bv repository
if (temp.sameValue(set.sharedPart)) {
this.privatePart = null;
this.sharedPart = set.sharedPart;
} else {
copyValue(temp);
}
}
return b;
}
} else {
// set.privatePart != null;
BitVectorIntSet temp = makeDenseCopy();
BitVectorIntSet other = set.makeDenseCopy();
boolean b = temp.addAll(other);
if (b) {
// a heuristic: many times these are the same value,
// so avoid looking up the shared subset in the bv repository
if (temp.sameValue(other)) {
this.privatePart = MutableSparseIntSet.make(set.privatePart);
this.sharedPart = set.sharedPart;
} else {
// System.err.println("COPY " + this + " " + set);
copyValue(temp);
}
}
return b;
}
}
}
}
@Override
public boolean add(int i) {
if (privatePart == null) {
if (sharedPart == null) {
privatePart = MutableSparseIntSet.makeEmpty();
privatePart.add(i);
return true;
} else {
if (sharedPart.contains(i)) {
return false;
} else {
privatePart = MutableSparseIntSet.makeEmpty();
privatePart.add(i);
return true;
}
}
} else {
if (sharedPart == null) {
boolean result = privatePart.add(i);
checkOverflow();
return result;
} else {
if (sharedPart.contains(i)) {
return false;
} else {
boolean result = privatePart.add(i);
checkOverflow();
return result;
}
}
}
}
@Override
public boolean remove(int i) {
if (privatePart != null) {
if (privatePart.contains(i)) {
privatePart.remove(i);
if (privatePart.size() == 0) {
privatePart = null;
}
return true;
}
}
if (sharedPart != null) {
if (sharedPart.contains(i)) {
privatePart = makeSparseCopy();
privatePart.remove(i);
if (privatePart.size() == 0) {
privatePart = null;
}
sharedPart = null;
checkOverflow();
return true;
}
}
return false;
}
@Override
public void intersectWith(IntSet set) {
if (set instanceof MutableSharedBitVectorIntSet) {
intersectWithInternal((MutableSharedBitVectorIntSet) set);
} else if (set instanceof BitVectorIntSet) {
intersectWithInternal(new MutableSharedBitVectorIntSet((BitVectorIntSet) set));
} else {
// this is really slow. optimize as needed.
for (IntIterator it = intIterator(); it.hasNext(); ) {
int x = it.next();
if (!set.contains(x)) {
remove(x);
}
}
}
if (DEBUG) {
if (privatePart != null && sharedPart != null)
assert privatePart.intersection(sharedPart).isEmpty();
}
}
private void intersectWithInternal(MutableSharedBitVectorIntSet set) {
if (sharedPart != null) {
if (sameSharedPart(this, set)) {
// no need to intersect shared part
if (privatePart != null) {
if (set.privatePart == null) {
privatePart = null;
} else {
privatePart.intersectWith(set.privatePart);
if (privatePart.isEmpty()) {
privatePart = null;
}
}
}
} else {
// not the same shared part
if (set.sharedPart == null) {
if (set.privatePart == null) {
privatePart = null;
sharedPart = null;
} else {
MutableSparseIntSet temp = MutableSparseIntSet.make(set.privatePart);
temp.intersectWith(this);
sharedPart = null;
if (temp.isEmpty()) {
privatePart = null;
} else {
privatePart = temp;
checkOverflow();
}
}
} else {
// set.sharedPart != null
BitVectorIntSet b = makeDenseCopy();
b.intersectWith(set.makeDenseCopy());
copyValue(b);
}
}
} else {
if (privatePart != null) {
privatePart.intersectWith(set);
if (privatePart.isEmpty()) {
privatePart = null;
}
}
}
if (PARANOID) {
checkIntegrity();
}
}
public static boolean sameSharedPart(
MutableSharedBitVectorIntSet a, MutableSharedBitVectorIntSet b) {
if (b == null) {
throw new IllegalArgumentException("b is null");
}
if (a == null) {
throw new IllegalArgumentException("a is null");
}
return a.sharedPart == b.sharedPart;
}
@Override
public String toString() {
return makeSparseCopy().toString();
}
/** Warning: inefficient; this should not be called often. */
MutableSparseIntSet makeSparseCopy() {
if (privatePart == null) {
if (sharedPart == null) {
return MutableSparseIntSet.makeEmpty();
} else {
return new MutableSparseIntSetFactory().makeCopy(sharedPart);
}
} else {
if (sharedPart == null) {
return MutableSparseIntSet.make(privatePart);
} else {
/* privatePart != null, sharedPart != null */
MutableSparseIntSet result = MutableSparseIntSet.make(privatePart);
result.addAll(sharedPart);
return result;
}
}
}
/** */
BitVectorIntSet makeDenseCopy() {
if (privatePart == null) {
if (sharedPart == null) {
return new BitVectorIntSet();
} else {
return new BitVectorIntSet(sharedPart);
}
} else {
if (sharedPart == null) {
return new BitVectorIntSet(privatePart);
} else {
BitVectorIntSet temp = new BitVectorIntSet(sharedPart);
temp.addAllOblivious(privatePart);
return temp;
}
}
}
public boolean hasSharedPart() {
return sharedPart != null;
}
/** @see com.ibm.wala.util.intset.IntSet#containsAny(com.ibm.wala.util.intset.IntSet) */
@Override
public boolean containsAny(IntSet set) {
if (set instanceof MutableSharedBitVectorIntSet) {
MutableSharedBitVectorIntSet other = (MutableSharedBitVectorIntSet) set;
if (sharedPart != null) {
// an optimization to make life easier on the underlying
// bitvectorintsets
if (other.sharedPart != null && sharedPart.containsAny(other.sharedPart)) {
return true;
}
if (other.privatePart != null && sharedPart.containsAny(other.privatePart)) {
return true;
}
}
} else {
if (sharedPart != null && sharedPart.containsAny(set)) {
return true;
}
}
if (privatePart != null && privatePart.containsAny(set)) {
return true;
}
return false;
}
@Override
public boolean addAllInIntersection(IntSet other, IntSet filter) {
if (other instanceof MutableSharedBitVectorIntSet) {
return addAllInIntersectionInternal((MutableSharedBitVectorIntSet) other, filter);
}
return addAllInIntersectionGeneral(other, filter);
}
/** */
private boolean addAllInIntersectionGeneral(IntSet other, IntSet filter) {
BitVectorIntSet o = new BitVectorIntSet(other);
o.intersectWith(filter);
return addAll(o);
}
/** */
private boolean addAllInIntersectionInternal(MutableSharedBitVectorIntSet other, IntSet filter) {
if (other.sharedPart == null) {
if (other.privatePart == null) {
return false;
} else {
// other.sharedPart == null, other.privatePart != null
return addAllInIntersectionInternal(other.privatePart, filter);
}
} else {
// other.sharedPart != null
if (sharedPart == other.sharedPart) {
// no need to add in other.sharedPart
if (other.privatePart == null) {
return false;
} else {
return addAllInIntersectionInternal(other.privatePart, filter);
}
} else {
MutableSharedBitVectorIntSet o = new MutableSharedBitVectorIntSet(other);
o.intersectWith(filter);
return addAll(o);
}
}
}
private boolean addAllInIntersectionInternal(SparseIntSet other, IntSet filter) {
if (sharedPart == null) {
if (privatePart == null) {
privatePart = MutableSparseIntSet.make(other);
privatePart.intersectWith(filter);
if (privatePart.size() == 0) {
privatePart = null;
}
checkOverflow();
return size() > 0;
} else {
// sharedPart == null, privatePart != null
boolean result = privatePart.addAllInIntersection(other, filter);
checkOverflow();
return result;
}
} else {
// sharedPart != null
if (privatePart == null) {
privatePart = MutableSparseIntSet.make(sharedPart);
sharedPart = null;
boolean result = privatePart.addAllInIntersection(other, filter);
checkOverflow();
return result;
} else {
// sharedPart != null, privatePart != null
// note that "other" is likely small
MutableSparseIntSet temp = MutableSparseIntSet.make(other);
temp.intersectWith(filter);
return addAll(temp);
}
}
}
@Override
public void clear() {
privatePart = null;
sharedPart = null;
}
}
| 31,474
| 29.647517
| 129
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/MutableSharedBitVectorIntSetFactory.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
/** A factory for mutable shared bit vector int sets */
public class MutableSharedBitVectorIntSetFactory
implements MutableIntSetFactory<MutableSharedBitVectorIntSet> {
private final MutableSparseIntSetFactory sparseFactory = new MutableSparseIntSetFactory();
@Override
public MutableSharedBitVectorIntSet make(int[] set) {
SparseIntSet s = sparseFactory.make(set);
return new MutableSharedBitVectorIntSet(s);
}
@Override
public MutableSharedBitVectorIntSet parse(String string) throws NumberFormatException {
SparseIntSet s = sparseFactory.parse(string);
return new MutableSharedBitVectorIntSet(s);
}
@Override
public MutableSharedBitVectorIntSet makeCopy(IntSet x) throws IllegalArgumentException {
if (x == null) {
throw new IllegalArgumentException("x == null");
}
if (x instanceof MutableSharedBitVectorIntSet) {
return new MutableSharedBitVectorIntSet((MutableSharedBitVectorIntSet) x);
} else if (x instanceof SparseIntSet) {
return new MutableSharedBitVectorIntSet((SparseIntSet) x);
} else if (x instanceof BitVectorIntSet) {
return new MutableSharedBitVectorIntSet((BitVectorIntSet) x);
} else if (x instanceof DebuggingMutableIntSet) {
return new MutableSharedBitVectorIntSet(new SparseIntSet(x));
} else {
// really slow. optimize as needed.
MutableSharedBitVectorIntSet result = new MutableSharedBitVectorIntSet();
for (IntIterator it = x.intIterator(); it.hasNext(); ) {
result.add(it.next());
}
return result;
}
}
@Override
public MutableSharedBitVectorIntSet make() {
return new MutableSharedBitVectorIntSet();
}
}
| 2,097
| 34.559322
| 92
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/MutableSparseIntSet.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.debug.Assertions;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/**
* A sparse ordered, mutable duplicate-free, fully-encapsulated set of integers. Instances are not
* canonical, except for EMPTY.
*
* <p>This implementation will be inefficient if these sets get large.
*
* <p>TODO: even for small sets, we probably want to work on this to reduce the allocation activity.
*/
public class MutableSparseIntSet extends SparseIntSet implements MutableIntSet {
private static final long serialVersionUID = 1479453398189400698L;
/** If forced to grow the backing array .. then by how much */
private static final float EXPANSION_FACTOR = 1.5f;
/** Default initial size for a backing array with one element */
private static final int INITIAL_NONEMPTY_SIZE = 2;
/** a debug flag, used to trap when a set gets large */
private static final boolean DEBUG_LARGE = false;
private static final int TRAP_SIZE = 1000;
protected MutableSparseIntSet(@Nullable IntSet set) {
super();
copySet(set);
}
protected MutableSparseIntSet(int[] backingStore) {
super(backingStore);
}
/** Create an empty set with a non-zero capacity */
private MutableSparseIntSet(int initialCapacity) throws IllegalArgumentException {
super(new int[initialCapacity]);
size = 0;
if (initialCapacity <= 0) {
throw new IllegalArgumentException("initialCapacity must be positive");
}
}
protected MutableSparseIntSet() {
super();
}
@Override
public void clear() {
size = 0;
}
/** */
@NullUnmarked
@Override
public boolean remove(int value) {
if (elements != null) {
int remove;
for (remove = 0; remove < size; remove++) {
if (elements[remove] >= value) {
break;
}
}
if (remove == size) {
return false;
}
if (elements[remove] == value) {
if (size == 1) {
elements = null;
size = 0;
} else {
if (remove < size) {
System.arraycopy(elements, remove + 1, elements, remove, size - remove - 1);
}
size--;
}
return true;
}
}
return false;
}
/** */
public int getInitialNonEmptySize() {
return INITIAL_NONEMPTY_SIZE;
}
public float getExpansionFactor() {
return EXPANSION_FACTOR;
}
/** @return true iff this value changes */
@Override
@SuppressWarnings("unused")
public boolean add(int value) {
if (elements == null) {
elements = new int[getInitialNonEmptySize()];
size = 1;
elements[0] = value;
} else {
int insert;
if (size == 0 || value > max()) {
insert = size;
} else if (value == max()) {
return false;
} else {
for (insert = 0; insert < size; insert++) {
if (elements[insert] >= value) {
break;
}
}
}
if (insert < size && elements[insert] == value) {
return false;
}
if (size < elements.length - 1) {
// there's space in the backing elements array. Use it.
if (size != insert) {
System.arraycopy(elements, insert, elements, insert + 1, size - insert);
}
size++;
elements[insert] = value;
} else {
// no space left. expand the backing array.
float newExtent = elements.length * getExpansionFactor() + 1;
int[] tmp = new int[(int) newExtent];
System.arraycopy(elements, 0, tmp, 0, insert);
if (size != insert) {
System.arraycopy(elements, insert, tmp, insert + 1, size - insert);
}
tmp[insert] = value;
size++;
elements = tmp;
}
if (DEBUG_LARGE && size() > TRAP_SIZE) {
Assertions.UNREACHABLE();
}
}
return true;
}
/** @throws IllegalArgumentException if that == null */
@NullUnmarked
@Override
@SuppressWarnings("unused")
public void copySet(@Nullable IntSet that) throws IllegalArgumentException {
if (that == null) {
throw new IllegalArgumentException("that == null");
}
if (that instanceof SparseIntSet) {
SparseIntSet set = (SparseIntSet) that;
if (set.elements != null) {
// SJF: clone is performance problem. don't use it.
// elements = set.elements.clone();
elements = new int[set.elements.length];
System.arraycopy(set.elements, 0, elements, 0, set.size);
size = set.size;
} else {
elements = null;
size = 0;
}
} else {
elements = new int[that.size()];
size = that.size();
that.foreach(
new IntSetAction() {
private int index = 0;
@Override
public void act(int i) {
elements[index++] = i;
}
});
}
if (DEBUG_LARGE && size() > TRAP_SIZE) {
Assertions.UNREACHABLE();
}
}
@Override
public void intersectWith(IntSet set) {
if (set == null) {
throw new IllegalArgumentException("null set");
}
if (set instanceof SparseIntSet) {
intersectWith((SparseIntSet) set);
} else {
int j = 0;
for (int i = 0; i < size; i++)
if (set.contains(elements[i])) {
elements[j++] = elements[i];
}
size = j;
}
}
@NullUnmarked
public void intersectWith(SparseIntSet set) {
if (set == null) {
throw new IllegalArgumentException("null set");
}
SparseIntSet that = set;
if (this.isEmpty()) {
return;
} else if (that.isEmpty()) {
elements = null;
size = 0;
return;
} else if (this.equals(that)) {
return;
}
// some simple optimizations
if (size == 1) {
if (that.contains(elements[0])) {
return;
} else {
elements = null;
size = 0;
return;
}
}
if (that.size == 1) {
if (contains(that.elements[0])) {
if (size > getInitialNonEmptySize()) {
elements = new int[getInitialNonEmptySize()];
}
size = 1;
elements[0] = that.elements[0];
return;
} else {
elements = null;
size = 0;
return;
}
}
int[] ar = this.elements;
int ai = 0;
int al = size;
int[] br = that.elements;
int bi = 0;
int bl = that.size;
int[] cr = null; // allocate on demand
int ci = 0;
while (ai < al && bi < bl) {
int cmp = (ar[ai] - br[bi]);
// (accept element only on a match)
if (cmp > 0) { // a greater
bi++;
} else if (cmp < 0) { // b greater
ai++;
} else {
if (cr == null) {
cr = new int[al]; // allocate enough (i.e. too much)
}
cr[ci++] = ar[ai];
ai++;
bi++;
}
}
// now compact cr to 'just enough'
size = ci;
elements = cr;
return;
}
/**
* Add all elements from another int set.
*
* @return true iff this set changes
* @throws IllegalArgumentException if set == null
*/
@Override
@SuppressWarnings("unused")
public boolean addAll(IntSet set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (set instanceof SparseIntSet) {
return addAll((SparseIntSet) set);
} else {
int oldSize = size;
set.foreach(
i -> {
if (!contains(i)) add(i);
});
if (DEBUG_LARGE && size() > TRAP_SIZE) {
Assertions.UNREACHABLE();
}
return size != oldSize;
}
}
/**
* Add all elements from another int set.
*
* @return true iff this set changes
*/
public boolean addAll(@Nullable SparseIntSet that) {
if (that == null) {
throw new IllegalArgumentException("null that");
}
if (this.isEmpty()) {
copySet(that);
return !that.isEmpty();
} else if (that.isEmpty()) {
return false;
} else if (this.equals(that)) {
return false;
}
// common-case optimization
if (that.size == 1) {
boolean result = add(that.elements[0]);
return result;
}
int[] br = that.elements;
int bl = that.size();
return addAll(br, bl);
}
@SuppressWarnings("unused")
private boolean addAll(int[] that, int thatSize) {
int[] ar = this.elements;
int ai = 0;
final int al = size();
int bi = 0;
// invariant: assume cr has same value as ar until cr is allocated.
// we allocate cr lazily when we discover cr != ar.
int[] cr = null;
int ci = 0;
while (ai < al && bi < thatSize) {
int cmp = (ar[ai] - that[bi]);
// (always accept element)
if (cmp > 0) { // a greater
if (cr == null) {
cr = new int[al + thatSize];
System.arraycopy(ar, 0, cr, 0, ci);
}
cr[ci++] = that[bi++];
} else if (cmp < 0) { // b greater
if (cr != null) {
cr[ci] = ar[ai];
}
ci++;
ai++;
} else {
if (cr != null) {
cr[ci] = ar[ai]; // (same: use a)
}
ci++;
ai++;
bi++;
}
}
// append tail if any (at most one of a or b has tail)
if (ai < al) {
int tail = al - ai;
if (cr != null) {
System.arraycopy(ar, ai, cr, ci, tail);
}
ci += tail;
} else if (bi < thatSize) {
int tail = thatSize - bi;
if (cr == null) {
cr = new int[al + thatSize];
System.arraycopy(ar, 0, cr, 0, ci);
}
System.arraycopy(that, bi, cr, ci, tail);
ci += tail;
}
assert ci > 0;
elements = (cr == null) ? ar : cr;
size = ci;
if (DEBUG_LARGE && size() > TRAP_SIZE) {
Assertions.UNREACHABLE();
}
return (al != size);
}
public void removeAll(BitVectorIntSet v) {
if (v == null) {
throw new IllegalArgumentException("null v");
}
int ai = 0;
for (int i = 0; i < size; i++) {
if (!v.contains(elements[i])) {
elements[ai++] = elements[i];
}
}
size = ai;
}
public <T extends BitVectorBase<T>> void removeAll(T v) {
if (v == null) {
throw new IllegalArgumentException("null v");
}
int ai = 0;
for (int i = 0; i < size; i++) {
if (!v.get(elements[i])) {
elements[ai++] = elements[i];
}
}
size = ai;
}
/**
* TODO optimize
*
* @throws IllegalArgumentException if set is null
*/
public void removeAll(MutableSparseIntSet set) {
if (set == null) {
throw new IllegalArgumentException("set is null");
}
for (IntIterator it = set.intIterator(); it.hasNext(); ) {
remove(it.next());
}
}
/*
* @see
* com.ibm.wala.util.intset.MutableIntSet#addAllInIntersection(com.ibm.wala
* .util.intset.IntSet, com.ibm.wala.util.intset.IntSet)
*/
@Override
public boolean addAllInIntersection(IntSet other, IntSet filter) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
if (filter == null) {
throw new IllegalArgumentException("invalid filter");
}
// a hack. TODO: better algorithm
if (other.size() < 5) {
boolean result = false;
for (IntIterator it = other.intIterator(); it.hasNext(); ) {
int i = it.next();
if (filter.contains(i)) {
result |= add(i);
}
}
return result;
} else if (filter.size() < 5) {
boolean result = false;
for (IntIterator it = filter.intIterator(); it.hasNext(); ) {
int i = it.next();
if (other.contains(i)) {
result |= add(i);
}
}
return result;
} else {
BitVectorIntSet o = new BitVectorIntSet(other);
o.intersectWith(filter);
return addAll(o);
}
}
public static MutableSparseIntSet diff(MutableSparseIntSet A, MutableSparseIntSet B) {
return new MutableSparseIntSet(diffInternal(A, B));
}
public static MutableSparseIntSet make(@Nullable IntSet set) {
return new MutableSparseIntSet(set);
}
public static MutableSparseIntSet makeEmpty() {
return new MutableSparseIntSet();
}
public static MutableSparseIntSet createMutableSparseIntSet(int initialCapacity)
throws IllegalArgumentException {
if (initialCapacity < 0) {
throw new IllegalArgumentException("illegal initialCapacity: " + initialCapacity);
}
return new MutableSparseIntSet(initialCapacity);
}
}
| 12,940
| 24.524655
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/MutableSparseIntSetFactory.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.util.TreeSet;
/** An object that creates mutable sparse int sets. */
public class MutableSparseIntSetFactory implements MutableIntSetFactory<MutableSparseIntSet> {
/** @throws IllegalArgumentException if set is null */
@Override
public MutableSparseIntSet make(int[] set) {
if (set == null) {
throw new IllegalArgumentException("set is null");
}
if (set.length == 0) {
return MutableSparseIntSet.makeEmpty();
} else {
// XXX not very efficient.
TreeSet<Integer> T = new TreeSet<>();
for (int element : set) {
T.add(element);
}
int[] copy = new int[T.size()];
int i = 0;
for (Integer I : T) {
copy[i++] = I;
}
MutableSparseIntSet result = new MutableSparseIntSet(copy);
return result;
}
}
@Override
public MutableSparseIntSet parse(String string) throws NumberFormatException {
int[] backingStore = SparseIntSet.parseIntArray(string);
return new MutableSparseIntSet(backingStore);
}
@Override
public MutableSparseIntSet makeCopy(IntSet x) throws IllegalArgumentException {
if (x == null) {
throw new IllegalArgumentException("x == null");
}
return MutableSparseIntSet.make(x);
}
@Override
public MutableSparseIntSet make() {
return MutableSparseIntSet.makeEmpty();
}
}
| 1,759
| 27.852459
| 94
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/MutableSparseLongSet.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import org.jspecify.annotations.NullUnmarked;
/**
* A sparse ordered, mutable duplicate-free, fully-encapsulated set of longs. Instances are not
* canonical, except for EMPTY.
*
* <p>This implementation will be inefficient if these sets get large.
*
* <p>TODO: even for small sets, we probably want to work on this to reduce the allocation activity.
*/
public final class MutableSparseLongSet extends SparseLongSet implements MutableLongSet {
/** If forced to grow the backing array .. then by how much */
private static final float EXPANSION_FACTOR = 1.5f;
/** Default initial size for a backing array with one element */
private static final int INITIAL_NONEMPTY_SIZE = 2;
public static MutableSparseLongSet make(LongSet set) throws UnimplementedError {
if (!(set instanceof SparseLongSet)) {
Assertions.UNREACHABLE("implement me");
}
return new MutableSparseLongSet(set);
}
public static MutableSparseLongSet createMutableSparseLongSet(int initialCapacity) {
if (initialCapacity < 0) {
throw new IllegalArgumentException("illegal initialCapacity: " + initialCapacity);
}
return new MutableSparseLongSet(initialCapacity);
}
private MutableSparseLongSet(LongSet set) {
super();
copySet(set);
}
public MutableSparseLongSet(long[] backingStore) {
super(backingStore);
}
/** Create an empty set with a non-zero capacity */
private MutableSparseLongSet(int initialCapacity) {
super(new long[initialCapacity]);
size = 0;
}
public MutableSparseLongSet() {
super();
}
/** */
@NullUnmarked
@Override
public void remove(long value) {
if (elements != null) {
int remove;
for (remove = 0; remove < size; remove++) {
if (elements[remove] >= value) {
break;
}
}
if (remove == size) {
return;
}
if (elements[remove] == value) {
if (size == 1) {
elements = null;
size = 0;
} else {
if (remove < size) {
System.arraycopy(elements, remove + 1, elements, remove, size - remove - 1);
}
size--;
}
}
}
}
/** @return true iff this value changes */
@Override
public boolean add(long value) {
if (value < 0) {
throw new IllegalArgumentException("illegal value: " + value);
}
if (elements == null) {
elements = new long[INITIAL_NONEMPTY_SIZE];
size = 1;
elements[0] = value;
} else {
int insert;
if (size == 0 || value > max()) {
insert = size;
} else if (value == max()) {
return false;
} else {
for (insert = 0; insert < size; insert++) {
if (elements[insert] >= value) {
break;
}
}
}
if (insert < size && elements[insert] == value) {
return false;
}
if (size < elements.length - 1) {
// there's space in the backing elements array. Use it.
if (size != insert) {
System.arraycopy(elements, insert, elements, insert + 1, size - insert);
}
size++;
elements[insert] = value;
} else {
// no space left. expand the backing array.
float newExtent = elements.length * EXPANSION_FACTOR + 1;
long[] tmp = new long[(int) newExtent];
System.arraycopy(elements, 0, tmp, 0, insert);
if (size != insert) {
System.arraycopy(elements, insert, tmp, insert + 1, size - insert);
}
tmp[insert] = value;
size++;
elements = tmp;
}
}
return true;
}
/**
* @throws UnimplementedError if not ( that instanceof com.ibm.wala.util.intset.SparseLongSet )
*/
@NullUnmarked
@Override
public void copySet(LongSet that) throws UnimplementedError {
if (that instanceof SparseLongSet) {
SparseLongSet set = (SparseLongSet) that;
if (set.elements != null) {
elements = set.elements.clone();
size = set.size;
} else {
elements = null;
size = 0;
}
} else {
Assertions.UNREACHABLE();
}
}
@Override
public void intersectWith(LongSet set) {
if (set == null) {
throw new IllegalArgumentException("null set");
}
if (set instanceof SparseLongSet) {
intersectWith((SparseLongSet) set);
} else {
int j = 0;
for (int i = 0; i < size; i++) if (set.contains(elements[i])) elements[j++] = elements[i];
size = j;
}
}
@NullUnmarked
public void intersectWith(SparseLongSet set) {
if (set == null) {
throw new IllegalArgumentException("null set");
}
SparseLongSet that = set;
if (this.isEmpty()) {
return;
} else if (that.isEmpty()) {
elements = null;
size = 0;
return;
} else if (this.equals(that)) {
return;
}
// some simple optimizations
if (size == 1) {
if (that.contains(elements[0])) {
return;
} else {
elements = null;
size = 0;
return;
}
}
if (that.size == 1) {
if (contains(that.elements[0])) {
if (size > INITIAL_NONEMPTY_SIZE) {
elements = new long[INITIAL_NONEMPTY_SIZE];
}
size = 1;
elements[0] = that.elements[0];
return;
} else {
elements = null;
size = 0;
return;
}
}
long[] ar = this.elements;
int ai = 0;
int al = size;
long[] br = that.elements;
int bi = 0;
int bl = that.size;
long[] cr = null; // allocate on demand
int ci = 0;
while (ai < al && bi < bl) {
long cmp = (ar[ai] - br[bi]);
// (accept element only on a match)
if (cmp > 0) { // a greater
bi++;
} else if (cmp < 0) { // b greater
ai++;
} else {
if (cr == null) {
cr = new long[al]; // allocate enough (i.e. too much)
}
cr[ci++] = ar[ai];
ai++;
bi++;
}
}
// now compact cr to 'just enough'
size = ci;
elements = cr;
return;
}
/**
* Add all elements from another int set.
*
* @return true iff this set changes
* @throws UnimplementedError if not ( set instanceof com.ibm.wala.util.intset.SparseLongSet )
*/
@Override
public boolean addAll(LongSet set) throws UnimplementedError {
if (set instanceof SparseLongSet) {
return addAll((SparseLongSet) set);
} else {
Assertions.UNREACHABLE();
return false;
}
}
/**
* Add all elements from another int set.
*
* @return true iff this set changes
*/
public boolean addAll(SparseLongSet that) {
if (that == null) {
throw new IllegalArgumentException("null that");
}
if (this.isEmpty()) {
copySet(that);
return !that.isEmpty();
} else if (that.isEmpty()) {
return false;
} else if (this.equals(that)) {
return false;
}
// common-case optimization
if (that.size == 1) {
boolean result = add(that.elements[0]);
return result;
}
long[] br = that.elements;
int bl = that.size();
return addAll(br, bl);
}
private boolean addAll(long[] that, int thatSize) {
long[] ar = this.elements;
int ai = 0;
final int al = size();
int bi = 0;
// invariant: assume cr has same value as ar until cr is allocated.
// we allocate cr lazily when we discover cr != ar.
long[] cr = null;
int ci = 0;
while (ai < al && bi < thatSize) {
long cmp = (ar[ai] - that[bi]);
// (always accept element)
if (cmp > 0) { // a greater
if (cr == null) {
cr = new long[al + thatSize];
System.arraycopy(ar, 0, cr, 0, ci);
}
cr[ci++] = that[bi++];
} else if (cmp < 0) { // b greater
if (cr != null) {
cr[ci] = ar[ai];
}
ci++;
ai++;
} else {
if (cr != null) {
cr[ci] = ar[ai]; // (same: use a)
}
ci++;
ai++;
bi++;
}
}
// append tail if any (at most one of a or b has tail)
if (ai < al) {
int tail = al - ai;
if (cr != null) {
System.arraycopy(ar, ai, cr, ci, tail);
}
ci += tail;
} else if (bi < thatSize) {
int tail = thatSize - bi;
if (cr == null) {
cr = new long[al + thatSize];
System.arraycopy(ar, 0, cr, 0, ci);
}
System.arraycopy(that, bi, cr, ci, tail);
ci += tail;
}
assert ci > 0;
elements = (cr == null) ? ar : cr;
size = ci;
return (al != size);
}
}
| 9,123
| 24.415042
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/MutableSparseLongSetFactory.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.util.Arrays;
import java.util.TreeSet;
/** An object that creates mutable sparse int sets. */
public class MutableSparseLongSetFactory implements MutableLongSetFactory {
/** @throws IllegalArgumentException if set is null */
@Override
public MutableLongSet make(long[] set) {
if (set == null) {
throw new IllegalArgumentException("set is null");
}
if (set.length == 0) {
return new MutableSparseLongSet();
} else {
// XXX not very efficient.
TreeSet<Long> T = new TreeSet<>();
for (long element : set) {
T.add(element);
}
long[] copy = new long[T.size()];
int i = 0;
for (Long I : T) {
copy[i++] = I;
}
MutableSparseLongSet result = new MutableSparseLongSet(copy);
return result;
}
}
@Override
public MutableLongSet parse(String string) throws NumberFormatException {
int[] backingStore = SparseIntSet.parseIntArray(string);
long[] bs = Arrays.stream(backingStore).asLongStream().toArray();
return new MutableSparseLongSet(bs);
}
@Override
public MutableLongSet makeCopy(LongSet x) throws IllegalArgumentException {
if (x == null) {
throw new IllegalArgumentException("x == null");
}
return MutableSparseLongSet.make(x);
}
@Override
public MutableLongSet make() {
return new MutableSparseLongSet();
}
}
| 1,798
| 27.555556
| 77
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/NumberUtility.java
|
/*
* Copyright (c) 2009 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
public class NumberUtility {
static boolean isByte(int number) {
if (number >= Byte.MIN_VALUE && number <= Byte.MAX_VALUE) {
return true;
}
return false;
}
static boolean isShort(int number) {
if (!isByte(number) && number >= Short.MIN_VALUE && number <= Short.MAX_VALUE) {
return true;
}
return false;
}
}
| 756
| 25.103448
| 84
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/OffsetBitVector.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.util.Arrays;
/** */
public final class OffsetBitVector extends BitVectorBase<OffsetBitVector> {
private static final long serialVersionUID = -5846568678514886375L;
int offset;
private static int wordDiff(int offset1, int offset2) {
return (offset1 > offset2)
? (offset1 - offset2) >> LOG_BITS_PER_UNIT
: -((offset2 - offset1) >> LOG_BITS_PER_UNIT);
}
/** Expand this bit vector to size newCapacity. */
private void expand(int newOffset, int newCapacity) {
int wordDiff = wordDiff(newOffset, offset);
int[] oldbits = bits;
bits = new int[subscript(newCapacity) + 1];
System.arraycopy(oldbits, 0, bits, 0 - wordDiff, oldbits.length);
offset = newOffset;
}
private void ensureCapacity(int newOffset, int newCapacity) {
if (newOffset < offset || newCapacity > (bits.length << LOG_BITS_PER_UNIT)) {
expand(newOffset, newCapacity);
}
}
public OffsetBitVector() {
this(0, 1);
}
/**
* Creates an empty string with the specified size.
*
* @param nbits the size of the string
*/
public OffsetBitVector(int offset, int nbits) {
if (nbits < 0) {
throw new IllegalArgumentException("invalid nbits: " + nbits);
}
if (offset < 0) {
throw new IllegalArgumentException("invalid offset: " + offset);
}
offset &= ~LOW_MASK;
this.offset = offset;
this.bits = new int[subscript(nbits) + 1];
}
/**
* Creates a copy of a Bit String
*
* @param s the string to copy
* @throws IllegalArgumentException if s is null
*/
public OffsetBitVector(OffsetBitVector s) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
offset = s.offset;
bits = s.bits.clone();
}
@Override
public String toString() {
return super.toString() + "(offset:" + offset + ')';
}
void growCapacity(float fraction) {
expand(offset, (int) (fraction * (bits.length << LOG_BITS_PER_UNIT)));
}
public int getOffset() {
return offset;
}
int getSize() {
return bits.length;
}
/**
* Sets a bit.
*
* @param bit the bit to be set
*/
@Override
public void set(int bit) {
if (bit < 0) {
throw new IllegalArgumentException("illegal bit: " + bit);
}
int shiftBits;
int subscript;
if (bit < offset) {
int newOffset = bit & ~LOW_MASK;
expand(newOffset, length() - 1 - newOffset);
shiftBits = bit & LOW_MASK;
subscript = 0;
} else {
bit -= offset;
shiftBits = bit & LOW_MASK;
subscript = subscript(bit);
if (subscript >= bits.length) {
expand(offset, bit);
}
}
try {
bits[subscript] |= (1 << shiftBits);
} catch (RuntimeException e) {
e.printStackTrace();
throw e;
}
}
/**
* Clears a bit.
*
* @param bit the bit to be cleared
*/
@Override
public void clear(int bit) {
if (bit < offset) {
return;
}
bit -= offset;
int ss = subscript(bit);
if (ss >= bits.length) {
return;
}
int shiftBits = bit & LOW_MASK;
bits[ss] &= ~(1 << shiftBits);
}
/**
* Gets a bit.
*
* @param bit the bit to be gotten
*/
@Override
public boolean get(int bit) {
if (DEBUG) {
assert bit >= 0;
}
if (bit < offset) {
return false;
}
bit -= offset;
int ss = subscript(bit);
if (ss >= bits.length) {
return false;
}
int shiftBits = bit & LOW_MASK;
return ((bits[ss] & (1 << shiftBits)) != 0);
}
/** @return min j >= start s.t get(j) */
@Override
public int nextSetBit(int start) {
int nb = super.nextSetBit(Math.max(0, start - offset));
return nb == -1 ? -1 : offset + nb;
}
/** Logically NOT this bit string */
public void not() {
if (offset != 0) {
expand(0, offset + length() - 1);
}
for (int i = 0; i < bits.length; i++) {
bits[i] ^= MASK;
}
}
@Override
public int max() {
return super.max() + offset;
}
/**
* Calculates and returns the set's size in bits. The maximum element in the set is the size - 1st
* element.
*/
@Override
public int length() {
return (bits.length << LOG_BITS_PER_UNIT) + offset;
}
/** Sets all bits. */
public void setAll() {
expand(0, length() - 1);
Arrays.fill(bits, MASK);
}
/**
* Compares this object against the specified object.
*
* @param obj the object to compare with
* @return true if the objects are the same; false otherwise.
*/
@Override
public boolean equals(Object obj) {
if ((obj != null) && (obj instanceof OffsetBitVector)) {
if (this == obj) { // should help alias analysis
return true;
}
OffsetBitVector set = (OffsetBitVector) obj;
return sameBits(set);
}
return false;
}
/**
* Check if the intersection of the two sets is empty
*
* @param set the set to check intersection with
* @throws IllegalArgumentException if set == null
*/
@Override
public boolean intersectionEmpty(OffsetBitVector set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (this == set) {
return isZero();
}
int wordDiff = wordDiff(offset, set.offset);
int maxWord = Math.min(bits.length, set.bits.length - wordDiff);
int i = Math.max(0, -wordDiff);
for (; i < maxWord; i++) {
if ((bits[i] & set.bits[i + wordDiff]) != 0) {
return false;
}
}
return true;
}
/**
* Compares this object against the specified object.
*
* @param set the object to compare with
* @return true if the objects are the same; false otherwise.
* @throws IllegalArgumentException if set == null
*/
@Override
public boolean sameBits(OffsetBitVector set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (this == set) { // should help alias analysis
return true;
}
int wordDiff = wordDiff(offset, set.offset);
int maxWord = Math.min(bits.length, set.bits.length - wordDiff);
int i = 0;
if (wordDiff < 0) {
for (; i < -wordDiff; i++) {
if (bits[i] != 0) {
return false;
}
}
} else {
for (int j = 0; j < wordDiff; j++) {
if (set.bits[j] != 0) {
return false;
}
}
}
for (; i < maxWord; i++) {
if (bits[i] != set.bits[i + wordDiff]) {
return false;
}
}
for (int j = maxWord + wordDiff; j < set.bits.length; j++) {
if (set.bits[j] != 0) {
return false;
}
}
for (; i < bits.length; i++) {
if (bits[i] != 0) {
return false;
}
}
return true;
}
/*
* @param other @return true iff this is a subset of other
*/
@Override
public boolean isSubset(OffsetBitVector other) throws IllegalArgumentException {
if (other == null) {
throw new IllegalArgumentException("other == null");
}
if (this == other) { // should help alias analysis
return true;
}
int wordDiff = wordDiff(offset, other.offset);
int maxWord = Math.min(bits.length, other.bits.length - wordDiff);
int i = 0;
for (; i < -wordDiff; i++) {
if (bits[i] != 0) {
return false;
}
}
for (; i < maxWord; i++) {
if ((bits[i] & ~other.bits[i + wordDiff]) != 0) {
return false;
}
}
for (; i < bits.length; i++) {
if (bits[i] != 0) {
return false;
}
}
return true;
}
/**
* Copies the values of the bits in the specified set into this set.
*
* @param set the bit set to copy the bits from
* @throws IllegalArgumentException if set is null
*/
public void copyBits(OffsetBitVector set) {
if (set == null) {
throw new IllegalArgumentException("set is null");
}
super.copyBits(set);
offset = set.offset;
}
/**
* Logically ANDs this bit set with the specified set of bits.
*
* @param set the bit set to be ANDed with
* @throws IllegalArgumentException if set == null
*/
@Override
public void and(OffsetBitVector set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (this == set) {
return;
}
int wordDiff = wordDiff(offset, set.offset);
int maxWord = Math.min(bits.length, set.bits.length - wordDiff);
int i = 0;
for (; i < -wordDiff; i++) {
bits[i] = 0;
}
for (; i < maxWord; i++) {
bits[i] &= set.bits[i + wordDiff];
}
for (; i < bits.length; i++) {
bits[i] = 0;
}
}
/**
* Logically ORs this bit set with the specified set of bits.
*
* @param set the bit set to be ORed with
* @throws IllegalArgumentException if set == null
*/
@Override
public void or(OffsetBitVector set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (this == set) { // should help alias analysis
return;
}
int newOffset = Math.min(offset, set.offset);
int newCapacity = Math.max(length(), set.length()) - newOffset;
ensureCapacity(newOffset, newCapacity);
int wordDiff = wordDiff(newOffset, set.offset);
for (int i = 0; i < set.bits.length; i++) {
bits[i - wordDiff] |= set.bits[i];
}
}
/**
* Logically XORs this bit set with the specified set of bits.
*
* @param set the bit set to be XORed with
* @throws IllegalArgumentException if set == null
*/
@Override
public void xor(OffsetBitVector set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (this == set) {
clearAll();
return;
}
int newOffset = Math.min(offset, set.offset);
int newCapacity = Math.max(length(), set.length()) - newOffset;
ensureCapacity(newOffset, newCapacity);
int wordDiff = wordDiff(newOffset, set.offset);
for (int i = 0; i < set.bits.length; i++) {
bits[i - wordDiff] ^= set.bits[i];
}
}
@Override
public void andNot(OffsetBitVector set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (this == set) {
clearAll();
return;
}
int wordDiff = wordDiff(offset, set.offset);
int maxWord = Math.min(bits.length, set.bits.length - wordDiff);
int i = Math.max(0, -wordDiff);
for (; i < maxWord; i++) {
bits[i] &= ~set.bits[i + wordDiff];
}
}
/** Return the NOT of a bit string */
public static OffsetBitVector not(OffsetBitVector s) {
OffsetBitVector b = new OffsetBitVector(s);
b.not();
return b;
}
/**
* Return a new bit string as the AND of two others.
*
* @throws IllegalArgumentException if b2 == null
*/
public static OffsetBitVector and(OffsetBitVector b1, OffsetBitVector b2)
throws IllegalArgumentException {
if (b2 == null) {
throw new IllegalArgumentException("b2 == null");
}
OffsetBitVector b = new OffsetBitVector(b1);
b.and(b2);
return b;
}
/**
* Return a new FixedSizeBitVector as the OR of two others
*
* @throws IllegalArgumentException if b2 == null
*/
public static OffsetBitVector or(OffsetBitVector b1, OffsetBitVector b2)
throws IllegalArgumentException {
if (b2 == null) {
throw new IllegalArgumentException("b2 == null");
}
OffsetBitVector b = new OffsetBitVector(b1);
b.or(b2);
return b;
}
/** Return a new bit string as the AND of two others. */
public static OffsetBitVector andNot(OffsetBitVector b1, OffsetBitVector b2) {
OffsetBitVector b = new OffsetBitVector(b1);
b.andNot(b2);
return b;
}
}
| 12,317
| 23.011696
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/OffsetOrdinalSetMapping.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.stream.Stream;
/** An ordinal set mapping, backed a delegate, but adding an offset to each index. */
public class OffsetOrdinalSetMapping<T> implements OrdinalSetMapping<T> {
private final OrdinalSetMapping<T> delegate;
private final int offset;
private OffsetOrdinalSetMapping(OrdinalSetMapping<T> delegate, int offset) {
this.delegate = delegate;
this.offset = offset;
}
@Override
public int getMaximumIndex() {
return offset + delegate.getMaximumIndex();
}
@Override
public int getSize() {
return delegate.getSize();
}
public static <T> OffsetOrdinalSetMapping<T> make(OrdinalSetMapping<T> delegate, int offset) {
if (delegate == null) {
throw new IllegalArgumentException("null delegate");
}
return new OffsetOrdinalSetMapping<>(delegate, offset);
}
public static <T> OffsetOrdinalSetMapping<T> make(int offset) {
MutableMapping<T> m = MutableMapping.make();
return new OffsetOrdinalSetMapping<>(m, offset);
}
@Override
public int add(T o) {
return offset + delegate.add(o);
}
@Override
public int getMappedIndex(Object o) {
if (delegate.getMappedIndex(o) == -1) {
return -1;
}
return offset + delegate.getMappedIndex(o);
}
@Override
public T getMappedObject(int n) throws NoSuchElementException {
return delegate.getMappedObject(n - offset);
}
@Override
public boolean hasMappedIndex(T o) {
return delegate.hasMappedIndex(o);
}
@Override
public Iterator<T> iterator() {
return delegate.iterator();
}
@Override
public Stream<T> stream() {
return delegate.stream();
}
}
| 2,119
| 24.238095
| 96
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/OrdinalSet.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.Iterator2Collection;
import com.ibm.wala.util.debug.Assertions;
import java.util.Collection;
import java.util.Iterator;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/** A Set backed by a set of integers. */
public class OrdinalSet<T> implements Iterable<T> {
@Nullable private final IntSet S;
@Nullable private final OrdinalSetMapping<T> mapping;
@SuppressWarnings("rawtypes")
private static final OrdinalSet EMPTY = new OrdinalSet();
public static <T> OrdinalSet<T> empty() {
return EMPTY;
}
private OrdinalSet() {
S = null;
mapping = null;
}
public OrdinalSet(@Nullable IntSet S, @Nullable OrdinalSetMapping<T> mapping) {
this.S = S;
this.mapping = mapping;
}
public boolean containsAny(OrdinalSet<T> that) {
if (that == null) {
throw new IllegalArgumentException("null that");
}
if (S == null || that.S == null) {
return false;
}
return S.containsAny(that.S);
}
public int size() {
return (S == null) ? 0 : S.size();
}
@Override
public Iterator<T> iterator() {
if (S == null) {
return EmptyIterator.instance();
} else {
return new Iterator<>() {
@SuppressWarnings("NullAway")
final IntIterator it = S.intIterator();
@Override
public boolean hasNext() {
return it.hasNext();
}
@NullUnmarked
@Override
public T next() {
return mapping.getMappedObject(it.next());
}
@Override
public void remove() {
Assertions.UNREACHABLE();
}
};
}
}
/**
* @return a new OrdinalSet instances
* @throws IllegalArgumentException if A is null
*/
public static <T> OrdinalSet<T> intersect(OrdinalSet<T> A, OrdinalSet<T> B) {
if (A == null) {
throw new IllegalArgumentException("A is null");
}
if (A.size() != 0 && B.size() != 0) {
assert A.mapping.equals(B.mapping);
}
if (A.S == null || B.S == null) {
return new OrdinalSet<>(null, A.mapping);
}
IntSet isect = A.S.intersection(B.S);
return new OrdinalSet<>(isect, A.mapping);
}
/** @return true if the contents of two sets are equal */
public static <T> boolean equals(OrdinalSet<T> a, OrdinalSet<T> b) {
if ((a == null && b == null) || a == b || (a.mapping == b.mapping && a.S == b.S)) {
return true;
}
assert a != null && b != null;
if (a.size() == b.size()) {
if (a.mapping == b.mapping
|| (a.mapping != null && b.mapping != null && a.mapping.equals(b.mapping))) {
return a.S == b.S || (a.S != null && b.S != null && a.S.sameValue(b.S));
}
}
return false;
}
/**
* Creates the union of two ordinal sets.
*
* @param A ordinal set a
* @param B ordinal set b
* @return union of a and b
* @throws IllegalArgumentException iff A or B is null
*/
public static <T> OrdinalSet<T> unify(OrdinalSet<T> A, OrdinalSet<T> B) {
if (A == null) {
throw new IllegalArgumentException("A is null");
}
if (B == null) {
throw new IllegalArgumentException("B is null");
}
if (A.size() != 0 && B.size() != 0) {
assert A.mapping.equals(B.mapping);
}
if (A.S == null) {
return (B.S == null) ? OrdinalSet.<T>empty() : new OrdinalSet<>(B.S, B.mapping);
} else if (B.S == null) {
return new OrdinalSet<>(A.S, A.mapping);
}
IntSet union = A.S.union(B.S);
return new OrdinalSet<>(union, A.mapping);
}
@Override
public String toString() {
return Iterator2Collection.toSet(iterator()).toString();
}
/** */
public SparseIntSet makeSparseCopy() {
return (S == null) ? new SparseIntSet() : new SparseIntSet(S);
}
/**
* Dangerous. Added for performance reasons. Use this only if you really know what you are doing.
*/
@Nullable
public IntSet getBackingSet() {
return S;
}
/** @return true iff this set contains object */
@NullUnmarked
public boolean contains(T object) {
if (this == EMPTY || S == null || object == null) {
return false;
}
int index = mapping.getMappedIndex(object);
return (index == -1) ? false : S.contains(index);
}
public boolean isEmpty() {
return size() == 0;
}
/** @throws NullPointerException if instances is null */
public static <T> Collection<T> toCollection(OrdinalSet<T> instances) {
return Iterator2Collection.toSet(instances.iterator());
}
/**
* Precondition: the ordinal set mapping has an index for every element of c Convert a "normal"
* collection to an OrdinalSet, based on the given mapping.
*
* @throws IllegalArgumentException if c is null
*/
public static <T> OrdinalSet<T> toOrdinalSet(Collection<T> c, OrdinalSetMapping<T> m) {
if (c == null) {
throw new IllegalArgumentException("c is null");
}
if (m == null) {
throw new IllegalArgumentException("m is null");
}
MutableSparseIntSet s = MutableSparseIntSet.makeEmpty();
for (T t : c) {
int index = m.getMappedIndex(t);
assert index >= 0;
s.add(index);
}
return new OrdinalSet<>(s, m);
}
@Nullable
public OrdinalSetMapping<T> getMapping() {
return mapping;
}
}
| 5,778
| 25.75463
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/OrdinalSetMapping.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.util.NoSuchElementException;
import java.util.stream.Stream;
/** An object that implements a bijection between whole numbers and objects. */
public interface OrdinalSetMapping<T> extends Iterable<T> {
/** @return the object numbered n. */
T getMappedObject(int n) throws NoSuchElementException;
/** @return the number of a given object, or -1 if the object is not currently in the range. */
int getMappedIndex(Object o);
/** @return whether the given object is mapped by this mapping */
boolean hasMappedIndex(T o);
/** @return the maximum integer mapped to an object */
int getMaximumIndex();
/** @return the current size of the bijection */
int getSize();
/**
* Add an Object to the set of mapped objects.
*
* @return the integer to which the object is mapped.
*/
int add(T o);
/**
* Stream over mapped objects.
*
* @return a stream over the mapped objects
*/
Stream<T> stream();
}
| 1,365
| 28.06383
| 97
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/SemiSparseMutableIntSet.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.collections.CompoundIntIterator;
import com.ibm.wala.util.collections.EmptyIntIterator;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
public class SemiSparseMutableIntSet implements MutableIntSet {
private static final long serialVersionUID = 8647721176321526013L;
private static final boolean DEBUG = true;
private static final double FIX_SPARSE_MOD = 12;
private static final double FIX_SPARSE_RATIO = .05;
@SuppressWarnings("NullAway.Init")
private MutableSparseIntSet sparsePart;
@Nullable private OffsetBitVector densePart = null;
public SemiSparseMutableIntSet() {
this(MutableSparseIntSet.makeEmpty());
}
private SemiSparseMutableIntSet(MutableSparseIntSet sparsePart) {
this.sparsePart = sparsePart;
}
private SemiSparseMutableIntSet(MutableSparseIntSet sparsePart, OffsetBitVector densePart) {
this.sparsePart = sparsePart;
this.densePart = densePart;
}
public SemiSparseMutableIntSet(SemiSparseMutableIntSet set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
copySet(set);
}
private final boolean assertDisjoint() {
if (DEBUG) {
if (densePart != null) {
for (IntIterator sparseBits = sparsePart.intIterator(); sparseBits.hasNext(); ) {
int bit = sparseBits.next();
if (densePart.contains(bit)) {
return false;
}
if (inDenseRange(bit)) {
return false;
}
}
}
}
return true;
}
private void fixAfterSparseInsert() {
if (sparsePart.size() % FIX_SPARSE_MOD == FIX_SPARSE_MOD - 1
&& (densePart == null
|| (densePart != null && sparsePart.size() > FIX_SPARSE_RATIO * densePart.getSize()))) {
assert assertDisjoint() : this.toString();
if (densePart == null) {
IntIterator sparseBits = sparsePart.intIterator();
int maxOffset = -1;
int maxCount = -1;
int maxMax = -1;
int offset = 0;
int bits = 0;
int count = 0;
int oldBit = 0;
while (sparseBits.hasNext()) {
int nextBit = sparseBits.next();
int newBits = bits + (nextBit - oldBit);
int newCount = count + 1;
if (newBits < (32 * newCount)) {
count = newCount;
bits = newBits;
if (count > maxCount) {
maxOffset = offset;
maxMax = nextBit;
maxCount = count;
}
} else {
offset = nextBit;
count = 1;
bits = 32;
}
oldBit = nextBit;
}
if (maxOffset != -1) {
densePart = new OffsetBitVector(maxOffset, maxMax - maxOffset);
sparseBits = sparsePart.intIterator();
int bit;
while ((bit = sparseBits.next()) < maxOffset) {
// do nothing
}
densePart.set(bit);
for (int i = 1; i < maxCount; i++) {
densePart.set(sparseBits.next());
}
sparsePart.removeAll(densePart);
}
assert assertDisjoint()
: this + ", maxOffset=" + maxOffset + ", maxMax=" + maxMax + ", maxCount=" + maxCount;
} else {
IntIterator sparseBits = sparsePart.intIterator();
int thisBit = sparseBits.next();
int moveCount = 0;
int newOffset = -1;
int newCount = -1;
int newLength = -1;
// push stuff just below dense part into it, if it saves space
if (thisBit < densePart.getOffset()) {
newOffset = thisBit;
int bits = 32;
int count = 1;
while (sparseBits.hasNext()) {
int nextBit = sparseBits.next();
if (nextBit >= densePart.getOffset() || !sparseBits.hasNext()) {
if (nextBit < densePart.getOffset() && !sparseBits.hasNext()) {
count++;
}
if (densePart.getOffset() - newOffset < (32 * count)) {
moveCount += count;
} else {
newOffset = -1;
}
thisBit = nextBit;
break;
} else {
bits += (nextBit - thisBit);
count++;
if (bits > (32 * count)) {
newOffset = nextBit;
count = 1;
bits = 32;
}
thisBit = nextBit;
}
}
}
while (thisBit < densePart.length() && sparseBits.hasNext()) {
thisBit = sparseBits.next();
}
// push stuff just above dense part into it, if it saves space
if (thisBit >= densePart.length()) {
int count = 1;
int bits = (thisBit + 1 - densePart.length());
if (32 * count > bits) {
newLength = thisBit;
newCount = 1;
}
while (sparseBits.hasNext()) {
thisBit = sparseBits.next();
count++;
bits = (thisBit + 1 - densePart.length());
if ((32 * count) > bits) {
newLength = thisBit;
newCount = count;
}
}
if (newLength > -1) {
moveCount += newCount;
}
}
// actually move bits from sparse to dense
if (moveCount > 0) {
int index = 0;
int[] bits = new int[moveCount];
for (sparseBits = sparsePart.intIterator(); sparseBits.hasNext(); ) {
int bit = sparseBits.next();
if (newOffset != -1 && bit >= newOffset && bit < densePart.getOffset()) {
bits[index++] = bit;
}
if (newLength != -1 && bit >= densePart.length() && bit <= newLength) {
bits[index++] = bit;
}
}
if (index != moveCount) {
assert index == moveCount
: "index is " + index + ", but moveCount is " + moveCount + " for " + this;
}
if (newLength != -1 && bits[index - 1] == sparsePart.max()) {
int base = densePart.getOffset();
int currentSize = densePart.length() - base;
float newSize = 1.1f * (bits[index - 1] - base);
float fraction = newSize / currentSize;
assert fraction > 1;
densePart.growCapacity(fraction);
}
for (int i = index - 1; i >= 0; i--) {
sparsePart.remove(bits[i]);
densePart.set(bits[i]);
}
}
assert assertDisjoint()
: this
+ ", densePart.length()="
+ densePart.length()
+ ", newOffset="
+ newOffset
+ ", newLength="
+ newLength
+ ", newCount="
+ newCount
+ ", moveCount="
+ moveCount;
}
}
}
@Override
public void clear() {
sparsePart.clear();
densePart = null;
}
/** @return true iff this set contains integer i */
@Override
public boolean contains(int i) {
if (densePart != null && inDenseRange(i)) {
return densePart.contains(i);
} else {
return sparsePart.contains(i);
}
}
/** @return true iff this set contains integer i */
@Override
public boolean containsAny(IntSet set) {
if (set == null) {
throw new IllegalArgumentException("null set");
}
if (!sparsePart.isEmpty() && sparsePart.containsAny(set)) {
return true;
} else if (densePart != null) {
int lower = densePart.getOffset();
for (IntIterator is = set.intIterator(); is.hasNext(); ) {
int i = is.next();
if (i < lower) continue;
if (densePart.get(i)) {
return true;
}
}
}
return false;
}
/**
* This implementation must not despoil the original value of "this"
*
* @return a new IntSet which is the intersection of this and that
*/
@Override
public IntSet intersection(IntSet that) {
if (that == null) {
throw new IllegalArgumentException("null that");
}
SemiSparseMutableIntSet newThis = new SemiSparseMutableIntSet();
for (IntIterator bits = intIterator(); bits.hasNext(); ) {
int bit = bits.next();
if (that.contains(bit)) {
newThis.add(bit);
}
}
return newThis;
}
/** @see com.ibm.wala.util.intset.IntSet#union(com.ibm.wala.util.intset.IntSet) */
@Override
public IntSet union(IntSet that) {
SemiSparseMutableIntSet temp = new SemiSparseMutableIntSet();
temp.addAll(this);
temp.addAll(that);
return temp;
}
/** @return true iff this set is empty */
@Override
public boolean isEmpty() {
return sparsePart.isEmpty() && (densePart == null || densePart.isZero());
}
/** @return the number of elements in this set */
@Override
public int size() {
return sparsePart.size() + (densePart == null ? 0 : densePart.populationCount());
}
/** @return a perhaps more efficient iterator */
@Override
public IntIterator intIterator() {
class DensePartIterator implements IntIterator {
private int i = -1;
@NullUnmarked
@Override
public boolean hasNext() {
return densePart.nextSetBit(i + 1) != -1;
}
@NullUnmarked
@Override
public int next() {
int next = densePart.nextSetBit(i + 1);
i = next;
return next;
}
}
if (sparsePart.isEmpty()) {
if (densePart == null || densePart.isZero()) {
return EmptyIntIterator.instance();
} else {
return new DensePartIterator();
}
} else {
if (densePart == null || densePart.isZero()) {
return sparsePart.intIterator();
} else {
return new CompoundIntIterator(sparsePart.intIterator(), new DensePartIterator());
}
}
}
/** Invoke an action on each element of the Set */
@Override
public void foreach(IntSetAction action) {
if (action == null) {
throw new IllegalArgumentException("null action");
}
sparsePart.foreach(action);
if (densePart != null) {
for (int b = densePart.nextSetBit(0); b != -1; b = densePart.nextSetBit(b + 1)) {
action.act(b);
}
}
}
/** Invoke an action on each element of the Set, excluding elements of Set X */
@Override
public void foreachExcluding(IntSet X, IntSetAction action) {
sparsePart.foreachExcluding(X, action);
if (densePart != null) {
for (int b = densePart.nextSetBit(0); b != -1; b = densePart.nextSetBit(b + 1)) {
if (!X.contains(b)) {
action.act(b);
}
}
}
}
/** @return maximum integer in this set. */
@Override
public int max() throws IllegalStateException {
if (densePart == null) {
return sparsePart.max();
} else {
return Math.max(sparsePart.max(), densePart.max());
}
}
/**
* @return true iff {@code this} has the same value as {@code that}.
* @throws IllegalArgumentException if that is null
*/
@Override
public boolean sameValue(IntSet that) {
if (that == null) {
throw new IllegalArgumentException("that is null");
}
if (size() != that.size()) {
return false;
}
if (densePart != null) {
for (int bit = densePart.nextSetBit(0); bit != -1; bit = densePart.nextSetBit(bit + 1)) {
if (!that.contains(bit)) {
return false;
}
}
}
for (IntIterator bits = sparsePart.intIterator(); bits.hasNext(); ) {
if (!that.contains(bits.next())) {
return false;
}
}
return true;
}
/**
* @return true iff {@code this} is a subset of {@code that}.
* @throws IllegalArgumentException if that is null
*/
@Override
public boolean isSubset(IntSet that) {
if (that == null) {
throw new IllegalArgumentException("that is null");
}
if (size() > that.size()) {
return false;
}
for (IntIterator bits = sparsePart.intIterator(); bits.hasNext(); ) {
if (!that.contains(bits.next())) {
return false;
}
}
if (densePart != null) {
for (int b = densePart.nextSetBit(0); b != -1; b = densePart.nextSetBit(b + 1)) {
if (!that.contains(b)) {
return false;
}
}
}
return true;
}
/**
* Set the value of this to be the same as the value of set
*
* @throws IllegalArgumentException if set == null
*/
@Override
public void copySet(IntSet set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (set instanceof SemiSparseMutableIntSet) {
SemiSparseMutableIntSet that = (SemiSparseMutableIntSet) set;
sparsePart = MutableSparseIntSet.make(that.sparsePart);
if (that.densePart == null) {
densePart = null;
} else {
densePart = new OffsetBitVector(that.densePart);
}
} else {
densePart = null;
sparsePart = MutableSparseIntSet.makeEmpty();
for (IntIterator bits = set.intIterator(); bits.hasNext(); ) {
add(bits.next());
}
}
}
@NullUnmarked
private boolean inDenseRange(int i) {
return densePart.getOffset() <= i && densePart.length() > i;
}
/**
* Add all members of set to this.
*
* @return true iff the value of this changes.
* @throws IllegalArgumentException if set == null
*/
@Override
public boolean addAll(IntSet set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
boolean change = false;
if (set instanceof SemiSparseMutableIntSet) {
SemiSparseMutableIntSet that = (SemiSparseMutableIntSet) set;
if (densePart == null) {
// that dense part only
if (that.densePart != null) {
int oldSize = size();
densePart = new OffsetBitVector(that.densePart);
for (IntIterator bits = sparsePart.intIterator(); bits.hasNext(); ) {
int bit = bits.next();
if (inDenseRange(bit)) {
densePart.set(bit);
}
}
sparsePart.removeAll(densePart);
sparsePart.addAll(that.sparsePart);
change = size() != oldSize;
// no dense part
} else {
change = sparsePart.addAll(that.sparsePart);
fixAfterSparseInsert();
}
} else {
// both dense parts
if (that.densePart != null) {
int oldSize = size();
densePart.or(that.densePart);
sparsePart.addAll(that.sparsePart);
for (IntIterator bits = sparsePart.intIterator(); bits.hasNext(); ) {
int bit = bits.next();
if (inDenseRange(bit)) {
densePart.set(bit);
}
}
sparsePart.removeAll(densePart);
change = size() != oldSize;
// this dense part only
} else {
for (IntIterator bs = that.sparsePart.intIterator(); bs.hasNext(); ) {
change |= add(bs.next());
}
}
}
} else {
for (IntIterator bs = set.intIterator(); bs.hasNext(); ) {
change |= add(bs.next());
}
}
assert assertDisjoint() : this.toString();
return change;
}
/**
* Add an integer value to this set.
*
* @param i integer to add
* @return true iff the value of this changes.
*/
@Override
public boolean add(int i) {
if (densePart != null && inDenseRange(i)) {
if (!densePart.get(i)) {
densePart.set(i);
assert assertDisjoint() : this.toString();
return true;
}
} else if (!sparsePart.contains(i)) {
sparsePart.add(i);
assert assertDisjoint() : this.toString();
fixAfterSparseInsert();
return true;
}
return false;
}
/**
* Remove an integer from this set.
*
* @param i integer to remove
* @return true iff the value of this changes.
*/
@Override
public boolean remove(int i) {
if (densePart != null && densePart.get(i)) {
densePart.clear(i);
if (densePart.nextSetBit(0) == -1) {
densePart = null;
}
return true;
} else if (sparsePart.contains(i)) {
sparsePart.remove(i);
return true;
} else {
return false;
}
}
/** Interset this with another set. */
@Override
public void intersectWith(IntSet set) {
sparsePart.intersectWith(set);
if (densePart != null) {
for (int b = densePart.nextSetBit(0); b != -1; b = densePart.nextSetBit(b + 1)) {
if (!set.contains(b)) {
densePart.clear(b);
}
}
}
}
/** @throws IllegalArgumentException if other is null */
@Override
public boolean addAllInIntersection(IntSet other, IntSet filter) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
if (filter == null) {
throw new IllegalArgumentException("null filter");
}
boolean change = false;
for (IntIterator bits = other.intIterator(); bits.hasNext(); ) {
int bit = bits.next();
if (filter.contains(bit)) {
change |= add(bit);
}
}
return change;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
if (densePart != null) {
sb.append("densePart: ").append(densePart).append(' ');
}
sb.append("sparsePart: ").append(sparsePart.toString()).append(']');
return sb.toString();
}
public SemiSparseMutableIntSet removeAll(SemiSparseMutableIntSet B) {
if (B == null) {
throw new IllegalArgumentException("B null");
}
if (densePart == null) {
if (B.densePart == null) {
sparsePart = MutableSparseIntSet.diff(sparsePart, B.sparsePart);
} else {
MutableSparseIntSet C = MutableSparseIntSet.diff(sparsePart, B.sparsePart);
for (IntIterator bits = sparsePart.intIterator(); bits.hasNext(); ) {
int bit = bits.next();
if (B.densePart.get(bit)) {
C.remove(bit);
}
}
sparsePart = C;
}
} else {
if (B.densePart == null) {
for (IntIterator bits = B.sparsePart.intIterator(); bits.hasNext(); ) {
densePart.clear(bits.next());
}
sparsePart = MutableSparseIntSet.diff(sparsePart, B.sparsePart);
} else {
densePart.andNot(B.densePart);
for (IntIterator bits = B.sparsePart.intIterator(); bits.hasNext(); ) {
densePart.clear(bits.next());
}
MutableSparseIntSet C = MutableSparseIntSet.diff(sparsePart, B.sparsePart);
for (IntIterator bits = sparsePart.intIterator(); bits.hasNext(); ) {
int bit = bits.next();
if (B.densePart.get(bit)) {
C.remove(bit);
}
}
sparsePart = C;
}
}
return this;
}
public static SemiSparseMutableIntSet diff(SemiSparseMutableIntSet A, SemiSparseMutableIntSet B) {
if (A == null) {
throw new IllegalArgumentException("A is null");
}
if (B == null) {
throw new IllegalArgumentException("B is null");
}
if (A.densePart == null) {
if (B.densePart == null) {
return new SemiSparseMutableIntSet(MutableSparseIntSet.diff(A.sparsePart, B.sparsePart));
} else {
MutableSparseIntSet C = MutableSparseIntSet.diff(A.sparsePart, B.sparsePart);
for (IntIterator bits = A.sparsePart.intIterator(); bits.hasNext(); ) {
int bit = bits.next();
if (B.densePart.get(bit)) {
C.remove(bit);
}
}
return new SemiSparseMutableIntSet(C);
}
} else {
if (B.densePart == null) {
OffsetBitVector newDensePart = new OffsetBitVector(A.densePart);
for (IntIterator bits = B.sparsePart.intIterator(); bits.hasNext(); ) {
newDensePart.clear(bits.next());
}
return new SemiSparseMutableIntSet(
MutableSparseIntSet.diff(A.sparsePart, B.sparsePart), newDensePart);
} else {
OffsetBitVector newDensePart = new OffsetBitVector(A.densePart);
newDensePart.andNot(B.densePart);
for (IntIterator bits = B.sparsePart.intIterator(); bits.hasNext(); ) {
newDensePart.clear(bits.next());
}
MutableSparseIntSet C = MutableSparseIntSet.diff(A.sparsePart, B.sparsePart);
for (IntIterator bits = A.sparsePart.intIterator(); bits.hasNext(); ) {
int bit = bits.next();
if (B.densePart.get(bit)) {
C.remove(bit);
}
}
return new SemiSparseMutableIntSet(C, newDensePart);
}
}
}
}
| 21,268
| 27.320905
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/SemiSparseMutableIntSetFactory.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.util.TreeSet;
/** */
public class SemiSparseMutableIntSetFactory
implements MutableIntSetFactory<SemiSparseMutableIntSet> {
/** @throws IllegalArgumentException if set is null */
@Override
public SemiSparseMutableIntSet make(int[] set) {
if (set == null) {
throw new IllegalArgumentException("set is null");
}
if (set.length == 0) {
return make();
} else {
// XXX not very efficient.
TreeSet<Integer> T = new TreeSet<>();
for (int element : set) {
T.add(element);
}
SemiSparseMutableIntSet result = new SemiSparseMutableIntSet();
for (Integer I : T) {
result.add(I);
}
return result;
}
}
@Override
public SemiSparseMutableIntSet parse(String string) throws NumberFormatException {
int[] data = SparseIntSet.parseIntArray(string);
SemiSparseMutableIntSet result = new SemiSparseMutableIntSet();
for (int element : data) result.add(element);
return result;
}
@Override
public SemiSparseMutableIntSet makeCopy(IntSet x) {
SemiSparseMutableIntSet y = new SemiSparseMutableIntSet();
y.copySet(x);
return y;
}
@Override
public SemiSparseMutableIntSet make() {
return new SemiSparseMutableIntSet();
}
}
| 1,681
| 26.57377
| 84
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/SimpleIntVector.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.io.Serializable;
import java.util.Arrays;
/** simple implementation of IntVector */
public class SimpleIntVector implements IntVector, Serializable {
private static final long serialVersionUID = -7909547846468543777L;
private static final int MAX_SIZE = Integer.MAX_VALUE / 4;
private static final float GROWTH_FACTOR = 1.5f;
private static final int INITIAL_SIZE = 1;
int maxIndex = -1;
int[] store;
final int defaultValue;
public SimpleIntVector(int defaultValue) {
this.defaultValue = defaultValue;
store = new int[getInitialSize()];
store[0] = defaultValue;
}
public SimpleIntVector(int defaultValue, int initialSize) {
if (initialSize <= 0) {
throw new IllegalArgumentException("Illegal initialSize: " + initialSize);
}
this.defaultValue = defaultValue;
store = new int[initialSize];
store[0] = defaultValue;
}
int getInitialSize() {
return INITIAL_SIZE;
}
float getGrowthFactor() {
return GROWTH_FACTOR;
}
@Override
public int get(int x) {
if (x < 0) {
throw new IllegalArgumentException("illegal x: " + x);
}
if (x < store.length) {
return store[x];
} else {
return defaultValue;
}
}
@Override
public void set(int x, int value) {
if (x < 0) {
throw new IllegalArgumentException("illegal x: " + x);
}
if (x > MAX_SIZE) {
throw new IllegalArgumentException("x is too big: " + x);
}
maxIndex = Math.max(maxIndex, x);
if (value == defaultValue) {
if (x >= store.length) {
return;
} else {
store[x] = value;
}
} else {
ensureCapacity(x);
store[x] = value;
}
}
/** make sure we can store to a particular index */
private void ensureCapacity(int capacity) {
if (capacity >= store.length) {
int[] old = store;
store = Arrays.copyOf(old, 1 + (int) (getGrowthFactor() * capacity));
Arrays.fill(store, old.length, store.length, defaultValue);
}
}
public void performVerboseAction() {
System.err.println(("size: " + store.length));
System.err.println(("occupancy: " + computeOccupancy()));
}
/** @return the percentage of entries in delegateStore that are non-null */
private double computeOccupancy() {
int count1 = 0;
for (int element : store) {
if (element != -1) {
count1++;
}
}
int count = count1;
return (double) count / (double) store.length;
}
@Override
public int getMaxIndex() {
return maxIndex;
}
}
| 2,968
| 23.741667
| 80
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/SparseIntSet.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.TreeSet;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/** A sparse ordered, duplicate-free, fully-encapsulated set of integers; not necessary mutable */
public class SparseIntSet implements IntSet {
private static final long serialVersionUID = 2394141733718319022L;
private static final int SINGLETON_CACHE_SIZE = 5000;
private static final SparseIntSet[] singletonCache = new SparseIntSet[SINGLETON_CACHE_SIZE];
static {
for (int i = 0; i < SINGLETON_CACHE_SIZE; i++) {
singletonCache[i] = new SparseIntSet(new int[] {i});
}
}
// TODO: I'm not thrilled with exposing these to subclasses, but
// it seems expedient for now.
/** The backing store of int arrays */
@SuppressWarnings("NullAway.Init")
protected int[] elements;
/** The number of entries in the backing store that are valid. */
protected int size = 0;
protected SparseIntSet(int size) {
elements = new int[size];
this.size = size;
}
/**
* Subclasses should use this with extreme care. Do not allow the backing array to escape
* elsewhere.
*/
protected SparseIntSet(int[] backingArray) {
if (backingArray == null) {
throw new IllegalArgumentException("backingArray is null");
}
elements = backingArray;
this.size = backingArray.length;
}
/** Subclasses should use this with extreme care. */
@NullUnmarked
public SparseIntSet() {
elements = null;
this.size = 0;
}
protected SparseIntSet(SparseIntSet S) {
cloneState(S);
}
@NullUnmarked
private void cloneState(SparseIntSet S) {
if (S.elements != null) {
elements = S.elements.clone();
} else {
elements = null;
}
this.size = S.size;
}
public SparseIntSet(IntSet S) throws IllegalArgumentException {
if (S == null) {
throw new IllegalArgumentException("S == null");
}
if (S instanceof SparseIntSet) {
cloneState((SparseIntSet) S);
} else {
elements = new int[S.size()];
size = S.size();
S.foreach(
new IntSetAction() {
private int index = 0;
@Override
public void act(int i) {
elements[index++] = i;
}
});
}
}
/** Does this set contain value x? */
@Override
public final boolean contains(int x) {
if (elements == null) {
return false;
}
return IntSetUtil.binarySearch(elements, x, 0, size - 1) >= 0;
}
/** @return index i s.t. elements[i] == x, or -1 if not found. */
public final int getIndex(int x) {
if (elements == null) {
return -1;
}
return IntSetUtil.binarySearch(elements, x, 0, size - 1);
}
@Override
public final int size() {
return size;
}
@Override
public final boolean isEmpty() {
return size == 0;
}
public final int elementAt(int idx) throws NoSuchElementException {
if (idx < 0) {
throw new IllegalArgumentException("invalid idx: " + idx);
}
if (elements == null || idx >= size) {
throw new NoSuchElementException("Index: " + idx);
}
return elements[idx];
}
private boolean sameValueInternal(SparseIntSet that) {
if (size != that.size) {
return false;
} else {
for (int i = 0; i < size; i++) {
if (elements[i] != that.elements[i]) {
return false;
}
}
return true;
}
}
@Override
public boolean sameValue(IntSet that) throws IllegalArgumentException, UnimplementedError {
if (that == null) {
throw new IllegalArgumentException("that == null");
}
if (that instanceof SparseIntSet) {
return sameValueInternal((SparseIntSet) that);
} else if (that instanceof BimodalMutableIntSet) {
return that.sameValue(this);
} else if (that instanceof BitVectorIntSet) {
return that.sameValue(this);
} else if (that instanceof MutableSharedBitVectorIntSet) {
return sameValue(((MutableSharedBitVectorIntSet) that).makeSparseCopy());
} else {
Assertions.UNREACHABLE(that.getClass().toString());
return false;
}
}
/**
* @return true iff {@code this} is a subset of {@code that}.
* <p>Faster than: {@code this.diff(that) == EMPTY}.
*/
private boolean isSubsetInternal(SparseIntSet that) {
if (elements == null) return true;
if (that.elements == null) return false;
if (this.equals(that)) return true;
if (this.sameValue(that)) {
return true;
}
int[] ar = this.elements;
int ai = 0;
int al = size;
int[] br = that.elements;
int bi = 0;
int bl = that.size;
while (ai < al && bi < bl) {
int cmp = (ar[ai] - br[bi]);
// (fail when element only found in 'a')
if (cmp > 0) { // a greater
bi++;
} else if (cmp < 0) { // b greater
return false;
} else {
ai++;
bi++;
}
}
if (bi == bl && ai < al) {
// we ran off the end of b without finding an a
return false;
}
return true;
}
/** Compute the asymmetric difference of two sets, a \ b. */
public static SparseIntSet diff(SparseIntSet A, SparseIntSet B) {
return new SparseIntSet(diffInternal(A, B));
}
public static int[] diffInternal(SparseIntSet A, SparseIntSet B) {
if (A == null) {
throw new IllegalArgumentException("A is null");
}
if (B == null) {
throw new IllegalArgumentException("B is null");
}
if (A.isEmpty()) {
return new int[0];
} else if (B.isEmpty()) {
int[] newElts = new int[A.size];
System.arraycopy(A.elements, 0, newElts, 0, A.size);
return newElts;
} else if (A.equals(B)) {
return new int[0];
} else if (A.sameValue(B)) {
return new int[0];
}
int[] ar = A.elements;
int ai = 0;
int al = A.size;
int[] br = B.elements;
int bi = 0;
int bl = B.size;
int[] cr = new int[al];
// allocate enough (i.e. too much)
int ci = 0;
while (ai < al && bi < bl) {
int cmp = (ar[ai] - br[bi]);
// (accept element when only found in 'a')
if (cmp > 0) { // a greater
bi++;
} else if (cmp < 0) { // b greater
cr[ci++] = ar[ai];
ai++;
} else {
ai++;
bi++;
}
}
// append a's tail if any
if (ai < al) {
int tail = al - ai;
System.arraycopy(ar, ai, cr, ci, tail);
ci += tail;
}
// now compact cr to 'just enough'
ar = new int[ci];
System.arraycopy(cr, 0, ar, 0, ci); // ar := cr
return ar;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(6 * size);
sb.append("{ ");
if (elements != null) {
for (int ii = 0; ii < size; ii++) {
sb.append(elements[ii]);
sb.append(' ');
}
}
sb.append('}');
return sb.toString();
}
/**
* Reverse of toString(): "{2,3}" -> [2,3]
*
* @throws IllegalArgumentException if str is null
*/
public static int[] parseIntArray(String str) {
if (str == null) {
throw new IllegalArgumentException("str is null");
}
int len = str.length();
if (len == 0 || str.charAt(0) != '{' || str.charAt(len - 1) != '}') {
throw new IllegalArgumentException(str);
}
str = str.substring(1, len - 1);
StringTokenizer tok = new StringTokenizer(str, " ,");
// XXX not very efficient:
TreeSet<Integer> set = new TreeSet<>();
while (tok.hasMoreTokens()) {
set.add(Integer.decode(tok.nextToken()));
}
int[] result = new int[set.size()];
int i = 0;
for (Integer I : set) {
result[i++] = I;
}
return result;
}
public static SparseIntSet singleton(int i) {
if (i >= 0 && i < SINGLETON_CACHE_SIZE) {
return singletonCache[i];
} else {
return new SparseIntSet(new int[] {i});
}
}
public static SparseIntSet pair(int i, int j) {
if (i == j) {
return SparseIntSet.singleton(i);
}
if (j > i) {
return new SparseIntSet(new int[] {i, j});
} else {
return new SparseIntSet(new int[] {j, i});
}
}
@Override
public IntSet intersection(IntSet that) {
if (that == null) {
throw new IllegalArgumentException("that == null");
}
if (that instanceof SparseIntSet) {
MutableSparseIntSet temp = MutableSparseIntSet.make(this);
temp.intersectWith((SparseIntSet) that);
return temp;
} else if (that instanceof BitVectorIntSet) {
SparseIntSet s = ((BitVectorIntSet) that).toSparseIntSet();
MutableSparseIntSet temp = MutableSparseIntSet.make(this);
temp.intersectWith(s);
return temp;
} else if (that instanceof MutableSharedBitVectorIntSet) {
MutableSparseIntSet temp = MutableSparseIntSet.make(this);
temp.intersectWith(that);
return temp;
} else {
// this is really slow. optimize as needed.
MutableSparseIntSet temp = MutableSparseIntSet.makeEmpty();
for (IntIterator it = intIterator(); it.hasNext(); ) {
int x = it.next();
if (that.contains(x)) {
temp.add(x);
}
}
return temp;
}
}
@Override
public IntSet union(IntSet that) {
MutableSparseIntSet temp = new MutableSparseIntSet();
temp.addAll(this);
temp.addAll(that);
return temp;
}
@Override
public IntIterator intIterator() {
return new IntIterator() {
int i = 0;
@Override
public boolean hasNext() {
return (i < size);
}
@Override
public int next() throws NoSuchElementException {
if (elements == null) {
throw new NoSuchElementException();
}
return elements[i++];
}
};
}
/** @return the largest element in the set */
@Override
public final int max() throws IllegalStateException {
if (elements == null) {
throw new IllegalStateException("Illegal to ask max() on an empty int set");
}
return (size > 0) ? elements[size - 1] : -1;
}
@Override
public void foreach(IntSetAction action) {
if (action == null) {
throw new IllegalArgumentException("null action");
}
for (int i = 0; i < size; i++) action.act(elements[i]);
}
/** @see com.ibm.wala.util.intset.IntSet#foreach(com.ibm.wala.util.intset.IntSetAction) */
@Override
public void foreachExcluding(IntSet X, IntSetAction action) {
if (action == null) {
throw new IllegalArgumentException("null action");
}
for (int i = 0; i < size; i++) {
if (!X.contains(elements[i])) {
action.act(elements[i]);
}
}
}
/**
* @return a new sparse int set which adds j to s
* @throws IllegalArgumentException if s is null
*/
public static SparseIntSet add(SparseIntSet s, int j) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
if (s.elements == null) {
return SparseIntSet.singleton(j);
}
SparseIntSet result = new SparseIntSet(s.size + 1);
int k = 0;
int m = 0;
while (k < s.elements.length && s.elements[k] < j) {
result.elements[k++] = s.elements[m++];
}
if (k == s.size) {
result.elements[k] = j;
} else {
if (s.elements[k] == j) {
result.size--;
} else {
result.elements[k++] = j;
}
while (k < result.size) {
result.elements[k++] = s.elements[m++];
}
}
return result;
}
@Override
public boolean isSubset(@Nullable IntSet that) {
if (that == null) {
throw new IllegalArgumentException("null that");
}
if (that instanceof SparseIntSet) {
return isSubsetInternal((SparseIntSet) that);
} else if (that instanceof BitVectorIntSet) {
return isSubsetInternal((BitVectorIntSet) that);
} else {
// really slow. optimize as needed.
for (IntIterator it = intIterator(); it.hasNext(); ) {
if (!that.contains(it.next())) {
return false;
}
}
return true;
}
}
private boolean isSubsetInternal(BitVectorIntSet set) {
for (int i = 0; i < size; i++) {
if (!set.contains(elements[i])) {
return false;
}
}
return true;
}
@Override
public boolean containsAny(IntSet set) {
if (set instanceof SparseIntSet) {
return containsAny((SparseIntSet) set);
} else if (set instanceof BimodalMutableIntSet) {
return set.containsAny(this);
} else {
for (int i = 0; i < size; i++) {
if (set.contains(elements[i])) {
return true;
}
}
return false;
}
}
public boolean containsAny(SparseIntSet set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
int i = 0;
for (int j = 0; j < set.size; j++) {
int x = set.elements[j];
while (i < size && elements[i] < x) {
i++;
}
if (i == size) {
return false;
} else if (elements[i] == x) {
return true;
}
}
return false;
}
/** @return contents as an int[] */
public int[] toIntArray() {
int[] result = new int[size];
if (size > 0) {
System.arraycopy(elements, 0, result, 0, size);
}
return result;
}
}
| 13,878
| 25.0394
| 98
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/SparseIntVector.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.io.Serializable;
import java.util.Arrays;
/**
* an int vector implementation designed for low occupancy. Note that get() from this vector is a
* binary search.
*
* <p>This should only be used for small sets ... insertion and deletion are linear in size of set.
*/
public class SparseIntVector implements IntVector, Serializable {
private static final long serialVersionUID = -2428993854689991888L;
private static final int INITIAL_SIZE = 5;
private final double EXPANSION = 1.5;
int maxIndex = -1;
/** if indices[i] = x, then data[i] == get(x) */
private final MutableSparseIntSet indices = MutableSparseIntSet.makeEmpty();
private int[] data = new int[INITIAL_SIZE];
private final int defaultValue;
public SparseIntVector(int defaultValue) {
this.defaultValue = defaultValue;
}
@Override
public int get(int x) {
int index = indices.getIndex(x);
if (index == -1) {
return defaultValue;
} else {
return data[index];
}
}
/*
* TODO: this can be optimized
*
* @see com.ibm.wala.util.intset.IntVector#set(int, int)
*/
@Override
public void set(int x, int value) {
maxIndex = Math.max(maxIndex, x);
int index = indices.getIndex(x);
if (index == -1) {
indices.add(x);
index = indices.getIndex(x);
ensureCapacity(indices.size() + 1);
if (index < (data.length - 1)) {
System.arraycopy(data, index, data, index + 1, indices.size() - index);
}
}
data[index] = value;
}
private void ensureCapacity(int capacity) {
if (data.length < capacity + 1) {
data = Arrays.copyOf(data, 1 + (int) (capacity * EXPANSION));
}
}
/** @see com.ibm.wala.util.debug.VerboseAction#performVerboseAction() */
public void performVerboseAction() {
System.err.println((getClass() + " stats: "));
System.err.println(("data.length " + data.length));
System.err.println(("indices.size() " + indices.size()));
}
@Override
public int getMaxIndex() {
return maxIndex;
}
}
| 2,449
| 26.840909
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/SparseLongIntVector.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import java.util.Arrays;
/**
* an int vector implementation designed for low occupancy. Note that get() from this vector is a
* binary search.
*
* <p>This should only be used for small sets ... insertion and deletion are linear in size of set.
*
* <p>In this optimizations, the indices are longs.
*/
public class SparseLongIntVector {
private static final int INITIAL_SIZE = 5;
private final double EXPANSION = 1.5;
/** if indices[i] = x, then data[i] == get(x) */
private final MutableSparseLongSet indices = new MutableSparseLongSet();
private int[] data = new int[INITIAL_SIZE];
private final int defaultValue;
public SparseLongIntVector(int defaultValue) {
this.defaultValue = defaultValue;
}
/** @see com.ibm.wala.util.intset.IntVector#get(int) */
public int get(long x) {
int index = indices.getIndex(x);
if (index == -1) {
return defaultValue;
} else {
return data[index];
}
}
/*
* TODO: this can be optimized
*
* @see com.ibm.wala.util.intset.IntVector#set(int, int)
*/
public void set(long x, int value) {
int index = indices.getIndex(x);
if (index == -1) {
indices.add(x);
index = indices.getIndex(x);
ensureCapacity(indices.size() + 1);
if (index < (data.length - 1)) {
System.arraycopy(data, index, data, index + 1, indices.size() - index);
}
}
data[index] = value;
}
private void ensureCapacity(int capacity) {
if (data.length < capacity + 1) {
data = Arrays.copyOf(data, 1 + (int) (capacity * EXPANSION));
}
}
/** @see com.ibm.wala.util.debug.VerboseAction#performVerboseAction() */
public void performVerboseAction() {
System.err.println((getClass() + " stats: "));
System.err.println(("data.length " + data.length));
System.err.println(("indices.size() " + indices.size()));
}
}
| 2,285
| 27.222222
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/SparseLongSet.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import java.util.TreeSet;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/** A sparse ordered, duplicate-free, fully-encapsulated set of longs; not necessary mutable */
public class SparseLongSet implements LongSet {
private static final int SINGLETON_CACHE_SIZE = 0;
private static final SparseLongSet[] singletonCache = new SparseLongSet[SINGLETON_CACHE_SIZE];
static {
for (int i = 0; i < SINGLETON_CACHE_SIZE; i++) {
singletonCache[i] = new SparseLongSet(new long[] {i});
}
}
// TODO: I'm not thrilled with exposing these to subclasses, but
// it seems expedient for now.
/** The backing store of int arrays */
@SuppressWarnings("NullAway.Init")
protected long[] elements;
/** The number of entries in the backing store that are valid. */
protected int size = 0;
/////////////////////////////////////////////////////////////////////////////
//
// Constructors & Factories
//
/////////////////////////////////////////////////////////////////////////////
protected SparseLongSet(int size) {
elements = new long[size];
this.size = size;
}
/**
* Subclasses should use this with extreme care. Do not allow the backing array to escape
* elsewhere.
*/
protected SparseLongSet(long[] backingArray) {
if (backingArray == null) {
throw new IllegalArgumentException("backingArray is null");
}
elements = backingArray;
this.size = backingArray.length;
}
/** Subclasses should use this with extreme care. */
@NullUnmarked
public SparseLongSet() {
elements = null;
this.size = 0;
}
protected SparseLongSet(SparseLongSet S) {
cloneState(S);
}
private void cloneState(SparseLongSet S) {
elements = S.elements.clone();
this.size = S.size;
}
public SparseLongSet(IntSet S) throws IllegalArgumentException {
if (S == null) {
throw new IllegalArgumentException("S == null");
}
if (S instanceof SparseLongSet) {
cloneState((SparseLongSet) S);
} else {
elements = new long[S.size()];
size = S.size();
S.foreach(
new IntSetAction() {
private int index = 0;
@Override
public void act(int i) {
elements[index++] = i;
}
});
}
}
/**
* Does this set contain value x?
*
* @see com.ibm.wala.util.intset.IntSet#contains(int)
*/
@Override
public final boolean contains(long x) {
if (elements == null) {
return false;
}
return LongSetUtil.binarySearch(elements, x, 0, size - 1) >= 0;
}
/** @return index i s.t. elements[i] == x, or -1 if not found. */
public final int getIndex(long x) {
if (elements == null) {
return -1;
}
return LongSetUtil.binarySearch(elements, x, 0, size - 1);
}
@Override
public final int size() {
return size;
}
@Override
public final boolean isEmpty() {
return size == 0;
}
public final long elementAt(int idx) throws NoSuchElementException {
if (idx < 0 || idx >= size) {
throw new NoSuchElementException();
}
return elements[idx];
}
private boolean sameValueInternal(SparseLongSet that) {
if (size != that.size) {
return false;
} else {
for (int i = 0; i < size; i++) {
if (elements[i] != that.elements[i]) {
return false;
}
}
return true;
}
}
@Override
public boolean sameValue(LongSet that) throws IllegalArgumentException, UnimplementedError {
if (that == null) {
throw new IllegalArgumentException("that == null");
}
if (that instanceof SparseLongSet) {
return sameValueInternal((SparseLongSet) that);
} else {
Assertions.UNREACHABLE(that.getClass().toString());
return false;
}
}
/**
* @return true iff {@code this} is a subset of {@code that}.
* <p>Faster than: {@code this.diff(that) == EMPTY}.
*/
private boolean isSubsetInternal(SparseLongSet that) {
if (elements == null) return true;
if (that.elements == null) return false;
if (this.equals(that)) return true;
if (this.sameValue(that)) {
return true;
}
long[] ar = this.elements;
int ai = 0;
int al = size;
long[] br = that.elements;
int bi = 0;
int bl = that.size;
while (ai < al && bi < bl) {
long cmp = (ar[ai] - br[bi]);
// (fail when element only found in 'a')
if (cmp > 0) { // a greater
bi++;
} else if (cmp < 0) { // b greater
return false;
} else {
ai++;
bi++;
}
}
if (bi == bl && ai < al) {
// we ran off the end of b without finding an a
return false;
}
return true;
}
/**
* Compute the asymmetric difference of two sets, a \ b.
*
* @throws IllegalArgumentException if A is null
*/
public static SparseLongSet diff(SparseLongSet A, SparseLongSet B) {
if (A == null) {
throw new IllegalArgumentException("A is null");
}
if (B == null) {
throw new IllegalArgumentException("B is null");
}
if (A.isEmpty()) {
return new SparseLongSet(0);
} else if (B.isEmpty()) {
return new SparseLongSet(A);
} else if (A.equals(B)) {
return new SparseLongSet(0);
} else if (A.sameValue(B)) {
return new SparseLongSet(0);
}
long[] ar = A.elements;
int ai = 0;
int al = A.size;
long[] br = B.elements;
int bi = 0;
int bl = B.size;
long[] cr = new long[al];
// allocate enough (i.e. too much)
int ci = 0;
while (ai < al && bi < bl) {
long cmp = (ar[ai] - br[bi]);
// (accept element when only found in 'a')
if (cmp > 0) { // a greater
bi++;
} else if (cmp < 0) { // b greater
cr[ci++] = ar[ai];
ai++;
} else {
ai++;
bi++;
}
}
// append a's tail if any
if (ai < al) {
int tail = al - ai;
System.arraycopy(ar, ai, cr, ci, tail);
ci += tail;
}
// now compact cr to 'just enough'
ar = new long[ci];
System.arraycopy(cr, 0, ar, 0, ci); // ar := cr
return new SparseLongSet(ar);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(6 * size);
sb.append("{ ");
if (elements != null) {
for (int ii = 0; ii < size; ii++) {
sb.append(elements[ii]);
sb.append(' ');
}
}
sb.append('}');
return sb.toString();
}
/**
* Reverse of toString(): "{2,3}" -> [2,3]
*
* @throws IllegalArgumentException if str is null
*/
public static long[] parseLongArray(String str)
throws NumberFormatException, IllegalArgumentException {
if (str == null) {
throw new IllegalArgumentException("str is null");
}
int len = str.length();
if (len < 2) {
throw new IllegalArgumentException("malformed input: " + str);
}
if (str.charAt(0) != '{' || str.charAt(len - 1) != '}') {
throw new NumberFormatException(str);
}
str = str.substring(1, len - 1);
StringTokenizer tok = new StringTokenizer(str, " ,");
// XXX not very efficient:
TreeSet<Long> set = new TreeSet<>();
while (tok.hasMoreTokens()) {
set.add(Long.decode(tok.nextToken()));
}
long[] result = new long[set.size()];
int i = 0;
for (Long L : set) {
result[i++] = L;
}
return result;
}
public static SparseLongSet singleton(int i) {
if (i >= 0 && i < SINGLETON_CACHE_SIZE) {
return singletonCache[i];
} else {
return new SparseLongSet(new long[] {i});
}
}
public static SparseLongSet pair(long i, long j) {
if (j > i) {
return new SparseLongSet(new long[] {i, j});
} else {
return new SparseLongSet(new long[] {j, i});
}
}
/** @see com.ibm.wala.util.intset.IntSet#intersection(com.ibm.wala.util.intset.IntSet) */
@Nullable
@Override
public LongSet intersection(LongSet that) throws IllegalArgumentException, UnimplementedError {
if (that == null) {
throw new IllegalArgumentException("that == null");
}
if (that instanceof SparseLongSet) {
MutableSparseLongSet temp = MutableSparseLongSet.make(this);
temp.intersectWith((SparseLongSet) that);
return temp;
} else {
Assertions.UNREACHABLE("Unexpected: " + that.getClass());
return null;
}
}
/** @see com.ibm.wala.util.intset.IntSet#intIterator() */
@Override
public LongIterator longIterator() {
return new LongIterator() {
int i = 0;
@Override
public boolean hasNext() {
return (i < size);
}
@Override
public long next() throws NoSuchElementException {
if (elements == null) {
throw new NoSuchElementException();
}
return elements[i++];
}
};
}
@Override
public void foreach(LongSetAction action) {
if (action == null) {
throw new IllegalArgumentException("null action");
}
for (int i = 0; i < size; i++) action.act(elements[i]);
}
@Override
public void foreachExcluding(LongSet X, LongSetAction action) {
if (X == null) {
throw new IllegalArgumentException("null X");
}
if (action == null) {
throw new IllegalArgumentException("null action");
}
for (int i = 0; i < size; i++) {
if (!X.contains(elements[i])) {
action.act(elements[i]);
}
}
}
/** @return the largest element in the set */
@Override
public final long max() throws IllegalStateException {
if (elements == null) {
throw new IllegalStateException("Illegal to ask max() on an empty int set");
}
return (size > 0) ? elements[size - 1] : -1;
}
/** @return a new sparse int set which adds j to s */
public static SparseLongSet add(SparseLongSet s, int j) {
if (s == null || s.elements == null) {
return SparseLongSet.singleton(j);
}
SparseLongSet result = new SparseLongSet(s.size + 1);
int k = 0;
int m = 0;
while (k < s.elements.length && s.elements[k] < j) {
result.elements[k++] = s.elements[m++];
}
if (k == s.size) {
result.elements[k] = j;
} else {
if (s.elements[k] == j) {
result.size--;
} else {
result.elements[k++] = j;
}
while (k < result.size) {
result.elements[k++] = s.elements[m++];
}
}
return result;
}
/** @see com.ibm.wala.util.intset.IntSet#isSubset(com.ibm.wala.util.intset.IntSet) */
@Override
public boolean isSubset(LongSet that) throws IllegalArgumentException, UnimplementedError {
if (that == null) {
throw new IllegalArgumentException("that == null");
}
if (that instanceof SparseLongSet) {
return isSubsetInternal((SparseLongSet) that);
} else {
Assertions.UNREACHABLE("Unexpected type " + that.getClass());
return false;
}
}
/** @see com.ibm.wala.util.intset.IntSet#containsAny(com.ibm.wala.util.intset.IntSet) */
@Override
public boolean containsAny(LongSet set) {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
if (set instanceof SparseLongSet) {
return containsAny((SparseLongSet) set);
} else {
for (int i = 0; i < size; i++) {
if (set.contains(elements[i])) {
return true;
}
}
return false;
}
}
public boolean containsAny(SparseLongSet set) throws IllegalArgumentException {
if (set == null) {
throw new IllegalArgumentException("set == null");
}
int i = 0;
for (int j = 0; j < set.size; j++) {
long x = set.elements[j];
while (i < size && elements[i] < x) {
i++;
}
if (i == size) {
return false;
} else if (elements[i] == x) {
return true;
}
}
return false;
}
}
| 12,482
| 25.060543
| 97
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/TunedMutableSparseIntSet.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
/**
* A {@link MutableSparseIntSet} that allows for tuning of its initial size and expansion factor.
*
* @see #getInitialNonEmptySize()
* @see #getExpansionFactor()
*/
public class TunedMutableSparseIntSet extends MutableSparseIntSet {
private static final long serialVersionUID = -1559172158241923881L;
private final int initialSize;
private final float expansion;
public TunedMutableSparseIntSet(int initialSize, float expansion)
throws IllegalArgumentException {
super();
if (initialSize <= 0) {
throw new IllegalArgumentException("invalid initial size " + initialSize);
}
this.initialSize = initialSize;
this.expansion = expansion;
}
@Override
public float getExpansionFactor() {
return expansion;
}
@Override
public int getInitialNonEmptySize() {
return initialSize;
}
}
| 1,259
| 25.808511
| 97
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/TunedSimpleIntVector.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
/** a simple implementation of int vector that can be tuned to control space usage */
public class TunedSimpleIntVector extends SimpleIntVector {
private static final long serialVersionUID = -1380867351543398351L;
private final int initialSize;
private final float expansion;
TunedSimpleIntVector(int defaultValue, int initialSize, float expansion) {
super(defaultValue, initialSize);
this.initialSize = initialSize;
this.expansion = expansion;
}
@Override
float getGrowthFactor() {
return expansion;
}
@Override
int getInitialSize() {
return initialSize;
}
}
| 1,018
| 25.815789
| 85
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/intset/TwoLevelIntVector.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.intset;
import com.ibm.wala.util.math.Logs;
import java.io.Serializable;
import java.util.Vector;
/** an int vector implementation which delegates to pages of int vectors. */
public class TwoLevelIntVector implements IntVector, Serializable {
private static final long serialVersionUID = -7383053435395846217L;
private static final int PAGE_SIZE = 4096;
private static final int LOG_PAGE_SIZE = Logs.log2(PAGE_SIZE);
int maxIndex = -1;
/** Array of IntVector: data.get(i) holds data[i*PAGE_SIZE] ... data[(i+1)*PAGESIZE - 1] */
@SuppressWarnings("JdkObsolete") // uses Vector-specific APIs
private final Vector<SparseIntVector> data = new Vector<>();
private final int defaultValue;
TwoLevelIntVector(int defaultValue) {
this.defaultValue = defaultValue;
}
@Override
public int get(int x) {
int page = getPageNumber(x);
if (page >= data.size()) {
return defaultValue;
}
IntVector v = data.get(page);
if (v == null) {
return defaultValue;
}
int localX = toLocalIndex(x, page);
return v.get(localX);
}
private static int toLocalIndex(int x, int page) {
return x - getFirstIndexOnPage(page);
}
private static int getFirstIndexOnPage(int page) {
return page << LOG_PAGE_SIZE;
}
private static int getPageNumber(int x) {
return x >> LOG_PAGE_SIZE;
}
/*
* TODO: this can be optimized
*
* @see com.ibm.wala.util.intset.IntVector#set(int, int)
*/
@Override
public void set(int x, int value) {
maxIndex = Math.max(maxIndex, x);
int page = getPageNumber(x);
IntVector v = findOrCreatePage(page);
int localX = toLocalIndex(x, page);
v.set(localX, value);
}
private IntVector findOrCreatePage(int page) {
if (page >= data.size()) {
SparseIntVector v = new SparseIntVector(defaultValue);
data.setSize(page + 1);
data.add(page, v);
return v;
} else {
SparseIntVector v = data.get(page);
if (v == null) {
v = new SparseIntVector(defaultValue);
data.set(page, v);
}
return v;
}
}
/** @see com.ibm.wala.util.debug.VerboseAction#performVerboseAction() */
public void performVerboseAction() {
System.err.println(("stats of " + getClass()));
System.err.println(("data: size = " + data.size()));
}
@Override
public int getMaxIndex() {
return maxIndex;
}
}
| 2,795
| 25.628571
| 93
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/io/CommandLine.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.io;
import java.util.Properties;
import org.jspecify.annotations.Nullable;
/** utilities for parsing a command line */
public class CommandLine {
/**
* create a Properties object representing the properties set by the command line args. if args[i]
* is "-foo" and args[i+1] is "bar", then the result will define a property with key "foo" and
* value "bar"
*
* @throws IllegalArgumentException if args == null
*/
public static Properties parse(String[] args) throws IllegalArgumentException {
if (args == null) {
throw new IllegalArgumentException("args == null");
}
Properties result = new Properties();
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
// skip it
continue;
}
String key = parseForKey(args[i]);
if (key != null) {
if (args[i].contains("=")) {
result.put(key, args[i].substring(args[i].indexOf('=') + 1));
} else {
if ((i + 1) >= args.length || args[i + 1].charAt(0) == '-') {
throw new IllegalArgumentException(
"Malformed command-line. Must be of form -key=value or -key value");
}
result.put(key, args[i + 1]);
i++;
}
}
}
return result;
}
/** if string is of the form "-foo" or "-foo=", return "foo". else return null. */
@Nullable
private static String parseForKey(String string) {
if (string.charAt(0) == '-') {
if (string.contains("=")) {
return string.substring(1, string.indexOf('='));
} else {
return string.substring(1);
}
} else {
return null;
}
}
}
| 2,058
| 29.731343
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/io/FileUtil.java
|
/*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.io;
import com.ibm.wala.util.collections.HashSetFactory;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import org.jspecify.annotations.Nullable;
/** Simple utilities for accessing files. */
public class FileUtil {
/**
* List all the files in a directory that match a regular expression
*
* @param recurse recurse to subdirectories?
* @throws IllegalArgumentException if dir is null
*/
public static Collection<File> listFiles(String dir, String regex, boolean recurse) {
if (dir == null) {
throw new IllegalArgumentException("dir is null");
}
File d = new File(dir);
Pattern p = null;
if (regex != null) {
p = Pattern.compile(regex);
}
return listFiles(d, recurse, p);
}
private static Collection<File> listFiles(File directory, boolean recurse, @Nullable Pattern p) {
File[] files = directory.listFiles();
if (files == null) {
return Collections.emptyList();
}
HashSet<File> result = HashSetFactory.make();
for (File file : files) {
if (p == null || p.matcher(file.getAbsolutePath()).matches()) {
result.add(file);
}
if (recurse && file.isDirectory()) {
result.addAll(listFiles(file, recurse, p));
}
}
return result;
}
/**
* <a href="http://bugs.sun.com/view_bug.do?bug_id=4724038">This may be a resource leak.</a>
*
* <p>We may have to reconsider using nio for this, or apply one of the horrible workarounds
* listed in the bug report above.
*/
public static void copy(String srcFileName, String destFileName) throws IOException {
if (srcFileName == null) {
throw new IllegalArgumentException("srcFileName is null");
}
if (destFileName == null) {
throw new IllegalArgumentException("destFileName is null");
}
try (final FileInputStream srcStream = new FileInputStream(srcFileName);
final FileOutputStream dstStream = new FileOutputStream(destFileName);
final FileChannel src = srcStream.getChannel();
final FileChannel dest = dstStream.getChannel(); ) {
long n = src.size();
MappedByteBuffer buf = src.map(FileChannel.MapMode.READ_ONLY, 0, n);
dest.write(buf);
}
}
/**
* delete all files (recursively) in a directory. This is dangerous. Use with care.
*
* @throws IOException if there's a problem deleting some file
*/
public static void deleteContents(String directory) throws IOException {
File f = new File(directory);
if (!f.exists()) {
return;
}
if (!f.isDirectory()) {
throw new IOException(directory + " is not a vaid directory");
}
for (String s : f.list()) {
deleteRecursively(new File(f, s));
}
}
private static void deleteRecursively(File f) throws IOException {
if (f.isDirectory()) {
for (String s : f.list()) {
deleteRecursively(new File(f, s));
}
}
boolean b = f.delete();
if (!b) {
throw new IOException("failed to delete " + f);
}
}
/**
* Create a {@link FileOutputStream} corresponding to a particular file name. Delete the existing
* file if one exists.
*/
public static final FileOutputStream createFile(String fileName) throws IOException {
if (fileName == null) {
throw new IllegalArgumentException("null file");
}
File f = new File(fileName);
if (f.getParentFile() != null && !f.getParentFile().exists()) {
boolean result = f.getParentFile().mkdirs();
if (!result) {
throw new IOException("failed to create " + f.getParentFile());
}
}
if (f.exists()) {
f.delete();
}
boolean result = f.createNewFile();
if (!result) {
throw new IOException("failed to create " + f);
}
return new FileOutputStream(f);
}
/** read fully the contents of s and return a byte array holding the result */
public static byte[] readBytes(InputStream s) throws IOException {
if (s == null) {
throw new IllegalArgumentException("null s");
}
try (final ByteArrayOutputStream out = new ByteArrayOutputStream()) {
byte[] b = new byte[1024];
int n = s.read(b);
while (n != -1) {
out.write(b, 0, n);
n = s.read(b);
}
byte[] bb = out.toByteArray();
return bb;
}
}
/** write string s into file f */
public static void writeFile(File f, String content) throws IOException {
try (final Writer fw = Files.newBufferedWriter(f.toPath(), StandardCharsets.UTF_8)) {
fw.append(content);
}
}
public static void recurseFiles(Consumer<File> action, final Predicate<File> filter, File top) {
if (top.isDirectory()) {
for (File f : top.listFiles(file -> filter.test(file) || file.isDirectory())) {
recurseFiles(action, filter, f);
}
} else {
action.accept(top);
}
}
}
| 5,698
| 30.142077
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/io/JavaHome.java
|
package com.ibm.wala.util.io;
public class JavaHome {
public static void main(String[] args) {
System.err.println(System.getProperty("java.home"));
}
}
| 162
| 17.111111
| 56
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/io/RtJar.java
|
package com.ibm.wala.util.io;
import com.ibm.wala.util.PlatformUtil;
import com.ibm.wala.util.collections.ArrayIterator;
import com.ibm.wala.util.collections.FilterIterator;
import com.ibm.wala.util.collections.MapIterator;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.jar.JarFile;
import org.jspecify.annotations.NullUnmarked;
public class RtJar {
@NullUnmarked
public static JarFile getRtJar(Iterator<JarFile> x) {
while (x.hasNext()) {
JarFile JF = x.next();
switch (Paths.get(JF.getName()).getFileName().toString()) {
case "core.jar":
case "java.base.jmod":
case "rt.jar":
return JF;
case "classes.jar":
if (PlatformUtil.onMacOSX()) return JF;
// $FALL-THROUGH$
default:
}
}
return null;
}
public static void main(String[] args) {
@SuppressWarnings("resource")
JarFile rt =
getRtJar(
new MapIterator<>(
new FilterIterator<>(
new ArrayIterator<>(
System.getProperty("sun.boot.class.path").split(File.pathSeparator)),
t -> t.endsWith(".jar")),
object -> {
try {
return new JarFile(object);
} catch (IOException e) {
assert false : e.toString();
return null;
}
}));
System.err.println(rt.getName());
}
}
| 1,555
| 26.785714
| 93
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/io/Streams.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.io;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/** utilities for IO streams */
public class Streams {
/**
* @return byte[] holding the contents of the stream
* @throws IllegalArgumentException if in == null
*/
public static byte[] inputStream2ByteArray(InputStream in)
throws IllegalArgumentException, IOException {
if (in == null) {
throw new IllegalArgumentException("in == null");
}
ByteArrayOutputStream b = new ByteArrayOutputStream();
while (in.available() > 0) {
byte[] data = new byte[in.available()];
in.read(data);
b.write(data);
}
byte[] data = b.toByteArray();
return data;
}
}
| 1,118
| 27.692308
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/io/TemporaryFile.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.jspecify.annotations.Nullable;
public class TemporaryFile {
@Nullable private static Path outputDir;
public static File urlToFile(String fileName, URL input) throws IOException {
if (input == null) {
throw new NullPointerException("input == null");
}
if (outputDir == null) {
outputDir = Files.createTempDirectory("wala");
}
Path filePath = outputDir.resolve(fileName);
return urlToFile(filePath.toFile(), input);
}
public static File urlToFile(File F, URL input) throws IOException {
try (InputStream openStream = input.openStream()) {
return streamToFile(F, openStream);
}
}
public static File streamToFile(File F, InputStream... inputs) throws IOException {
try (final FileOutputStream output = new FileOutputStream(F)) {
int read;
byte[] buffer = new byte[1024];
for (InputStream input : inputs) {
while ((read = input.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
input.close();
}
}
return F;
}
public static File stringToFile(File F, String... inputs) throws IOException {
try (final FileOutputStream output = new FileOutputStream(F)) {
for (String input : inputs) {
output.write(input.getBytes(StandardCharsets.UTF_8));
}
}
return F;
}
}
| 1,979
| 27.285714
| 85
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/math/Factorial.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.util.math;
import java.math.BigInteger;
/** Factorial utilities */
public class Factorial {
/** Factorial */
public static long fact(long n) {
long result = 1;
for (long i = 1; i <= n; i++) result *= i;
return result;
}
/** Factorial */
public static BigInteger fact(BigInteger n) {
if (n == null) {
throw new IllegalArgumentException("n is null");
}
BigInteger result = BigInteger.ONE;
for (BigInteger i = BigInteger.ONE; i.compareTo(n) <= 0; i = i.add(BigInteger.ONE)) {
result = result.multiply(i);
}
return result;
}
/**
* Factorial on doubles; avoids overflow problems present when using integers.
*
* @param n arg on which to compute factorial
* @return (<code>double</code> approximation to) factorial of largest positive integer <= (n_
* + epsilon)
*/
public static double fact(double n) {
n += 1e-6;
double result = 1.0;
for (double i = 1; i <= n; i += 1.0) result *= i;
return result;
}
/** Factorial */
public static int fact(int n) {
int result = 1;
for (int i = 1; i <= n; i++) result *= i;
return result;
}
}
| 3,093
| 35.4
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/math/Logs.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*/
/*
* This file includes material derived from code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.util.math;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.intset.Bits;
/** simple utilities with logarithms */
public class Logs {
/** @return true iff x == 2^n for some integer n */
public static boolean isPowerOf2(int x) {
if (x < 0) {
return false;
} else {
return Bits.populationCount(x) == 1;
}
}
/** @param x where x == 2^n for some integer n */
public static int log2(int x) throws IllegalArgumentException {
if (!isPowerOf2(x)) {
throw new IllegalArgumentException();
}
int test = 1;
for (int i = 0; i < 31; i++) {
if (test == x) {
return i;
}
test <<= 1;
}
Assertions.UNREACHABLE();
return -1;
}
/** Binary log: finds the smallest power k such that 2^k >= n */
public static int binaryLogUp(int n) {
int k = 0;
while ((1 << k) < n) {
k++;
}
return k;
}
/** Binary log: finds the smallest power k such that 2^k >= n */
public static int binaryLogUp(long n) {
int k = 0;
while ((1L << k) < n) {
k++;
}
return k;
}
}
| 3,132
| 33.054348
| 78
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/math/LongUtil.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.math;
/** */
public class LongUtil {
public static long pack(int hi, int lo) {
return ((long) hi << 32) | lo;
}
}
| 525
| 25.3
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/perf/Stopwatch.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.perf;
/** Basic class to time events */
public class Stopwatch {
protected int count;
/** elapsed time in nanoseconds */
private long elapsedTime;
private long startTime;
public Stopwatch() {}
public void start() {
startTime = System.nanoTime();
}
public void stop() {
long endTime = System.nanoTime();
count++;
elapsedTime += (endTime - startTime);
}
/** @return elapsed time in ms */
public long getElapsedMillis() {
return elapsedTime / 1000000;
}
/** @return number of times this stopwatch was stopped */
public int getCount() {
return count;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("total: ").append(getElapsedMillis());
if (count > 0) {
sb.append(", inv: ").append(count);
sb.append(", avg: ").append(getElapsedMillis() / count);
}
return sb.toString();
}
}
| 1,316
| 22.517857
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/perf/StopwatchGC.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.perf;
/** A {@link Stopwatch} that also queries the free memory from the GC. This is mostly useless. */
public class StopwatchGC extends com.ibm.wala.util.perf.Stopwatch {
private final String name;
private long startMemory;
private long endMemory;
public StopwatchGC(String name) {
super();
this.name = name;
}
@Override
public final void start() {
if (count == 0) {
// when the GC stop watch is used for repeating events, we count from the first start to the
// last end.
// (a different approach would be to accumulate the delta's)
System.gc();
Runtime r = Runtime.getRuntime();
startMemory = r.totalMemory() - r.freeMemory();
}
super.start();
}
@Override
public final void stop() {
super.stop();
System.gc();
Runtime r = Runtime.getRuntime();
endMemory = r.totalMemory() - r.freeMemory();
}
public final String report() {
String result = "";
if (getCount() > 0) {
result += "Stopwatch: " + name + ' ' + getElapsedMillis() + " ms" + '\n';
}
if (getCount() == 1) {
result += " Footprint at entry: " + (float) startMemory / 1000000 + " MB\n";
result += " Footprint at exit: " + (float) endMemory / 1000000 + " MB\n";
result +=
" Delta: " + (float) (endMemory - startMemory) / 1000000 + " MB\n";
}
return result;
}
/** @return memory at the end of the phase, in MB */
public float getEndMemory() {
return (float) endMemory / 1000000;
}
/** @return memory at the end of the phase, in MB */
public float getStartMemory() {
return (float) startMemory / 1000000;
}
/** @return getEndMemory() - getStartMemory() */
public float getFootprint() {
return getEndMemory() - getStartMemory();
}
/** Returns the name for this timer. */
public String getName() {
return name;
}
@Override
public String toString() {
// if (count == 1){
// sb.append (", Footprint at entry: " + (float) startMemory / 1000000 + " MB");
// sb.append (", Footprint at exit: " + (float) endMemory / 1000000 + " MB");
// }
return super.toString() + ", Delta: " + (float) (endMemory - startMemory) / 1000000 + " MB";
}
}
| 2,667
| 28.318681
| 98
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/processes/BasicLauncher.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.processes;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.logging.Logger;
import org.jspecify.annotations.Nullable;
/** A generic process launcher */
public class BasicLauncher extends Launcher {
@Nullable protected String cmd;
public BasicLauncher(boolean captureOutput, boolean captureErr, Logger logger) {
super(captureOutput, captureErr, logger);
}
@Nullable
public String getCmd() {
return cmd;
}
public void setCmd(String newCmd) {
cmd = newCmd;
}
@Override
public String toString() {
return super.toString() + " (cmd: " + cmd;
}
/** Launch the process and wait until it is finished. Returns the exit value of the process. */
public int launch() throws IllegalArgumentException, IOException {
Process p = spawnProcess(getCmd());
Thread d1 = isCaptureErr() ? captureStdErr(p) : drainStdErr(p);
Thread d2 = isCaptureOutput() ? captureStdOut(p) : drainStdOut(p);
if (getInput() != null) {
try (final BufferedOutputStream input = new BufferedOutputStream(p.getOutputStream())) {
input.write(getInput(), 0, getInput().length);
input.flush();
} catch (IOException e) {
e.printStackTrace();
throw new IOException("error priming stdin", e);
}
}
try {
d1.join();
d2.join();
} catch (InterruptedException e) {
throw new Error("Internal error", e);
}
if (isCaptureErr()) {
Drainer d = (Drainer) d1;
setStdErr(d.getCapture().toByteArray());
}
if (isCaptureOutput()) {
Drainer d = (Drainer) d2;
setStdOut(d.getCapture().toByteArray());
}
return p.exitValue();
}
}
| 2,089
| 28.027778
| 97
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/processes/JavaLauncher.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.processes;
import com.ibm.wala.util.PlatformUtil;
import com.ibm.wala.util.collections.Iterator2Iterable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
import org.jspecify.annotations.Nullable;
/** A Java process launcher */
public class JavaLauncher extends Launcher {
/**
* @param programArgs arguments to be passed to the Java program
* @param mainClass Declaring class of the main() method to run.
* @param classpathEntries Paths that will be added to the default classpath
*/
public static JavaLauncher make(
String programArgs, String mainClass, List<String> classpathEntries, Logger logger) {
return new JavaLauncher(programArgs, mainClass, true, classpathEntries, false, false, logger);
}
/**
* @param programArgs arguments to be passed to the Java program
* @param mainClass Declaring class of the main() method to run.
* @param inheritClasspath Should the spawned process inherit all classpath entries of the
* currently running process?
* @param classpathEntries Paths that will be added to the default classpath
* @param captureOutput should the launcher capture the stdout from the subprocess?
* @param captureErr should the launcher capture the stderr from the subprocess?
*/
public static JavaLauncher make(
String programArgs,
String mainClass,
boolean inheritClasspath,
List<String> classpathEntries,
boolean captureOutput,
boolean captureErr,
Logger logger) {
if (mainClass == null) {
throw new IllegalArgumentException("null mainClass");
}
return new JavaLauncher(
programArgs,
mainClass,
inheritClasspath,
classpathEntries,
captureOutput,
captureErr,
logger);
}
/** arguments to be passed to the Java program */
private String programArgs;
/** Declaring class of the main() method to run. */
private final String mainClass;
/** Should the spawned process inherit all classpath entries of the currently running process? */
private final boolean inheritClasspath;
/** Should assertions be enabled in the subprocess? default false. */
private boolean enableAssertions;
/** Paths that will be added to the default classpath */
private final List<String> xtraClasspath = new ArrayList<>();
/** A {@link Thread} which spins and drains stdout of the running process. */
@Nullable private Thread stdOutDrain;
/** A {@link Thread} which spins and drains stderr of the running process. */
@Nullable private Thread stdErrDrain;
/** Absolute path of the 'java' executable to use. */
private String javaExe;
/** Extra args to pass to the JVM */
private final List<String> vmArgs = new ArrayList<>();
/** The last process returned by a call to start() on this object. */
@Nullable private Process lastProcess;
private JavaLauncher(
String programArgs,
String mainClass,
boolean inheritClasspath,
List<String> xtraClasspath,
boolean captureOutput,
boolean captureErr,
Logger logger) {
super(captureOutput, captureErr, logger);
this.programArgs = programArgs;
this.mainClass = mainClass;
this.inheritClasspath = inheritClasspath;
if (xtraClasspath != null) {
this.xtraClasspath.addAll(xtraClasspath);
}
this.javaExe = defaultJavaExe();
}
public String getJavaExe() {
return javaExe;
}
public void setJavaExe(String javaExe) {
this.javaExe = javaExe;
}
public void setProgramArgs(String s) {
this.programArgs = s;
}
public String getProgramArgs() {
return programArgs;
}
public String getMainClass() {
return mainClass;
}
public List<String> getXtraClassPath() {
return xtraClasspath;
}
@Override
public String toString() {
return super.toString()
+ " (programArgs: "
+ programArgs
+ ", mainClass: "
+ mainClass
+ ", xtraClasspath: "
+ xtraClasspath
+ ')';
}
/** @return the string that identifies the java executable file */
public static String defaultJavaExe() {
String java =
System.getProperty("java.home") + File.separatorChar + "bin" + File.separatorChar + "java";
return java;
}
/** Launch the java process. */
public Process start() throws IllegalArgumentException, IOException {
String cp = makeClasspath();
String heap = "-Xmx800M";
// on Mac, need to pass an extra parameter so we can cleanly kill child
// Java process
String signalParam = PlatformUtil.onMacOSX() ? "-Xrs" : null;
List<String> cmd = new ArrayList<>();
cmd.add(javaExe);
cmd.add(heap);
if (signalParam != null) {
cmd.add(signalParam);
}
cmd.add("-classpath");
cmd.add(cp);
String libPath = makeLibPath();
if (libPath != null) {
cmd.add(libPath);
}
if (enableAssertions) {
cmd.add("-ea");
}
if (vmArgs != null) {
cmd.addAll(vmArgs);
}
cmd.add(getMainClass());
if (getProgramArgs() != null) {
String[] pa = getProgramArgs().split(" ");
for (String s : pa) {
if (s.length() > 0) {
cmd.add(s);
}
}
}
String[] cmds = new String[cmd.size()];
cmd.toArray(cmds);
Process p = spawnProcess(cmds);
stdErrDrain = isCaptureErr() ? captureStdErr(p) : drainStdErr(p);
stdOutDrain = isCaptureOutput() ? captureStdOut(p) : drainStdOut(p);
lastProcess = p;
return p;
}
@Nullable
public Process getLastProcess() {
return lastProcess;
}
@Nullable
private static String makeLibPath() {
String libPath = System.getProperty("java.library.path");
if (libPath == null) {
return null;
} else {
return "-Djava.library.path=" + libPath.trim();
}
}
/**
* Wait for the spawned process to terminate.
*
* @throws IllegalStateException if the process has not been started
*/
public void join() {
if (stdOutDrain == null || stdErrDrain == null) {
throw new IllegalStateException("process not started. illegal to join()");
}
try {
stdOutDrain.join();
stdErrDrain.join();
} catch (InterruptedException e) {
e.printStackTrace();
throw new InternalError("Internal error in JavaLauncher.join()");
}
if (isCaptureErr()) {
Drainer d = (Drainer) stdErrDrain;
setStdErr(d.getCapture().toByteArray());
}
if (isCaptureOutput()) {
Drainer d = (Drainer) stdOutDrain;
setStdOut(d.getCapture().toByteArray());
}
}
/** Compute the classpath for the spawned process */
public String makeClasspath() {
final StringBuilder cp =
inheritClasspath
? new StringBuilder(System.getProperty("java.class.path"))
: new StringBuilder();
if (getXtraClassPath() != null && !getXtraClassPath().isEmpty()) {
for (String p : Iterator2Iterable.make(getXtraClassPath().iterator())) {
cp.append(File.pathSeparatorChar);
cp.append(p);
}
}
return cp.toString().trim();
}
/**
* If the input string contains a space, quote it (for use as a classpath). TODO: Figure out how
* to make a Mac happy with quotes. Trailing separators are unsafe, so we have to escape the last
* backslash (if present and unescaped), so it doesn't escape the closing quote.
*/
@Deprecated
public static String quoteStringIfNeeded(String s) {
s = s.trim();
// s = s.replaceAll(" ", "\\\\ ");
return s;
// Check if there's a space. If not, skip quoting to make Macs happy.
// TODO: Add the check for an escaped space.
// if (s.indexOf(' ') == -1) {
// return s;
// }
// if (s.charAt(s.length() - 1) == '\\' && s.charAt(s.length() - 2) != '\\')
// {
// s += '\\'; // Escape the last backslash, so it doesn't escape the quote.
// }
// return '\"' + s + '\"';
}
public boolean isEnableAssertions() {
return enableAssertions;
}
public void setEnableAssertions(boolean enableAssertions) {
this.enableAssertions = enableAssertions;
}
public void addVmArg(String arg) {
this.vmArgs.add(arg);
}
public List<String> getVmArgs() {
return Collections.unmodifiableList(vmArgs);
}
}
| 8,771
| 28.24
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/processes/Launcher.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.processes;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Map;
import java.util.logging.Logger;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/** Abstract base class for a process launcher */
public abstract class Launcher {
// use a fairly big buffer size to avoid performance problems with the default
private static final int BUFFER_SIZE = 32 * 1024;
@Nullable protected File workingDir = null;
@Nullable protected Map<String, String> env = null;
protected byte @Nullable [] stdOut = null;
protected byte @Nullable [] stdErr = null;
private byte @Nullable [] input = null;
/** capture the contents of stdout? */
private final boolean captureOutput;
/** capture the contents of stderr? */
private final boolean captureErr;
private final Logger logger;
protected Launcher(Logger logger) {
super();
this.captureOutput = false;
this.captureErr = false;
this.logger = logger;
}
protected Launcher(boolean captureOutput, boolean captureErr, Logger logger) {
super();
this.captureOutput = captureOutput;
this.captureErr = captureErr;
this.logger = logger;
}
@Nullable
public File getWorkingDir() {
return workingDir;
}
public void setWorkingDir(File newWorkingDir) {
workingDir = newWorkingDir;
}
@Nullable
public Map<String, String> getEnv() {
return env;
}
public void setEnv(Map<String, String> newEnv) {
env = newEnv;
}
@Override
public String toString() {
return super.toString() + " (workingDir: " + workingDir + ", env: " + env + ')';
}
/**
* Spawn a process to execute the given command
*
* @return an object representing the process
*/
protected Process spawnProcess(@Nullable String cmd)
throws IllegalArgumentException, IOException {
if (cmd == null) {
throw new IllegalArgumentException("cmd cannot be null");
}
if (logger != null) {
logger.info("spawning process " + cmd);
}
String[] ev = getEnv() == null ? null : buildEnv(getEnv());
Process p = Runtime.getRuntime().exec(cmd, ev, getWorkingDir());
return p;
}
/**
* Spawn a process to execute the given command
*
* @return an object representing the process
*/
protected Process spawnProcess(String[] cmd) throws IllegalArgumentException, IOException {
if (cmd == null) {
throw new IllegalArgumentException("cmd cannot be null");
}
if (logger != null) {
logger.info("spawning process " + Arrays.toString(cmd));
}
String[] ev = getEnv() == null ? null : buildEnv(getEnv());
Process p = Runtime.getRuntime().exec(cmd, ev, getWorkingDir());
return p;
}
private static String[] buildEnv(Map<String, String> ev) {
String[] result = new String[ev.size()];
int i = 0;
for (Map.Entry<String, String> e : ev.entrySet()) {
result[i++] = e.getKey() + '=' + e.getValue();
}
return result;
}
protected Thread drainStdOut(Process p) {
final BufferedInputStream out = new BufferedInputStream(p.getInputStream(), BUFFER_SIZE);
Thread result =
new Drainer(p) {
@Override
void drain() throws IOException {
drainAndPrint(out, System.out);
}
@Override
void blockingDrain() throws IOException {
blockingDrainAndPrint(out, System.out);
}
};
result.start();
return result;
}
protected Drainer captureStdOut(Process p) {
final BufferedInputStream out = new BufferedInputStream(p.getInputStream(), BUFFER_SIZE);
final ByteArrayOutputStream b = new ByteArrayOutputStream(BUFFER_SIZE);
Drainer result =
new Drainer(p) {
@Override
void drain() throws IOException {
drainAndCatch(out, b);
}
@Override
void blockingDrain() throws IOException {
blockingDrainAndCatch(out, b);
}
};
result.setCapture(b);
result.start();
return result;
}
protected Thread drainStdErr(Process p) {
final BufferedInputStream err = new BufferedInputStream(p.getErrorStream(), BUFFER_SIZE);
Thread result =
new Drainer(p) {
@Override
void drain() throws IOException {
drainAndPrint(err, System.err);
}
@Override
void blockingDrain() throws IOException {
blockingDrainAndPrint(err, System.err);
}
};
result.start();
return result;
}
protected Drainer captureStdErr(Process p) {
final BufferedInputStream out = new BufferedInputStream(p.getErrorStream(), BUFFER_SIZE);
final ByteArrayOutputStream b = new ByteArrayOutputStream(BUFFER_SIZE);
Drainer result =
new Drainer(p) {
@Override
void drain() throws IOException {
drainAndCatch(out, b);
}
@Override
void blockingDrain() throws IOException {
blockingDrainAndCatch(out, b);
}
};
result.setCapture(b);
result.start();
return result;
}
/** A thread that runs in a loop, performing the drain() action until a process terminates */
protected abstract class Drainer extends Thread {
// how many ms to sleep before waking up to check the streams?
private static final int SLEEP_MS = 5;
private final Process p;
@Nullable private ByteArrayOutputStream capture;
/** Drain data from the stream, but don't block. */
abstract void drain() throws IOException;
/** Drain data from the stream until it is finished. Block if necessary. */
abstract void blockingDrain() throws IOException;
Drainer(Process p) {
this.p = p;
}
@Override
public void run() {
try {
boolean repeat = true;
while (repeat) {
try {
Thread.sleep(SLEEP_MS);
} catch (InterruptedException e1) {
// e1.printStackTrace();
// just ignore and continue
}
drain();
try {
p.exitValue();
// if we get here, the process has terminated
repeat = false;
blockingDrain();
if (logger != null) {
logger.fine("process terminated with exit code " + p.exitValue());
}
} catch (IllegalThreadStateException e) {
// this means the process has not yet terminated.
repeat = true;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
@NullUnmarked
public ByteArrayOutputStream getCapture() {
return capture;
}
public void setCapture(ByteArrayOutputStream capture) {
this.capture = capture;
}
}
/** Drain some data from the input stream, and print said data to p. Do not block. */
private static void drainAndPrint(BufferedInputStream s, PrintStream p) {
try {
while (s.available() > 0) {
byte[] data = new byte[s.available()];
s.read(data);
p.print(new String(data, StandardCharsets.UTF_8));
}
} catch (IOException e) {
// assume the stream has been closed (e.g. the process died)
// so, just exit
}
}
/** Drain all data from the input stream, and print said data to p. Block if necessary. */
private static void blockingDrainAndPrint(BufferedInputStream s, PrintStream p) {
ByteArrayOutputStream b = new ByteArrayOutputStream();
try {
// gather all the data from the stream.
int next = s.read();
while (next != -1) {
b.write(next);
next = s.read();
}
} catch (IOException e) {
// assume the stream has been closed (e.g. the process died)
// so, just print the data and then leave
}
// print the data.
p.print(b);
}
/** Drain some data from the input stream, and append said data to b. Do not block. */
private static void drainAndCatch(BufferedInputStream s, ByteArrayOutputStream b) {
try {
while (s.available() > 0) {
byte[] data = new byte[s.available()];
int nRead = s.read(data);
b.write(data, 0, nRead);
}
} catch (IOException e) {
// assume the stream has been closed (e.g. the process died)
// so, just exit
}
}
/** Drain all data from the input stream, and append said data to p. Block if necessary. */
private static void blockingDrainAndCatch(BufferedInputStream s, ByteArrayOutputStream b) {
try {
int next = s.read();
while (next != -1) {
b.write(next);
next = s.read();
}
} catch (IOException e) {
// assume the stream has been closed (e.g. the process died)
// so, just exit
}
}
public boolean isCaptureOutput() {
return captureOutput;
}
public boolean isCaptureErr() {
return captureErr;
}
@NullUnmarked
@Nullable
public byte[] getStdOut() {
return stdOut;
}
@NullUnmarked
@Nullable
public byte[] getStderr() {
return stdErr;
}
protected void setStdOut(byte[] newOutput) {
stdOut = newOutput;
}
protected void setStdErr(byte[] newErr) {
stdErr = newErr;
}
@NullUnmarked
@Nullable
public byte[] getInput() {
return input;
}
/** Set input which will be fed to the launched process's stdin */
public void setInput(byte[] input) {
this.input = input;
}
}
| 10,019
| 26.377049
| 95
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/tables/Query.java
|
/*
* Copyright (c) 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.tables;
import com.ibm.wala.util.collections.HashSetFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.function.Predicate;
import org.jspecify.annotations.NullUnmarked;
/** Misc SQL-like support for queries on tables */
public class Query {
/**
* SELECT * from t where column=value
*
* @throws IllegalArgumentException if t == null
*/
@NullUnmarked
public static <T> Collection<Map<String, T>> selectStarWhereEquals(
Table<T> t, String column, T value) throws IllegalArgumentException {
if (t == null) {
throw new IllegalArgumentException("t == null");
}
Collection<Map<String, T>> result = new ArrayList<>();
for (int i = 0; i < t.getNumberOfRows(); i++) {
Map<String, T> p = t.row2Map(i);
if (p.get(column).equals(value)) {
result.add(p);
}
}
return result;
}
/** SELECT attribute FROM t where column=value */
public static <T> Collection<T> selectWhereEquals(
Table<T> t, String attribute, String column, T value) {
Collection<Map<String, T>> rows = selectStarWhereEquals(t, column, value);
Collection<T> result = HashSetFactory.make();
for (Map<String, T> p : rows) {
result.add(p.get(attribute));
}
return result;
}
/** SELECT attribute FROM t where P(column) */
public static <T> Collection<Map<String, T>> selectStarWhere(
Table<T> t, String column, Predicate<T> P) {
if (t == null) {
throw new IllegalArgumentException("t == null");
}
Collection<Map<String, T>> c = new ArrayList<>();
for (int i = 0; i < t.getNumberOfRows(); i++) {
Map<String, T> p = t.row2Map(i);
T s = p.get(column);
if (P.test(s)) {
c.add(p);
}
}
return c;
}
public static <T> Table<T> viewWhereEquals(Table<T> t, String column, T value) {
Collection<Map<String, T>> c = selectStarWhereEquals(t, column, value);
Table<T> result = new Table<>(t);
for (Map<String, T> p : c) {
result.addRow(p);
}
return result;
}
public static StringTable viewWhereEquals(StringTable t, String column, String value) {
Collection<Map<String, String>> c = selectStarWhereEquals(t, column, value);
StringTable result = new StringTable(t);
for (Map<String, String> p : c) {
result.addRow(p);
}
return result;
}
}
| 2,779
| 29.888889
| 89
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/tables/StringTable.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.tables;
import com.ibm.wala.util.collections.SimpleVector;
import com.ibm.wala.util.debug.Assertions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.nio.charset.StandardCharsets;
import java.util.StringTokenizer;
import org.jspecify.annotations.Nullable;
/** */
public class StringTable extends Table<String> implements Cloneable {
/** create an empty table */
public StringTable() {
super();
}
/** create an empty table with the same column headings as t */
public StringTable(StringTable t) {
super(t);
}
/** create an empty table with the given column headings */
public StringTable(String[] columns) {
super(columns);
}
/**
* read from a direct (native) text file
*
* @throws IllegalArgumentException if fileName is null
*/
public static StringTable readFromDirectTextFile(String fileName, Character comment)
throws FileNotFoundException, IOException {
if (fileName == null) {
throw new IllegalArgumentException("fileName is null");
}
File f = new File(fileName);
return readFromTextFile(f, comment);
}
// /**
// * read from a text file obtained as a resource
// */
// public static StringTable readFromTextFile(String fileName, Character comment) throws
// IOException {
// if (fileName == null) {
// throw new IllegalArgumentException("null fileName");
// }
// File f = FileProvider.getFile(fileName);
// return readFromTextFile(f, comment);
// }
/** @param f a file containing a table in text format, whitespace delimited */
public static StringTable readFromTextFile(File f, Character comment)
throws FileNotFoundException, IOException {
if (f == null) {
throw new IllegalArgumentException("null f");
}
try (final FileInputStream in = new FileInputStream(f)) {
return readFromStream(in, comment);
}
}
/**
* @param s a stream containing a table in text format, whitespace delimited
* @throws IllegalArgumentException if s is null
*/
public static StringTable readFromStream(InputStream s, Character commentToken)
throws IOException {
return readFromStream(s, commentToken, null);
}
/**
* @param s a stream containing a table in text format, whitespace delimited
* @throws IllegalArgumentException if s is null
*/
public static StringTable readFromStream(
InputStream s, Character commentToken, @Nullable Character delimiter) throws IOException {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
StringTable result = new StringTable();
LineNumberReader reader =
new LineNumberReader(new InputStreamReader(s, StandardCharsets.UTF_8));
// LineNumberReader reader = new LineNumberReader(new
// InputStreamReader(new FileInputStream(f)));
String line = readNextNonCommentLine(reader, commentToken);
if (line == null) {
throw new IOException("first line expected to be column headings");
}
result.populateColumnHeadings(line, delimiter);
line = readNextNonCommentLine(reader, commentToken);
int row = 0;
while (line != null) {
result.populateRow(row, line, delimiter);
line = readNextNonCommentLine(reader, commentToken);
row++;
}
return result;
}
public static String readNextNonCommentLine(LineNumberReader reader, Character commentToken)
throws IOException {
if (reader == null) {
throw new IllegalArgumentException("reader is null");
}
String line = reader.readLine();
while (line != null && isCommented(line, commentToken)) {
line = reader.readLine();
}
return line;
}
private static boolean isCommented(String line, Character commentToken) {
if (line.length() == 0) {
return true;
}
if (commentToken == null) {
return false;
}
return line.charAt(0) == commentToken;
}
private void populateRow(int row, String line, @Nullable Character delimiter) {
StringTokenizer st =
delimiter == null
? new StringTokenizer(line)
: new StringTokenizer(line, delimiter.toString());
int nColumns = st.countTokens();
Assertions.productionAssertion(
nColumns == getNumberOfColumns(),
"expected "
+ getNumberOfColumns()
+ " got "
+ nColumns
+ " row "
+ row
+ ' '
+ line.length()
+ ' '
+ line);
SimpleVector<String> r = new SimpleVector<>();
rows.add(row, r);
for (int i = 0; i < nColumns; i++) {
r.set(i, (String) st.nextElement());
}
}
/** @param line a whitespace-delimited string of column names */
private void populateColumnHeadings(String line, @Nullable Character delimiter) {
StringTokenizer st =
delimiter == null
? new StringTokenizer(line)
: new StringTokenizer(line, delimiter.toString());
int nColumns = st.countTokens();
for (int i = 0; i < nColumns; i++) {
columnHeadings.set(i, (String) st.nextElement());
}
}
@Override
public Object clone() throws CloneNotSupportedException {
StringTable result = new StringTable(this);
for (int i = 0; i < getNumberOfRows(); i++) {
result.addRow(row2Map(i));
}
return result;
}
}
| 5,907
| 29.931937
| 96
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/tables/Table.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.tables;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.SimpleVector;
import com.ibm.wala.util.intset.BitVector;
import java.util.ArrayList;
import java.util.Map;
/** */
public class Table<T> {
// table is implemented as an ArrayList of rows. Each row is a SimpleVector<T>.
protected final ArrayList<SimpleVector<T>> rows = new ArrayList<>();
// SimpleVector<String> ... headings of columns
protected final SimpleVector<String> columnHeadings = new SimpleVector<>();
/** create an empty table */
public Table() {}
/**
* create an empty table with the same column headings as t
*
* @throws IllegalArgumentException if t == null
*/
public Table(Table<T> t) throws IllegalArgumentException {
if (t == null) {
throw new IllegalArgumentException("t == null");
}
for (int i = 0; i < t.getNumberOfColumns(); i++) {
columnHeadings.set(i, t.getColumnHeading(i));
}
}
/**
* create an empty table with the given column headings
*
* @throws IllegalArgumentException if columns == null, or columns[i] == null for some i
*/
public Table(String[] columns) throws IllegalArgumentException {
if (columns == null) {
throw new IllegalArgumentException("columns == null");
}
for (int i = 0; i < columns.length; i++) {
if (columns[i] == null) {
throw new IllegalArgumentException("columns[" + i + "] is null");
}
columnHeadings.set(i, columns[i]);
}
}
@Override
public String toString() {
int[] format = computeColumnWidths();
StringBuilder result = new StringBuilder();
for (int i = 0; i < getNumberOfColumns(); i++) {
StringBuilder heading = new StringBuilder(getColumnHeading(i));
padWithSpaces(heading, format[i]);
result.append(heading);
}
result.append('\n');
for (int j = 0; j < getNumberOfRows(); j++) {
for (int i = 0; i < getNumberOfColumns(); i++) {
T e = getElement(j, i);
StringBuilder element = e == null ? new StringBuilder() : new StringBuilder(e.toString());
padWithSpaces(element, format[i]);
result.append(element);
}
result.append('\n');
}
return result.toString();
}
public synchronized T getElement(int row, int column) {
try {
SimpleVector<T> r = rows.get(row);
return r.get(column);
} catch (IndexOutOfBoundsException e) {
throw new IllegalArgumentException("row: " + row + " column: " + column, e);
}
}
/** Note that column indices start at zero */
public synchronized String getColumnHeading(int i) {
return columnHeadings.get(i);
}
public int[] computeColumnWidths() {
int[] result = new int[getNumberOfColumns()];
for (int i = 0; i < getNumberOfColumns(); i++) {
result[i] = columnHeadings.get(i).length() + 1;
}
for (int j = 0; j < getNumberOfRows(); j++) {
for (int i = 0; i < getNumberOfColumns(); i++) {
T element = getElement(j, i);
result[i] =
element == null ? result[i] : Math.max(result[i], element.toString().length() + 1);
}
}
return result;
}
public synchronized int getNumberOfColumns() {
return columnHeadings.getMaxIndex() + 1;
}
public synchronized int getNumberOfRows() {
return rows.size();
}
public synchronized Map<String, T> row2Map(int row) {
Map<String, T> result = HashMapFactory.make();
for (int j = 0; j < getNumberOfColumns(); j++) {
result.put(getColumnHeading(j), getElement(row, j));
}
return result;
}
public synchronized void addRow(Map<String, T> p) {
if (p == null) {
throw new IllegalArgumentException("null p " + p);
}
SimpleVector<T> r = new SimpleVector<>();
rows.add(r);
for (int i = 0; i < getNumberOfColumns(); i++) {
r.set(i, p.get(getColumnHeading(i)));
}
}
public synchronized void removeRow(Map<String, T> p) {
if (p == null) {
throw new IllegalArgumentException("p is null");
}
BitVector toRemove = new BitVector();
for (int i = 0; i < rows.size(); i++) {
Map<String, T> row = row2Map(i);
if (row.equals(p)) {
toRemove.set(i);
}
}
for (int i = 0; i < rows.size(); i++) {
if (toRemove.get(i)) {
rows.remove(i);
}
}
}
public static void padWithSpaces(StringBuilder b, int length) {
if (b == null) {
throw new IllegalArgumentException("b is null");
}
if (b.length() < length) {
b.append(" ".repeat(length - b.length()));
}
}
}
| 4,983
| 28.844311
| 98
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/viz/DotUtil.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.viz;
import com.ibm.wala.util.WalaException;
import com.ibm.wala.util.collections.Iterator2Collection;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.graph.Graph;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Collection;
import org.jspecify.annotations.Nullable;
/** utilities for interfacing with DOT */
public class DotUtil {
/** possible output formats for dot */
public enum DotOutputType {
PS("ps"),
SVG("svg"),
PDF("pdf"),
EPS("eps");
public final String suffix;
DotOutputType(final String suffix) {
this.suffix = suffix;
}
}
private static DotOutputType outputType = DotOutputType.PDF;
private static int fontSize = 6;
private static final String fontColor = "black";
private static final String fontName = "Arial";
public static void setOutputType(DotOutputType outType) {
outputType = outType;
}
public static DotOutputType getOutputType() {
return outputType;
}
private static String outputTypeCmdLineParam() {
return "-T" + outputType.suffix;
}
/** Some versions of dot appear to croak on long labels. Reduce this if so. */
private static final int MAX_LABEL_LENGTH = Integer.MAX_VALUE;
/** @param <T> the type of a graph node */
public static <T> void dotify(
Graph<T> g, NodeDecorator<T> labels, String dotFile, String outputFile, String dotExe)
throws WalaException {
dotify(g, labels, null, dotFile, outputFile, dotExe);
}
/** @param <T> the type of a graph node */
public static <T> void dotify(
Graph<T> g,
NodeDecorator<T> labels,
@Nullable String title,
String dotFile,
String outputFile,
String dotExe)
throws WalaException {
if (g == null) {
throw new IllegalArgumentException("g is null");
}
File f = DotUtil.writeDotFile(g, labels, title, dotFile);
if (dotExe != null) {
spawnDot(dotExe, outputFile, f);
}
}
public static void spawnDot(String dotExe, String outputFile, File dotFile) throws WalaException {
if (dotFile == null) {
throw new IllegalArgumentException("dotFile is null");
}
String[] cmdarray = {
dotExe, outputTypeCmdLineParam(), "-o", outputFile, "-v", dotFile.getAbsolutePath()
};
System.out.println("spawning process " + Arrays.toString(cmdarray));
BufferedInputStream output = null;
BufferedInputStream error = null;
try {
Process p = Runtime.getRuntime().exec(cmdarray);
output = new BufferedInputStream(p.getInputStream());
error = new BufferedInputStream(p.getErrorStream());
boolean repeat = true;
while (repeat) {
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
// just ignore and continue
}
if (output.available() > 0) {
byte[] data = new byte[output.available()];
int nRead = output.read(data);
System.err.println("read " + nRead + " bytes from output stream");
}
if (error.available() > 0) {
byte[] data = new byte[error.available()];
int nRead = error.read(data);
System.err.println("read " + nRead + " bytes from error stream");
}
try {
p.exitValue();
// if we get here, the process has terminated
repeat = false;
System.out.println("process terminated with exit code " + p.exitValue());
} catch (IllegalThreadStateException e) {
// this means the process has not yet terminated.
repeat = true;
}
}
} catch (IOException e) {
e.printStackTrace();
throw new WalaException("IOException in " + DotUtil.class);
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (error != null) {
try {
error.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static <T> File writeDotFile(
Graph<T> g, NodeDecorator<T> labels, @Nullable String title, String dotfile)
throws WalaException {
if (g == null) {
throw new IllegalArgumentException("g is null");
}
StringBuilder dotStringBuffer = dotOutput(g, labels, title);
// retrieve the filename parameter to this component, a String
if (dotfile == null) {
throw new WalaException("internal error: null filename parameter");
}
try {
File f = new File(dotfile);
try (Writer fw = Files.newBufferedWriter(f.toPath(), StandardCharsets.UTF_8)) {
fw.write(dotStringBuffer.toString());
}
return f;
} catch (Exception e) {
throw new WalaException("Error writing dot file " + dotfile, e);
}
}
/** @return StringBuffer holding dot output representing G */
public static <T> StringBuilder dotOutput(
Graph<T> g, NodeDecorator<T> labels, @Nullable String title) throws WalaException {
StringBuilder result = new StringBuilder("digraph \"DirectedGraph\" {\n");
if (title != null) {
result
.append("graph [label = \"")
.append(title)
.append("\", labelloc=t, concentrate = true];");
} else {
result.append("graph [concentrate = true];");
}
String rankdir = getRankDir();
if (rankdir != null) {
result.append("rankdir=").append(rankdir).append(';');
}
String fontsizeStr = "fontsize=" + fontSize;
String fontcolorStr = ",fontcolor=" + fontColor;
String fontnameStr = ",fontname=" + fontName;
result.append("center=true;");
result.append(fontsizeStr);
result.append(";node [ color=blue,shape=\"box\"");
result.append(fontsizeStr);
result.append(fontcolorStr);
result.append(fontnameStr);
result.append("];edge [ color=black,");
result.append(fontsizeStr);
result.append(fontcolorStr);
result.append(fontnameStr);
result.append("]; \n");
Collection<T> dotNodes = computeDotNodes(g);
outputNodes(labels, result, dotNodes);
for (T n : g) {
for (T s : Iterator2Iterable.make(g.getSuccNodes(n))) {
result.append(' ');
result.append(getPort(n, labels));
result.append(" -> ");
result.append(getPort(s, labels));
result.append(" \n");
}
}
result.append("\n}");
return result;
}
private static <T> void outputNodes(
NodeDecorator<T> labels, StringBuilder result, Collection<T> dotNodes) throws WalaException {
for (T t : dotNodes) {
outputNode(labels, result, t);
}
}
private static <T> void outputNode(NodeDecorator<T> labels, StringBuilder result, T n)
throws WalaException {
result.append(" ");
result.append('\"');
result.append(getLabel(n, labels));
result.append('\"');
result.append(decorateNode(n, labels));
}
/** Compute the nodes to visualize */
private static <T> Collection<T> computeDotNodes(Graph<T> g) {
return Iterator2Collection.toSet(g.iterator());
}
@Nullable
private static String getRankDir() {
return null;
}
/**
* @param n node to decorate
* @param d decorating master
*/
private static <T> String decorateNode(T n, NodeDecorator<T> d) throws WalaException {
return " [ label=\"" + getLabel(n, d) + "\"]\n";
}
private static <T> String getLabel(T n, NodeDecorator<T> d) throws WalaException {
String result = null;
if (d == null) {
result = n.toString();
} else {
result = d.getLabel(n);
result = result == null ? n.toString() : result;
}
if (result.length() >= MAX_LABEL_LENGTH) {
result = result.substring(0, MAX_LABEL_LENGTH - 3) + "...";
}
return result;
}
private static <T> String getPort(T n, NodeDecorator<T> d) throws WalaException {
return '"' + getLabel(n, d) + '"';
}
public static int getFontSize() {
return fontSize;
}
public static void setFontSize(int fontSize) {
DotUtil.fontSize = fontSize;
}
}
| 8,671
| 28.903448
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/viz/NodeDecorator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.viz;
import com.ibm.wala.util.WalaException;
/** @param <T> the node type */
public interface NodeDecorator<T> {
/** @return the String label for node n */
String getLabel(T n) throws WalaException;
}
| 609
| 28.047619
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/viz/PDFViewLauncher.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.viz;
import com.ibm.wala.util.WalaException;
import java.io.IOException;
import java.util.Arrays;
import org.jspecify.annotations.Nullable;
/**
* Launch gsview on a postscript file
*
* <p>TODO: inherit from a launcher?
*/
public class PDFViewLauncher {
@Nullable private Process process;
/** Name of the postscript file to view */
@Nullable protected String pdffile = null;
/** Path to ghostview executable */
@Nullable protected String gvExe = null;
public PDFViewLauncher() {
super();
}
@Nullable
public String getPDFFile() {
return pdffile;
}
public void setPDFFile(String newPsfile) {
pdffile = newPsfile;
}
@Nullable
public String getGvExe() {
return gvExe;
}
public void setGvExe(String newGvExe) {
gvExe = newGvExe;
}
@Override
public String toString() {
return super.toString() + ", psfile: " + pdffile + ", gvExe: " + gvExe + ')';
}
@Nullable private WalaException exception = null;
/** @see java.lang.Runnable#run() */
public void run() {
String[] cmdarray = {getGvExe(), getPDFFile()};
try {
Process p = Runtime.getRuntime().exec(cmdarray);
setProcess(p);
} catch (IOException e) {
e.printStackTrace();
exception = new WalaException("gv invocation failed for\n" + Arrays.toString(cmdarray));
}
}
@Nullable
public WalaException getException() {
return exception;
}
@Nullable
public Process getProcess() {
return process;
}
public void setProcess(Process process) {
this.process = process;
}
}
| 1,964
| 21.329545
| 94
|
java
|
WALA
|
WALA-master/util/src/test/java/com/ibm/wala/util/test/BasicGraphTest.java
|
/*
* Copyright (c) 2021 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Manu Sridharan - initial API and implementation
*/
package com.ibm.wala.util.test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import com.ibm.wala.util.collections.Iterator2Collection;
import com.ibm.wala.util.graph.impl.BasicGraph;
import org.junit.Assert;
import org.junit.Test;
/** Tests for {@link com.ibm.wala.util.graph.impl.BasicGraph}. */
public class BasicGraphTest {
@Test
public void testSingleEdge() {
BasicGraph<String> graph = new BasicGraph<>();
String root = "root";
String leaf = "leaf";
graph.addNode(root);
graph.addNode(leaf);
graph.addEdge(root, leaf);
Assert.assertTrue(graph.containsNode(root));
Assert.assertTrue(graph.containsNode(leaf));
assertThat(Iterator2Collection.toList(graph.getPredNodes(leaf)), contains(root));
assertThat(Iterator2Collection.toList(graph.getSuccNodes(root)), contains(leaf));
}
}
| 1,253
| 32
| 85
|
java
|
GBST
|
GBST-master/gbst_src/dmlc-core/tracker/yarn/src/main/java/org/apache/hadoop/yarn/dmlc/ApplicationMaster.java
|
package org.apache.hadoop.yarn.dmlc;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.yarn.util.ConverterUtils;
import org.apache.hadoop.yarn.util.Records;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.api.ApplicationConstants;
import org.apache.hadoop.yarn.api.protocolrecords.RegisterApplicationMasterResponse;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerExitStatus;
import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
import org.apache.hadoop.yarn.api.records.ContainerState;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.LocalResource;
import org.apache.hadoop.yarn.api.records.LocalResourceType;
import org.apache.hadoop.yarn.api.records.LocalResourceVisibility;
import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.ContainerStatus;
import org.apache.hadoop.yarn.api.records.NodeReport;
import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest;
import org.apache.hadoop.yarn.client.api.async.NMClientAsync;
import org.apache.hadoop.yarn.client.api.async.AMRMClientAsync;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
/**
* application master for allocating resources of dmlc client
*
* @author Tianqi Chen
*/
public class ApplicationMaster {
// logger
private static final Log LOG = LogFactory.getLog(ApplicationMaster.class);
// configuration
private Configuration conf = new YarnConfiguration();
// hdfs handler
private FileSystem dfs;
// number of cores allocated for each worker task
private int workerCores = 1;
// number of cores allocated for each server task
private int serverCores = 1;
// memory needed requested for the worker task
private int workerMemoryMB = 10;
// memory needed requested for the server task
private int serverMemoryMB = 10;
// priority of the workers tasks
private int workerPriority = 1;
// priority of the server nodes
private int serverPriority = 2;
// total number of workers
private int numWorker = 1;
// total number of server
private int numServer = 0;
// total number of tasks
private int numTasks;
// maximum number of attempts to try in each task
private int maxNumAttempt = 3;
// command to launch
private String command = "";
// username
private String userName = "";
// user credentials
private Credentials credentials = null;
// application tracker hostname
private String appHostName = "";
// tracker URL to do
private String appTrackerUrl = "";
// tracker port
private int appTrackerPort = 0;
// whether we start to abort the application, due to whatever fatal reasons
private boolean startAbort = false;
// worker resources
private Map<String, LocalResource> workerResources = new java.util.HashMap<String, LocalResource>();
// record the aborting reason
private String abortDiagnosis = "";
// resource manager
private AMRMClientAsync<ContainerRequest> rmClient = null;
// node manager
private NMClientAsync nmClient = null;
// list of tasks that pending for resources to be allocated
private final Queue<TaskRecord> pendingTasks = new java.util.LinkedList<TaskRecord>();
// map containerId->task record of tasks that was running
private final Map<ContainerId, TaskRecord> runningTasks = new java.util.HashMap<ContainerId, TaskRecord>();
// collection of tasks
private final Collection<TaskRecord> finishedTasks = new java.util.LinkedList<TaskRecord>();
// collection of killed tasks
private final Collection<TaskRecord> killedTasks = new java.util.LinkedList<TaskRecord>();
// worker environment
private final Map<String, String> env = new java.util.HashMap<String, String>();
//add the blacklist
private Collection<String> blackList = new java.util.HashSet();
public static void main(String[] args) throws Exception {
new ApplicationMaster().run(args);
}
private ApplicationMaster() throws IOException {
dfs = FileSystem.get(conf);
userName = UserGroupInformation.getCurrentUser().getShortUserName();
credentials = UserGroupInformation.getCurrentUser().getCredentials();
}
/**
* setup security token given current user
* @return the ByeBuffer containing the security tokens
* @throws IOException
*/
private ByteBuffer setupTokens() {
try {
DataOutputBuffer dob = new DataOutputBuffer();
credentials.writeTokenStorageToStream(dob);
return ByteBuffer.wrap(dob.getData(), 0, dob.getLength()).duplicate();
} catch (IOException e) {
throw new RuntimeException(e); // TODO: FIXME
}
}
/**
* get integer argument from environment variable
*
* @param name
* name of key
* @param required
* whether this is required
* @param defv
* default value
* @return the requested result
*/
private int getEnvInteger(String name, boolean required, int defv)
throws IOException {
String value = System.getenv(name);
if (value == null) {
if (required) {
throw new IOException("environment variable " + name
+ " not set");
} else {
return defv;
}
}
return Integer.valueOf(value);
}
/**
* initialize from arguments and command lines
*
* @param args
*/
private void initArgs(String args[]) throws IOException {
LOG.info("Start AM as user=" + this.userName);
// get user name
userName = UserGroupInformation.getCurrentUser().getShortUserName();
// cached maps
Map<String, Path> cacheFiles = new java.util.HashMap<String, Path>();
for (int i = 0; i < args.length; ++i) {
if (args[i].equals("-file")) {
String[] arr = args[++i].split("#");
Path path = new Path(arr[0]);
if (arr.length == 1) {
cacheFiles.put(path.getName(), path);
} else {
cacheFiles.put(arr[1], path);
}
} else if (args[i].equals("-env")) {
String[] pair = args[++i].split("=", 2);
env.put(pair[0], (pair.length == 1) ? "" : pair[1]);
} else {
this.command += args[i] + " ";
}
}
for (Map.Entry<String, Path> e : cacheFiles.entrySet()) {
LocalResource r = Records.newRecord(LocalResource.class);
FileStatus status = dfs.getFileStatus(e.getValue());
r.setResource(ConverterUtils.getYarnUrlFromPath(e.getValue()));
r.setSize(status.getLen());
r.setTimestamp(status.getModificationTime());
r.setType(LocalResourceType.FILE);
r.setVisibility(LocalResourceVisibility.APPLICATION);
workerResources.put(e.getKey(), r);
}
workerCores = this.getEnvInteger("DMLC_WORKER_CORES", true, workerCores);
serverCores = this.getEnvInteger("DMLC_SERVER_CORES", true, serverCores);
workerMemoryMB = this.getEnvInteger("DMLC_WORKER_MEMORY_MB", true, workerMemoryMB);
serverMemoryMB = this.getEnvInteger("DMLC_SERVER_MEMORY_MB", true, serverMemoryMB);
numWorker = this.getEnvInteger("DMLC_NUM_WORKER", true, numWorker);
numServer = this.getEnvInteger("DMLC_NUM_SERVER", true, numServer);
numTasks = numWorker + numServer;
maxNumAttempt = this.getEnvInteger("DMLC_MAX_ATTEMPT", false,
maxNumAttempt);
LOG.info("Try to start " + numServer + " Servers and " + numWorker + " Workers");
}
/**
* called to start the application
*/
private void run(String args[]) throws Exception {
this.initArgs(args);
this.rmClient = AMRMClientAsync.createAMRMClientAsync(1000,
new RMCallbackHandler());
this.nmClient = NMClientAsync
.createNMClientAsync(new NMCallbackHandler());
this.rmClient.init(conf);
this.rmClient.start();
this.nmClient.init(conf);
this.nmClient.start();
RegisterApplicationMasterResponse response = this.rmClient
.registerApplicationMaster(this.appHostName,
this.appTrackerPort, this.appTrackerUrl);
boolean success = false;
String diagnostics = "";
try {
// list of tasks that waits to be submit
java.util.Collection<TaskRecord> tasks = new java.util.LinkedList<TaskRecord>();
// add waiting tasks
for (int i = 0; i < this.numWorker; ++i) {
tasks.add(new TaskRecord(i, "worker"));
}
for (int i = 0; i < this.numServer; ++i) {
tasks.add(new TaskRecord(i, "server"));
}
Resource maxResource = response.getMaximumResourceCapability();
if (maxResource.getMemory() < this.serverMemoryMB) {
LOG.warn("[DMLC] memory requested exceed bound "
+ maxResource.getMemory());
this.serverMemoryMB = maxResource.getMemory();
}
if (maxResource.getMemory() < this.workerMemoryMB) {
LOG.warn("[DMLC] memory requested exceed bound "
+ maxResource.getMemory());
this.workerMemoryMB = maxResource.getMemory();
}
if (maxResource.getVirtualCores() < this.workerCores) {
LOG.warn("[DMLC] cores requested exceed bound "
+ maxResource.getVirtualCores());
this.workerCores = maxResource.getVirtualCores();
}
if (maxResource.getVirtualCores() < this.serverCores) {
LOG.warn("[DMLC] cores requested exceed bound "
+ maxResource.getVirtualCores());
this.serverCores = maxResource.getVirtualCores();
}
this.submitTasks(tasks);
LOG.info("[DMLC] ApplicationMaster started");
while (!this.doneAllJobs()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
assert (killedTasks.size() + finishedTasks.size() == numTasks);
success = finishedTasks.size() == numTasks;
LOG.info("Application completed. Stopping running containers");
diagnostics = "Diagnostics." + ", num_tasks" + this.numTasks
+ ", finished=" + this.finishedTasks.size() + ", failed="
+ this.killedTasks.size() + "\n" + this.abortDiagnosis;
LOG.info(diagnostics);
} catch (Exception e) {
diagnostics = e.toString();
}
rmClient.unregisterApplicationMaster(
success ? FinalApplicationStatus.SUCCEEDED
: FinalApplicationStatus.FAILED, diagnostics,
appTrackerUrl);
if (!success)
throw new Exception("Application not successful");
}
/**
* check if the job finishes
*
* @return whether we finished all the jobs
*/
private synchronized boolean doneAllJobs() {
return pendingTasks.size() == 0 && runningTasks.size() == 0;
}
/**
* submit tasks to request containers for the tasks
*
* @param tasks
* a collection of tasks we want to ask container for
*/
private synchronized void submitTasks(Collection<TaskRecord> tasks) {
for (TaskRecord r : tasks) {
Resource resource = Records.newRecord(Resource.class);
Priority priority = Records.newRecord(Priority.class);
if (r.taskRole == "server") {
resource.setMemory(serverMemoryMB);
resource.setVirtualCores(serverCores);
priority.setPriority(this.serverPriority);
} else {
resource.setMemory(workerMemoryMB);
resource.setVirtualCores(workerCores);
priority.setPriority(this.workerPriority);
}
r.containerRequest = new ContainerRequest(resource, null, null,
priority);
rmClient.addContainerRequest(r.containerRequest);
pendingTasks.add(r);
}
}
private synchronized void launchDummyTask(Container container){
ContainerLaunchContext ctx = Records.newRecord(ContainerLaunchContext.class);
String new_command = "./launcher.py";
String cmd = new_command + " 1>"
+ ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stdout"
+ " 2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR
+ "/stderr";
ctx.setCommands(Collections.singletonList(cmd));
ctx.setTokens(setupTokens());
ctx.setLocalResources(this.workerResources);
synchronized (this){
this.nmClient.startContainerAsync(container, ctx);
}
}
/**
* launch the task on container
*
* @param container
* container to run the task
* @param task
* the task
*/
private void launchTask(Container container, TaskRecord task) {
task.container = container;
task.containerRequest = null;
ContainerLaunchContext ctx = Records
.newRecord(ContainerLaunchContext.class);
String cmd =
// use this to setup CLASSPATH correctly for libhdfs
this.command + " 1>"
+ ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stdout"
+ " 2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR
+ "/stderr";
ctx.setCommands(Collections.singletonList(cmd));
// TODO: token was not right
ctx.setTokens(setupTokens());
LOG.info(workerResources);
ctx.setLocalResources(this.workerResources);
// setup environment variables
boolean isWindows = System.getProperty("os.name").startsWith("Windows");
// setup class path, this is kind of duplicated, ignoring
String classPathStr = isWindows? "%CLASSPATH%" : "${CLASSPATH}";
StringBuilder cpath = new StringBuilder(classPathStr
+ File.pathSeparatorChar
+ "./*");
for (String c : conf.getStrings(
YarnConfiguration.YARN_APPLICATION_CLASSPATH,
YarnConfiguration.DEFAULT_YARN_APPLICATION_CLASSPATH)) {
if (isWindows) c = c.replace('\\', '/');
String[] arrPath = c.split("" + File.pathSeparatorChar);
for (String ps : arrPath) {
if (ps.endsWith("*.jar")
|| ps.endsWith("*")
|| ps.endsWith("/")) {
ps = ps.substring(0, ps.lastIndexOf('*'));
if (ps.startsWith("$") || ps.startsWith("%")) {
String[] arr =ps.split("/", 2);
if (arr.length != 2) continue;
try {
String vname = isWindows ?
arr[0].substring(1, arr[0].length() - 1) :
arr[0].substring(1);
String vv = System.getenv(vname);
if (isWindows) vv = vv.replace('\\', '/');
ps = vv + '/' + arr[1];
} catch (Exception e){
continue;
}
}
File dir = new File(ps);
if (dir.isDirectory()) {
for (File f: dir.listFiles()) {
if (f.isFile() && f.getPath().endsWith(".jar")) {
cpath.append(File.pathSeparatorChar);
cpath.append(ps + '/' + f.getName());
}
}
}
cpath.append(File.pathSeparatorChar);
cpath.append(ps + '/');
} else {
cpath.append(File.pathSeparatorChar);
cpath.append(ps.trim());
}
}
}
// already use hadoop command to get class path in worker, maybe a
// better solution in future
env.put("CLASSPATH", cpath.toString());
// setup LD_LIBARY_PATH path for libhdfs
String oldLD_LIBRARY_PATH = System.getenv("LD_LIBRARY_PATH");
env.put("LD_LIBRARY_PATH",
oldLD_LIBRARY_PATH == null ? "" : oldLD_LIBRARY_PATH + ":$HADOOP_HDFS_HOME/lib/native:$JAVA_HOME/jre/lib/amd64/server");
env.put("PYTHONPATH", "${PYTHONPATH}:.");
// inherit all rabit variables
for (Map.Entry<String, String> e : System.getenv().entrySet()) {
if (e.getKey().startsWith("DMLC_")) {
env.put(e.getKey(), e.getValue());
}
if (e.getKey().startsWith("rabit_")) {
env.put(e.getKey(), e.getValue());
}
if (e.getKey().startsWith("AWS_")) {
env.put(e.getKey(), e.getValue());
}
if (e.getKey() == "LIBHDFS_OPTS") {
env.put(e.getKey(), e.getValue());
}
}
String nodeHost = container.getNodeId().getHost();
env.put("DMLC_NODE_HOST", nodeHost);
env.put("DMLC_TASK_ID", String.valueOf(task.taskId));
env.put("DMLC_ROLE", task.taskRole);
env.put("DMLC_NUM_ATTEMPT", String.valueOf(task.attemptCounter));
// ctx.setUser(userName);
ctx.setEnvironment(env);
LOG.info(env);
synchronized (this) {
assert (!this.runningTasks.containsKey(container.getId()));
this.runningTasks.put(container.getId(), task);
this.nmClient.startContainerAsync(container, ctx);
}
}
/**
* free the containers that have not yet been launched
*
* @param containers
*/
private synchronized void onStartContainerError(ContainerId cid) {
ApplicationMaster.this.handleFailure(Collections.singletonList(cid));
}
/**
* free the containers that have not yet been launched
*
* @param containers
*/
private synchronized void freeUnusedContainers(
Collection<Container> containers) {
if(containers.size() == 0) return;
for(Container c : containers){
launchDummyTask(c);
}
}
/**
* handle method for AMRMClientAsync.CallbackHandler container allocation
*
* @param containers
*/
private synchronized void onContainersAllocated(List<Container> containers) {
if (this.startAbort) {
this.freeUnusedContainers(containers);
return;
}
Collection<Container> freelist = new java.util.LinkedList<Container>();
for (Container c : containers) {
if(blackList.contains(c.getNodeHttpAddress())){
launchDummyTask(c);
continue;
}
TaskRecord task;
task = pendingTasks.poll();
if (task == null) {
freelist.add(c);
continue;
}
this.launchTask(c, task);
}
this.freeUnusedContainers(freelist);
}
/**
* start aborting the job
*
* @param msg
* the fatal message
*/
private synchronized void abortJob(String msg) {
if (!this.startAbort)
this.abortDiagnosis = msg;
this.startAbort = true;
for (TaskRecord r : this.runningTasks.values()) {
if (!r.abortRequested) {
nmClient.stopContainerAsync(r.container.getId(),
r.container.getNodeId());
r.abortRequested = true;
this.killedTasks.add(r);
}
}
this.killedTasks.addAll(this.pendingTasks);
for (TaskRecord r : this.pendingTasks) {
rmClient.removeContainerRequest(r.containerRequest);
}
this.pendingTasks.clear();
this.runningTasks.clear();
LOG.info(msg);
}
/**
* handle non fatal failures
*
* @param cid
*/
private synchronized void handleFailure(Collection<ContainerId> failed) {
Collection<TaskRecord> tasks = new java.util.LinkedList<TaskRecord>();
for (ContainerId cid : failed) {
TaskRecord r = runningTasks.remove(cid);
if (r == null) {
continue;
}
LOG.info("Task "
+ r.taskId
+ " failed on "
+ r.container.getId()
+ ". See LOG at : "
+ String.format("http://%s/node/containerlogs/%s/"
+ userName, r.container.getNodeHttpAddress(),
r.container.getId()));
r.attemptCounter += 1;
//stop the failed container and add it to blacklist
nmClient.stopContainerAsync(r.container.getId(), r.container.getNodeId());
blackList.add(r.container.getNodeHttpAddress());
r.container = null;
tasks.add(r);
if (r.attemptCounter >= this.maxNumAttempt) {
this.abortJob("[DMLC] Task " + r.taskId + " failed more than "
+ r.attemptCounter + "times");
}
}
if (this.startAbort) {
this.killedTasks.addAll(tasks);
} else {
this.submitTasks(tasks);
}
}
/**
* handle method for AMRMClientAsync.CallbackHandler container allocation
*
* @param status
* list of status
*/
private synchronized void onContainersCompleted(List<ContainerStatus> status) {
Collection<ContainerId> failed = new java.util.LinkedList<ContainerId>();
for (ContainerStatus s : status) {
assert (s.getState().equals(ContainerState.COMPLETE));
int exstatus = s.getExitStatus();
TaskRecord r = runningTasks.get(s.getContainerId());
if (r == null)
continue;
if (exstatus == ContainerExitStatus.SUCCESS) {
finishedTasks.add(r);
runningTasks.remove(s.getContainerId());
} else {
try {
if (exstatus == ContainerExitStatus.class.getField(
"KILLED_EXCEEDED_PMEM").getInt(null)) {
this.abortJob("[DMLC] Task "
+ r.taskId
+ " killed because of exceeding allocated physical memory");
return;
}
if (exstatus == ContainerExitStatus.class.getField(
"KILLED_EXCEEDED_VMEM").getInt(null)) {
this.abortJob("[DMLC] Task "
+ r.taskId
+ " killed because of exceeding allocated virtual memory");
return;
}
} catch (Exception e) {
LOG.warn(e.getMessage());
}
LOG.info("[DMLC] Task " + r.taskId + " exited with status "
+ exstatus + " Diagnostics:"+ s.getDiagnostics());
failed.add(s.getContainerId());
}
}
this.handleFailure(failed);
}
/**
* callback handler for resource manager
*/
private class RMCallbackHandler implements AMRMClientAsync.CallbackHandler {
@Override
public float getProgress() {
return 1.0f - (float) (pendingTasks.size()) / numTasks;
}
@Override
public void onContainersAllocated(List<Container> containers) {
ApplicationMaster.this.onContainersAllocated(containers);
}
@Override
public void onContainersCompleted(List<ContainerStatus> status) {
ApplicationMaster.this.onContainersCompleted(status);
}
@Override
public void onError(Throwable ex) {
ApplicationMaster.this.abortJob("[DMLC] Resource manager Error "
+ ex.toString());
}
@Override
public void onNodesUpdated(List<NodeReport> nodereport) {
}
@Override
public void onShutdownRequest() {
ApplicationMaster.this
.abortJob("[DMLC] Get shutdown request, start to shutdown...");
}
}
private class NMCallbackHandler implements NMClientAsync.CallbackHandler {
@Override
public void onContainerStarted(ContainerId cid,
Map<String, ByteBuffer> services) {
LOG.info("onContainerStarted Invoked");
}
@Override
public void onContainerStatusReceived(ContainerId cid,
ContainerStatus status) {
LOG.info("onContainerStatusReceived Invoked");
}
@Override
public void onContainerStopped(ContainerId cid) {
LOG.info("onContainerStopped Invoked");
}
@Override
public void onGetContainerStatusError(ContainerId cid, Throwable ex) {
LOG.info("onGetContainerStatusError Invoked: " + ex.toString());
ApplicationMaster.this
.handleFailure(Collections.singletonList(cid));
}
@Override
public void onStartContainerError(ContainerId cid, Throwable ex) {
LOG.info("onStartContainerError Invoked: " + ex.getMessage());
ApplicationMaster.this
.onStartContainerError(cid);
}
@Override
public void onStopContainerError(ContainerId cid, Throwable ex) {
LOG.info("onStopContainerError Invoked: " + ex.toString());
}
}
}
| 27,065
| 38.226087
| 136
|
java
|
GBST
|
GBST-master/gbst_src/dmlc-core/tracker/yarn/src/main/java/org/apache/hadoop/yarn/dmlc/Client.java
|
package org.apache.hadoop.yarn.dmlc;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.yarn.api.ApplicationConstants;
import org.apache.hadoop.yarn.api.ApplicationConstants.Environment;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.ApplicationSubmissionContext;
import org.apache.hadoop.yarn.api.records.ContainerLaunchContext;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.LocalResource;
import org.apache.hadoop.yarn.api.records.LocalResourceType;
import org.apache.hadoop.yarn.api.records.LocalResourceVisibility;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.api.records.QueueInfo;
import org.apache.hadoop.yarn.api.records.YarnApplicationState;
import org.apache.hadoop.yarn.client.api.YarnClient;
import org.apache.hadoop.yarn.client.api.YarnClientApplication;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.util.ConverterUtils;
import org.apache.hadoop.yarn.util.Records;
import sun.misc.Signal;
import sun.misc.SignalHandler;
public class Client {
// logger
private static final Log LOG = LogFactory.getLog(Client.class);
// permission for temp file
private static final FsPermission permTemp = new FsPermission("777");
// configuration
private YarnConfiguration conf = new YarnConfiguration();
// hdfs handler
private FileSystem dfs;
// cached maps
private Map<String, String> cacheFiles = new java.util.HashMap<String, String>();
// enviroment variable to setup cachefiles
private String cacheFileArg = "";
// args to pass to application master
private String appArgs = "";
// HDFS Path to store temporal result
private String tempdir = "/tmp";
// user name
private String userName = "";
// user credentials
private Credentials credentials = null;
// job name
private String jobName = "";
// queue
private String queue = "default";
// ApplicationMaster classpath
private String appCp = null;
// ApplicationMaster env
private Map<String, String> env = new java.util.HashMap<String, String>();
/**
* constructor
* @throws IOException
*/
private Client() throws IOException {
conf.addResource(new Path(System.getenv("HADOOP_CONF_DIR") +"/core-site.xml"));
conf.addResource(new Path(System.getenv("HADOOP_CONF_DIR") +"/hdfs-site.xml"));
dfs = FileSystem.get(conf);
userName = UserGroupInformation.getCurrentUser().getShortUserName();
credentials = UserGroupInformation.getCurrentUser().getCredentials();
}
/**
* setup security token given current user
* @return the ByeBuffer containing the security tokens
* @throws IOException
*/
private ByteBuffer setupTokens() throws IOException {
DataOutputBuffer buffer = new DataOutputBuffer();
String loc = System.getenv().get("HADOOP_TOKEN_FILE_LOCATION");
if ((loc != null && loc.trim().length() > 0)
|| (!UserGroupInformation.isSecurityEnabled())) {
this.credentials.writeTokenStorageToStream(buffer);
} else {
// Note: Credentials class is marked as LimitedPrivate for HDFS and MapReduce
Credentials credentials = new Credentials();
String tokenRenewer = conf.get(YarnConfiguration.RM_PRINCIPAL);
if (tokenRenewer == null || tokenRenewer.length() == 0) {
throw new IOException(
"Can't get Master Kerberos principal for the RM to use as renewer");
}
// For now, only getting tokens for the default file-system.
final Token<?> tokens[] = dfs.addDelegationTokens(tokenRenewer, credentials);
if (tokens != null) {
for (Token<?> token : tokens) {
LOG.info("Got dt for " + dfs.getUri() + "; " + token);
}
}
credentials.writeTokenStorageToStream(buffer);
}
return ByteBuffer.wrap(buffer.getData(), 0, buffer.getLength());
}
/**
* setup all the cached files
*
* @param fmaps
* the file maps
* @return the resource map
* @throws IOException
*/
private Map<String, LocalResource> setupCacheFiles(ApplicationId appId) throws IOException {
// create temporary dmlc directory
Path tmpPath = new Path(this.tempdir);
if (!dfs.exists(tmpPath)) {
dfs.mkdirs(tmpPath, permTemp);
LOG.info("HDFS temp directory do not exist, creating.. " + tmpPath);
}
tmpPath = new Path(tmpPath + "/temp-dmlc-yarn-" + appId);
if (dfs.exists(tmpPath)) {
dfs.delete(tmpPath, true);
}
// create temporary directory
FileSystem.mkdirs(dfs, tmpPath, permTemp);
StringBuilder cstr = new StringBuilder();
Map<String, LocalResource> rmap = new java.util.HashMap<String, LocalResource>();
for (Map.Entry<String, String> e : cacheFiles.entrySet()) {
LocalResource r = Records.newRecord(LocalResource.class);
Path path = new Path(e.getValue());
// copy local data to temporary folder in HDFS
if (!e.getValue().startsWith("hdfs://")) {
Path dst = new Path("hdfs://" + tmpPath + "/"+ path.getName());
dfs.copyFromLocalFile(false, true, path, dst);
dfs.setPermission(dst, permTemp);
dfs.deleteOnExit(dst);
path = dst;
}
FileStatus status = dfs.getFileStatus(path);
r.setResource(ConverterUtils.getYarnUrlFromPath(path));
r.setSize(status.getLen());
r.setTimestamp(status.getModificationTime());
r.setType(LocalResourceType.FILE);
r.setVisibility(LocalResourceVisibility.APPLICATION);
rmap.put(e.getKey(), r);
cstr.append(" -file \"");
cstr.append(path.toString());
cstr.append('#');
cstr.append(e.getKey());
cstr.append("\"");
}
dfs.deleteOnExit(tmpPath);
this.cacheFileArg = cstr.toString();
return rmap;
}
/**
* get the environment variables for container
*
* @return the env variable for child class
*/
private Map<String, String> getEnvironment() {
// Setup environment variables
if (appCp != null) {
env.put("CLASSPATH", appCp);
} else {
StringBuilder cpath = new StringBuilder()
.append(Environment.CLASSPATH.$$())
.append(File.pathSeparatorChar)
.append("." + File.pathSeparator + "*");
for (String c : conf.getStrings(
YarnConfiguration.YARN_APPLICATION_CLASSPATH,
YarnConfiguration.DEFAULT_YARN_APPLICATION_CLASSPATH)) {
cpath.append(File.pathSeparatorChar)
.append(c.trim());
}
env.put("CLASSPATH", cpath.toString());
}
for (Map.Entry<String, String> e : System.getenv().entrySet()) {
if (e.getKey().startsWith("DMLC_")) {
env.put(e.getKey(), e.getValue());
}
if (e.getKey().startsWith("AWS_")) {
env.put(e.getKey(), e.getValue());
}
if (e.getKey().startsWith("rabit_")) {
env.put(e.getKey(), e.getValue());
}
if (e.getKey() == "LIBHDFS_OPTS") {
env.put(e.getKey(), e.getValue());
}
if (e.getKey().equals("LD_LIBRARY_PATH")) {
env.put(e.getKey(), e.getValue());
}
}
LOG.debug(env);
return env;
}
/**
* initialize the settings
*
* @param args
*/
private void initArgs(String[] args) {
// directly pass all arguments except args0
StringBuilder sargs = new StringBuilder("");
for (int i = 0; i < args.length; ++i) {
if (args[i].equals("-file")) {
String[] arr = args[++i].split("#");
if (arr.length == 1) {
cacheFiles.put(new Path(arr[0]).getName(), arr[0]);
} else {
cacheFiles.put(arr[1], arr[0]);
}
} else if(args[i].equals("-jobname")) {
this.jobName = args[++i];
} else if(args[i].equals("-tempdir")) {
this.tempdir = args[++i];
} else if(args[i].equals("-queue")) {
this.queue = args[++i];
} else if(args[i].equals("-appcp")) {
this.appCp = args[++i];
} else if(args[i].equals("-env")) {
sargs.append(" ");
sargs.append(args[i]);
sargs.append(" ");
sargs.append(args[i+1]);
String[] pair = args[++i].split("=", 2);
env.put(pair[0], (pair.length == 1) ? "" : pair[1]);
} else {
sargs.append(" ");
sargs.append(args[i]);
}
}
this.appArgs = sargs.toString();
}
private void run(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("Usage: [options] [commands..]");
System.out.println("options: [-file filename] [-appcp appClasspath]");
return;
}
this.initArgs(args);
// Create yarnClient
YarnClient yarnClient = YarnClient.createYarnClient();
yarnClient.init(conf);
yarnClient.start();
// Create application via yarnClient
YarnClientApplication app = yarnClient.createApplication();
// Set up the container launch context for the application master
ContainerLaunchContext amContainer = Records
.newRecord(ContainerLaunchContext.class);
ApplicationSubmissionContext appContext = app
.getApplicationSubmissionContext();
// Submit application
ApplicationId appId = appContext.getApplicationId();
//add ctrl+c signal handler
CtrlCHandler handler = new CtrlCHandler(appId, yarnClient);
Signal intSignal = new Signal("INT");
Signal.handle(intSignal, handler);
// setup security token
amContainer.setTokens(this.setupTokens());
// setup cache-files and environment variables
amContainer.setLocalResources(this.setupCacheFiles(appId));
amContainer.setEnvironment(this.getEnvironment());
String cmd = Environment.JAVA_HOME.$$() + "/bin/java"
+ " -Xmx900m"
+ " org.apache.hadoop.yarn.dmlc.ApplicationMaster"
+ this.cacheFileArg + ' ' + this.appArgs + " 1>"
+ ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stdout"
+ " 2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/stderr";
LOG.debug(cmd);
amContainer.setCommands(Collections.singletonList(cmd));
// Set up resource type requirements for ApplicationMaster
Resource capability = Records.newRecord(Resource.class);
capability.setMemory(1024);
capability.setVirtualCores(1);
LOG.info("jobname=" + this.jobName + ",username=" + this.userName);
appContext.setApplicationName(jobName + ":DMLC-YARN");
appContext.setAMContainerSpec(amContainer);
appContext.setResource(capability);
appContext.setQueue(queue);
//appContext.setUser(userName);
LOG.info("Submitting application " + appId);
yarnClient.submitApplication(appContext);
ApplicationReport appReport = yarnClient.getApplicationReport(appId);
YarnApplicationState appState = appReport.getYarnApplicationState();
while (appState != YarnApplicationState.FINISHED
&& appState != YarnApplicationState.KILLED
&& appState != YarnApplicationState.FAILED) {
Thread.sleep(100);
appReport = yarnClient.getApplicationReport(appId);
appState = appReport.getYarnApplicationState();
}
System.out.println("Application " + appId + " finished with"
+ " state " + appState + " at " + appReport.getFinishTime());
if (!appReport.getFinalApplicationStatus().equals(
FinalApplicationStatus.SUCCEEDED)) {
System.err.println(appReport.getDiagnostics());
System.out.println("Available queues:");
for (QueueInfo q : yarnClient.getAllQueues()) {
System.out.println(q.getQueueName());
}
yarnClient.killApplication(appId);
}
}
class CtrlCHandler implements SignalHandler{
private ApplicationId appId;
private YarnClient yarnClient;
public CtrlCHandler(ApplicationId appId, YarnClient yarnClient){
this.appId = appId;
this.yarnClient = yarnClient;
}
public void handle(Signal signal){
try{
yarnClient.killApplication(appId);
}catch (Exception e){
System.out.println("yarn client exception");
}
}
}
public static void main(String[] args) throws Exception {
new Client().run(args);
}
}
| 14,107
| 39.193732
| 96
|
java
|
GBST
|
GBST-master/gbst_src/dmlc-core/tracker/yarn/src/main/java/org/apache/hadoop/yarn/dmlc/TaskRecord.java
|
package org.apache.hadoop.yarn.dmlc;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.client.api.AMRMClient.ContainerRequest;
/**
* data structure to hold the task information
*/
public class TaskRecord {
// task id of the task
public int taskId = 0;
// role of current node
public String taskRole = "worker";
// number of failed attempts to run the task
public int attemptCounter = 0;
// container request, can be null if task is already running
public ContainerRequest containerRequest = null;
// running container, can be null if the task is not launched
public Container container = null;
// whether we have requested abortion of this task
public boolean abortRequested = false;
public TaskRecord(int taskId, String role) {
this.taskId = taskId;
this.taskRole = role;
}
}
| 888
| 30.75
| 69
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-pmd/src/main/java/org/repositoryminer/pmd/cpd/RepositoryMinerCPD.java
|
package org.repositoryminer.pmd.cpd;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import org.repositoryminer.RepositoryMinerException;
import org.repositoryminer.domain.Commit;
import org.repositoryminer.plugin.SnapshotAnalysisPlugin;
import org.repositoryminer.pmd.cpd.model.Match;
import org.repositoryminer.pmd.cpd.persistence.CPDDAO;
public class RepositoryMinerCPD extends SnapshotAnalysisPlugin<CPDConfig> {
@Override
public void run(String snapshot, CPDConfig config) {
scm.checkout(snapshot);
Commit commit = scm.resolve(snapshot);
CPDDAO dao = new CPDDAO();
dao.deleteByCommit(commit.getHash());
CPDExecutor cpdExecutor = new CPDExecutor(tmpRepository);
cpdExecutor.setCharset("UTF-8");
if (config == null) {
config = new CPDConfig();
}
cpdExecutor.setLanguages(config.getLanguages());
cpdExecutor.setMinTokens(config.getTokensThreshold());
List<Match> matches;
try {
matches = cpdExecutor.execute();
} catch (IOException e) {
throw new RepositoryMinerException("Can not execute PMD/CPD.", e);
}
List<Document> documents = new ArrayList<Document>(matches.size());
for (Match match : matches) {
Document doc = new Document();
doc.append("reference", snapshot).
append("commit", commit.getHash()).
append("commit_date", commit.getCommitterDate()).
append("repository", repositoryId).
append("tokens_threshold", config.getTokensThreshold());
doc.putAll(match.toDocument());
documents.add(doc);
}
dao.insertMany(documents);
}
}
| 1,582
| 26.77193
| 75
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-pmd/src/main/java/org/repositoryminer/pmd/cpd/CPDConfig.java
|
package org.repositoryminer.pmd.cpd;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.repositoryminer.pmd.cpd.model.Language;
public class CPDConfig {
private int tokensThreshold = 100;
private Set<Language> languages = new HashSet<>(Arrays.asList(Language.JAVA));
public CPDConfig() {}
public CPDConfig(int tokensThreshold, Set<Language> languages) {
this.tokensThreshold = tokensThreshold;
this.languages = languages;
}
public int getTokensThreshold() {
return tokensThreshold;
}
public void setTokensThreshold(int tokensThreshold) {
this.tokensThreshold = tokensThreshold;
}
public Set<Language> getLanguages() {
return languages;
}
public void setLanguages(Set<Language> languages) {
this.languages = languages;
}
}
| 791
| 20.405405
| 79
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-pmd/src/main/java/org/repositoryminer/pmd/cpd/CPDExecutor.java
|
package org.repositoryminer.pmd.cpd;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.FilenameUtils;
import org.repositoryminer.pmd.cpd.model.Language;
import org.repositoryminer.pmd.cpd.model.Match;
import org.repositoryminer.pmd.cpd.model.Occurrence;
import org.repositoryminer.util.StringUtils;
import net.sourceforge.pmd.cpd.CPD;
import net.sourceforge.pmd.cpd.CPDConfiguration;
import net.sourceforge.pmd.cpd.JavaLanguage;
import net.sourceforge.pmd.cpd.Mark;
public class CPDExecutor{
private int minTokens;
private String charset;
private String repositoryFolder;
private Set<Language> languages;
public CPDExecutor(String repositoryFolder) {
this.repositoryFolder = repositoryFolder;
}
public void setMinTokens(int minTokens) {
this.minTokens = minTokens;
}
public void setCharset(String charset) {
this.charset = charset;
}
public void setLanguages(Set<Language> languages) {
this.languages = languages;
}
public List<Match> execute() throws IOException {
List<Match> matches = new ArrayList<Match>();
for (Language lang : languages) {
CPDConfiguration config = new CPDConfiguration();
config.setEncoding(charset);
config.setLanguage(languageFactory(lang));
config.setSkipLexicalErrors(true);
config.setSourceEncoding(charset);
config.setNonRecursive(false);
config.setMinimumTileSize(minTokens);
CPDConfiguration.setSystemProperties(config);
CPD cpd = new CPD(config);
cpd.addRecursively(new File(repositoryFolder));
cpd.go();
Iterator<net.sourceforge.pmd.cpd.Match> ms = cpd.getMatches();
while (ms.hasNext()) {
net.sourceforge.pmd.cpd.Match m = ms.next();
List<Occurrence> occurrences = new ArrayList<Occurrence>();
for (Mark mark : m.getMarkSet()) {
// removes the repository path from file path
String filePath = FilenameUtils.normalize(mark.getFilename());
filePath = filePath.substring(repositoryFolder.length()+1);
Occurrence occurrence = new Occurrence();
occurrence.setFilename(filePath);
occurrence.setFilehash(StringUtils.encodeToCRC32(filePath));
occurrence.setBeginLine(mark.getBeginLine());
occurrence.setLineCount(mark.getLineCount());
occurrence.setSourceCodeSlice(mark.getSourceCodeSlice());
occurrence.setDuplicationPercentage(getDuplicatedPercentage(mark.getFilename(),
occurrence.getSourceCodeSlice().length()));
occurrences.add(occurrence);
}
matches.add(new Match(m.getTokenCount(), lang, occurrences));
}
}
return matches;
}
private net.sourceforge.pmd.cpd.Language languageFactory(Language lang) {
switch (lang) {
case JAVA:
return new JavaLanguage();
default:
return new JavaLanguage();
}
}
private double getDuplicatedPercentage(String filename, int duplicatedSliceLength) {
try {
String source = new String(Files.readAllBytes(Paths.get(filename)));
double value = (duplicatedSliceLength * 1.0) / source.length();
return new BigDecimal(value * 100).setScale(2, BigDecimal.ROUND_CEILING).doubleValue();
} catch (IOException e) {
return 0.0f;
}
}
}
| 3,320
| 28.651786
| 90
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-pmd/src/main/java/org/repositoryminer/pmd/cpd/persistence/CPDDAO.java
|
package org.repositoryminer.pmd.cpd.persistence;
import java.util.List;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.repositoryminer.persistence.GenericDAO;
import com.mongodb.client.model.Filters;
public class CPDDAO extends GenericDAO {
private static final String COLLECTION_NAME = "pmd_cpd_analysis";
public CPDDAO() {
super(COLLECTION_NAME);
}
public void deleteByCommit(String hash) {
deleteMany(Filters.eq("commit", hash));
}
public List<Document> findByCommit(String hash, Bson projection) {
return findMany(Filters.eq("commit", hash), projection);
}
}
| 611
| 21.666667
| 67
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-pmd/src/main/java/org/repositoryminer/pmd/cpd/model/Language.java
|
package org.repositoryminer.pmd.cpd.model;
public enum Language {
JAVA;
}
| 78
| 10.285714
| 42
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-pmd/src/main/java/org/repositoryminer/pmd/cpd/model/Match.java
|
package org.repositoryminer.pmd.cpd.model;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
public class Match {
private int tokenCount;
private Language language;
private List<Occurrence> occurrence;
public Match(int tokenCount, Language language, List<Occurrence> occurrence) {
this.tokenCount = tokenCount;
this.language = language;
this.occurrence = occurrence;
}
public Document toDocument() {
Document doc = new Document();
doc.append("token_count", tokenCount).
append("language", language.name()).
append("occurrences",Occurrence.toDocumentList(occurrence));
return doc;
}
public static List<Document> toDocumentList(List<Match> occurrences) {
if (occurrences == null) {
return new ArrayList<Document>();
}
List<Document> docs = new ArrayList<Document>();
for (Match o : occurrences) {
docs.add(o.toDocument());
}
return docs;
}
public int getTokenCount() {
return tokenCount;
}
public void setTokenCount(int tokenCount) {
this.tokenCount = tokenCount;
}
public Language getLanguage() {
return language;
}
public void setLanguage(Language language) {
this.language = language;
}
public List<Occurrence> getOccurrence() {
return occurrence;
}
public void setOccurrence(List<Occurrence> occurrence) {
this.occurrence = occurrence;
}
}
| 1,354
| 19.530303
| 79
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-pmd/src/main/java/org/repositoryminer/pmd/cpd/model/Occurrence.java
|
package org.repositoryminer.pmd.cpd.model;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
public class Occurrence {
private String filename;
private long filehash;
private int beginLine;
private int lineCount;
private double duplicationPercentage;
private String sourceCodeSlice;
public Document toDocument() {
Document doc = new Document();
doc.append("filename", filename).
append("filehash", filehash).
append("begin_line", beginLine).
append("line_count", lineCount).
append("duplication_percentage", duplicationPercentage).
append("source_code_slice", sourceCodeSlice);
return doc;
}
public static List<Document> toDocumentList(List<Occurrence> filesInfo) {
if (filesInfo == null) {
return new ArrayList<Document>();
}
List<Document> docs = new ArrayList<Document>();
for (Occurrence fi : filesInfo) {
docs.add(fi.toDocument());
}
return docs;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public long getFilehash() {
return filehash;
}
public void setFilehash(long filehash) {
this.filehash = filehash;
}
public int getBeginLine() {
return beginLine;
}
public void setBeginLine(int beginLine) {
this.beginLine = beginLine;
}
public int getLineCount() {
return lineCount;
}
public void setLineCount(int lineCount) {
this.lineCount = lineCount;
}
public double getDuplicationPercentage() {
return duplicationPercentage;
}
public void setDuplicationPercentage(double duplicationPercentage) {
this.duplicationPercentage = duplicationPercentage;
}
public String getSourceCodeSlice() {
return sourceCodeSlice;
}
public void setSourceCodeSlice(String sourceCodeSlice) {
this.sourceCodeSlice = sourceCodeSlice;
}
}
| 1,840
| 19.455556
| 74
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/RepositoryExtractor.java
|
package org.repositoryminer;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.repositoryminer.domain.Commit;
import org.repositoryminer.domain.Developer;
import org.repositoryminer.domain.Reference;
import org.repositoryminer.domain.Repository;
import org.repositoryminer.persistence.CommitDAO;
import org.repositoryminer.persistence.ReferenceDAO;
import org.repositoryminer.persistence.RepositoryDAO;
import org.repositoryminer.scm.ISCM;
import org.repositoryminer.scm.SCMFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is responsible for extract informations from a SCM.
*/
public class RepositoryExtractor {
private static final Logger LOG = LoggerFactory.getLogger(RepositoryExtractor.class);
private static final int MAX_COMMITS = 1000;
private static ISCM scm;
/**
* Starts the repository data extraction process.
*
* @param rm
* instance of {@link org.repositoryminer.RepositoryMiner} .
* It must <b>NEVER<b> be null, since it will provide important
* parameters for the source-code analysis and persistence
* @throws IOException
*/
public static void run(RepositoryMiner rm) throws IOException {
LOG.info("Starting extraction process.");
File repositoryFolder = new File(rm.getPath());
scm = SCMFactory.getSCM(rm.getSCM());
scm.open(rm.getPath());
Repository repository = new Repository(null, rm.getKey(), rm.getName(),
rm.getPath(), rm.getSCM(), rm.getDescription(),
new ArrayList<Developer>());
repository.setPath(repositoryFolder.getAbsolutePath().replace("\\", "/"));
RepositoryDAO repoHandler = new RepositoryDAO();
Document repoDoc = repository.toDocument();
repoHandler.insert(repoDoc);
repository.setId(repoDoc.getObjectId("_id"));
extractReferences(repository.getId());
repoHandler.updateOnlyContributors(repository.getId(),
Developer.toDocumentList(extractCommits(repository.getId())));
scm.close();
LOG.info("Extraction finished.");
}
private static void extractReferences(ObjectId repository) {
LOG.info("Start references extraction process.");
ReferenceDAO refDocumentHandler = new ReferenceDAO();
List<Reference> references = scm.getReferences();
for (Reference ref : references) {
List<String> commits = scm.getCommitsNames(ref);
ref.setRepository(repository);
ref.setCommits(commits);
Document refDoc = ref.toDocument();
refDocumentHandler.insert(refDoc);
}
LOG.info("References extraction process Finished.");
}
private static Set<Developer> extractCommits(ObjectId repository) {
LOG.info("Start commits extraction process.");
CommitDAO documentHandler = new CommitDAO();
Set<Developer> contributors = new HashSet<Developer>();
int skip = 0;
List<Commit> commits = scm.getCommits(skip, MAX_COMMITS);
while (commits.size() > 0) {
for (Commit commit : commits) {
commit.setRepository(repository);
contributors.add(commit.getCommitter());
documentHandler.insert(commit.toDocument());
}
skip += MAX_COMMITS;
commits = scm.getCommits(skip, MAX_COMMITS);
}
LOG.info("Commits extraction process finished.");
return contributors;
}
}
| 3,363
| 29.306306
| 86
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/RepositoryMinerException.java
|
package org.repositoryminer;
/**
* Catch-all type for internal exceptions thrown by RepositoryMiner.
*/
public class RepositoryMinerException extends RuntimeException{
private static final long serialVersionUID = 1L;
public RepositoryMinerException(String message){
super(message);
}
public RepositoryMinerException(Throwable cause){
super(cause);
}
public RepositoryMinerException(String message, Throwable cause){
super(message, cause);
}
}
| 467
| 19.347826
| 69
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/IncrementalRepositoryExtractor.java
|
package org.repositoryminer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bson.Document;
import org.repositoryminer.domain.Commit;
import org.repositoryminer.domain.Developer;
import org.repositoryminer.domain.Reference;
import org.repositoryminer.domain.Repository;
import org.repositoryminer.persistence.CommitDAO;
import org.repositoryminer.persistence.ReferenceDAO;
import org.repositoryminer.persistence.RepositoryDAO;
import org.repositoryminer.scm.ISCM;
import org.repositoryminer.scm.SCMFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.client.model.Projections;
public class IncrementalRepositoryExtractor {
private static final Logger LOG = LoggerFactory.getLogger(IncrementalRepositoryExtractor.class);
private static Repository repository;
private static Set<Developer> contributos;
private static ISCM scm;
public static void run(String key) {
LOG.info("Starting extraction process.");
RepositoryDAO repoDAO = new RepositoryDAO();
repository = Repository.parseDocument(repoDAO.findByKey(key, null));
if (repository == null) {
throw new RepositoryMinerException("Repository with the key " + key + " was not found.");
}
scm = SCMFactory.getSCM(repository.getScm());
scm.open(repository.getPath());
contributos = new HashSet<Developer>(repository.getContributors());
updateReferences();
updateCommits();
repoDAO.updateOnlyContributors(repository.getId(), Developer.toDocumentList(contributos));
scm.close();
LOG.info("Extraction finished.");
}
private static void updateReferences() {
LOG.info("Start references extraction process.");
List<Reference> references = scm.getReferences();
ReferenceDAO refDao = new ReferenceDAO();
List<Reference> dbReferences = Reference
.parseDocuments(refDao.findByRepository(repository.getId(), Projections.exclude("commits")));
Map<String, Reference> dbRefsMap = new HashMap<>();
for (Reference ref : dbReferences) {
dbRefsMap.put(ref.getPath(), ref);
}
for (Reference ref : references) {
Reference tempRef = dbRefsMap.get(ref.getPath());
if (tempRef == null) {
ref.setCommits(scm.getCommitsNames(ref));
refDao.insert(ref.toDocument());
ref.setCommits(null);
} else {
refDao.updateCommitsAndLastCommitDate(tempRef.getId(), scm.getCommitsNames(ref),
ref.getLastCommitDate());
dbRefsMap.remove(ref.getPath());
}
}
for (Reference ref : dbRefsMap.values()) {
refDao.delete(ref.getId());
}
LOG.info("References update process finished.");
}
private static void updateCommits() {
LOG.info("Start commits extraction process.");
Set<String> commits = new HashSet<String>(scm.getCommitsNames());
List<String> commitsDb = new ArrayList<>();
CommitDAO commitDao = new CommitDAO();
for (Document doc : commitDao.findByRepository(repository.getId(), Projections.include("hash"))) {
commitsDb.add(doc.getString("hash"));
}
// removes the commits already saved and delete the commits that were modified.
for (String commitName : commitsDb) {
if (!commits.remove(commitName)) {
commitDao.delete(commitName, repository.getId());
}
}
// saves the new/modified commits
if (commits.size() > 0) {
List<Document> documents = new ArrayList<>();
for (Commit commit : scm.getCommits(commits)) {
documents.add(commit.toDocument());
contributos.add(commit.getAuthor());
contributos.add(commit.getCommitter());
}
commitDao.insertMany(documents);
}
LOG.info("Commits extraction process finished.");
}
}
| 3,676
| 29.89916
| 100
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/RepositoryMiner.java
|
package org.repositoryminer;
import java.io.IOException;
import org.repositoryminer.domain.SCMType;
import org.repositoryminer.persistence.RepositoryDAO;
/**
* The front-end class to perform the repository data extraction.
*/
public class RepositoryMiner {
private String key;
private String path;
private String name;
private String description;
private SCMType scm;
/**
* Starts the SCM data extraction process. If a repository was analyzed before,
* its informations will be updated.
*
* @throws IOException
*/
public void mine() throws IOException {
RepositoryDAO repoDocHandler = new RepositoryDAO();
if (!repoDocHandler.wasMined(key)) {
RepositoryExtractor.run(this);
} else {
IncrementalRepositoryExtractor.run(key);
}
}
public RepositoryMiner(String key) {
this.key = key;
}
public RepositoryMiner(String key, String path, String name,
String description, SCMType scm) {
this.key = key;
this.path = path;
this.name = name;
this.description = description;
this.scm = scm;
}
/*** Getters and Setters ***/
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public SCMType getSCM() {
return scm;
}
public void setSCM(SCMType scm) {
this.scm = scm;
}
}
| 1,639
| 17.222222
| 80
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/util/StringUtils.java
|
package org.repositoryminer.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
import org.repositoryminer.RepositoryMinerException;
/**
* Contains some utilities operations for strings.
*/
public class StringUtils {
/**
* Hashes the input using SHA1 algorithm.
*
* @param input
* the input string.
* @return the hashed input string.
*/
public static String encodeToSHA1(final String input) {
MessageDigest mDigest;
try {
mDigest = MessageDigest.getInstance("SHA1");
} catch (NoSuchAlgorithmException e) {
throw new RepositoryMinerException("SHA1 algorithm not supported.", e);
}
byte[] result = mDigest.digest(input.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < result.length; i++) {
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
/**
* Hashes the input using CRC32 algorithm.
*
* @param input
* the input string.
* @return the hashed input string.
*/
public static long encodeToCRC32(final String input) {
byte bytes[] = input.getBytes();
Checksum checksum = new CRC32();
checksum.update(bytes, 0, bytes.length);
return checksum.getValue();
}
}
| 1,321
| 23.943396
| 76
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/util/RMFileUtils.java
|
package org.repositoryminer.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.NotFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
/**
* Contains some utilities operations for files.
*/
public class RMFileUtils {
/**
* Retrieves all the sub directories from a root directory.
*
* @param path
* the root path.
* @return the sub directories.
*/
public static List<File> getAllDirs(String path) {
return (List<File>) FileUtils.listFilesAndDirs(new File(path), new NotFileFilter(TrueFileFilter.INSTANCE),
DirectoryFileFilter.DIRECTORY);
}
/**
* Retrieves all the sub directories from a root directory.
*
* @param path
* the root path.
* @return the sub directories.
*/
public static List<String> getAllDirsAsString(String path) {
List<File> dirs = (List<File>) FileUtils.listFilesAndDirs(new File(path), new NotFileFilter(TrueFileFilter.INSTANCE),
DirectoryFileFilter.DIRECTORY);
List<String> dirsNames = new ArrayList<>();
for (File f : dirs) {
dirsNames.add(f.getAbsolutePath());
}
return dirsNames;
}
/**
* Copies a folder to another location with a new name.
*
* @param srcFolder
* the source folder.
* @param destFolder
* the destiny folder.
* @param newName
* the source folder name at the new location.
*
* @return the path of the copied folder.
* @throws IOException
*/
public static String copyFolderTo(String src, String dest, String newName) throws IOException {
File srcFile = new File(src);
File destFile = new File(dest, newName);
if (destFile.exists()) {
FileUtils.forceDelete(destFile);
}
FileUtils.copyDirectory(srcFile, destFile);
return FilenameUtils.normalize(destFile.getAbsolutePath(), true);
}
/**
* Copies a folder to the temporary directory with a new name.
*
* @param src
* the source folder.
* @param newName
* the source folder name at the temporary directory.
* @return the path of the copied folder.
* @throws IOException
*/
public static String copyFolderToTmp(String src, String newName) throws IOException {
return copyFolderTo(src, System.getProperty("java.io.tmpdir"), newName);
}
/**
* Deletes some folder.
*
* @param folder
* the name of folder that will be deleted.
* @throws IOException
*/
public static void deleteFolder(String folder) throws IOException {
final File file = new File(folder);
if (file.exists()) {
FileUtils.deleteDirectory(file);
}
}
/**
* Concatenates two file paths.
*
* @param parent
* the parent file path.
* @param child
* the child file path.
* @return a new absolute file path compound by the parent and the child
* concatenated.
*/
public static String concatFilePath(String parent, String child) {
return FilenameUtils.normalize(new File(parent, child).getAbsolutePath(), true);
}
/**
* Concatenates a list of children file paths with a parent file path.
*
* @param parent
* the parent file path.
* @param children
* the list of children file paths.
* @return a list of absolute file path compound by the parent and the children
* concatenated.
*/
public static List<String> concatFilePath(String parent, Collection<String> children) {
List<String> newPaths = new ArrayList<String>();
for (String child : children) {
newPaths.add(concatFilePath(parent, child));
}
return newPaths;
}
/**
* Concatenates a list of children file paths with a parent file path.
*
* @param parent
* the parent file path.
* @param children
* the list of children file paths.
* @return a list of absolute file path compound by the parent and the children
* concatenated.
*/
public static String[] concatFilePath(String parent, String[] children) {
String[] newPaths = new String[children.length];
for (int i = 0; i < children.length; i++) {
newPaths[i] = concatFilePath(parent, children[i]);
}
return newPaths;
}
}
| 4,378
| 27.620915
| 119
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/plugin/MiningPlugin.java
|
package org.repositoryminer.plugin;
import org.bson.Document;
import org.repositoryminer.RepositoryMiner;
import org.repositoryminer.RepositoryMinerException;
import org.repositoryminer.domain.Repository;
import org.repositoryminer.persistence.RepositoryDAO;
/**
* This extension point is interesting for plugins that wish to perform some
* mining process in the database or add information from other sources to the
* database without having to access the repository.
*
* @param <T>
* some configuration.
*/
public abstract class MiningPlugin<T> {
protected Repository repository;
public MiningPlugin(String repositoryKey) {
Document repoDoc = new RepositoryDAO().findByKey(repositoryKey, null);
if (repoDoc == null) {
throw new RepositoryMinerException("Repository not found.");
}
repository = Repository.parseDocument(repoDoc);
}
/**
* This analysis must to execute after mining the repository with
* {@link RepositoryMiner}.
*
* @param config
*/
public abstract void mine(T config);
}
| 1,043
| 25.1
| 78
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/plugin/SnapshotAnalysisPlugin.java
|
package org.repositoryminer.plugin;
import java.io.IOException;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.repositoryminer.RepositoryMinerException;
import org.repositoryminer.domain.SCMType;
import org.repositoryminer.persistence.RepositoryDAO;
import org.repositoryminer.scm.ISCM;
import org.repositoryminer.scm.SCMFactory;
import org.repositoryminer.util.RMFileUtils;
import org.repositoryminer.util.StringUtils;
import com.mongodb.client.model.Projections;
/**
* This extension point is interesting for plugins that want to access the
* repository and perform some sort of analysis in one or more of its versions,
* such as static code analysis.
*
* @param <T>
* some configuration.
*/
public abstract class SnapshotAnalysisPlugin<T> {
protected String tmpRepository;
protected ObjectId repositoryId;
protected ISCM scm;
/**
* This method is responsible for preparing the repository to run the plugin,
* and should be called only once.
*
* @param repositoryKey
* the repository key
* @throws IOException
*/
public void init(String repositoryKey) throws IOException {
Document repoDoc = new RepositoryDAO().findByKey(repositoryKey, Projections.include("_id", "path", "scm"));
if (repoDoc == null) {
throw new RepositoryMinerException("Repository with the key " + repositoryKey + " does not exists");
}
scm = SCMFactory.getSCM(SCMType.valueOf(repoDoc.getString("scm")));
repositoryId = repoDoc.getObjectId("_id");
tmpRepository = RMFileUtils.copyFolderToTmp(repoDoc.getString("path"),
StringUtils.encodeToSHA1(repositoryId.toHexString()));
scm.open(tmpRepository);
}
/**
* This method is the plugin entry point, by calling it, the plugin will execute
* its analysis in a given repository version.
*
* @param snapshot
* the commit reference
* @param config
* some configuration
*/
public abstract void run(String snapshot, T config);
/**
* This method is responsible for releasing the resources allocated to the
* plugin execution, and should be called only once.
*
* @throws IOException
*/
public void finish() throws IOException {
scm.close();
RMFileUtils.deleteFolder(tmpRepository);
}
}
| 2,259
| 28.736842
| 109
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/domain/ReferenceType.java
|
package org.repositoryminer.domain;
/**
* Represents the types of references to a commit.
*/
public enum ReferenceType {
TAG, BRANCH;
}
| 142
| 13.3
| 50
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/domain/SCMType.java
|
package org.repositoryminer.domain;
/**
* Represents the types of SCM.
*/
public enum SCMType {
GIT;
public static SCMType parse(String name) {
if (name == null || name.length() == 0) {
return null;
}
for (SCMType scm : values()) {
if (scm.name().equals(name)) {
return scm;
}
}
return null;
}
}
| 335
| 13
| 43
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/domain/Reference.java
|
package org.repositoryminer.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.bson.Document;
import org.bson.types.ObjectId;
/**
* Represents a reference to a commit (e.g. branches and tags).
*/
public class Reference {
private ObjectId id;
private ObjectId repository;
private String name;
private String path;
private ReferenceType type;
private Date lastCommitDate;
private List<String> commits;
/**
* Converts a list of documents to references.
*
* @param documents
*
* @return a list of references.
*/
public static List<Reference> parseDocuments(List<Document> documents) {
List<Reference> refs = new ArrayList<Reference>();
for (Document doc : documents) {
refs.add(parseDocument(doc));
}
return refs;
}
/**
* Converts a document to a reference.
*
* @param document
*
* @return a reference.
*/
@SuppressWarnings("unchecked")
public static Reference parseDocument(Document document) {
Reference r = new Reference(document.getObjectId("_id"),
document.getObjectId("repository"),
document.getString("name"),
document.getString("path"),
ReferenceType.valueOf(document.getString("type")),
document.getDate("last_commit_date"),
document.get("commits", List.class));
return r;
}
/**
* Converts a reference to a document.
*
* @return a document.
*/
public Document toDocument() {
Document doc = new Document();
doc.append("repository", repository)
.append("name", name)
.append("path", path)
.append("type", type.toString())
.append("last_commit_date", lastCommitDate)
.append("commits", commits);
return doc;
}
public Reference() {}
public Reference(ObjectId id, ObjectId repository, String name, String path, ReferenceType type,
Date lastCommitDate, List<String> commits) {
this.id = id;
this.repository = repository;
this.name = name;
this.path = path;
this.type = type;
this.lastCommitDate = lastCommitDate;
this.commits = commits;
}
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public ObjectId getRepository() {
return repository;
}
public void setRepository(ObjectId repository) {
this.repository = repository;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public ReferenceType getType() {
return type;
}
public void setType(ReferenceType type) {
this.type = type;
}
public Date getLastCommitDate() {
return lastCommitDate;
}
public void setLastCommitDate(Date lastCommitDate) {
this.lastCommitDate = lastCommitDate;
}
public List<String> getCommits() {
return commits;
}
public void setCommits(List<String> commits) {
this.commits = commits;
}
}
| 2,904
| 19.173611
| 97
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/domain/Change.java
|
package org.repositoryminer.domain;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
/**
* Represents a change made in a commit.
*/
public class Change {
private String newPath;
private String oldPath;
private int linesAdded;
private int linesRemoved;
private ChangeType type;
/**
* Converts documents to changes.
*
* @param documents
*
* @return a list of changes.
*/
public static List<Change> parseDocuments(List<Document> documents) {
List<Change> changes = new ArrayList<Change>();
if (documents == null)
return changes;
for (Document doc : documents) {
Change change = new Change(doc.getString("new_path"), doc.getString("old_path"),
doc.getInteger("lines_added", 0), doc.getInteger("lines_removed", 0),
ChangeType.valueOf(doc.getString("type")));
changes.add(change);
}
return changes;
}
/**
* Converts changes to documents.
*
* @param changes
*
* @return a list of documents.
*/
public static List<Document> toDocumentList(List<Change> changes) {
List<Document> list = new ArrayList<Document>();
for (Change c : changes) {
Document doc = new Document();
doc.append("new_path", c.getNewPath()).append("old_path", c.getOldPath())
.append("lines_added", c.getLinesAdded()).append("lines_removed", c.getLinesRemoved())
.append("type", c.getType().toString());
list.add(doc);
}
return list;
}
public Change() {
}
public Change(String newPath, String oldPath, int linesAdded, int linesRemoved, ChangeType type) {
super();
this.newPath = newPath;
this.oldPath = oldPath;
this.linesAdded = linesAdded;
this.linesRemoved = linesRemoved;
this.type = type;
}
public String getNewPath() {
return newPath;
}
public void setNewPath(String newPath) {
this.newPath = newPath;
}
public String getOldPath() {
return oldPath;
}
public void setOldPath(String oldPath) {
this.oldPath = oldPath;
}
public int getLinesAdded() {
return linesAdded;
}
public void setLinesAdded(int linesAdded) {
this.linesAdded = linesAdded;
}
public int getLinesRemoved() {
return linesRemoved;
}
public void setLinesRemoved(int linesRemoved) {
this.linesRemoved = linesRemoved;
}
public ChangeType getType() {
return type;
}
public void setType(ChangeType type) {
this.type = type;
}
}
| 2,354
| 20.216216
| 99
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/domain/Commit.java
|
package org.repositoryminer.domain;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.bson.Document;
import org.bson.types.ObjectId;
/**
* Represents a commit.
*/
public class Commit {
private ObjectId id;
private String hash;
private Developer author;
private Developer committer;
private String message;
private List<Change> changes;
private List<String> parents;
private Date authorDate;
private Date committerDate;
private boolean merge;
private ObjectId repository;
/**
* Converts database documents to commits.
*
* @param documents
*
* @return a list of commits.
*/
public static List<Commit> parseDocuments(List<Document> documents) {
List<Commit> commits = new ArrayList<Commit>();
for (Document doc : documents) {
commits.add(parseDocument(doc));
}
return commits;
}
/**
* Converts a document to a commit.
*
* @param document
*
* @return a commit.
*/
@SuppressWarnings("unchecked")
public static Commit parseDocument(Document document) {
Commit commit = new Commit(document.getObjectId("_id"), document.getString("hash"),
Developer.parseDocument(document.get("author", Document.class)),
Developer.parseDocument(document.get("committer", Document.class)), document.getString("message"),
Change.parseDocuments(document.get("changes", List.class)), document.get("parents", List.class),
document.getDate("author_date"), document.getDate("committer_date"),
document.getBoolean("merge", false), document.getObjectId("repository"));
return commit;
}
/**
* Converts the commit to a document.
*
* @return a document.
*/
public Document toDocument() {
Document doc = new Document();
doc.append("hash", hash).append("author", author.toDocument()).append("committer", committer.toDocument())
.append("message", message).append("changes", Change.toDocumentList(changes)).append("parents", parents)
.append("author_date", authorDate.getTime()).append("committer_date", committerDate.getTime())
.append("merge", merge).append("repository", repository);
return doc;
}
public Commit() {
}
public Commit(String hash, Date committerDate) {
this.hash = hash;
this.committerDate = committerDate;
}
public Commit(ObjectId id, String hash, Developer author, Developer committer, String message, List<Change> changes,
List<String> parents, Date authorDate, Date committerDate, boolean merge, ObjectId repository) {
super();
this.id = id;
this.hash = hash;
this.author = author;
this.committer = committer;
this.message = message;
this.changes = changes;
this.parents = parents;
this.authorDate = authorDate;
this.committerDate = committerDate;
this.merge = merge;
this.repository = repository;
}
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public Developer getAuthor() {
return author;
}
public void setAuthor(Developer author) {
this.author = author;
}
public Developer getCommitter() {
return committer;
}
public void setCommitter(Developer committer) {
this.committer = committer;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Change> getChanges() {
return changes;
}
public void setChanges(List<Change> changes) {
this.changes = changes;
}
public List<String> getParents() {
return parents;
}
public void setParents(List<String> parents) {
this.parents = parents;
}
public Date getAuthorDate() {
return authorDate;
}
public void setAuthorDate(Date authorDate) {
this.authorDate = authorDate;
}
public Date getCommitterDate() {
return committerDate;
}
public void setCommitterDate(Date committerDate) {
this.committerDate = committerDate;
}
public boolean isMerge() {
return merge;
}
public void setMerge(boolean merge) {
this.merge = merge;
}
public ObjectId getRepository() {
return repository;
}
public void setRepository(ObjectId repository) {
this.repository = repository;
}
}
| 4,197
| 21.449198
| 117
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/domain/ChangeType.java
|
package org.repositoryminer.domain;
/**
* Represents the types of changes made in a file during a commit.
*/
public enum ChangeType {
ADD, COPY, MODIFY, RENAME, DELETE;
}
| 176
| 16.7
| 66
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/domain/Repository.java
|
package org.repositoryminer.domain;
import java.util.List;
import org.bson.Document;
import org.bson.types.ObjectId;
/**
* Represents a SCM repository.
*/
public class Repository {
private ObjectId id;
private String key;
private String name;
private String path;
private SCMType scm;
private String description;
private List<Developer> contributors;
/**
* Converts a repository to a document.
*
* @return the document.
*/
public Document toDocument() {
Document doc = new Document();
doc.append("key", key).append("name", name).append("path", path).append("scm", scm.toString())
.append("description", description).append("contributors", Developer.toDocumentList(contributors));
return doc;
}
/**
* Converts a document to a repository.
*
* @param doc
*
* @return a repository.
*/
@SuppressWarnings("unchecked")
public static Repository parseDocument(Document doc) {
if (doc == null) {
return null;
}
return new Repository(doc.getObjectId("_id"), doc.getString("key"), doc.getString("name"),
doc.getString("path"), SCMType.parse(doc.getString("scm")), doc.getString("description"),
Developer.parseDocuments(doc.get("contributors", List.class)));
}
public Repository() {}
public Repository(ObjectId id, String key, String name, String path, SCMType scm, String description,
List<Developer> contributors) {
this.id = id;
this.key = key;
this.name = name;
this.path = path;
this.scm = scm;
this.description = description;
this.contributors = contributors;
}
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public SCMType getScm() {
return scm;
}
public void setScm(SCMType scm) {
this.scm = scm;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Developer> getContributors() {
return contributors;
}
public void setContributors(List<Developer> contributors) {
this.contributors = contributors;
}
}
| 2,382
| 18.858333
| 102
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/domain/Developer.java
|
package org.repositoryminer.domain;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.bson.Document;
/**
* Represents the developer signature.
*/
public class Developer {
private String name;
private String email;
/**
* Converts documents to developers.
*
* @param documents
*
* @return a list of developers signatures.
*/
public static List<Developer> parseDocuments(List<Document> documents) {
if (documents == null) {
return new ArrayList<Developer>();
}
List<Developer> personIdents = new ArrayList<Developer>();
for (Document doc : documents) {
Developer c = parseDocument(doc);
personIdents.add(c);
}
return personIdents;
}
/**
* Converts a document to a developer.
*
* @param document
*
* @return a document.
*/
public static Developer parseDocument(Document document) {
if (document == null) {
return null;
}
Developer c = new Developer(document.getString("name"), document.getString("email"));
return c;
}
/**
* Converts the person identity to a document.
*
* @return a document.
*/
public Document toDocument() {
Document doc = new Document();
doc.append("name", name).append("email", email);
return doc;
}
/**
* Converts a list of developers to documents.
*
* @param developers
*
* @return a list of documents.
*/
public static List<Document> toDocumentList(Collection<Developer> developers) {
if (developers == null) {
return new ArrayList<Document>();
}
List<Document> list = new ArrayList<Document>();
for (Developer c : developers) {
list.add(c.toDocument());
}
return list;
}
public Developer() {
}
public Developer(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Developer other = (Developer) obj;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
| 2,728
| 18.775362
| 87
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/persistence/ReferenceDAO.java
|
package org.repositoryminer.persistence;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.repositoryminer.domain.ReferenceType;
import com.mongodb.client.model.Filters;
/**
* This class handles rm_reference collection.
*/
public class ReferenceDAO extends GenericDAO {
private static final String COLLECTION_NAME = "rm_reference";
public ReferenceDAO() {
super(COLLECTION_NAME);
}
/**
* Retrieves a reference by path.
*
* @param path
* the reference path.
* @param repositoryId
* the repository id.
* @param projection
* the query projection.
* @return a reference.
*/
public Document findByPath(String path, String repositoryId, Bson projection) {
return findOne(Filters.and(Filters.eq("path", path), Filters.eq("repository", new ObjectId(repositoryId))),
projection);
}
/**
* Retrieves all reference from a repository.
*
* @param repositoryId
* the repository id.
* @param projection
* the query projection.
* @return list of references.
*/
public List<Document> findByRepository(ObjectId repositoryId, Bson projection) {
return findMany(Filters.eq("repository", repositoryId), projection);
}
/**
* Finds a reference that contains certain commit.
*
* @param repositoryId
* the repository id.
* @param commitId
* the commit id.
* @param projection
* the query projection.
* @return a reference.
*/
public Document findByCommit(String repositoryId, String commitId, Bson projection) {
return findOne(Filters.and(Filters.eq("repository", new ObjectId(repositoryId)),
Filters.in("commits", Arrays.asList(commitId))), projection);
}
/**
* Updates the commits in a reference.
*
* @param id
* reference id.
* @param commits
* the new commits.
*/
public void updateOnlyCommits(String id, List<String> commits) {
collection.updateOne(Filters.eq("_id", new ObjectId(id)),
new Document("$set", new Document("commits", commits)));
}
/**
* Updates a reference.
*
* @param id
* reference id.
* @param doc
* the reference document.
*/
public void update(ObjectId id, Document doc) {
collection.updateOne(Filters.eq("_id", id), doc);
}
/**
* Updates the commits and last commit date in a reference.
*
* @param id
* reference id.
* @param commits
* the new commits.
* @param lastCommitDate
* the new last commit date.
*/
public void updateCommitsAndLastCommitDate(ObjectId id, List<String> commits, Date lastCommitDate) {
collection.updateOne(Filters.eq("_id", id),
new Document("$set", new Document("commits", commits).append("last_commit_date", lastCommitDate)));
}
/**
* Deletes a reference by its id.
*
* @param id
* reference id.
*/
public void delete(ObjectId id) {
collection.deleteOne(Filters.eq("_id", id));
}
/**
* Finds a reference by name and type.
*
* @param repositoryId
* the repository id
* @param name
* the reference name
* @param type
* the reference type
* @param projection
* the query projection
* @return a reference.
*/
public Document findByNameAndType(String name, ReferenceType type, String repositoryId, Bson projection) {
return findOne(Filters.and(Filters.eq("repository", new ObjectId(repositoryId)), Filters.eq("name", name),
Filters.eq("type", type.toString())), projection);
}
}
| 3,668
| 25.586957
| 109
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/persistence/GenericDAO.java
|
package org.repositoryminer.persistence;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
/**
* This class handles a generic collection.
*/
public class GenericDAO {
protected MongoCollection<Document> collection;
/**
* @param collectionName
* the target collection name.
*/
public GenericDAO(String collectionName) {
collection = MongoConnection.getInstance().getCollection(collectionName);
}
/**
* Count the number of documents.
*
* @param where
* clause to filter results or null for no filter.
* @return the number of documents.
*/
public long count(Bson where) {
return collection.count(where);
}
/**
* Inserts one document.
*
* @param document
* the document to be stored.
*/
public void insert(Document document) {
collection.insertOne(document);
}
/**
* Inserts various documents.
*
* @param documents
* list of documents to be stored.
*/
public void insertMany(List<Document> documents) {
collection.insertMany(documents);
}
/**
* Updates one document.
*
* @param where
* clause to filter results or null for no filter.
* @param newDocument
* the modifications.
* @return the result of update operation.
*/
public UpdateResult updateOne(Bson where, Bson newDocument) {
return collection.updateOne(where, newDocument);
}
/**
* Updates various documents.
*
* @param where
* clause to filter results or null for no filter.
* @param newDocument
* the modifications.
* @return the result of update operation.
*/
public UpdateResult updateMany(Bson where, Bson newDocument) {
return collection.updateMany(where, newDocument);
}
/**
* Deletes one document.
*
* @param where
* clause to filter results or null for no filter.
* @return the result of delete operation.
*/
public DeleteResult deleteOne(Bson where) {
return collection.deleteOne(where);
}
/**
* Deletes various documents.
*
* @param where
* clause to filter results or null for no filter.
* @return the result of delete operation.
*/
public DeleteResult deleteMany(Bson whereClause) {
return collection.deleteMany(whereClause);
}
/**
* Retrieves one document by its id.
*
* @param id
* the document id.
* @param projection
* the query projection.
* @return the found document or null.
*/
public Document findById(String id, Bson projection) {
return findOne(Filters.eq("_id", new ObjectId(id)), projection);
}
/**
* Retrieves one document by its id.
*
* @param id
* the document id.
* @param projection
* the query projection.
* @return the found document or null.
*/
public Document findById(ObjectId id, Bson projection) {
return findOne(Filters.eq("_id", id), projection);
}
/**
* Retrieves only the first document from a query.
*
* @param where
* clause to filter results or null for no filter.
* @param projection
* the query projection.
* @return the found document or null.
*/
public Document findOne(Bson where, Bson projection) {
return collection.find(where).projection(projection).first();
}
/**
* Retrieves various documents.
*
* @param where
* clause to filter results or null for no filter.
* @param projection
* the query projection.
* @return a list of documents.
*/
public List<Document> findMany(Bson where, Bson projection) {
return fromCursorToList(collection.find(where).projection(projection).iterator());
}
/**
* Converts a query cursor to a list.
*
* @param cursor
* the query cursor.
* @return a list of documents.
*/
public List<Document> fromCursorToList(MongoCursor<Document> cursor) {
List<Document> list = new ArrayList<Document>();
while (cursor.hasNext()) {
list.add(cursor.next());
}
cursor.close();
return list;
}
}
| 4,316
| 22.983333
| 84
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/persistence/RepositoryDAO.java
|
package org.repositoryminer.persistence;
import java.util.List;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import com.mongodb.client.model.Filters;
/**
* This class handles rm_repository collection.
*/
public class RepositoryDAO extends GenericDAO {
private static final String COLLECTION_NAME = "rm_repository";
public RepositoryDAO() {
super(COLLECTION_NAME);
}
/**
* Finds a repository by its key.
*
* @param key
* the repository key.
* @param projection
* the query projection.
* @return the found repository.
*/
public Document findByKey(String key, Bson projection) {
return findOne(Filters.eq("key", key), projection);
}
/**
* Checks if a repository was already mined.
*
* @param id
* the repository id.
* @return true if the repository was mined or false otherwise.
*/
public boolean wasMined(String key) {
return super.count(Filters.eq("key", key)) > 0;
}
/**
* Update contributors in the repository.
*
* @param repository
* the repository id.
* @param contributors
* the contributors.
*/
public void updateOnlyContributors(ObjectId repository, List<Document> contributors) {
collection.updateOne(Filters.eq("_id", repository),
new Document("$set", new Document("contributors", contributors)));
}
}
| 1,392
| 22.610169
| 87
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/persistence/CommitDAO.java
|
package org.repositoryminer.persistence;
import java.util.List;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
/**
* This class handles rm_commit collection.
*/
public class CommitDAO extends GenericDAO {
private static final String COLLECTION_NAME = "rm_commit";
public CommitDAO() {
super(COLLECTION_NAME);
}
/**
* Finds a commit by its hash.
*
* @param hash
* the commit hash.
* @param projection
* the query projection.
* @return a commit.
*/
public Document findByHash(String hash, Bson projection) {
BasicDBObject whereClause = new BasicDBObject("hash", hash);
return findOne(whereClause, projection);
}
/**
* Deletes a commit by its hash.
*
* @param hash
* the commit hash.
* @param repositoryId
* the repository id.
*/
public void delete(String hash, ObjectId repositoryId) {
deleteOne(new BasicDBObject("repository", repositoryId).append("hash", hash));
}
/**
* Retrieves commits from a repository.
*
* @param repositoryId
* the repository id.
* @param projection
* the query projection.
* @return a list of commits.
*/
public List<Document> findByRepository(ObjectId repositoryId, Bson projection) {
return findMany(new BasicDBObject("repository", repositoryId), projection);
}
/**
* Retrieves commits from a id list. The commits are ordered by commit date.
*
* @param repositoryId
* the repository id.
* @param idList
* the id list.
* @param projection
* the query projection.
* @return a list of commits.
*/
public List<Document> findByIdList(List<String> idList, Bson projection) {
MongoCursor<Document> cursor = collection.find(Filters.in("_id", idList))
.sort(new BasicDBObject("commit_date", 1)).projection(projection).iterator();
return fromCursorToList(cursor);
}
}
| 2,058
| 24.7375
| 81
|
java
|
repositoryminer
|
repositoryminer-master/repositoryminer-core/src/main/java/org/repositoryminer/persistence/MongoConnection.java
|
package org.repositoryminer.persistence;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
/**
* This class handles MongoDB database connection.
*/
public class MongoConnection {
private static class LazyHelper {
private static final MongoConnection INSTANCE = new MongoConnection();
}
private static MongoClient client;
private String database;
private MongoConnection() {
}
/**
* @return a shared instance of connection handler.
*/
public static MongoConnection getInstance() {
return LazyHelper.INSTANCE;
}
/**
* Opens database connection.
*
* @param uri
* the database URI.
* @param database
* the database name.
*/
public void connect(String uri, String database) {
MongoConnection.client = new MongoClient(new MongoClientURI(uri));
this.database = database;
}
/**
* Returns a database collection handler.
*
* @param collection
* the collection name.
* @return the collection handler.
*/
public MongoCollection<Document> getCollection(String collection) {
return MongoConnection.client.getDatabase(database).getCollection(collection);
}
/**
* Closes database connection.
*/
public void close() {
MongoConnection.client.close();
}
}
| 1,334
| 20.532258
| 80
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.