given a list of strings and an optional delimiter return a concatenation of all the strings using the given delimiter string.join(list, delimiter = '') -> string
| 214 | // return a concatenation of all the strings using the given delimiter |
| 215 | // string.join(list, delimiter = '') -> string |
| 216 | SIValue AR_JOIN(SIValue *argv, int argc, void *private_data) { |
| 217 | SIValue list = argv[0]; |
| 218 | if(SI_TYPE(list) == T_NULL) { |
| 219 | return SI_NullVal(); |
| 220 | } |
| 221 | |
| 222 | char *delimiter = ""; |
| 223 | if(argc == 2) { |
| 224 | delimiter = argv[1].stringval; |
| 225 | } |
| 226 | |
| 227 | int str_len = 0; // output string length |
| 228 | uint32_t n = SIArray_Length(list); // number of strings to join |
| 229 | size_t delimeter_len = strlen(delimiter); // length of the delimiter |
| 230 | |
| 231 | //-------------------------------------------------------------------------- |
| 232 | // compute required string length |
| 233 | //-------------------------------------------------------------------------- |
| 234 | |
| 235 | // delimeter length is added between each string |
| 236 | if(n >= 2) { |
| 237 | if(safe_mul(delimeter_len, n - 1, &str_len)) { |
| 238 | ErrorCtx_SetError("String overflow"); |
| 239 | return SI_NullVal(); |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | // acount for each string length |
| 244 | for(uint i = 0; i < n; i++) { |
| 245 | SIValue str = SIArray_Get(list, i); |
| 246 | if(SI_TYPE(str) != T_STRING) { |
| 247 | // all elements in the list should be string. |
| 248 | Error_SITypeMismatch(str, T_STRING); |
| 249 | return SI_NullVal(); |
| 250 | } |
| 251 | |
| 252 | if(safe_add(str_len, strlen(str.stringval), &str_len)) { |
| 253 | ErrorCtx_SetError("String overflow"); |
| 254 | return SI_NullVal(); |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | // acoun for null terminator |
| 259 | if(safe_add(str_len, 1, &str_len)) { |
| 260 | ErrorCtx_SetError("String overflow"); |
| 261 | return SI_NullVal(); |
| 262 | } |
| 263 | |
| 264 | //-------------------------------------------------------------------------- |
| 265 | // join strings |
| 266 | //-------------------------------------------------------------------------- |
| 267 | |
| 268 | int l = 0; // current string length |
| 269 | int cur_len = 0; // offset into output string |
| 270 | char *res = rm_malloc(str_len); // output string |
| 271 | |
| 272 | for(uint i = 0; i < n - 1; i++) { |
| 273 | SIValue str = SIArray_Get(list, i); |
nothing calls this directly
no test coverage detected