1 //===-- Unittests for strcspn ---------------------------------------------===//
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/strcspn.h"
10 
11 #include "utils/UnitTest/Test.h"
12 
TEST(StrCSpnTest,ComplementarySpanShouldNotGoPastNullTerminator)13 TEST(StrCSpnTest, ComplementarySpanShouldNotGoPastNullTerminator) {
14   const char src[5] = {'a', 'b', '\0', 'c', 'd'};
15   EXPECT_EQ(__llvm_libc::strcspn(src, "b"), size_t{1});
16   EXPECT_EQ(__llvm_libc::strcspn(src, "d"), size_t{2});
17 
18   // Same goes for the segment to be searched for.
19   const char segment[5] = {'1', '2', '\0', '3', '4'};
20   EXPECT_EQ(__llvm_libc::strcspn("123", segment), size_t{0});
21 }
22 
TEST(StrCSpnTest,ComplementarySpanForEachIndividualCharacter)23 TEST(StrCSpnTest, ComplementarySpanForEachIndividualCharacter) {
24   const char *src = "12345";
25   // The complementary span size should increment accordingly.
26   EXPECT_EQ(__llvm_libc::strcspn(src, "1"), size_t{0});
27   EXPECT_EQ(__llvm_libc::strcspn(src, "2"), size_t{1});
28   EXPECT_EQ(__llvm_libc::strcspn(src, "3"), size_t{2});
29   EXPECT_EQ(__llvm_libc::strcspn(src, "4"), size_t{3});
30   EXPECT_EQ(__llvm_libc::strcspn(src, "5"), size_t{4});
31 }
32 
TEST(StrCSpnTest,ComplementarySpanIsStringLengthIfNoCharacterFound)33 TEST(StrCSpnTest, ComplementarySpanIsStringLengthIfNoCharacterFound) {
34   // Null terminator.
35   EXPECT_EQ(__llvm_libc::strcspn("", ""), size_t{0});
36   EXPECT_EQ(__llvm_libc::strcspn("", "_"), size_t{0});
37   // Single character.
38   EXPECT_EQ(__llvm_libc::strcspn("a", "b"), size_t{1});
39   // Multiple characters.
40   EXPECT_EQ(__llvm_libc::strcspn("abc", "1"), size_t{3});
41 }
42 
TEST(StrCSpnTest,DuplicatedCharactersNotPartOfComplementarySpan)43 TEST(StrCSpnTest, DuplicatedCharactersNotPartOfComplementarySpan) {
44   // Complementary span should be zero in all these cases.
45   EXPECT_EQ(__llvm_libc::strcspn("a", "aa"), size_t{0});
46   EXPECT_EQ(__llvm_libc::strcspn("aa", "a"), size_t{0});
47   EXPECT_EQ(__llvm_libc::strcspn("aaa", "aa"), size_t{0});
48   EXPECT_EQ(__llvm_libc::strcspn("aaaa", "aa"), size_t{0});
49   EXPECT_EQ(__llvm_libc::strcspn("aaaa", "baa"), size_t{0});
50 }
51