Skip to content

Instantly share code, notes, and snippets.

@bluebrown
Created June 14, 2024 11:45
Show Gist options
  • Save bluebrown/6193003927f5d6f380727dc1265811be to your computer and use it in GitHub Desktop.
Save bluebrown/6193003927f5d6f380727dc1265811be to your computer and use it in GitHub Desktop.
#include <stdio.h>
typedef void Write(void *, char);
struct Writer {
enum { WRITER_ANY, WRITER_BUFFER } type;
void *impl;
Write *write;
};
void fprint(struct Writer *w, const char *s) {
while (*s)
w->write(w->impl, *s++);
}
struct SomeFile {
FILE *f;
};
void SomeFile_write(struct SomeFile *w, char c) { fputc(c, w->f); }
struct Buffer {
char *data;
size_t cap;
size_t pos;
};
void Buffer_write(struct Buffer *b, char c) {
if (b->pos < b->cap)
b->data[b->pos++] = c;
}
int main() {
struct Writer stdw = (struct Writer){
.impl = &(struct SomeFile){stdout},
.write = (Write *)SomeFile_write,
};
fprintf(stdout, "stdw tag: %d\n", stdw.type);
struct Writer bufw = (struct Writer){
.type = WRITER_BUFFER,
.impl = &(struct Buffer){.data = (char[1024]){}, .cap = 1024},
.write = (Write *)Buffer_write,
};
fprint(&stdw, "console meat\n");
fprint(&bufw, "buffered beefalo\n");
if (bufw.type == WRITER_BUFFER)
fprint(&stdw, ((struct Buffer *)bufw.impl)->data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment