Created
October 29, 2020 01:27
-
-
Save nathanPro/3faca08d8fa2732059456c0eed60b973 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <assert.h> | |
#include <stdlib.h> | |
// Define generic interface for types | |
struct type_def { | |
void (*print)(void *); | |
int (*cmp)(void *, void *); | |
}; | |
struct item { | |
struct type_def* type; | |
void* data; | |
}; | |
void print_item(struct item a) { | |
a.type->print(a.data); | |
} | |
int cmp_item(struct item a, struct item b) { | |
assert(a.type == b.type); | |
a.type->cmp(a.data, b.data); | |
} | |
// Define type for char | |
void print_char(void *c) { | |
printf("%c", *(char *)c); | |
} | |
int cmp_char(void *a, void *b) { | |
return *(char *)a < *(char *)b; | |
} | |
struct type_def char_def = {.print = print_char, .cmp = cmp_char }; | |
struct item malloc_char_item(char a){ | |
struct item ans; | |
ans.type = &char_def; | |
ans.data = malloc(sizeof(char)); | |
*(char *)ans.data = a; | |
return ans; | |
} | |
// Define type for int | |
void print_int(void *i) { | |
printf("%d", *(int*)i); | |
} | |
int cmp_int(void *a, void *b){ | |
return *(int *) a < *(int *) b; | |
} | |
struct type_def int_def = {.print = print_int, .cmp = cmp_char }; | |
struct item malloc_int_item(int a) { | |
struct item ans; | |
ans.type = &int_def; | |
ans.data = malloc(sizeof(int)); | |
*(int *) ans.data = a; | |
return ans; | |
} | |
// Create generic vector | |
struct item_vector { | |
struct item* begin; | |
struct item* end; | |
}; | |
struct item_vector malloc_item_vector(int size) { | |
struct item_vector ans; | |
ans.begin = malloc(sizeof(struct item) * size); | |
ans.end = ans.begin + size; | |
return ans; | |
} | |
void print_item_vector(struct item_vector v) { | |
for (struct item* p = v.begin; p != v.end; p++) { | |
print_item(*p); | |
putchar(' '); | |
} | |
} | |
struct item* at(struct item_vector v, int i) { | |
return v.begin + i; | |
} | |
int main() { | |
struct item_vector vec = malloc_item_vector(3); | |
*at(vec, 0) = malloc_char_item('a'); | |
*at(vec, 1) = malloc_int_item(42); | |
*at(vec, 2) = malloc_char_item('x'); | |
print_item_vector(vec); | |
putchar('\n'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment