Created
July 27, 2017 14:23
-
-
Save Luiz-Monad/96a487a33a68c11d9edfd1a15c870b25 to your computer and use it in GitHub Desktop.
stupid small GC allocator
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 <cstdio> | |
#include <cstdint> | |
#include <iostream> | |
#include <algorithm> | |
using namespace std; | |
template<typename T> | |
T * gcalloc(uintptr_t * buf, size_t qty, size_t max) { | |
if (buf == nullptr) { | |
buf = new uintptr_t[max]; *buf = (uintptr_t)&buf[1]; } | |
auto p = *buf; | |
*buf += (qty * sizeof(T) / 8 + 1) * 8; | |
return (T *)p; | |
} | |
int main(int argc, char ** argv) { | |
const int max_gc = 2 * 1024 * 1024; | |
uintptr_t * gc = nullptr; | |
auto item1 = gcalloc<float>(gc, 2, max_gc); | |
auto item2 = gcalloc<int>(gc, 1, max_gc); | |
auto item3 = gcalloc<char>(gc, 5, max_gc); | |
item1[0] = 6.66; item1[1] = 3.33; | |
item2[0] = 1; | |
string sitem3(item3); | |
sitem3.replace(0, 2, "ok"); | |
//bonus functional programming | |
auto compose = [] (auto f1, auto f2) { | |
return [f1, f2] (auto i) { | |
f2(f1(i)); }; }; | |
auto lcast = [] (auto i) { return (float) i; }; | |
auto lcout = [] (auto i) { cout << i << endl; }; | |
for_each(item1, item1 + 2, lcout); | |
for_each(item2, item2 + 1, compose(lcast, lcout)); | |
cout << item3 << endl; | |
//throw everything away | |
delete gc; | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment