StrForeachInRangeIdx

Table of Contents

StrForeachInRangeIdx

Description

Iterate over characters in a specific range of the given Str str at each index idx. This macro is a direct alias for VecForeachInRangeIdx specialized for Str. The variables chr and idx are declared and defined by the underlying macro.

Parameters

NameDirectionDescription
strin,outStr to iterate over.
chrinName of variable to be used which’ll contain character at iterated index idx.
idxinName of variable to be used for iterating over indices.
startinStarting index (inclusive).
endinEnding index (exclusive).

Success

The body is executed for each character of the Str str from the start index to the end-1 index.

Failure

If the Str str is NULL, its length is zero, or the range is invalid, the loop body will not be executed. Any access to an invalid index will result in a fatal log message and program termination.

Usage example (Cross-references)

    // Deadend test: Make idx go out of bounds in StrForeachInRangeIdx by shrinking string during iteration
    bool test_str_foreach_out_of_bounds_access(void) {
    printf("Testing StrForeachInRangeIdx where idx goes out of bounds (should crash)\n");
    
    Str s = StrInitFromZstr("Hello World!"); // 12 characters
    // Even if we shrink the string, the loop will continue until idx reaches the fixed end
    size original_length = s.length; // Capture this as 12
    StrForeachInRangeIdx(&s, chr, idx, 0, original_length, {
    printf("Accessing idx %zu (s.length=%zu): '%c'\n", idx, s.length, chr);
    // Deadend test: Make idx go out of bounds in StrForeachInRangeIdx by deleting characters
    bool test_str_foreach_idx_out_of_bounds_access(void) {
    printf("Testing StrForeachInRangeIdx with character deletion where idx goes out of bounds (should crash)\n");
    
    Str s = StrInitFromZstr("Programming"); // 11 characters
    // when we delete characters during iteration
    size original_length = s.length; // Capture this as 11
    StrForeachInRangeIdx(&s, chr, idx, 0, original_length, {
    printf("Accessing idx %zu (s.length=%zu): '%c'\n", idx, s.length, chr);
    // Test StrForeachInRangeIdx macro
    bool test_str_foreach_in_range_idx(void) {
    printf("Testing StrForeachInRangeIdx\n");
    
    Str s = StrInitFromZstr("Hello World");
    // Build a new string by iterating through a range of characters with indices
    Str result = StrInit();
    StrForeachInRangeIdx(&s, chr, idx, 6, 11, {
    // Append the character and its index to the result string
    StrWriteFmt(&result, "{c}{}", chr, idx);
    // Test with empty range
    Str empty_result = StrInit();
    StrForeachInRangeIdx(&s, chr, idx, 3, 3, {
    // This block should not execute
    StrPushBack(&empty_result, chr);

Share :