aboutsummaryrefslogtreecommitdiff
path: root/include/_bsearch.h
blob: ce8f11854f2295c2ea38b54548db9f293b6a9830 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <stddef.h>

#include "macros.h"

#define _MLIB_DEFINE_BSEARCH(TYPE, TABLE, DEFAULT) \
	static TYPE mlib_lookup(rune ch) \
	{ \
		ptrdiff_t i, lo, hi; \
		lo = 0; \
		hi = lengthof(TABLE) - 1; \
		i = (lo + hi) / 2; \
		do { \
			if (ch < TABLE[i].lo) \
				hi = i - 1; \
			else if (ch > TABLE[i].hi) \
				lo = i + 1; \
			else \
				return TABLE[i].val; \
			i = (lo + hi) / 2; \
		} while (lo <= hi); \
		return DEFAULT; \
	}

#define _MLIB_DEFINE_BSEARCH_CONTAINS(TABLE) \
	static bool mlib_lookup_contains(rune ch) \
	{ \
		ptrdiff_t i, lo, hi; \
		lo = 0; \
		hi = lengthof(TABLE) - 1; \
		i = (lo + hi) / 2; \
		do { \
			if (ch < TABLE[i].lo) \
				hi = i - 1; \
			else if (ch > TABLE[i].hi) \
				lo = i + 1; \
			else \
				return true; \
			i = (lo + hi) / 2; \
		} while (lo <= hi); \
		return false; \
	}

#define _MLIB_DEFINE_BSEARCH_KV(TYPE, TABLE, DEFAULT) \
	static TYPE mlib_lookup_kv(rune ch) \
	{ \
		ptrdiff_t i, lo, hi; \
		lo = 0; \
		hi = lengthof(TABLE) - 1; \
		i = (lo + hi) / 2; \
		do { \
			if (ch < TABLE[i].k) \
				hi = i - 1; \
			else if (ch > TABLE[i].k) \
				lo = i + 1; \
			else \
				return TABLE[i].v; \
			i = (lo + hi) / 2; \
		} while (lo <= hi); \
		return DEFAULT; \
	}