cbase 1.50.0
C/C++ Static Template
Loading...
Searching...
No Matches
cbase

cbase is a high-performance, zero-dependency foundational framework for modern C development.

Designed as a robust, production-ready starting point for enterprise infrastructure, proprietary engines, and systems-level applications, cbase replaces standard C library abstractions (such as malloc, free, and null-terminated strings) with modern, safe, and highly efficient paradigms. It enforces data-oriented design, predictable memory access patterns, and strict architectural boundaries while maintaining the raw execution speed and compilation simplicity of C.

Design Philosophy

The architecture of cbase is built strictly upon the following engineering principles:

  1. Explicit Memory Ownership: The standard heap (malloc/free) is entirely bypassed in favor of localized, virtual-memory-backed arenas. Allocation lifetimes are tied to systemic scopes rather than individual objects.
  2. Zero-Cost Abstractions: Structures like string slices and linked-list string builders manipulate pointers and offsets directly, avoiding hidden heap allocations, buffer overflows, and $O(N)$ length computations.
  3. C++ Interoperability: The entire codebase is wrapped in explicit C_LINKAGE blocks, allowing seamless ingestion by C++ compilers (such as MSVC, Clang, or GCC) without name-mangling penalties.
  4. Zero External Dependencies: The core framework relies exclusively on platform-specific virtual memory APIs and a minimal subset of the standard library, guaranteeing high portability and deterministic build times.

Core Architecture

Memory Subsystem (mem_)

The memory module abstracts standard operating system paging (VirtualAlloc on Windows, mmap on POSIX) into high-performance linear allocators.

  • Virtual Memory Arenas (MemArena): Reserves massive contiguous blocks of virtual address space directly from the operating system. Physical RAM is dynamically committed exclusively as the allocation pointer linearly advances.
  • Transient Scratch Memory (MemArenaTemp): Provides snapshotting and rewinding capabilities for arena states. This enables zero-fragmentation scratch allocations for intermediate processing without ever calling a memory-free routine.
  • Generic Allocator Interface (MemAllocator): A formalized vtable interface that allows core data structures to dynamically accept either linear arenas or general-purpose allocators depending on the algorithmic requirements.

Base Subsystem (base_)

The base module provides foundational primitives, type definitions, and string manipulation utilities.

  • Sized String Slices (String8): Safe, pointer-and-length pairs replacing standard C-strings. Enables $O(1)$ string slicing, chopping, and manipulation with strict bounds-checking and zero memory allocation.
  • Arena-Backed String Builder (StringBuilder): Accumulates string segments as singly-linked nodes using transient scratch memory. Upon completion, it seamlessly materializes a perfectly-sized, contiguous buffer into a target permanent arena.
  • Thread-Safe Logging (BaseLog): A comprehensive, leveled logging infrastructure (TRACE through FATAL). It supports custom output sinks (console, files, user callbacks), user-defined thread synchronization mechanisms, and ANSI terminal formatting.
  • Fixed-Width Types (base_types.h): Standardizes primitive types (u8, i32, f64, usize) across all compilers and architectures for strict byte-alignment guarantees.

Testing Framework (test.h)

A lightweight, single-header unit testing suite built directly into the framework. It features automatic test execution, precise microsecond-level timing, failure message buffering, and formatted test suite summaries.


Directory Architecture

The repository is strictly organized to separate interface from implementation, ensuring clean inclusion in parent projects.

cbase/
├── include/ # Public API surface (Headers only)
│ ├── base/ # Foundational types, macros, strings, and logging
│ ├── memory/ # Virtual memory wrappers and allocator vtables
│ └── test/ # Zero-dependency, single-header unit testing framework
├── src/ # Internal implementations (.c files)
│ ├── base/ # String builders, loggers, and base systems
│ └── memory/ # OS-specific memory mappings and arena logic
├── test/ # Comprehensive test suites
├── docs/ # Doxygen config and usage guides
│ └── guides/ # In-depth architectural documentation
├── build.bat # Unified Windows build & format script
├── build.sh # Unified Unix build & format script
└── CMakeLists.txt # Root CMake configuration

Roadmap

  • Base Primitives (Exact-width types, Math Macros, Linkage rules)
  • Logging Subsystem (Thread-safe, leveled, multi-sink)
  • Automated Testing Suite (Microsecond timing, colored output)
  • Memory & Allocators
    • OS Virtual Memory Wrapper (VirtualAlloc/mmap)
    • General-Purpose Heap Allocator (MemGpAlloc)
    • Pool Allocator
  • Data Structures & Algorithms
    • Intrusive Linked Lists
    • Array Lists
    • Stacks & Queues
    • Hash Maps
    • Interned String Table

