#include "oop.h"

Dictionary::Dictionary(int size) : Set(size)
{
}

oop Dictionary::classNew(int size)
{
  return new Dictionary(size);
}

oop Dictionary::noCheckAdd(oop anObject)
{
  // Must be defined separately for Dictionary because
  // findElementOrNil expects a key, not an Association.
  mArray->atPut(findElementOrNil(anObject->key()), anObject);
  mTally += 1;
  return this;
}

oop Dictionary::atOrNil(oop key)
{
  // Answer the value associated with the key or, if nil if the key isn't found.
  oop assoc= mArray->at(findElementOrNil(key));
  return assoc ? assoc->value() : 0;
}

oop Dictionary::at(oop key)
{
  oop value= atOrNil(key);
  if (!value) error("key '%s' not found", key->printCString());
  return value;
}

oop Dictionary::atPut(oop key, oop anObject)
{
  // Set the value at key to be anObject.  If key is not found, create a
  // new entry for key and set is value to anObject.  Answer anObject.
  int index= findElementOrNil(key);
  oop assoc= mArray->at(index);
  if (assoc)
    assoc->value(anObject);
  else
    atNewIndexPut(index, new Association(key, anObject));
  return anObject;
}

oop Dictionary::keys(void)
{
  oop keys= new Set(mArray->size());
  iterate(this, iterator)
    keys->add(iterator.element()->key());
  return keys;
}

int Dictionary::includesKey(oop aKey)
{
  return !!mArray->at(findElementOrNil(aKey));
}

