package ModSQL;
import java.io.Serializable;
import java.util.ArrayList;

/* $Id: IndexTableRowset.java,v 1.4 2004/01/04 01:59:39 cvs Exp $
 *
 * Copyright (c) 2004 Chris Studholme <chris.studholme@utoronto.ca>
 *
 * May be copied or modified under the terms of the GNU General Public
 * License.  See COPYING for more information.
 */

/** 
 * Each object describes a set of rows in a table.  The set of rows is
 * described by one or more rowids and a count of the number of rows including
 * and following the specified row.  That is, count n associated with rowid r
 * specifies the n rows beginning at rowid.
 *
 * @author chris.studholme@utoronto.ca
 */
class IndexTableRowset implements Serializable {
  /** Array of rowids. */
  public Object[] rowid;

  /** Array of counts (number of rows beginning with rowid). */
  public long[] count;

  /** Temporary array of rowids.  Only used when building rowset. */
  protected transient ArrayList rowid_array=null;
  /** Temporary array of counts.  Only used when building rowset. */
  protected transient ArrayList count_array=null;

  /**
   * Constructor requiring an initial rowid and count.
   *
   * @param rowid first row
   * @param count number of rows
   */
  public IndexTableRowset(Object rowid, long count) {
    rowid_array = new ArrayList();
    count_array = new ArrayList();
    rowid_array.add(rowid);
    count_array.add(new Long(count));
  }

  /**
   * Add count rows starting at rowid.
   *
   * @param rowid first row
   * @param count number of rows
   */
  public void add(Object rowid, long count) {
    if (rowid_array==null && rowid==null) {
      rowid_array = new ArrayList();
      count_array = new ArrayList();
    }
    rowid_array.add(rowid);
    count_array.add(new Long(count));
  }

  /**
   * Merge another rowset with this one.
   * 
   * @param o other rowset
   */
  public void mergeWith(IndexTableRowset o) {
    if (rowid_array==null && rowid==null) {
      rowid_array = new ArrayList();
      count_array = new ArrayList();
    }
    rowid_array.addAll(o.rowid_array);
    count_array.addAll(o.count_array);
  }

  /**
   * Finish rowset by setting static arrays rowid and count.
   */
  public void finish() {
    if (rowid==null && rowid_array!=null) {
      rowid = rowid_array.toArray();
      count = new long[count_array.size()];
      for (int i=0; i<count_array.size(); ++i)
	count[i] = ((Long)count_array.get(i)).longValue();
      rowid_array = null;
      count_array = null;
    }
  }
};
