58 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8 9#include "src/__support/CPP/span.h"10#include "src/string/strncpy.h"11#include "test/UnitTest/Test.h"12#include <stddef.h> // For size_t.13 14class LlvmLibcStrncpyTest : public LIBC_NAMESPACE::testing::Test {15public:16 void check_strncpy(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 // Making sure we don't overflow buffer.20 ASSERT_GE(dst.size(), n);21 // Making sure strncpy returns dst.22 ASSERT_EQ(LIBC_NAMESPACE::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 31TEST_F(LlvmLibcStrncpyTest, 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 38TEST_F(LlvmLibcStrncpyTest, CopyOne) {39 char dst[] = {'a', 'b'};40 const char src[] = {'x', 'y'};41 const char expected[] = {'x', 'b'}; // no \0 is appended42 check_strncpy(dst, src, 1, expected);43}44 45TEST_F(LlvmLibcStrncpyTest, 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 52TEST_F(LlvmLibcStrncpyTest, 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