Last active
March 24, 2017 09:41
-
-
Save chrisbarrett/5794681 to your computer and use it in GitHub Desktop.
C object using blocks language extension
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 <assert.h> | |
#include <stdlib.h> | |
#define Array_new(name, type, len) \ | |
typedef void(^name##_each)(type); \ | |
typedef void(^name##_each_i)(type, int); \ | |
\ | |
struct { \ | |
type *data; \ | |
size_t length; \ | |
void(^free)(); \ | |
type(^get)(int); \ | |
void(^set)(int, type); \ | |
void(^each)(name##_each); \ | |
void(^each_i)(name##_each_i); \ | |
} name; \ | |
\ | |
name.data = malloc(len * sizeof(type)); \ | |
name.length = len; \ | |
\ | |
name.free = ^{ free(name.data); }; \ | |
\ | |
name.get = ^(int i){ \ | |
assert(i<= name.length); \ | |
return ((type *)name.data)[i]; \ | |
}; \ | |
\ | |
name.set = ^(int i, type value){ \ | |
assert(i<= name.length); \ | |
((type*)name.data)[i] = value; \ | |
}; \ | |
\ | |
name.each = ^(name##_each action){ \ | |
for (int i=0; i<name.length; ++i) \ | |
action(name.get(i)); \ | |
}; \ | |
\ | |
name.each_i = ^(name##_each_i action){ \ | |
for (int i=0; i<name.length; ++i) \ | |
action(name.get(i), i); \ | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment