Optimize tprintf implementation

It no longer uses a local buffer, so it needs less memory
and no mutex.

Signed-off-by: Stefan Weil <sw@weilnetz.de>
This commit is contained in:
Stefan Weil 2019-07-10 20:59:07 +02:00
parent 2aebd10fb7
commit 9259ed8f26
3 changed files with 24 additions and 26 deletions

View File

@ -52,5 +52,4 @@ void CCUtilMutex::Unlock() {
#endif
}
CCUtilMutex tprintfMutex; // should remain global
} // namespace tesseract

View File

@ -87,7 +87,6 @@ class CCUtil {
"Use ambigs for deciding whether to adapt to a character");
};
extern CCUtilMutex tprintfMutex; // should remain global
} // namespace tesseract
#endif // TESSERACT_CCUTIL_CCUTIL_H_

View File

@ -23,7 +23,6 @@
#include <cstdio>
#include <cstdarg>
#include "ccutil.h"
#include "params.h"
#include "strngs.h"
#include "tprintf.h"
@ -35,34 +34,35 @@ static STRING_VAR(debug_file, "", "File to send tprintf output to");
// Trace printf
DLLSYM void tprintf(const char *format, ...)
{
tesseract::tprintfMutex.Lock();
va_list args; // variable args
const char* debug_file_name = debug_file.string();
static FILE *debugfp = nullptr; // debug file
// debug window
int32_t offset = 0; // into message
char msg[MAX_MSG_LEN + 1];
va_start(args, format); // variable list
// Format into msg
#ifdef _WIN32
offset += _vsnprintf(msg + offset, MAX_MSG_LEN - offset, format, args);
if (debug_file_name && strcmp(debug_file_name, "/dev/null") == 0)
debug_file.set_value("nul");
#else
offset += vsnprintf(msg + offset, MAX_MSG_LEN - offset, format, args);
#endif
va_end(args);
if (debug_file_name == nullptr) {
// This should not happen.
return;
}
if (debugfp == nullptr && debug_file_name && strlen(debug_file_name) > 0) {
debugfp = fopen(debug_file.string(), "wb");
} else if (debugfp != nullptr && debug_file_name && strlen(debug_file_name) == 0) {
#ifdef _WIN32
// Replace /dev/null by nul for Windows.
if (strcmp(debug_file_name, "/dev/null") == 0) {
debug_file_name = "nul";
debug_file.set_value(debug_file_name);
}
#endif
if (debugfp == nullptr && debug_file_name[0] != '\0') {
debugfp = fopen(debug_file_name, "wb");
} else if (debugfp != nullptr && debug_file_name[0] == '\0') {
fclose(debugfp);
debugfp = nullptr;
}
if (debugfp != nullptr)
fprintf(debugfp, "%s", msg);
else
fprintf(stderr, "%s", msg);
tesseract::tprintfMutex.Unlock();
va_list args; // variable args
va_start(args, format); // variable list
if (debugfp != nullptr) {
vfprintf(debugfp, format, args);
} else {
vfprintf(stderr, format, args);
}
va_end(args);
}