Skip to content

Commit 3e7d783

Browse files
authored
fix(utility): Fix edge case behavior of vsnprintf, vswprintf for VC6 builds (#1375)
1 parent 4dc13d0 commit 3e7d783

File tree

1 file changed

+32
-18
lines changed

1 file changed

+32
-18
lines changed

Dependencies/Utility/Utility/stdio_adapter.h

Lines changed: 32 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -26,38 +26,52 @@
2626

2727
inline int vsnprintf(char* _Buffer, size_t _BufferCount, const char* _Format, va_list _ArgList)
2828
{
29-
// Microsoft's _vsnprintf does not null terminate when writing the entire length.
30-
int result = _vsnprintf(_Buffer, _BufferCount, _Format, _ArgList);
31-
_Buffer[_BufferCount - 1] = '\0';
32-
return result;
29+
if (_BufferCount == 0)
30+
return -1;
31+
// Microsoft's _vsnprintf does not null terminate when writing the entire length.
32+
int result = _vsnprintf(_Buffer, _BufferCount, _Format, _ArgList);
33+
// Deal with errors and edge cases.
34+
if (result == -1 || (size_t)result == _BufferCount)
35+
{
36+
_Buffer[_BufferCount - 1] = '\0';
37+
return -1;
38+
}
39+
return result;
3340
}
3441

3542
// Yes, this is called vswprintf instead of vsnwprintf
3643
inline int vswprintf(wchar_t* _Buffer, size_t _BufferCount, const wchar_t* _Format, va_list _ArgList)
3744
{
38-
// Microsoft's _vsnwprintf does not null terminate when writing the entire length.
39-
int result = _vsnwprintf(_Buffer, _BufferCount, _Format, _ArgList);
40-
_Buffer[_BufferCount - 1] = L'\0';
41-
return result;
45+
if (_BufferCount == 0)
46+
return -1;
47+
// Microsoft's _vsnwprintf does not null terminate when writing the entire length.
48+
int result = _vsnwprintf(_Buffer, _BufferCount, _Format, _ArgList);
49+
// Deal with errors and edge cases.
50+
if (result == -1 || (size_t)result == _BufferCount)
51+
{
52+
_Buffer[_BufferCount - 1] = L'\0';
53+
return -1;
54+
}
55+
return result;
4256
}
4357

4458
inline int snprintf(char* _Buffer, size_t _BufferCount, const char* _Format, ...)
4559
{
46-
va_list _ArgList;
47-
va_start(_ArgList, _Format);
48-
int result = vsnprintf(_Buffer, _BufferCount, _Format, _ArgList);
49-
va_end(_ArgList);
50-
return result;
60+
va_list _ArgList;
61+
va_start(_ArgList, _Format);
62+
int result = vsnprintf(_Buffer, _BufferCount, _Format, _ArgList);
63+
va_end(_ArgList);
64+
return result;
5165
}
5266

5367
// Yes, this is called swprintf instead of snwprintf
5468
inline int swprintf(wchar_t* _Buffer, size_t _BufferCount, const wchar_t* _Format, ...)
5569
{
56-
va_list _ArgList;
57-
va_start(_ArgList, _Format);
58-
int result = vswprintf(_Buffer, _BufferCount, _Format, _ArgList);
59-
va_end(_ArgList);
60-
return result;
70+
va_list _ArgList;
71+
va_start(_ArgList, _Format);
72+
int result = vswprintf(_Buffer, _BufferCount, _Format, _ArgList);
73+
va_end(_ArgList);
74+
return result;
6175
}
6276

6377
#endif

0 commit comments

Comments
 (0)