Small optimization to check ranges of bits set in BitArray in bulk
[zxing.git] / core / src / com / google / zxing / common / BitArray.java
index 91ad8b3..3bfc3c9 100644 (file)
@@ -73,6 +73,50 @@ public final class BitArray {
     }\r
   }\r
 \r
+  /**\r
+   * Efficient method to check if a range of bits is set, or not set.\r
+   *\r
+   * @param start start of range, inclusive.\r
+   * @param end end of range, exclusive\r
+   * @param value if true, checks that bits in range are set, otherwise checks that they are not set\r
+   * @return true iff all bits are set or not set in range, according to value argument\r
+   * @throws IllegalArgumentException if end is less than or equal to start\r
+   */\r
+  public boolean isRange(int start, int end, boolean value) {\r
+    if (end < start) {\r
+      throw new IllegalArgumentException();\r
+    }\r
+    if (end == start) {\r
+      return true; // empty range matches\r
+    }\r
+    end--; // will be easier to treat this as the last actually set bit -- inclusive    \r
+    int firstInt = start >> 5;\r
+    int lastInt = end >> 5;\r
+    for (int i = firstInt; i <= lastInt; i++) {\r
+      int firstBit = i > firstInt ? 0 : start & 0x1F;\r
+      int lastBit = i < lastInt ? 31 : end & 0x1F;\r
+      int mask;\r
+      if (firstBit == 0 && lastBit == 31) {\r
+        mask = -1;\r
+      } else {\r
+        mask = 0;\r
+        for (int j = firstBit; j <= lastBit; j++) {\r
+          mask |= 1 << j;\r
+        }\r
+      }\r
+      if (value) {\r
+        if ((bits[i] & mask) != mask) {\r
+          return false;\r
+        }\r
+      } else {\r
+        if ((bits[i] & mask) != 0) {\r
+          return false;\r
+        }\r
+      }\r
+    }\r
+    return true;\r
+  }\r
+\r
   /**\r
    * @return underlying array of ints. The first element holds the first 32 bits, and the least\r
    *  significant bit is bit 0.\r