/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.lucene.index;

import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.BitSetIterator;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.RamUsageEstimator;

/**
 * Accumulator for documents that have a value for a field. This is optimized for the case that all
 * documents have a value.
 */
public final class DocsWithFieldSet extends DocIdSet {

  private static final long BASE_RAM_BYTES_USED =
      RamUsageEstimator.shallowSizeOfInstance(DocsWithFieldSet.class);

  private FixedBitSet set;
  private int cardinality = 0;
  private int lastDocId = -1;

  /** Creates an empty DocsWithFieldSet. */
  public DocsWithFieldSet() {}

  /**
   * Add a document to the set
   *
   * @param docID – document ID to be added
   */
  public void add(int docID) {
    if (docID <= lastDocId) {
      throw new IllegalArgumentException(
          "Out of order doc ids: last=" + lastDocId + ", next=" + docID);
    }
    if (set != null) {
      set = FixedBitSet.ensureCapacity(set, docID);
      set.set(docID);
    } else if (docID != cardinality) {
      // migrate to a sparse encoding using a bit set
      set = new FixedBitSet(docID + 1);
      set.set(0, cardinality);
      set.set(docID);
    }
    lastDocId = docID;
    cardinality++;
  }

  /**
   * Add a contiguous range of document IDs to the set.
   *
   * @param from first document ID (inclusive)
   * @param toExclusive one past the last document ID (exclusive)
   */
  public void addRange(int from, int toExclusive) {
    if (from >= toExclusive) {
      if (from > toExclusive) {
        throw new IllegalArgumentException(
            "from=" + from + " must be <= toExclusive=" + toExclusive);
      }
      return;
    }
    if (from <= lastDocId) {
      throw new IllegalArgumentException(
          "Out of order doc ids: last=" + lastDocId + ", next=" + from);
    }
    int count = toExclusive - from;
    if (set != null) {
      set = FixedBitSet.ensureCapacity(set, toExclusive - 1);
      set.set(from, toExclusive);
    } else if (from != cardinality) {
      // migrate to a sparse encoding using a bit set
      set = new FixedBitSet(toExclusive);
      set.set(0, cardinality);
      set.set(from, toExclusive);
    }
    lastDocId = toExclusive - 1;
    cardinality += count;
  }

  @Override
  public long ramBytesUsed() {
    return BASE_RAM_BYTES_USED + (set == null ? 0 : set.ramBytesUsed());
  }

  @Override
  public DocIdSetIterator iterator() {
    return set != null ? new BitSetIterator(set, cardinality) : DocIdSetIterator.all(cardinality);
  }

  /** Return the number of documents of this set. */
  public int cardinality() {
    return cardinality;
  }
}
