blob: a04cd27362df38ead8dfd67d074ed05bf69f820c [file] [log] [blame]
Raphael Isemann80814282020-01-24 08:23:27 +01001//===-- VASprintfTest.cpp -------------------------------------------------===//
Zachary Turner24ae6292017-02-16 19:38:21 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Zachary Turner24ae6292017-02-16 19:38:21 +00006//
7//===----------------------------------------------------------------------===//
8
Zachary Turnerd9c0e152017-02-16 20:15:26 +00009#include "lldb/Utility/VASPrintf.h"
Zachary Turner24ae6292017-02-16 19:38:21 +000010#include "llvm/ADT/SmallString.h"
11
12#include "gtest/gtest.h"
13
14#include <locale.h>
15
Tim Hammerquist5706f1e2017-08-09 17:27:02 +000016#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
Zachary Turner24ae6292017-02-16 19:38:21 +000022using namespace lldb_private;
23using namespace llvm;
24
25static 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
33TEST(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
42TEST(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
50TEST(VASprintfTest, EncodingError) {
51 // Save the current locale first.
52 std::string Current(::setlocale(LC_ALL, nullptr));
53
Tim Hammerquist5706f1e2017-08-09 17:27:02 +000054 // Ensure tested locale is successfully set
55 ASSERT_TRUE(setlocale(LC_ALL, TEST_ENCODING));
Zachary Turner24ae6292017-02-16 19:38:21 +000056
57 wchar_t Invalid[2];
Pavel Labath6673afb2017-02-17 13:27:50 +000058 Invalid[0] = 0x100;
Zachary Turner24ae6292017-02-16 19:38:21 +000059 Invalid[1] = 0;
60 llvm::SmallString<32> Buffer;
61 EXPECT_FALSE(Sprintf(Buffer, "%ls", Invalid));
62 EXPECT_EQ("<Encoding error>", Buffer);
63
Tim Hammerquist5706f1e2017-08-09 17:27:02 +000064 // Ensure we've restored the original locale once tested
65 ASSERT_TRUE(setlocale(LC_ALL, Current.c_str()));
Zachary Turner24ae6292017-02-16 19:38:21 +000066}