Skip to content

Commit d0b0494

Browse files
committed
[core] Simplify ErrorHandler implementation
The current implementation uses a stack-allocated buffer + an optionally- allocated thread local heap buffer for vsnprintf. This likely was made to avoid heap allocating whenever not necessary (i.e. in the majority of cases). However, a subsequent commit introduced a string `bp` that always performs the copy anyway. At this point the code can be simplified to avoid the double buffer and simply allocate straight into the string avoiding an extra copy.
1 parent 6229242 commit d0b0494

File tree

1 file changed

+8
-22
lines changed

1 file changed

+8
-22
lines changed

core/foundation/src/TError.cxx

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -108,34 +108,20 @@ ErrorHandlerFunc_t GetErrorHandler()
108108

109109
void ErrorHandler(Int_t level, const char *location, const char *fmt, std::va_list ap)
110110
{
111-
thread_local Int_t buf_size(256);
112-
thread_local char *buf_storage(nullptr);
113-
114-
char small_buf[256];
115-
char *buf = buf_storage ? buf_storage : small_buf;
116-
117-
std::va_list ap_copy;
118-
va_copy(ap_copy, ap);
119-
120111
if (!fmt)
121112
fmt = "no error message provided";
122113

123-
Int_t n = vsnprintf(buf, buf_size, fmt, ap_copy);
124-
if (n >= buf_size) {
125-
va_end(ap_copy);
126-
127-
buf_size = n + 1;
128-
if (buf != &(small_buf[0]))
129-
delete[] buf;
130-
buf_storage = buf = new char[buf_size];
114+
std::va_list ap_copy;
115+
va_copy(ap_copy, ap);
116+
// Get the required buffer size
117+
const int required_bytes = vsnprintf(nullptr, 0, fmt, ap) + 1;
131118

132-
// Try again with a sufficiently large buffer
133-
va_copy(ap_copy, ap);
134-
vsnprintf(buf, buf_size, fmt, ap_copy);
135-
}
119+
std::string bp;
120+
bp.resize(required_bytes - 1, 0);
121+
// Actually print the string to the buffer
122+
vsnprintf(bp.data(), required_bytes, fmt, ap_copy);
136123
va_end(ap_copy);
137124

138-
std::string bp = buf;
139125
if (level >= kSysError && level < kFatal) {
140126
bp.push_back(' ');
141127
if (GetErrorSystemMsgHandlerRef())

0 commit comments

Comments
 (0)