diff options
Diffstat (limited to 'frontend/print.cpp')
-rw-r--r-- | frontend/print.cpp | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/frontend/print.cpp b/frontend/print.cpp new file mode 100644 index 0000000..396e9ad --- /dev/null +++ b/frontend/print.cpp @@ -0,0 +1,73 @@ +#include <cstdarg> +#include <string> +#include <unistd.h> + +#include "print.h" + +using namespace std; + +static string va_stringf(va_list args, const char * fmt) { + va_list args_copy; + va_copy(args_copy, args); + + size_t sz = vsnprintf(NULL, 0, fmt, args_copy) + 1; + char * msg = (char *) malloc(sz); + va_end(args_copy); + + vsnprintf(msg, sz, fmt, args); + + string out = msg; + free(msg); + + va_end(args); + + return out; +} + +static string stringf(const char * fmt, ...) { + va_list args; + va_start(args, fmt); + string out = va_stringf(args, fmt); + va_end(args); + return out; +} + +void lprtf(const char * fmt, ...) { + va_list args; + va_start(args, fmt); + string formatted = va_stringf(args, fmt); + va_end(args); + + fwrite(formatted.c_str(), 1, formatted.size(), stdout); + fflush(stdout); + + SessionLog::get().append(formatted); +} + +SessionLog & SessionLog::get() { + static SessionLog instance; + return instance; +} + +SessionLog::SessionLog() { + if (!this->enable) return; + + string filename = stringf("%lu.log", getpid()); + FILE * file = fopen(filename.c_str(), "w+"); + this->file = { file, [] (FILE * file) { fclose(file); } }; +} + +void SessionLog::append(const string & str) { + this->append(str.data(), str.size()); +} + +void SessionLog::append(const char * str) { + this->append(str, strlen(str)); +} + +void SessionLog::append(const char * buf, size_t buf_size) { + if (this->file == nullptr) return; + if (buf_size == 0) return; + fwrite(buf, 1, buf_size, this->file.get()); +} + |