1 //===-- Unittests for strchr ----------------------------------------------===// 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/strchr.h" 10 #include "utils/UnitTest/Test.h" 11 12 TEST(LlvmLibcStrChrTest, FindsFirstCharacter) { 13 const char *src = "abcde"; 14 15 // Should return original string since 'a' is the first character. 16 ASSERT_STREQ(__llvm_libc::strchr(src, 'a'), "abcde"); 17 // Source string should not change. 18 ASSERT_STREQ(src, "abcde"); 19 } 20 21 TEST(LlvmLibcStrChrTest, FindsMiddleCharacter) { 22 const char *src = "abcde"; 23 24 // Should return characters after (and including) 'c'. 25 ASSERT_STREQ(__llvm_libc::strchr(src, 'c'), "cde"); 26 // Source string should not change. 27 ASSERT_STREQ(src, "abcde"); 28 } 29 30 TEST(LlvmLibcStrChrTest, FindsLastCharacterThatIsNotNullTerminator) { 31 const char *src = "abcde"; 32 33 // Should return 'e' and null-terminator. 34 ASSERT_STREQ(__llvm_libc::strchr(src, 'e'), "e"); 35 // Source string should not change. 36 ASSERT_STREQ(src, "abcde"); 37 } 38 39 TEST(LlvmLibcStrChrTest, FindsNullTerminator) { 40 const char *src = "abcde"; 41 42 // Should return null terminator. 43 ASSERT_STREQ(__llvm_libc::strchr(src, '\0'), ""); 44 // Source string should not change. 45 ASSERT_STREQ(src, "abcde"); 46 } 47 48 TEST(LlvmLibcStrChrTest, CharacterNotWithinStringShouldReturnNullptr) { 49 // Since 'z' is not within the string, should return nullptr. 50 ASSERT_STREQ(__llvm_libc::strchr("123?", 'z'), nullptr); 51 } 52 53 TEST(LlvmLibcStrChrTest, TheSourceShouldNotChange) { 54 const char *src = "abcde"; 55 // When the character is found, the source string should not change. 56 __llvm_libc::strchr(src, 'd'); 57 ASSERT_STREQ(src, "abcde"); 58 // Same case for when the character is not found. 59 __llvm_libc::strchr(src, 'z'); 60 ASSERT_STREQ(src, "abcde"); 61 // Same case for when looking for nullptr. 62 __llvm_libc::strchr(src, '\0'); 63 ASSERT_STREQ(src, "abcde"); 64 } 65 66 TEST(LlvmLibcStrChrTest, ShouldFindFirstOfDuplicates) { 67 // '1' is duplicated in the string, but it should find the first copy. 68 ASSERT_STREQ(__llvm_libc::strchr("abc1def1ghi", '1'), "1def1ghi"); 69 70 const char *dups = "XXXXX"; 71 // Should return original string since 'X' is the first character. 72 ASSERT_STREQ(__llvm_libc::strchr(dups, 'X'), dups); 73 } 74 75 TEST(LlvmLibcStrChrTest, EmptyStringShouldOnlyMatchNullTerminator) { 76 // Null terminator should match. 77 ASSERT_STREQ(__llvm_libc::strchr("", '\0'), ""); 78 // All other characters should not match. 79 ASSERT_STREQ(__llvm_libc::strchr("", 'Z'), nullptr); 80 ASSERT_STREQ(__llvm_libc::strchr("", '3'), nullptr); 81 ASSERT_STREQ(__llvm_libc::strchr("", '*'), nullptr); 82 } 83