[OptTable] Fix typo VALUE => VALUES (NFCI) (#121523)
[llvm-project.git] / libc / test / src / stdio / vasprintf_test.cpp
blob2eb1be3d7a9bfd7a838b28c2ec162008a43476fe
1 //===-- Unittests for vasprintf--------------------------------------------===//
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 //===----------------------------------------------------------------------===//
9 #include "src/stdio/sprintf.h"
10 #include "src/stdio/vasprintf.h"
11 #include "src/string/memset.h"
12 #include "test/UnitTest/Test.h"
14 int call_vasprintf(char **__restrict buffer, const char *__restrict format,
15 ...) {
16 va_list vlist;
17 va_start(vlist, format);
18 int ret = LIBC_NAMESPACE::vasprintf(buffer, format, vlist);
19 va_end(vlist);
20 return ret;
23 TEST(LlvmLibcVASPrintfTest, SimpleNoConv) {
24 char *buff = nullptr;
25 int written;
26 written = call_vasprintf(&buff, "A simple string with no conversions.");
27 EXPECT_EQ(written, 36);
28 ASSERT_STREQ(buff, "A simple string with no conversions.");
29 free(buff);
32 TEST(LlvmLibcVASPrintfTest, PercentConv) {
33 char *buff = nullptr;
34 int written;
36 written = call_vasprintf(&buff, "%%");
37 EXPECT_EQ(written, 1);
38 ASSERT_STREQ(buff, "%");
39 free(buff);
41 written = call_vasprintf(&buff, "abc %% def");
42 EXPECT_EQ(written, 9);
43 ASSERT_STREQ(buff, "abc % def");
44 free(buff);
46 written = call_vasprintf(&buff, "%%%%%%");
47 EXPECT_EQ(written, 3);
48 ASSERT_STREQ(buff, "%%%");
49 free(buff);
52 TEST(LlvmLibcVASPrintfTest, CharConv) {
53 char *buff = nullptr;
54 int written;
56 written = call_vasprintf(&buff, "%c", 'a');
57 EXPECT_EQ(written, 1);
58 ASSERT_STREQ(buff, "a");
59 free(buff);
61 written = call_vasprintf(&buff, "%3c %-3c", '1', '2');
62 EXPECT_EQ(written, 7);
63 ASSERT_STREQ(buff, " 1 2 ");
64 free(buff);
66 written = call_vasprintf(&buff, "%*c", 2, '3');
67 EXPECT_EQ(written, 2);
68 ASSERT_STREQ(buff, " 3");
69 free(buff);
72 TEST(LlvmLibcVASPrintfTest, LargeStringNoConv) {
73 char *buff = nullptr;
74 char long_str[1001];
75 LIBC_NAMESPACE::memset(long_str, 'a', 1000);
76 long_str[1000] = '\0';
77 int written;
78 written = call_vasprintf(&buff, long_str);
79 EXPECT_EQ(written, 1000);
80 ASSERT_STREQ(buff, long_str);
81 free(buff);
84 TEST(LlvmLibcVASPrintfTest, ManyReAlloc) {
85 char *buff = nullptr;
86 const int expected_num_chars = 600;
87 int written = call_vasprintf(&buff, "%200s%200s%200s", "", "", "");
88 EXPECT_EQ(written, expected_num_chars);
90 bool isPadding = true;
91 for (int i = 0; i < expected_num_chars; i++) {
92 if (buff[i] != ' ') {
93 isPadding = false;
94 break;
97 EXPECT_TRUE(isPadding);
98 free(buff);