// ---------------------------------------------------------------------------
// - BitSet.cpp                                                              -
// - standard object library - bit set class implementation                  -
// ---------------------------------------------------------------------------
// - This program is free software;  you can redistribute it  and/or  modify -
// - it provided that this copyright notice is kept intact.                  -
// -                                                                         -
// - 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.  In no event shall -
// - the copyright holder be liable for any  direct, indirect, incidental or -
// - special damages arising in any way out of the use of this software.     -
// ---------------------------------------------------------------------------
// - copyright (c) 1999-2006 amaury darsch                                   -
// ---------------------------------------------------------------------------

#include "Vector.hpp"
#include "BitSet.hpp"
#include "Boolean.hpp"
#include "Integer.hpp"
#include "QuarkZone.hpp"
#include "Exception.hpp"

namespace afnix {
    
  // -------------------------------------------------------------------------
  // - private section                                                       -
  // -------------------------------------------------------------------------

  // default bitset size
  const long BITSET_SIZE = 32;

  // this procedure return the number of bytes needed to create a bitset
  static long get_length (const long size) {
    long result = (size <= 0) ? 1 : (size / 8);
    if ((size % 8) == 0) return result;
    return (result + 1);
  }

  // -------------------------------------------------------------------------
  // - class section                                                         -
  // -------------------------------------------------------------------------

  // create a default bitset

  BitSet::BitSet (void) {
    d_size   = BITSET_SIZE;
    long len = get_length (d_size); 
    p_byte   = new t_byte[len];
    for (long i = 0; i < len; i++) p_byte[i] = nilc;
  }

  // create a new bitset with a certain size

  BitSet::BitSet (const long size) {
    d_size = (size <= 0) ? BITSET_SIZE : size;
    long len = get_length (d_size); 
    p_byte   = new t_byte[len];
    for (long i = 0; i < len; i++) p_byte[i] = nilc;
  }

  // copy constructor for this bitset

  BitSet::BitSet (const BitSet& that) {
    d_size   = that.d_size;
    long len = get_length(d_size);
    p_byte   = new t_byte[len];
    for (long i = 0; i < len; i++) p_byte[i] = that.p_byte[i];
  }

  // destroy this bitset

  BitSet::~BitSet (void) {
    delete [] p_byte;
  }

  // return the class name

  String BitSet::repr (void) const {
    return "BitSet";
  }

  // assign a bitset to this one

  BitSet& BitSet::operator = (const BitSet& that) {
    // check if we assign to ourself
    if (this == &that) return *this;
    wrlock ();
    // destroy the old bitset
    delete [] p_byte;
    // set the new bitset
    d_size   = that.d_size;
    long len = get_length (d_size);
    p_byte   = new t_byte[len];
    for (long i = 0; i < len; i++) p_byte[i] = that.p_byte[i];
    unlock ();
    return *this;
  }
  
  // check that two bitsets are equal

  bool BitSet::operator == (const BitSet& bset) const {
    if (d_size != bset.d_size) return false;
    for (long i = 0; i < d_size; i++) {
      if (p_byte[i] != bset.p_byte[i]) return false;
    }
    return true;
  }
  
  // return the bit set size
  
  long BitSet::length (void) const {
    return d_size;
  }
  
  // get a bit at a certain position

  bool BitSet::get (const long pos) const {
    rdlock ();
    if ((pos < 0) || (pos >= d_size)) {
      unlock ();
      throw Exception ("bound-error", "invalid bit position in bitset");
    }
    t_byte byte = p_byte[pos/8];
    long   boff = pos % 8;
    t_byte mask = (boff == 0) ? 0x01 : (0x01 << (boff-1));
    unlock ();
    return ((byte & mask) == mask);
  }

  // mark a bit at a certain position

  void BitSet::mark (const long pos) {
    if (pos < 0) throw Exception ("bound-error", "negative bit position");
    wrlock ();
    if (pos >= d_size) reserve (pos+1);
    long   boff    = pos % 8;
    t_byte mask    = (boff == 0) ? 0x01 : (0x01 << (boff-1));
    p_byte[pos/8] |= mask;
    unlock ();
  }

  // clear a bit at a certain position

  void BitSet::clear (const long pos) {
    if (pos < 0) throw Exception ("bound-error", "negative bit position");
    wrlock ();
    if (pos >= d_size) reserve (pos+1);
    long   boff    = pos % 8;
    t_byte mask    = (boff == 0) ? 0x01 : (0x01 << (boff-1));
    p_byte[pos/8] &= (~mask);
    unlock ();
  }

  // set a bit at a certain position

  void BitSet::set (const long pos, const bool bit) {
    if (bit == true) 
      mark  (pos);
    else
      clear (pos);
  }

  // set a byte at a certain position

  void BitSet::set (const long idx, const t_byte val) {
    // check if the position is valid - here idx is in byte
    long pos = idx * 8;
    if (pos >= d_size) reserve (pos+1);
    // set the byte
    p_byte[idx] = val;
  }

  // reserve a new size for this bitset

  void BitSet::reserve (const long size) {
    wrlock ();
    // check for the size
    if (size <= d_size) {
      unlock ();
      return;
    }
    // create the new array
    long    nlen  = get_length (size); 
    t_byte* bytes = new t_byte[nlen];
    for (long i = 0; i < nlen; i++) bytes[i] = nilc;
    // update the old array into the new one
    long olen = get_length (d_size);
    for (long i = 0; i < olen; i++) bytes[i] |= p_byte[i];
    // destroy old arry and update
    delete [] p_byte;
    p_byte = bytes;
    d_size = size;
    unlock ();
  }

  // -------------------------------------------------------------------------
  // - object section                                                        -
  // -------------------------------------------------------------------------

  // the quark zone
  static const long QUARK_ZONE_LENGTH = 5;
  static QuarkZone  zone (QUARK_ZONE_LENGTH);

  // the object supported quarks
  static const long QUARK_GET    = zone.intern ("get");
  static const long QUARK_SET    = zone.intern ("set");
  static const long QUARK_MARK   = zone.intern ("mark");
  static const long QUARK_CLEAR  = zone.intern ("clear");
  static const long QUARK_LENGTH = zone.intern ("length");

  // create a new object in a generic way

  Object* BitSet::mknew (Vector* argv) {
    long argc = (argv == nilp) ? 0 : argv->length ();
    if (argc == 0) return new BitSet;
    if (argc == 1) {
      long size = argv->getint (0);
      return new BitSet (size);
    }
    throw Exception ("argument-error", "too many argument for bitset");
  }

  // return true if the given quark is defined

  bool BitSet::isquark (const long quark, const bool hflg) const {
    rdlock ();
    if (zone.exists (quark) == true) {
      unlock ();
      return true;
    }
    bool result = hflg ? Object::isquark (quark, hflg) : false;
    unlock ();
    return result;
  }

  // apply this object with a set of arguments and a quark

  Object* BitSet::apply (Runnable* robj, Nameset* nset, const long quark,
			 Vector* argv) {
    // get the number of arguments
    long argc = (argv == nilp) ? 0 : argv->length ();

    // dispatch 0 argument
    if (argc == 0) {
      if (quark == QUARK_LENGTH) return new Integer (length ());
    }

    // dispatch 1 argument
    if (argc == 1) {
      if (quark == QUARK_GET) {
	long pos = argv->getint (0);
	return new Boolean (get (pos));
      }
      if (quark == QUARK_MARK) {
	long pos = argv->getint (0);
	mark (pos);
	return nilp;
      }
      if (quark == QUARK_CLEAR) {
	long pos = argv->getint (0);
	clear (pos);
	return nilp;
      }
    }
    // dispatch 2 arguments
    if (argc == 2) {
      if (quark == QUARK_SET) {
	long pos = argv->getint  (0);
	bool bit = argv->getbool (1);
	set (pos, bit);
	return nilp;
      }
    }
    // call the object method
    return Object::apply (robj, nset, quark, argv);
  }
}
