• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- Unittests for strnlen ---------------------------------------------===//
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/strnlen.h"
10 #include "utils/UnitTest/Test.h"
11 #include <stddef.h>
12 
TEST(StrNLenTest,EmptyString)13 TEST(StrNLenTest, EmptyString) {
14   const char *empty = "";
15   ASSERT_EQ(static_cast<size_t>(0), __llvm_libc::strnlen(empty, 0));
16   // If N is greater than string length, this should still return 0.
17   ASSERT_EQ(static_cast<size_t>(0), __llvm_libc::strnlen(empty, 1));
18 }
19 
TEST(StrNLenTest,OneCharacterString)20 TEST(StrNLenTest, OneCharacterString) {
21   const char *single = "X";
22   ASSERT_EQ(static_cast<size_t>(1), __llvm_libc::strnlen(single, 1));
23   // If N is zero, this should return 0.
24   ASSERT_EQ(static_cast<size_t>(0), __llvm_libc::strnlen(single, 0));
25   // If N is greater than string length, this should still return 1.
26   ASSERT_EQ(static_cast<size_t>(1), __llvm_libc::strnlen(single, 2));
27 }
28 
TEST(StrNLenTest,ManyCharacterString)29 TEST(StrNLenTest, ManyCharacterString) {
30   const char *many = "123456789";
31   ASSERT_EQ(static_cast<size_t>(9), __llvm_libc::strnlen(many, 9));
32   // If N is smaller than the string length, it should return N.
33   ASSERT_EQ(static_cast<size_t>(3), __llvm_libc::strnlen(many, 3));
34   // If N is zero, this should return 0.
35   ASSERT_EQ(static_cast<size_t>(0), __llvm_libc::strnlen(many, 0));
36   // If N is greater than the string length, this should still return 9.
37   ASSERT_EQ(static_cast<size_t>(9), __llvm_libc::strnlen(many, 42));
38 }
39 
TEST(StrNLenTest,CharactersAfterNullTerminatorShouldNotBeIncluded)40 TEST(StrNLenTest, CharactersAfterNullTerminatorShouldNotBeIncluded) {
41   const char str[5] = {'a', 'b', 'c', '\0', 'd'};
42   ASSERT_EQ(static_cast<size_t>(3), __llvm_libc::strnlen(str, 3));
43   // This should only read up to the null terminator.
44   ASSERT_EQ(static_cast<size_t>(3), __llvm_libc::strnlen(str, 4));
45   ASSERT_EQ(static_cast<size_t>(3), __llvm_libc::strnlen(str, 5));
46 }
47