Skip to content

Commit 8f67671

Browse files
use x-macros for states to avoid duplicated code
1 parent 4a98244 commit 8f67671

1 file changed

Lines changed: 22 additions & 19 deletions

File tree

ampel/main.c

Lines changed: 22 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,23 @@
22

33
#define COUNT_OF(x) ((sizeof(x) / sizeof(0 [x])) / ((size_t)(!(sizeof(x) % sizeof(0 [x]))))) /* NOLINT(readability-misplaced-array-index) */
44

5+
#define LIST_OF_STATES \
6+
X(YELLOW_BLINKING, yellow_blinking) \
7+
X(YELLOW, yellow ) \
8+
X(RED, red ) \
9+
X(RED_YELLOW, red_yellow ) \
10+
X(GREEN, green ) \
11+
X(GREEN_BLINKING, green_blinking )
12+
13+
// States enum
14+
typedef enum __attribute__((packed)) {
15+
#define X(enum_name, func_name) STATE_##enum_name,
16+
LIST_OF_STATES
17+
#undef X
18+
STATE_MAX,
19+
} State;
20+
21+
// Function pointer array
522
typedef void (*State_Function)(void);
623

724
void state_yellow_blinking(void);
@@ -11,28 +28,14 @@ void state_red_yellow(void);
1128
void state_green(void);
1229
void state_green_blinking(void);
1330

14-
typedef enum __attribute__((packed)) {
15-
STATE_YELLOW_BLINKING,
16-
STATE_YELLOW,
17-
STATE_RED,
18-
STATE_RED_YELLOW,
19-
STATE_GREEN,
20-
STATE_GREEN_BLINKING,
21-
22-
STATE_MAX,
23-
} State;
24-
25-
static State state;
26-
2731
static State_Function state_functions[STATE_MAX] = {
28-
[STATE_YELLOW_BLINKING] = state_yellow_blinking,
29-
[STATE_YELLOW] = state_yellow,
30-
[STATE_RED] = state_red,
31-
[STATE_RED_YELLOW] = state_red_yellow,
32-
[STATE_GREEN] = state_green,
33-
[STATE_GREEN_BLINKING] = state_green_blinking,
32+
#define X(enum_name, func_name) [STATE_##enum_name] = state_##func_name,
33+
LIST_OF_STATES
34+
#undef X
3435
};
3536

37+
static State state;
38+
3639
typedef enum {
3740
LIGHT_RED,
3841
LIGHT_YELLOW,

0 commit comments

Comments
 (0)