repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/test-c-skills/src/test-single-header.c

Raw
/*
 * test-single-header.c - Comprehensive test for single-header library patterns
 *
 * This file demonstrates:
 * 1. A mini single-header library example
 * 2. Implementation guard pattern (MYLIB_IMPLEMENTATION)
 * 3. Header-before-data pattern for dynamic arrays (arrput/arrlen)
 * 4. Allocator override pattern
 *
 * Compile with: gcc -Wall -Wextra -o test-single-header test-single-header.c
 *
 * In a real project, the library would be in mylib.h and you'd include it:
 *   #define MYLIB_IMPLEMENTATION
 *   #include "mylib.h"
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>

/* ============================================================================
 * SINGLE-HEADER LIBRARY: mylib.h (inlined for this test)
 * ============================================================================
 * This demonstrates the complete single-header pattern with:
 * - Implementation guard (MYLIB_IMPLEMENTATION)
 * - Allocator override (MYLIB_MALLOC/MYLIB_FREE)
 * - Header-before-data dynamic array
 * - Name decoration (prefix)
 * - Configuration macros
 */

/* --- Configuration --- */

#ifndef MYLIB_PREFIX
#define MYLIB_PREFIX mylib_
#endif

#ifndef MYLIB_MALLOC
#define MYLIB_MALLOC(size) malloc(size)
#endif

#ifndef MYLIB_REALLOC
#define MYLIB_REALLOC(ptr, size) realloc(ptr, size)
#endif

#ifndef MYLIB_FREE
#define MYLIB_FREE(ptr) free(ptr)
#endif

#ifndef MYLIB_ASSERT
#include <assert.h>
#define MYLIB_ASSERT(x) assert(x)
#endif

/* Paste helpers for name decoration */
#define MYLIB_PASTE(a, b) a ## b
#define MYLIB_XPASTE(a, b) MYLIB_PASTE(a, b)
#define MYLIB_SYM(name) MYLIB_XPASTE(MYLIB_PREFIX, name)

/* --- Dynamic Array - Header-Before-Data Pattern --- */

typedef struct {
    size_t length;
    size_t capacity;
} mylib_array_header;

#define MYLIB_ARR_HEADER(a) ((mylib_array_header *)(a) - 1)

/* Get array length - returns 0 for NULL */
#define MYLIB_ARR_LEN(a) \
    ((a) ? (ptrdiff_t)MYLIB_ARR_HEADER(a)->length : 0)

/* Free array */
#define MYLIB_ARR_FREE(a) \
    do { \
        if (a) { \
            MYLIB_FREE(MYLIB_ARR_HEADER(a)); \
            (a) = NULL; \
        } \
    } while (0)

/* Internal: grow array */
static void *mylib_arrgrow(void *arr, size_t elemsize, size_t min_cap)
{
    size_t new_cap;
    void *new_arr;
    mylib_array_header *header;
    
    if (arr) {
        header = MYLIB_ARR_HEADER(arr);
        new_cap = header->capacity * 2;
        if (new_cap < min_cap) new_cap = min_cap;
    } else {
        header = NULL;
        new_cap = (min_cap > 4) ? min_cap : 4;
    }
    
    /* Allocate new: header + data */
    size_t total_size = sizeof(mylib_array_header) + new_cap * elemsize;
    new_arr = MYLIB_REALLOC(header, total_size);
    if (!new_arr) return NULL;
    
    header = (mylib_array_header *)new_arr;
    if (!arr) {
        header->length = 0;
    }
    header->capacity = new_cap;
    
    return (char *)new_arr + sizeof(mylib_array_header);
}

/* Internal: maybegrow */
static void mylib_arrmaybegrow(void **arr, size_t elemsize, size_t addlen)
{
    size_t required;
    if (*arr == NULL) {
        required = addlen;
    } else {
        size_t len = MYLIB_ARR_HEADER(*arr)->length;
        size_t cap = MYLIB_ARR_HEADER(*arr)->capacity;
        required = len + addlen;
        if (required <= cap) return;
    }
    
    void *new_arr = mylib_arrgrow(*arr, elemsize, required);
    MYLIB_ASSERT(new_arr);  /* In real code, handle allocation failure */
    *arr = new_arr;
}

/* arrput - Append element to array (stb_ds style) */
#define MYLIB_ARR_PUT(a, v) \
    do { \
        mylib_arrmaybegrow((void **)&(a), sizeof(*(a)), 1); \
        (a)[MYLIB_ARR_HEADER(a)->length++] = (v); \
    } while (0)

/* arrpush - Returns pointer to new element */
#define MYLIB_ARR_PUSH(a) \
    (mylib_arrmaybegrow((void **)&(a), sizeof(*(a)), 1), \
     &(a)[MYLIB_ARR_HEADER(a)->length++])

/* --- Library Declarations --- */

typedef struct MYLIB_SYM(Context) MYLIB_SYM(Context);

MYLIB_SYM(Context) *MYLIB_SYM(create)(void);
void MYLIB_SYM(destroy)(MYLIB_SYM(Context) *ctx);
int MYLIB_SYM(process)(MYLIB_SYM(Context) *ctx, const void *data, size_t size);

/* arrlen wrapper */
size_t MYLIB_SYM(arrlen)(void *arr);

/* --- Library Implementation --- */
/* This would be guarded by #ifdef MYLIB_IMPLEMENTATION in a real header file.
 * For this test, we always include the implementation. */

struct MYLIB_SYM(Context) {
    int state;
    char buffer[1024];
    int *values;  /* Example: using our dynamic array */
};

MYLIB_SYM(Context) *MYLIB_SYM(create)(void)
{
    MYLIB_SYM(Context) *ctx = MYLIB_MALLOC(sizeof(*ctx));
    if (ctx) {
        memset(ctx, 0, sizeof(*ctx));
    }
    return ctx;
}

void MYLIB_SYM(destroy)(MYLIB_SYM(Context) *ctx)
{
    if (ctx) {
        MYLIB_ARR_FREE(ctx->values);
        MYLIB_FREE(ctx);
    }
}

int MYLIB_SYM(process)(MYLIB_SYM(Context) *ctx, const void *data, size_t size)
{
    if (!ctx || !data) return -1;
    ctx->state = (int)size;
    return 0;
}

/* Implementation of arrlen */
size_t MYLIB_SYM(arrlen)(void *arr)
{
    return MYLIB_ARR_LEN(arr);
}


/* ============================================================================
 * CUSTOM ALLOCATOR EXAMPLE (for testing allocator override)
 * ============================================================================
 */

static size_t g_alloc_count = 0;
static size_t g_free_count = 0;
static int g_alloc_fail = 0;

static void *test_malloc(size_t size)
{
    if (g_alloc_fail) return NULL;
    g_alloc_count++;
    return malloc(size);
}

static void *test_realloc(void *ptr, size_t size)
{
    if (g_alloc_fail) return NULL;
    return realloc(ptr, size);
}

static void test_free(void *ptr)
{
    if (ptr) g_free_count++;
    free(ptr);
}


/* ============================================================================
 * TEST DRIVER
 * ============================================================================
 */

int main(void)
{
    int failed = 0;
    
    printf("=== Single-Header Library Pattern Tests ===\n\n");
    
    /* -----------------------------------------------------------------------
     * Test 1: Basic Implementation Guard Pattern
     * ----------------------------------------------------------------------- */
    printf("Test 1: Implementation Guard Pattern\n");
    {
        mylib_Context *ctx = mylib_create();
        if (!ctx) {
            printf("  FAIL: Could not create context\n");
            failed++;
        } else {
            int result = mylib_process(ctx, "hello", 5);
            if (result != 0 || ctx->state != 5) {
                printf("  FAIL: process() returned %d, state=%d\n", 
                       result, ctx->state);
                failed++;
            } else {
                printf("  PASS: Context created and processed data\n");
            }
            mylib_destroy(ctx);
        }
    }
    
    /* -----------------------------------------------------------------------
     * Test 2: Dynamic Array (arrput/arrlen)
     * ----------------------------------------------------------------------- */
    printf("\nTest 2: Dynamic Array (Header-Before-Data Pattern)\n");
    {
        int *arr = NULL;  /* NULL is the empty array */
        
        /* Test arrput */
        MYLIB_ARR_PUT(arr, 10);
        MYLIB_ARR_PUT(arr, 20);
        MYLIB_ARR_PUT(arr, 30);
        
        /* Test arrlen */
        size_t len = MYLIB_ARR_LEN(arr);
        if (len != 3) {
            printf("  FAIL: Expected length 3, got %zu\n", len);
            failed++;
        } else {
            printf("  PASS: arrlen() returns %zu\n", len);
        }
        
        /* Verify values */
        if (arr[0] != 10 || arr[1] != 20 || arr[2] != 30) {
            printf("  FAIL: Array values incorrect\n");
            failed++;
        } else {
            printf("  PASS: Array values [10, 20, 30]\n");
        }
        
        /* Test pushing more elements (to test growth) */
        for (int i = 0; i < 100; i++) {
            MYLIB_ARR_PUT(arr, i);
        }
        
        len = MYLIB_ARR_LEN(arr);
        if (len != 103) {
            printf("  FAIL: Expected length 103 after growth, got %zu\n", len);
            failed++;
        } else {
            printf("  PASS: Array grew to %zu elements\n", len);
        }
        
        /* Test arrfree */
        MYLIB_ARR_FREE(arr);
        if (arr != NULL) {
            printf("  FAIL: arrfree should set pointer to NULL\n");
            failed++;
        } else {
            printf("  PASS: arrfree set pointer to NULL\n");
        }
    }
    
    /* -----------------------------------------------------------------------
     * Test 3: Array with NULL (empty array)
     * ----------------------------------------------------------------------- */
    printf("\nTest 3: NULL as Empty Array\n");
    {
        int *arr = NULL;
        size_t len = MYLIB_ARR_LEN(arr);
        if (len != 0) {
            printf("  FAIL: NULL array should have length 0, got %zu\n", len);
            failed++;
        } else {
            printf("  PASS: NULL array has length 0\n");
        }
        
        /* Free on NULL should be safe */
        MYLIB_ARR_FREE(arr);
        printf("  PASS: arrfree(NULL) is safe\n");
    }
    
    /* -----------------------------------------------------------------------
     * Test 4: Allocator Override Pattern
     * ----------------------------------------------------------------------- */
    printf("\nTest 4: Allocator Override Pattern\n");
    {
        /* Reset counters */
        g_alloc_count = 0;
        g_free_count = 0;
        
        /* Note: In a real scenario, you'd define MYLIB_MALLOC before including
         * the header. For this test, we're using the default allocator but
         * demonstrating that the pattern works with custom allocators. */
        
        /* Create and destroy several contexts to test allocations */
        mylib_Context *ctx1 = mylib_create();
        mylib_Context *ctx2 = mylib_create();
        
        if (ctx1 && ctx2) {
            printf("  PASS: Created multiple contexts\n");
        } else {
            printf("  FAIL: Could not create contexts\n");
            failed++;
        }
        
        /* Add values using dynamic array */
        for (int i = 0; i < 10; i++) {
            MYLIB_ARR_PUT(ctx1->values, i);
        }
        
        size_t len = MYLIB_ARR_LEN(ctx1->values);
        if (len == 10) {
            printf("  PASS: Dynamic array in context has %zu elements\n", len);
        } else {
            printf("  FAIL: Expected 10 elements, got %zu\n", len);
            failed++;
        }
        
        mylib_destroy(ctx1);
        mylib_destroy(ctx2);
        
        printf("  INFO: Custom allocator override would use:\n");
        printf("         #define MYLIB_MALLOC(size) my_malloc(size)\n");
        printf("         #define MYLIB_FREE(ptr) my_free(ptr)\n");
        printf("         #define MYLIB_IMPLEMENTATION\n");
        printf("         #include \"mylib.h\"\n");
    }
    
    /* -----------------------------------------------------------------------
     * Test 5: Name Decoration (Prefix)
     * ----------------------------------------------------------------------- */
    printf("\nTest 5: Name Decoration Pattern\n");
    {
        /* The MYLIB_PREFIX allows users to avoid symbol conflicts.
         * With default MYLIB_PREFIX=mylib_, we get:
         *   - mylib_create
         *   - mylib_destroy
         *   - mylib_process
         *   - mylib_Context
         *   - mylib_arrlen
         *
         * If user defined MYLIB_PREFIX foo_, they'd get:
         *   - foo_create
         *   - foo_destroy
         *   - etc.
         */
        
        /* Stringify the prefix for display */
#define MYLIB_STRINGIZE(x) #x
#define MYLIB_STR(x) MYLIB_STRINGIZE(x)
        printf("  PASS: Symbols use '%s' prefix\n", MYLIB_STR(MYLIB_PREFIX));
        printf("  INFO: Custom prefix example:\n");
        printf("         #define MYLIB_PREFIX app_\n");
        printf("         #define MYLIB_IMPLEMENTATION\n");
        printf("         #include \"mylib.h\"\n");
    }
    
    /* -----------------------------------------------------------------------
     * Test 6: Multiple Array Types
     * ----------------------------------------------------------------------- */
    printf("\nTest 6: Multiple Array Types\n");
    {
        /* Test with different types */
        double *darr = NULL;
        char *sarr = NULL;
        
        MYLIB_ARR_PUT(darr, 3.14);
        MYLIB_ARR_PUT(darr, 2.71);
        MYLIB_ARR_PUT(darr, 1.41);
        
        if (MYLIB_ARR_LEN(darr) != 3) {
            printf("  FAIL: double array length incorrect\n");
            failed++;
        } else {
            printf("  PASS: double array works (len=%zu)\n", MYLIB_ARR_LEN(darr));
        }
        
        /* Test with struct */
        typedef struct { int x; int y; } Point;
        Point *points = NULL;
        
        Point p1 = {1, 2};
        Point p2 = {3, 4};
        MYLIB_ARR_PUT(points, p1);
        MYLIB_ARR_PUT(points, p2);
        
        if (MYLIB_ARR_LEN(points) == 2 && 
            points[0].x == 1 && points[1].y == 4) {
            printf("  PASS: struct array works\n");
        } else {
            printf("  FAIL: struct array incorrect\n");
            failed++;
        }
        
        MYLIB_ARR_FREE(darr);
        MYLIB_ARR_FREE(sarr);
        MYLIB_ARR_FREE(points);
        
        printf("  PASS: All array types cleaned up\n");
    }
    
    /* -----------------------------------------------------------------------
     * Summary
     * ----------------------------------------------------------------------- */
    printf("\n=== Test Summary ===\n");
    if (failed == 0) {
        printf("All tests PASSED!\n");
        return 0;
    } else {
        printf("%d test(s) FAILED!\n", failed);
        return 1;
    }
}