| 1 |
//===-- VASprintfTest.cpp -------------------------------------------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
|
| 9 |
#include "lldb/Utility/VASPrintf.h" |
| 10 |
#include "llvm/ADT/SmallString.h" |
| 11 |
|
| 12 |
#include "gtest/gtest.h" |
| 13 |
|
| 14 |
#include <locale.h> |
| 15 |
|
| 16 |
#if defined (_WIN32) |
| 17 |
#define TEST_ENCODING ".932" // On Windows, test codepage 932 |
| 18 |
#else |
| 19 |
#define TEST_ENCODING "C" // ...otherwise, any widely available uni-byte LC |
| 20 |
#endif |
| 21 |
|
| 22 |
using namespace lldb_private; |
| 23 |
using namespace llvm; |
| 24 |
|
| 25 |
static bool Sprintf(llvm::SmallVectorImpl<char> &Buffer, const char *Fmt, ...) { |
| 26 |
va_list args; |
| 27 |
va_start(args, Fmt); |
| 28 |
bool Result = VASprintf(Buffer, Fmt, args); |
| 29 |
va_end(args); |
| 30 |
return Result; |
| 31 |
} |
| 32 |
|
| 33 |
TEST(VASprintfTest, NoBufferResize) { |
| 34 |
std::string TestStr("small"); |
| 35 |
|
| 36 |
llvm::SmallString<32> BigBuffer; |
| 37 |
ASSERT_TRUE(Sprintf(BigBuffer, "%s", TestStr.c_str())); |
| 38 |
EXPECT_STREQ(TestStr.c_str(), BigBuffer.c_str()); |
| 39 |
EXPECT_EQ(TestStr.size(), BigBuffer.size()); |
| 40 |
} |
| 41 |
|
| 42 |
TEST(VASprintfTest, BufferResize) { |
| 43 |
std::string TestStr("bigger"); |
| 44 |
llvm::SmallString<4> SmallBuffer; |
| 45 |
ASSERT_TRUE(Sprintf(SmallBuffer, "%s", TestStr.c_str())); |
| 46 |
EXPECT_STREQ(TestStr.c_str(), SmallBuffer.c_str()); |
| 47 |
EXPECT_EQ(TestStr.size(), SmallBuffer.size()); |
| 48 |
} |
| 49 |
|
| 50 |
TEST(VASprintfTest, EncodingError) { |
| 51 |
// Save the current locale first. |
| 52 |
std::string Current(::setlocale(LC_ALL, nullptr)); |
| 53 |
|
| 54 |
// Ensure tested locale is successfully set |
| 55 |
ASSERT_TRUE(setlocale(LC_ALL, TEST_ENCODING)); |
| 56 |
|
| 57 |
wchar_t Invalid[2]; |
| 58 |
Invalid[0] = 0x100; |
| 59 |
Invalid[1] = 0; |
| 60 |
llvm::SmallString<32> Buffer; |
| 61 |
EXPECT_FALSE(Sprintf(Buffer, "%ls", Invalid)); |
| 62 |
EXPECT_EQ("<Encoding error>", Buffer); |
| 63 |
|
| 64 |
// Ensure we've restored the original locale once tested |
| 65 |
ASSERT_TRUE(setlocale(LC_ALL, Current.c_str())); |
| 66 |
} |