9. Buffer Management
All content must be written to in-memory location.
This is handled in a very simple way via a buffer type
called wws_buffer
.
typedef struct wws_buffer wws_buffer;
A wws_buffer
struct contains the buffer itself (an
unsigned char array), the current position of the buffer
(which is therefore the current size), and the
total size.
struct wws_buffer {
int pos;
int size;
unsigned char *buf;
};
The wws_buffer
is allocated with the function
wws_buffer_alloc
. Choose a largish size because this
is the maximum HTML size for a page. Re-allocation could
come later, but for this proof-of concept, a fixed
size is simple and good enough.
void wws_buffer_alloc(wws_buffer *wb, int size);
void wws_buffer_alloc(wws_buffer *wb, int size)
{
wb->buf = calloc(1, size);
wb->pos = 0;
wb->size = size;
}
A allocated buffer must be freed with wws_buffer_free
.
void wws_buffer_free(wws_buffer *wb);
void wws_buffer_free(wws_buffer *wb)
{
wb->size = 0;
wb->pos = 0;
free(wb->buf);
}
Write to the buffer using wws_buffer_write
.
void wws_buffer_write(wws_buffer *wb,
const char *buf,
int size);
This copies over a chunk of data to the internal buffer. If the buffer is full, it just stops adding and breaks away.
void wws_buffer_write(wws_buffer *wb,
const char *buf,
int size)
{
int i;
if (wb->pos >= wb->size) {
wws_buffer_extend(wb, 512);
}
for (i = 0; i < size; i++) {
wb->buf[wb->pos] = buf[i];
wb->pos++;
if (wb->pos >= wb->size) {
wws_buffer_extend(wb, 512);
}
}
}
Extending a buffer is done via wws_buffer_extend
. This is
done automatically inside of wws_buffer_write
.
void wws_buffer_extend(wws_buffer *wb, int amount);
void wws_buffer_extend(wws_buffer *wb, int amount)
{
wb->size += amount;
wb->buf = realloc(wb->buf, wb->size);
}
prev | home | next