Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them.
Page: /drakestapleton/klib
# klib
[Ported from github.com/attractivechaos/klib] added block arena
Brought by drakestapleton
Unfinished: not checked yet
There is no published receipt of a rebuild from its source yet. What a receipt is
Get this repository
Git over HTTPS
`git clone --no-checkout https://interplane.io/projects/klib/repo.git klib && git -C klib checkout --detach 97a0fcb790b43b9e5da8994f4671021fec036f19`
Source archive of `97a0fcb790b43b9e5da8994f4671021fec036f19`
Download ZIP · tar.gz
Sign in to star 0 stars 0 watching
About Files History Releases Proposed changes Issues For developers
README.md
# Klib: a Generic Library in C
## Overview
Klib is a standalone and lightweight C library distributed under [MIT/X11 license]1 . Most components are independent of external libraries, except the standard C library, and independent of each other. To use a component of this library, you only need to copy a couple of files to your source code tree without worrying about library dependencies.
Klib strives for efficiency and a small memory footprint. Some components, such as khash.h, kbtree.h, ksort.h and kvec.h, are among the most efficient implementations of similar algorithms or data structures in all programming languages, in terms of both speed and memory use.
A new documentation is available here which includes most information in this README file.
#### Common components
- khash.h : generic hash table with open addressing.
- kbtree.h : generic search tree based on B-tree .
- kavl.h : generic intrusive AVL tree .
- ksort.h : generic sort, including introsort , merge sort , heap sort , comb sort , Knuth shuffle and the k-small algorithm.
- kseq.h : generic stream buffer and a FASTA /FASTQ format parser.
- kvec.h: generic dynamic array.
- klist.h: generic single-linked list and memory pool .
- kstring.{h,c}: basic string library.
- kmath.{h,c}: numerical routines including MT19937-64 pseudorandom generator , basic nonlinear programming and a few special math functions.
- ketopt.h : portable command-line argument parser with getopt_long-like API.
#### Components for more specific use cases
- ksa.c: constructing suffix arrays for strings with multiple sentinels, based on a revised SAIS algorithm .
- knetfile.{h,c}: random access to remote files on HTTP or FTP.
- kopen.c: smart stream opening.
- khmm.{h,c}: basic HMM library.
- ksw.(h,c}: Striped Smith-Waterman algorithm .
- knhx.{h,c}: Newick tree format parser.
## Methodology
For the implementation of generic containers , klib extensively uses C macros. To use these data structures, we usually need to instantiate methods by expanding a long macro. This makes the source code look unusual or even ugly and adds difficulty to debugging. Unfortunately, for efficient generic programming in C that lacks template , using macros is the only solution. Only with macros, we can write a generic container which, once instantiated, compete with a type-specific container in efficiency. Some generic libraries in C, such as Glib , use the `void*` type to implement containers. These implementations are usually slower and use more memory than klib (see this benchmark ).
To effectively use klib, it is important to understand how it achieves generic programming. We will use the hash table library as an example:
```
#include "khash.h"
KHASH_MAP_INIT_INT(m32, char) // instantiate structs and methods
int main() {
int ret, is_missing;
khint_t k;
khash_t(m32) *h = kh_init(m32); // allocate a hash table
k = kh_put(m32, h, 5, &ret); // insert a key to the hash table
if (!ret) kh_del(m32, h, k);
kh_value(h, k) = 10; // set the value
k = kh_get(m32, h, 10); // query the hash table
is_missing = (k == kh_end(h)); // test if the key is present
k = kh_get(m32, h, 5);
kh_del(m32, h, k); // remove a key-value pair
for (k = kh_begin(h); k != kh_end(h); ++k) // traverse
if (kh_exist(h, k)) // test if a bucket contains data
kh_value(h, k) = 1;
kh_destroy(m32, h); // deallocate the hash table
return 0;
}
```
In this example, the second line instantiates a hash table with `unsigned` as the key type and `char` as the value type. `m32` names such a type of hash table. All types and functions associated with this name are macros, which will be explained later. Macro `kh_init()` initiates a hash table and `kh_destroy()` frees it. `kh_put()` inserts a key and returns the iterator (or the position) in the hash table. `kh_get()` and `kh_del()` get a key and delete an element, respectively. Macro `kh_exist()` tests if an iterator (or a position) is filled with data.
An immediate question is this piece of code does not look like a valid C program (e.g. lacking semicolon, assignment to an apparent function call and apparent undefined `m32` 'variable'). To understand why the code is correct, let's go a bit further into the source code of `khash.h`, whose skeleton looks like:
```
#define KHASH_INIT(name, SCOPE, key_t, val_t, is_map, _hashf, _hasheq) \
typedef struct { \
int n_buckets, size, n_occupied, upper_bound; \
unsigned *flags; \
key_t *keys; \
val_t *vals; \
} kh_##name##_t; \
SCOPE inline kh_##name##_t *init_##name() { \
return (kh_##name##_t*)calloc(1, sizeof(kh_##name##_t)); \
} \
SCOPE inline int get_##name(kh_##name##_t *h, key_t k) \
... \
SCOPE inline void destroy_##name(kh_##name##_t *h) { \
if (h) { \
free(h->keys); free(h->flags); free(h->vals); free(h); \
} \
}
#define _int_hf(key) (unsigned)(key)
#define _int_heq(a, b) (a == b)
#define khash_t(name) kh_##name##_t
#define kh_value(h, k) ((h)->vals[k])
#define kh_begin(h, k) 0
#define kh_end(h) ((h)->n_buckets)
#define kh_init(name) init_##name()
#define kh_get(name, h, k) get_##name(h, k)
#define kh_destroy(name, h) destroy_##name(h)
...
#define KHASH_MAP_INIT_INT(name, val_t) \
KHASH_INIT(name, static, unsigned, val_t, is_map, _int_hf, _int_heq)
```
`KHASH_INIT()` is a huge macro defining all the structs and methods. When this macro is called, all the code inside it will be inserted by the [C preprocess]37 to the place where it is called. If the macro is called multiple times, multiple copies of the code will be inserted. To avoid naming conflict of hash tables with different key-value types, the library uses [token concatenation]36 , which is a preprocessor feature whereby we can substitute part of a symbol based on the parameter of the macro. In the end, the C preprocessor will generate the following code and feed it to the compiler (macro `kh_exist(h,k)` is a little complex and not expanded for simplicity):
```
typedef struct {
int n_buckets, size, n_occupied, upper_bound;
unsigned *flags;
unsigned *keys;
char *vals;
} kh_m32_t;
static inline kh_m32_t *init_m32() {
return (kh_m32_t*)calloc(1, sizeof(kh_m32_t));
}
static inline int get_m32(kh_m32_t *h, unsigned k)
...
static inline void destroy_m32(kh_m32_t *h) {
if (h) {
free(h->keys); free(h->flags); free(h->vals); free(h);
}
}
int main() {
int ret, is_missing;
khint_t k;
kh_m32_t *h = init_m32();
k = put_m32(h, 5, &ret);
if (!ret) del_m32(h, k);
h->vals[k] = 10;
k = get_m32(h, 10);
is_missing = (k == h->n_buckets);
k = get_m32(h, 5);
del_m32(h, k);
for (k = 0; k != h->n_buckets; ++k)
if (kh_exist(h, k)) h->vals[k] = 1;
destroy_m32(h);
return 0;
}
```
This is the C program we know.
From this example, we can see that macros and the C preprocessor plays a key role in klib. Klib is fast partly because the compiler knows the key-value type at the compile time and is able to optimize the code to the same level as type-specific code. A generic library written with `void*` will not get such performance boost.
Massively inserting code upon instantiation may remind us of C++'s slow compiling speed and huge binary size when STL/boost is in use. Klib is much better in this respect due to its small code size and component independency. Inserting several hundreds lines of code won't make compiling obviously slower.
## Resources
- Library documentation, if present, is available in the header files. Examples can be found in the test/ directory.
- Obsolete documentation of the hash table library can be found at SourceForge . This README is partly adapted from the old documentation.
- Blog post describing the hash table library.
- Blog post on why using `void*` for generic programming may be inefficient.
- Blog post on the generic stream buffer.
- Blog post evaluating the performance of `kvec.h`.
- Blog post arguing B-tree may be a better data structure than a binary search tree.
- Blog post evaluating the performance of `khash.h` and `kbtree.h` among many other implementations. An older version of the benchmark is also available.
- Blog post benchmarking internal sorting algorithms and implementations.
- Blog post on the k-small algorithm.
- Blog post on the Hooke-Jeeve's algorithm for nonlinear programming.
## For developers: proof and records
The full record of this project. Words that are used only here are explained once:
ID
The project's permanent id on Interplane: the SHA-256 of its first signed record. This one is `git:ae6891467e7951ba0497a82bae048328fdab2b7616f5684d7fbab01be043ceeb`. Its old id, kept only so that old links still work: `z3bQJ4fuRXymu7MN2DW3TV6moUVDK`.
Owner
The key that signs every record of the project. This forge lists the project under drakestapleton; its key is `SHA256:qg3vxoE9ul3Cgk5heosQvPmO9pqIJNsdcsGJ2cHghTs`.
Refs and HEAD
Refs are the names that point at versions: branches and tags. HEAD is the version a fresh copy starts from, the newest commit of the default branch.
Patch
A proposed change, reviewed before it is merged. This forge does not show proposed changes from its own store yet. The list is under Proposed changes .
Receipt
A public record that someone checked a claim, with the fingerprint of its evidence file. The state at the top of this page is read from the list at interplane.io/receipts . This project has no receipt in that list yet.
Clones and fetches over HTTPS: 0 by visitors (git smart-HTTP `info/refs` requests answered 200 in the front-door download log; our own addresses and bots left out; since 2026-11-08) · not measured `git-upload-pack` requests from all clients (the source of this count is retired)
Downloads: 2 by visitors (2 source archives, 0 release assets; forged access log; our own addresses left out; since 2026-11-07)
commit `97a0fcb790b43b9e5da8994f4671021fec036f19` Branches Tags History
`97a0fcb` added block arena Attractive Chaos committed 2025-12-22
```
cpp/
lua/
test/
.gitignore 470
LICENSE.txt 1105
README.md 12137
bgzf.c 17083
bgzf.h 5861
kalloc.c 8054
kalloc.h 2630
kavl-lite.h 9859
kavl.h 13752
kbarena.c 2922
kbarena.h 921
kbit.h 1087
kbtree.h 17212
kdq.h 4272
keigen.c 3724
keigen.h 1571
ketopt.h 3975
kexpr.c 16936
kexpr.h 2005
kgraph.h 2793
khash.h 21543
khashl.h 20838
khmm.c 10825
khmm.h 2929
klist.h 5086
kmath.c 13757
kmath.h 1075
kmempool.c 2017
kmempool.h 240
knetfile.c 18467
knetfile.h 1611
knhx.c 4028
knhx.h 570
kopen.c 9151
krmq.h 16430
krng.h 1147
ksa.c 8834
kseq.h 9223
kson.c 6782
kson.h 1358
ksort.h 12275
kstring.c 6185
kstring.h 7045
ksw.c 22211
ksw.h 2731
kthread.c 6854
kthread.h 444
kurl.c 16844
kurl.h 1303
kvec.h 2880
```
Every record: History (commits) · Branches · Tags · Releases, with the SHA-256 of each download · Patches · Issues · This project as JSON