Skip to content

Commit

Permalink
Add rudimentary register implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
martanne committed Aug 31, 2014
1 parent 5f113ae commit 0ce017c
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
62 changes: 62 additions & 0 deletions register.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#include <stdlib.h>
#include <string.h>

#include "register.h"
#include "util.h"

#define REG_SIZE 1024

struct Register {
char *data;
size_t len;
size_t size;
};

bool register_alloc(Register *reg, size_t size) {
if (size < REG_SIZE)
size = REG_SIZE;
if (reg->size < size) {
reg->data = realloc(reg->data, size);
if (!reg->data) {
reg->size = 0;
reg->len = 0;
return false;
}
reg->size = size;
}
return true;
}

void register_free(Register *reg) {
if (!reg)
return;
free(reg->data);
reg->data = NULL;
reg->len = 0;
reg->size = 0;
}

bool register_store(Register *reg, const char *data, size_t len) {
if (!register_alloc(reg, len))
return false;
memcpy(reg->data, data, len);
reg->len = len;
return true;
}

bool register_put(Register *reg, Text *txt, Filerange *range) {
size_t len = range->end - range->start;
if (!register_alloc(reg, len))
return false;
reg->len = text_bytes_get(txt, range->start, len, reg->data);
return true;
}

bool register_append(Register *reg, Text *txt, Filerange *range) {
size_t rem = reg->size - reg->len;
size_t len = range->end - range->start;
if (len > rem && !register_alloc(reg, reg->size + len - rem))
return false;
reg->len += text_bytes_get(txt, range->start, len, reg->data + reg->len);
return true;
}
16 changes: 16 additions & 0 deletions register.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#ifndef REGISTER_H
#define REGISTER_H

#include <stddef.h>
#include <stdbool.h>
#include "text.h"

typedef struct Register Register;

bool register_alloc(Register *reg, size_t size);
void register_free(Register *reg);
bool register_store(Register *reg, const char *data, size_t len);
bool register_put(Register *reg, Text *txt, Filerange *range);
bool register_append(Register *reg, Text *txt, Filerange *range);

#endif

0 comments on commit 0ce017c

Please sign in to comment.