luxos/Kernel/library/array/dynamic_arr.c

104 lines
2.2 KiB
C
Raw Normal View History

/*
* dynamic-arr.c
*
* Created on: Sep 3, 2011
* Author: Tiberiu
*/
#include <stdlib.h>
#include <memory.h>
#include <array.h>
void DynamicArrayCreate (uint32 ElemSize, DynamicArray* arr)
{
// Create a simple array. Allocate 16 elems for start
arr->ElemSize = ElemSize;
arr->Size = 0;
arr->Allocated = 0x10;
arr->Data = kmalloc(0x10 * ElemSize);
}
void DynamicArrayPush (void* item, DynamicArray* arr)
{
// Make sure we have enough space
if (arr->Allocated <= arr->Size)
{
arr->Allocated += 0x10;
arr->Data = kmrealloc(arr->Data, arr->Allocated * arr->ElemSize);
}
// Calculate the address of next item
uint32 addr = (uint32)arr->Data + arr->Size * arr->ElemSize;
// Copy data
memcpy((void*)addr, item, arr->ElemSize);
++arr->Size;
}
void DynamicArrayPop (DynamicArray* arr)
{
// Decrease size
--arr->Size;
}
void DynamicArrayInsert (void* item, uint32 index, DynamicArray* arr)
{
// Make sure we have enough space
if (arr->Allocated <= arr->Size)
{
arr->Allocated += 0x10;
arr->Data = kmrealloc(arr->Data, arr->Allocated * arr->ElemSize);
}
// Move the data out of the way
uint8* buffer = (uint8*) arr->Data;
uint32 start = index * arr->ElemSize;
uint32 end = arr->Size * arr->ElemSize;
for (--end; end >= start; end--)
buffer[end + arr->ElemSize] = buffer[end];
// Insert item
memcpy((void*)((uint32)arr->Data + start), item, arr->ElemSize);
++ arr->Size;
}
void DynamicArrayRemove (uint32 index, DynamicArray* arr)
{
uint8* buffer = (uint8*) arr->Data;
uint32 start = index * arr->ElemSize;
uint32 end = (arr->Size-1) * arr->ElemSize;
for (; start < end; start++)
buffer[start] = buffer[start + arr->ElemSize];
-- arr->Size;
}
void DynamicArraySwap (uint32 a, uint32 b, DynamicArray* arr)
{
uint8 temp, *buffer = (uint8*) arr->Data;
uint32 addra = a * arr->ElemSize;
uint32 addrb = b * arr->ElemSize;
uint32 i;
for (i = 0; i < arr->ElemSize; i++)
{
// Swap byte i from elem A with byte i from elem B
temp = buffer[addra + i];
buffer[addra + i] = buffer[addrb + i];
buffer[addrb + i] = temp;
}
}
void DynamicArrayDispose (DynamicArray* arr)
{
// Free used data
kfree(arr->Data);
// Set everything to 0 so we don't attempt to add more items and stuff
arr->Allocated = 0;
arr->Size = 0;
arr->ElemSize = 0;
}