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/span.h"
10#include "src/string/stpncpy.h"
11#include "test/UnitTest/Test.h"
12#include <stddef.h> // For size_t.
13
14class LlvmLibcStpncpyTest : public LIBC_NAMESPACE::testing::Test {
15public:
16 void check_stpncpy(LIBC_NAMESPACE::cpp::span<char> dst,
17 const LIBC_NAMESPACE::cpp::span<const char> src, size_t n,
18 const LIBC_NAMESPACE::cpp::span<const 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(LIBC_NAMESPACE::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
33TEST_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, n: 0, expected, expectedCopied: 0);
38}
39
40TEST_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, n: 1, expected, expectedCopied: 1);
45}
46
47TEST_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, n: 1, expected, expectedCopied: 0);
52}
53
54TEST_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, n: 2, expected, expectedCopied: 0);
59}
60
61TEST_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, n: 2, expected, expectedCopied: 2);
66}
67
68TEST_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, n: 2, expected, expectedCopied: 1);
73}
74

source code of libc/test/src/string/stpncpy_test.cpp