• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- Unittests for strncpy ---------------------------------------------===//
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/strncpy.h"
10 #include "utils/CPP/ArrayRef.h"
11 #include "utils/UnitTest/Test.h"
12 #include <stddef.h> // For size_t.
13 
14 class StrncpyTest : public __llvm_libc::testing::Test {
15 public:
check_strncpy(__llvm_libc::cpp::MutableArrayRef<char> dst,const __llvm_libc::cpp::ArrayRef<char> src,size_t n,const __llvm_libc::cpp::ArrayRef<char> expected)16   void check_strncpy(__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     // Making sure we don't overflow buffer.
20     ASSERT_GE(dst.size(), n);
21     // Making sure strncpy returns dst.
22     ASSERT_EQ(__llvm_libc::strncpy(dst.data(), src.data(), n), dst.data());
23     // Expected must be of the same size as dst.
24     ASSERT_EQ(dst.size(), expected.size());
25     // Expected and dst are the same.
26     for (size_t i = 0; i < expected.size(); ++i)
27       ASSERT_EQ(expected[i], dst[i]);
28   }
29 };
30 
TEST_F(StrncpyTest,Untouched)31 TEST_F(StrncpyTest, Untouched) {
32   char dst[] = {'a', 'b'};
33   const char src[] = {'x', '\0'};
34   const char expected[] = {'a', 'b'};
35   check_strncpy(dst, src, 0, expected);
36 }
37 
TEST_F(StrncpyTest,CopyOne)38 TEST_F(StrncpyTest, CopyOne) {
39   char dst[] = {'a', 'b'};
40   const char src[] = {'x', 'y'};
41   const char expected[] = {'x', 'b'}; // no \0 is appended
42   check_strncpy(dst, src, 1, expected);
43 }
44 
TEST_F(StrncpyTest,CopyNull)45 TEST_F(StrncpyTest, CopyNull) {
46   char dst[] = {'a', 'b'};
47   const char src[] = {'\0', 'y'};
48   const char expected[] = {'\0', 'b'};
49   check_strncpy(dst, src, 1, expected);
50 }
51 
TEST_F(StrncpyTest,CopyPastSrc)52 TEST_F(StrncpyTest, CopyPastSrc) {
53   char dst[] = {'a', 'b'};
54   const char src[] = {'\0', 'y'};
55   const char expected[] = {'\0', '\0'};
56   check_strncpy(dst, src, 2, expected);
57 }
58