| 2277 | } |
| 2278 | |
| 2279 | FORCE_INLINE |
| 2280 | const char* split_part(gdv_int64 context, const char* text, gdv_int32 text_len, |
| 2281 | const char* delimiter, gdv_int32 delim_len, gdv_int32 index, |
| 2282 | gdv_int32* out_len) { |
| 2283 | *out_len = 0; |
| 2284 | if (index < 1) { |
| 2285 | char error_message[100]; |
| 2286 | snprintf(error_message, sizeof(error_message), |
| 2287 | "Index in split_part must be positive, value provided was %d", index); |
| 2288 | gdv_fn_context_set_error_msg(context, error_message); |
| 2289 | return ""; |
| 2290 | } |
| 2291 | |
| 2292 | if (delim_len == 0 || text_len == 0) { |
| 2293 | // output will just be text if no delimiter is provided |
| 2294 | *out_len = text_len; |
| 2295 | return text; |
| 2296 | } |
| 2297 | |
| 2298 | int i = 0, match_no = 1; |
| 2299 | |
| 2300 | while (i < text_len) { |
| 2301 | // find the position where delimiter matched for the first time |
| 2302 | int match_pos = match_string(text, text_len, i, delimiter, delim_len); |
| 2303 | if (match_pos == -1 && match_no != index) { |
| 2304 | // reached the end without finding a match. |
| 2305 | return ""; |
| 2306 | } else { |
| 2307 | // Found a match. If the match number is index then return this match |
| 2308 | if (match_no == index) { |
| 2309 | int end_pos = match_pos - delim_len; |
| 2310 | |
| 2311 | if (match_pos == -1) { |
| 2312 | // end position should be last position of the string as we have the last |
| 2313 | // delimiter |
| 2314 | end_pos = text_len; |
| 2315 | } |
| 2316 | |
| 2317 | *out_len = end_pos - i; |
| 2318 | return text + i; |
| 2319 | } else { |
| 2320 | i = match_pos; |
| 2321 | match_no++; |
| 2322 | } |
| 2323 | } |
| 2324 | } |
| 2325 | |
| 2326 | return ""; |
| 2327 | } |
| 2328 | |
| 2329 | // Returns the x leftmost characters of a given string. Cases: |
| 2330 | // LEFT("TestString", 10) => "TestString" |