Skip to content

Instantly share code, notes, and snippets.

@joachifm
Created September 2, 2015 21:04
Show Gist options
  • Save joachifm/e83ee9ab05ffa5d81ee6 to your computer and use it in GitHub Desktop.
Save joachifm/e83ee9ab05ffa5d81ee6 to your computer and use it in GitHub Desktop.
#pragma once
#include <stdbool.h>
/** A data table, with fast membership testing.
*
* Data tables are static arrays of data, with keys ranging from 0 to N-1. To
* distinguish unset elements from 0 values, tables also contain an array
* indicating whether a value has been set.
*
* The total size of a table is (N*sizeof(T))+N bytes. To avoid the overhead
* of using two arrays, see optional.h, which trades value range for a
* very compact representation of "optional" values.
*/
#define data_table(T, N) \
struct { bool isset[N]; int data[N]; }
#define data_table_create(T, N) \
((data_table (T, N)) { 0, 0 })
/** Set table value for key.
*/
#define data_table_set(i, x, t) \
({ \
let _i = i; \
let _x = x; \
(t)->data[_i] = _x; \
(t)->isset[_i] = 1; \
})
/** Unset table value for key.
*/
#define data_table_unset(i, t) \
({ \
let _i = i; \
(t)->isset[_i] = 0; \
})
/** Test whether key has value. */
#define data_table_isset(i, t) \
({ let _i = i; (t)->isset[_i]; })
/** Retrieve key value. */
#define data_table_get(i, t) \
({ let _i = i; (t)->data[_i]; })
/** Define a static table. */
#define deftable(NAME, T, N) \
static let tbl_ ## NAME = data_table_create (T, N)
/** Refer to a static table. */
#define t(NAME) &(tbl_ ## NAME)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment