Skip to content

Instantly share code, notes, and snippets.

@ceberly
Created July 10, 2022 17:03
Show Gist options
  • Save ceberly/d3d68bcea9bfecdb6b2ca59e64fcc101 to your computer and use it in GitHub Desktop.
Save ceberly/d3d68bcea9bfecdb6b2ca59e64fcc101 to your computer and use it in GitHub Desktop.
Generic db impl, in C
#include <stdlib.h>
#include <stdio.h>
// db.h
typedef struct DB {
void *private;
const char *(*get)(struct DB*);
} DB;
// test_db_impl.c
typedef struct {
const char *tmpfile;
} TestDBImpl;
void test_db_init(TestDBImpl *t) {
t->tmpfile = "antempfile.db";
}
const char *test_db_get(DB *db) {
TestDBImpl *t = (TestDBImpl *)db->private;
return t->tmpfile;
}
// s3_db_impl.c
typedef struct {
const char *addr;
} S3DBImpl;
void s3_db_init(S3DBImpl *s) {
s->addr = "localhost:3000";
}
const char *s3_db_get(DB *db) {
S3DBImpl *s = (S3DBImpl *)db->private;
return s->addr;
}
// db.c
const char *do_something_with_db(DB *db) {
return db->get(db);
}
// main
int main(void) {
TestDBImpl test_db_impl;
test_db_init(&test_db_impl);
S3DBImpl s3_db_impl;
s3_db_init(&s3_db_impl);
DB test_db; test_db.get = test_db_get;
test_db.private = &test_db_impl;
DB s3_db;
s3_db.get = s3_db_get;
s3_db.private = &s3_db_impl;
printf("test_db: %s\n", do_something_with_db(&test_db));
printf("s3_db: %s\n", do_something_with_db(&s3_db));
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment