/* ***************************************************************** *
 * Copyright 1998 International Business Machines Corporation. All   *
 * Rights Reserved.                                                  *
 *                                                                   *
 * Please read this carefully.  Your use of this reference           *
 * implementation of certain of the IETF public-key infrastructure   *
 * specifications ("Software") indicates your acceptance of the      *
 * following.  If you do not agree to the following, do not install  *
 * or use any of the Software.                                       *
 *                                                                   *
 * Permission to use, reproduce, distribute and create derivative    *
 * works from the Software ("Software Derivative Works"), and to     *
 * distribute such Software Derivative Works is hereby granted to    *
 * you by International Business Machines Corporation ("IBM").  This *
 * permission includes a license under the patents of IBM that are   *
 * necessarily infringed by your use of the Software as provided by  *
 * IBM.                                                              *
 *                                                                   *
 * IBM licenses the Software to you on an "AS IS" basis, without     *
 * warranty of any kind.  IBM HEREBY EXPRESSLY DISCLAIMS ALL         *
 * WARRANTIES OR CONDITIONS, EITHER EXPRESS OR IMPLIED, INCLUDING,   *
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OR CONDITIONS OF       *
 * MERCHANTABILITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR    *
 * PURPOSE.  You are solely responsible for determining the          *
 * appropriateness of using this Software and assume all risks       *
 * associated with the use of this Software, including but not       *
 * limited to the risks of program errors, damage to or loss of      *
 * data, programs or equipment, and unavailability or interruption   *
 * of operations.                                                    *
 *                                                                   *
 * IBM WILL NOT BE LIABLE FOR ANY DIRECT DAMAGES OR FOR ANY SPECIAL, *
 * INCIDENTAL, OR  INDIRECT DAMAGES OR FOR ANY ECONOMIC              *
 * CONSEQUENTIAL DAMAGES (INCLUDING LOST PROFITS OR SAVINGS), EVEN   *
 * IF IBM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.  IBM  *
 * will not be liable for the loss of, or damage to, your records or *
 * data, or any damages claimed by you based on a third party claim. *
 *                                                                   *
 * IBM wishes to obtain your feedback to assist in improving the     *
 * Software.  You grant IBM a world-wide, royalty-free right to use, *
 * copy, distribute, sublicense and prepare derivative works based   *
 * upon any feedback, including materials, error corrections,        *
 * Software Derivatives, enhancements, suggestions and the like that *
 * you provide to IBM relating to the Software (this does not        *
 * include products for which you charge a royalty and distribute to *
 * IBM under other terms and conditions).                            *
 *                                                                   *
 * You agree to distribute the Software and any Software Derivatives *
 * under a license agreement that: 1) is sufficient to notify all    *
 * licensees of the Software and Software Derivatives that IBM       *
 * assumes no liability for any claim that may arise regarding the   *
 * Software or Software Derivatives, and 2) that disclaims all       *
 * warranties, both express and implied, from IBM regarding the      *
 * Software and Software Derivatives.  (If you include this          *
 * Agreement with any distribution of the Software or Software       *
 * Derivatives you will have met this requirement.)  You agree that  *
 * you will not delete any copyright notices in the Software.        *
 *                                                                   *
 * This Agreement is the exclusive statement of your rights in the   *
 * Software as provided by IBM.   Except for the rights granted to   *
 * you in the second paragraph above, You are not granted any other  *
 * patent rights, including but not limited to the right to make     *
 * combinations of the Software with products that infringe IBM      *
 * patents. You agree to comply with all applicable laws and         *
 * regulations, including all export and import laws and regulation. *
 * This Agreement is governed by the laws of the State of New York.  *
 * This Agreement supersedes all other communications,               *
 * understandings or agreements we may have had prior to this        *
 * Agreement.                                                        *
 * ***************************************************************** */

#include "StrngLst.h"
#include "string.h"
#include "malloc.h"

static char * copyOf(const char * s) {
  if (s == NULL) return NULL;
  char * sc = (char *)malloc(strlen(s)+1);
  strcpy(sc, s);
  return sc;
}

StringList::StringList(size_t initSize) {
  slist = NULL;
  olist = NULL;
  listLength = 0;
  items = 0;
  Extent = initSize;
  duplicatesAllowed = true;
  DuplicatesAllowed = true;
  sorted = false;
  Sorted = false;
}


void StringList::extend(unsigned delta) const {
  StringList * varThis = (StringList *)this;
  unsigned i;
  
  if (delta == 0) delta = Extent;
  if (delta == 0) delta = 1;

  varThis->slist = (char **)realloc(slist, sizeof(char *) * (listLength + delta));
  for (i=listLength; i < listLength+delta; i++) varThis->slist[i] = NULL;

  varThis->olist = (void **)realloc(olist, sizeof(void *) * (listLength + delta));
  for (i=listLength; i < listLength+delta; i++) varThis->olist[i] = NULL;

  varThis->listLength+=delta;
}

StringList::~StringList() {
  unsigned i;
  for (i=0; i<items; i++) free(slist[i]);
  free(slist);
  free(olist);
}

unsigned StringList::Count() const {
  StringList * varThis = (StringList *)this;
  varThis->fixup();
  return items;
}

const char * StringList::operator[] (unsigned index) const {
  StringList * varThis = (StringList *)this;
  varThis->fixup();
  
  if (index < items) return slist[index];
  else return NULL;
}

unsigned StringList::AddItem(const char * value, void * ptr) {
  unsigned i, j;
  int lastRes;
  fixup();
  if (sorted) {
// Find the place to insert
    for (i=0; (i<items) && ((lastRes = strcmp(value, slist[i])) > 0); i++);
    if (i<items) {
      if ((duplicatesAllowed) || (lastRes != 0)) {
// We need to make room for the new item in the middle of the array
        if (listLength <= items) extend();
        items++;
        for (j=items-1;j>i;j--) slist[j] = slist[j-1];
      } else {
// Otherwise, if duplicates aren't allowed, we'll overwrite the one we found.
        free(slist[i]);
      };
    } else {
      if (listLength <= items) extend();
      items++;
    };
  } else if (!duplicatesAllowed) {
// See if the string already exists...
    for (i=0; (i<items) && ((lastRes = strcmp(value, slist[i])) != 0); i++);
    if (i>=items) {
// We didn't find a duplicate.
      if (listLength <= items) extend();
      i = items++;
    } else {
// Otherwise overwrite the one we found.
      free(slist[i]);
    };
  } else {
// the simple case - append to the end of the list.
    if (listLength <= items) extend();
    i = items++;
  };
  slist[i] = copyOf(value);
  olist[i] = (void *)ptr;
  return i;
}

unsigned StringList::InsertItem(unsigned index, const char * value, void * ptr) {
  unsigned i;
  Sorted = false;
  fixup();
  if (index > items) index = items;
  if (listLength <= items) extend();
  if (index < items) {
     for (i=items;i>index;i--) slist[i] = slist[i-1];
  };
  slist[index] = copyOf(value);
  olist[index] = (void *)ptr;
  return index;
}

void * StringList::Object(unsigned index) const {
  StringList * varThis = (StringList *)this;
  varThis->fixup();
  if (index < items) return olist[index];
  else return NULL;
}

void StringList::fixup(void) {
  char ** sl;
  void ** ol;
  unsigned ll;
  unsigned it;
  unsigned i;

  if ((sorted == Sorted) && (duplicatesAllowed == DuplicatesAllowed)) return;
  if (Sorted || !DuplicatesAllowed) {
// We're going from unsorted->sorted, or we're preventing duplicates, so we have 
// to rebuild the list.  We don't expect these lists to get too big, so simply 
// allocate a new list to handle stuff.
    sl = slist;
    ol = olist;
    ll = listLength;
    it = items;
    slist = NULL;
    olist = NULL;
    listLength = 0;
    items = 0;
    extend(listLength);
    sorted = Sorted;
    duplicatesAllowed = DuplicatesAllowed;
    for (i=0;i<it;i++) AddItem(sl[i], ol[i]);
    free(sl);
    free(ol);
  };
  sorted = Sorted;
  duplicatesAllowed = DuplicatesAllowed;
}

int StringList::IndexOf(const char * value) const {
  unsigned i;
  StringList * varThis = (StringList *)this;
  varThis->fixup();
  for (i=0;i<items;i++) {
    if (strcmp(value, slist[i]) == 0) return i;
  };
  return -1;

}

int StringList::IndexOfObject(const void * value) const {
  unsigned i;
  StringList * varThis = (StringList *)this;
  varThis->fixup();
  for (i=0;i<items;i++) {
    if (value == olist[i]) return i;
  };
  return -1;

}

void StringList::SetObject(unsigned index, void * ptr) {
  fixup();
  if (index < items) olist[index] = ptr;
}

bool StringList::Remove(unsigned index) {
  unsigned i;
  fixup();
  if (index >= items) return false;
  free(slist[index]);
  for (i=index; i<items-1; i++) {
    slist[i] = slist[i+1];
    olist[i] = olist[i+1];
  };
  items--;
  return true;
}

void StringList::empty(void) {
  unsigned i;
  fixup();
  for (i=0; i<items; i++) free(slist[i]);
  items = 0;
}

