Commit f883da31 authored by Matthew Burket's avatar Matthew Burket

Work on buffer

parent 995481ba
......@@ -3,3 +3,50 @@
//
#include "buffer.h"
#include "string.h"
void initBuffer(GrowthBuffer *arr, size_t initSize) {
arr->array = (char *) malloc(sizeof(char) * initSize);
arr->total_size = initSize;
arr->used = 0;
}
void appendBuffer(GrowthBuffer *arr, char *value, int length) {
int dLength = length + 1;
if (!hasSpaceBuffer(arr, dLength)) {
int growthFactor = arr->total_size;
if (growthFactor < dLength) {
growthFactor = dLength;
}
int arrNewSize = growthFactor * 2;
char *newArr = realloc(arr->array, dLength * sizeof(char));
arr->array = newArr;
arr->total_size = arrNewSize;
}
int buffPos;
int copiedBytesCount;
for (int i = 0; i < length; i++) {
if (value[i] == NULL) {
break;
}
buffPos = arr->used + i;
*(arr->array + buffPos) = value[i];
copiedBytesCount++;
}
arr->used += copiedBytesCount;
}
void freeBuffer(GrowthBuffer *arr) {
free(arr->array);
arr->array = NULL;
arr->used = arr->total_size = 0;
}
int hasSpaceBuffer(GrowthBuffer *arr, int length) {
size_t unused = arr->total_size - arr->used;
return length <= unused;
}
\ No newline at end of file
......@@ -5,4 +5,18 @@
#ifndef COMS352_PROJECT2_PART1_BUFFER_H
#define COMS352_PROJECT2_PART1_BUFFER_H
#include "stdlib.h"
typedef struct {
char *array;
size_t used;
size_t total_size;
} GrowthBuffer;
void initBuffer(GrowthBuffer *arr, size_t initSize);
void appendBuffer(GrowthBuffer *arr, char *value, int length);
void freeBuffer(GrowthBuffer *arr);
int hasSpaceBuffer(GrowthBuffer *arr, int length);
#endif //COMS352_PROJECT2_PART1_BUFFER_H
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment