Substring_index
| 400 | |
| 401 | // Substring_index |
| 402 | GDV_FORCE_INLINE |
| 403 | const char* gdv_fn_substring_index(int64_t context, const char* txt, int32_t txt_len, |
| 404 | const char* pat, int32_t pat_len, int32_t cnt, |
| 405 | int32_t* out_len) { |
| 406 | if (txt_len == 0 || pat_len == 0 || cnt == 0) { |
| 407 | *out_len = 0; |
| 408 | return ""; |
| 409 | } |
| 410 | |
| 411 | if (ARROW_PREDICT_FALSE(txt_len < 0)) { |
| 412 | gdv_fn_context_set_error_msg(context, "Input string length cannot be negative"); |
| 413 | *out_len = 0; |
| 414 | return ""; |
| 415 | } |
| 416 | if (ARROW_PREDICT_FALSE(pat_len < 0)) { |
| 417 | gdv_fn_context_set_error_msg(context, "Pattern string length cannot be negative"); |
| 418 | *out_len = 0; |
| 419 | return ""; |
| 420 | } |
| 421 | |
| 422 | char* out = reinterpret_cast<char*>(gdv_fn_context_arena_malloc(context, txt_len)); |
| 423 | if (out == nullptr) { |
| 424 | gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string"); |
| 425 | *out_len = 0; |
| 426 | return ""; |
| 427 | } |
| 428 | |
| 429 | std::vector<int> lps(pat_len); |
| 430 | int len = 0; |
| 431 | |
| 432 | lps[0] = 0; // lps[0] is always 0 |
| 433 | |
| 434 | // the loop calculates lps[i] for i = 1 to M-1 |
| 435 | int i = 1; |
| 436 | while (i < pat_len) { |
| 437 | if (pat[i] == pat[len]) { |
| 438 | len++; |
| 439 | lps[i] = len; |
| 440 | i++; |
| 441 | } else { |
| 442 | // (pat[i] != pat[len]) |
| 443 | // This is tricky. Consider the example. |
| 444 | // AAACAAAA and i = 7. The idea is similar |
| 445 | // to search step. |
| 446 | if (len != 0) { |
| 447 | len = lps[len - 1]; |
| 448 | |
| 449 | // Also, note that we do not increment |
| 450 | // i here |
| 451 | } else { |
| 452 | // if (len == 0) |
| 453 | lps[i] = 0; |
| 454 | i++; |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | std::vector<int> occ; |