DynamicByteArray.c 1.7 KB
Newer Older
T
tickduan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/**
 *  @file DynamicByteArray.c
 *  @author Sheng Di
 *  @date May, 2016
 *  @brief Dynamic Byte Array
 *  (C) 2015 by Mathematics and Computer Science (MCS), Argonne National Laboratory.
 *      See COPYRIGHT in top-level directory.
 */

#include <stdlib.h> 
#include <stdio.h>
#include <string.h>
#include "DynamicByteArray.h"
T
tickduan 已提交
14
#include "sz.h"
T
tickduan 已提交
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

void new_DBA(DynamicByteArray **dba, size_t cap) {
		*dba = (DynamicByteArray *)malloc(sizeof(DynamicByteArray));
        (*dba)->size = 0;
        (*dba)->capacity = cap;
        (*dba)->array = (unsigned char*)malloc(sizeof(unsigned char)*cap);
    }

void convertDBAtoBytes(DynamicByteArray *dba, unsigned char** bytes)
{
	size_t size = dba->size;
	if(size>0)
		*bytes = (unsigned char*)malloc(size * sizeof(unsigned char));
	else
		*bytes = NULL;
	memcpy(*bytes, dba->array, size*sizeof(unsigned char));	
}

void free_DBA(DynamicByteArray *dba)
{
	free(dba->array);
	free(dba);
}

T
tickduan 已提交
39
INLINE unsigned char getDBA_Data(DynamicByteArray *dba, size_t pos)
T
tickduan 已提交
40 41 42 43 44 45 46 47 48
{
	if(pos>=dba->size)
	{
		printf("Error: wrong position of DBA (impossible case unless bugs elsewhere in the code?).\n");
		exit(0);
	}
	return dba->array[pos];
}

T
tickduan 已提交
49
INLINE void addDBA_Data(DynamicByteArray *dba, unsigned char value)
T
tickduan 已提交
50 51 52 53 54 55 56 57 58 59
{
	if(dba->size==dba->capacity)
	{
		dba->capacity = dba->capacity << 1;
		dba->array = (unsigned char *)realloc(dba->array, dba->capacity*sizeof(unsigned char));
	}
	dba->array[dba->size] = value;
	dba->size ++;
}

T
tickduan 已提交
60
INLINE void memcpyDBA_Data(DynamicByteArray *dba, unsigned char* data, size_t length)
T
tickduan 已提交
61 62 63 64 65 66 67 68 69
{
	if(dba->size + length > dba->capacity)
	{
		dba->capacity = dba->size + length;
		dba->array = (unsigned char *)realloc(dba->array, dba->capacity*sizeof(unsigned char));
	}
	memcpy(&(dba->array[dba->size]), data, length);
	dba->size += length;
}