* @brief Extracts a substring from the given String object. * * This function creates a new String object containing a substring of the original string starting at the specified * position and having the specified length. If the length exceeds the bounds of the original string, * the substring will be shortened accordingly. * * @param str The original String object from which the substring
| 477 | * @return A new String object containing the substring, or NULL if an error occurs. |
| 478 | */ |
| 479 | String* string_substr(String* str, size_t pos, size_t len) { |
| 480 | STRING_LOG("[string_substr]: Entering function with pos=%zu, len=%zu.\n", pos, len); |
| 481 | |
| 482 | if (str == NULL) { |
| 483 | STRING_LOG("[string_substr]: Error: The String object is NULL.\n"); |
| 484 | return NULL; |
| 485 | } |
| 486 | if (pos >= str->size) { |
| 487 | STRING_LOG("[string_substr]: Error: Position out of bounds (pos=%zu, size=%zu).\n", pos, str->size); |
| 488 | return NULL; |
| 489 | } |
| 490 | |
| 491 | // Adjust len if it goes beyond the end of the string |
| 492 | if (pos + len > str->size) { |
| 493 | len = str->size - pos; |
| 494 | } |
| 495 | |
| 496 | STRING_LOG("[string_substr]: Allocating memory for substring (len=%zu).\n", len); |
| 497 | String* substr = string_create(NULL); |
| 498 | if (substr == NULL) { |
| 499 | STRING_LOG("[string_substr]: Error: Memory allocation failed for substring.\n"); |
| 500 | return NULL; |
| 501 | } |
| 502 | |
| 503 | if (len + 1 > substr->capacitySize) { |
| 504 | char* newData = (char*)memory_pool_allocate(substr->pool, len + 1); |
| 505 | if (!newData) { |
| 506 | STRING_LOG("[string_substr]: Error: Pool allocation failed for dataStr.\n"); |
| 507 | string_deallocate(substr); |
| 508 | return NULL; |
| 509 | } |
| 510 | substr->dataStr = newData; |
| 511 | substr->capacitySize = len + 1; |
| 512 | } |
| 513 | |
| 514 | STRING_LOG("[string_substr]: Copying substring from pos=%zu, len=%zu.\n", pos, len); |
| 515 | memcpy(substr->dataStr, str->dataStr + pos, len); |
| 516 | substr->dataStr[len] = '\0'; |
| 517 | substr->size = len; |
| 518 | |
| 519 | STRING_LOG("[string_substr]: Successfully created substring.\n"); |
| 520 | return substr; |
| 521 | } |
| 522 | |
| 523 | |
| 524 | /** |
nothing calls this directly
no test coverage detected