Created
May 8, 2018 15:19
-
-
Save notnullnotvoid/479550249dc4a1d38a8cab7f496a48c7 to your computer and use it in GitHub Desktop.
example of simple type generics in C
This file contains hidden or 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
#ifndef LIST_H | |
#define LIST_H | |
#define LIST IntList | |
#define TYPE int | |
#include "ListImpl.h" | |
#undef LIST | |
#undef TYPE | |
#define LIST Vec2List | |
#define TYPE Vec2 | |
#include "ListImpl.h" | |
#undef LIST | |
#undef TYPE | |
#define LIST FloatList | |
#define TYPE float | |
#include "ListImpl.h" | |
#undef LIST | |
#undef TYPE | |
#endif |
This file contains hidden or 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 <stdlib.h> | |
struct LIST { | |
TYPE * data; | |
size_t len; | |
size_t max; | |
} | |
inline LIST LIST ## _create(size_t reserve) { | |
LIST l = {}; | |
l.data = (TYPE *) malloc(reserve * sizeof(TYPE)); | |
l.max = reserve; | |
l.len = 0; | |
return l; | |
} | |
inline LIST LIST ## _add(LIST l, TYPE t) { | |
if (l.len == l.max) { | |
l.max *= 2; | |
l.data = (TYPE *) realloc(l.data, l.max * sizeof(TYPE)); | |
} | |
l.data[l.len] = t; | |
++l.len; | |
return l; | |
} | |
inline LIST LIST ## _remove(LIST l, size_t index) { | |
--l.len; | |
for (int i = index; i < l.len; ++i) { | |
l.data[i] = l.data[i + 1]; | |
} | |
return l; | |
} | |
//removes elements in range [first, last) | |
inline LIST LIST ## _remove(LIST l, size_t first, size_t last) { | |
size_t range = last - first; | |
l.len -= range; | |
for (int i = first; i < l.len; ++i) { | |
l.data[i] = l.data[i + range]; | |
} | |
return l; | |
} | |
inline LIST LIST ## _shrink_to_fit(LIST l) { | |
l.data = (TYPE *) realloc(l.data, l.len * sizeof(TYPE)); | |
} | |
inline LIST LIST ## _destroy(LIST l) { | |
free(l.data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment