Skip to content

ListRemove

Description

Remove the element at idx and optionally move its value out to val.

Parameters

Name Direction Description
l in,out List handle.
val out Optional destination for the removed element. Pass NULL to discard it (the configured copy_deinit is invoked instead).
idx in Position in [0, length).

Success

Returns to the caller. The node at position idx is unlinked and its allocator-owned storage freed; list length shrinks by one. When val is non-NULL, the removed value is memcopied into *val and ownership transfers to the caller. When val is NULL and copy_deinit is configured, the handler is invoked on the removed element.

Failure

Function cannot fail. An out-of-range idx is a caller bug and aborts via LOG_FATAL.

Usage example (Cross-references)

Usage examples (Cross-references)
                if (idx < ListLen(list)) {
                    i32 removed;
                    ListRemove(list, &removed, idx);
                }
                break;
    
    static bool test_list_remove_and_pop(void) {
        WriteFmt("Testing ListRemove and pop helpers\n");
    
        DefaultAllocator alloc = DefaultAllocatorInit();
        ListPushBackR(&list, 40);
    
        ListRemove(&list, &removed, 1);
        bool result = (removed == 20);
        result      = result && list_matches(GENERIC_LIST(&list), (const int[]) {10, 30, 40}, 3);
        result      = result && list_matches(GENERIC_LIST(&list), (const int[]) {7, 8, 9}, 3);
    
        ListRemove(&list, &removed, 0);
        result = result && (removed == 7);
        result = result && (g_copy_deinit_count == 0);
    
    static bool test_list_remove_out_of_range_fails(void) {
        WriteFmt("Testing ListRemove out of range\n");
    
        List(int) list = ListInit(get_test_alloc());
        List(int) list = ListInit(get_test_alloc());
        ListPushBackR(&list, 10);
        ListRemove(&list, NULL, 1);
    
        return false;
    /// TAGS: List, Remove, Pop, Front
    ///
    #define ListPopFront(l, val) ListRemove((l), (val), 0)
    
    ///
    /// TAGS: List, Remove, Pop, Back
    ///
    #define ListPopBack(l, val) ListRemove((l), (val), (l)->length - 1)
    
    ///
    /// TAGS: List, Delete
    ///
    #define ListDelete(l, idx) ListRemove((l), NULL, (idx))
    
    ///
Last updated on