1 package org.apache.lucene.util; 2 3 18 19 import java.io.IOException ; 20 21 import org.apache.lucene.store.Directory; 22 import org.apache.lucene.store.IndexInput; 23 import org.apache.lucene.store.IndexOutput; 24 25 36 public final class BitVector { 37 38 private byte[] bits; 39 private int size; 40 private int count = -1; 41 42 43 public BitVector(int n) { 44 size = n; 45 bits = new byte[(size >> 3) + 1]; 46 } 47 48 49 public final void set(int bit) { 50 bits[bit >> 3] |= 1 << (bit & 7); 51 count = -1; 52 } 53 54 55 public final void clear(int bit) { 56 bits[bit >> 3] &= ~(1 << (bit & 7)); 57 count = -1; 58 } 59 60 62 public final boolean get(int bit) { 63 return (bits[bit >> 3] & (1 << (bit & 7))) != 0; 64 } 65 66 68 public final int size() { 69 return size; 70 } 71 72 75 public final int count() { 76 if (count == -1) { 78 int c = 0; 79 int end = bits.length; 80 for (int i = 0; i < end; i++) 81 c += BYTE_COUNTS[bits[i] & 0xFF]; count = c; 83 } 84 return count; 85 } 86 87 private static final byte[] BYTE_COUNTS = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 89 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 90 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 91 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 92 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 93 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 94 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 95 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 96 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 97 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 98 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 99 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 100 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 101 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 102 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 103 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 104 }; 105 106 107 110 public final void write(Directory d, String name) throws IOException { 111 IndexOutput output = d.createOutput(name); 112 try { 113 output.writeInt(size()); output.writeInt(count()); output.writeBytes(bits, bits.length); } finally { 117 output.close(); 118 } 119 } 120 121 124 public BitVector(Directory d, String name) throws IOException { 125 IndexInput input = d.openInput(name); 126 try { 127 size = input.readInt(); count = input.readInt(); bits = new byte[(size >> 3) + 1]; input.readBytes(bits, 0, bits.length); } finally { 132 input.close(); 133 } 134 } 135 136 } 137 | Popular Tags |