Last active
May 4, 2022 19:00
-
-
Save RealNeGate/41ed37bb4481ed19be35983f3a6ee573 to your computer and use it in GitHub Desktop.
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
| // I'm going to hell for this one... | |
| // | |
| // https://godbolt.org/z/PjxjveaG4 | |
| #include <stdbool.h> | |
| #include <stddef.h> | |
| #ifdef __clang__ | |
| #define typeof(x) __typeof__(x) | |
| #endif | |
| // extract | |
| #define _ITER__TYPENAME(a, b, c, d, e, ...) a | |
| #define _ITER__COND(a, b, c, d, e, ...) b | |
| #define _ITER__NEXT(a, b, c, d, e, ...) c | |
| #define _ITER__ITERATOR(a, b, c, d, e, ...) d | |
| #define _ITER__ENDPOINT(a, b, c, d, e, ...) e | |
| #define _ITER__REST(a, b, c, d, e, ...) , ## __VA_ARGS__ | |
| // lmao | |
| #define for(a, b) \ | |
| for (_ITER__TYPENAME b a = _ITER__ITERATOR b, \ | |
| __end = _ITER__ENDPOINT b; \ | |
| _ITER__COND b (a, __end _ITER__REST b); \ | |
| _ITER__NEXT b (&a _ITER__REST b)) | |
| ////////////////////////////////////// | |
| // Range based iterator | |
| ////////////////////////////////////// | |
| inline static bool range_cond(int it, int end) { return it < end; } | |
| inline static void range_next(int* it) { *it += 1; } | |
| #define RANGE(min, max) (int, range_cond, range_next, min, max) | |
| ////////////////////////////////////// | |
| // Array iterator | |
| ////////////////////////////////////// | |
| inline static bool array_cond(void* it, void* end, size_t stride) { return it != end; } | |
| inline static void array_next(void** it, size_t stride) { char** ptr = (char**)it; *ptr += stride; } | |
| #define ARRAY(arr, n) (typeof(arr), array_cond, array_next, arr, &arr[n], sizeof(*arr)) | |
| ////////////////////////////////////// | |
| // C string iterator | |
| ////////////////////////////////////// | |
| inline static bool cstr_cond(char* it, char* end) { return *it != 0; } | |
| inline static void cstr_next(char** it) { *it += 1; } | |
| #define CSTR(arr) (const char*, cstr_cond, cstr_next, arr, 0) | |
| int foo(int n, int* arr) { | |
| int sum = 0; | |
| for (i, RANGE(0, n)) sum += arr[i]; | |
| return sum; | |
| } | |
| int bar(int n, int* arr) { | |
| int sum = 0; | |
| for (p, ARRAY(arr, n)) sum += *p; | |
| return sum; | |
| } | |
| int baz(int n, const char* str) { | |
| int sum = 0; | |
| for (c, CSTR(str)) sum += *c; | |
| return sum; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment