Merge pull request #76 from Arkshine/improve-cellarray

Update dynamic Array.
This commit is contained in:
Vincent Herbet 2014-08-01 18:03:53 +02:00
commit 47dc226393
9 changed files with 1304 additions and 1172 deletions

View File

@ -147,8 +147,8 @@ void UTIL_ShowMenu(edict_t* pEntity, int slots, int time, char *menu, int mlen);
void UTIL_ClientSayText(edict_t *pEntity, int sender, char *msg); void UTIL_ClientSayText(edict_t *pEntity, int sender, char *msg);
void UTIL_TeamInfo(edict_t *pEntity, int playerIndex, const char *pszTeamName); void UTIL_TeamInfo(edict_t *pEntity, int playerIndex, const char *pszTeamName);
template <typename D> template <typename D> int UTIL_CheckValidChar(D *c);
int UTIL_CheckValidChar(D *c); template <typename D, typename S> unsigned int strncopy(D *dest, const S *src, size_t count);
unsigned int UTIL_GetUTF8CharBytes(const char *stream); unsigned int UTIL_GetUTF8CharBytes(const char *stream);
unsigned int UTIL_ReplaceAll(char *subject, size_t maxlength, const char *search, const char *replace, bool caseSensitive); unsigned int UTIL_ReplaceAll(char *subject, size_t maxlength, const char *search, const char *replace, bool caseSensitive);
char *UTIL_ReplaceEx(char *subject, size_t maxLen, const char *search, size_t searchLen, const char *replace, size_t replaceLen, bool caseSensitive); char *UTIL_ReplaceEx(char *subject, size_t maxLen, const char *search, size_t searchLen, const char *replace, size_t replaceLen, bool caseSensitive);
@ -301,7 +301,7 @@ int amxstring_len(cell* cstr);
int load_amxscript(AMX* amx, void** program, const char* path, char error[64], int debug); int load_amxscript(AMX* amx, void** program, const char* path, char error[64], int debug);
int set_amxnatives(AMX* amx, char error[64]); int set_amxnatives(AMX* amx, char error[64]);
int set_amxstring(AMX *amx, cell amx_addr, const char *source, int max); int set_amxstring(AMX *amx, cell amx_addr, const char *source, int max);
int set_amxstring_utf8(AMX *amx, cell amx_addr, const char *source, size_t sourcelen, size_t maxlen); template <typename T> int set_amxstring_utf8(AMX *amx, cell amx_addr, const T *source, size_t sourcelen, size_t maxlen);
int unload_amxscript(AMX* amx, void** program); int unload_amxscript(AMX* amx, void** program);
void copy_amxmemory(cell* dest, cell* src, int len); void copy_amxmemory(cell* dest, cell* src, int len);

File diff suppressed because it is too large Load Diff

View File

@ -31,352 +31,193 @@
#ifndef DATASTRUCTS_H #ifndef DATASTRUCTS_H
#define DATASTRUCTS_H #define DATASTRUCTS_H
class CellVector #include <am-vector.h>
class CellArray
{ {
private:
cell* data; // allocated with malloc
size_t cellcount; // how many cells per element
size_t cursize; // current size of the vector (maximum elements)
size_t count; // how many units of the vector are in use
bool GrowIfNeeded(size_t howmany)
{
/* Shortcut out if we can store this */
if (count + howmany <= cursize)
{
return true;
}
/* Set a base allocation size of 8 items */
if (!cursize)
{
cursize = 8;
}
/* If it's not enough, keep doubling */
while (count + howmany > cursize)
{
cursize *= 2;
}
if (data)
{
data = (cell*)realloc(data, (sizeof(cell)* cellcount) * cursize);
}
else
{
data = (cell*)malloc((sizeof(cell)* cellcount) * cursize);
}
return (data != NULL);
};
public: public:
CellVector(): data(NULL), cellcount(0), cursize(0), count(0) CellArray(size_t blocksize) : m_Data(NULL), m_BlockSize(blocksize), m_AllocSize(0), m_Size(0)
{ {
};
CellVector(int cellsize): data(NULL), cellcount(cellsize), cursize(0), count(0)
{
};
~CellVector()
{
if (data)
{
free(data);
}
};
size_t GetCellCount()
{
return cellcount;
};
void Grow(size_t howmany)
{
cursize+=howmany;
if (data)
{
data=(cell*)realloc(data, (sizeof(cell) * cellcount) * cursize);
}
else
{
data=(cell*)malloc((sizeof(cell) * cellcount) * cursize);
}
};
void FreeUnused(void)
{
if (cursize != count &&
data != NULL)
{
cursize=count;
data=(cell*)realloc(data, cursize * (sizeof(cell) * cellcount));
}
};
// Returns 1 on success
// 0 on out of bounds.
int GetArray(size_t which, cell* output)
{
// make sure it is in bounds.
if (which >= count)
{
return 0;
}
// align output data
cell* out=data + (cellcount * which);
memcpy(output, out, sizeof(cell) * cellcount);
return 1;
};
// Returns 1 on success
// 0 on out of bounds
int GetCell(size_t which, cell* output)
{
// check bounds
if (which >= count)
{
return 0;
}
*output=*(data + (cellcount * which));
return 1;
} }
// Returns 1 on success
// 0 on out of bounds ~CellArray()
int GetString(size_t which, cell* output, size_t size)
{ {
// check bounds free(m_Data);
if (which >= count)
{
return 0;
}
cell* out=data + (cellcount * which);
size_t count=cellcount;
while (size-- &&
count-- &&
(*output++=*out++)!='\0')
/* do nothing */ ;
// If size is zero here, then the string was never null terminated.
if (size==0)
{
*out='\0';
}
/* Don't truncate a multi-byte character */
if (*(output - 1) & 1 << 7)
{
size = UTIL_CheckValidChar(output - 1);
*(output - size) = '\0';
}
return 1;
} }
// Returns 1 on success
// 0 on out of bounds size_t size() const
int SetArray(size_t which, cell* output)
{ {
if (which >= count) return m_Size;
}
cell *push()
{
if (!GrowIfNeeded(1))
{ {
return 0; return NULL;
} }
// align output cell *arr = &m_Data[m_Size * m_BlockSize];
cell* out=data + (cellcount * which); m_Size++;
return arr;
}
memcpy(out, output, sizeof(cell) * cellcount); cell *at(size_t b) const
return 1;
};
// Returns 1 on success
// 0 on out of bounds
int SetCell(size_t which, cell output)
{ {
if (which >= count) return &m_Data[b * m_BlockSize];
{ }
return 0;
}
// align output
*(data + (cellcount * which))=output;
return 1; size_t blocksize() const
};
// Returns 1 on success
// 0 on out of bounds
int SetString(size_t which, cell* output)
{ {
if (which >= count) return m_BlockSize;
{ }
return 0;
}
// align output
cell* out=data + (cellcount * which);
memcpy(out, output, sizeof(cell) * cellcount); void clear()
// now force a null terminator on the last entry.
out+=(cellcount - 1);
*out='\0';
return 1;
};
int Push()
{ {
if (count >= cursize) m_Size = 0;
{ }
// Grow in 8s to cause less reallocation
this->Grow(8);
};
this->count++; bool swap(size_t item1, size_t item2)
return this->count-1;
};
int Size()
{ {
return this->count; /* Make sure there is extra space available */
}; if (!GrowIfNeeded(1))
bool Resize(size_t newsize)
{
if (newsize <= count)
{
count = newsize;
return true;
}
if (!GrowIfNeeded(newsize - count))
{ {
return false; return false;
} }
count = newsize; cell *pri = at(item1);
cell *alt = at(item2);
/* Get our temporary array 1 after the limit */
cell *temp = &m_Data[m_Size * m_BlockSize];
memcpy(temp, pri, sizeof(cell)* m_BlockSize);
memcpy(pri, alt, sizeof(cell)* m_BlockSize);
memcpy(alt, temp, sizeof(cell)* m_BlockSize);
return true; return true;
} }
CellVector *Clone() void remove(size_t index)
{ {
CellVector *array = new CellVector(cellcount); /* If we're at the end, take the easy way out */
array->count = count; if (index == m_Size - 1)
array->cursize = cursize; {
array->data = (cell *)malloc((sizeof(cell)* cellcount) * cursize); m_Size--;
memcpy(array->data, data, (sizeof(cell)* cellcount) * count); return;
return array; }
/* Otherwise, it's time to move stuff! */
size_t remaining_indexes = (m_Size - 1) - index;
cell *src = at(index + 1);
cell *dest = at(index);
memmove(dest, src, sizeof(cell)* m_BlockSize * remaining_indexes);
m_Size--;
} }
void Clear() cell *insert_at(size_t index)
{ {
free(data); /* Make sure it'll fit */
data=(cell*)malloc(sizeof(cell) * cellcount); if (!GrowIfNeeded(1))
cursize=1;
count=0;
};
cell* Base()
{
return data;
}
cell* GetCellPointer(size_t which)
{
if (which >= count)
{ {
return NULL; return NULL;
} }
return data + (which * cellcount);
}; /* move everything up */
// Shifts all items from this item, and including this item up 1. cell *src = at(index);
int ShiftUpFrom(size_t which) cell *dst = at(index + 1);
memmove(dst, src, sizeof(cell)* m_BlockSize * (m_Size - index));
m_Size++;
return src;
}
bool resize(size_t count)
{ {
// No point shifting this. if (count <= m_Size)
if (which > this->count)
{ {
m_Size = count;
return 0; return true;
}
// First make a new item.
this->Push();
// If we got an InsertAfter(lastitem), then which will equal this->count - 1
// all we needed to do was Push()
if (which == this->count ||
which == this->count - 1)
{
return 1;
} }
// Allocate a temporary buffer to store data in if (!GrowIfNeeded(count - m_Size))
size_t tempbuffsize=(sizeof(cell) * cellcount) * (this->count - 1 - which); {
return false;
}
cell* temp=(cell*)malloc(tempbuffsize); m_Size = count;
return true;
}
// Copy old data to temp buffer CellArray *clone()
memcpy(temp, GetCellPointer(which), tempbuffsize);
// Now copy temp buffer to adjusted location
memcpy(GetCellPointer(which+1), temp, tempbuffsize);
// cleanup
free(temp);
return 1;
};
// Shifts all items from this item, and including this item down 1.
// This deletes the item specified.
int Delete(size_t which)
{ {
// No point shifting this. CellArray *array = new CellArray(m_BlockSize);
if (which >= this->count) array->m_AllocSize = m_AllocSize;
{ array->m_Size = m_Size;
return 0; array->m_Data = (cell *)malloc(sizeof(cell)* m_BlockSize * m_AllocSize);
} memcpy(array->m_Data, m_Data, sizeof(cell)* m_BlockSize * m_Size);
return array;
}
cell *base()
for (size_t i=which; i<this->count - 1; i++)
{
memcpy(GetCellPointer(i), GetCellPointer(i + 1), sizeof(cell) * cellcount);
}
this->count--;
return 1;
};
int Swap(size_t item1, size_t item2)
{ {
if (item1 >= this->count || return m_Data;
item2 >= this->count) }
size_t mem_usage()
{
return m_AllocSize * m_BlockSize * sizeof(cell);
}
private:
bool GrowIfNeeded(size_t count)
{
/* Shortcut out if we can store this */
if (m_Size + count <= m_AllocSize)
{ {
return 0; return true;
} }
/* Set a base allocation size of 8 items */
// Make a temp buffer to store item2 if (!m_AllocSize)
cell* temp=(cell*)malloc(sizeof(cell) * cellcount); {
memcpy(temp, GetCellPointer(item2), sizeof(cell) * cellcount); m_AllocSize = 8;
}
// copy item1 to item2 /* If it's not enough, keep doubling */
memcpy(GetCellPointer(item2), GetCellPointer(item1), sizeof(cell) * cellcount); while (m_Size + count > m_AllocSize)
{
// copy item2 to item1 m_AllocSize *= 2;
memcpy(GetCellPointer(item1), temp, sizeof(cell) * cellcount); }
/* finally, allocate the new block */
// Cleanup if (m_Data)
free(temp); {
m_Data = (cell *)realloc(m_Data, sizeof(cell)* m_BlockSize * m_AllocSize);
return 1; }
}; else {
m_Data = (cell *)malloc(sizeof(cell)* m_BlockSize * m_AllocSize);
}
return (m_Data != NULL);
}
private:
cell *m_Data;
size_t m_BlockSize;
size_t m_AllocSize;
size_t m_Size;
}; };
extern CVector<CellVector*> VectorHolder; extern ke::Vector<CellArray*> VectorHolder;
inline CellVector* HandleToVector(AMX* amx, int handle) inline CellArray* HandleToVector(AMX* amx, int handle)
{ {
if (handle <= 0 || if (handle <= 0 || handle > (int)VectorHolder.length())
handle > (int)VectorHolder.size())
{ {
LogError(amx, AMX_ERR_NATIVE, "Invalid array handle provided (%d)", handle); LogError(amx, AMX_ERR_NATIVE, "Invalid array handle provided (%d)", handle);
return NULL; return NULL;
} }
CellVector* ret=VectorHolder[handle-1]; CellArray* ret = VectorHolder[handle - 1];
if (ret == NULL) if (ret == NULL)
{ {

View File

@ -408,7 +408,7 @@ int C_Spawn(edict_t *pent)
FlagMan.LoadFile(); FlagMan.LoadFile();
for (unsigned int i=0; i<VectorHolder.size(); i++) for (unsigned int i=0; i<VectorHolder.length(); i++)
{ {
delete VectorHolder[i]; delete VectorHolder[i];
}; };

View File

@ -403,9 +403,9 @@ int sort_adtarray_strings_desc(const void *str1, const void *str2)
return strcmp((char *) str2, (char *) str1); return strcmp((char *) str2, (char *) str1);
} }
void sort_adt_random(CellVector *cArray) void sort_adt_random(CellArray *cArray)
{ {
size_t arraysize = cArray->Size(); size_t arraysize = cArray->size();
srand((unsigned int)time(NULL)); srand((unsigned int)time(NULL));
@ -413,15 +413,15 @@ void sort_adt_random(CellVector *cArray)
{ {
int n = rand() % (i + 1); int n = rand() % (i + 1);
cArray->Swap(i, n); cArray->swap(i, n);
} }
} }
static cell AMX_NATIVE_CALL SortADTArray(AMX *amx, cell *params) static cell AMX_NATIVE_CALL SortADTArray(AMX *amx, cell *params)
{ {
CellVector* vec=HandleToVector(amx, params[1]); CellArray* vec = HandleToVector(amx, params[1]);
if (vec==NULL) if (vec == NULL)
{ {
return 0; return 0;
} }
@ -436,9 +436,9 @@ static cell AMX_NATIVE_CALL SortADTArray(AMX *amx, cell *params)
} }
cell type = params[3]; cell type = params[3];
size_t arraysize = vec->Size(); size_t arraysize = vec->size();
size_t blocksize = vec->GetCellCount(); size_t blocksize = vec->blocksize();
cell *array = vec->Base(); cell *array = vec->base();
if (type == Sort_Integer) if (type == Sort_Integer)
{ {

View File

@ -109,7 +109,11 @@ int set_amxstring(AMX *amx, cell amx_addr, const char *source, int max)
return dest - start; return dest - start;
} }
int set_amxstring_utf8(AMX *amx, cell amx_addr, const char *source, size_t sourcelen, size_t maxlen) template int set_amxstring_utf8<cell>(AMX *, cell, const cell *, size_t, size_t);
template int set_amxstring_utf8<char>(AMX *, cell, const char *, size_t, size_t);
template <typename T>
int set_amxstring_utf8(AMX *amx, cell amx_addr, const T *source, size_t sourcelen, size_t maxlen)
{ {
size_t len = sourcelen; size_t len = sourcelen;
bool needtocheck = false; bool needtocheck = false;

View File

@ -514,18 +514,25 @@ unsigned int UTIL_ReplaceAll(char *subject, size_t maxlength, const char *search
return total; return total;
} }
unsigned int strncopy(char *dest, const char *src, size_t count) template unsigned int strncopy<char, char>(char *, const char *src, size_t count);
template unsigned int strncopy<cell, char>(cell *, const char *src, size_t count);
template unsigned int strncopy<cell, cell>(cell *, const cell *src, size_t count);
template <typename D, typename S>
unsigned int strncopy(D *dest, const S *src, size_t count)
{ {
if (!count) if (!count)
{ {
return 0; return 0;
} }
char *start = dest; D *start = dest;
while ((*src) && (--count)) while ((*src) && (--count))
{ {
*dest++ = *src++; *dest++ = *(unsigned char*)src++;
} }
*dest = '\0'; *dest = '\0';
return (dest - start); return (dest - start);

View File

@ -4,10 +4,6 @@
#define _cellarray_included #define _cellarray_included
enum Array
{
Invalid_Array = 0
};
/** /**
* These arrays are intended to be used for a form of global storage without * These arrays are intended to be used for a form of global storage without
* requiring a #define that needs to be increased each time a person needs more * requiring a #define that needs to be increased each time a person needs more
@ -16,39 +12,69 @@ enum Array
* normal arrays are faster and should be used whenever possible. * normal arrays are faster and should be used whenever possible.
*/ */
enum Array
{
Invalid_Array = 0
};
/**
* Given a maximum string size (including the null terminator),
* returns the number of cells required to fit that string.
*
* @param size Number of bytes.
* @return Minimum number of cells required to fit the byte count.
*/
stock ByteCountToCells(size)
{
if (!size)
{
return 1;
}
return (size + 3) / 4;
}
/** /**
* Creates a handle to a dynamically sized array. * Creates a handle to a dynamically sized array.
* It is very important that the cellsize you provide matches up with the buffer sizes * It is very important that the cellsize you provide matches up with the buffer sizes
* that you pass with subsequent Array{Get,Set,Push} calls. * that you pass with subsequent Array{Get,Set,Push} calls.
* *
* @param cellsize How many cells each entry in the array is. * @param cellsize How many cells each entry in the array is.
* @param reserved How many blank entries are created immediately when the array is created. These entries are not valid to read from until called with ArraySet. * @param reserved How many blank entries are created immediately when the array is created.
* @return Handle to the array. * These entries are not valid to read from until called with ArraySet.
*
* @return Handle to the array.
*/ */
native Array:ArrayCreate(cellsize=1, reserved=32); native Array:ArrayCreate(cellsize = 1, reserved = 0);
/** /**
* Clones an array, returning a new handle with the same size and data. * Clones an array, returning a new handle with the same size and data.
* You must close it. * You must close it.
* *
* @param which Array handle to be cloned. * @param which Array handle to be cloned.
* @return New handle to the cloned array object on success, 0 on failure. *
* @return New handle to the cloned array object on success, 0 on failure.
* @error Invalid handle.
*/ */
native Array:ArrayClone(Array:which); native Array:ArrayClone(Array:which);
/** /**
* Clears all entries from the array. * Clears all entries from the array.
* *
* @param which The array to clear. * @param which The array to clear.
* @return 1 on success, 0 on failure. *
* @noreturn
* @error Invalid handle.
*/ */
native ArrayClear(Array:which); native ArrayClear(Array:which);
/** /**
* Returns the number of elements in the array. * Returns the number of elements in the array.
* *
* @param which The array to check. * @param which The array to check.
* @return How many elements are in the array. *
* @return How many elements are in the array.
* @error Invalid handle.
*/ */
native ArraySize(Array:which); native ArraySize(Array:which);
@ -56,9 +82,11 @@ native ArraySize(Array:which);
* Resizes an array. If the size is smaller than the current size, * Resizes an array. If the size is smaller than the current size,
* the array is truncated. * the array is truncated.
* *
* @param which Array Handle. * @param which Array handle.
* @param newsize New size. * @param newsize New size.
* @return 1 on success, 0 on failure. *
* @noreturn
* @error Invalid handle or out of memory.
*/ */
native bool:ArrayResize(Array:which, newsize); native bool:ArrayResize(Array:which, newsize);
@ -66,29 +94,41 @@ native bool:ArrayResize(Array:which, newsize);
* Returns data within an array. * Returns data within an array.
* Make sure the output buffer matches the size the array was created with! * Make sure the output buffer matches the size the array was created with!
* *
* @param which The array to retrieve the item from. * @param which The array to retrieve the item from.
* @param item The item to retrieve (zero-based). * @param item The item to retrieve (zero-based).
* @param output The output buffer to write. * @param output The output buffer to write.
* @param size If not set, assumes the buffer size is equal to the
* cellsize. Otherwise, the size passed is used.
*
* @return Number of cells copied.
* @error Invalid handle or invalid index.
*/ */
native ArrayGetArray(Array:which, item, any:output[]); native ArrayGetArray(Array:which, item, any:output[], size = -1);
/** /**
* Returns a single cell of data from an array. * Returns a single cell of data from an array.
* Use this only with arrays that were created with a cellsize of 1!
* *
* @param which The array to retrieve the item from. * @param which The array to retrieve the item from.
* @param item The item to retrieve (zero-based). * @param item The item to retrieve (zero-based).
* @return The value of the cell. * @param block Optionally specify which block to read from
* (useful if the blocksize > 0).
* @param asChar Optionally read as a byte instead of a cell.
*
* @return Value read.
* @error Invalid handle, invalid index, or invalid block.
*/ */
native any:ArrayGetCell(Array:which, item); native any:ArrayGetCell(Array:which, item, block = 0, bool:asChar = false);
/** /**
* Returns a string value from an array. * Returns a string value from an array.
* *
* @param which The array to retrieve the item from. * @param which The array to retrieve the item from.
* @param item The item to retrieve (zero-based). * @param item The item to retrieve (zero-based).
* @param output The variable to store the value in. * @param output The variable to store the value in.
* @param size Character size of the output buffer. * @param size Character size of the output buffer.
*
* @return Number of characters copied.
* @error Invalid handle or invalid index.
*/ */
native ArrayGetString(Array:which, item, output[], size); native ArrayGetString(Array:which, item, output[], size);
@ -97,30 +137,44 @@ native ArrayGetString(Array:which, item, output[], size);
* The buffer size must match what the cellsize that the array was created with! * The buffer size must match what the cellsize that the array was created with!
* The item must already exist, use ArrayPushArray to create a new item within the array. * The item must already exist, use ArrayPushArray to create a new item within the array.
* *
* @param which The array to set the item from within. * @param which The array to set the item from within.
* @param item The item to set (zero-based). * @param item The item to set (zero-based).
* @param input The input buffer to store. * @param input The input buffer to store.
* @param size If not set, assumes the buffer size is equal to the
* blocksize. Otherwise, the size passed is used.
*
* @return Number of cells copied.
* @error Invalid handle or invalid index.
*/ */
native ArraySetArray(Array:which, item, const any:input[]); native ArraySetArray(Array:which, item, const any:input[], size =-1);
/** /**
* Sets an array's single cell value. Use this only on array that were created with a cellsize of 1! * Sets an array's single cell value. Use this only on array that were created with a cellsize of 1!
* The item must already exist, use ArrayPushCell to create a new item within the array. * The item must already exist, use ArrayPushCell to create a new item within the array.
* *
* @param which The array to set the item from within. * @param which The array to set the item from within.
* @param item The item to set (zero-based). * @param item The item to set (zero-based).
* @param input The value to set. * @param input The value to set.
* @param block Optionally specify which block to write to
* (useful if the blocksize > 0).
* @param asChar Optionally set as a byte instead of a cell.
*
* @noreturn
* @error Invalid handle, invalid index, or invalid block.
*/ */
native ArraySetCell(Array:which, item, any:input); native ArraySetCell(Array:which, item, any:input, block = 0, bool:asChar = false);
/** /**
* Sets a string value from an array. * Sets a string value from an array.
* The stored string will be truncated if it is longer than the cellsize the array was created with! * The stored string will be truncated if it is longer than the cellsize the array was created with!
* The item must already exist, use ArrayPushString to create a new item within the array. * The item must already exist, use ArrayPushString to create a new item within the array.
* *
* @param which The array to set the item from within. * @param which The array to set the item from within.
* @param item The item to set (zero-based). * @param item The item to set (zero-based).
* @param input The string to set the item as. * @param input The string to set the item as.
*
* @return Number of characters copied.
* @error Invalid handle or invalid index.
*/ */
native ArraySetString(Array:which, item, const input[]); native ArraySetString(Array:which, item, const input[]);
@ -128,17 +182,26 @@ native ArraySetString(Array:which, item, const input[]);
* Creates a new item at the end of the array and sets its data with that of a local buffer. * Creates a new item at the end of the array and sets its data with that of a local buffer.
* The buffer size must match what the cellsize that the array was created with! * The buffer size must match what the cellsize that the array was created with!
* *
* @param which The array to add the item to. * @param which The array to add the item to.
* @param input The input buffer to store. * @param input The input buffer to store.
* @param size If not set, the number of elements copied from the array
* will be equal to the blocksize. If set higher than the
* blocksize, the operation will be truncated.
*
* @return Index of the new entry.
* @error Invalid handle or out of memory.
*/ */
native ArrayPushArray(Array:which, const any:input[]); native ArrayPushArray(Array:which, const any:input[], size = -1);
/** /**
* Creates a new item and sets the array's single cell value. * Creates a new item and sets the array's single cell value.
* Use this only on array that were created with a cellsize of 1! * Use this only on array that were created with a cellsize of 1!
* *
* @param which The array to add the item to. * @param which The array to add the item to.
* @param input The value to set. * @param input The value to set.
*
* @return Index of the new entry.
* @error Invalid handle or out of memory.
*/ */
native ArrayPushCell(Array:which, any:input); native ArrayPushCell(Array:which, any:input);
@ -146,8 +209,11 @@ native ArrayPushCell(Array:which, any:input);
* Creates a new element in the array and sets its value to the input buffer. * Creates a new element in the array and sets its value to the input buffer.
* The stored string will be truncated if it is longer than the cellsize the array was created with! * The stored string will be truncated if it is longer than the cellsize the array was created with!
* *
* @param which The array to add the item to. * @param which The array to add the item to.
* @param input The string to set the item as. * @param input The string to set the item as.
*
* @return Index of the new entry.
* @error Invalid handle or out of memory.
*/ */
native ArrayPushString(Array:which, const input[]); native ArrayPushString(Array:which, const input[]);
@ -155,9 +221,12 @@ native ArrayPushString(Array:which, const input[]);
* Inserts an item after the selected item. All items beyond it get shifted up 1 space. * Inserts an item after the selected item. All items beyond it get shifted up 1 space.
* The buffer size must match what the cellsize that the array was created with! * The buffer size must match what the cellsize that the array was created with!
* *
* @param which The array to add the item to. * @param which The array to add the item to.
* @param item The item to insert after. * @param item The item to insert after.
* @param input The input buffer to store. * @param input The input buffer to store.
*
* @noreturn
* @error Invalid handle or invalid index.
*/ */
native ArrayInsertArrayAfter(Array:which, item, const any:input[]); native ArrayInsertArrayAfter(Array:which, item, const any:input[]);
@ -165,9 +234,12 @@ native ArrayInsertArrayAfter(Array:which, item, const any:input[]);
* Inserts an item after the selected item. All items beyond it get shifted up 1 space. * Inserts an item after the selected item. All items beyond it get shifted up 1 space.
* Use this only on an array that was created with a cellsize of 1! * Use this only on an array that was created with a cellsize of 1!
* *
* @param which The array to add the item to. * @param which The array to add the item to.
* @param item The item to insert after. * @param item The item to insert after.
* @param input The value to set. * @param input The value to set.
*
* @noreturn
* @error Invalid handle or invalid index.
*/ */
native ArrayInsertCellAfter(Array:which, item, any:input); native ArrayInsertCellAfter(Array:which, item, any:input);
@ -175,9 +247,12 @@ native ArrayInsertCellAfter(Array:which, item, any:input);
* Inserts an item after the selected item. All items beyond it get shifted up 1 space. * Inserts an item after the selected item. All items beyond it get shifted up 1 space.
* The stored string will be truncated if it is longer than the cellsize the array was created with! * The stored string will be truncated if it is longer than the cellsize the array was created with!
* *
* @param which The array to add the item to. * @param which The array to add the item to.
* @param item The item to insert after. * @param item The item to insert after.
* @param input The value to set. * @param input The value to set.
*
* @noreturn
* @error Invalid handle or invalid index.
*/ */
native ArrayInsertStringAfter(Array:which, item, const input[]); native ArrayInsertStringAfter(Array:which, item, const input[]);
@ -185,9 +260,12 @@ native ArrayInsertStringAfter(Array:which, item, const input[]);
* Inserts an item before the selected item. All items beyond it, and the selected item get shifted up 1 space. * Inserts an item before the selected item. All items beyond it, and the selected item get shifted up 1 space.
* The buffer size must match what the cellsize that the array was created with! * The buffer size must match what the cellsize that the array was created with!
* *
* @param which The array to add the item to. * @param which The array to add the item to.
* @param item The item to insert before. * @param item The item to insert before.
* @param input The input buffer to store. * @param input The input buffer to store.
*
* @noreturn
* @error Invalid handle or invalid index.
*/ */
native ArrayInsertArrayBefore(Array:which, item, const any:input[]); native ArrayInsertArrayBefore(Array:which, item, const any:input[]);
@ -195,9 +273,12 @@ native ArrayInsertArrayBefore(Array:which, item, const any:input[]);
* Inserts an item before the selected item. All items beyond it, and the selected item get shifted up 1 space. * Inserts an item before the selected item. All items beyond it, and the selected item get shifted up 1 space.
* Use this only on an array that was created with a cellsize of 1! * Use this only on an array that was created with a cellsize of 1!
* *
* @param which The array to add the item to. * @param which The array to add the item to.
* @param item The item to insert after. * @param item The item to insert after.
* @param input The value to set. * @param input The value to set.
*
* @noreturn
* @error Invalid handle or invalid index.
*/ */
native ArrayInsertCellBefore(Array:which, item, const any:input); native ArrayInsertCellBefore(Array:which, item, const any:input);
@ -205,26 +286,35 @@ native ArrayInsertCellBefore(Array:which, item, const any:input);
* Inserts an item before the selected item. All items beyond it, and the selected item get shifted up 1 space. * Inserts an item before the selected item. All items beyond it, and the selected item get shifted up 1 space.
* The stored string will be truncated if it is longer than the cellsize the array was created with! * The stored string will be truncated if it is longer than the cellsize the array was created with!
* *
* @param which The array to add the item to. * @param which The array to add the item to.
* @param item The item to insert before. * @param item The item to insert before.
* @param input The value to set. * @param input The value to set.
*
* @noreturn
* @error Invalid handle or invalid index.
*/ */
native ArrayInsertStringBefore(Array:which, item, const input[]); native ArrayInsertStringBefore(Array:which, item, const input[]);
/** /**
* Swaps the position of two items. * Swaps the position of two items.
* *
* @param which The array that contains the items. * @param which The array that contains the items.
* @param item1 The first item to swap. * @param item1 The first item to swap.
* @param item2 The second item to swap. * @param item2 The second item to swap.
*
* @noreturn
* @error Invalid handle or invalid index.
*/ */
native ArraySwap(Array:which, item1, item2); native ArraySwap(Array:which, item1, item2);
/** /**
* Deletes an item from the array. All items beyond it get shifted down 1 space. * Deletes an item from the array. All items beyond it get shifted down 1 space.
* *
* @param which The array that contains the item to delete. * @param which The array that contains the item to delete.
* @param item The item to delete. * @param item The item to delete.
*
* @noreturn
* @error Invalid handle or invalid index.
*/ */
native ArrayDeleteItem(Array:which, item); native ArrayDeleteItem(Array:which, item);
@ -232,9 +322,11 @@ native ArrayDeleteItem(Array:which, item);
* Returns the index for the first occurance of the provided string. If the string * Returns the index for the first occurance of the provided string. If the string
* cannot be located, -1 will be returned. * cannot be located, -1 will be returned.
* *
* @param which Array Handle. * @param which Array handle.
* @param item String to search for. * @param item String to search for.
* @return Array index, or -1 on failure. *
* @return Array index, or -1 on failure.
* @error Invalid handle.
*/ */
native ArrayFindString(Array:which, const item[]); native ArrayFindString(Array:which, const item[]);
@ -242,9 +334,11 @@ native ArrayFindString(Array:which, const item[]);
* Returns the index for the first occurance of the provided value. If the value * Returns the index for the first occurance of the provided value. If the value
* cannot be located, -1 will be returned. * cannot be located, -1 will be returned.
* *
* @param which Array Handle. * @param which Array handle.
* @param item Value to search for. * @param item Value to search for.
* @return Array index, or -1 on failure. *
* @return Array index, or -1 on failure.
* @error Invalid handle.
*/ */
native ArrayFindValue(Array:which, any:item); native ArrayFindValue(Array:which, any:item);
@ -255,21 +349,25 @@ native ArrayFindValue(Array:which, any:item);
* *
* An example usage: client_print(id, print_chat, "%a", ArrayGetStringHandle(MessageArray, i)); * An example usage: client_print(id, print_chat, "%a", ArrayGetStringHandle(MessageArray, i));
* *
* @param which The array the string is stored in. * @param which The array the string is stored in.
* @param item Which item to print the string value of. * @param item Which item to print the string value of.
* @return Handle to the item directly. Do not use or save stale handles. *
* @return Handle to the item directly. Do not use or save stale handles.
* @error Invalid handle or invalid index.
*/ */
native DoNotUse:ArrayGetStringHandle(Array:which, item); native DoNotUse:ArrayGetStringHandle(Array:which, item);
/** /**
* Destroys the array, and resets the handle to 0 to prevent accidental usage after it is destroyed. * Destroys the array, and resets the handle to 0 to prevent accidental usage after it is destroyed.
* *
* @param which The array to destroy. * @param which The array to destroy.
*
* @noreturn
* @error Invalid handle.
*/ */
native ArrayDestroy(&Array:which); native ArrayDestroy(&Array:which);
/** /**
* Similar to sorting.inc's CustomSort. * Similar to sorting.inc's CustomSort.
* The sorting algorithm then uses your comparison function to sort the data. * The sorting algorithm then uses your comparison function to sort the data.
@ -277,18 +375,26 @@ native ArrayDestroy(&Array:which);
* *
* public MySortFunc(Array:array, item1, item2, const data[], data_size) * public MySortFunc(Array:array, item1, item2, const data[], data_size)
* *
* array - Array handle in its current un-sorted state. * array - Array handle in its current un-sorted state.
* item1, item2 - Current item pair being compared * item1, item2 - Current item pair being compared
* data[] - Extra data array you passed to the sort func. * data[] - Extra data array you passed to the sort func.
* data_size - Size of extra data you passed to the sort func. * data_size - Size of extra data you passed to the sort func.
* *
* Your function should return: * Your function should return:
* -1 if item1 should go before item2 * -1 if item1 should go before item2
* 0 if item1 and item2 are equal * 0 if item1 and item2 are equal
* 1 if item1 should go after item2 * 1 if item1 should go after item2
* Note that the parameters after item2 are all optional and you do not need to specify them.
* *
* Note that the parameters after item2 are all optional and you do not need to specify them.
* Note that unlike the sorting.inc versions, the array passed to the callback is not in mid-sorted state. * Note that unlike the sorting.inc versions, the array passed to the callback is not in mid-sorted state.
*
* @param array Array handle.
* @param comparefunc A callback function used for comparison.
* @param data Extra data array you passed to the sort func.
* @param data_size Size of extra data you passed to the sort func.
*
* @noreturn
* @error Invalid handle or invalid callback.
*/ */
native ArraySort(Array:array, const comparefunc[], data[]="", data_size=0); native ArraySort(Array:array, const comparefunc[], data[]="", data_size=0);
@ -306,20 +412,20 @@ native ArraySort(Array:array, const comparefunc[], data[]="", data_size=0);
* *
* public MySortFunc(Array:array, elem1, elem2, const data[], data_size) * public MySortFunc(Array:array, elem1, elem2, const data[], data_size)
* *
* array - Array handle in its current un-sorted state. * array - Array handle in its current un-sorted state.
* elem1, elem2 - Current element pair being compared * elem1, elem2 - Current element pair being compared
* data[] - Extra data array you passed to the sort func. * data[] - Extra data array you passed to the sort func.
* data_size - Size of extra data you passed to the sort func. * data_size - Size of extra data you passed to the sort func.
* *
* For Arrays with a cellsize larger than 1 (used for storing arrays and strings), * For Arrays with a cellsize larger than 1 (used for storing arrays and strings),
* the function is called in the following manner: * the function is called in the following manner:
* *
* public MySortFunc(Array:array, elem1[], elem2[], const data[], data_size) * public MySortFunc(Array:array, elem1[], elem2[], const data[], data_size)
* *
* array - Array handle in its current un-sorted state. * array - Array handle in its current un-sorted state.
* elem1[], elem2[] - Current element pair being compared * elem1[], elem2[] - Current element pair being compared
* data[] - Extra data array you passed to the sort func. * data[] - Extra data array you passed to the sort func.
* data_size - Size of extra data you passed to the sort func. * data_size - Size of extra data you passed to the sort func.
* *
* *
* In both cases your function should return: * In both cases your function should return:
@ -328,7 +434,14 @@ native ArraySort(Array:array, const comparefunc[], data[]="", data_size=0);
* 1 if elem1 should go after elem2 * 1 if elem1 should go after elem2
* *
* Note that the parameters after elem2 are all optional and you do not need to specify them. * Note that the parameters after elem2 are all optional and you do not need to specify them.
*
* Note that unlike the sorting.inc versions, the array passed to the callback is not in mid-sorted state. * Note that unlike the sorting.inc versions, the array passed to the callback is not in mid-sorted state.
*
* @param array Array handle.
* @param comparefunc A callback function used for comparison.
* @param data Extra data array you passed to the sort func.
* @param data_size Size of extra data you passed to the sort func.
*
* @noreturn
* @error Invalid handle, invalid callback or out of memory.
*/ */
native ArraySortEx(Array:array, const comparefunc[], data[]="", data_size=0); native ArraySortEx(Array:array, const comparefunc[], data[]="", data_size=0);

View File

@ -24,7 +24,7 @@ new TestWords[6][] = {
"!=" "!="
}; };
stock test(any:A,any:B=0,TestType:Type=TT_Equal) stock test(any:A, any:B = 0, TestType:Type = TT_Equal)
{ {
++__testnumber; ++__testnumber;
@ -32,31 +32,31 @@ stock test(any:A,any:B=0,TestType:Type=TT_Equal)
switch (Type) switch (Type)
{ {
case TT_Equal: if (A==B) passed=1; case TT_Equal: if (A == B) passed = 1;
case TT_LessThan: if (A<B) passed=1; case TT_LessThan: if (A < B) passed = 1;
case TT_GreaterThan: if (A>B) passed=1; case TT_GreaterThan: if (A > B) passed = 1;
case TT_LessThanEqual: if (A<=B) passed=1; case TT_LessThanEqual: if (A <= B) passed = 1;
case TT_GreaterThanEqual: if (A>=B) passed=1; case TT_GreaterThanEqual: if (A >= B) passed = 1;
case TT_NotEqual: if (A!=B) passed=1; case TT_NotEqual: if (A != B) passed =1;
} }
if (!passed) if (!passed)
{ {
log_amx("Failed test #%d (%d %s %d)",__testnumber,A,TestWords[_:Type],B); log_amx("Failed test #%d (%d %s %d)", __testnumber, A, TestWords[_:Type], B);
errcount++; errcount++;
} }
} }
stock starttests(const startfunc[]) stock starttests(const startfunc[])
{ {
__testnumber=0; __testnumber = 0;
errcount=0; errcount = 0;
__testfuncnum=1; __testfuncnum = 1;
server_print("Starting tests..."); server_print("Starting tests...");
formatex(__testfunc,sizeof(__testfunc)-1,"%s",startfunc); formatex(__testfunc, charsmax(__testfunc), "%s", startfunc);
new func[32]; new func[32];
formatex(func,sizeof(func)-1,"%s%d",__testfunc,__testfuncnum++); formatex(func, charsmax(func), "%s%d", __testfunc, __testfuncnum++);
set_task(0.1,func); set_task(0.1, func);
} }
stock showres() stock showres()
@ -64,8 +64,8 @@ stock showres()
if (errcount==0) if (errcount==0)
{ {
new func[32]; new func[32];
formatex(func,sizeof(func)-1,"%s%d",__testfunc,__testfuncnum++); formatex(func, charsmax(func), "%s%d", __testfunc, __testfuncnum++);
if (get_func_id(func)==-1) if (get_func_id(func) == -1)
{ {
server_print("All tests ok!"); server_print("All tests ok!");
} }
@ -73,7 +73,7 @@ stock showres()
{ {
server_print("Test ok, moving on..."); server_print("Test ok, moving on...");
set_task(0.1,func); set_task(0.1, func);
} }
} }
else else
@ -98,46 +98,46 @@ public arraytest1()
server_print("Testing 1000 iterations of 1-cell arrays..."); server_print("Testing 1000 iterations of 1-cell arrays...");
new Float:f; new Float:f;
new Array:a=ArrayCreate(1); new Array:a = ArrayCreate(1);
if (a == Invalid_Array) if (a == Invalid_Array)
{ {
} }
for (new i=0; i<1000; i++)
for (new i = 0; i < 1000; i++)
{ {
f=float(i); f = float(i);
ArrayPushCell(a,f); ArrayPushCell(a,f);
} }
new Float:r; new Float:r;
for (new i=0; i<1000; i++) for (new i = 0; i < 1000; i++)
{ {
f=float(i); f = float(i);
r=Float:ArrayGetCell(a, i); r = Float:ArrayGetCell(a, i);
// This is normally bad for float "casting", but in this case it should be fine. // This is normally bad for float "casting", but in this case it should be fine.
test(_:f, _:r); test(_:f, _:r);
// Reset with inversed values // Reset with inversed values
new g=_:f; new g=_:f;
g=~g; g=~g;
ArraySetCell(a, i, g); ArraySetCell(a, i, g);
r = Float:ArrayGetCell(a,i);
r=Float:ArrayGetCell(a,i);
test(g, _:r); test(g, _:r);
} }
ArrayDestroy(a); ArrayDestroy(a);
showres(); showres();
} }
stock bool:checkarray(const a[], const b[], size) stock bool:checkarray(const a[], const b[], size)
{ {
while (size--) while (size--)
{ {
if (a[size]!=b[size]) if (a[size] != b[size])
{ {
return false; return false;
} }
@ -145,6 +145,7 @@ stock bool:checkarray(const a[], const b[], size)
return true; return true;
} }
stock invarray(a[],size) stock invarray(a[],size)
{ {
while (size--) while (size--)
@ -157,68 +158,61 @@ public arraytest2()
{ {
server_print("Testing 1000 iterations of 40-cell arrays..."); server_print("Testing 1000 iterations of 40-cell arrays...");
new Array:a=ArrayCreate(40); new Array:a = ArrayCreate(40);
new buff[40]; new buff[40];
new buffb[40]; new buffb[40];
for (new i=0; i<1000; i++)
{
arrayset(buff,i,sizeof(buff));
ArrayPushArray(a, buff); for (new i = 0; i < 1000; i++)
}
for (new i=0; i<1000; i++)
{ {
arrayset(buff, i, sizeof(buff)); arrayset(buff, i, sizeof(buff));
ArrayPushArray(a, buff);
}
for (new i = 0; i < 1000; i++)
{
arrayset(buff, i, sizeof(buff));
ArrayGetArray(a, i, buffb); ArrayGetArray(a, i, buffb);
test(_:checkarray(buff, buffb, sizeof(buff)), 1);
test(_:checkarray(buff,buffb,sizeof(buff)),1);
// Now overwrite the array with inversed value // Now overwrite the array with inversed value
invarray(buff,sizeof(buff)); invarray(buff, sizeof(buff));
ArraySetArray(a, i, buff); ArraySetArray(a, i, buff);
ArrayGetArray(a, i, buffb); ArrayGetArray(a, i, buffb);
test(_:checkarray(buff, buffb, sizeof(buff)), 1);
test(_:checkarray(buff,buffb,sizeof(buff)),1);
} }
ArrayDestroy(a); ArrayDestroy(a);
showres(); showres();
} }
public arraytest3() public arraytest3()
{ {
server_print("Testing 1000 iterations of strings..."); server_print("Testing 1000 iterations of strings...");
// The string is 10 long, the string we're trying to pass is 20 long. // The string is 10 long, the string we're trying to pass is 20 long.
new Array:a = ArrayCreate(10);
new Array:a=ArrayCreate(10); new buff[20] = "1234567890abcdefghi";
new buff[20]="1234567890abcdefghi";
new buffb[20]; new buffb[20];
for (new i=0; i<1000; i++) for (new i = 0; i < 1000; i++)
{ {
ArrayPushString(a, buff); ArrayPushString(a, buff);
} }
for (new i=0; i<1000; i++)
{
ArrayGetString(a, i, buffb, sizeof(buffb)-1);
for (new i = 0; i < 1000; i++)
{
ArrayGetString(a, i, buffb, charsmax(buffb));
test(strcmp(buffb,"123456789"),0); test(strcmp(buffb,"123456789"),0);
ArraySetString(a, i, "9876543210"); ArraySetString(a, i, "9876543210");
ArrayGetString(a, i, buffb, charsmax(buffb));
ArrayGetString(a, i, buffb, sizeof(buffb)-1);
test(strcmp(buffb,"987654321"),0); test(strcmp(buffb,"987654321"),0);
buffb[0]=0; buffb[0] = EOS;
formatex(buffb, charsmax(buffb),"%a", ArrayGetStringHandle(a, i));
formatex(buffb,sizeof(buffb)-1,"%a", ArrayGetStringHandle(a, i));
test(strcmp(buffb, "987654321"),0); test(strcmp(buffb, "987654321"),0);
} }
@ -232,15 +226,17 @@ public sortcallback(Array:a, b, c)
static stra[40]; static stra[40];
static strb[40]; static strb[40];
ArrayGetString(a, b, stra, sizeof(stra)-1); ArrayGetString(a, b, stra, charsmax(stra));
ArrayGetString(a, c, strb, sizeof(strb)-1); ArrayGetString(a, c, strb, charsmax(strb));
return strcmp(stra,strb); return strcmp(stra,strb);
} }
public arraytest4() public arraytest4()
{ {
server_print("Testing sorting function..."); server_print("Testing sorting function...");
new Array:a=ArrayCreate(40); new Array:a = ArrayCreate(40);
ArrayPushString(a, "z"); ArrayPushString(a, "z");
ArrayPushString(a, "yz"); ArrayPushString(a, "yz");
@ -269,56 +265,54 @@ public arraytest4()
ArrayPushString(a, "bcdefghijklmnopqrstuvwxyz"); ArrayPushString(a, "bcdefghijklmnopqrstuvwxyz");
ArrayPushString(a, "abcdefghijklmnopqrstuvwxyz"); ArrayPushString(a, "abcdefghijklmnopqrstuvwxyz");
new OldSize=ArraySize(a); new OldSize = ArraySize(a);
ArraySort(a, "sortcallback"); ArraySort(a, "sortcallback");
test(ArraySize(a), OldSize);
test(ArraySize(a),OldSize);
new buff[40]; new buff[40];
ArrayGetString(a, 0, buff, charsmax(buff));
ArrayGetString(a,0,buff,sizeof(buff)-1);
test(strcmp(buff,"abcdefghijklmnopqrstuvwxyz"),0); test(strcmp(buff,"abcdefghijklmnopqrstuvwxyz"),0);
ArrayGetString(a,25,buff,sizeof(buff)-1); ArrayGetString(a, 25, buff, charsmax(buff));
test(strcmp(buff, "z"), 0);
test(strcmp(buff,"z"),0); new start = 'a';
for (new i = 0; i < OldSize; i++)
new start='a';
for (new i=0;i<OldSize;i++)
{ {
ArrayGetString(a,i,buff,sizeof(buff)-1) ArrayGetString(a, i, buff, charsmax(buff));
test(buff[0], start++);
test(buff[0],start++);
} }
showres(); showres();
} }
public arraytest5() public arraytest5()
{ {
server_print("Testing ArrayDeleteItem()..."); server_print("Testing ArrayDeleteItem()...");
new Array:a=ArrayCreate(1);
new Array:a = ArrayCreate(1);
new v; new v;
for (new i=0; i<1000; i++) for (new i = 0; i < 1000; i++)
{ {
ArrayPushCell(a, i); ArrayPushCell(a, i);
} }
for (new i=ArraySize(a) - 1; i>=0 ; i--)
for (new i = ArraySize(a) - 1; i >= 0; i--)
{ {
if (i % 2 == 0) if (i % 2 == 0)
{ {
ArrayDeleteItem(a, i); ArrayDeleteItem(a, i);
} }
} }
test(ArraySize(a), 500); test(ArraySize(a), 500);
for (new i=0; i< 500; i++)
for (new i = 0; i < 500; i++)
{ {
v=ArrayGetCell(a, i); v = ArrayGetCell(a, i);
// All items should be incrementing odd numbers // All items should be incrementing odd numbers
test(((i + 1) * 2) - 1, v); test(((i + 1) * 2) - 1, v);
@ -326,25 +320,30 @@ public arraytest5()
// All remaining entries should be odd // All remaining entries should be odd
test((v & 1), 1); test((v & 1), 1);
} }
ArrayDestroy(a); ArrayDestroy(a);
a=ArrayCreate(1); a = ArrayCreate(1);
// Repeat the same test, but check even numbers // Repeat the same test, but check even numbers
for (new i=0; i<1000; i++) for (new i = 0; i < 1000; i++)
{ {
ArrayPushCell(a, i); ArrayPushCell(a, i);
} }
for (new i=ArraySize(a) - 1; i>=0 ; i--)
for (new i = ArraySize(a) - 1; i >= 0 ; i--)
{ {
if (i % 2 == 1) if (i % 2 == 1)
{ {
ArrayDeleteItem(a, i); ArrayDeleteItem(a, i);
} }
} }
test(ArraySize(a), 500); test(ArraySize(a), 500);
for (new i=0; i< 500; i++)
for (new i = 0; i < 500; i++)
{ {
v=ArrayGetCell(a, i); v = ArrayGetCell(a, i);
// All items should be incrementing even numbers // All items should be incrementing even numbers
test(((i + 1) * 2) - 2, v); test(((i + 1) * 2) - 2, v);
@ -352,21 +351,24 @@ public arraytest5()
// All remaining entries should be even // All remaining entries should be even
test((v & 1), 0); test((v & 1), 0);
} }
ArrayDestroy(a); ArrayDestroy(a);
showres(); showres();
} }
public arraytest6() public arraytest6()
{ {
server_print("Testing ArrayInsertCellAfter()..."); server_print("Testing ArrayInsertCellAfter()...");
new Array:a=ArrayCreate(1); new Array:a = ArrayCreate(1);
for (new i=0; i<10;i++) for (new i = 0; i < 10;i++)
{ {
ArrayPushCell(a, i); ArrayPushCell(a, i);
new item=ArraySize(a)-1; new item = ArraySize(a) - 1;
for (new j=0; j<10; j++)
for (new j = 0; j < 10; j++)
{ {
ArrayInsertCellAfter(a, item + j, j); ArrayInsertCellAfter(a, item + j, j);
} }
@ -375,34 +377,73 @@ public arraytest6()
test(ArraySize(a), 110); test(ArraySize(a), 110);
new v; new v;
for (new i=0; i<110; i++) for (new i = 0; i < 110; i++)
{ {
v=ArrayGetCell(a, i); v = ArrayGetCell(a, i);
test(v, i / 10); test(v, i / 10);
for (new j=0; j<10; j++)
for (new j = 0; j < 10; j++)
{ {
v=ArrayGetCell(a, ++i); v = ArrayGetCell(a, ++i);
test(v, j); test(v, j);
} }
} }
ArrayDestroy(a); ArrayDestroy(a);
showres(); showres();
} }
public arraytest7() public arraytest7()
{
server_print("Testing ArrayInsertStringAfter()...");
new Array:a = ArrayCreate(4);
new buffer[4];
for (new i = 0; i < 10;i++)
{
formatex(buffer, charsmax(buffer), "%d", i);
ArrayPushString(a, buffer);
new item = ArraySize(a) - 1;
for (new j = 0; j < 10; j++)
{
formatex(buffer, charsmax(buffer), "%d", j);
ArrayInsertStringAfter(a, item + j, buffer);
}
}
test(ArraySize(a), 110);
for (new i = 0; i < 110; i++)
{
ArrayGetString(a, i, buffer, charsmax(buffer));
test(str_to_num(buffer), i / 10);
for (new j = 0; j < 10; j++)
{
ArrayGetString(a, ++i, buffer, charsmax(buffer));
test(str_to_num(buffer), j);
}
}
ArrayDestroy(a);
showres();
}
public arraytest8()
{ {
server_print("Testing ArrayInsertCellBefore()..."); server_print("Testing ArrayInsertCellBefore()...");
new Array:a=ArrayCreate(1); new Array:a = ArrayCreate(1);
for (new i=0; i<10;i++) for (new i = 0; i < 10; i++)
{ {
ArrayPushCell(a, i); new item = ArrayPushCell(a, i);
new item=ArraySize(a)-1;
for (new j=0; j<10; j++) for (new j = 0; j < 10; j++)
{ {
ArrayInsertCellBefore(a, item, j); ArrayInsertCellBefore(a, item, j);
} }
@ -410,42 +451,79 @@ public arraytest7()
test(ArraySize(a), 110); test(ArraySize(a), 110);
new v; for (new i = 0; i < 110; i++)
for (new i=0; i<110; i++)
{ {
for (new j=9; j>=0; j--) for (new j = 9; j >= 0; j--)
{ {
v=ArrayGetCell(a, i++); test(ArrayGetCell(a, i++), j);
test(v, j);
} }
v=ArrayGetCell(a, i); test(ArrayGetCell(a, i), (i - 10) / 10);
test(v, (i - 10) / 10);
} }
ArrayDestroy(a); ArrayDestroy(a);
showres(); showres();
} }
public arraytest8()
public arraytest9()
{
server_print("Testing ArrayInsertStringBefore()...");
new buffer[4];
new Array:a = ArrayCreate(4);
for (new i = 0; i < 10; i++)
{
formatex(buffer, charsmax(buffer), "%d", i);
new item = ArrayPushString(a, buffer);
for (new j = 0; j < 10; j++)
{
formatex(buffer, charsmax(buffer), "%d", j);
ArrayInsertStringBefore(a, item, buffer);
}
}
test(ArraySize(a), 110);
for (new i = 0; i < 110; i++)
{
for (new j = 9; j >= 0; j--)
{
ArrayGetString(a, i++, buffer, charsmax(buffer));
test(str_to_num(buffer), j);
}
ArrayGetString(a, i, buffer, charsmax(buffer));
test(str_to_num(buffer), (i - 10) / 10);
}
ArrayDestroy(a);
showres();
}
public arraytest10()
{ {
server_print("Testing ArraySwap()..."); server_print("Testing ArraySwap()...");
new Array:a=ArrayCreate(1);
for (new i=0; i<10; i++) new Array:a = ArrayCreate(1);
for (new i = 0; i < 10; i++)
{ {
ArrayPushCell(a, i); ArrayPushCell(a, i);
} }
for (new i=0; i<5; i++)
for (new i = 0; i < 5; i++)
{ {
ArraySwap(a, i, (10 - (i + 1))); ArraySwap(a, i, (10 - (i + 1)));
} }
new v; new v;
for (new i=0; i<5; i++) for (new i = 0; i < 5; i++)
{ {
v=ArrayGetCell(a, i); v = ArrayGetCell(a, i);
test(v, (10 - (i + 1))); test(v, (10 - (i + 1)));
} }
@ -455,15 +533,16 @@ public arraytest8()
showres(); showres();
} }
public sortcallbackex_string(Array:a, const b[], const c[], d) public Sortcallbackex_string(Array:a, const b[], const c[], d)
{ {
return strcmp(b,c); return strcmp(b, c);
} }
public arraytest9()
public arraytest11()
{ {
server_print("Testing (new) sorting function with string..."); server_print("Testing (new) sorting function with string...");
new Array:a=ArrayCreate(40); new Array:a = ArrayCreate(40);
ArrayPushString(a, "z"); ArrayPushString(a, "z");
ArrayPushString(a, "yz"); ArrayPushString(a, "yz");
@ -492,30 +571,24 @@ public arraytest9()
ArrayPushString(a, "bcdefghijklmnopqrstuvwxyz"); ArrayPushString(a, "bcdefghijklmnopqrstuvwxyz");
ArrayPushString(a, "abcdefghijklmnopqrstuvwxyz"); ArrayPushString(a, "abcdefghijklmnopqrstuvwxyz");
new OldSize=ArraySize(a); new OldSize = ArraySize(a);
ArraySortEx(a, "sortcallbackex_string"); ArraySortEx(a, "Sortcallbackex_string");
test(ArraySize(a), OldSize);
test(ArraySize(a),OldSize);
new buff[40]; new buff[40];
ArrayGetString(a, 0, buff, charsmax(buff));
test(strcmp(buff, "abcdefghijklmnopqrstuvwxyz"), 0);
ArrayGetString(a,0,buff,sizeof(buff)-1); ArrayGetString(a, 25, buff, charsmax(buff));
test(strcmp(buff, "z"),0);
test(strcmp(buff,"abcdefghijklmnopqrstuvwxyz"),0); new start = 'a';
ArrayGetString(a,25,buff,sizeof(buff)-1); for (new i = 0; i < OldSize; i++)
test(strcmp(buff,"z"),0);
new start='a';
for (new i=0;i<OldSize;i++)
{ {
ArrayGetString(a,i,buff,sizeof(buff)-1) ArrayGetString(a, i, buff, charsmax(buff))
test(buff[0], start++);
test(buff[0],start++);
} }
ArrayDestroy(a); ArrayDestroy(a);
@ -523,15 +596,17 @@ public arraytest9()
showres(); showres();
} }
public sortcallbackex_int(Array:a, const b, const c, d)
public Sortcallbackex_int(Array:a, const b, const c, d)
{ {
return b < c ? -1 : 1; return b < c ? -1 : 1;
} }
public arraytest10()
public arraytest12()
{ {
server_print("Testing (new) sorting function with integer..."); server_print("Testing (new) sorting function with integer...");
new Array:a=ArrayCreate(1); new Array:a = ArrayCreate(1);
ArrayPushCell(a, 8); ArrayPushCell(a, 8);
ArrayPushCell(a, 1); ArrayPushCell(a, 1);
@ -544,17 +619,17 @@ public arraytest10()
ArrayPushCell(a, 10); ArrayPushCell(a, 10);
ArrayPushCell(a, 6); ArrayPushCell(a, 6);
new OldSize=ArraySize(a); new OldSize = ArraySize(a);
ArraySortEx(a, "sortcallbackex_int"); ArraySortEx(a, "Sortcallbackex_int");
test(ArraySize(a),OldSize); test(ArraySize(a), OldSize);
test(ArrayGetCell(a, 0),1); test(ArrayGetCell(a, 0), 1);
test(ArrayGetCell(a, 9),10); test(ArrayGetCell(a, 9), 10);
for (new i=0;i<OldSize;i++) for (new i = 0; i < OldSize; i++)
{ {
test(ArrayGetCell(a, i),i+1); test(ArrayGetCell(a, i), i+1);
} }
ArrayDestroy(a); ArrayDestroy(a);
@ -562,7 +637,7 @@ public arraytest10()
showres(); showres();
} }
public arraytest11() public arraytest13()
{ {
server_print("Testing cloning function..."); server_print("Testing cloning function...");
@ -595,7 +670,7 @@ public arraytest11()
showres(); showres();
} }
public arraytest12() public arraytest14()
{ {
server_print("Testing resizing function..."); server_print("Testing resizing function...");
@ -619,7 +694,7 @@ public arraytest12()
showres(); showres();
} }
public arraytest13() public arraytest15()
{ {
server_print("Testing finding string in array..."); server_print("Testing finding string in array...");
@ -645,7 +720,7 @@ public arraytest13()
showres(); showres();
} }
public arraytest14() public arraytest16()
{ {
server_print("Testing finding value in array..."); server_print("Testing finding value in array...");