private void appendFill(int nWords, int v) {
   if (vec.isEmpty()) {
     if (v == 0) {
       vec.add(HEADER0 | nWords);
     } else {
       vec.add(HEADER1 | nWords);
     }
   } else if (nWords > 1) {
     int back = getBack();
     if (v == 0) {
       if (isZeroFill(back)) {
         setBack(back + nWords);
       } else {
         vec.add(HEADER0 | nWords);
       }
     } else if (isOneFill(back)) {
       setBack(back + nWords);
     } else {
       vec.add(HEADER1 | nWords);
     }
   } else {
     active.val = v != 0 ? ALLONES : 0;
     appendLiteral();
   }
 }
  /**
   * Returns the number of 1 bits in the bitset.
   *
   * @return the number of 1 bits in the bitset.
   */
  public int cardinality() {
    // check the cardinality, again if it has been reset.
    if (nset == 0 && !vec.isEmpty()) {
      doCount();
    }

    // the sizes in the vector and the active word.
    return nset + Integer.bitCount(active.val);
  }
  private void appendCounter(int val, int cnt) {
    int head = 2 + val;
    int w = (head << SECONDBIT) + cnt;

    nbits += cnt * MAXBITS;
    if (vec.isEmpty()) {
      vec.add(w);
    } else {
      int back = getBack();
      if ((back >>> SECONDBIT) == head) {
        back += cnt;
        setBack(back);
      } else if ((back == ALLONES) && head == 3) {
        setBack(w + 1);
      } else if ((back == 0) && head == 2) {
        setBack(w + 1);
      } else {
        vec.add(w);
      }
    }
  }