Scan one file. `buffer` holds its bytes plus one spare byte. */
| 16194 | |
| 16195 | /* Scan one file. `buffer` holds its bytes plus one spare byte. */ |
| 16196 | static mcp_scan_cause_t search_scan_buffer(cbm_mcp_server_t *srv, search_scan_sink_t *sink, |
| 16197 | const search_scan_patterns_t *patterns, bool use_regex, |
| 16198 | const char *path, size_t path_length, char *buffer, |
| 16199 | size_t length, uint64_t deadline_ms) { |
| 16200 | size_t probe = length < SEARCH_SCAN_BINARY_PROBE ? length : SEARCH_SCAN_BINARY_PROBE; |
| 16201 | if (memchr(buffer, '\0', probe)) { |
| 16202 | return MCP_SCAN_SUCCESS; |
| 16203 | } |
| 16204 | const char *nul = memchr(buffer, '\0', length); |
| 16205 | if (nul) { |
| 16206 | /* Lines up to the last complete line before the NUL. */ |
| 16207 | size_t keep = 0; |
| 16208 | for (size_t i = (size_t)(nul - buffer); i > 0; i--) { |
| 16209 | if (buffer[i - SKIP_ONE] == '\n') { |
| 16210 | keep = i; |
| 16211 | break; |
| 16212 | } |
| 16213 | } |
| 16214 | length = keep; |
| 16215 | } |
| 16216 | buffer[length] = '\0'; |
| 16217 | bool over_limit = false; |
| 16218 | size_t line_number = 1; |
| 16219 | size_t since_check = 0; |
| 16220 | bool single_literal = !use_regex && !patterns->any_empty && patterns->count == 1; |
| 16221 | size_t pos = 0; |
| 16222 | while (pos < length) { |
| 16223 | if (++since_check >= SEARCH_SCAN_CHECK_EVERY) { |
| 16224 | since_check = 0; |
| 16225 | if (mcp_request_cancelled(srv)) { |
| 16226 | return MCP_SCAN_CANCELLED; |
| 16227 | } |
| 16228 | if (cbm_now_ms() >= deadline_ms) { |
| 16229 | return MCP_SCAN_DEADLINE; |
| 16230 | } |
| 16231 | } |
| 16232 | size_t line_start = pos; |
| 16233 | if (single_literal) { |
| 16234 | /* Jump to the next occurrence instead of visiting every line. */ |
| 16235 | const char *hit = search_scan_find(buffer + pos, length - pos, patterns->items[0], |
| 16236 | patterns->lengths[0]); |
| 16237 | if (!hit) { |
| 16238 | break; |
| 16239 | } |
| 16240 | line_start = (size_t)(hit - buffer); |
| 16241 | while (line_start > pos && buffer[line_start - SKIP_ONE] != '\n') { |
| 16242 | line_start--; |
| 16243 | } |
| 16244 | line_number += search_scan_count_newlines(buffer + pos, buffer + line_start); |
| 16245 | } |
| 16246 | char *newline = memchr(buffer + line_start, '\n', length - line_start); |
| 16247 | size_t line_end = newline ? (size_t)(newline - buffer) : length; |
| 16248 | /* Windows matched Select-String's Line, which has no trailing CR, so |
| 16249 | * `foo$` matched a CRLF line there; POSIX grep matches with the CR. */ |
| 16250 | size_t match_end = line_end; |
| 16251 | #ifdef _WIN32 |
| 16252 | if (match_end > line_start && buffer[match_end - SKIP_ONE] == '\r') { |
| 16253 | match_end--; |
no test coverage detected