1 //===-- Unittests for asprintf--------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "src/stdio/asprintf.h"
10 #include "src/stdio/sprintf.h"
11 #include "src/string/memset.h"
12 #include "test/UnitTest/Test.h"
14 TEST(LlvmLibcASPrintfTest
, SimpleNoConv
) {
18 LIBC_NAMESPACE::asprintf(&buff
, "A simple string with no conversions.");
19 EXPECT_EQ(written
, 36);
20 ASSERT_STREQ(buff
, "A simple string with no conversions.");
24 TEST(LlvmLibcASPrintfTest
, PercentConv
) {
28 written
= LIBC_NAMESPACE::asprintf(&buff
, "%%");
29 EXPECT_EQ(written
, 1);
30 ASSERT_STREQ(buff
, "%");
33 written
= LIBC_NAMESPACE::asprintf(&buff
, "abc %% def");
34 EXPECT_EQ(written
, 9);
35 ASSERT_STREQ(buff
, "abc % def");
38 written
= LIBC_NAMESPACE::asprintf(&buff
, "%%%%%%");
39 EXPECT_EQ(written
, 3);
40 ASSERT_STREQ(buff
, "%%%");
44 TEST(LlvmLibcASPrintfTest
, CharConv
) {
48 written
= LIBC_NAMESPACE::asprintf(&buff
, "%c", 'a');
49 EXPECT_EQ(written
, 1);
50 ASSERT_STREQ(buff
, "a");
53 written
= LIBC_NAMESPACE::asprintf(&buff
, "%3c %-3c", '1', '2');
54 EXPECT_EQ(written
, 7);
55 ASSERT_STREQ(buff
, " 1 2 ");
58 written
= LIBC_NAMESPACE::asprintf(&buff
, "%*c", 2, '3');
59 EXPECT_EQ(written
, 2);
60 ASSERT_STREQ(buff
, " 3");
64 TEST(LlvmLibcASPrintfTest
, LargeStringNoConv
) {
67 LIBC_NAMESPACE::memset(long_str
, 'a', 1000);
68 long_str
[1000] = '\0';
70 written
= LIBC_NAMESPACE::asprintf(&buff
, long_str
);
71 EXPECT_EQ(written
, 1000);
72 ASSERT_STREQ(buff
, long_str
);
76 TEST(LlvmLibcASPrintfTest
, ManyReAlloc
) {
79 auto expected_num_chars
=
80 LIBC_NAMESPACE::sprintf(long_str
, "%200s%200s%200s", "a", "b", "c");
81 long_str
[expected_num_chars
] = '\0';
83 written
= LIBC_NAMESPACE::asprintf(&buff
, long_str
);
84 EXPECT_EQ(written
, expected_num_chars
);
85 ASSERT_STREQ(buff
, long_str
);