| 1986 | } |
| 1987 | |
| 1988 | FORCE_INLINE |
| 1989 | const char* replace_utf8_utf8_utf8(gdv_int64 context, const char* text, |
| 1990 | gdv_int32 text_len, const char* from_str, |
| 1991 | gdv_int32 from_str_len, const char* to_str, |
| 1992 | gdv_int32 to_str_len, gdv_int32* out_len) { |
| 1993 | // Size the output buffer so large results are not capped by an arbitrary |
| 1994 | // limit, while avoiding a second pass over the input in the common case. |
| 1995 | // - No replacement possible, or the result can only shrink/stay equal: |
| 1996 | // text_len is a safe exact-or-upper bound, no scan. |
| 1997 | // - Bounded-ratio expansion (per-match growth <= match length, upper bound |
| 1998 | // fits within kMaxEagerAllocBytes): use an O(1) upper bound that assumes |
| 1999 | // every position matches, skipping the match-counting scan. |
| 2000 | // - Otherwise: count non-overlapping matches for the exact output size. |
| 2001 | static constexpr gdv_int64 kMaxEagerAllocBytes = 32 * 1024 * 1024; // 32 MB |
| 2002 | gdv_int64 max_length; |
| 2003 | if (from_str_len <= 0 || from_str_len > text_len || to_str_len <= from_str_len) { |
| 2004 | max_length = text_len; |
| 2005 | } else { |
| 2006 | gdv_int32 delta = to_str_len - from_str_len; // > 0 |
| 2007 | gdv_int64 upper_bound = static_cast<gdv_int64>(text_len) + |
| 2008 | (static_cast<gdv_int64>(text_len) / from_str_len) * delta; |
| 2009 | if (delta <= from_str_len && upper_bound <= kMaxEagerAllocBytes) { |
| 2010 | max_length = upper_bound; |
| 2011 | } else { |
| 2012 | gdv_int64 num_matches = 0; |
| 2013 | for (gdv_int32 i = 0; i <= text_len - from_str_len;) { |
| 2014 | if (memcmp(text + i, from_str, from_str_len) == 0) { |
| 2015 | num_matches++; |
| 2016 | i += from_str_len; |
| 2017 | } else { |
| 2018 | i++; |
| 2019 | } |
| 2020 | } |
| 2021 | // No matches: the result is the input unchanged; return it without calling |
| 2022 | // the helper (which would otherwise scan the text a second time). |
| 2023 | if (num_matches == 0) { |
| 2024 | *out_len = text_len; |
| 2025 | return text; |
| 2026 | } |
| 2027 | max_length = static_cast<gdv_int64>(text_len) + num_matches * delta; |
| 2028 | } |
| 2029 | } |
| 2030 | // Gandiva variable-length output uses int32 offsets, so a single output string |
| 2031 | // cannot exceed INT_MAX bytes. Report this explicitly instead of letting the |
| 2032 | // cast below wrap silently. |
| 2033 | if (max_length > INT_MAX) { |
| 2034 | gdv_fn_context_set_error_msg(context, |
| 2035 | "REPLACE: output string exceeds maximum size of 2GB"); |
| 2036 | *out_len = 0; |
| 2037 | return ""; |
| 2038 | } |
| 2039 | return replace_with_max_len_utf8_utf8_utf8(context, text, text_len, from_str, |
| 2040 | from_str_len, to_str, to_str_len, |
| 2041 | static_cast<gdv_int32>(max_length), out_len); |
| 2042 | } |
| 2043 | |
| 2044 | // Returns the quoted string (Includes escape character for any single quotes) |
| 2045 | // E.g. DONT -> 'DONT' |