summaryrefslogtreecommitdiff
path: root/source/kit/move_back.h
blob: 1885f5d05721014811f1827ae71632f894bf772b (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
45
46
47
48
49
#ifndef KIT_MOVE_BACK_H
#define KIT_MOVE_BACK_H

#include "types.h"

#include <string.h>

#ifdef __cplusplus
extern "C" {
#endif

#define KIT_MOVE_BACK_INL(new_size, array, ...)          \
  do {                                                   \
    i64 index_;                                          \
    i64 end_ = (array).size;                             \
    u8  temp_[sizeof *(array).values];                   \
    for (index_ = 0; index_ < end_;) {                   \
      if (__VA_ARGS__) {                                 \
        end_--;                                          \
        if (index_ != end_) {                            \
          memcpy(temp_, (array).values + end_,           \
                 sizeof *(array).values);                \
          (array).values[end_] = (array).values[index_]; \
          memcpy((array).values + index_, temp_,         \
                 sizeof *(array).values);                \
        }                                                \
      } else                                             \
        index_++;                                        \
    }                                                    \
    (new_size) = end_;                                   \
  } while (0)

#define KIT_MOVE_BACK(new_size, array, value, cond) \
  KIT_MOVE_BACK_INL(new_size, array,                \
                    (cond) ((array).values[index_], (value)))

#define KIT_MOVE_BACK_REF(new_size, array, value, cond) \
  KIT_MOVE_BACK_INL(new_size, array,                    \
                    (cond) ((array).values + index_, (value)))

#ifdef __cplusplus
}
#endif

#define MOVE_BACK_INL KIT_MOVE_BACK_INL
#define MOVE_BACK KIT_MOVE_BACK
#define MOVE_BACK_REF KIT_MOVE_BACK_REF

#endif