4 #include <gtest/gtest.h>
15 void TestSearch(
const char* haystack_orig,
const char* needle_orig,
16 int haystack_len = -1,
int needle_len = -1) {
18 string haystack_copy(haystack_orig);
19 string needle_copy(needle_orig);
20 const char* haystack = haystack_copy.c_str();
21 const char* needle = needle_copy.c_str();
23 string haystack_buffer, needle_buffer;
25 const char* haystack_null_terminated = haystack;
26 const char* needle_null_terminated = needle;
29 if (haystack_len != -1) {
30 haystack_buffer = string(haystack, haystack_len);
31 haystack_null_terminated = haystack_buffer.c_str();
33 haystack_len = strlen(haystack);
36 if (needle_len != -1) {
37 needle_buffer = string(needle, needle_len);
38 needle_null_terminated = needle_buffer.c_str();
40 needle_len = strlen(needle);
44 const char* libc_result = strstr(haystack_null_terminated, needle_null_terminated);
45 int libc_offset = (libc_result == NULL) ? -1 : libc_result - haystack_null_terminated;
47 StringValue haystack_str_val(const_cast<char*>(haystack), haystack_len);
51 int null_offset = needle1.
Search(haystack_str_val);
52 EXPECT_EQ(null_offset, libc_offset);
55 StringValue needle_str_val(const_cast<char*>(needle), needle_len);
57 int not_null_offset = needle2.
Search(haystack_str_val);
58 EXPECT_EQ(not_null_offset, libc_offset);
61 EXPECT_EQ(strlen(needle_null_terminated), needle_len);
62 EXPECT_EQ(strlen(haystack_null_terminated), haystack_len);
63 EXPECT_EQ(strcmp(haystack, haystack_orig), 0);
64 EXPECT_EQ(strcmp(needle, needle_orig), 0);
68 TEST(StringSearchTest, Basic) {
104 int main(
int argc,
char **argv) {
105 ::testing::InitGoogleTest(&argc, argv);
106 return RUN_ALL_TESTS();
int main(int argc, char **argv)
void TestSearch(const char *haystack_orig, const char *needle_orig, int haystack_len=-1, int needle_len=-1)
int Search(const StringValue &haystack) const