# IndexState.java

    /*
    ** Module   : IndexState.java
    ** Abstract : Tracks which indices have been updated for a transient, newly created record.
    **
    ** Copyright (c) 2020-2024, Golden Code Development Corporation.
    **
    ** -#- -I- --Date-- ---------------------------------------Description---------------------------------------
    ** 001 ECF 20200820 First revision.
    ** 002 IAS 20200914 Re-work (de)serialization.
    **     ECF 20210924 Minor cleanup.
    ** 003 TJD 20240110 Implemented toString for easier debugging
    */

    /*
    ** This program is free software: you can redistribute it and/or modify
    ** it under the terms of the GNU Affero General Public License as
    ** published by the Free Software Foundation, either version 3 of the
    ** License, or (at your option) any later version.
    **
    ** This program is distributed in the hope that it will be useful,
    ** but WITHOUT ANY WARRANTY; without even the implied warranty of
    ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    ** GNU Affero General Public License for more details.
    **
    ** You may find a copy of the GNU Affero GPL version 3 at the following
    ** location: https://www.gnu.org/licenses/agpl-3.0.en.html
    **
    ** Additional terms under GNU Affero GPL version 3 section 7:
    **
    **   Under Section 7 of the GNU Affero GPL version 3, the following additional
    **   terms apply to the works covered under the License.  These additional terms
    **   are non-permissive additional terms allowed under Section 7 of the GNU
    **   Affero GPL version 3 and may not be removed by you.
    **
    **   0. Attribution Requirement.
    **
    **     You must preserve all legal notices or author attributions in the covered
    **     work or Appropriate Legal Notices displayed by works containing the covered
    **     work.  You may not remove from the covered work any author or developer
    **     credit already included within the covered work.
    **
    **   1. No License To Use Trademarks.
    **
    **     This license does not grant any license or rights to use the trademarks
    **     Golden Code, FWD, any Golden Code or FWD logo, or any other trademarks
    **     of Golden Code Development Corporation. You are not authorized to use the
    **     name Golden Code, FWD, or the names of any author or contributor, for
    **     publicity purposes without written authorization.
    **
    **   2. No Misrepresentation of Affiliation.
    **
    **     You may not represent yourself as Golden Code Development Corporation or FWD.
    **
    **     You may not represent yourself for publicity purposes as associated with
    **     Golden Code Development Corporation, FWD, or any author or contributor to
    **     the covered work, without written authorization.
    **
    **   3. No Misrepresentation of Source or Origin.
    **
    **     You may not represent the covered work as solely your work.  All modified
    **     versions of the covered work must be marked in a reasonable way to make it
    **     clear that the modified work is not originating from Golden Code Development
    **     Corporation or FWD.  All modified versions must contain the notices of
    **     attribution required in this license.
    */

    package com.goldencode.p2j.persist.orm;

    import java.io.*;
    import java.util.*;

    /**
     * An object which tracks which indices have been updated for a newly created database record, before it is
     * first flushed to the database.
     */
    public final class IndexState
    implements Externalizable
    {
       /** Map of unique indices which need to be updated */
       private BitSet unique;

       /** Map of non-unique indices which need to be updated */
       private BitSet nonunique;

       /** UID of primary index, if any (0 if none) */
       private int primaryUid;

       /** Default constructor */
       public IndexState()
       {
       }

       /**
        * Constructor.
        *
        * @param   ulen
        *          Number of unique indices. May be 0, but not negative.
        * @param   nlen
        *          Number of non-unique indices. May be 0, but not negative.
        * @param   primaryUid
        *          Optional UID of the primary index, if any. Must be set to 0 if there is no primary index.
        */
       public IndexState(int ulen, int nlen, int primaryUid)
       {
          this.unique = new BitSet(ulen);
          this.nonunique = new BitSet(nlen);
          this.primaryUid = primaryUid;
       }

       /**
        * Get the state of the index with the given index UID.
        *
        * @param   idxUid
        *          UID of the desired index.
        *
        * @return  {@code true} if the index has not yet been updated; {@code false} if it has been updated.
        */
       public boolean get(int idxUid)
       {
          return bitSetFromUid(idxUid).get(offsetFromUid(idxUid));
       }

       /**
        * Mark an index as needing to be updated.
        *
        * @param   idxUid
        *          Identifier of a unique (positive value) or non-unique (negative value) index.
        * @param   value
        *          new value
        */
       public void set(int idxUid, boolean value)
       {
          bitSetFromUid(idxUid).set(offsetFromUid(idxUid), value);
       }

       /**
        * Mark an index as having been updated by clearing its corresponding bit in the appropriate bit set.
        *
        * @param   idxUid
        *          Identifier of a unique (positive value) or non-unique (negative value) index.
        */
       void clear(int idxUid)
       {
          bitSetFromUid(idxUid).clear(offsetFromUid(idxUid));
       }

       /**
        * Indicate whether there are no indices remaining to be updated.
        *
        * @return  {@code true} if there are no indices left to be updated, else {@code false}. {@code true}
        *          will naturally be reported for a table with no indices.
        */
       public boolean isEmpty()
       {
          return unique.isEmpty() && nonunique.isEmpty();
       }

       /**
        * Get the index identifier of the primary index, if any.
        *
        * @return  Primary index UID.
        */
       public boolean getPrimary()
       {
          return primaryUid != 0 && get(primaryUid);
       }

       /**
        * Set all bits in both the unique and non-unique index bit sets.
        *
        * @param   ulen
        *          Number of unique indices. May be 0, but not negative.
        * @param   nlen
        *          Number of non-unique indices. May be 0, but not negative.
        */
       void setAll(int ulen, int nlen)
       {
          if (ulen > 0)
          {
             unique.set(0, ulen);
          }

          if (nlen > 0)
          {
             nonunique.set(0, nlen);
          }
       }

       /**
        * Clear all bits in both the unique and non-unique index bit sets.
        */
       void clearAll()
       {
          unique.clear();
          nonunique.clear();
       }

       /**
        * Get the bit set associated with either the unique or non-unique indices.
        *
        * @param   isUnique
        *          {@code true} to get the unique index bit set; {@code false} to get the non-unique index bit
        *          set.
        *
        * @return  Index bit set as described above.
        */
       BitSet getBitSet(boolean isUnique)
       {
          return isUnique ? unique : nonunique;
       }

       /**
        * Get the bit set upon which to operate, based on the value of the given index UID. A positive UID
        * returns the unique index bit set; a negative UID returns the non-unique index bit set.
        *
        * @param   idxUid
        *          A positive or negative index UID. A value of 0 is considered invalid.
        *
        * @return  The bit set representing the array of unique or non-unique indices, as described above.
        */
       private BitSet bitSetFromUid(int idxUid)
       {
          return idxUid > 0 ? unique : nonunique;
       }

       /**
        * Get the bit offset on which to operate, based on the value of the given index UID.
        *
        * @param   idxUid
        *          A positive or negative index UID. A value of 0 is considered invalid.
        *
        * @return  The bit offset associated with the UID.
        */
       private int offsetFromUid(int idxUid)
       {
          return (idxUid < 0 ? -idxUid : idxUid) - 1;
       }

       /**
        * Replacement for the default object writing method.
        *
        * @param    out
        *           The output destination to which fields will be saved.
        *
        * @throws   IOException
        *           In case of I/O errors.
        */
       @Override
       public void writeExternal(ObjectOutput out) throws IOException
       {
          out.writeObject(unique);
          out.writeObject(nonunique);
          out.writeInt(primaryUid);
       }

       /**
        * Replacement for the default object reading method.
        *
        * @param    in
        *           Input source from which fields will be restored.
        *
        * @throws   IOException
        *           In case of I/O errors.
        * @throws   ClassNotFoundException
        *           If payload can't be instantiated.
        */
       @Override
       public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
       {
          unique = (BitSet) in.readObject();
          nonunique = (BitSet) in.readObject();
          primaryUid = in.readInt();
       }
       /**
        * Create a string representation of this IndexState for debugging purposes.
        *
        */
       @Override
       public String toString()
       {
          return "IndexState [unique=" + unique + ", nonunique=" + nonunique + ", primaryUid="
                   + primaryUid + ", isEmpty()=" + isEmpty() + ", getPrimary()=" + getPrimary() + "]";
       }
    }