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 #endif
} }
CCUtilMutex tprintfMutex; // should remain global
} // namespace tesseract } // namespace tesseract

View File

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

View File

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