Skip to content

Instantly share code, notes, and snippets.

@pervognsen
Last active January 22, 2019 17:06
Show Gist options
  • Save pervognsen/49566974abd96f99e72f1a873cad3b17 to your computer and use it in GitHub Desktop.
Save pervognsen/49566974abd96f99e72f1a873cad3b17 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <windows.h>
typedef struct {
char *start;
char *current;
char *end;
} buf_t;
enum { MAX_BUFS = 16 };
buf_t bufs[MAX_BUFS];
buf_t *buf = bufs;
char c;
void push(char *start, char *end) {
assert(buf != bufs + MAX_BUFS);
buf++;
buf->start = start;
buf->current = start;
buf->end = end;
c = *buf->current;
}
void next() {
while (buf->current == buf->end) {
assert(buf != bufs);
--buf;
}
buf->current++;
c = *buf->current;
}
enum { LOOKAHEAD = 7 };
void splice(char *start, char *end) {
size_t tail_length = end - start >= LOOKAHEAD? LOOKAHEAD : end - start;
char *tail_start = end - tail_length;
char *tail_buffer = (char *)malloc(tail_length + LOOKAHEAD);
memcpy(tail_buffer, tail_start, tail_length);
memcpy(tail_buffer + tail_length, buf->current, LOOKAHEAD);
push(tail_buffer, tail_buffer + tail_length);
if (start != tail_start)
push(start, tail_start);
}
int main(int argc, char **argv) {
char eof[LOOKAHEAD] = {0};
push(eof, eof + LOOKAHEAD);
char *text0 = "before #include1ude2 after#";
char *text1 = "world << #incl";
char *text2 = "and again#";
enum { NUM_TEXTS = 3 };
char *texts[NUM_TEXTS][2] = {
{text0, text0 + strlen(text0)},
{text1, text1 + strlen(text1)},
{text2, text2 + strlen(text2)}
};
splice(texts[0][0], texts[0][1]);
while (c) {
if (c == '#') {
next();
if (strncmp(buf->current, "include", 7) == 0) {
for (int n = 0; n < 7; n++)
next();
int i = c - '0';
next();
if (0 <= i && i < NUM_TEXTS)
splice(texts[i][0], texts[i][1]);
}
} else {
printf("%c", c);
next();
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment