summaryrefslogtreecommitdiff
path: root/source/kit/move_back.h
blob: 2df12cd7bbb0c4823d6096bb3537efa8ce376e15 (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
50
51
52
53
54
55
56
57
58
59
#ifndef KIT_MOVE_BACK_H
#define KIT_MOVE_BACK_H

#include <string.h>

#ifdef __cplusplus
extern "C" {
#endif

#define KIT_MOVE_BACK(new_size, array, value, cond)  \
  do {                                               \
    ptrdiff_t     end_ = (array).size;               \
    unsigned char temp_[sizeof *(array).values];     \
    for (ptrdiff_t i_ = 0; i_ < end_;) {             \
      if ((cond) ((array).values[i_], (value))) {    \
        end_--;                                      \
        if (i_ != end_) {                            \
          memcpy(temp_, (array).values + end_,       \
                 sizeof *(array).values);            \
          (array).values[end_] = (array).values[i_]; \
          memcpy((array).values + i_, temp_,         \
                 sizeof *(array).values);            \
        }                                            \
      } else                                         \
        i_++;                                        \
    }                                                \
    (new_size) = end_;                               \
  } while (0)

#define KIT_MOVE_BACK_REF(new_size, array, value, cond) \
  do {                                                  \
    ptrdiff_t     end_ = (array).size;                  \
    unsigned char temp_[sizeof *(array).values];        \
    for (ptrdiff_t i_ = 0; i_ < end_;) {                \
      if ((cond) (&(array).values[i_], &(value))) {     \
        end_--;                                         \
        if (i_ != end_) {                               \
          memcpy(temp_, (array).values + end_,          \
                 sizeof *(array).values);               \
          (array).values[end_] = (array).values[i_];    \
          memcpy((array).values + i_, temp_,            \
                 sizeof *(array).values);               \
        }                                               \
      } else                                            \
        i_++;                                           \
    }                                                   \
    (new_size) = end_;                                  \
  } while (0)

#ifndef KIT_DISABLE_SHORT_NAMES
#  define MOVE_BACK KIT_MOVE_BACK
#  define MOVE_BACK_REF KIT_MOVE_BACK_REF
#endif

#ifdef __cplusplus
}
#endif

#endif