Skip to content

Instantly share code, notes, and snippets.

@reagent
Last active December 11, 2015 03:58
Show Gist options
  • Save reagent/4541574 to your computer and use it in GitHub Desktop.
Save reagent/4541574 to your computer and use it in GitHub Desktop.
Simple buffer library
#include "buffer.h"
Buffer *
buffer_alloc(int initial_size)
{
Buffer *buf = malloc(sizeof(Buffer));
buf->contents = calloc(1, initial_size * sizeof(char));
buf->bytes_used = 0;
buf->total_size = initial_size;
return buf;
}
void
buffer_free(Buffer *buf)
{
free(buf->contents);
free(buf);
}
int
buffer_has_space(Buffer *buf, int desired_length)
{
return desired_length <= (buf->total_size - buf->bytes_used - 1);
}
int
buffer_grow(Buffer *buf, int minimum_size)
{
int min_allocation = minimum_size + 1; // Need to hold NUL
int new_size = (buf->total_size * 2);
if (new_size < min_allocation) {
new_size = min_allocation;
}
char *tmp = realloc(buf->contents, new_size * sizeof(char));
if (tmp == NULL) { return -1; }
buf->contents = tmp;
buf->total_size = new_size;
return 0;
}
void
buffer_cat(Buffer *buf, char *append, int length)
{
int i = 0;
int bytes_copied = 0;
int buffer_position = 0;
for (i = 0; i < length; i++) {
if (append[i] == '\0') { break; }
buffer_position = buf->bytes_used + i;
*(buf->contents + buffer_position) = append[i];
bytes_copied++;
}
buf->bytes_used += bytes_copied;
*(buf->contents + buf->bytes_used) = '\0';
}
int
buffer_append(Buffer *buf, char *append, int length)
{
int status = 0;
if (!buffer_has_space(buf, length)) {
status = buffer_grow(buf, length);
if (status == -1) { return -1; }
}
buffer_cat(buf, append, length);
return 0;
}
#ifndef BUFFER_H
#define BUFFER_H
#include <stdlib.h>
#include <strings.h>
struct Buffer {
char *contents;
int bytes_used;
int total_size;
};
typedef struct Buffer Buffer;
Buffer * buffer_alloc(int initial_size);
void buffer_free(Buffer *str);
int buffer_append(Buffer *str, char *append, int length);
#endif
#include <stdlib.h>
#include <stdio.h>
#include "buffer.h"
void
print_chars(Buffer *buf)
{
int i = 0;
char ch;
for(i = 0; i < buf->total_size; i++) {
printf("%d", (i + 1) % 10);
}
printf("\n");
for(i = 0; i < buf->total_size; i++) {
ch = *(buf->contents + i);
if (ch == '\0') {
printf("N");
} else {
printf("%c", ch);
}
}
printf("\n");
}
int
main(int argc, const char *argv[])
{
int i = 0;
Buffer *buf = buffer_alloc(8);
char *content = "123456";
for (i = 0; i < 20; i++) {
buffer_append(buf, content, 6);
printf("`buf`: %s\n", buf->contents);
}
buffer_free(buf);
return 0;
}
CFLAGS=-Wall -g
all: main
main: main.o buffer.o
clean:
rm -rf main *.o *.dSYM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment