blob: cb5b2533688e7967413441ab9cfd705d0a0233ad [file] [log] [blame]
Zachary Turner24ae6292017-02-16 19:38:21 +00001//===-- VASprintfTest.cpp ---------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Zachary Turnerd9c0e152017-02-16 20:15:26 +000010#include "lldb/Utility/VASPrintf.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000011#include "llvm/ADT/SmallString.h"
12
13#include "gtest/gtest.h"
14
15#include <locale.h>
16
Tim Hammerquist5706f1e2017-08-09 17:27:02 +000017#if defined (_WIN32)
18#define TEST_ENCODING ".932" // On Windows, test codepage 932
19#else
20#define TEST_ENCODING "C" // ...otherwise, any widely available uni-byte LC
21#endif
22
Zachary Turner24ae6292017-02-16 19:38:21 +000023using namespace lldb_private;
24using namespace llvm;
25
26static bool Sprintf(llvm::SmallVectorImpl<char> &Buffer, const char *Fmt, ...) {
27 va_list args;
28 va_start(args, Fmt);
29 bool Result = VASprintf(Buffer, Fmt, args);
30 va_end(args);
31 return Result;
32}
33
34TEST(VASprintfTest, NoBufferResize) {
35 std::string TestStr("small");
36
37 llvm::SmallString<32> BigBuffer;
38 ASSERT_TRUE(Sprintf(BigBuffer, "%s", TestStr.c_str()));
39 EXPECT_STREQ(TestStr.c_str(), BigBuffer.c_str());
40 EXPECT_EQ(TestStr.size(), BigBuffer.size());
41}
42
43TEST(VASprintfTest, BufferResize) {
44 std::string TestStr("bigger");
45 llvm::SmallString<4> SmallBuffer;
46 ASSERT_TRUE(Sprintf(SmallBuffer, "%s", TestStr.c_str()));
47 EXPECT_STREQ(TestStr.c_str(), SmallBuffer.c_str());
48 EXPECT_EQ(TestStr.size(), SmallBuffer.size());
49}
50
51TEST(VASprintfTest, EncodingError) {
52 // Save the current locale first.
53 std::string Current(::setlocale(LC_ALL, nullptr));
54
Tim Hammerquist5706f1e2017-08-09 17:27:02 +000055 // Ensure tested locale is successfully set
56 ASSERT_TRUE(setlocale(LC_ALL, TEST_ENCODING));
Zachary Turner24ae6292017-02-16 19:38:21 +000057
58 wchar_t Invalid[2];
Pavel Labath6673afb2017-02-17 13:27:50 +000059 Invalid[0] = 0x100;
Zachary Turner24ae6292017-02-16 19:38:21 +000060 Invalid[1] = 0;
61 llvm::SmallString<32> Buffer;
62 EXPECT_FALSE(Sprintf(Buffer, "%ls", Invalid));
63 EXPECT_EQ("<Encoding error>", Buffer);
64
Tim Hammerquist5706f1e2017-08-09 17:27:02 +000065 // Ensure we've restored the original locale once tested
66 ASSERT_TRUE(setlocale(LC_ALL, Current.c_str()));
Zachary Turner24ae6292017-02-16 19:38:21 +000067}