Usage Examples

The Scratch Arena Pattern

cbase mandates explicit memory ownership. The following example demonstrates generating a dynamically formatted string with zero heap fragmentation and practical $O(1)$ allocation overhead.

int main(void) {
// Initialize a persistent arena and a transient scratch arena.
MemArena perm_arena = mem_arena_create(MB(4));
MemArena scratch = mem_arena_create(MB(1));
// Accumulate string segments using scratch memory for internal nodes.
StringBuilder sb = {0};
sb_append(&sb, &scratch, STR8("User Session: "));
sb_append_fmt(&sb, &scratch, "%s (ID: %d)", "SystemAdmin", 1024);
// Materialize the contiguous string explicitly into the persistent arena.
String8 final_string = sb_join(&sb, &perm_arena);
// Instantly reclaim scratch memory. Zero fragmentation penalty.
mem_arena_clear(&scratch);
// [...] Utilize final_string
mem_arena_release(&perm_arena);
mem_arena_release(&scratch);
return 0;
}
Sized UTF-8 string slices (String8) and manipulation utilities.
void mem_arena_clear(MemArena *arena)
Resets the arena pointer to zero, freeing all allocations in O(1).
Definition mem_arena.c:105
void mem_arena_release(MemArena *arena)
Returns all virtual memory back to the operating system.
Definition mem_arena.c:59
MemArena mem_arena_create(usize reserve_size)
Initializes a new virtual memory Arena.
Definition mem_arena.c:48
#define MB(x)
Definition base_types.h:120
static void sb_append(StringBuilder *sb, MemAllocator *alloc, String8 str)
Appends a String8 slice to the builder.
Definition str_builder.h:75
static String8 sb_join(StringBuilder *sb, MemAllocator *out_alloc)
Materializes all appended segments into a single contiguous String8.
static void sb_append_fmt(StringBuilder *sb, MemAllocator *alloc, const char *fmt,...)
Appends a printf-style formatted string to the builder.
#define STR8(s)
Wraps a C string literal into a String8 at compile time.
High-performance virtual memory Arena Allocator.
Allocator-agnostic StringBuilder for efficient string concatenation.
A virtual memory-backed linear allocator.
Definition mem_arena.h:70
A sized UTF-8 string slice.
An allocator-agnostic string builder.
Definition str_builder.h:56

Safe String Slicing

#include <stdio.h>
void parse_file_path(void) {
String8 full_path = STR8("src/memory/mem_arena.c");
// O(1) pointer arithmetic. No memory allocation occurs here.
String8 directory = str8_prefix(full_path, 11);
String8 filename = str8_suffix(full_path, 11);
String8 extension = str8_suffix(filename, 2);
// STR8_FMT ensures safe printf output without requiring null-terminators.
printf("Dir: %.*s, Ext: %.*s\n", STR8_FMT(directory), STR8_FMT(extension));
}
static String8 str8_suffix(String8 str, usize size)
Returns the last size bytes of str.
static String8 str8_prefix(String8 str, usize size)
Returns the first size bytes of str.
#define STR8_FMT(s)
Helper macro to use a String8 in a printf-style format string. Example:

Build Instructions

The framework utilizes CMake internally to generate build files, but provides unified wrapper scripts for seamless cross-platform compilation.

Windows Compilation

Execute within the x64 Native Tools Command Prompt:

build.bat [command]

Linux / macOS Compilation

Execute within a standard Unix terminal:

./build.sh [command]

Available Build Commands

Command Description
(empty) Builds the project in Debug mode.
release Builds the project in Release mode (highly optimized).
ninja Builds using the Ninja generator (Debug mode).
ninja release Builds using the Ninja generator (Release mode).
docs Generates Doxygen HTML API documentation.
format Recursively formats source code using clang-format (ignores build artifacts).
clean Removes the build directory and generated artifacts entirely.
help Displays the help menu and available arguments.

Project Integration

To integrate cbase into an existing enterprise repository or parent CMake project, add it as a subdirectory. The framework explicitly exports its include directories and link libraries.

# Add cbase to your parent CMakeLists.txt
add_subdirectory(vendor/cbase)
# Link cbase to your target executable or library
target_link_libraries(my_application PRIVATE cbase_lib)

Documentation

The official API documentation is hosted online and automatically generated from the source code via Doxygen.

Online Documentation: https://alfred-jijo.github.io/docs/cbase/

To generate the HTML manual locally for offline viewing:

  1. Execute ./build.sh docs (or build.bat docs).
  2. Navigate to build/docs/html/index.html via a web browser.

License

This software is released under the MIT License. See the LICENSE file for details.