1 | //===-- Unittests for strncat ---------------------------------------------===// |
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/string/strncat.h" |
10 | #include "test/UnitTest/Test.h" |
11 | |
12 | TEST(LlvmLibcStrNCatTest, EmptyDest) { |
13 | const char *abc = "abc" ; |
14 | char dest[4]; |
15 | |
16 | dest[0] = '\0'; |
17 | |
18 | // Start by copying nothing |
19 | char *result = LIBC_NAMESPACE::strncat(dest, src: abc, count: 0); |
20 | ASSERT_EQ(dest, result); |
21 | ASSERT_EQ(dest[0], '\0'); |
22 | |
23 | // Then copy part of it. |
24 | result = LIBC_NAMESPACE::strncat(dest, src: abc, count: 1); |
25 | ASSERT_EQ(dest, result); |
26 | ASSERT_STREQ(dest, "a" ); |
27 | |
28 | // Reset for the last test. |
29 | dest[0] = '\0'; |
30 | |
31 | // Then copy all of it. |
32 | result = LIBC_NAMESPACE::strncat(dest, src: abc, count: 3); |
33 | ASSERT_EQ(dest, result); |
34 | ASSERT_STREQ(dest, result); |
35 | ASSERT_STREQ(dest, abc); |
36 | } |
37 | |
38 | TEST(LlvmLibcStrNCatTest, NonEmptyDest) { |
39 | const char *abc = "abc" ; |
40 | char dest[7]; |
41 | |
42 | dest[0] = 'x'; |
43 | dest[1] = 'y'; |
44 | dest[2] = 'z'; |
45 | dest[3] = '\0'; |
46 | |
47 | // Copy only part of the string onto the end |
48 | char *result = LIBC_NAMESPACE::strncat(dest, src: abc, count: 1); |
49 | ASSERT_EQ(dest, result); |
50 | ASSERT_STREQ(dest, "xyza" ); |
51 | |
52 | // Copy a bit more, but without resetting. |
53 | result = LIBC_NAMESPACE::strncat(dest, src: abc, count: 2); |
54 | ASSERT_EQ(dest, result); |
55 | ASSERT_STREQ(dest, "xyzaab" ); |
56 | |
57 | // Set just the end marker, to make sure it overwrites properly. |
58 | dest[3] = '\0'; |
59 | |
60 | result = LIBC_NAMESPACE::strncat(dest, src: abc, count: 3); |
61 | ASSERT_EQ(dest, result); |
62 | ASSERT_STREQ(dest, "xyzabc" ); |
63 | |
64 | // Check that copying still works when count > src length |
65 | dest[0] = '\0'; |
66 | // And that it doesn't write beyond what is necessary. |
67 | dest[4] = 'Z'; |
68 | result = LIBC_NAMESPACE::strncat(dest, src: abc, count: 4); |
69 | ASSERT_EQ(dest, result); |
70 | ASSERT_STREQ(dest, "abc" ); |
71 | ASSERT_EQ(dest[4], 'Z'); |
72 | |
73 | result = LIBC_NAMESPACE::strncat(dest, src: abc, count: 5); |
74 | ASSERT_EQ(dest, result); |
75 | ASSERT_STREQ(dest, "abcabc" ); |
76 | } |
77 | |