summaryrefslogtreecommitdiff
path: root/source/kit/lower_bound.h
blob: 2ee04b948f4fcc26c8fa573dc294d550e71d9b1c (plain)
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
#ifndef KIT_LOWER_BOUND_H
#define KIT_LOWER_BOUND_H

#include "types.h"

#ifdef __cplusplus
extern "C" {
#endif

#define KIT_LOWER_BOUND_INL(return_val, size, ...) \
  do {                                             \
    i64 position_ = 0;                             \
    i64 count_    = (size);                        \
    while (count_ > 0) {                           \
      i64 delta_ = count_ / 2;                     \
      i64 index_ = position_ + delta_;             \
      if (__VA_ARGS__) {                           \
        position_ += delta_ + 1;                   \
        count_ -= delta_ + 1;                      \
      } else                                       \
        count_ = delta_;                           \
    }                                              \
    (return_val) = position_;                      \
  } while (0)

#define KIT_LOWER_BOUND(return_val, array, value, op) \
  KIT_LOWER_BOUND_INL(return_val, (array).size,       \
                      (op) ((array).values[index_], (value)))

#define KIT_LOWER_BOUND_REF(return_val, array, value, op) \
  KIT_LOWER_BOUND_INL(return_val, (array).size,           \
                      (op) ((array).values + index_, (value)))

#ifdef __cplusplus
}
#endif

#ifndef KIT_DISABLE_SHORT_NAMES
#  define LOWER_BOUND_INL KIT_LOWER_BOUND_INL
#  define LOWER_BOUND KIT_LOWER_BOUND
#  define LOWER_BOUND_REF KIT_LOWER_BOUND_REF
#endif

#endif