/* ***** BEGIN LICENSE BLOCK *****
 * Source last modified: $Id: CHXFlatArray.h,v 1.2.2.3 2004/07/09 01:49:47 hubbe Exp $
 * 
 * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
 * 
 * The contents of this file, and the files included with this file,
 * are subject to the current version of the RealNetworks Public
 * Source License (the "RPSL") available at
 * http://www.helixcommunity.org/content/rpsl unless you have licensed
 * the file under the current version of the RealNetworks Community
 * Source License (the "RCSL") available at
 * http://www.helixcommunity.org/content/rcsl, in which case the RCSL
 * will apply. You may also obtain the license terms directly from
 * RealNetworks.  You may not use this file except in compliance with
 * the RPSL or, if you have a valid RCSL with RealNetworks applicable
 * to this file, the RCSL.  Please see the applicable RPSL or RCSL for
 * the rights, obligations and limitations governing use of the
 * contents of the file.
 * 
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL") in which case the provisions of the GPL are applicable
 * instead of those above. If you wish to allow use of your version of
 * this file only under the terms of the GPL, and not to allow others
 * to use your version of this file under the terms of either the RPSL
 * or RCSL, indicate your decision by deleting the provisions above
 * and replace them with the notice and other provisions required by
 * the GPL. If you do not delete the provisions above, a recipient may
 * use your version of this file under the terms of any one of the
 * RPSL, the RCSL or the GPL.
 * 
 * This file is part of the Helix DNA Technology. RealNetworks is the
 * developer of the Original Code and owns the copyrights in the
 * portions it created.
 * 
 * This file, and the files included with this file, is distributed
 * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
 * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
 * ENJOYMENT OR NON-INFRINGEMENT.
 * 
 * Technology Compatibility Kit Test Suite(s) Location:
 *    http://www.helixcommunity.org/content/tck
 * 
 * Contributor(s):
 * 
 * ***** END LICENSE BLOCK ***** */

///////////////////////////////////////////////////////////////////////////////////////
//
//  CHXFlatArray
//
//  A flat array data structure for storage and fast retrieval of records.
//
//  Usage notes:
//
//    Record numbers are always zero-based indices.
//
//    The record size must be specified before records are added to the array, either
//    in the constructor or with the method SetRecordSize.  For example, if you are
//    keeping an array of Flummoxes, declare the array as
//
//      CHXFlatArray arrMyFlummoxes( sizeof(Flummox) )
//
//    Use HasRecord, FindRecord, DiffRecords, or SectRecords to avoid
//    traversing the array with a for loop. 
//
//    Use SetCount before adding or removing large numbers of records; this avoids
//    the need for the array data to be reallocated each time it grows or shrinks.  
//    The items are initially added initialized to zero.  For example,
//
//      arrItems.SetCount( nTotalItemsNeeded );   // pre-allocate the space needed
//
//      for (i = 0; i < nTotalItemsNeeded; i++)   // now fill in the records 
//      {
//          arrItems.SetAt(i, &itemData[i]);
//      }
//
//
//  Implementation notes:
//
//    This array is implemented for maximum *retrieval* speed and minimum code, 
//    not for maximimum insertion/deletion speed.  It does not do chunked allocation
//    of memory for records, nor does it do sparse record allocation.  Chunked
//    allocations require more complex code; sparse allocations require more code
//    and defeat speed advantages of contiguous allocation, particularly for
//    retrieving record data from the processor data cache.
//
//    To improve speed when adding or removing many records, use SetCount to
//    explicitly set the number of records in the array. This minimizes
//    the need to reallocate memory that would be required using Push/Pop
//    or Enqueue/Dequeue repeatedly.
//
///////////////////////////////////////////////////////////////////////////////////////

#ifndef _CHXFLATARRAY_H
#define _CHXFLATARRAY_H

#include "enter_hx_headers.h"
#include "hxtypes.h"
#include "exit_hx_headers.h"

typedef bool (*AreElementsEqualProcPtr) (const void* item1Ptr, const void* item2Ptr);

class CHXFlatArray
{
public:
	CHXFlatArray(UINT32 recordSize, const void* firstItemPtr);
	CHXFlatArray(UINT32 recordSize);
	CHXFlatArray(const CHXFlatArray& sourceArray);
	~CHXFlatArray();
    
	CHXFlatArray& operator=(const CHXFlatArray& sourceArray);
	CHXFlatArray& operator+=(const CHXFlatArray& array2);		// concatenate array records
	
	bool SetRecordSize(UINT32 recordSize);			// removes all current entries
	
	UINT32 CopyDataTo(void *pOutBuff, UINT32 buffSize) const;	// get all record data at once
	bool SetToDataAt(const void *pBuff, UINT32 buffSize);	// set all record data at once
	
	bool SetAt(UINT32 recordNum, const void *itemPtr); // allocates zeroed intermediate records if needed
	bool GetAt(UINT32 recordNum, void *outItemPtr) const;
	
	bool InsertBefore(UINT32 recordNum, const void *itemPtr);	// lengthens array
	bool Remove(UINT32 recordNum);				// shortens array
	
	bool Push(const void *itemPtr);		// add to end of array
	bool Pop(void *itemPtr);			// remove from end of array
	
	bool Enqueue(const void *itemPtr);		// same as Push
	bool Dequeue(void *itemPtr);		// remove from start of array
			
	bool FindRecord(const void *matchPtr, AreElementsEqualProcPtr AreElementsEqual,
					UINT32 startAtRecordNum = 0, UINT32 *outFoundRecordNum = NULL, void *outFoundRecordPtr = NULL) const;
								// looks for identical record
	
	bool DiffRecords(AreElementsEqualProcPtr AreElementsEqual, const CHXFlatArray& recordDataToSubtract);  // removes common records
	bool SectRecords(AreElementsEqualProcPtr AreElementsEqual, const CHXFlatArray& recordDataToIntersect); // removes unique records
	
	void RemoveAll();
		
	bool SetCount(UINT32 numRecords);	// allocates zeroed records at the end when growing array
	
	inline bool HasRecord(const void *matchPtr, AreElementsEqualProcPtr AreElementsEqual) const
	{
		return FindRecord(matchPtr, AreElementsEqual, 0);
	}
	inline UINT32 GetRecordSize() const
	{
		return mRecordSize;
	}
	inline UINT32 GetCount() const		// returns current number of records
	{
		return mCount;
	}
	inline UINT32 GetUpperBound() const
	{
		return mCount - 1;
	}
	inline bool IsEmpty() const
	{
		return (mCount == 0);
	}
	inline bool GetTopOfStack(void *itemPtr)		// copy from end of array
	{
		return GetAt(mCount - 1, itemPtr);
	}
	
private:
	
	UINT32 mRecordSize;
	UINT32 mCount;		// number of records stored in array
	
	UINT8 *mpData;		// array data, (nil if no data)
	UINT32 mDataSize;	// size of array, 0 if no data (mpData should also be nil)
	
	bool InternalReplaceAllData(const void *pReplacementData, UINT32 replacementDataSize);
	bool InternalInsertData(UINT32 insertBeforeOffset, const void *pInsertData, UINT32 insertDataSize); // insertBeforeOffset is 0-based
	inline bool InternalAppendData(const void *pAppendData, UINT32 appendDataSize)
	{
		return InternalInsertData(mDataSize, pAppendData, appendDataSize);
	}
	bool InternalDeleteData(UINT32 deleteAtOffset, UINT32 deleteDataSize);
	inline bool InternalTruncateData(UINT32 deleteDataSize)
	{
		return InternalDeleteData(mDataSize - deleteDataSize, deleteDataSize);
	}
	inline bool InternalDeleteAllData()
	{
		return InternalDeleteData(0, mDataSize);
	}
};

#endif // _CHXFLATARRAY_H
