CLibs
Loading...
Searching...
No Matches
foreach.h
Go to the documentation of this file.
1/*
2 * Macros for iterating over different structures (arrays, strings, sets, ...).
3 *
4 * To define `foreach` for a data structure in `src/structs`,
5 * first include the struct, then this header.
6 *
7 *
8 * Created by MacBook on 23.10.2024.
9 */
10
11#ifndef CLIBS_FOREACH_H
12#define CLIBS_FOREACH_H
13
14#include <stdlib.h>
15#include <string.h>
16
17
27#define foreach_uni( TYPE, ITEM_NAME, INITIALIZER, ACCESSOR, SIZE ) \
28 foreach_helper_init( SIZE, ITEM_NAME ) \
29 foreach_helper_assign( TYPE, ITEM_NAME, INITIALIZER, ACCESSOR )
30
43#define foreach_arr( ITEM_TYPE, ITEM_NAME, ARRAY, COUNT ) \
44 foreach_helper_init( COUNT, ITEM_NAME ) \
45 foreach_helper_assign( ITEM_TYPE, ITEM_NAME, ( ARRAY )[ 0 ], \
46 ( ARRAY )[ foreach_index_##ITEM_NAME ] )
47
56#define foreach_str( ITEM_NAME, STRING ) \
57 foreach_helper_init( strlen( STRING ), ITEM_NAME ) \
58 foreach_helper_assign( const char, ITEM_NAME, ( STRING )[ 0 ], \
59 ( STRING )[ foreach_index_##ITEM_NAME ] )
60
61
62#if defined( CLIBS_DYNAMIC_ARRAY_H ) || defined( CLIBS__GENERATE_DOCS )
76#define foreach_ls( TYPE, ITEM_NAME, LIST ) \
77 foreach_helper_init( list_size( LIST ), ITEM_NAME ) \
78 foreach_helper_assign( TYPE, ITEM_NAME, list_fetch( LIST, 0, TYPE ), \
79 list_fetch( LIST, foreach_index_##ITEM_NAME, TYPE ) )
80#endif // List
81
82
83#if defined( CLIBS_SETS_H ) || defined( CLIBS__GENERATE_DOCS )
98#define foreach_set( ENTRY_NAME, SET ) \
99 for ( SetEnumeratedEntry ENTRY_NAME = set_get_next( ( SET ), -1 ); \
100 ENTRY_NAME.index >= 0; \
101 ENTRY_NAME = set_get_next( ( SET ), ENTRY_NAME.index ) )
102#endif // Set
103
104
105#if defined( CLIBS_QUEUE_H ) || defined( CLIBS__GENERATE_DOCS )
128#define foreach_que( ENTRY_NAME, QUEUE ) \
129 for ( const struct queue_node *ENTRY_NAME = queue__iterator_get_head( QUEUE ); \
130 ENTRY_NAME != NULL; ENTRY_NAME = queue__iterator_get_next( ENTRY_NAME ) )
131
132#endif // Queue
133
134
136#define foreach_helper_init( SIZE, ITEM_NAME ) \
137 for ( size_t foreach_keep_##ITEM_NAME = 1, foreach_index_##ITEM_NAME = 0, \
138 foreach_cap_##ITEM_NAME = ( SIZE ); \
139 foreach_keep_##ITEM_NAME \
140 && foreach_index_##ITEM_NAME < foreach_cap_##ITEM_NAME; \
141 foreach_keep_##ITEM_NAME = !foreach_keep_##ITEM_NAME, \
142 ++foreach_index_##ITEM_NAME )
143
144#define foreach_helper_assign( TYPE, ITEM_NAME, INITIALIZER, ACCESSOR ) \
145 for ( TYPE ITEM_NAME = ( foreach_index_##ITEM_NAME == 0 ) ? ( INITIALIZER ) \
146 : ( ACCESSOR ); \
147 foreach_keep_##ITEM_NAME; \
148 foreach_keep_##ITEM_NAME = !foreach_keep_##ITEM_NAME )
150
151
152#endif //CLIBS_FOREACH_H