| 1 | //===-- Unittests for snprintf --------------------------------------------===// |
| 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 "src/stdio/snprintf.h" |
| 10 | |
| 11 | #include "test/UnitTest/Test.h" |
| 12 | |
| 13 | // The sprintf test cases cover testing the shared printf functionality, so |
| 14 | // these tests will focus on snprintf exclusive features. |
| 15 | |
| 16 | TEST(LlvmLibcSNPrintfTest, CutOff) { |
| 17 | char buff[100]; |
| 18 | int written; |
| 19 | |
| 20 | written = LIBC_NAMESPACE::snprintf(buff, 16, |
| 21 | "A simple string with no conversions." ); |
| 22 | EXPECT_EQ(written, 36); |
| 23 | ASSERT_STREQ(buff, "A simple string" ); |
| 24 | |
| 25 | written = LIBC_NAMESPACE::snprintf(buff, 5, "%s" , "1234567890" ); |
| 26 | EXPECT_EQ(written, 10); |
| 27 | ASSERT_STREQ(buff, "1234" ); |
| 28 | |
| 29 | written = LIBC_NAMESPACE::snprintf(buff, 67, "%-101c" , 'a'); |
| 30 | EXPECT_EQ(written, 101); |
| 31 | ASSERT_STREQ(buff, "a " |
| 32 | " " // Each of these is 8 spaces, and there are 8. |
| 33 | " " // In total there are 65 spaces |
| 34 | " " // 'a' + 65 spaces + '\0' = 67 |
| 35 | " " |
| 36 | " " |
| 37 | " " |
| 38 | " " |
| 39 | " " ); |
| 40 | |
| 41 | // passing null as the output pointer is allowed as long as buffsz is 0. |
| 42 | written = LIBC_NAMESPACE::snprintf(nullptr, 0, "%s and more" , "1234567890" ); |
| 43 | EXPECT_EQ(written, 19); |
| 44 | |
| 45 | written = LIBC_NAMESPACE::snprintf(nullptr, 0, "%*s" , INT_MIN, "nothing" ); |
| 46 | EXPECT_EQ(written, INT_MAX); |
| 47 | } |
| 48 | |
| 49 | TEST(LlvmLibcSNPrintfTest, NoCutOff) { |
| 50 | char buff[64]; |
| 51 | int written; |
| 52 | |
| 53 | written = LIBC_NAMESPACE::snprintf(buff, 37, |
| 54 | "A simple string with no conversions." ); |
| 55 | EXPECT_EQ(written, 36); |
| 56 | ASSERT_STREQ(buff, "A simple string with no conversions." ); |
| 57 | |
| 58 | written = LIBC_NAMESPACE::snprintf(buff, 20, "%s" , "1234567890" ); |
| 59 | EXPECT_EQ(written, 10); |
| 60 | ASSERT_STREQ(buff, "1234567890" ); |
| 61 | } |
| 62 | |