forked from RandyGaul/cute_headers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tinytiled.h
2197 lines (1805 loc) · 68.3 KB
/
tinytiled.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
/*
------------------------------------------------------------------------------
Licensing information can be found at the end of the file.
------------------------------------------------------------------------------
tinytiled.h - v1.00
To create implementation (the function definitions)
#define TINYTILED_IMPLEMENTATION
in *one* C/CPP file (translation unit) that includes this file
SUMMARY
Parses Tiled (http://www.mapeditor.org/) files saved as the JSON file
format. See http://doc.mapeditor.org/en/latest/reference/json-map-format/
for a complete description of the JSON Tiled format. An entire map file
is loaded up in entirety and used to fill in a set of structs. The entire
struct collection is then handed to the user.
This header is up to date with Tiled's documentation Revision f205c0b5 and
verified to work with Tiled stable version 1.1.3.
http://doc.mapeditor.org/en/latest/reference/json-map-format/
Here is a past discussion thread on this header:
https://www.reddit.com/r/gamedev/comments/87680n/tinytiled_tiled_json_map_parserloader_in_c/
*/
/*
DOCUMENTATION
Load up a Tiled json exported file, either from disk or memory, like so:
tinytiled_map_t* map = tinytiled_load_map_from_memory(memory, size, 0);
Then simply access the map's fields like so:
// get map width and height
int w = map->width;
int h = map->height;
// loop over the map's layers
tinytiled_layer_t* layer = map->layers;
while (layer)
{
int* data = layer->data;
int data_count = layer->data_count;
// do something with the tile data
UserFunction_HandleTiles(data, data_count);
layer = layer->next;
}
Finally, free it like so:
tinytiled_free_map(map);
LIMITATIONS
More uncommon fields are not supported, and are annotated in this header.
Search for "Not currently supported." without quotes to find them. tinytiled
logs a warning whenever a known unsupported field is encountered, and will
attempt to gracefully skip the field. If a field with completely unknown
syntax is encountered (which can happen if tinytiled is used on a newer
and unsupported version of Tiled), undefined behavior may occur (crashes).
Compression of the tile GIDs is *not* supported in this header. Exporting
a map from Tiled will create a JSON file. This JSON file itself can very
trivially be compressed in its entirety, thus making Tiled's internal
compression exporting not a useful feature for this header to support.
Simply wrap calls to `tinytiled_load_map_from_file` in a decompression
routine. Here is an example (assuming `zlib_uncompress` is already imp-
lemented somewhere in the user's codebase):
int size;
void* uncompressed_data = zlib_uncompress(path_to_zipped_map_file, &size);
tinytiled_map_t* map = tinytiled_load_map_from_memory(uncompressed_data, size, 0);
*/
#if !defined(TINYTILED_H)
// Read this in the event of errors
extern const char* tinytiled_error_reason;
typedef struct tinytiled_map_t tinytiled_map_t;
/*!
* Load a map from disk, placed into heap allocated memory.. \p mem_ctx can be
* NULL. It is used for custom allocations.
*/
tinytiled_map_t* tinytiled_load_map_from_file(const char* path, void* mem_ctx);
/*!
* Load a map from memory. \p mem_ctx can be NULL. It is used for custom allocations.
*/
tinytiled_map_t* tinytiled_load_map_from_memory(const void* memory, int size_in_bytes, void* mem_ctx);
/*!
* Free all dynamic memory associated with this map.
*/
void tinytiled_free_map(tinytiled_map_t* map);
#if !defined(TINYTILED_U64)
#define TINYTILED_U64 unsigned long long
#endif
#if !defined(TINYTILED_INLINE)
#if defined(_MSC_VER)
#define TINYTILED_INLINE __inline
#else
#define TINYTILED_INLINE __inline__
#endif
#endif
typedef struct tinytiled_layer_t tinytiled_layer_t;
typedef struct tinytiled_object_t tinytiled_object_t;
typedef struct tinytiled_tileset_t tinytiled_tileset_t;
typedef struct tinytiled_property_t tinytiled_property_t;
typedef union tinytiled_string_t tinytiled_string_t;
/*!
* To access a string, simply do: object->name.ptr; this union is needed
* as a workaround for 32-bit builds where the size of a pointer is only
* 32 bits.
*
* More info:
* This unions is needed to support a single-pass parser, with string
* interning, where the parser copies value directly into the user-facing
* structures. As opposed to the parser copying values into an intermediate
* structure, and finally copying the intermediate values into the
* user-facing struct at the end. The latter option requires more code!
*/
union tinytiled_string_t
{
const char* ptr;
TINYTILED_U64 hash_id;
};
typedef enum TINYTILED_PROPERTY_TYPE
{
TINYTILED_PROPERTY_NONE,
TINYTILED_PROPERTY_INT,
TINYTILED_PROPERTY_BOOL,
TINYTILED_PROPERTY_FLOAT,
TINYTILED_PROPERTY_STRING,
// Note: currently unused! File properties are reported as strings in
// this header, and it is up to users to know a-priori which strings
// contain file paths.
TINYTILED_PROPERTY_FILE,
TINYTILED_PROPERTY_COLOR,
} TINYTILED_PROPERTY_TYPE;
struct tinytiled_property_t
{
union
{
int integer;
int boolean;
float floating;
tinytiled_string_t string;
tinytiled_string_t file;
int color;
} data;
TINYTILED_PROPERTY_TYPE type;
tinytiled_string_t name;
};
struct tinytiled_object_t
{
int ellipse; // 0 or 1. Used to mark an object as an ellipse.
int gid; // GID, only if object comes from a Tilemap.
int height; // Height in pixels. Ignored if using a gid.
int id; // Incremental id - unique across all objects.
tinytiled_string_t name; // String assigned to name field in editor.
int point; // 0 or 1. Used to mark an object as a point.
// Example to index each vert of a polygon/polyline:
/*
float x, y;
for(int i = 0; i < vert_count * 2; i += 2)
{
x = vertices[i];
y = vertices[i + 1];
}
*/
int vert_count;
float* vertices; // Represents both type `polyline` and `polygon`.
int vert_type; // 1 for `polygon` and 0 for `polyline`.
int property_count; // Number of elements in the properties array.
tinytiled_property_t* properties; // Array of properties.
float rotation; // Angle in degrees clockwise.
/* text */ // Not currently supported.
tinytiled_string_t type; // String assigned to type field in editor.
int visible; // 0 or 1. Whether object is shown in editor.
int width; // Width in pixels. Ignored if using a gid.
float x; // x coordinate in pixels.
float y; // y coordinate in pixels.
tinytiled_object_t* next; // Pointer to next object. NULL if final object.
};
/*!
* Example of using both helper functions below to process the `data` pointer of a layer,
* containing an array of `GID`s.
*
* for (int i = 0; i < layer->data_count; i++)
* {
* int hflip, vflip, dflip;
* int tile_id = layer->data[i];
* tinytiled_get_flags(tile_id, &hflip, &vflip, &dflip);
* tile_id = tinytiled_unset_flags(tile_id);
* DoSomethingWithFlags(tile_id, flip, vflip, dlfip);
* DoSomethingWithTileID(tile_id);
* }
*/
#define TINYTILED_FLIPPED_HORIZONTALLY_FLAG 0x80000000
#define TINYTILED_FLIPPED_VERTICALLY_FLAG 0x40000000
#define TINYTILED_FLIPPED_DIAGONALLY_FLAG 0x20000000
/*!
* Helper for processing tile data in /ref `tinytiled_layer_t` `data`. Unsets all of
* the image flipping flags in the higher bit of /p `tile_data_gid`.
*/
TINYTILED_INLINE int tinytiled_unset_flags(int tile_data_gid)
{
const int flags = ~(TINYTILED_FLIPPED_HORIZONTALLY_FLAG | TINYTILED_FLIPPED_VERTICALLY_FLAG | TINYTILED_FLIPPED_DIAGONALLY_FLAG);
return tile_data_gid & flags;
}
/*!
* Helper for processing tile data in /ref `tinytiled_layer_t` `data`. Flags are
* stored in the GID array `data` for flipping the image. Retrieves all three flag types.
*/
TINYTILED_INLINE void tinytiled_get_flags(int tile_data_gid, int* flip_horizontal, int* flip_vertical, int* flip_diagonal)
{
*flip_horizontal = !!(tile_data_gid & TINYTILED_FLIPPED_HORIZONTALLY_FLAG);
*flip_vertical = !!(tile_data_gid & TINYTILED_FLIPPED_VERTICALLY_FLAG);
*flip_diagonal = !!(tile_data_gid & TINYTILED_FLIPPED_DIAGONALLY_FLAG);
}
struct tinytiled_layer_t
{
/* compression; */ // Not currently supported.
int data_count; // Number of integers in `data`.
int* data; // Array of GIDs. `tilelayer` only. Only support CSV style exports.
/* encoding; */ // Not currently supported.
tinytiled_string_t draworder; // `topdown` (default) or `index`. `objectgroup` only.
int height; // Row count. Same as map height for fixed-size maps.
tinytiled_layer_t* layers; // Linked list of layers. Only appears if `type` is `group`.
tinytiled_string_t name; // Name assigned to this layer.
tinytiled_object_t* objects; // Linked list of objects. `objectgroup` only.
float opacity; // Value between 0 and 1.
int property_count; // Number of elements in the properties array.
tinytiled_property_t* properties; // Array of properties.
tinytiled_string_t type; // `tilelayer`, `objectgroup`, `imagelayer` or `group`.
int visible; // 0 or 1. Whether layer is shown or hidden in editor.
int width; // Column count. Same as map width for fixed-size maps.
int x; // Horizontal layer offset in tiles. Always 0.
int y; // Vertical layer offset in tiles. Always 0.
tinytiled_layer_t* next; // Pointer to the next layer. NULL if final layer.
};
struct tinytiled_tileset_t
{
int columns; // The number of tile columns in the tileset.
int firstgid; // GID corresponding to the first tile in the set.
/* grid */ // Not currently supported.
tinytiled_string_t image; // Image used for tiles in this set (relative path from map file to source image).
int imagewidth; // Width of source image in pixels.
int imageheight; // Height of source image in pixels.
int margin; // Buffer between image edge and first tile (pixels).
tinytiled_string_t name; // Name given to this tileset.
int property_count; // Number of elements in the properties array.
tinytiled_property_t* properties; // Array of properties.
int spacing; // Spacing between adjacent tiles in image (pixels).
/* terrains */ // Not currently supported.
int tilecount; // The number of tiles in this tileset.
int tileheight; // Maximum height of tiles in this set.
/* tileoffset */ // Not currently supported.
/* tileproperties */ // Not currently supported.
/* tiles */ // Not currently supported.
int tilewidth; // Maximum width of tiles in this set.
tinytiled_string_t type; // `tileset` (for tileset files, since 1.0).
tinytiled_string_t source; // Relative path to tileset, when saved externally from the map file.
tinytiled_tileset_t* next; // Pointer to next tileset. NULL if final tileset.
};
struct tinytiled_map_t
{
int backgroundcolor; // Hex-formatted color (#RRGGBB or #AARRGGBB) (optional).
int height; // Number of tile rows.
int infinite; // Whether the map has infinite dimensions.
tinytiled_layer_t* layers; // Linked list of layers. Can be NULL.
int nextobjectid; // Auto-increments for each placed object.
tinytiled_string_t orientation; // `orthogonal`, `isometric`, `staggered` or `hexagonal`.
int property_count; // Number of elements in the properties array.
tinytiled_property_t* properties; // Array of properties.
tinytiled_string_t renderorder; // Rendering direction (orthogonal maps only).
tinytiled_string_t tiledversion; // The Tiled version used to save the file.
int tileheight; // Map grid height.
tinytiled_tileset_t* tilesets; // Linked list of tilesets.
int tilewidth; // Map grid width.
tinytiled_string_t type; // `map` (since 1.0).
int version; // The JSON format version.
int width; // Number of tile columns.
};
#define TINYTILED_H
#endif
#ifdef TINYTILED_IMPLEMENTATION
#ifndef TINYTILED_IMPLEMENTATION_ONCE
#define TINYTILED_IMPLEMENTATION_ONCE
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#ifndef _CRT_NONSTDC_NO_DEPRECATE
#define _CRT_NONSTDC_NO_DEPRECATE
#endif
#if !defined(TINYTILED_MALLOC)
#include <stdlib.h>
#define TINYTILED_MALLOC(size, ctx) malloc(size)
#define TINYTILED_FREE(mem, ctx) free(mem)
#endif
#define STRPOOL_EMBEDDED_IMPLEMENTATION
#define STRPOOL_EMBEDDED_MALLOC(ctx, size) TINYTILED_MALLOC(size, ctx)
#define STRPOOL_EMBEDDED_FREE(ctx, ptr) TINYTILED_FREE(ptr, ctx)
/*
begin embedding modified strpool.h
*/
/*
------------------------------------------------------------------------------
Licensing information can be found at the end of the file.
------------------------------------------------------------------------------
strpool.h - v1.4 - Highly efficient string pool for C/C++.
Do this:
#define STRPOOL_EMBEDDED_IMPLEMENTATION
before you include this file in *one* C/C++ file to create the implementation.
*/
#ifndef strpool_embedded_h
#define strpool_embedded_h
#ifndef STRPOOL_EMBEDDED_U32
#define STRPOOL_EMBEDDED_U32 unsigned int
#endif
#ifndef STRPOOL_EMBEDDED_U64
#define STRPOOL_EMBEDDED_U64 unsigned long long
#endif
typedef struct strpool_embedded_t strpool_embedded_t;
typedef struct strpool_embedded_config_t
{
void* memctx;
int ignore_case;
int counter_bits;
int index_bits;
int entry_capacity;
int block_capacity;
int block_size;
int min_length;
} strpool_embedded_config_t;
extern strpool_embedded_config_t const strpool_embedded_default_config;
void strpool_embedded_init( strpool_embedded_t* pool, strpool_embedded_config_t const* config );
void strpool_embedded_term( strpool_embedded_t* pool );
STRPOOL_EMBEDDED_U64 strpool_embedded_inject( strpool_embedded_t* pool, char const* string, int length );
char const* strpool_embedded_cstr( strpool_embedded_t const* pool, STRPOOL_EMBEDDED_U64 handle );
#endif /* strpool_embedded_h */
/*
----------------------
IMPLEMENTATION
----------------------
*/
#ifndef strpool_embedded_impl
#define strpool_embedded_impl
struct strpool_embedded_internal_hash_slot_t;
struct strpool_embedded_internal_entry_t;
struct strpool_embedded_internal_handle_t;
struct strpool_embedded_internal_block_t;
struct strpool_embedded_t
{
void* memctx;
int ignore_case;
int counter_shift;
STRPOOL_EMBEDDED_U64 counter_mask;
STRPOOL_EMBEDDED_U64 index_mask;
int initial_entry_capacity;
int initial_block_capacity;
int block_size;
int min_data_size;
struct strpool_embedded_internal_hash_slot_t* hash_table;
int hash_capacity;
struct strpool_embedded_internal_entry_t* entries;
int entry_capacity;
int entry_count;
struct strpool_embedded_internal_handle_t* handles;
int handle_capacity;
int handle_count;
int handle_freelist_head;
int handle_freelist_tail;
struct strpool_embedded_internal_block_t* blocks;
int block_capacity;
int block_count;
int current_block;
};
#endif /* strpool_embedded_impl */
#ifdef STRPOOL_EMBEDDED_IMPLEMENTATION
#ifndef STRPOOL_EMBEDDED_IMPLEMENTATION_ONCE
#define STRPOOL_EMBEDDED_IMPLEMENTATION_ONCE
#include <stddef.h>
#ifndef STRPOOL_EMBEDDED_ASSERT
#include <assert.h>
#define STRPOOL_EMBEDDED_ASSERT( x ) assert( x )
#endif
#ifndef STRPOOL_EMBEDDED_MEMSET
#include <string.h>
#define STRPOOL_EMBEDDED_MEMSET( ptr, val, cnt ) ( memset( ptr, val, cnt ) )
#endif
#ifndef STRPOOL_EMBEDDED_MEMCPY
#include <string.h>
#define STRPOOL_EMBEDDED_MEMCPY( dst, src, cnt ) ( memcpy( dst, src, cnt ) )
#endif
#ifndef STRPOOL_EMBEDDED_MEMCMP
#include <string.h>
#define STRPOOL_EMBEDDED_MEMCMP( pr1, pr2, cnt ) ( memcmp( pr1, pr2, cnt ) )
#endif
#ifndef STRPOOL_EMBEDDED_STRNICMP
#ifdef _WIN32
#include <string.h>
#define STRPOOL_EMBEDDED_STRNICMP( s1, s2, len ) ( strnicmp( s1, s2, len ) )
#else
#include <string.h>
#define STRPOOL_EMBEDDED_STRNICMP( s1, s2, len ) ( strncasecmp( s1, s2, len ) )
#endif
#endif
#ifndef STRPOOL_EMBEDDED_MALLOC
#include <stdlib.h>
#define STRPOOL_EMBEDDED_MALLOC( ctx, size ) ( malloc( size ) )
#define STRPOOL_EMBEDDED_FREE( ctx, ptr ) ( free( ptr ) )
#endif
typedef struct strpool_embedded_internal_hash_slot_t
{
STRPOOL_EMBEDDED_U32 hash_key;
int entry_index;
int base_count;
} strpool_embedded_internal_hash_slot_t;
typedef struct strpool_embedded_internal_entry_t
{
int hash_slot;
int handle_index;
char* data;
int size;
int length;
int refcount;
} strpool_embedded_internal_entry_t;
typedef struct strpool_embedded_internal_handle_t
{
int entry_index;
int counter;
} strpool_embedded_internal_handle_t;
typedef struct strpool_embedded_internal_block_t
{
int capacity;
char* data;
char* tail;
int free_list;
} strpool_embedded_internal_block_t;
typedef struct strpool_embedded_internal_free_block_t
{
int size;
int next;
} strpool_embedded_internal_free_block_t;
strpool_embedded_config_t const strpool_embedded_default_config =
{
/* memctx = */ 0,
/* ignore_case = */ 0,
/* counter_bits = */ 32,
/* index_bits = */ 32,
/* entry_capacity = */ 4096,
/* block_capacity = */ 32,
/* block_size = */ 256 * 1024,
/* min_length = */ 23,
};
static STRPOOL_EMBEDDED_U32 strpool_embedded_internal_pow2ceil( STRPOOL_EMBEDDED_U32 v )
{
--v;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
++v;
v += ( v == 0 );
return v;
}
static int strpool_embedded_internal_add_block( strpool_embedded_t* pool, int size )
{
if( pool->block_count >= pool->block_capacity )
{
pool->block_capacity *= 2;
strpool_embedded_internal_block_t* new_blocks = (strpool_embedded_internal_block_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
pool->block_capacity * sizeof( *pool->blocks ) );
STRPOOL_EMBEDDED_ASSERT( new_blocks );
STRPOOL_EMBEDDED_MEMCPY( new_blocks, pool->blocks, pool->block_count * sizeof( *pool->blocks ) );
STRPOOL_EMBEDDED_FREE( pool->memctx, pool->blocks );
pool->blocks = new_blocks;
}
pool->blocks[ pool->block_count ].capacity = size;
pool->blocks[ pool->block_count ].data = (char*) STRPOOL_EMBEDDED_MALLOC( pool->memctx, (size_t) size );
STRPOOL_EMBEDDED_ASSERT( pool->blocks[ pool->block_count ].data );
pool->blocks[ pool->block_count ].tail = pool->blocks[ pool->block_count ].data;
pool->blocks[ pool->block_count ].free_list = -1;
return pool->block_count++;
}
void strpool_embedded_init( strpool_embedded_t* pool, strpool_embedded_config_t const* config )
{
if( !config ) config = &strpool_embedded_default_config;
pool->memctx = config->memctx;
pool->ignore_case = config->ignore_case;
STRPOOL_EMBEDDED_ASSERT( config->counter_bits + config->index_bits <= 64 );
pool->counter_shift = config->index_bits;
pool->counter_mask = ( 1ULL << (STRPOOL_EMBEDDED_U64) config->counter_bits ) - 1;
pool->index_mask = ( 1ULL << (STRPOOL_EMBEDDED_U64) config->index_bits ) - 1;
pool->initial_entry_capacity =
(int) strpool_embedded_internal_pow2ceil( config->entry_capacity > 1 ? (STRPOOL_EMBEDDED_U32)config->entry_capacity : 2U );
pool->initial_block_capacity =
(int) strpool_embedded_internal_pow2ceil( config->block_capacity > 1 ? (STRPOOL_EMBEDDED_U32)config->block_capacity : 2U );
pool->block_size =
(int) strpool_embedded_internal_pow2ceil( config->block_size > 256 ? (STRPOOL_EMBEDDED_U32)config->block_size : 256U );
pool->min_data_size =
(int) ( sizeof( int ) * 2 + 1 + ( config->min_length > 8 ? (STRPOOL_EMBEDDED_U32)config->min_length : 8U ) );
pool->hash_capacity = pool->initial_entry_capacity * 2;
pool->entry_capacity = pool->initial_entry_capacity;
pool->handle_capacity = pool->initial_entry_capacity;
pool->block_capacity = pool->initial_block_capacity;
pool->handle_freelist_head = -1;
pool->handle_freelist_tail = -1;
pool->block_count = 0;
pool->handle_count = 0;
pool->entry_count = 0;
pool->hash_table = (strpool_embedded_internal_hash_slot_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
pool->hash_capacity * sizeof( *pool->hash_table ) );
STRPOOL_EMBEDDED_ASSERT( pool->hash_table );
STRPOOL_EMBEDDED_MEMSET( pool->hash_table, 0, pool->hash_capacity * sizeof( *pool->hash_table ) );
pool->entries = (strpool_embedded_internal_entry_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
pool->entry_capacity * sizeof( *pool->entries ) );
STRPOOL_EMBEDDED_ASSERT( pool->entries );
pool->handles = (strpool_embedded_internal_handle_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
pool->handle_capacity * sizeof( *pool->handles ) );
STRPOOL_EMBEDDED_ASSERT( pool->handles );
pool->blocks = (strpool_embedded_internal_block_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
pool->block_capacity * sizeof( *pool->blocks ) );
STRPOOL_EMBEDDED_ASSERT( pool->blocks );
pool->current_block = strpool_embedded_internal_add_block( pool, pool->block_size );
}
void strpool_embedded_term( strpool_embedded_t* pool )
{
#if 0
// Debug statistics
printf( "\n\n" );
printf( "Handles: %d/%d\n", pool->handle_count, pool->handle_capacity );
printf( "Entries: %d/%d\n", pool->entry_count, pool->entry_capacity );
printf( "Hashtable: %d/%d\n", pool->entry_count, pool->hash_capacity );
printf( "Blocks: %d/%d\n", pool->block_count, pool->block_capacity );
for( int i = 0; i < pool->block_count; ++i )
{
printf( "\n" );
printf( "BLOCK: %d\n", i );
printf( "Capacity: %d\n", pool->blocks[ i ].capacity );
printf( "Free: [ %d ]", pool->blocks[ i ].capacity - ( pool->blocks[ i ].tail - pool->blocks[ i ].data ) );
int fl = pool->blocks[ i ].free_list;
int count = 0;
int size = 0;
int total = 0;
while( fl >= 0 )
{
strpool_embedded_free_block_t* free_entry = (strpool_embedded_free_block_t*) ( pool->blocks[ i ].data + fl );
total += free_entry->size;
if( size == 0 ) { size = free_entry->size; }
if( size != free_entry->size )
{
printf( ", %dx%d", count, size );
count = 1;
size = free_entry->size;
}
else
{
++count;
}
fl = free_entry->next;
}
if( size != 0 ) printf( ", %dx%d", count, size );
printf( ", { %d }\n", total );
}
printf( "\n\n" );
#endif
for( int i = 0; i < pool->block_count; ++i ) STRPOOL_EMBEDDED_FREE( pool->memctx, pool->blocks[ i ].data );
STRPOOL_EMBEDDED_FREE( pool->memctx, pool->blocks );
STRPOOL_EMBEDDED_FREE( pool->memctx, pool->handles );
STRPOOL_EMBEDDED_FREE( pool->memctx, pool->entries );
STRPOOL_EMBEDDED_FREE( pool->memctx, pool->hash_table );
}
static STRPOOL_EMBEDDED_U64 strpool_embedded_internal_make_handle( int index, int counter, STRPOOL_EMBEDDED_U64 index_mask, int counter_shift,
STRPOOL_EMBEDDED_U64 counter_mask )
{
STRPOOL_EMBEDDED_U64 i = (STRPOOL_EMBEDDED_U64) ( index + 1 );
STRPOOL_EMBEDDED_U64 c = (STRPOOL_EMBEDDED_U64) counter;
return ( ( c & counter_mask ) << counter_shift ) | ( i & index_mask );
}
static int strpool_embedded_internal_counter_from_handle( STRPOOL_EMBEDDED_U64 handle, int counter_shift, STRPOOL_EMBEDDED_U64 counter_mask )
{
return (int) ( ( handle >> counter_shift ) & counter_mask ) ;
}
static int strpool_embedded_internal_index_from_handle( STRPOOL_EMBEDDED_U64 handle, STRPOOL_EMBEDDED_U64 index_mask )
{
return ( (int) ( handle & index_mask ) ) - 1;
}
static strpool_embedded_internal_entry_t* strpool_embedded_internal_get_entry( strpool_embedded_t const* pool, STRPOOL_EMBEDDED_U64 handle )
{
int index = strpool_embedded_internal_index_from_handle( handle, pool->index_mask );
int counter = strpool_embedded_internal_counter_from_handle( handle, pool->counter_shift, pool->counter_mask );
if( index >= 0 && index < pool->handle_count &&
counter == (int) ( pool->handles[ index ].counter & pool->counter_mask ) )
return &pool->entries[ pool->handles[ index ].entry_index ];
return 0;
}
static STRPOOL_EMBEDDED_U32 strpool_embedded_internal_find_in_blocks( strpool_embedded_t const* pool, char const* string, int length )
{
for( int i = 0; i < pool->block_count; ++i )
{
strpool_embedded_internal_block_t* block = &pool->blocks[ i ];
// Check if string comes from pool
if( string >= block->data + 2 * sizeof( STRPOOL_EMBEDDED_U32 ) && string < block->data + block->capacity )
{
STRPOOL_EMBEDDED_U32* ptr = (STRPOOL_EMBEDDED_U32*) string;
int stored_length = (int)( *( ptr - 1 ) ); // Length is stored immediately before string
if( stored_length != length || string[ length ] != '\0' ) return 0; // Invalid string
STRPOOL_EMBEDDED_U32 hash = *( ptr - 2 ); // Hash is stored before the length field
return hash;
}
}
return 0;
}
static STRPOOL_EMBEDDED_U32 strpool_embedded_internal_calculate_hash( char const* string, int length, int ignore_case )
{
STRPOOL_EMBEDDED_U32 hash = 5381U;
if( ignore_case)
{
for( int i = 0; i < length; ++i )
{
char c = string[ i ];
c = ( c <= 'z' && c >= 'a' ) ? c - ( 'a' - 'A' ) : c;
hash = ( ( hash << 5U ) + hash) ^ c;
}
}
else
{
for( int i = 0; i < length; ++i )
{
char c = string[ i ];
hash = ( ( hash << 5U ) + hash) ^ c;
}
}
hash = ( hash == 0 ) ? 1 : hash; // We can't allow 0-value hash keys, but dupes are ok
return hash;
}
static void strpool_embedded_internal_expand_hash_table( strpool_embedded_t* pool )
{
int old_capacity = pool->hash_capacity;
strpool_embedded_internal_hash_slot_t* old_table = pool->hash_table;
pool->hash_capacity *= 2;
pool->hash_table = (strpool_embedded_internal_hash_slot_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
pool->hash_capacity * sizeof( *pool->hash_table ) );
STRPOOL_EMBEDDED_ASSERT( pool->hash_table );
STRPOOL_EMBEDDED_MEMSET( pool->hash_table, 0, pool->hash_capacity * sizeof( *pool->hash_table ) );
for( int i = 0; i < old_capacity; ++i )
{
STRPOOL_EMBEDDED_U32 hash_key = old_table[ i ].hash_key;
if( hash_key )
{
int base_slot = (int)( hash_key & (STRPOOL_EMBEDDED_U32)( pool->hash_capacity - 1 ) );
int slot = base_slot;
while( pool->hash_table[ slot ].hash_key )
slot = ( slot + 1 ) & ( pool->hash_capacity - 1 );
STRPOOL_EMBEDDED_ASSERT( hash_key );
pool->hash_table[ slot ].hash_key = hash_key;
pool->hash_table[ slot ].entry_index = old_table[ i ].entry_index;
pool->entries[ pool->hash_table[ slot ].entry_index ].hash_slot = slot;
++pool->hash_table[ base_slot ].base_count;
}
}
STRPOOL_EMBEDDED_FREE( pool->memctx, old_table );
}
static void strpool_embedded_internal_expand_entries( strpool_embedded_t* pool )
{
pool->entry_capacity *= 2;
strpool_embedded_internal_entry_t* new_entries = (strpool_embedded_internal_entry_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
pool->entry_capacity * sizeof( *pool->entries ) );
STRPOOL_EMBEDDED_ASSERT( new_entries );
STRPOOL_EMBEDDED_MEMCPY( new_entries, pool->entries, pool->entry_count * sizeof( *pool->entries ) );
STRPOOL_EMBEDDED_FREE( pool->memctx, pool->entries );
pool->entries = new_entries;
}
static void strpool_embedded_internal_expand_handles( strpool_embedded_t* pool )
{
pool->handle_capacity *= 2;
strpool_embedded_internal_handle_t* new_handles = (strpool_embedded_internal_handle_t*) STRPOOL_EMBEDDED_MALLOC( pool->memctx,
pool->handle_capacity * sizeof( *pool->handles ) );
STRPOOL_EMBEDDED_ASSERT( new_handles );
STRPOOL_EMBEDDED_MEMCPY( new_handles, pool->handles, pool->handle_count * sizeof( *pool->handles ) );
STRPOOL_EMBEDDED_FREE( pool->memctx, pool->handles );
pool->handles = new_handles;
}
static char* strpool_embedded_internal_get_data_storage( strpool_embedded_t* pool, int size, int* alloc_size )
{
if( size < (int)sizeof( strpool_embedded_internal_free_block_t ) ) size = sizeof( strpool_embedded_internal_free_block_t );
if( size < pool->min_data_size ) size = pool->min_data_size;
size = (int)strpool_embedded_internal_pow2ceil( (STRPOOL_EMBEDDED_U32)size );
// Try to find a large enough free slot in existing blocks
for( int i = 0; i < pool->block_count; ++i )
{
int free_list = pool->blocks[ i ].free_list;
int prev_list = -1;
while( free_list >= 0 )
{
strpool_embedded_internal_free_block_t* free_entry =
(strpool_embedded_internal_free_block_t*) ( pool->blocks[ i ].data + free_list );
if( free_entry->size / 2 < size )
{
// At this point, all remaining slots are too small, so bail out if the current slot is not large enough
if( free_entry->size < size ) break;
if( prev_list < 0 )
{
pool->blocks[ i ].free_list = free_entry->next;
}
else
{
strpool_embedded_internal_free_block_t* prev_entry =
(strpool_embedded_internal_free_block_t*) ( pool->blocks[ i ].data + prev_list );
prev_entry->next = free_entry->next;
}
*alloc_size = free_entry->size;
return (char*) free_entry;
}
prev_list = free_list;
free_list = free_entry->next;
}
}
// Use current block, if enough space left
int offset = (int) ( pool->blocks[ pool->current_block ].tail - pool->blocks[ pool->current_block ].data );
if( size <= pool->blocks[ pool->current_block ].capacity - offset )
{
char* data = pool->blocks[ pool->current_block ].tail;
pool->blocks[ pool->current_block ].tail += size;
*alloc_size = size;
return data;
}
// Allocate a new block
pool->current_block = strpool_embedded_internal_add_block( pool, size > pool->block_size ? size : pool->block_size );
char* data = pool->blocks[ pool->current_block ].tail;
pool->blocks[ pool->current_block ].tail += size;
*alloc_size = size;
return data;
}
STRPOOL_EMBEDDED_U64 strpool_embedded_inject( strpool_embedded_t* pool, char const* string, int length )
{
if( !string || length < 0 ) return 0;
STRPOOL_EMBEDDED_U32 hash = strpool_embedded_internal_find_in_blocks( pool, string, length );
// If no stored hash, calculate it from data
if( !hash ) hash = strpool_embedded_internal_calculate_hash( string, length, pool->ignore_case );
// Return handle to existing string, if it is already in pool
int base_slot = (int)( hash & (STRPOOL_EMBEDDED_U32)( pool->hash_capacity - 1 ) );
int base_count = pool->hash_table[ base_slot ].base_count;
int slot = base_slot;
int first_free = slot;
while( base_count > 0 )
{
STRPOOL_EMBEDDED_U32 slot_hash = pool->hash_table[ slot ].hash_key;
if( slot_hash == 0 && pool->hash_table[ first_free ].hash_key != 0 ) first_free = slot;
int slot_base = (int)( slot_hash & (STRPOOL_EMBEDDED_U32)( pool->hash_capacity - 1 ) );
if( slot_base == base_slot )
{
STRPOOL_EMBEDDED_ASSERT( base_count > 0 );
--base_count;
if( slot_hash == hash )
{
int index = pool->hash_table[ slot ].entry_index;
strpool_embedded_internal_entry_t* entry = &pool->entries[ index ];
if( entry->length == length &&
(
( !pool->ignore_case && STRPOOL_EMBEDDED_MEMCMP( entry->data + 2 * sizeof( STRPOOL_EMBEDDED_U32 ), string, (size_t)length ) == 0 )
|| ( pool->ignore_case && STRPOOL_EMBEDDED_STRNICMP( entry->data + 2 * sizeof( STRPOOL_EMBEDDED_U32 ), string, (size_t)length ) == 0 )
)
)
{
int handle_index = entry->handle_index;
return strpool_embedded_internal_make_handle( handle_index, pool->handles[ handle_index ].counter,
pool->index_mask, pool->counter_shift, pool->counter_mask );
}
}
}
slot = ( slot + 1 ) & ( pool->hash_capacity - 1 );
}
// This is a new string, so let's add it
if( pool->entry_count >= ( pool->hash_capacity - pool->hash_capacity / 3 ) )
{
strpool_embedded_internal_expand_hash_table( pool );
base_slot = (int)( hash & (STRPOOL_EMBEDDED_U32)( pool->hash_capacity - 1 ) );
slot = base_slot;
first_free = slot;
while( base_count )
{
STRPOOL_EMBEDDED_U32 slot_hash = pool->hash_table[ slot ].hash_key;
if( slot_hash == 0 && pool->hash_table[ first_free ].hash_key != 0 ) first_free = slot;
int slot_base = (int)( slot_hash & (STRPOOL_EMBEDDED_U32)( pool->hash_capacity - 1 ) );
if( slot_base == base_slot ) --base_count;
slot = ( slot + 1 ) & ( pool->hash_capacity - 1 );
}
}
slot = first_free;
while( pool->hash_table[ slot ].hash_key )
slot = ( slot + 1 ) & ( pool->hash_capacity - 1 );
if( pool->entry_count >= pool->entry_capacity )
strpool_embedded_internal_expand_entries( pool );
STRPOOL_EMBEDDED_ASSERT( !pool->hash_table[ slot ].hash_key && ( hash & ( (STRPOOL_EMBEDDED_U32) pool->hash_capacity - 1 ) ) == (STRPOOL_EMBEDDED_U32) base_slot );
STRPOOL_EMBEDDED_ASSERT( hash );
pool->hash_table[ slot ].hash_key = hash;
pool->hash_table[ slot ].entry_index = pool->entry_count;
++pool->hash_table[ base_slot ].base_count;
int handle_index;
if( pool->handle_count < pool->handle_capacity )
{
handle_index = pool->handle_count;
pool->handles[ pool->handle_count ].counter = 1;
++pool->handle_count;
}
else if( pool->handle_freelist_head >= 0 )
{
handle_index = pool->handle_freelist_head;
if( pool->handle_freelist_tail == pool->handle_freelist_head )
pool->handle_freelist_tail = pool->handles[ pool->handle_freelist_head ].entry_index;
pool->handle_freelist_head = pool->handles[ pool->handle_freelist_head ].entry_index;
}
else
{
strpool_embedded_internal_expand_handles( pool );
handle_index = pool->handle_count;
pool->handles[ pool->handle_count ].counter = 1;
++pool->handle_count;
}
pool->handles[ handle_index ].entry_index = pool->entry_count;
strpool_embedded_internal_entry_t* entry = &pool->entries[ pool->entry_count ];
++pool->entry_count;
int data_size = length + 1 + (int) ( 2 * sizeof( STRPOOL_EMBEDDED_U32 ) );
char* data = strpool_embedded_internal_get_data_storage( pool, data_size, &data_size );
entry->hash_slot = slot;
entry->handle_index = handle_index;
entry->data = data;
entry->size = data_size;
entry->length = length;
entry->refcount = 0;
*(STRPOOL_EMBEDDED_U32*)(data) = hash;
data += sizeof( STRPOOL_EMBEDDED_U32 );
*(STRPOOL_EMBEDDED_U32*)(data) = (STRPOOL_EMBEDDED_U32) length;
data += sizeof( STRPOOL_EMBEDDED_U32 );
STRPOOL_EMBEDDED_MEMCPY( data, string, (size_t) length );
data[ length ] = 0; // Ensure trailing zero
return strpool_embedded_internal_make_handle( handle_index, pool->handles[ handle_index ].counter, pool->index_mask,
pool->counter_shift, pool->counter_mask );
}
char const* strpool_embedded_cstr( strpool_embedded_t const* pool, STRPOOL_EMBEDDED_U64 handle )
{
strpool_embedded_internal_entry_t const* entry = strpool_embedded_internal_get_entry( pool, handle );
if( entry ) return entry->data + 2 * sizeof( STRPOOL_EMBEDDED_U32 ); // Skip leading hash value
return NULL;
}
#endif // STRPOOL_EMBEDDED_IMPLEMENTATION_ONCE
#endif /* STRPOOL_EMBEDDED_IMPLEMENTATION */
/*
revision history: