luxos/Kernel/library/array/dynamic_arr.c
Tiberiu Chibici 852cf1bb17 [GOOD] BUILD 0.1.0.590 DATE 9/05/2011 AT 2:40 PM
====================================================
Mainly changed: FS.Initrd
+ (kind of) refractored VFS, bugfixed
+ Rewrote 'initrd' file system, fixed many problems
+ Working 'cat' and 'dir' console commands
+ Wrote 'initrd' image write application (for windows), however it may
be bugged
2021-09-14 18:52:47 +03:00

104 lines
2.2 KiB
C

/*
* 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;
}