| 2198 | } |
| 2199 | |
| 2200 | FORCE_INLINE |
| 2201 | const char* rpad_utf8_int32_utf8(gdv_int64 context, const char* text, gdv_int32 text_len, |
| 2202 | gdv_int32 return_length, const char* fill_text, |
| 2203 | gdv_int32 fill_text_len, gdv_int32* out_len) { |
| 2204 | // if the text length or the defined return length (number of characters to return) |
| 2205 | // is <=0, then return an empty string. |
| 2206 | return_length = std::min(max_str_length, return_length); |
| 2207 | return_length = std::max(min_str_length, return_length); |
| 2208 | if (text_len == 0 || return_length <= 0) { |
| 2209 | *out_len = 0; |
| 2210 | return ""; |
| 2211 | } |
| 2212 | |
| 2213 | // count the number of utf8 characters on text, ignoring invalid bytes |
| 2214 | int actual_text_len = utf8_length_ignore_invalid(text, text_len); |
| 2215 | |
| 2216 | if (return_length == actual_text_len || |
| 2217 | (return_length > actual_text_len && fill_text_len == 0)) { |
| 2218 | // case where the return length is same as the text's length, or if it need to |
| 2219 | // fill into text but "fill_text" is empty, then return text directly. |
| 2220 | *out_len = text_len; |
| 2221 | return text; |
| 2222 | } |
| 2223 | if (return_length < actual_text_len) { |
| 2224 | // case where it truncates the result on return length. |
| 2225 | *out_len = utf8_byte_pos(context, text, text_len, return_length); |
| 2226 | return text; |
| 2227 | } |
| 2228 | |
| 2229 | gdv_int32 chars_to_pad = return_length - actual_text_len; |
| 2230 | |
| 2231 | // FAST PATH: Single-byte fill (most common - space padding) |
| 2232 | if (fill_text_len == 1) { |
| 2233 | gdv_int32 out_len_bytes = chars_to_pad + text_len; |
| 2234 | gdv_binary ret = |
| 2235 | reinterpret_cast<gdv_binary>(gdv_fn_context_arena_malloc(context, out_len_bytes)); |
| 2236 | if (ret == nullptr) { |
| 2237 | gdv_fn_context_set_error_msg(context, |
| 2238 | "Could not allocate memory for output string"); |
| 2239 | *out_len = 0; |
| 2240 | return ""; |
| 2241 | } |
| 2242 | memcpy(ret, text, text_len); |
| 2243 | memset(ret + text_len, fill_text[0], chars_to_pad); |
| 2244 | *out_len = out_len_bytes; |
| 2245 | return ret; |
| 2246 | } |
| 2247 | |
| 2248 | // GENERAL PATH: Multi-byte fill - use evaluate_return_char_length for buffer size |
| 2249 | gdv_int32 return_char_length = evaluate_return_char_length( |
| 2250 | text_len, actual_text_len, return_length, fill_text, fill_text_len); |
| 2251 | gdv_binary ret = reinterpret_cast<gdv_binary>( |
| 2252 | gdv_fn_context_arena_malloc(context, return_char_length)); |
| 2253 | if (ret == nullptr) { |
| 2254 | gdv_fn_context_set_error_msg(context, "Could not allocate memory for output string"); |
| 2255 | *out_len = 0; |
| 2256 | return ""; |
| 2257 | } |