gitmyhub

klib

C ★ 4.7k updated 6mo ago

A standalone and lightweight C library

A fast, header-only C library providing hash tables, trees, dynamic arrays, sorting algorithms, and string utilities as single files you copy into your project with no build system or external dependencies.

Csetup: easycomplexity 3/5

Klib is a small collection of building blocks for C programs. It provides things like hash tables, sorted search trees, dynamic arrays, sorting algorithms, and string utilities in a single library with no external dependencies beyond the standard C library. Each component is contained in one or two files, so you can drop just the pieces you need directly into your own project rather than linking in a whole framework.

The library is aimed at C developers who want these common data structures at high speed and low memory use. The README claims that components like the hash table and sorting implementations compete with the best equivalents found in any programming language, in both speed and memory. It backs this up by explaining the design choice that makes this possible: the library uses C macros extensively to generate type-specific code at compile time. This is different from using a generic void pointer approach, where the compiler cannot optimize the code because it does not know the actual type being stored.

The tradeoff for that speed is that the code looks unusual. Using the hash table, for example, requires calling a macro that expands into dozens of lines of type-specific struct definitions and functions. This is not how typical library code looks, and the README acknowledges it can make code harder to read and debug. The advantage is that the compiler sees fully typed code and can optimize it as aggressively as if you had written it by hand for a specific type.

Components include a hash table with open addressing, a B-tree and an AVL tree for sorted data, several sorting algorithms including introsort and merge sort, a generic dynamic array, a linked list with a memory pool, a string library, a command-line argument parser, and a pseudorandom number generator. There are also more specialized components for reading remote files over HTTP or FTP and for parsing bioinformatics file formats.

Klib is distributed under the MIT license and has no required build system: you copy the files you want and compile them with your code.

Where it fits