1 //===-- Unittests for stpncpy ---------------------------------------------===// 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/__support/CPP/ArrayRef.h" 10 #include "src/string/stpncpy.h" 11 #include "utils/UnitTest/Test.h" 12 #include <stddef.h> // For size_t. 13 14 class LlvmLibcStpncpyTest : public __llvm_libc::testing::Test { 15 public: 16 void check_stpncpy(__llvm_libc::cpp::MutableArrayRef<char> dst, 17 const __llvm_libc::cpp::ArrayRef<char> src, size_t n, 18 const __llvm_libc::cpp::ArrayRef<char> expected, 19 size_t expectedCopied) { 20 // Making sure we don't overflow buffer. 21 ASSERT_GE(dst.size(), n); 22 // Making sure stpncpy returns a pointer to the end of dst. 23 ASSERT_EQ(__llvm_libc::stpncpy(dst.data(), src.data(), n), 24 dst.data() + expectedCopied); 25 // Expected must be of the same size as dst. 26 ASSERT_EQ(dst.size(), expected.size()); 27 // Expected and dst are the same. 28 for (size_t i = 0; i < expected.size(); ++i) 29 ASSERT_EQ(expected[i], dst[i]); 30 } 31 }; 32 33 TEST_F(LlvmLibcStpncpyTest, Untouched) { 34 char dst[] = {'a', 'b'}; 35 const char src[] = {'x', '\0'}; 36 const char expected[] = {'a', 'b'}; 37 check_stpncpy(dst, src, 0, expected, 0); 38 } 39 40 TEST_F(LlvmLibcStpncpyTest, CopyOne) { 41 char dst[] = {'a', 'b'}; 42 const char src[] = {'x', 'y'}; 43 const char expected[] = {'x', 'b'}; // no \0 is appended 44 check_stpncpy(dst, src, 1, expected, 1); 45 } 46 47 TEST_F(LlvmLibcStpncpyTest, CopyNull) { 48 char dst[] = {'a', 'b'}; 49 const char src[] = {'\0', 'y'}; 50 const char expected[] = {'\0', 'b'}; 51 check_stpncpy(dst, src, 1, expected, 0); 52 } 53 54 TEST_F(LlvmLibcStpncpyTest, CopyPastSrc) { 55 char dst[] = {'a', 'b'}; 56 const char src[] = {'\0', 'y'}; 57 const char expected[] = {'\0', '\0'}; 58 check_stpncpy(dst, src, 2, expected, 0); 59 } 60 61 TEST_F(LlvmLibcStpncpyTest, CopyTwoNoNull) { 62 char dst[] = {'a', 'b'}; 63 const char src[] = {'x', 'y'}; 64 const char expected[] = {'x', 'y'}; 65 check_stpncpy(dst, src, 2, expected, 2); 66 } 67 68 TEST_F(LlvmLibcStpncpyTest, CopyTwoWithNull) { 69 char dst[] = {'a', 'b'}; 70 const char src[] = {'x', '\0'}; 71 const char expected[] = {'x', '\0'}; 72 check_stpncpy(dst, src, 2, expected, 1); 73 } 74