-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcc.h
6418 lines (5573 loc) · 291 KB
/
cc.h
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*----------------------------------------- CC: CONVENIENT CONTAINERS v1.3.2 -------------------------------------------
This library provides usability-oriented generic containers (vectors, linked lists, unordered maps, unordered sets,
ordered maps, and ordered sets).
Features:
* Fully generic API (no need to specify element or key type except when first declaring a container).
* No need to pre-declare container types per element or key/element pair.
* Type safety.
* User-defined destructor, comparison, and hash functions associated with element and key types.
* Handles memory allocation failure.
* Single header.
* Compiles in C and C++.
It requires C23, or C11 and compiler support for __typeof__, or C++11.
It has been tested with GCC, Clang, MinGW, and MSVC.
Usage example:
+---------------------------------------------------------+----------------------------------------------------------+
| Vector: | List: |
|---------------------------------------------------------|----------------------------------------------------------|
| #include <stdio.h> | #include <stdio.h> |
| #include "cc.h" | #include "cc.h" |
| | |
| int main( void ) | int main( void ) |
| { | { |
| vec( int ) our_vec; | list( int ) our_list; |
| init( &our_vec ); | init( &our_list ); |
| | |
| // Adding elements to end. | // Adding elements to end. |
| for( int i = 0; i < 10; ++i ) | for( int i = 0; i < 10; ++i ) |
| if( !push( &our_vec, i ) ) | if( !push( &our_list, i ) ) |
| { | { |
| // Out of memory, so abort. | // Out of memory, so abort. |
| cleanup( &our_vec ); | cleanup( &our_list ); |
| return 1; | return 1; |
| } | } |
| | |
| // Inserting an element at an index. | // Inserting an element before another element. |
| for( int i = 0; i < 10; ++i ) | for( |
| if( !insert( &our_vec, i * 2, i ) ) | int *el = first( &our_list ); |
| { | el != end( &our_list ); |
| // Out of memory, so abort. | el = next( &our_list, el ) |
| cleanup( &our_vec ); | ) |
| return 1; | if( !insert( &our_list, el, *el ) ) |
| } | { |
| | // Out of memory, so abort. |
| // Retrieving and erasing elements. | cleanup( &our_list ); |
| for( int i = 0; i < size( &our_vec ); ) | return 1; |
| if( *get( &our_vec, i ) % 3 == 0 ) | } |
| erase( &our_vec, i ); | |
| else | // Erasing elements. |
| ++i; | for( |
| | int *el = first( &our_list ); |
| // Iteration #1. | el != end( &our_list ); |
| for_each( &our_vec, el ) | ) |
| printf( "%d ", *el ); | if( *el % 3 == 0 ) |
| // Printed: 1 1 2 2 4 4 5 5 7 7 8 8 | el = erase( &our_list, el ); |
| | else |
| // Iteration #2. | el = next( &our_list, el ); |
| for( | |
| int *el = first( &our_vec ); | // Iteration #1. |
| el != end( &our_vec ); | for_each( &our_list, el ) |
| el = next( &our_vec, el ) | printf( "%d ", *el ); |
| ) | // Printed: 1 1 2 2 4 4 5 5 7 7 8 8 |
| printf( "%d ", *el ); | |
| // Printed: Same as above. | // Iteration #2. |
| | for( |
| cleanup( &our_vec ); | int *el = first( &our_list ); |
| } | el != end( &our_list ); |
| | el = next( &our_list, el ) |
| | ) |
| | printf( "%d ", *el ); |
| | // Printed: Same as above. |
| | |
| | cleanup( &our_list ); |
| | } |
+---------------------------------------------------------+----------------------------------------------------------+
| Map: | Set: |
|---------------------------------------------------------|----------------------------------------------------------|
| #include <stdio.h> | #include <stdio.h> |
| #include "cc.h" | #include "cc.h" |
| | |
| int main( void ) | int main( void ) |
| { | { |
| // Declare a map with int keys and short elements. | set( int ) our_set; |
| map( int, short ) our_map; | init( &our_set ); |
| init( &our_map ); | |
| | // Inserting elements. |
| // Inserting elements. | for( int i = 0; i < 10; ++i ) |
| for( int i = 0; i < 10; ++i ) | if( !insert( &our_set, i ) ) |
| if( !insert( &our_map, i, i + 1 ) ) | { |
| { | // Out of memory, so abort. |
| // Out of memory, so abort. | cleanup( &our_set ); |
| cleanup( &our_map ); | return 1; |
| return 1; | } |
| } | |
| | // Erasing elements. |
| // Erasing elements. | for( int i = 0; i < 10; i += 3 ) |
| for( int i = 0; i < 10; i += 3 ) | erase( &our_set, i ); |
| erase( &our_map, i ); | |
| | // Retrieving elements. |
| // Retrieving elements. | for( int i = 0; i < 10; ++i ) |
| for( int i = 0; i < 10; ++i ) | { |
| { | int *el = get( &our_set, i ); |
| short *el = get( &our_map, i ); | if( el ) |
| if( el ) | printf( "%d ", *el ); |
| printf( "%d:%d ", i, *el ); | } |
| } | // Printed: 1 2 4 5 7 8 |
| // Printed: 1:2 2:3 4:5 5:6 7:8 8:9 | |
| | // Iteration #1. |
| // Iteration #1 (elements only). | for_each( &our_set, el ) |
| for_each( &our_map, el ) | printf( "%d ", *el ); |
| printf( "%d ", *el ); | // Printed: 2 4 7 1 5 8 |
| // Printed: 3 5 8 2 6 9 | |
| | // Iteration #2. |
| // Iteration #2 (elements and keys). | for( |
| for_each( &our_map, key, el ) | int *el = first( &our_set ); |
| printf( "%d:%d ", *key, *el ); | el != end( &our_set ); |
| // Printed: 2:3 4:5 7:8 1:2 5:6 8:9 | el = next( &our_set, el ) |
| | ) |
| // Iteration #3. | printf( "%d ", *el ); |
| for( | // Printed: Same as above. |
| short *el = first( &our_map ); | |
| el != end( &our_map ); | cleanup( &our_set ); |
| el = next( &our_map, el ) | } |
| ) | |
| printf( "%d:%d ", *key_for( &our_map, el ), *el ); | |
| // Printed: Same as above. | |
| | |
| cleanup( &our_map ); | |
| } | |
+---------------------------------------------------------+----------------------------------------------------------+
| Ordered map: | Ordered set: |
|---------------------------------------------------------|----------------------------------------------------------|
| #include <stdio.h> | #include <stdio.h> |
| #include "cc.h" | #include "cc.h" |
| | |
| int main( void ) | int main( void ) |
| { | { |
| // Declare an ordered map with int keys and short | oset( int ) our_oset; |
| // elements. | init( &our_oset ); |
| omap( int, short ) our_omap; | |
| init( &our_omap ); | // Inserting elements. |
| | for( int i = 0; i < 10; ++i ) |
| // Inserting elements. | if( !insert( &our_oset, i ) ) |
| for( int i = 0; i < 10; ++i ) | { |
| if( !insert( &our_omap, i, i + 1 ) ) | // Out of memory, so abort. |
| { | cleanup( &our_oset ); |
| // Out of memory, so abort. | return 1; |
| cleanup( &our_omap ); | } |
| return 1; | |
| } | // Erasing elements. |
| | for( int i = 0; i < 10; i += 3 ) |
| // Erasing elements. | erase( &our_oset, i ); |
| for( int i = 0; i < 10; i += 3 ) | |
| erase( &our_omap, i ); | // Retrieving elements. |
| | for( int i = 0; i < 10; ++i ) |
| // Retrieving elements. | { |
| for( int i = 0; i < 10; ++i ) | int *el = get( &our_oset, i ); |
| { | if( el ) |
| short *el = get( &our_omap, i ); | printf( "%d ", *el ); |
| if( el ) | } |
| printf( "%d:%d ", i, *el ); | // Printed: 1 2 4 5 7 8 |
| } | |
| // Printed: 1:2 2:3 4:5 5:6 7:8 8:9 | // Iteration #1. |
| | for_each( &our_oset, el ) |
| // Iteration #1 (elements only). | printf( "%d ", *el ); |
| for_each( &our_omap, el ) | // Printed: 1 2 4 5 7 8 |
| printf( "%d ", *el ); | |
| // Printed: 2 3 5 6 8 9 | // Iteration #2. |
| | for( |
| // Iteration #2 (elements and keys). | int *el = first( &our_oset ); |
| for_each( &our_omap, key, el ) | el != end( &our_oset ); |
| printf( "%d:%d ", *key, *el ); | el = next( &our_oset, el ) |
| // Printed: 1:2 2:3 4:5 5:6 7:8 8:9 | ) |
| | printf( "%d ", *el ); |
| // Iteration #3. | // Printed: Same as above. |
| for( | |
| short *el = first( &our_omap ); | // Iteration over an element range, namely from 2 |
| el != end( &our_omap ); | // (inclusive) to 7 (exclusive). |
| el = next( &our_omap, el ) | for( |
| ) | int *el = first( &our_oset, 2 ), |
| printf( "%d:%d ", *key_for( &our_omap, el ), *el ); | *range_end = first( &our_oset, 7 ); |
| // Printed: Same as above. | el != range_end; |
| | el = next( &our_oset, el ) |
| // Iteration over a key range, namely from 2 | ) |
| // (inclusive) to 7 (exclusive). | printf( "%d ", *el ); |
| for( | // Printed: 2 4 5 |
| short *el = first( &our_omap, 2 ), | |
| *range_end = first( &our_omap, 7 ); | cleanup( &our_oset ); |
| el != range_end; | } |
| el = next( &our_omap, el ) | |
| ) | |
| printf( "%d:%d ", *key_for( &our_omap, el ), *el ); | |
| // Printed: 2:3 4:5 5:6 | |
| | |
| cleanup( &our_omap ); | |
| } | |
+---------------------------------------------------------+----------------------------------------------------------+
Including the library:
Place this at the top of your file/s:
#include "cc.h"
The following can be defined before including the library in any file:
#define CC_NO_SHORT_NAMES
By default, CC exposes API macros without the "cc_" prefix.
Define this flag to withhold the unprefixed names.
The following can be defined anywhere and affect all calls to API macros where the definition is visible:
#define CC_REALLOC our_realloc
Causes API macros to use a custom realloc function rather than the one in the standard library.
#define CC_FREE our_free
Causes API macros to use a custom free function rather than the one in the standard library.
API:
General notes:
* API macros may evaluate their first argument - the pointer to the container - multiple times, so never use
expressions with side effects (e.g. &our_containers[ ++i ] ) for that argument. In GCC and Clang, attempting to do
so will cause a compiler warning. All other arguments are only evaluated once.
* If CC_NO_SHORT_NAMES was declared, all API macros are prefixed with "cc_".
* Duplicating a container handle via assignment and then operating on the duplicate will invalidate the original.
Hence, only create a duplicate via assignment (including through function parameters and return values) if you have
finished with the original.
* An iterator is a pointer to an element in the container or to the associated end (or r_end, if the container
supports it). In the documentation below, these pointers are referred to as "pointer-iterators".
* In the documentation below, el_ty is the container's element type and key_ty is the container's key type (where
applicable).
All containers:
The following function-like macros operate on all containers:
void init( <any container type> *cntr )
Initializes cntr for use.
This call cannot fail (it does not allocate memory).
bool init_clone( <any container type> *cntr, <same container type> *src )
Initializes cntr as a shallow copy of src.
Returns true, or false if unsuccessful due to memory allocation failure.
size_t size( <any container type> *cntr )
Returns the number of elements.
void clear( <any container type> *cntr )
Erases all elements, calling the element and key types' destructors if they exist.
void cleanup( <any container type> *cntr )
Erases all elements (calling the element and key types' destructors if they exist), frees any other memory
associated with the container, and initializes the container for reuse.
el_ty *first( <any container type> *cntr )
Returns a pointer-iterator to the first element, or an end pointer-iterator if the container is empty.
el_ty *next( <any container type> *cntr, el_ty *i )
Returns a pointer-iterator to the element after the one pointed to by i.
If i points to the last element, the return value is an end pointer-iterator.
If i points to r_end (for the containers that support reverse iteration), the return value is a pointer-iterator
to the first element, or an end pointer-iterator if the container is empty.
el_ty *end( <any container type> *cntr )
Returns an end pointer-iterator for the container.
for_each( <any container type> *cntr, i_name )
Creates a loop iterating over all elements from first to last.
This macro declares a pointer-iterator (el_ty *) named i_name.
It is equivalent to
for( el_ty *i_name = first( cntr ); i_name != end( cntr ); i_name = next( cntr, i_name ) )
and should be followed by the loop body.
Vector (a dynamic array that stores elements in contiguous memory):
vec( el_ty ) cntr
Declares an uninitialized vector named cntr.
size_t cap( vec( el_ty ) *cntr )
Returns the current capacity.
bool reserve( vec( el_ty ) *cntr, size_t n )
Ensures that the the capacity is large enough to accommodate n elements.
Returns true, or false if unsuccessful due to memory allocation failure.
bool resize( vec( el_ty ) *cntr, size_t n )
Sets the number of elements to n.
If n is above the current size, the new elements are uninitialized.
If n is below the current size, the element type's destructor (if it exists) is called for each erased element.
Returns true, or false if unsuccessful due to memory allocation failure.
bool shrink( vec( el_ty ) *cntr )
Shrinks the capacity to the current size.
Returns true, or false if unsuccessful due to memory allocation failure.
el_ty *get( vec( el_ty ) *cntr, size_t i )
Returns a pointer-iterator to the element at index i.
el_ty *push( vec( el_ty ) *cntr, el_ty el )
Inserts el at the end of the vector.
Returns a pointer-iterator to the new element, or NULL in the case of memory allocation failure.
el_ty *push_n( vec( el_ty ) *cntr, el_ty *els, size_t n )
Inserts n elements from array els at the end of the vector.
Returns a pointer-iterator to the first new element, or NULL in the case of memory allocation failure.
el_ty *insert( vec( el_ty ) *cntr, size_t i, el_ty el )
Inserts el at index i.
Returns a pointer-iterator to the new element, or NULL in the case of memory allocation failure.
el_ty *insert_n( vec( el_ty ) *cntr, size_t i, el_ty *els, size_t n )
Inserts n elements from array els at index i.
Returns a pointer-iterator to the first new element, or NULL in the case of memory allocation failure.
el_ty *erase( vec( el_ty ) *cntr, size_t i )
Erases the element at index i, calling the element type's destructor if it exists.
Returns a pointer-iterator to the element after the erased element, or an end pointer-iterator if there
is no subsequent element.
el_ty *erase_n( vec( el_ty ) *cntr, size_t i, size_t n )
Erases n elements beginning at index i, calling the element type's destructor, if it exists, for each
erased element.
Returns a pointer-iterator to the element after the erased elements, or an end pointer-iterator if there is no
subsequent element.
el_ty *last( vec( el_ty ) *cntr )
Returns a pointer-iterator to the last element.
This call is synonymous with get( cntr, size( cntr ) - 1 ) and assumes that at the vector is not empty.
Notes:
* Vector pointer-iterators (including end) are invalidated by any API calls that cause memory reallocation.
List (a doubly linked list):
list( el_ty ) cntr
Declares an uninitialized list named cntr.
el_ty *insert( list( el_ty ) *cntr, el_ty *i, el_ty el )
Inserts el before pointer-iterator i.
Returns a pointer-iterator to the new element, or NULL in the case of memory allocation failure.
el_ty *push( list( el_ty ) *cntr, el_ty el )
Inserts el at the end of the list.
Returns a pointer-iterator to the new element, or NULL in the case of memory allocation failure.
This call is synonymous with insert( cntr, end( cntr ), el ).
el_ty *erase( list( el_ty ) *cntr, el_ty *i )
Erases the element pointed to by pointer-iterator i, calling the element type's destructor if it exists.
Returns a pointer-iterator to the element after i, or an end pointer-iterator if i was the last element.
bool splice( list( el_ty ) *cntr, el_ty *i, list( el_ty ) src, el_ty *src_i )
Removes the element pointed to by pointer-iterator src_i from src and inserts it before the element pointed to by
pointer-iterator i in cntr.
Returns true, or false if unsuccessful.
This call only allocates memory, and therefore can only fail, if the list has not had any element inserted,
pushed, or spliced into it since it was initialized.
el_ty *last( list( el_ty ) *cntr )
Returns a pointer-iterator to the last element, or an r_end pointer-iterator if the list is empty.
el_ty *prev( list( el_ty ) *cntr, el_ty *i )
Returns a pointer-iterator to the element before the one pointed to by i.
If i points to the first element, the return value is an r_end pointer-iterator.
If i points to end, then the return value is a pointer-iterator to the last element, or an r_end pointer-iterator
if the list is empty.
el_ty *r_end( list( el_ty ) *cntr )
Returns an r_end (reverse end) pointer-iterator for the list.
r_for_each( list( el_ty ) *cntr, i_name )
Creates a loop iterating over all elements from last to first.
This macro declares an el_ty * pointer-iterator named i_name.
It is equivalent to
for( el_ty *i_name = last( cntr ); i_name != r_end( cntr ); i_name = prev( cntr, i_name ) )
and should be followed by the body of the loop.
Notes:
* List pointer-iterators (including r_end and end) are not invalidated by any API calls besides init and cleanup,
unless they point to erased elements.
Map (an unordered associative container mapping elements to keys, implemented as a hybrid open-addressing, chained
hash table):
map( key_ty, el_ty ) cntr
Declares an uninitialized map named cntr.
key_ty must be a type, or alias for a type, for which comparison and hash functions have been defined (this
requirement is enforced internally such that neglecting it causes a compiler error).
For types with in-built comparison and hash functions, and for details on how to declare new comparison and hash
functions, see "Destructor, comparison, and hash functions and custom max load factors" below.
size_t cap( map( key_ty, el_ty ) *cntr )
Returns the current capacity, i.e. bucket count.
Note that the number of elements a map can accommodate without rehashing is not its capacity but its capacity
multiplied by the max load factor associated with its key type.
bool reserve( map( key_ty, el_ty ) *cntr, size_t n )
Ensures that the capacity is large enough to accommodate n elements without rehashing.
Returns true, or false if unsuccessful due to memory allocation failure.
bool shrink( map( key_ty, el_ty ) *cntr )
Shrinks the capacity to best accommodate the current size.
Returns true, or false if unsuccessful due to memory allocation failure.
el_ty *insert( map( key_ty, el_ty ) *cntr, key_ty key, el_ty el )
Inserts element el with the specified key.
If an element with the same key already exists, the existing element is replaced.
Returns a pointer-iterator to the new element, or NULL in the case of memory allocation failure.
el_ty *get( map( key_ty, el_ty ) *cntr, key_ty key )
Returns a pointer-iterator to the element with the specified key, or NULL if no such element exists.
el_ty *get_or_insert( map( key_ty, el_ty ) *cntr, key_ty key, el_ty el )
Inserts element el if no element with the specified key already exist.
Returns a pointer-iterator to the new element if it was inserted, or a pointer-iterator to the existing element
with the same key, or NULL in the case of memory allocation failure.
Determine whether an element was inserted by comparing the map's size before and after the call.
const key_ty *key_for( map( key_ty, el_ty ) *cntr, el_ty *i )
Returns a const pointer to the key for the element pointed to by pointer-iterator i.
bool erase( map( key_ty, el_ty ) *cntr, key_ty key )
Erases the element with the specified key, if it exists.
Returns true if an element was erased, or false if no such element exists.
el_ty *erase_itr( map( key_ty, el_ty ) *cntr, el_ty *i )
Erases the element pointed to by pointer-iterator i.
Returns a pointer-iterator to the next element in the map, or an end pointer-iterator if the erased element was
the last one.
for_each( map( key_ty, el_ty ) *cntr, key_ptr_name, i_name )
Creates a loop iterating over all elements from first to last, with easy access to the corresponding keys.
This macro declares a pointer to the key (const key_ty *) named key_ptr_name and a pointer-iterator (el_ty *)
named i_name.
It should be followed by the body of the loop.
Notes:
* Map pointer-iterators (including end) may be invalidated by any API calls that cause memory reallocation.
Set (an unordered associative container for elements without a separate key, implemented as a hybrid open-addressing,
chained hash table):
set( el_ty ) cntr
Declares an uninitialized set named cntr.
el_ty must be a type, or alias for a type, for which comparison and hash functions have been defined (this
requirement is enforced internally such that neglecting it causes a compiler error).
For types with in-built comparison and hash functions, and for details on how to declare new comparison and hash
functions, see "Destructor, comparison, and hash functions and custom max load factors" below.
size_t cap( set( el_ty ) *cntr )
Returns the current capacity, i.e. bucket count.
Note that the number of elements a set can accommodate without rehashing is not its capacity but its capacity
multiplied by the max load factor associated with its key type.
bool reserve( set( el_ty ) *cntr, size_t n )
Ensures that the capacity is large enough to accommodate n elements without rehashing.
Returns true, or false if unsuccessful due to memory allocation failure.
bool shrink( set( el_ty ) *cntr )
Shrinks the capacity to best accommodate the current size.
Returns true, or false if unsuccessful due to memory allocation failure.
el_ty *insert( set( el_ty ) *cntr, el_ty el )
Inserts element el.
If the element already exists, the existing element is replaced.
Returns a pointer-iterator to the new element, or NULL in the case of memory allocation failure.
el_ty *get( set( el_ty ) *cntr, el_ty el )
Returns a pointer-iterator to element el, or NULL if no such element exists.
el_ty *get_or_insert( set( el_ty ) *cntr, el_ty el )
Inserts element el if it does not already exist.
Returns a pointer-iterator to the new element if it was inserted, or a pointer-iterator to the existing element,
or NULL in the case of memory allocation failure.
Determine whether an element was inserted by comparing the set's size before and after the call.
bool erase( set( el_ty ) *cntr, el_ty el )
Erases the element el, if it exists.
Returns true if an element was erased, or false if no such element exists.
el_ty *erase_itr( set( el_ty ) *cntr, el_ty *i )
Erases the element pointed to by pointer-iterator i.
Returns a pointer-iterator to the next element in the set, or an end pointer-iterator if the erased element was
the last one.
Notes:
* Set pointer-iterators (including end) may be invalidated by any API calls that cause memory reallocation.
Ordered map (an ordered associative container mapping elements to keys, implemented as a red-black tree):
omap( key_ty, el_ty ) cntr
Declares an uninitialized ordered map named cntr.
key_ty must be a type, or alias for a type, for which a comparison function has been defined (this requirement is
enforced internally such that neglecting it causes a compiler error).
For types with in-built comparison functions, and for details on how to declare new comparison functions, see
"Destructor, comparison, and hash functions and custom max load factors" below.
el_ty *insert( omap( key_ty, el_ty ) *cntr, key_ty key, el_ty el )
Inserts element el with the specified key.
If an element with the same key already exists, the existing element is replaced.
Returns a pointer-iterator to the new element, or NULL in the case of memory allocation failure.
el_ty *get( omap( key_ty, el_ty ) *cntr, key_ty key )
Returns a pointer-iterator to the element with the specified key, or NULL if no such element exists.
el_ty *get_or_insert( omap( key_ty, el_ty ) *cntr, key_ty key, el_ty el )
Inserts element el if no element with the specified key already exists.
Returns a pointer-iterator to the new element if it was inserted, or a pointer-iterator to the existing element
with the same key, or NULL in the case of memory allocation failure.
Determine whether an element was inserted by comparing the ordered map's size before and after the call.
const key_ty *key_for( omap( key_ty, el_ty ) *cntr, el_ty *i )
Returns a const pointer to the key for the element pointed to by pointer-iterator i.
bool erase( omap( key_ty, el_ty ) *cntr, key_ty key )
Erases the element with the specified key, if it exists.
Returns true if an element was erased, or false if no such element exists.
el_ty *erase_itr( omap( key_ty, el_ty ) *cntr, el_ty *i )
Erases the element pointed to by pointer-iterator i.
Returns a pointer-iterator to the next element in the ordered map, or an end pointer-iterator if the erased
element was the last one.
el_ty *first( omap( key_ty, el_ty ) *cntr, key_ty key )
Returns a pointer-iterator to the first element with a key greater than or equal to the specified key, or an end
pointer-iterator if no such element exists.
el_ty *last( omap( key_ty, el_ty ) *cntr )
Returns a pointer-iterator to the last element, or an r_end pointer-iterator if the ordered map is empty.
el_ty *last( omap( key_ty, el_ty ) *cntr, key_ty key )
Returns a pointer-iterator to the last element with a key less than or equal to the specified key, or an r_end
pointer-iterator if the ordered map is empty.
el_ty *prev( omap( key_ty, el_ty ) *cntr, el_ty *i )
Returns a pointer-iterator to the element before the one pointed to by i.
If i points to the first element, the value returned is an r_end pointer-iterator.
If i points to end, then the value returned points to the last element, or is an r_end pointer-iterator if the
ordered map is empty.
el_ty *r_end( omap( key_ty, el_ty ) *cntr )
Returns an r_end (reverse end) pointer-iterator for the ordered map.
for_each( omap( key_ty, el_ty ) *cntr, key_ptr_name, i_name )
Creates a loop iterating over all elements from first to last, with easy access to the corresponding keys.
This macro declares a pointer to the key (const key_ty *) named key_ptr_name and a pointer-iterator (el_ty *)
named i_name.
It should be followed by the body of the loop.
r_for_each( omap( key_ty, el_ty ) *cntr, i_name )
Creates a loop iterating over all elements from last to first.
This macro declares an el_ty * pointer-iterator named i_name.
It is equivalent to
for( el_ty *i_name = last( cntr ); i_name != r_end( cntr ); i_name = prev( cntr, i_name ) )
and should be followed by the body of the loop.
r_for_each( omap( key_ty, el_ty ) *cntr, key_ptr_name, i_name )
Creates a loop iterating over all elements from last to first, with easy access to the corresponding keys.
This macro declares a pointer to the key (const key_ty *) named key_ptr_name and a pointer-iterator (el_ty *)
named i_name.
It should be followed by the body of the loop.
Notes:
* Ordered map pointer-iterators (including r_end and end) are not invalidated by any API calls besides init and
cleanup, unless they point to erased elements.
Ordered set (an ordered associative container for elements without a separate key, implemented as a red-black tree:
oset( el_ty ) cntr
Declares an uninitialized ordered set named cntr.
el_ty must be a type, or alias for a type, for which a comparison function has been defined (this requirement is
enforced internally such that neglecting it causes a compiler error).
For types with in-built comparison functions, and for details on how to declare new comparison functions, see
"Destructor, comparison, and hash functions and custom max load factors" below.
el_ty *insert( oset( el_ty ) *cntr, el_ty el )
Inserts element el.
If the element already exists, the existing element is replaced.
Returns a pointer-iterator to the new element, or NULL in the case of memory allocation failure.
el_ty *get( oset( el_ty ) *cntr, el_ty el )
Returns a pointer-iterator to element el, or NULL if no such element exists.
el_ty *get_or_insert( oset( el_ty ) *cntr, el_ty el )
Inserts element el if it does not already exist.
Returns a pointer-iterator to the new element if it was inserted, or a pointer-iterator to the existing element,
or NULL in the case of memory allocation failure.
Determine whether an element was inserted by comparing the ordered set's size before and after the call.
bool erase( oset( el_ty ) *cntr, el_ty el )
Erases the element el, if it exists.
Returns true if an element was erased, or false if no such element exists.
el_ty *erase_itr( oset( el_ty ) *cntr, el_ty *i )
Erases the element pointed to by pointer-iterator i.
Returns a pointer-iterator to the next element in the ordered set, or an end pointer-iterator if the erased
element was the last one.
el_ty *first( oset( key_ty, el_ty ) *cntr, el_ty el )
Returns a pointer-iterator to the first element greater than or equal to el, or an end pointer-iterator if no such
element exists.
el_ty *last( oset( el_ty ) *cntr )
Returns a pointer-iterator to the last element, or an r_end pointer-iterator if the ordered set is empty.
el_ty *last( oset( key_ty, el_ty ) *cntr, el_ty el )
Returns a pointer-iterator to the last element less than or equal to el, or an end pointer-iterator if no such
element exists.
el_ty *prev( oset( el_ty ) *cntr, el_ty *i )
Returns a pointer-iterator to the element before the one pointed to by i.
If i points to the first element, the return value is an r_end pointer-iterator.
If i points to end, then the pointer-iterator returned points to the last element, or is an r_end pointer-iterator
if the ordered set is empty.
el_ty *r_end( oset( el_ty ) *cntr )
Returns an r_end (reverse end) pointer-iterator for the ordered set.
r_for_each( oset( el_ty ) *cntr, i_name )
Creates a loop iterating over all elements from last to first.
This macro declares an el_ty * pointer-iterator named i_name.
It is equivalent to
for( el_ty *i_name = last( cntr ); i_name != r_end( cntr ); i_name = prev( cntr, i_name ) )
and should be followed by the body of the loop.
Notes:
* Ordered set pointer-iterators (including r_end and end) may be invalidated by any API calls that cause memory
reallocation.
Destructor, comparison, and hash functions and custom max load factors:
This part of the API allows the user to define custom destructor, comparison, and hash functions and max load
factors for a type.
Once these functions are defined, any container using that type for its elements or keys will call them
automatically.
Once the max load factor is defined, any map using the type for its keys and any set using the type for its elements
will use the defined load factor to determine when rehashing is necessary.
#define CC_DTOR ty, { function body }
#include "cc.h"
Defines a destructor for type ty.
The signature of the function is void ( ty val ).
#define CC_CMPR ty, { function body }
#include "cc.h"
Defines a comparison function for type ty.
The signature of the function is int ( ty val_1, ty val_2 ).
The function should return 0 if val_1 and val_2 are equal, a negative integer if val_1 is less than val_2, and a
positive integer if val_1 is greater than val_2.
#define CC_HASH ty, { function body }
#include "cc.h"
Defines a hash function for type ty.
The signature of the function is size_t ( ty val ).
The function should return the hash of val.
#define CC_LOAD ty, max_load_factor
Defines the max load factor for type ty.
max_load_factor should be a float or double between 0.0 and 1.0.
The default max load factor is 0.9.
Trivial example:
typedef struct { int x; } our_type;
#define CC_DTOR our_type, { printf( "!%d\n", val.x ); }
#define CC_CMPR our_type, { return val_1.x < val_2.x ? -1 : val_1.x > val_2.x; }
#define CC_HASH our_type, { return val.x * 2654435761ull; }
#define CC_LOAD our_type, 0.5
#include "cc.h"
Notes:
* These functions are inline and have static scope, so you need to either redefine them in each translation unit
from which they should be called or (preferably) define them in a shared header. For structs or unions, a sensible
place to define them is immediately after the definition of the struct or union.
* Only one destructor, comparison, or hash function or max load factor should be defined by the user for each type.
* Including cc.h in these cases does not include the full header, so you still need to include it separately at the
top of your files.
* In-built comparison and hash functions are already defined for the following types: char, unsigned char, signed
char, unsigned short, short, unsigned int, int, unsigned long, long, unsigned long long, long long, size_t, and
char * (a NULL-terminated string). Defining a comparison or hash function for one of these types will overwrite
the in-built function.
Version history:
11/02/2025 1.3.2: Fixed a critical bug causing maps to call the wrong destructors during cleanup.
23/08/2024 1.3.1: Fixed missing static inline qualifier on an internal omap function.
29/07/2024 1.3.0: Added ordered map and ordered set.
Fixed cc_erase_itr to return a correctly typed pointer-iterator instead of void *.
Fixed a bug in list that caused cc_next and cc_prev to behave incorrectly when passed an r_end and
end pointer-iterator, respectively.
Deprecated reverse iteration (cc_last, cc_prev, and cc_r_end) for maps and sets.
12/07/2024 1.2.0: Added MSVC support.
Added README examples to the documentation in the header.
27/05/2024 1.1.1: Fixed a bug in map and set that could theoretically cause a crash on rehash (triggerable in testing
using cc_shrink with a maximum load factor significantly higher than 1.0).
18/03/2024 1.1.0: Replaced the Robin Hood implementations of map and set with Verstable implementations.
Added branch-prediction optimizations.
Improved documentation.
23/01/2024 1.0.4: Fixed critical bug causing undefined behavior upon iteration of empty maps with nonzero capacities.
Fixed formatting inconsistencies and improved code comments.
04/05/2023 1.0.3: Completed a refractor that reduces compile speed by approximately 53% in C with GCC.
This was achieved by:
* Reducing the number of _Generic expressions in API calls by extracting multiple key-related data
from a single expression).
* Reducing the work done inside _Generic expressions (this seemed to be a bottleneck).
* Changing the API macro function-selection mechanism so that only the function itself varies based
on container type (all parallel functions now use the same parameter interface) and each macro
contains only one argument list (unused arguments are discarded).
Also introduced performance improvements into maps and sets, changed the default integer hash
functions to more robust ones, and corrected a bug that could cause map and set probe-length
integers to be unaligned for small elements and keys.
04/02/2023 1.0.2: Fixed bug preventing custom hash table load factors from taking effect when CC_LOAD is defined in
isolation of CC_HASH, CC_CMPR, or CC_DTOR.
Made minor adjustment to code comments and documentation so that they are more consistent.
27/01/2023 1.0.1: Made minor corrections to code comments.
26/12/2022 1.0.0: Initial release.
License (MIT):
Copyright (c) 2022-2025 Jackson L. Allan
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#if !defined( CC_DTOR ) && !defined( CC_CMPR ) && !defined( CC_HASH ) && !defined( CC_LOAD )/*------------------------*/
/* */
/* REGULAR HEADER MODE */
/* */
/*--------------------------------------------------------------------------------------------------------------------*/
// Standard headers must be included before the unprefixed names are defined below in case they clash with identifiers
// used in those headers.
// This does not prevent clashes with identifiers used in headers that the user includes after including cc.h.
// In that case, CC_NO_SHORT_NAMES is a necessity.
#ifndef CC_H
#include <limits.h>
#include <stdalign.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#ifdef __cplusplus
#include <type_traits>
#endif
#endif
#ifndef CC_NO_SHORT_NAMES
#define vec( ... ) CC_MSVC_PP_FIX( cc_vec( __VA_ARGS__ ) )
#define list( ... ) CC_MSVC_PP_FIX( cc_list( __VA_ARGS__ ) )
#define map( ... ) CC_MSVC_PP_FIX( cc_map( __VA_ARGS__ ) )
#define set( ... ) CC_MSVC_PP_FIX( cc_set( __VA_ARGS__ ) )
#define omap( ... ) CC_MSVC_PP_FIX( cc_omap( __VA_ARGS__ ) )
#define oset( ... ) CC_MSVC_PP_FIX( cc_oset( __VA_ARGS__ ) )
#define init( ... ) CC_MSVC_PP_FIX( cc_init( __VA_ARGS__ ) )
#define init_clone( ... ) CC_MSVC_PP_FIX( cc_init_clone( __VA_ARGS__ ) )
#define size( ... ) CC_MSVC_PP_FIX( cc_size( __VA_ARGS__ ) )
#define cap( ... ) CC_MSVC_PP_FIX( cc_cap( __VA_ARGS__ ) )
#define reserve( ... ) CC_MSVC_PP_FIX( cc_reserve( __VA_ARGS__ ) )
#define resize( ... ) CC_MSVC_PP_FIX( cc_resize( __VA_ARGS__ ) )
#define shrink( ... ) CC_MSVC_PP_FIX( cc_shrink( __VA_ARGS__ ) )
#define insert( ... ) CC_MSVC_PP_FIX( cc_insert( __VA_ARGS__ ) )
#define insert_n( ... ) CC_MSVC_PP_FIX( cc_insert_n( __VA_ARGS__ ) )
#define get_or_insert( ... ) CC_MSVC_PP_FIX( cc_get_or_insert( __VA_ARGS__ ) )
#define push( ... ) CC_MSVC_PP_FIX( cc_push( __VA_ARGS__ ) )
#define push_n( ... ) CC_MSVC_PP_FIX( cc_push_n( __VA_ARGS__ ) )
#define splice( ... ) CC_MSVC_PP_FIX( cc_splice( __VA_ARGS__ ) )
#define get( ... ) CC_MSVC_PP_FIX( cc_get( __VA_ARGS__ ) )
#define key_for( ... ) CC_MSVC_PP_FIX( cc_key_for( __VA_ARGS__ ) )
#define erase( ... ) CC_MSVC_PP_FIX( cc_erase( __VA_ARGS__ ) )
#define erase_n( ... ) CC_MSVC_PP_FIX( cc_erase_n( __VA_ARGS__ ) )
#define erase_itr( ... ) CC_MSVC_PP_FIX( cc_erase_itr( __VA_ARGS__ ) )
#define clear( ... ) CC_MSVC_PP_FIX( cc_clear( __VA_ARGS__ ) )
#define cleanup( ... ) CC_MSVC_PP_FIX( cc_cleanup( __VA_ARGS__ ) )
#define first( ... ) CC_MSVC_PP_FIX( cc_first( __VA_ARGS__ ) )
#define last( ... ) CC_MSVC_PP_FIX( cc_last( __VA_ARGS__ ) )
#define r_end( ... ) CC_MSVC_PP_FIX( cc_r_end( __VA_ARGS__ ) )
#define end( ... ) CC_MSVC_PP_FIX( cc_end( __VA_ARGS__ ) )
#define next( ... ) CC_MSVC_PP_FIX( cc_next( __VA_ARGS__ ) )
#define prev( ... ) CC_MSVC_PP_FIX( cc_prev( __VA_ARGS__ ) )
#define for_each( ... ) CC_MSVC_PP_FIX( cc_for_each( __VA_ARGS__ ) )
#define r_for_each( ... ) CC_MSVC_PP_FIX( cc_r_for_each( __VA_ARGS__ ) )
#endif
#ifndef CC_H
#define CC_H
/*--------------------------------------------------------------------------------------------------------------------*/
/* Preliminary */
/*--------------------------------------------------------------------------------------------------------------------*/
// _Static_assert alternative that can be used inside an expression.
#define CC_STATIC_ASSERT( xp ) (void)sizeof( char[ (xp) ? 1 : -1 ] )
// Ensures inlining if possible.
#if defined( __GNUC__ )
#define CC_ALWAYS_INLINE __attribute__((always_inline))
#elif defined( _MSC_VER )
#define CC_ALWAYS_INLINE __forceinline
#else
#define CC_ALWAYS_INLINE
#endif
// Branch optimization macros.
#ifdef __GNUC__
#define CC_LIKELY( xp ) __builtin_expect( (bool)( xp ), true )
#define CC_UNLIKELY( xp ) __builtin_expect( (bool)( xp ), false )
#else
#define CC_LIKELY( xp ) ( xp )
#define CC_UNLIKELY( xp ) ( xp )
#endif
// Marks a point where the program never reaches.
#ifdef __GNUC__
#define CC_UNREACHABLE __builtin_unreachable()
#elif defined( _MSC_VER )
#define CC_UNREACHABLE __assume( false )
#else
#define CC_UNREACHABLE (void)0
#endif
// CC_MAKE_LVAL_COPY macro for making an addressable temporary copy of a variable or expression.
// The copy is valid until at least the end of full expression surrounding the macro call.
// In C, this is accomplished using a compound literal.
// In C++, we use rvalue reference magic.
// This is used to pass pointers to elements and keys (which the user may have provided as rvalues) into container
// functions.
#ifdef __cplusplus
template<class ty> ty& cc_unmove( ty&& var ) { return var; }
#define CC_MAKE_LVAL_COPY( ty, xp ) cc_unmove( (ty)( xp ) )
#else
#define CC_MAKE_LVAL_COPY( ty, xp ) *( ty[ 1 ] ){ xp }
#endif
// Macro used primarily for silencing unused-expression warnings for macros that return cast pointers.
// This issue seems to affect Clang in particular.
// GCC, on the other hand, seems to accept that pointer casts may be redundant.
#ifdef __cplusplus
template<typename ty_1, typename ty_2> ty_1 cc_maybe_unused( ty_2 xp ){ return (ty_1)xp; }
#define CC_CAST_MAYBE_UNUSED( ty, xp ) cc_maybe_unused<ty>( xp )
#else
#define CC_CAST_MAYBE_UNUSED( ty, xp ) ( ( ty ){ 0 } = ( (ty)( xp ) ) )
#endif
// Typeof for expressions and abstract declarators.
#ifdef __cplusplus
#define CC_TYPEOF_XP( xp ) std::decay<std::remove_reference<decltype( xp )>::type>::type
#define CC_TYPEOF_TY( ty ) std::decay<std::remove_reference<decltype( std::declval<ty>() )>::type>::type
#elif __STDC_VERSION__ >= 202311L // C23.
#define CC_TYPEOF_XP( xp ) typeof( xp )
#define CC_TYPEOF_TY( ty ) typeof( ty )
#else // GNU.
#define CC_TYPEOF_XP( xp ) __typeof__( xp )
#define CC_TYPEOF_TY( ty ) __typeof__( ty )
#endif
// CC_IF_THEN_CAST_TY_1_ELSE_CAST_TY_2 is the same as above, except that it selects the type to which to cast based on
// a condition.
// This is necessary because some API macros (e.g. cc_erase) return either a pointer-iterator or a bool depending on the
// container type.
#ifdef __cplusplus
template<bool cond, class ty_1, class ty_2, class xp_ty, typename std::enable_if<cond, bool>::type = true> \
ty_1 cc_if_then_cast_ty_1_else_cast_ty_2( xp_ty xp ){ return (ty_1)xp; } \
template<bool cond, class ty_1, class ty_2, class xp_ty, typename std::enable_if<!cond, bool>::type = true> \
ty_2 cc_if_then_cast_ty_1_else_cast_ty_2( xp_ty xp ){ return (ty_2)xp; } \
#define CC_IF_THEN_CAST_TY_1_ELSE_CAST_TY_2( cond, ty_1, ty_2, xp ) \
cc_if_then_cast_ty_1_else_cast_ty_2<cond, ty_1, ty_2>( xp ) \
#else
#define CC_IF_THEN_CAST_TY_1_ELSE_CAST_TY_2( cond, ty_1, ty_2, xp ) \
CC_CAST_MAYBE_UNUSED( \
CC_TYPEOF_XP( \
_Generic( (char (*)[ 1 + (bool)( cond ) ]){ 0 }, \
char (*)[ 1 ]: (ty_2){ 0 }, \
char (*)[ 2 ]: (ty_1){ 0 } \
) \
), \
( xp ) \
) \
#endif
// In GCC and Clang, we can generate a warning if the user passes an expression that may have side effects as the first
// argument of API macros.
// If the expression could have side effects, the compiler will be unable to resolve a comparison of it with itself at
// compile time, which we can check using __builtin_constant_p.
// The warning itself is generated via a division by zero.
// This macro may produce false positives (e.g. for &our_containers[ our_func() ] where our_func is a pure function that
// always returns the same value), but that is a reasonable price to pay for more macro safety.
#ifdef __GNUC__
#define CC_WARN_DUPLICATE_SIDE_EFFECTS( cntr ) \
(void)( \