Making progress on util::dprintf

This commit is contained in:
2023-02-27 17:21:00 -05:00
parent 596e39add8
commit aa77480fb5
6 changed files with 97 additions and 1 deletions

View File

@@ -720,6 +720,63 @@ eng::string XYZ::debug_string() const {
return oss.str();
}
void (*dprintf_hook)(const char *oneline);
void hook_dprintf(void (*func)(const char *oneline)) {
dprintf_hook = func;
}
static void chop_up_dprintf(char *buffer, int size) {
// Drop the final newline, if any. We're going
// to automatically end with a newline and we don't
// want to double up.
if ((size > 0) && (buffer[size-1] == '\n')) {
size -= 1;
}
// Chop it up into lines and call the hook one line
// at a time. Replace control characters as we go.
const char *base = buffer;
for (int i = 0; i <= size; i++) {
if (buffer[i] < ' ') {
if ((buffer[i] == '\n') || (buffer[i] == 0)) {
buffer[i] = 0;
if (dprintf_hook == nullptr) {
fprintf(stderr, "%s\n", base);
} else {
dprintf_hook(base);
}
base = buffer + i + 1;
} else {
buffer[i] = ' ';
}
}
}
// If we're sending to stderr, flush. If not, then
// the hook routine is responsible for flushing its own
// output.
if (dprintf_hook == nullptr) {
fflush(stderr);
}
}
void dprintf(const char *format, ...) {
char buffer[256];
va_list args;
va_start (args, format);
int n = vsnprintf(buffer, 256, format, args);
if (n <= 255) {
chop_up_dprintf(buffer, n);
} else {
char *lbuffer = (char *)malloc(n + 1);
vsnprintf(lbuffer, n+1, format, args);
chop_up_dprintf(lbuffer, n);
free(lbuffer);
}
}
} // namespace util