123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- #include "Stream.h"
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- 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;
- }
|