// examples/files // BEGIN mycpp output #include "gc_heap.h" using gc_heap::Alloc; using gc_heap::kZeroMask; using gc_heap::StackRoots; #include "my_runtime.h" #include "mylib2.h" using gc_heap::NewStr; using gc_heap::NewList; using gc_heap::NewDict; GLOBAL_STR(str0, "Wrote %d bytes to StringIO"); GLOBAL_STR(str1, "contents = %s ... %s"); GLOBAL_STR(str2, "stdout\n"); GLOBAL_STR(str3, "Ran %d iterations"); GLOBAL_STR(str4, "result = %d"); namespace files { // forward declare } // forward declare namespace files namespace files { // declare void run_tests(); void run_benchmarks(); inline Str* fmt0(int a0) { gBuf.reset(); gBuf.write_const("Wrote ", 6); gBuf.format_d(a0); gBuf.write_const(" bytes to StringIO", 18); return gBuf.getvalue(); } inline Str* fmt1(Str* a0, Str* a1) { gBuf.reset(); gBuf.write_const("contents = ", 11); gBuf.format_s(a0); gBuf.write_const(" ... ", 5); gBuf.format_s(a1); return gBuf.getvalue(); } inline Str* fmt2(int a0) { gBuf.reset(); gBuf.write_const("Ran ", 4); gBuf.format_d(a0); gBuf.write_const(" iterations", 11); return gBuf.getvalue(); } inline Str* fmt3(int a0) { gBuf.reset(); gBuf.write_const("result = ", 9); gBuf.format_d(a0); return gBuf.getvalue(); } } // declare namespace files namespace files { // define void run_tests() { mylib::BufWriter* f = nullptr; Str* contents = nullptr; mylib::Writer* f2 = nullptr; StackRoots _roots({&f, &contents, &f2}); f = Alloc(); for (int i = 0; i < 30; ++i) { f->write(chr((i + 65))); } contents = f->getvalue(); println_stderr(fmt0(len(contents))); println_stderr(fmt1(contents->slice(0, 10), contents->slice(-10))); f2 = mylib::Stdout(); f2->write(str2); } void run_benchmarks() { int n; int result; int i; mylib::BufWriter* f = nullptr; StackRoots _roots({&f}); n = 10000; result = 0; i = 0; while (i < n) { f = Alloc(); for (int j = 0; j < 30; ++j) { f->write(chr((j + 65))); } result += len(f->getvalue()); i += 1; } println_stderr(fmt2(n)); println_stderr(fmt3(result)); } } // define namespace files int main(int argc, char **argv) { // gc_heap::gHeap.Init(512); gc_heap::gHeap.Init(128 << 10); // 128 KiB; doubling in size // gc_heap::gHeap.Init(400 << 20); // 400 MiB to avoid garbage collection if (getenv("BENCHMARK")) { fprintf(stderr, "Benchmarking...\n"); files::run_benchmarks(); } else { files::run_tests(); } }