1 package org.robolectric.shadows; 2 3 /** 4 * Transliteration of native BitSet64. 5 * 6 * <p>Unlike the native code stores value inline as opposed to a manipulating data via series of 7 * static methods passed values by reference. 8 * 9 * @see system/core/libutils/include/utils/BitSet.h 10 */ 11 public class NativeBitSet64 { 12 13 private long value; 14 NativeBitSet64(long value)15 NativeBitSet64(long value) { 16 this.value = value; 17 } 18 NativeBitSet64(NativeBitSet64 other)19 NativeBitSet64(NativeBitSet64 other) { 20 this.value = other.value; 21 } 22 NativeBitSet64()23 NativeBitSet64() { 24 this(0); 25 } 26 27 /** Gets the value associated with a particular bit index. */ valueForBit(int n)28 static long valueForBit(int n) { 29 return 0x8000000000000000L >>> n; 30 } 31 32 /** Clears the bit set. */ clear()33 void clear() { 34 value = 0; 35 } 36 37 /** Returns the number of marked bits in the set. */ count()38 int count() { 39 int count = 0; 40 for (int n = 0; n < 64; n++) { 41 if (hasBit(n)) { 42 count++; 43 } 44 } 45 return count; 46 } 47 48 /** Returns true if the bit set does not contain any marked bits. */ isEmpty()49 boolean isEmpty() { 50 return value == 0; 51 } 52 53 /** Returns true if the specified bit is marked. */ hasBit(int n)54 boolean hasBit(int n) { 55 return (value & valueForBit(n)) != 0; 56 } 57 58 /** Marks the specified bit. */ markBit(int n)59 void markBit(int n) { 60 value |= valueForBit(n); 61 } 62 63 /** Clears the specified bit. */ clearBit(int n)64 void clearBit(int n) { 65 value &= ~valueForBit(n); 66 } 67 68 /** Finds the first marked bit in the set. Result is undefined if all bits are unmarked. */ firstMarkedBit()69 int firstMarkedBit() { 70 for (int n = 0; n < 64; n++) { 71 if (hasBit(n)) { 72 return n; 73 } 74 } 75 return 0; 76 } 77 78 /** 79 * Finds the first marked bit in the set and clears it. Returns the bit index. Result is undefined 80 * if all bits are unmarked. 81 */ clearFirstMarkedBit()82 int clearFirstMarkedBit() { 83 int n = firstMarkedBit(); 84 clearBit(n); 85 return n; 86 } 87 88 /** 89 * Gets the index of the specified bit in the set, which is the number of marked bits that appear 90 * before the specified bit. 91 */ getIndexOfBit(int n)92 int getIndexOfBit(int n) { 93 // return __builtin_popcountll(value & ~(0xffffffffffffffffULL >> n)); 94 int numMarkedBits = 0; 95 for (int i = 0; i < n; i++) { 96 if (hasBit(i)) { 97 numMarkedBits++; 98 } 99 } 100 return numMarkedBits; 101 } 102 setValue(long l)103 public void setValue(long l) { 104 value = l; 105 } 106 getValue()107 public long getValue() { 108 return value; 109 } 110 } 111