Test string search for haystack/needle, up to len for each. If the length is -1, use the full string length haystack/needle are null terminated
| 28 | // If the length is -1, use the full string length |
| 29 | // haystack/needle are null terminated |
| 30 | void TestSearch(const char* haystack_orig, const char* needle_orig, int haystack_len = -1, |
| 31 | int needle_len = -1) { |
| 32 | string haystack_copy(haystack_orig); |
| 33 | string needle_copy(needle_orig); |
| 34 | const char* haystack = haystack_copy.c_str(); |
| 35 | const char* needle = needle_copy.c_str(); |
| 36 | |
| 37 | string haystack_buffer, needle_buffer; |
| 38 | |
| 39 | const char* haystack_null_terminated = haystack; |
| 40 | const char* needle_null_terminated = needle; |
| 41 | |
| 42 | // Make null terminated versions (for libc). |
| 43 | if (haystack_len != -1) { |
| 44 | haystack_buffer = string(haystack, haystack_len); |
| 45 | haystack_null_terminated = haystack_buffer.c_str(); |
| 46 | } else { |
| 47 | haystack_len = strlen(haystack); |
| 48 | } |
| 49 | |
| 50 | if (needle_len != -1) { |
| 51 | needle_buffer = string(needle, needle_len); |
| 52 | needle_null_terminated = needle_buffer.c_str(); |
| 53 | } else { |
| 54 | needle_len = strlen(needle); |
| 55 | } |
| 56 | |
| 57 | // Call libc for correct result |
| 58 | const char* libc_result = strstr(haystack_null_terminated, needle_null_terminated); |
| 59 | int libc_offset = (libc_result == NULL) ? -1 : libc_result - haystack_null_terminated; |
| 60 | |
| 61 | StringValue haystack_str_val(const_cast<char*>(haystack), haystack_len); |
| 62 | |
| 63 | // Call our strstr with null terminated needle |
| 64 | StringSearchSSE needle1(needle_null_terminated); |
| 65 | int null_offset = needle1.Search(haystack_str_val); |
| 66 | EXPECT_EQ(null_offset, libc_offset); |
| 67 | |
| 68 | // Call our strstr with non-null terminated needle |
| 69 | StringValue needle_str_val(const_cast<char*>(needle), needle_len); |
| 70 | StringSearchSSE needle2(&needle_str_val); |
| 71 | int not_null_offset = needle2.Search(haystack_str_val); |
| 72 | EXPECT_EQ(not_null_offset, libc_offset); |
| 73 | |
| 74 | // Ensure haystack/needle are unmodified |
| 75 | EXPECT_EQ(strlen(needle_null_terminated), needle_len); |
| 76 | EXPECT_EQ(strlen(haystack_null_terminated), haystack_len); |
| 77 | EXPECT_EQ(strcmp(haystack, haystack_orig), 0); |
| 78 | EXPECT_EQ(strcmp(needle, needle_orig), 0); |
| 79 | } |
| 80 | |
| 81 | TEST(StringSearchTest, Basic) { |
| 82 | // Basic Tests |