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