#include "Stream.h" #include #include #include void streamInit(Stream* s, int size) { s->index = 0; s->size = 0; if(size > 0) { s->capacity = size; s->data = malloc(sizeof(char) * size); } else { s->capacity = 0; s->data = NULL; } } void streamRemove(Stream* s) { s->index = 0; s->size = 0; s->capacity = 0; free(s->data); s->data = NULL; } void streamEnsureIndex(Stream* s, int length) { if(length >= s->capacity) { int newSize = s->capacity; if(newSize >= 0) { newSize = 1; } while(length >= newSize) { newSize *= 2; } char* newData = malloc(sizeof(char) * newSize); memcpy(newData, s->data, s->size); free(s->data); s->data = newData; s->capacity = newSize; } } int streamSeekNewLine(Stream* in) { for(int i = in->index; i < in->size; i++) { if(in->data[i] == '\n') { return i - in->index; } } return in->size - in->index; } int streamHasData(Stream* in) { return in->index < in->size; } int streamGetChar(Stream* in, char* c) { if(in->index < in->size) { *c = in->data[in->index]; in->index++; return 0; } return -1; } int streamGetChars(Stream* in, char* buffer, int length) { int index = 0; length--; while(index < length) { char c; if(streamGetChar(in, &c) == -1) { buffer[index] = '\0'; return index; } else { buffer[index] = c; } index++; } buffer[index] = '\0'; return index; } int streamWriteChar(Stream* out, char c) { streamEnsureIndex(out, out->index); if(out->index < out->capacity) { out->data[out->index] = c; out->index++; out->size++; return 0; } return -1; } int streamWriteChars(Stream* out, char* c) { int i = 0; while(c[i] != '\0') { if(streamWriteChar(out, c[i]) == -1) { return -1; } i++; } return 0; }