// examples/cgi // 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, "\\"); GLOBAL_STR(str1, "\\d+"); GLOBAL_STR(str2, "&"); GLOBAL_STR(str3, "&"); GLOBAL_STR(str4, "<"); GLOBAL_STR(str5, "<"); GLOBAL_STR(str6, ">"); GLOBAL_STR(str7, ">"); GLOBAL_STR(str8, "\""); GLOBAL_STR(str9, """); GLOBAL_STR(str10, "xo--xo"); GLOBAL_STR(str11, "s: %s"); GLOBAL_STR(str12, "escaped: %s"); GLOBAL_STR(str13, ""); GLOBAL_STR(str14, "%s\n"); GLOBAL_STR(str15, "x"); GLOBAL_STR(str16, "X"); GLOBAL_STR(str17, ""); namespace cgi { // forward declare } // forward declare namespace cgi namespace cgi { // declare extern Str* BACKSLASH; extern Str* RAW_BACKSLASH; Str* escape(Str* s, bool quote); void run_tests(); void run_benchmarks(); inline Str* fmt0(Str* a0) { gBuf.reset(); gBuf.write_const("s: ", 3); gBuf.format_s(a0); return gBuf.getvalue(); } inline Str* fmt1(Str* a0) { gBuf.reset(); gBuf.write_const("escaped: ", 9); gBuf.format_s(a0); return gBuf.getvalue(); } inline Str* fmt2(Str* a0) { gBuf.reset(); gBuf.format_s(a0); gBuf.write_const("\n", 1); return gBuf.getvalue(); } } // declare namespace cgi namespace cgi { // define Str* BACKSLASH = str0; Str* RAW_BACKSLASH = str1; Str* escape(Str* s, bool quote) { StackRoots _roots({&s}); s = s->replace(str2, str3); s = s->replace(str4, str5); s = s->replace(str6, str7); if (quote) { s = s->replace(str8, str9); } return s; } void run_tests() { Str* mystr = nullptr; StackRoots _roots({&mystr}); mystr = str10; println_stderr(fmt0(mystr)); println_stderr(fmt1(escape(str13, true))); println_stderr(fmt2(mystr->replace(str15, str16))); } void run_benchmarks() { int i; int n; i = 0; n = 1000000; while (i < n) { escape(str17, true); i = (i + 1); } } } // define namespace cgi 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"); cgi::run_benchmarks(); } else { cgi::run_tests(); } }