1 /* stb.h - v2.30 - Sean's Tool Box -- public domain -- http://nothings.org/stb.h
2           no warranty is offered or implied; use this code at your own risk
3 
4    This is a single header file with a bunch of useful utilities
5    for getting stuff done in C/C++.
6 
7    Documentation: http://nothings.org/stb/stb_h.html
8    Unit tests:    http://nothings.org/stb/stb.c
9 
10 
11  ============================================================================
12    You MUST
13 
14       #define STB_DEFINE
15 
16    in EXACTLY _one_ C or C++ file that includes this header, BEFORE the
17    include, like this:
18 
19       #define STB_DEFINE
20       #include "stb.h"
21 
22    All other files should just #include "stb.h" without the #define.
23  ============================================================================
24 
25 
26 Version History
27 
28    2.30   MinGW fix
29    2.29   attempt to fix use of swprintf()
30    2.28   various new functionality
31    2.27   test _WIN32 not WIN32 in STB_THREADS
32    2.26   various warning & bugfixes
33    2.25   various warning & bugfixes
34    2.24   various warning & bugfixes
35    2.23   fix 2.22
36    2.22   64-bit fixes from '!='; fix stb_sdict_copy() to have preferred name
37    2.21   utf-8 decoder rejects "overlong" encodings; attempted 64-bit improvements
38    2.20   fix to hash "copy" function--reported by someone with handle "!="
39    2.19   ???
40    2.18   stb_readdir_subdirs_mask
41    2.17   stb_cfg_dir
42    2.16   fix stb_bgio_, add stb_bgio_stat(); begin a streaming wrapper
43    2.15   upgraded hash table template to allow:
44             - aggregate keys (explicit comparison func for EMPTY and DEL keys)
45             - "static" implementations (so they can be culled if unused)
46    2.14   stb_mprintf
47    2.13   reduce identifiable strings in STB_NO_STB_STRINGS
48    2.12   fix STB_ONLY -- lots of uint32s, TRUE/FALSE things had crept in
49    2.11   fix bug in stb_dirtree_get() which caused "c://path" sorts of stuff
50    2.10   STB_F(), STB_I() inline constants (also KI,KU,KF,KD)
51    2.09   stb_box_face_vertex_axis_side
52    2.08   bugfix stb_trimwhite()
53    2.07   colored printing in windows (why are we in 1985?)
54    2.06   comparison functions are now functions-that-return-functions and
55           accept a struct-offset as a parameter (not thread-safe)
56    2.05   compile and pass tests under Linux (but no threads); thread cleanup
57    2.04   stb_cubic_bezier_1d, smoothstep, avoid dependency on registry
58    2.03   ?
59    2.02   remove integrated documentation
60    2.01   integrate various fixes; stb_force_uniprocessor
61    2.00   revised stb_dupe to use multiple hashes
62    1.99   stb_charcmp
63    1.98   stb_arr_deleten, stb_arr_insertn
64    1.97   fix stb_newell_normal()
65    1.96   stb_hash_number()
66    1.95   hack stb__rec_max; clean up recursion code to use new functions
67    1.94   stb_dirtree; rename stb_extra to stb_ptrmap
68    1.93   stb_sem_new() API cleanup (no blockflag-starts blocked; use 'extra')
69    1.92   stb_threadqueue--multi reader/writer queue, fixed size or resizeable
70    1.91   stb_bgio_* for reading disk asynchronously
71    1.90   stb_mutex uses CRITICAL_REGION; new stb_sync primitive for thread
72           joining; workqueue supports stb_sync instead of stb_semaphore
73    1.89   support ';' in constant-string wildcards; stb_mutex wrapper (can
74           implement with EnterCriticalRegion eventually)
75    1.88   portable threading API (only for win32 so far); worker thread queue
76    1.87   fix wildcard handling in stb_readdir_recursive
77    1.86   support ';' in wildcards
78    1.85   make stb_regex work with non-constant strings;
79                beginnings of stb_introspect()
80    1.84   (forgot to make notes)
81    1.83   whoops, stb_keep_if_different wasn't deleting the temp file
82    1.82   bring back stb_compress from stb_file.h for cmirror
83    1.81   various bugfixes, STB_FASTMALLOC_INIT inits FASTMALLOC in release
84    1.80   stb_readdir returns utf8; write own utf8-utf16 because lib was wrong
85    1.79   stb_write
86    1.78   calloc() support for malloc wrapper, STB_FASTMALLOC
87    1.77   STB_FASTMALLOC
88    1.76   STB_STUA - Lua-like language; (stb_image, stb_csample, stb_bilinear)
89    1.75   alloc/free array of blocks; stb_hheap bug; a few stb_ps_ funcs;
90           hash*getkey, hash*copy; stb_bitset; stb_strnicmp; bugfix stb_bst
91    1.74   stb_replaceinplace; use stdlib C function to convert utf8 to UTF-16
92    1.73   fix performance bug & leak in stb_ischar (C++ port lost a 'static')
93    1.72   remove stb_block, stb_block_manager, stb_decompress (to stb_file.h)
94    1.71   stb_trimwhite, stb_tokens_nested, etc.
95    1.70   back out 1.69 because it might problemize mixed builds; stb_filec()
96    1.69   (stb_file returns 'char *' in C++)
97    1.68   add a special 'tree root' data type for stb_bst; stb_arr_end
98    1.67   full C++ port. (stb_block_manager)
99    1.66   stb_newell_normal
100    1.65   stb_lex_item_wild -- allow wildcard items which MUST match entirely
101    1.64   stb_data
102    1.63   stb_log_name
103    1.62   stb_define_sort; C++ cleanup
104    1.61   stb_hash_fast -- Paul Hsieh's hash function (beats Bob Jenkins'?)
105    1.60   stb_delete_directory_recursive
106    1.59   stb_readdir_recursive
107    1.58   stb_bst variant with parent pointer for O(1) iteration, not O(log N)
108    1.57   replace LCG random with Mersenne Twister (found a public domain one)
109    1.56   stb_perfect_hash, stb_ischar, stb_regex
110    1.55   new stb_bst API allows multiple BSTs per node (e.g. secondary keys)
111    1.54   bugfix: stb_define_hash, stb_wildmatch, regexp
112    1.53   stb_define_hash; recoded stb_extra, stb_sdict use it
113    1.52   stb_rand_define, stb_bst, stb_reverse
114    1.51   fix 'stb_arr_setlen(NULL, 0)'
115    1.50   stb_wordwrap
116    1.49   minor improvements to enable the scripting language
117    1.48   better approach for stb_arr using stb_malloc; more invasive, clearer
118    1.47   stb_lex (lexes stb.h at 1.5ML/s on 3Ghz P4; 60/70% of optimal/flex)
119    1.46   stb_wrapper_*, STB_MALLOC_WRAPPER
120    1.45   lightly tested DFA acceleration of regexp searching
121    1.44   wildcard matching & searching; regexp matching & searching
122    1.43   stb_temp
123    1.42   allow stb_arr to use stb_malloc/realloc; note this is global
124    1.41   make it compile in C++; (disable stb_arr in C++)
125    1.40   stb_dupe tweak; stb_swap; stb_substr
126    1.39   stb_dupe; improve stb_file_max to be less stupid
127    1.38   stb_sha1_file: generate sha1 for file, even > 4GB
128    1.37   stb_file_max; partial support for utf8 filenames in Windows
129    1.36   remove STB__NO_PREFIX - poor interaction with IDE, not worth it
130           streamline stb_arr to make it separately publishable
131    1.35   bugfixes for stb_sdict, stb_malloc(0), stristr
132    1.34   (streaming interfaces for stb_compress)
133    1.33   stb_alloc; bug in stb_getopt; remove stb_overflow
134    1.32   (stb_compress returns, smaller&faster; encode window & 64-bit len)
135    1.31   stb_prefix_count
136    1.30   (STB__NO_PREFIX - remove stb_ prefixes for personal projects)
137    1.29   stb_fput_varlen64, etc.
138    1.28   stb_sha1
139    1.27   ?
140    1.26   stb_extra
141    1.25   ?
142    1.24   stb_copyfile
143    1.23   stb_readdir
144    1.22   ?
145    1.21   ?
146    1.20   ?
147    1.19   ?
148    1.18   ?
149    1.17   ?
150    1.16   ?
151    1.15   stb_fixpath, stb_splitpath, stb_strchr2
152    1.14   stb_arr
153    1.13   ?stb, stb_log, stb_fatal
154    1.12   ?stb_hash2
155    1.11   miniML
156    1.10   stb_crc32, stb_adler32
157    1.09   stb_sdict
158    1.08   stb_bitreverse, stb_ispow2, stb_big32
159           stb_fopen, stb_fput_varlen, stb_fput_ranged
160           stb_fcmp, stb_feq
161    1.07   (stb_encompress)
162    1.06   stb_compress
163    1.05   stb_tokens, (stb_hheap)
164    1.04   stb_rand
165    1.03   ?(s-strings)
166    1.02   ?stb_filelen, stb_tokens
167    1.01   stb_tolower
168    1.00   stb_hash, stb_intcmp
169           stb_file, stb_stringfile, stb_fgets
170           stb_prefix, stb_strlower, stb_strtok
171           stb_image
172           (stb_array), (stb_arena)
173 
174 Parenthesized items have since been removed.
175 
176 LICENSE
177 
178  See end of file for license information.
179 
180 CREDITS
181 
182  Written by Sean Barrett.
183 
184  Fixes:
185   Philipp Wiesemann
186   Robert Nix
187   r-lyeh
188   blackpawn
189   github:Mojofreem
190   Ryan Whitworth
191   Vincent Isambart
192   Mike Sartain
193   Eugene Opalev
194   Tim Sjostrand
195   github:infatum
196 */
197 
198 #include <stdarg.h>
199 
200 #ifndef STB__INCLUDE_STB_H
201 #define STB__INCLUDE_STB_H
202 
203 #define STB_VERSION  1
204 
205 #ifdef STB_INTROSPECT
206    #define STB_DEFINE
207 #endif
208 
209 #ifdef STB_DEFINE_THREADS
210    #ifndef STB_DEFINE
211    #define STB_DEFINE
212    #endif
213    #ifndef STB_THREADS
214    #define STB_THREADS
215    #endif
216 #endif
217 
218 #if defined(_WIN32) && !defined(__MINGW32__)
219    #ifndef _CRT_SECURE_NO_WARNINGS
220    #define _CRT_SECURE_NO_WARNINGS
221    #endif
222    #ifndef _CRT_NONSTDC_NO_DEPRECATE
223    #define _CRT_NONSTDC_NO_DEPRECATE
224    #endif
225    #ifndef _CRT_NON_CONFORMING_SWPRINTFS
226    #define _CRT_NON_CONFORMING_SWPRINTFS
227    #endif
228    #if !defined(_MSC_VER) || _MSC_VER > 1700
229    #include <intrin.h> // _BitScanReverse
230    #endif
231 #endif
232 
233 #include <stdlib.h>     // stdlib could have min/max
234 #include <stdio.h>      // need FILE
235 #include <string.h>     // stb_define_hash needs memcpy/memset
236 #include <time.h>       // stb_dirtree
237 #ifdef __MINGW32__
238    #include <fcntl.h>   // O_RDWR
239 #endif
240 
241 #ifdef STB_PERSONAL
242    typedef int Bool;
243    #define False 0
244    #define True 1
245 #endif
246 
247 #ifdef STB_MALLOC_WRAPPER_PAGED
248    #define STB_MALLOC_WRAPPER_DEBUG
249 #endif
250 #ifdef STB_MALLOC_WRAPPER_DEBUG
251    #define STB_MALLOC_WRAPPER
252 #endif
253 #ifdef STB_MALLOC_WRAPPER_FASTMALLOC
254    #define STB_FASTMALLOC
255    #define STB_MALLOC_WRAPPER
256 #endif
257 
258 #ifdef STB_FASTMALLOC
259    #ifndef _WIN32
260       #undef STB_FASTMALLOC
261    #endif
262 #endif
263 
264 #ifdef STB_DEFINE
265    #include <assert.h>
266    #include <stdarg.h>
267    #include <stddef.h>
268    #include <ctype.h>
269    #include <math.h>
270    #ifndef _WIN32
271    #include <unistd.h>
272    #else
273    #include <io.h>      // _mktemp
274    #include <direct.h>  // _rmdir
275    #endif
276    #include <sys/types.h> // stat()/_stat()
277    #include <sys/stat.h>  // stat()/_stat()
278 #endif
279 
280 #define stb_min(a,b)   ((a) < (b) ? (a) : (b))
281 #define stb_max(a,b)   ((a) > (b) ? (a) : (b))
282 
283 #ifndef STB_ONLY
284    #if !defined(__cplusplus) && !defined(min) && !defined(max)
285      #define min(x,y) stb_min(x,y)
286      #define max(x,y) stb_max(x,y)
287    #endif
288 
289    #ifndef M_PI
290      #define M_PI  3.14159265358979323846f
291    #endif
292 
293    #ifndef TRUE
294      #define TRUE  1
295      #define FALSE 0
296    #endif
297 
298    #ifndef deg2rad
299    #define deg2rad(a)  ((a)*(M_PI/180))
300    #endif
301    #ifndef rad2deg
302    #define rad2deg(a)  ((a)*(180/M_PI))
303    #endif
304 
305    #ifndef swap
306    #ifndef __cplusplus
307    #define swap(TYPE,a,b)  \
308                do { TYPE stb__t; stb__t = (a); (a) = (b); (b) = stb__t; } while (0)
309    #endif
310    #endif
311 
312    typedef unsigned char  uint8 ;
313    typedef   signed char   int8 ;
314    typedef unsigned short uint16;
315    typedef   signed short  int16;
316   #if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32)
317    typedef unsigned long  uint32;
318    typedef   signed long   int32;
319   #else
320    typedef unsigned int   uint32;
321    typedef   signed int    int32;
322   #endif
323 
324    typedef unsigned char  uchar ;
325    typedef unsigned short ushort;
326    typedef unsigned int   uint  ;
327    typedef unsigned long  ulong ;
328 
329    // produce compile errors if the sizes aren't right
330    typedef char stb__testsize16[sizeof(int16)==2];
331    typedef char stb__testsize32[sizeof(int32)==4];
332 #endif
333 
334 #ifndef STB_TRUE
335   #define STB_TRUE 1
336   #define STB_FALSE 0
337 #endif
338 
339 // if we're STB_ONLY, can't rely on uint32 or even uint, so all the
340 // variables we'll use herein need typenames prefixed with 'stb':
341 typedef unsigned char stb_uchar;
342 typedef unsigned char stb_uint8;
343 typedef unsigned int  stb_uint;
344 typedef unsigned short stb_uint16;
345 typedef          short stb_int16;
346 typedef   signed char  stb_int8;
347 #if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32)
348   typedef unsigned long  stb_uint32;
349   typedef          long  stb_int32;
350 #else
351   typedef unsigned int   stb_uint32;
352   typedef          int   stb_int32;
353 #endif
354 typedef char stb__testsize2_16[sizeof(stb_uint16)==2 ? 1 : -1];
355 typedef char stb__testsize2_32[sizeof(stb_uint32)==4 ? 1 : -1];
356 
357 #ifdef _MSC_VER
358   typedef unsigned __int64 stb_uint64;
359   typedef          __int64 stb_int64;
360   #define STB_IMM_UINT64(literalui64) (literalui64##ui64)
361   #define STB_IMM_INT64(literali64) (literali64##i64)
362 #else
363   // ??
364   typedef unsigned long long stb_uint64;
365   typedef          long long stb_int64;
366   #define STB_IMM_UINT64(literalui64) (literalui64##ULL)
367   #define STB_IMM_INT64(literali64) (literali64##LL)
368 #endif
369 typedef char stb__testsize2_64[sizeof(stb_uint64)==8 ? 1 : -1];
370 
371 // add platform-specific ways of checking for sizeof(char*) == 8,
372 // and make those define STB_PTR64
373 #if defined(_WIN64) || defined(__x86_64__) || defined(__ia64__) || defined(__LP64__)
374   #define STB_PTR64
375 #endif
376 
377 #ifdef STB_PTR64
378 typedef char stb__testsize2_ptr[sizeof(char *) == 8];
379 typedef stb_uint64 stb_uinta;
380 typedef stb_int64  stb_inta;
381 #else
382 typedef char stb__testsize2_ptr[sizeof(char *) == 4];
383 typedef stb_uint32 stb_uinta;
384 typedef stb_int32  stb_inta;
385 #endif
386 typedef char stb__testsize2_uinta[sizeof(stb_uinta)==sizeof(char*) ? 1 : -1];
387 
388 // if so, we should define an int type that is the pointer size. until then,
389 // we'll have to make do with this (which is not the same at all!)
390 
391 typedef union
392 {
393    unsigned int i;
394    void * p;
395 } stb_uintptr;
396 
397 
398 #ifdef __cplusplus
399    #define STB_EXTERN   extern "C"
400 #else
401    #define STB_EXTERN   extern
402 #endif
403 
404 // check for well-known debug defines
405 #if defined(DEBUG) || defined(_DEBUG) || defined(DBG)
406    #ifndef NDEBUG
407       #define STB_DEBUG
408    #endif
409 #endif
410 
411 #ifdef STB_DEBUG
412    #include <assert.h>
413 #endif
414 
415 
416 STB_EXTERN void stb_wrapper_malloc(void *newp, int sz, char *file, int line);
417 STB_EXTERN void stb_wrapper_free(void *oldp, char *file, int line);
418 STB_EXTERN void stb_wrapper_realloc(void *oldp, void *newp, int sz, char *file, int line);
419 STB_EXTERN void stb_wrapper_calloc(size_t num, size_t sz, char *file, int line);
420 STB_EXTERN void stb_wrapper_listall(void (*func)(void *ptr, int sz, char *file, int line));
421 STB_EXTERN void stb_wrapper_dump(char *filename);
422 STB_EXTERN int stb_wrapper_allocsize(void *oldp);
423 STB_EXTERN void stb_wrapper_check(void *oldp);
424 
425 #ifdef STB_DEFINE
426 // this is a special function used inside malloc wrapper
427 // to do allocations that aren't tracked (to avoid
428 // reentrancy). Of course if someone _else_ wraps realloc,
429 // this breaks, but if they're doing that AND the malloc
430 // wrapper they need to explicitly check for reentrancy.
431 //
432 // only define realloc_raw() and we do realloc(NULL,sz)
433 // for malloc() and realloc(p,0) for free().
stb__realloc_raw(void * p,int sz)434 static void * stb__realloc_raw(void *p, int sz)
435 {
436    if (p == NULL) return malloc(sz);
437    if (sz == 0)   { free(p); return NULL; }
438    return realloc(p,sz);
439 }
440 #endif
441 
442 #ifdef _WIN32
443 STB_EXTERN void * stb_smalloc(size_t sz);
444 STB_EXTERN void   stb_sfree(void *p);
445 STB_EXTERN void * stb_srealloc(void *p, size_t sz);
446 STB_EXTERN void * stb_scalloc(size_t n, size_t sz);
447 STB_EXTERN char * stb_sstrdup(char *s);
448 #endif
449 
450 #ifdef STB_FASTMALLOC
451 #define malloc  stb_smalloc
452 #define free    stb_sfree
453 #define realloc stb_srealloc
454 #define strdup  stb_sstrdup
455 #define calloc  stb_scalloc
456 #endif
457 
458 #ifndef STB_MALLOC_ALLCHECK
459    #define stb__check(p)  1
460 #else
461    #ifndef STB_MALLOC_WRAPPER
462       #error STB_MALLOC_ALLCHECK requires STB_MALLOC_WRAPPER
463    #else
464       #define stb__check(p) stb_mcheck(p)
465    #endif
466 #endif
467 
468 #ifdef STB_MALLOC_WRAPPER
469    STB_EXTERN void * stb__malloc(int, char *, int);
470    STB_EXTERN void * stb__realloc(void *, int, char *, int);
471    STB_EXTERN void * stb__calloc(size_t n, size_t s, char *, int);
472    STB_EXTERN void   stb__free(void *, char *file, int);
473    STB_EXTERN char * stb__strdup(char *s, char *file, int);
474    STB_EXTERN void   stb_malloc_checkall(void);
475    STB_EXTERN void   stb_malloc_check_counter(int init_delay, int rep_delay);
476    #ifndef STB_MALLOC_WRAPPER_DEBUG
477       #define stb_mcheck(p) 1
478    #else
479       STB_EXTERN int   stb_mcheck(void *);
480    #endif
481 
482 
483    #ifdef STB_DEFINE
484 
485    #ifdef STB_MALLOC_WRAPPER_DEBUG
486       #define STB__PAD   32
487       #define STB__BIAS  16
488       #define STB__SIG   0x51b01234
489       #define STB__FIXSIZE(sz)  (((sz+3) & ~3) + STB__PAD)
490       #define STB__ptr(x,y)   ((char *) (x) + (y))
491    #else
492       #define STB__ptr(x,y)   (x)
493       #define STB__FIXSIZE(sz)  (sz)
494    #endif
495 
496    #ifdef STB_MALLOC_WRAPPER_DEBUG
stb_mcheck(void * p)497    int stb_mcheck(void *p)
498    {
499       unsigned int sz;
500       if (p == NULL) return 1;
501       p = ((char *) p) - STB__BIAS;
502       sz = * (unsigned int *) p;
503       assert(* (unsigned int *) STB__ptr(p,4) == STB__SIG);
504       assert(* (unsigned int *) STB__ptr(p,8) == STB__SIG);
505       assert(* (unsigned int *) STB__ptr(p,12) == STB__SIG);
506       assert(* (unsigned int *) STB__ptr(p,sz-4) == STB__SIG+1);
507       assert(* (unsigned int *) STB__ptr(p,sz-8) == STB__SIG+1);
508       assert(* (unsigned int *) STB__ptr(p,sz-12) == STB__SIG+1);
509       assert(* (unsigned int *) STB__ptr(p,sz-16) == STB__SIG+1);
510       stb_wrapper_check(STB__ptr(p, STB__BIAS));
511       return 1;
512    }
513 
stb__check2(void * p,int sz,char * file,int line)514    static void stb__check2(void *p, int sz, char *file, int line)
515    {
516       stb_mcheck(p);
517    }
518 
stb_malloc_checkall(void)519    void stb_malloc_checkall(void)
520    {
521       stb_wrapper_listall(stb__check2);
522    }
523    #else
stb_malloc_checkall(void)524    void stb_malloc_checkall(void) { }
525    #endif
526 
527    static int stb__malloc_wait=(1 << 30), stb__malloc_next_wait = (1 << 30), stb__malloc_iter;
stb_malloc_check_counter(int init_delay,int rep_delay)528    void stb_malloc_check_counter(int init_delay, int rep_delay)
529    {
530       stb__malloc_wait = init_delay;
531       stb__malloc_next_wait = rep_delay;
532    }
533 
stb_mcheck_all(void)534    void stb_mcheck_all(void)
535    {
536       #ifdef STB_MALLOC_WRAPPER_DEBUG
537       ++stb__malloc_iter;
538       if (--stb__malloc_wait <= 0) {
539          stb_malloc_checkall();
540          stb__malloc_wait = stb__malloc_next_wait;
541       }
542       #endif
543    }
544 
545    #ifdef STB_MALLOC_WRAPPER_PAGED
546    #define STB__WINDOWS_PAGE (1 << 12)
547    #ifndef _WINDOWS_
548    STB_EXTERN __declspec(dllimport) void * __stdcall VirtualAlloc(void *p, unsigned long size, unsigned long type, unsigned long protect);
549    STB_EXTERN __declspec(dllimport) int   __stdcall VirtualFree(void *p, unsigned long size, unsigned long freetype);
550    #endif
551    #endif
552 
stb__malloc_final(int sz)553    static void *stb__malloc_final(int sz)
554    {
555       #ifdef STB_MALLOC_WRAPPER_PAGED
556       int aligned = (sz + STB__WINDOWS_PAGE - 1) & ~(STB__WINDOWS_PAGE-1);
557       char *p = VirtualAlloc(NULL, aligned + STB__WINDOWS_PAGE, 0x2000, 0x04); // RESERVE, READWRITE
558       if (p == NULL) return p;
559       VirtualAlloc(p, aligned,   0x1000, 0x04); // COMMIT, READWRITE
560       return p;
561       #else
562       return malloc(sz);
563       #endif
564    }
565 
stb__free_final(void * p)566    static void stb__free_final(void *p)
567    {
568       #ifdef STB_MALLOC_WRAPPER_PAGED
569       VirtualFree(p, 0, 0x8000); // RELEASE
570       #else
571       free(p);
572       #endif
573    }
574 
575    int stb__malloc_failure;
stb__realloc_final(void * p,int sz,int old_sz)576    static void *stb__realloc_final(void *p, int sz, int old_sz)
577    {
578       #ifdef STB_MALLOC_WRAPPER_PAGED
579       void *q = stb__malloc_final(sz);
580       if (q == NULL)
581           return ++stb__malloc_failure, q;
582       // @TODO: deal with p being smaller!
583       memcpy(q, p, sz < old_sz ? sz : old_sz);
584       stb__free_final(p);
585       return q;
586       #else
587       return realloc(p,sz);
588       #endif
589    }
590 
stb__free(void * p,char * file,int line)591    void stb__free(void *p, char *file, int line)
592    {
593       stb_mcheck_all();
594       if (!p) return;
595       #ifdef STB_MALLOC_WRAPPER_DEBUG
596       stb_mcheck(p);
597       #endif
598       stb_wrapper_free(p,file,line);
599       #ifdef STB_MALLOC_WRAPPER_DEBUG
600          p = STB__ptr(p,-STB__BIAS);
601          * (unsigned int *) STB__ptr(p,0) = 0xdeadbeef;
602          * (unsigned int *) STB__ptr(p,4) = 0xdeadbeef;
603          * (unsigned int *) STB__ptr(p,8) = 0xdeadbeef;
604          * (unsigned int *) STB__ptr(p,12) = 0xdeadbeef;
605       #endif
606       stb__free_final(p);
607    }
608 
stb__malloc(int sz,char * file,int line)609    void * stb__malloc(int sz, char *file, int line)
610    {
611       void *p;
612       stb_mcheck_all();
613       if (sz == 0) return NULL;
614       p = stb__malloc_final(STB__FIXSIZE(sz));
615       if (p == NULL) p = stb__malloc_final(STB__FIXSIZE(sz));
616       if (p == NULL) p = stb__malloc_final(STB__FIXSIZE(sz));
617       if (p == NULL) {
618          ++stb__malloc_failure;
619          #ifdef STB_MALLOC_WRAPPER_DEBUG
620          stb_malloc_checkall();
621          #endif
622          return p;
623       }
624       #ifdef STB_MALLOC_WRAPPER_DEBUG
625       * (int *) STB__ptr(p,0) = STB__FIXSIZE(sz);
626       * (unsigned int *) STB__ptr(p,4) = STB__SIG;
627       * (unsigned int *) STB__ptr(p,8) = STB__SIG;
628       * (unsigned int *) STB__ptr(p,12) = STB__SIG;
629       * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-4) = STB__SIG+1;
630       * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-8) = STB__SIG+1;
631       * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-12) = STB__SIG+1;
632       * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-16) = STB__SIG+1;
633       p = STB__ptr(p, STB__BIAS);
634       #endif
635       stb_wrapper_malloc(p,sz,file,line);
636       return p;
637    }
638 
stb__realloc(void * p,int sz,char * file,int line)639    void * stb__realloc(void *p, int sz, char *file, int line)
640    {
641       void *q;
642 
643       stb_mcheck_all();
644       if (p == NULL) return stb__malloc(sz,file,line);
645       if (sz == 0  ) { stb__free(p,file,line); return NULL; }
646 
647       #ifdef STB_MALLOC_WRAPPER_DEBUG
648          stb_mcheck(p);
649          p = STB__ptr(p,-STB__BIAS);
650       #endif
651       #ifdef STB_MALLOC_WRAPPER_PAGED
652       {
653          int n = stb_wrapper_allocsize(STB__ptr(p,STB__BIAS));
654          if (!n)
655             stb_wrapper_check(STB__ptr(p,STB__BIAS));
656          q = stb__realloc_final(p, STB__FIXSIZE(sz), STB__FIXSIZE(n));
657       }
658       #else
659       q = realloc(p, STB__FIXSIZE(sz));
660       #endif
661       if (q == NULL)
662          return ++stb__malloc_failure, q;
663       #ifdef STB_MALLOC_WRAPPER_DEBUG
664       * (int *) STB__ptr(q,0) = STB__FIXSIZE(sz);
665       * (unsigned int *) STB__ptr(q,4) = STB__SIG;
666       * (unsigned int *) STB__ptr(q,8) = STB__SIG;
667       * (unsigned int *) STB__ptr(q,12) = STB__SIG;
668       * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-4) = STB__SIG+1;
669       * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-8) = STB__SIG+1;
670       * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-12) = STB__SIG+1;
671       * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-16) = STB__SIG+1;
672 
673       q = STB__ptr(q, STB__BIAS);
674       p = STB__ptr(p, STB__BIAS);
675       #endif
676       stb_wrapper_realloc(p,q,sz,file,line);
677       return q;
678    }
679 
680    STB_EXTERN int stb_log2_ceil(unsigned int);
stb__calloc(size_t n,size_t sz,char * file,int line)681    static void *stb__calloc(size_t n, size_t sz, char *file, int line)
682    {
683       void *q;
684       stb_mcheck_all();
685       if (n == 0 || sz == 0) return NULL;
686       if (stb_log2_ceil(n) + stb_log2_ceil(sz) >= 32) return NULL;
687       q = stb__malloc(n*sz, file, line);
688       if (q) memset(q, 0, n*sz);
689       return q;
690    }
691 
stb__strdup(char * s,char * file,int line)692    char * stb__strdup(char *s, char *file, int line)
693    {
694       char *p;
695       stb_mcheck_all();
696       p = stb__malloc(strlen(s)+1, file, line);
697       if (!p) return p;
698       strcpy(p, s);
699       return p;
700    }
701    #endif // STB_DEFINE
702 
703    #ifdef STB_FASTMALLOC
704    #undef malloc
705    #undef realloc
706    #undef free
707    #undef strdup
708    #undef calloc
709    #endif
710 
711    // include everything that might define these, BEFORE making macros
712    #include <stdlib.h>
713    #include <string.h>
714    #include <malloc.h>
715 
716    #define malloc(s)      stb__malloc (  s, __FILE__, __LINE__)
717    #define realloc(p,s)   stb__realloc(p,s, __FILE__, __LINE__)
718    #define calloc(n,s)    stb__calloc (n,s, __FILE__, __LINE__)
719    #define free(p)        stb__free   (p,   __FILE__, __LINE__)
720    #define strdup(p)      stb__strdup (p,   __FILE__, __LINE__)
721 
722 #endif
723 
724 //////////////////////////////////////////////////////////////////////////////
725 //
726 //                         Windows pretty display
727 //
728 
729 STB_EXTERN void stbprint(const char *fmt, ...);
730 STB_EXTERN char *stb_sprintf(const char *fmt, ...);
731 STB_EXTERN char *stb_mprintf(const char *fmt, ...);
732 STB_EXTERN int  stb_snprintf(char *s, size_t n, const char *fmt, ...);
733 STB_EXTERN int  stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v);
734 
735 #ifdef STB_DEFINE
736 
stb_vsnprintf(char * s,size_t n,const char * fmt,va_list v)737 int stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v)
738 {
739    int res;
740    #ifdef _WIN32
741    // Could use "_vsnprintf_s(s, n, _TRUNCATE, fmt, v)" ?
742    res = _vsnprintf(s,n,fmt,v);
743    #else
744    res = vsnprintf(s,n,fmt,v);
745    #endif
746    if (n) s[n-1] = 0;
747    // Unix returns length output would require, Windows returns negative when truncated.
748    return (res >= (int) n || res < 0) ? -1 : res;
749 }
750 
stb_snprintf(char * s,size_t n,const char * fmt,...)751 int stb_snprintf(char *s, size_t n, const char *fmt, ...)
752 {
753    int res;
754    va_list v;
755    va_start(v,fmt);
756    res = stb_vsnprintf(s, n, fmt, v);
757    va_end(v);
758    return res;
759 }
760 
stb_sprintf(const char * fmt,...)761 char *stb_sprintf(const char *fmt, ...)
762 {
763    static char buffer[1024];
764    va_list v;
765    va_start(v,fmt);
766    stb_vsnprintf(buffer,1024,fmt,v);
767    va_end(v);
768    return buffer;
769 }
770 
stb_mprintf(const char * fmt,...)771 char *stb_mprintf(const char *fmt, ...)
772 {
773    static char buffer[1024];
774    va_list v;
775    va_start(v,fmt);
776    stb_vsnprintf(buffer,1024,fmt,v);
777    va_end(v);
778    return strdup(buffer);
779 }
780 
781 #ifdef _WIN32
782 
783 #ifndef _WINDOWS_
784 STB_EXTERN __declspec(dllimport) int __stdcall WriteConsoleA(void *, const void *, unsigned int, unsigned int *, void *);
785 STB_EXTERN __declspec(dllimport) void * __stdcall GetStdHandle(unsigned int);
786 STB_EXTERN __declspec(dllimport) int __stdcall SetConsoleTextAttribute(void *, unsigned short);
787 #endif
788 
stb__print_one(void * handle,char * s,int len)789 static void stb__print_one(void *handle, char *s, int len)
790 {
791    if (len)
792       if (WriteConsoleA(handle, s, len, NULL,NULL))
793          fwrite(s, 1, len, stdout); // if it fails, maybe redirected, so do normal
794 }
795 
stb__print(char * s)796 static void stb__print(char *s)
797 {
798    void *handle = GetStdHandle((unsigned int) -11); // STD_OUTPUT_HANDLE
799    int pad=0; // number of padding characters to add
800 
801    char *t = s;
802    while (*s) {
803       int lpad;
804       while (*s && *s != '{') {
805          if (pad) {
806             if (*s == '\r' || *s == '\n')
807                pad = 0;
808             else if (s[0] == ' ' && s[1] == ' ') {
809                stb__print_one(handle, t, s-t);
810                t = s;
811                while (pad) {
812                   stb__print_one(handle, t, 1);
813                   --pad;
814                }
815             }
816          }
817          ++s;
818       }
819       if (!*s) break;
820       stb__print_one(handle, t, s-t);
821       if (s[1] == '{') {
822          ++s;
823          continue;
824       }
825 
826       if (s[1] == '#') {
827          t = s+3;
828          if (isxdigit(s[2]))
829             if (isdigit(s[2]))
830                SetConsoleTextAttribute(handle, s[2] - '0');
831             else
832                SetConsoleTextAttribute(handle, tolower(s[2]) - 'a' + 10);
833          else {
834             SetConsoleTextAttribute(handle, 0x0f);
835             t=s+2;
836          }
837       } else if (s[1] == '!') {
838          SetConsoleTextAttribute(handle, 0x0c);
839          t = s+2;
840       } else if (s[1] == '@') {
841          SetConsoleTextAttribute(handle, 0x09);
842          t = s+2;
843       } else if (s[1] == '$') {
844          SetConsoleTextAttribute(handle, 0x0a);
845          t = s+2;
846       } else {
847          SetConsoleTextAttribute(handle, 0x08); // 0,7,8,15 => shades of grey
848          t = s+1;
849       }
850 
851       lpad = (t-s);
852       s = t;
853       while (*s && *s != '}') ++s;
854       if (!*s) break;
855       stb__print_one(handle, t, s-t);
856       if (s[1] == '}') {
857          t = s+2;
858       } else {
859          pad += 1+lpad;
860          t = s+1;
861       }
862       s=t;
863       SetConsoleTextAttribute(handle, 0x07);
864    }
865    stb__print_one(handle, t, s-t);
866    SetConsoleTextAttribute(handle, 0x07);
867 }
868 
stbprint(const char * fmt,...)869 void stbprint(const char *fmt, ...)
870 {
871    int res;
872    char buffer[1024];
873    char *tbuf = buffer;
874    va_list v;
875 
876    va_start(v,fmt);
877    res = stb_vsnprintf(buffer, sizeof(buffer), fmt, v);
878    va_end(v);
879 
880    if (res < 0) {
881       tbuf = (char *) malloc(16384);
882       va_start(v,fmt);
883       res = _vsnprintf(tbuf,16384, fmt, v);
884       va_end(v);
885       tbuf[16383] = 0;
886    }
887 
888    stb__print(tbuf);
889 
890    if (tbuf != buffer)
891       free(tbuf);
892 }
893 
894 #else  // _WIN32
stbprint(const char * fmt,...)895 void stbprint(const char *fmt, ...)
896 {
897    va_list v;
898    va_start(v,fmt);
899    vprintf(fmt,v);
900    va_end(v);
901 }
902 #endif // _WIN32
903 #endif // STB_DEFINE
904 
905 
906 
907 //////////////////////////////////////////////////////////////////////////////
908 //
909 //                         Windows UTF8 filename handling
910 //
911 // Windows stupidly treats 8-bit filenames as some dopey code page,
912 // rather than utf-8. If we want to use utf8 filenames, we have to
913 // convert them to WCHAR explicitly and call WCHAR versions of the
914 // file functions. So, ok, we do.
915 
916 
917 #ifdef _WIN32
918    #define stb__fopen(x,y)    _wfopen((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y))
919    #define stb__windows(x,y)  x
920 #else
921    #define stb__fopen(x,y)    fopen(x,y)
922    #define stb__windows(x,y)  y
923 #endif
924 
925 
926 typedef unsigned short stb__wchar;
927 
928 STB_EXTERN stb__wchar * stb_from_utf8(stb__wchar *buffer, char *str, int n);
929 STB_EXTERN char       * stb_to_utf8  (char *buffer, stb__wchar *str, int n);
930 
931 STB_EXTERN stb__wchar *stb__from_utf8(char *str);
932 STB_EXTERN stb__wchar *stb__from_utf8_alt(char *str);
933 STB_EXTERN char *stb__to_utf8(stb__wchar *str);
934 
935 
936 #ifdef STB_DEFINE
stb_from_utf8(stb__wchar * buffer,char * ostr,int n)937 stb__wchar * stb_from_utf8(stb__wchar *buffer, char *ostr, int n)
938 {
939    unsigned char *str = (unsigned char *) ostr;
940    stb_uint32 c;
941    int i=0;
942    --n;
943    while (*str) {
944       if (i >= n)
945          return NULL;
946       if (!(*str & 0x80))
947          buffer[i++] = *str++;
948       else if ((*str & 0xe0) == 0xc0) {
949          if (*str < 0xc2) return NULL;
950          c = (*str++ & 0x1f) << 6;
951          if ((*str & 0xc0) != 0x80) return NULL;
952          buffer[i++] = c + (*str++ & 0x3f);
953       } else if ((*str & 0xf0) == 0xe0) {
954          if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return NULL;
955          if (*str == 0xed && str[1] > 0x9f) return NULL; // str[1] < 0x80 is checked below
956          c = (*str++ & 0x0f) << 12;
957          if ((*str & 0xc0) != 0x80) return NULL;
958          c += (*str++ & 0x3f) << 6;
959          if ((*str & 0xc0) != 0x80) return NULL;
960          buffer[i++] = c + (*str++ & 0x3f);
961       } else if ((*str & 0xf8) == 0xf0) {
962          if (*str > 0xf4) return NULL;
963          if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return NULL;
964          if (*str == 0xf4 && str[1] > 0x8f) return NULL; // str[1] < 0x80 is checked below
965          c = (*str++ & 0x07) << 18;
966          if ((*str & 0xc0) != 0x80) return NULL;
967          c += (*str++ & 0x3f) << 12;
968          if ((*str & 0xc0) != 0x80) return NULL;
969          c += (*str++ & 0x3f) << 6;
970          if ((*str & 0xc0) != 0x80) return NULL;
971          c += (*str++ & 0x3f);
972          // utf-8 encodings of values used in surrogate pairs are invalid
973          if ((c & 0xFFFFF800) == 0xD800) return NULL;
974          if (c >= 0x10000) {
975             c -= 0x10000;
976             if (i + 2 > n) return NULL;
977             buffer[i++] = 0xD800 | (0x3ff & (c >> 10));
978             buffer[i++] = 0xDC00 | (0x3ff & (c      ));
979          }
980       } else
981          return NULL;
982    }
983    buffer[i] = 0;
984    return buffer;
985 }
986 
stb_to_utf8(char * buffer,stb__wchar * str,int n)987 char * stb_to_utf8(char *buffer, stb__wchar *str, int n)
988 {
989    int i=0;
990    --n;
991    while (*str) {
992       if (*str < 0x80) {
993          if (i+1 > n) return NULL;
994          buffer[i++] = (char) *str++;
995       } else if (*str < 0x800) {
996          if (i+2 > n) return NULL;
997          buffer[i++] = 0xc0 + (*str >> 6);
998          buffer[i++] = 0x80 + (*str & 0x3f);
999          str += 1;
1000       } else if (*str >= 0xd800 && *str < 0xdc00) {
1001          stb_uint32 c;
1002          if (i+4 > n) return NULL;
1003          c = ((str[0] - 0xd800) << 10) + ((str[1]) - 0xdc00) + 0x10000;
1004          buffer[i++] = 0xf0 + (c >> 18);
1005          buffer[i++] = 0x80 + ((c >> 12) & 0x3f);
1006          buffer[i++] = 0x80 + ((c >>  6) & 0x3f);
1007          buffer[i++] = 0x80 + ((c      ) & 0x3f);
1008          str += 2;
1009       } else if (*str >= 0xdc00 && *str < 0xe000) {
1010          return NULL;
1011       } else {
1012          if (i+3 > n) return NULL;
1013          buffer[i++] = 0xe0 + (*str >> 12);
1014          buffer[i++] = 0x80 + ((*str >> 6) & 0x3f);
1015          buffer[i++] = 0x80 + ((*str     ) & 0x3f);
1016          str += 1;
1017       }
1018    }
1019    buffer[i] = 0;
1020    return buffer;
1021 }
1022 
stb__from_utf8(char * str)1023 stb__wchar *stb__from_utf8(char *str)
1024 {
1025    static stb__wchar buffer[4096];
1026    return stb_from_utf8(buffer, str, 4096);
1027 }
1028 
stb__from_utf8_alt(char * str)1029 stb__wchar *stb__from_utf8_alt(char *str)
1030 {
1031    static stb__wchar buffer[64];
1032    return stb_from_utf8(buffer, str, 64);
1033 }
1034 
stb__to_utf8(stb__wchar * str)1035 char *stb__to_utf8(stb__wchar *str)
1036 {
1037    static char buffer[4096];
1038    return stb_to_utf8(buffer, str, 4096);
1039 }
1040 
1041 #endif
1042 
1043 //////////////////////////////////////////////////////////////////////////////
1044 //
1045 //                         Miscellany
1046 //
1047 
1048 STB_EXTERN void stb_fatal(char *fmt, ...);
1049 STB_EXTERN void stb_(char *fmt, ...);
1050 STB_EXTERN void stb_append_to_file(char *file, char *fmt, ...);
1051 STB_EXTERN void stb_log(int active);
1052 STB_EXTERN void stb_log_fileline(int active);
1053 STB_EXTERN void stb_log_name(char *filename);
1054 
1055 STB_EXTERN void stb_swap(void *p, void *q, size_t sz);
1056 STB_EXTERN void *stb_copy(void *p, size_t sz);
1057 STB_EXTERN void stb_pointer_array_free(void *p, int len);
1058 STB_EXTERN void **stb_array_block_alloc(int count, int blocksize);
1059 
1060 #define stb_arrcount(x)   (sizeof(x)/sizeof((x)[0]))
1061 
1062 
1063 STB_EXTERN int  stb__record_fileline(char *f, int n);
1064 
1065 #ifdef STB_DEFINE
1066 
1067 static char *stb__file;
1068 static int   stb__line;
1069 
stb__record_fileline(char * f,int n)1070 int  stb__record_fileline(char *f, int n)
1071 {
1072    stb__file = f;
1073    stb__line = n;
1074    return 0;
1075 }
1076 
stb_fatal(char * s,...)1077 void stb_fatal(char *s, ...)
1078 {
1079    va_list a;
1080    if (stb__file)
1081       fprintf(stderr, "[%s:%d] ", stb__file, stb__line);
1082    va_start(a,s);
1083    fputs("Fatal error: ", stderr);
1084    vfprintf(stderr, s, a);
1085    va_end(a);
1086    fputs("\n", stderr);
1087    #ifdef STB_DEBUG
1088    #ifdef _MSC_VER
1089    #ifndef STB_PTR64
1090    __asm int 3;   // trap to debugger!
1091    #else
1092    __debugbreak();
1093    #endif
1094    #else
1095    __builtin_trap();
1096    #endif
1097    #endif
1098    exit(1);
1099 }
1100 
1101 static int stb__log_active=1, stb__log_fileline=1;
1102 
stb_log(int active)1103 void stb_log(int active)
1104 {
1105    stb__log_active = active;
1106 }
1107 
stb_log_fileline(int active)1108 void stb_log_fileline(int active)
1109 {
1110    stb__log_fileline = active;
1111 }
1112 
1113 #ifdef STB_NO_STB_STRINGS
1114 char *stb__log_filename = "temp.log";
1115 #else
1116 char *stb__log_filename = "stb.log";
1117 #endif
1118 
stb_log_name(char * s)1119 void stb_log_name(char *s)
1120 {
1121    stb__log_filename = s;
1122 }
1123 
stb_(char * s,...)1124 void stb_(char *s, ...)
1125 {
1126    if (stb__log_active) {
1127       FILE *f = fopen(stb__log_filename, "a");
1128       if (f) {
1129          va_list a;
1130          if (stb__log_fileline && stb__file)
1131             fprintf(f, "[%s:%4d] ", stb__file, stb__line);
1132          va_start(a,s);
1133          vfprintf(f, s, a);
1134          va_end(a);
1135          fputs("\n", f);
1136          fclose(f);
1137       }
1138    }
1139 }
1140 
stb_append_to_file(char * filename,char * s,...)1141 void stb_append_to_file(char *filename, char *s, ...)
1142 {
1143    FILE *f = fopen(filename, "a");
1144    if (f) {
1145       va_list a;
1146       va_start(a,s);
1147       vfprintf(f, s, a);
1148       va_end(a);
1149       fputs("\n", f);
1150       fclose(f);
1151    }
1152 }
1153 
1154 
1155 typedef struct { char d[4]; } stb__4;
1156 typedef struct { char d[8]; } stb__8;
1157 
1158 // optimize the small cases, though you shouldn't be calling this for those!
stb_swap(void * p,void * q,size_t sz)1159 void stb_swap(void *p, void *q, size_t sz)
1160 {
1161    char buffer[256];
1162    if (p == q) return;
1163    if (sz == 4) {
1164       stb__4 temp    = * ( stb__4 *) p;
1165       * (stb__4 *) p = * ( stb__4 *) q;
1166       * (stb__4 *) q = temp;
1167       return;
1168    } else if (sz == 8) {
1169       stb__8 temp    = * ( stb__8 *) p;
1170       * (stb__8 *) p = * ( stb__8 *) q;
1171       * (stb__8 *) q = temp;
1172       return;
1173    }
1174 
1175    while (sz > sizeof(buffer)) {
1176       stb_swap(p, q, sizeof(buffer));
1177       p = (char *) p + sizeof(buffer);
1178       q = (char *) q + sizeof(buffer);
1179       sz -= sizeof(buffer);
1180    }
1181 
1182    memcpy(buffer, p     , sz);
1183    memcpy(p     , q     , sz);
1184    memcpy(q     , buffer, sz);
1185 }
1186 
stb_copy(void * p,size_t sz)1187 void *stb_copy(void *p, size_t sz)
1188 {
1189    void *q = malloc(sz);
1190    memcpy(q, p, sz);
1191    return q;
1192 }
1193 
stb_pointer_array_free(void * q,int len)1194 void stb_pointer_array_free(void *q, int len)
1195 {
1196    void **p = (void **) q;
1197    int i;
1198    for (i=0; i < len; ++i)
1199       free(p[i]);
1200 }
1201 
stb_array_block_alloc(int count,int blocksize)1202 void **stb_array_block_alloc(int count, int blocksize)
1203 {
1204    int i;
1205    char *p = (char *) malloc(sizeof(void *) * count + count * blocksize);
1206    void **q;
1207    if (p == NULL) return NULL;
1208    q = (void **) p;
1209    p += sizeof(void *) * count;
1210    for (i=0; i < count; ++i)
1211       q[i] = p + i * blocksize;
1212    return q;
1213 }
1214 #endif
1215 
1216 #ifdef STB_DEBUG
1217    // tricky hack to allow recording FILE,LINE even in varargs functions
1218    #define STB__RECORD_FILE(x)  (stb__record_fileline(__FILE__, __LINE__),(x))
1219    #define stb_log              STB__RECORD_FILE(stb_log)
1220    #define stb_                 STB__RECORD_FILE(stb_)
1221    #ifndef STB_FATAL_CLEAN
1222    #define stb_fatal            STB__RECORD_FILE(stb_fatal)
1223    #endif
1224    #define STB__DEBUG(x)        x
1225 #else
1226    #define STB__DEBUG(x)
1227 #endif
1228 
1229 //////////////////////////////////////////////////////////////////////////////
1230 //
1231 //                         stb_temp
1232 //
1233 
1234 #define stb_temp(block, sz)     stb__temp(block, sizeof(block), (sz))
1235 
1236 STB_EXTERN void * stb__temp(void *b, int b_sz, int want_sz);
1237 STB_EXTERN void   stb_tempfree(void *block, void *ptr);
1238 
1239 #ifdef STB_DEFINE
1240 
stb__temp(void * b,int b_sz,int want_sz)1241 void * stb__temp(void *b, int b_sz, int want_sz)
1242 {
1243    if (b_sz >= want_sz)
1244       return b;
1245    else
1246       return malloc(want_sz);
1247 }
1248 
stb_tempfree(void * b,void * p)1249 void   stb_tempfree(void *b, void *p)
1250 {
1251    if (p != b)
1252       free(p);
1253 }
1254 #endif
1255 
1256 
1257 //////////////////////////////////////////////////////////////////////////////
1258 //
1259 //                      math/sampling operations
1260 //
1261 
1262 
1263 #define stb_lerp(t,a,b)               ( (a) + (t) * (float) ((b)-(a)) )
1264 #define stb_unlerp(t,a,b)             ( ((t) - (a)) / (float) ((b) - (a)) )
1265 
1266 #define stb_clamp(x,xmin,xmax)  ((x) < (xmin) ? (xmin) : (x) > (xmax) ? (xmax) : (x))
1267 
1268 STB_EXTERN void stb_newell_normal(float *normal, int num_vert, float **vert, int normalize);
1269 STB_EXTERN int stb_box_face_vertex_axis_side(int face_number, int vertex_number, int axis);
1270 STB_EXTERN void stb_linear_controller(float *curpos, float target_pos, float acc, float deacc, float dt);
1271 
1272 STB_EXTERN int stb_float_eq(float x, float y, float delta, int max_ulps);
1273 STB_EXTERN int stb_is_prime(unsigned int m);
1274 STB_EXTERN unsigned int stb_power_of_two_nearest_prime(int n);
1275 
1276 STB_EXTERN float stb_smoothstep(float t);
1277 STB_EXTERN float stb_cubic_bezier_1d(float t, float p0, float p1, float p2, float p3);
1278 
1279 STB_EXTERN double stb_linear_remap(double x, double a, double b,
1280                                              double c, double d);
1281 
1282 #ifdef STB_DEFINE
stb_smoothstep(float t)1283 float stb_smoothstep(float t)
1284 {
1285    return (3 - 2*t)*(t*t);
1286 }
1287 
stb_cubic_bezier_1d(float t,float p0,float p1,float p2,float p3)1288 float stb_cubic_bezier_1d(float t, float p0, float p1, float p2, float p3)
1289 {
1290    float it = 1-t;
1291    return it*it*it*p0 + 3*it*it*t*p1 + 3*it*t*t*p2 + t*t*t*p3;
1292 }
1293 
stb_newell_normal(float * normal,int num_vert,float ** vert,int normalize)1294 void stb_newell_normal(float *normal, int num_vert, float **vert, int normalize)
1295 {
1296    int i,j;
1297    float p;
1298    normal[0] = normal[1] = normal[2] = 0;
1299    for (i=num_vert-1,j=0; j < num_vert; i=j++) {
1300       float *u = vert[i];
1301       float *v = vert[j];
1302       normal[0] += (u[1] - v[1]) * (u[2] + v[2]);
1303       normal[1] += (u[2] - v[2]) * (u[0] + v[0]);
1304       normal[2] += (u[0] - v[0]) * (u[1] + v[1]);
1305    }
1306    if (normalize) {
1307       p = normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2];
1308       p = (float) (1.0 / sqrt(p));
1309       normal[0] *= p;
1310       normal[1] *= p;
1311       normal[2] *= p;
1312    }
1313 }
1314 
stb_box_face_vertex_axis_side(int face_number,int vertex_number,int axis)1315 int stb_box_face_vertex_axis_side(int face_number, int vertex_number, int axis)
1316 {
1317    static int box_vertices[6][4][3] =
1318    {
1319       { { 1,1,1 }, { 1,0,1 }, { 1,0,0 }, { 1,1,0 } },
1320       { { 0,0,0 }, { 0,0,1 }, { 0,1,1 }, { 0,1,0 } },
1321       { { 0,0,0 }, { 0,1,0 }, { 1,1,0 }, { 1,0,0 } },
1322       { { 0,0,0 }, { 1,0,0 }, { 1,0,1 }, { 0,0,1 } },
1323       { { 1,1,1 }, { 0,1,1 }, { 0,0,1 }, { 1,0,1 } },
1324       { { 1,1,1 }, { 1,1,0 }, { 0,1,0 }, { 0,1,1 } },
1325    };
1326    assert(face_number >= 0 && face_number < 6);
1327    assert(vertex_number >= 0 && vertex_number < 4);
1328    assert(axis >= 0 && axis < 3);
1329    return box_vertices[face_number][vertex_number][axis];
1330 }
1331 
stb_linear_controller(float * curpos,float target_pos,float acc,float deacc,float dt)1332 void stb_linear_controller(float *curpos, float target_pos, float acc, float deacc, float dt)
1333 {
1334    float sign = 1, p, cp = *curpos;
1335    if (cp == target_pos) return;
1336    if (target_pos < cp) {
1337       target_pos = -target_pos;
1338       cp = -cp;
1339       sign = -1;
1340    }
1341    // first decelerate
1342    if (cp < 0) {
1343       p = cp + deacc * dt;
1344       if (p > 0) {
1345          p = 0;
1346          dt = dt - cp / deacc;
1347          if (dt < 0) dt = 0;
1348       } else {
1349          dt = 0;
1350       }
1351       cp = p;
1352    }
1353    // now accelerate
1354    p = cp + acc*dt;
1355    if (p > target_pos) p = target_pos;
1356    *curpos = p * sign;
1357    // @TODO: testing
1358 }
1359 
stb_quadratic_controller(float target_pos,float curpos,float maxvel,float maxacc,float dt,float * curvel)1360 float stb_quadratic_controller(float target_pos, float curpos, float maxvel, float maxacc, float dt, float *curvel)
1361 {
1362    return 0; // @TODO
1363 }
1364 
stb_float_eq(float x,float y,float delta,int max_ulps)1365 int stb_float_eq(float x, float y, float delta, int max_ulps)
1366 {
1367    if (fabs(x-y) <= delta) return 1;
1368    if (abs(*(int *)&x - *(int *)&y) <= max_ulps) return 1;
1369    return 0;
1370 }
1371 
stb_is_prime(unsigned int m)1372 int stb_is_prime(unsigned int m)
1373 {
1374    unsigned int i,j;
1375    if (m < 2) return 0;
1376    if (m == 2) return 1;
1377    if (!(m & 1)) return 0;
1378    if (m % 3 == 0) return (m == 3);
1379    for (i=5; (j=i*i), j <= m && j > i; i += 6) {
1380       if (m %   i   == 0) return 0;
1381       if (m % (i+2) == 0) return 0;
1382    }
1383    return 1;
1384 }
1385 
stb_power_of_two_nearest_prime(int n)1386 unsigned int stb_power_of_two_nearest_prime(int n)
1387 {
1388    static signed char tab[32] = { 0,0,0,0,1,0,-1,0,1,-1,-1,3,-1,0,-1,2,1,
1389                                    0,2,0,-1,-4,-1,5,-1,18,-2,15,2,-1,2,0 };
1390    if (!tab[0]) {
1391       int i;
1392       for (i=0; i < 32; ++i)
1393          tab[i] = (1 << i) + 2*tab[i] - 1;
1394       tab[1] = 2;
1395       tab[0] = 1;
1396    }
1397    if (n >= 32) return 0xfffffffb;
1398    return tab[n];
1399 }
1400 
stb_linear_remap(double x,double x_min,double x_max,double out_min,double out_max)1401 double stb_linear_remap(double x, double x_min, double x_max,
1402                                   double out_min, double out_max)
1403 {
1404    return stb_lerp(stb_unlerp(x,x_min,x_max),out_min,out_max);
1405 }
1406 #endif
1407 
1408 // create a macro so it's faster, but you can get at the function pointer
1409 #define stb_linear_remap(t,a,b,c,d)   stb_lerp(stb_unlerp(t,a,b),c,d)
1410 
1411 
1412 //////////////////////////////////////////////////////////////////////////////
1413 //
1414 //                         bit operations
1415 //
1416 
1417 #define stb_big32(c)    (((c)[0]<<24) + (c)[1]*65536 + (c)[2]*256 + (c)[3])
1418 #define stb_little32(c) (((c)[3]<<24) + (c)[2]*65536 + (c)[1]*256 + (c)[0])
1419 #define stb_big16(c)    ((c)[0]*256 + (c)[1])
1420 #define stb_little16(c) ((c)[1]*256 + (c)[0])
1421 
1422 STB_EXTERN          int stb_bitcount(unsigned int a);
1423 STB_EXTERN unsigned int stb_bitreverse8(unsigned char n);
1424 STB_EXTERN unsigned int stb_bitreverse(unsigned int n);
1425 
1426 STB_EXTERN          int stb_is_pow2(unsigned int n);
1427 STB_EXTERN          int stb_log2_ceil(unsigned int n);
1428 STB_EXTERN          int stb_log2_floor(unsigned int n);
1429 
1430 STB_EXTERN          int stb_lowbit8(unsigned int n);
1431 STB_EXTERN          int stb_highbit8(unsigned int n);
1432 
1433 #ifdef STB_DEFINE
stb_bitcount(unsigned int a)1434 int stb_bitcount(unsigned int a)
1435 {
1436    a = (a & 0x55555555) + ((a >>  1) & 0x55555555); // max 2
1437    a = (a & 0x33333333) + ((a >>  2) & 0x33333333); // max 4
1438    a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
1439    a = (a + (a >> 8)); // max 16 per 8 bits
1440    a = (a + (a >> 16)); // max 32 per 8 bits
1441    return a & 0xff;
1442 }
1443 
stb_bitreverse8(unsigned char n)1444 unsigned int stb_bitreverse8(unsigned char n)
1445 {
1446    n = ((n & 0xAA) >> 1) + ((n & 0x55) << 1);
1447    n = ((n & 0xCC) >> 2) + ((n & 0x33) << 2);
1448    return (unsigned char) ((n >> 4) + (n << 4));
1449 }
1450 
stb_bitreverse(unsigned int n)1451 unsigned int stb_bitreverse(unsigned int n)
1452 {
1453   n = ((n & 0xAAAAAAAA) >>  1) | ((n & 0x55555555) << 1);
1454   n = ((n & 0xCCCCCCCC) >>  2) | ((n & 0x33333333) << 2);
1455   n = ((n & 0xF0F0F0F0) >>  4) | ((n & 0x0F0F0F0F) << 4);
1456   n = ((n & 0xFF00FF00) >>  8) | ((n & 0x00FF00FF) << 8);
1457   return (n >> 16) | (n << 16);
1458 }
1459 
stb_is_pow2(unsigned int n)1460 int stb_is_pow2(unsigned int n)
1461 {
1462    return (n & (n-1)) == 0;
1463 }
1464 
1465 // tricky use of 4-bit table to identify 5 bit positions (note the '-1')
1466 // 3-bit table would require another tree level; 5-bit table wouldn't save one
1467 #if defined(_WIN32) && !defined(__MINGW32__)
1468 #pragma warning(push)
1469 #pragma warning(disable: 4035)  // disable warning about no return value
stb_log2_floor(unsigned int n)1470 int stb_log2_floor(unsigned int n)
1471 {
1472    #if _MSC_VER > 1700
1473    unsigned long i;
1474    _BitScanReverse(&i, n);
1475    return i != 0 ? i : -1;
1476    #else
1477    __asm {
1478       bsr eax,n
1479       jnz done
1480       mov eax,-1
1481    }
1482    done:;
1483    #endif
1484 }
1485 #pragma warning(pop)
1486 #else
stb_log2_floor(unsigned int n)1487 int stb_log2_floor(unsigned int n)
1488 {
1489    static signed char log2_4[16] = { -1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3 };
1490 
1491    // 2 compares if n < 16, 3 compares otherwise
1492    if (n < (1U << 14))
1493         if (n < (1U <<  4))        return     0 + log2_4[n      ];
1494         else if (n < (1U <<  9))      return  5 + log2_4[n >>  5];
1495              else                     return 10 + log2_4[n >> 10];
1496    else if (n < (1U << 24))
1497              if (n < (1U << 19))      return 15 + log2_4[n >> 15];
1498              else                     return 20 + log2_4[n >> 20];
1499         else if (n < (1U << 29))      return 25 + log2_4[n >> 25];
1500              else                     return 30 + log2_4[n >> 30];
1501 }
1502 #endif
1503 
1504 // define ceil from floor
stb_log2_ceil(unsigned int n)1505 int stb_log2_ceil(unsigned int n)
1506 {
1507    if (stb_is_pow2(n))  return     stb_log2_floor(n);
1508    else                 return 1 + stb_log2_floor(n);
1509 }
1510 
stb_highbit8(unsigned int n)1511 int stb_highbit8(unsigned int n)
1512 {
1513    return stb_log2_ceil(n&255);
1514 }
1515 
stb_lowbit8(unsigned int n)1516 int stb_lowbit8(unsigned int n)
1517 {
1518    static signed char lowbit4[16] = { -1,0,1,0, 2,0,1,0, 3,0,1,0, 2,0,1,0 };
1519    int k = lowbit4[n & 15];
1520    if (k >= 0) return k;
1521    k = lowbit4[(n >> 4) & 15];
1522    if (k >= 0) return k+4;
1523    return k;
1524 }
1525 #endif
1526 
1527 
1528 
1529 //////////////////////////////////////////////////////////////////////////////
1530 //
1531 //                            qsort Compare Routines
1532 //
1533 
1534 #ifdef _WIN32
1535    #define stb_stricmp(a,b) stricmp(a,b)
1536    #define stb_strnicmp(a,b,n) strnicmp(a,b,n)
1537 #else
1538    #define stb_stricmp(a,b) strcasecmp(a,b)
1539    #define stb_strnicmp(a,b,n) strncasecmp(a,b,n)
1540 #endif
1541 
1542 
1543 STB_EXTERN int (*stb_intcmp(int offset))(const void *a, const void *b);
1544 STB_EXTERN int (*stb_qsort_strcmp(int offset))(const void *a, const void *b);
1545 STB_EXTERN int (*stb_qsort_stricmp(int offset))(const void *a, const void *b);
1546 STB_EXTERN int (*stb_floatcmp(int offset))(const void *a, const void *b);
1547 STB_EXTERN int (*stb_doublecmp(int offset))(const void *a, const void *b);
1548 STB_EXTERN int (*stb_charcmp(int offset))(const void *a, const void *b);
1549 
1550 #ifdef STB_DEFINE
1551 static int stb__intcmpoffset, stb__charcmpoffset, stb__strcmpoffset;
1552 static int stb__floatcmpoffset, stb__doublecmpoffset;
1553 
stb__intcmp(const void * a,const void * b)1554 int stb__intcmp(const void *a, const void *b)
1555 {
1556    const int p = *(const int *) ((const char *) a + stb__intcmpoffset);
1557    const int q = *(const int *) ((const char *) b + stb__intcmpoffset);
1558    return p < q ? -1 : p > q;
1559 }
1560 
stb__charcmp(const void * a,const void * b)1561 int stb__charcmp(const void *a, const void *b)
1562 {
1563    const int p = *(const unsigned char *) ((const char *) a + stb__charcmpoffset);
1564    const int q = *(const unsigned char *) ((const char *) b + stb__charcmpoffset);
1565    return p < q ? -1 : p > q;
1566 }
1567 
stb__floatcmp(const void * a,const void * b)1568 int stb__floatcmp(const void *a, const void *b)
1569 {
1570    const float p = *(const float *) ((const char *) a + stb__floatcmpoffset);
1571    const float q = *(const float *) ((const char *) b + stb__floatcmpoffset);
1572    return p < q ? -1 : p > q;
1573 }
1574 
stb__doublecmp(const void * a,const void * b)1575 int stb__doublecmp(const void *a, const void *b)
1576 {
1577    const double p = *(const double *) ((const char *) a + stb__doublecmpoffset);
1578    const double q = *(const double *) ((const char *) b + stb__doublecmpoffset);
1579    return p < q ? -1 : p > q;
1580 }
1581 
stb__qsort_strcmp(const void * a,const void * b)1582 int stb__qsort_strcmp(const void *a, const void *b)
1583 {
1584    const char *p = *(const char **) ((const char *) a + stb__strcmpoffset);
1585    const char *q = *(const char **) ((const char *) b + stb__strcmpoffset);
1586    return strcmp(p,q);
1587 }
1588 
stb__qsort_stricmp(const void * a,const void * b)1589 int stb__qsort_stricmp(const void *a, const void *b)
1590 {
1591    const char *p = *(const char **) ((const char *) a + stb__strcmpoffset);
1592    const char *q = *(const char **) ((const char *) b + stb__strcmpoffset);
1593    return stb_stricmp(p,q);
1594 }
1595 
stb_intcmp(int offset)1596 int (*stb_intcmp(int offset))(const void *, const void *)
1597 {
1598    stb__intcmpoffset = offset;
1599    return &stb__intcmp;
1600 }
1601 
stb_charcmp(int offset)1602 int (*stb_charcmp(int offset))(const void *, const void *)
1603 {
1604    stb__charcmpoffset = offset;
1605    return &stb__charcmp;
1606 }
1607 
stb_qsort_strcmp(int offset)1608 int (*stb_qsort_strcmp(int offset))(const void *, const void *)
1609 {
1610    stb__strcmpoffset = offset;
1611    return &stb__qsort_strcmp;
1612 }
1613 
stb_qsort_stricmp(int offset)1614 int (*stb_qsort_stricmp(int offset))(const void *, const void *)
1615 {
1616    stb__strcmpoffset = offset;
1617    return &stb__qsort_stricmp;
1618 }
1619 
stb_floatcmp(int offset)1620 int (*stb_floatcmp(int offset))(const void *, const void *)
1621 {
1622    stb__floatcmpoffset = offset;
1623    return &stb__floatcmp;
1624 }
1625 
stb_doublecmp(int offset)1626 int (*stb_doublecmp(int offset))(const void *, const void *)
1627 {
1628    stb__doublecmpoffset = offset;
1629    return &stb__doublecmp;
1630 }
1631 
1632 #endif
1633 
1634 //////////////////////////////////////////////////////////////////////////////
1635 //
1636 //                           Binary Search Toolkit
1637 //
1638 
1639 typedef struct
1640 {
1641    int minval, maxval, guess;
1642    int mode, step;
1643 } stb_search;
1644 
1645 STB_EXTERN int stb_search_binary(stb_search *s, int minv, int maxv, int find_smallest);
1646 STB_EXTERN int stb_search_open(stb_search *s, int minv, int find_smallest);
1647 STB_EXTERN int stb_probe(stb_search *s, int compare, int *result); // return 0 when done
1648 
1649 #ifdef STB_DEFINE
1650 enum
1651 {
1652    STB_probe_binary_smallest,
1653    STB_probe_binary_largest,
1654    STB_probe_open_smallest,
1655    STB_probe_open_largest,
1656 };
1657 
stb_probe_guess(stb_search * s,int * result)1658 static int stb_probe_guess(stb_search *s, int *result)
1659 {
1660    switch(s->mode) {
1661       case STB_probe_binary_largest:
1662          if (s->minval == s->maxval) {
1663             *result = s->minval;
1664             return 0;
1665          }
1666          assert(s->minval < s->maxval);
1667          // if a < b, then a < p <= b
1668          s->guess = s->minval + (((unsigned) s->maxval - s->minval + 1) >> 1);
1669          break;
1670 
1671       case STB_probe_binary_smallest:
1672          if (s->minval == s->maxval) {
1673             *result = s->minval;
1674             return 0;
1675          }
1676          assert(s->minval < s->maxval);
1677          // if a < b, then a <= p < b
1678          s->guess = s->minval + (((unsigned) s->maxval - s->minval) >> 1);
1679          break;
1680       case STB_probe_open_smallest:
1681       case STB_probe_open_largest:
1682          s->guess = s->maxval;  // guess the current maxval
1683          break;
1684    }
1685    *result = s->guess;
1686    return 1;
1687 }
1688 
stb_probe(stb_search * s,int compare,int * result)1689 int stb_probe(stb_search *s, int compare, int *result)
1690 {
1691    switch(s->mode) {
1692       case STB_probe_open_smallest:
1693       case STB_probe_open_largest: {
1694          if (compare <= 0) {
1695             // then it lies within minval & maxval
1696             if (s->mode == STB_probe_open_smallest)
1697                s->mode = STB_probe_binary_smallest;
1698             else
1699                s->mode = STB_probe_binary_largest;
1700          } else {
1701             // otherwise, we need to probe larger
1702             s->minval  = s->maxval + 1;
1703             s->maxval  = s->minval + s->step;
1704             s->step   += s->step;
1705          }
1706          break;
1707       }
1708       case STB_probe_binary_smallest: {
1709          // if compare < 0, then s->minval <= a <  p
1710          // if compare = 0, then s->minval <= a <= p
1711          // if compare > 0, then         p <  a <= s->maxval
1712          if (compare <= 0)
1713             s->maxval = s->guess;
1714          else
1715             s->minval = s->guess+1;
1716          break;
1717       }
1718       case STB_probe_binary_largest: {
1719          // if compare < 0, then s->minval <= a < p
1720          // if compare = 0, then         p <= a <= s->maxval
1721          // if compare > 0, then         p <  a <= s->maxval
1722          if (compare < 0)
1723             s->maxval = s->guess-1;
1724          else
1725             s->minval = s->guess;
1726          break;
1727       }
1728    }
1729    return stb_probe_guess(s, result);
1730 }
1731 
stb_search_binary(stb_search * s,int minv,int maxv,int find_smallest)1732 int stb_search_binary(stb_search *s, int minv, int maxv, int find_smallest)
1733 {
1734    int r;
1735    if (maxv < minv) return minv-1;
1736    s->minval = minv;
1737    s->maxval = maxv;
1738    s->mode = find_smallest ? STB_probe_binary_smallest : STB_probe_binary_largest;
1739    stb_probe_guess(s, &r);
1740    return r;
1741 }
1742 
stb_search_open(stb_search * s,int minv,int find_smallest)1743 int stb_search_open(stb_search *s, int minv, int find_smallest)
1744 {
1745    int r;
1746    s->step   = 4;
1747    s->minval = minv;
1748    s->maxval = minv+s->step;
1749    s->mode = find_smallest ? STB_probe_open_smallest : STB_probe_open_largest;
1750    stb_probe_guess(s, &r);
1751    return r;
1752 }
1753 #endif
1754 
1755 //////////////////////////////////////////////////////////////////////////////
1756 //
1757 //                           String Processing
1758 //
1759 
1760 #define stb_prefixi(s,t)  (0==stb_strnicmp((s),(t),strlen(t)))
1761 
1762 enum stb_splitpath_flag
1763 {
1764    STB_PATH = 1,
1765    STB_FILE = 2,
1766    STB_EXT  = 4,
1767    STB_PATH_FILE = STB_PATH + STB_FILE,
1768    STB_FILE_EXT  = STB_FILE + STB_EXT,
1769    STB_EXT_NO_PERIOD = 8,
1770 };
1771 
1772 STB_EXTERN char * stb_skipwhite(char *s);
1773 STB_EXTERN char * stb_trimwhite(char *s);
1774 STB_EXTERN char * stb_skipnewline(char *s);
1775 STB_EXTERN char * stb_strncpy(char *s, char *t, int n);
1776 STB_EXTERN char * stb_substr(char *t, int n);
1777 STB_EXTERN char * stb_duplower(char *s);
1778 STB_EXTERN void   stb_tolower (char *s);
1779 STB_EXTERN char * stb_strchr2 (char *s, char p1, char p2);
1780 STB_EXTERN char * stb_strrchr2(char *s, char p1, char p2);
1781 STB_EXTERN char * stb_strtok(char *output, char *src, char *delimit);
1782 STB_EXTERN char * stb_strtok_keep(char *output, char *src, char *delimit);
1783 STB_EXTERN char * stb_strtok_invert(char *output, char *src, char *allowed);
1784 STB_EXTERN char * stb_dupreplace(char *s, char *find, char *replace);
1785 STB_EXTERN void   stb_replaceinplace(char *s, char *find, char *replace);
1786 STB_EXTERN char * stb_splitpath(char *output, char *src, int flag);
1787 STB_EXTERN char * stb_splitpathdup(char *src, int flag);
1788 STB_EXTERN char * stb_replacedir(char *output, char *src, char *dir);
1789 STB_EXTERN char * stb_replaceext(char *output, char *src, char *ext);
1790 STB_EXTERN void   stb_fixpath(char *path);
1791 STB_EXTERN char * stb_shorten_path_readable(char *path, int max_len);
1792 STB_EXTERN int    stb_suffix (char *s, char *t);
1793 STB_EXTERN int    stb_suffixi(char *s, char *t);
1794 STB_EXTERN int    stb_prefix (char *s, char *t);
1795 STB_EXTERN char * stb_strichr(char *s, char t);
1796 STB_EXTERN char * stb_stristr(char *s, char *t);
1797 STB_EXTERN int    stb_prefix_count(char *s, char *t);
1798 STB_EXTERN char * stb_plural(int n);  // "s" or ""
1799 STB_EXTERN size_t stb_strscpy(char *d, const char *s, size_t n);
1800 
1801 STB_EXTERN char **stb_tokens(char *src, char *delimit, int *count);
1802 STB_EXTERN char **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out);
1803 STB_EXTERN char **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out);
1804 STB_EXTERN char **stb_tokens_allowempty(char *src, char *delimit, int *count);
1805 STB_EXTERN char **stb_tokens_stripwhite(char *src, char *delimit, int *count);
1806 STB_EXTERN char **stb_tokens_withdelim(char *src, char *delimit, int *count);
1807 STB_EXTERN char **stb_tokens_quoted(char *src, char *delimit, int *count);
1808 // with 'quoted', allow delimiters to appear inside quotation marks, and don't
1809 // strip whitespace inside them (and we delete the quotation marks unless they
1810 // appear back to back, in which case they're considered escaped)
1811 
1812 #ifdef STB_DEFINE
1813 
stb_strscpy(char * d,const char * s,size_t n)1814 size_t stb_strscpy(char *d, const char *s, size_t n)
1815 {
1816    size_t len = strlen(s);
1817    if (len >= n) {
1818       if (n) d[0] = 0;
1819       return 0;
1820    }
1821    strcpy(d,s);
1822    return len + 1;
1823 }
1824 
stb_plural(int n)1825 char *stb_plural(int n)
1826 {
1827    return n == 1 ? "" : "s";
1828 }
1829 
stb_prefix(char * s,char * t)1830 int stb_prefix(char *s, char *t)
1831 {
1832    while (*t)
1833       if (*s++ != *t++)
1834          return STB_FALSE;
1835    return STB_TRUE;
1836 }
1837 
stb_prefix_count(char * s,char * t)1838 int stb_prefix_count(char *s, char *t)
1839 {
1840    int c=0;
1841    while (*t) {
1842       if (*s++ != *t++)
1843          break;
1844       ++c;
1845    }
1846    return c;
1847 }
1848 
stb_suffix(char * s,char * t)1849 int stb_suffix(char *s, char *t)
1850 {
1851    size_t n = strlen(s);
1852    size_t m = strlen(t);
1853    if (m <= n)
1854       return 0 == strcmp(s+n-m, t);
1855    else
1856       return 0;
1857 }
1858 
stb_suffixi(char * s,char * t)1859 int stb_suffixi(char *s, char *t)
1860 {
1861    size_t n = strlen(s);
1862    size_t m = strlen(t);
1863    if (m <= n)
1864       return 0 == stb_stricmp(s+n-m, t);
1865    else
1866       return 0;
1867 }
1868 
1869 // originally I was using this table so that I could create known sentinel
1870 // values--e.g. change whitetable[0] to be true if I was scanning for whitespace,
1871 // and false if I was scanning for nonwhite. I don't appear to be using that
1872 // functionality anymore (I do for tokentable, though), so just replace it
1873 // with isspace()
stb_skipwhite(char * s)1874 char *stb_skipwhite(char *s)
1875 {
1876    while (isspace((unsigned char) *s)) ++s;
1877    return s;
1878 }
1879 
stb_skipnewline(char * s)1880 char *stb_skipnewline(char *s)
1881 {
1882    if (s[0] == '\r' || s[0] == '\n') {
1883       if (s[0]+s[1] == '\r' + '\n') ++s;
1884       ++s;
1885    }
1886    return s;
1887 }
1888 
stb_trimwhite(char * s)1889 char *stb_trimwhite(char *s)
1890 {
1891    int i,n;
1892    s = stb_skipwhite(s);
1893    n = (int) strlen(s);
1894    for (i=n-1; i >= 0; --i)
1895       if (!isspace(s[i]))
1896          break;
1897    s[i+1] = 0;
1898    return s;
1899 }
1900 
stb_strncpy(char * s,char * t,int n)1901 char *stb_strncpy(char *s, char *t, int n)
1902 {
1903    strncpy(s,t,n);
1904    s[n-1] = 0;
1905    return s;
1906 }
1907 
stb_substr(char * t,int n)1908 char *stb_substr(char *t, int n)
1909 {
1910    char *a;
1911    int z = (int) strlen(t);
1912    if (z < n) n = z;
1913    a = (char *) malloc(n+1);
1914    strncpy(a,t,n);
1915    a[n] = 0;
1916    return a;
1917 }
1918 
stb_duplower(char * s)1919 char *stb_duplower(char *s)
1920 {
1921    char *p = strdup(s), *q = p;
1922    while (*q) {
1923       *q = tolower(*q);
1924       ++q;
1925    }
1926    return p;
1927 }
1928 
stb_tolower(char * s)1929 void stb_tolower(char *s)
1930 {
1931    while (*s) {
1932       *s = tolower(*s);
1933       ++s;
1934    }
1935 }
1936 
stb_strchr2(char * s,char x,char y)1937 char *stb_strchr2(char *s, char x, char y)
1938 {
1939    for(; *s; ++s)
1940       if (*s == x || *s == y)
1941          return s;
1942    return NULL;
1943 }
1944 
stb_strrchr2(char * s,char x,char y)1945 char *stb_strrchr2(char *s, char x, char y)
1946 {
1947    char *r = NULL;
1948    for(; *s; ++s)
1949       if (*s == x || *s == y)
1950          r = s;
1951    return r;
1952 }
1953 
stb_strichr(char * s,char t)1954 char *stb_strichr(char *s, char t)
1955 {
1956    if (tolower(t) == toupper(t))
1957       return strchr(s,t);
1958    return stb_strchr2(s, (char) tolower(t), (char) toupper(t));
1959 }
1960 
stb_stristr(char * s,char * t)1961 char *stb_stristr(char *s, char *t)
1962 {
1963    size_t n = strlen(t);
1964    char *z;
1965    if (n==0) return s;
1966    while ((z = stb_strichr(s, *t)) != NULL) {
1967       if (0==stb_strnicmp(z, t, n))
1968          return z;
1969       s = z+1;
1970    }
1971    return NULL;
1972 }
1973 
stb_strtok_raw(char * output,char * src,char * delimit,int keep,int invert)1974 static char *stb_strtok_raw(char *output, char *src, char *delimit, int keep, int invert)
1975 {
1976    if (invert) {
1977       while (*src && strchr(delimit, *src) != NULL) {
1978          *output++ = *src++;
1979       }
1980    } else {
1981       while (*src && strchr(delimit, *src) == NULL) {
1982          *output++ = *src++;
1983       }
1984    }
1985    *output = 0;
1986    if (keep)
1987       return src;
1988    else
1989       return *src ? src+1 : src;
1990 }
1991 
stb_strtok(char * output,char * src,char * delimit)1992 char *stb_strtok(char *output, char *src, char *delimit)
1993 {
1994    return stb_strtok_raw(output, src, delimit, 0, 0);
1995 }
1996 
stb_strtok_keep(char * output,char * src,char * delimit)1997 char *stb_strtok_keep(char *output, char *src, char *delimit)
1998 {
1999    return stb_strtok_raw(output, src, delimit, 1, 0);
2000 }
2001 
stb_strtok_invert(char * output,char * src,char * delimit)2002 char *stb_strtok_invert(char *output, char *src, char *delimit)
2003 {
2004    return stb_strtok_raw(output, src, delimit, 1,1);
2005 }
2006 
stb_tokens_raw(char * src_,char * delimit,int * count,int stripwhite,int allow_empty,char * start,char * end)2007 static char **stb_tokens_raw(char *src_, char *delimit, int *count,
2008                              int stripwhite, int allow_empty, char *start, char *end)
2009 {
2010    int nested = 0;
2011    unsigned char *src = (unsigned char *) src_;
2012    static char stb_tokentable[256]; // rely on static initializion to 0
2013    static char stable[256],etable[256];
2014    char *out;
2015    char **result;
2016    int num=0;
2017    unsigned char *s;
2018 
2019    s = (unsigned char *) delimit; while (*s) stb_tokentable[*s++] = 1;
2020    if (start) {
2021       s = (unsigned char *) start;         while (*s) stable[*s++] = 1;
2022       s = (unsigned char *) end;   if (s)  while (*s) stable[*s++] = 1;
2023       s = (unsigned char *) end;   if (s)  while (*s) etable[*s++] = 1;
2024    }
2025    stable[0] = 1;
2026 
2027    // two passes through: the first time, counting how many
2028    s = (unsigned char *) src;
2029    while (*s) {
2030       // state: just found delimiter
2031       // skip further delimiters
2032       if (!allow_empty) {
2033          stb_tokentable[0] = 0;
2034          while (stb_tokentable[*s])
2035             ++s;
2036          if (!*s) break;
2037       }
2038       ++num;
2039       // skip further non-delimiters
2040       stb_tokentable[0] = 1;
2041       if (stripwhite == 2) { // quoted strings
2042          while (!stb_tokentable[*s]) {
2043             if (*s != '"')
2044                ++s;
2045             else {
2046                ++s;
2047                if (*s == '"')
2048                   ++s;   // "" -> ", not start a string
2049                else {
2050                   // begin a string
2051                   while (*s) {
2052                      if (s[0] == '"') {
2053                         if (s[1] == '"') s += 2; // "" -> "
2054                         else { ++s; break; } // terminating "
2055                      } else
2056                         ++s;
2057                   }
2058                }
2059             }
2060          }
2061       } else
2062          while (nested || !stb_tokentable[*s]) {
2063             if (stable[*s]) {
2064                if (!*s) break;
2065                if (end ? etable[*s] : nested)
2066                   --nested;
2067                else
2068                   ++nested;
2069             }
2070             ++s;
2071          }
2072       if (allow_empty) {
2073          if (*s) ++s;
2074       }
2075    }
2076    // now num has the actual count... malloc our output structure
2077    // need space for all the strings: strings won't be any longer than
2078    // original input, since for every '\0' there's at least one delimiter
2079    result = (char **) malloc(sizeof(*result) * (num+1) + (s-src+1));
2080    if (result == NULL) return result;
2081    out = (char *) (result + (num+1));
2082    // second pass: copy out the data
2083    s = (unsigned char *) src;
2084    num = 0;
2085    nested = 0;
2086    while (*s) {
2087       char *last_nonwhite;
2088       // state: just found delimiter
2089       // skip further delimiters
2090       if (!allow_empty) {
2091          stb_tokentable[0] = 0;
2092          if (stripwhite)
2093             while (stb_tokentable[*s] || isspace(*s))
2094                ++s;
2095          else
2096             while (stb_tokentable[*s])
2097                ++s;
2098       } else if (stripwhite) {
2099          while (isspace(*s)) ++s;
2100       }
2101       if (!*s) break;
2102       // we're past any leading delimiters and whitespace
2103       result[num] = out;
2104       ++num;
2105       // copy non-delimiters
2106       stb_tokentable[0] = 1;
2107       last_nonwhite = out-1;
2108       if (stripwhite == 2) {
2109          while (!stb_tokentable[*s]) {
2110             if (*s != '"') {
2111                if (!isspace(*s)) last_nonwhite = out;
2112                *out++ = *s++;
2113             } else {
2114                ++s;
2115                if (*s == '"') {
2116                   if (!isspace(*s)) last_nonwhite = out;
2117                   *out++ = *s++; // "" -> ", not start string
2118                } else {
2119                   // begin a quoted string
2120                   while (*s) {
2121                      if (s[0] == '"') {
2122                         if (s[1] == '"') { *out++ = *s; s += 2; }
2123                         else { ++s; break; } // terminating "
2124                      } else
2125                         *out++ = *s++;
2126                   }
2127                   last_nonwhite = out-1; // all in quotes counts as non-white
2128                }
2129             }
2130          }
2131       } else {
2132          while (nested || !stb_tokentable[*s]) {
2133             if (!isspace(*s)) last_nonwhite = out;
2134             if (stable[*s]) {
2135                if (!*s) break;
2136                if (end ? etable[*s] : nested)
2137                   --nested;
2138                else
2139                   ++nested;
2140             }
2141             *out++ = *s++;
2142          }
2143       }
2144 
2145       if (stripwhite) // rewind to last non-whitespace char
2146          out = last_nonwhite+1;
2147       *out++ = '\0';
2148 
2149       if (*s) ++s; // skip delimiter
2150    }
2151    s = (unsigned char *) delimit; while (*s) stb_tokentable[*s++] = 0;
2152    if (start) {
2153       s = (unsigned char *) start;         while (*s) stable[*s++] = 1;
2154       s = (unsigned char *) end;   if (s)  while (*s) stable[*s++] = 1;
2155       s = (unsigned char *) end;   if (s)  while (*s) etable[*s++] = 1;
2156    }
2157    if (count != NULL) *count = num;
2158    result[num] = 0;
2159    return result;
2160 }
2161 
stb_tokens(char * src,char * delimit,int * count)2162 char **stb_tokens(char *src, char *delimit, int *count)
2163 {
2164    return stb_tokens_raw(src,delimit,count,0,0,0,0);
2165 }
2166 
stb_tokens_nested(char * src,char * delimit,int * count,char * nest_in,char * nest_out)2167 char **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out)
2168 {
2169    return stb_tokens_raw(src,delimit,count,0,0,nest_in,nest_out);
2170 }
2171 
stb_tokens_nested_empty(char * src,char * delimit,int * count,char * nest_in,char * nest_out)2172 char **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out)
2173 {
2174    return stb_tokens_raw(src,delimit,count,0,1,nest_in,nest_out);
2175 }
2176 
stb_tokens_allowempty(char * src,char * delimit,int * count)2177 char **stb_tokens_allowempty(char *src, char *delimit, int *count)
2178 {
2179    return stb_tokens_raw(src,delimit,count,0,1,0,0);
2180 }
2181 
stb_tokens_stripwhite(char * src,char * delimit,int * count)2182 char **stb_tokens_stripwhite(char *src, char *delimit, int *count)
2183 {
2184    return stb_tokens_raw(src,delimit,count,1,1,0,0);
2185 }
2186 
stb_tokens_quoted(char * src,char * delimit,int * count)2187 char **stb_tokens_quoted(char *src, char *delimit, int *count)
2188 {
2189    return stb_tokens_raw(src,delimit,count,2,1,0,0);
2190 }
2191 
stb_dupreplace(char * src,char * find,char * replace)2192 char *stb_dupreplace(char *src, char *find, char *replace)
2193 {
2194    size_t len_find = strlen(find);
2195    size_t len_replace = strlen(replace);
2196    int count = 0;
2197 
2198    char *s,*p,*q;
2199 
2200    s = strstr(src, find);
2201    if (s == NULL) return strdup(src);
2202    do {
2203       ++count;
2204       s = strstr(s + len_find, find);
2205    } while (s != NULL);
2206 
2207    p = (char *)  malloc(strlen(src) + count * (len_replace - len_find) + 1);
2208    if (p == NULL) return p;
2209    q = p;
2210    s = src;
2211    for (;;) {
2212       char *t = strstr(s, find);
2213       if (t == NULL) {
2214          strcpy(q,s);
2215          assert(strlen(p) == strlen(src) + count*(len_replace-len_find));
2216          return p;
2217       }
2218       memcpy(q, s, t-s);
2219       q += t-s;
2220       memcpy(q, replace, len_replace);
2221       q += len_replace;
2222       s = t + len_find;
2223    }
2224 }
2225 
stb_replaceinplace(char * src,char * find,char * replace)2226 void stb_replaceinplace(char *src, char *find, char *replace)
2227 {
2228    size_t len_find = strlen(find);
2229    size_t len_replace = strlen(replace);
2230    int delta;
2231 
2232    char *s,*p,*q;
2233 
2234    delta = len_replace - len_find;
2235    assert(delta <= 0);
2236    if (delta > 0) return;
2237 
2238    p = strstr(src, find);
2239    if (p == NULL) return;
2240 
2241    s = q = p;
2242    while (*s) {
2243       memcpy(q, replace, len_replace);
2244       p += len_find;
2245       q += len_replace;
2246       s = strstr(p, find);
2247       if (s == NULL) s = p + strlen(p);
2248       memmove(q, p, s-p);
2249       q += s-p;
2250       p = s;
2251    }
2252    *q = 0;
2253 }
2254 
stb_fixpath(char * path)2255 void stb_fixpath(char *path)
2256 {
2257    for(; *path; ++path)
2258       if (*path == '\\')
2259          *path = '/';
2260 }
2261 
stb__add_section(char * buffer,char * data,int curlen,int newlen)2262 void stb__add_section(char *buffer, char *data, int curlen, int newlen)
2263 {
2264    if (newlen < curlen) {
2265       int z1 = newlen >> 1, z2 = newlen-z1;
2266       memcpy(buffer, data, z1-1);
2267       buffer[z1-1] = '.';
2268       buffer[z1-0] = '.';
2269       memcpy(buffer+z1+1, data+curlen-z2+1, z2-1);
2270    } else
2271       memcpy(buffer, data, curlen);
2272 }
2273 
stb_shorten_path_readable(char * path,int len)2274 char * stb_shorten_path_readable(char *path, int len)
2275 {
2276    static char buffer[1024];
2277    int n = strlen(path),n1,n2,r1,r2;
2278    char *s;
2279    if (n <= len) return path;
2280    if (len > 1024) return path;
2281    s = stb_strrchr2(path, '/', '\\');
2282    if (s) {
2283       n1 = s - path + 1;
2284       n2 = n - n1;
2285       ++s;
2286    } else {
2287       n1 = 0;
2288       n2 = n;
2289       s = path;
2290    }
2291    // now we need to reduce r1 and r2 so that they fit in len
2292    if (n1 < len>>1) {
2293       r1 = n1;
2294       r2 = len - r1;
2295    } else if (n2 < len >> 1) {
2296       r2 = n2;
2297       r1 = len - r2;
2298    } else {
2299       r1 = n1 * len / n;
2300       r2 = n2 * len / n;
2301       if (r1 < len>>2) r1 = len>>2, r2 = len-r1;
2302       if (r2 < len>>2) r2 = len>>2, r1 = len-r2;
2303    }
2304    assert(r1 <= n1 && r2 <= n2);
2305    if (n1)
2306       stb__add_section(buffer, path, n1, r1);
2307    stb__add_section(buffer+r1, s, n2, r2);
2308    buffer[len] = 0;
2309    return buffer;
2310 }
2311 
stb__splitpath_raw(char * buffer,char * path,int flag)2312 static char *stb__splitpath_raw(char *buffer, char *path, int flag)
2313 {
2314    int len=0,x,y, n = (int) strlen(path), f1,f2;
2315    char *s = stb_strrchr2(path, '/', '\\');
2316    char *t = strrchr(path, '.');
2317    if (s && t && t < s) t = NULL;
2318    if (s) ++s;
2319 
2320    if (flag == STB_EXT_NO_PERIOD)
2321       flag |= STB_EXT;
2322 
2323    if (!(flag & (STB_PATH | STB_FILE | STB_EXT))) return NULL;
2324 
2325    f1 = s == NULL ? 0 : s-path; // start of filename
2326    f2 = t == NULL ? n : t-path; // just past end of filename
2327 
2328    if (flag & STB_PATH) {
2329       x = 0; if (f1 == 0 && flag == STB_PATH) len=2;
2330    } else if (flag & STB_FILE) {
2331       x = f1;
2332    } else {
2333       x = f2;
2334       if (flag & STB_EXT_NO_PERIOD)
2335          if (buffer[x] == '.')
2336             ++x;
2337    }
2338 
2339    if (flag & STB_EXT)
2340       y = n;
2341    else if (flag & STB_FILE)
2342       y = f2;
2343    else
2344       y = f1;
2345 
2346    if (buffer == NULL) {
2347       buffer = (char *) malloc(y-x + len + 1);
2348       if (!buffer) return NULL;
2349    }
2350 
2351    if (len) { strcpy(buffer, "./"); return buffer; }
2352    strncpy(buffer, path+x, y-x);
2353    buffer[y-x] = 0;
2354    return buffer;
2355 }
2356 
stb_splitpath(char * output,char * src,int flag)2357 char *stb_splitpath(char *output, char *src, int flag)
2358 {
2359    return stb__splitpath_raw(output, src, flag);
2360 }
2361 
stb_splitpathdup(char * src,int flag)2362 char *stb_splitpathdup(char *src, int flag)
2363 {
2364    return stb__splitpath_raw(NULL, src, flag);
2365 }
2366 
stb_replacedir(char * output,char * src,char * dir)2367 char *stb_replacedir(char *output, char *src, char *dir)
2368 {
2369    char buffer[4096];
2370    stb_splitpath(buffer, src, STB_FILE | STB_EXT);
2371    if (dir)
2372       sprintf(output, "%s/%s", dir, buffer);
2373    else
2374       strcpy(output, buffer);
2375    return output;
2376 }
2377 
stb_replaceext(char * output,char * src,char * ext)2378 char *stb_replaceext(char *output, char *src, char *ext)
2379 {
2380    char buffer[4096];
2381    stb_splitpath(buffer, src, STB_PATH | STB_FILE);
2382    if (ext)
2383       sprintf(output, "%s.%s", buffer, ext[0] == '.' ? ext+1 : ext);
2384    else
2385       strcpy(output, buffer);
2386    return output;
2387 }
2388 #endif
2389 
2390 //////////////////////////////////////////////////////////////////////////////
2391 //
2392 //                   stb_alloc - hierarchical allocator
2393 //
2394 //                                     inspired by http://swapped.cc/halloc
2395 //
2396 //
2397 // When you alloc a given block through stb_alloc, you have these choices:
2398 //
2399 //       1. does it have a parent?
2400 //       2. can it have children?
2401 //       3. can it be freed directly?
2402 //       4. is it transferrable?
2403 //       5. what is its alignment?
2404 //
2405 // Here are interesting combinations of those:
2406 //
2407 //                              children   free    transfer     alignment
2408 //  arena                          Y         Y         N           n/a
2409 //  no-overhead, chunked           N         N         N         normal
2410 //  string pool alloc              N         N         N            1
2411 //  parent-ptr, chunked            Y         N         N         normal
2412 //  low-overhead, unchunked        N         Y         Y         normal
2413 //  general purpose alloc          Y         Y         Y         normal
2414 //
2415 // Unchunked allocations will probably return 16-aligned pointers. If
2416 // we 16-align the results, we have room for 4 pointers. For smaller
2417 // allocations that allow finer alignment, we can reduce the pointers.
2418 //
2419 // The strategy is that given a pointer, assuming it has a header (only
2420 // the no-overhead allocations have no header), we can determine the
2421 // type of the header fields, and the number of them, by stepping backwards
2422 // through memory and looking at the tags in the bottom bits.
2423 //
2424 // Implementation strategy:
2425 //     chunked allocations come from the middle of chunks, and can't
2426 //     be freed. thefore they do not need to be on a sibling chain.
2427 //     they may need child pointers if they have children.
2428 //
2429 // chunked, with-children
2430 //     void *parent;
2431 //
2432 // unchunked, no-children -- reduced storage
2433 //     void *next_sibling;
2434 //     void *prev_sibling_nextp;
2435 //
2436 // unchunked, general
2437 //     void *first_child;
2438 //     void *next_sibling;
2439 //     void *prev_sibling_nextp;
2440 //     void *chunks;
2441 //
2442 // so, if we code each of these fields with different bit patterns
2443 // (actually same one for next/prev/child), then we can identify which
2444 // each one is from the last field.
2445 
2446 STB_EXTERN void  stb_free(void *p);
2447 STB_EXTERN void *stb_malloc_global(size_t size);
2448 STB_EXTERN void *stb_malloc(void *context, size_t size);
2449 STB_EXTERN void *stb_malloc_nofree(void *context, size_t size);
2450 STB_EXTERN void *stb_malloc_leaf(void *context, size_t size);
2451 STB_EXTERN void *stb_malloc_raw(void *context, size_t size);
2452 STB_EXTERN void *stb_realloc(void *ptr, size_t newsize);
2453 
2454 STB_EXTERN void stb_reassign(void *new_context, void *ptr);
2455 STB_EXTERN void stb_malloc_validate(void *p, void *parent);
2456 
2457 extern int stb_alloc_chunk_size ;
2458 extern int stb_alloc_count_free ;
2459 extern int stb_alloc_count_alloc;
2460 extern int stb_alloc_alignment  ;
2461 
2462 #ifdef STB_DEFINE
2463 
2464 int stb_alloc_chunk_size  = 65536;
2465 int stb_alloc_count_free  = 0;
2466 int stb_alloc_count_alloc = 0;
2467 int stb_alloc_alignment   = -16;
2468 
2469 typedef struct stb__chunk
2470 {
2471    struct stb__chunk *next;
2472    int                data_left;
2473    int                alloc;
2474 } stb__chunk;
2475 
2476 typedef struct
2477 {
2478    void *  next;
2479    void ** prevn;
2480 } stb__nochildren;
2481 
2482 typedef struct
2483 {
2484    void ** prevn;
2485    void *  child;
2486    void *  next;
2487    stb__chunk *chunks;
2488 } stb__alloc;
2489 
2490 typedef struct
2491 {
2492    stb__alloc *parent;
2493 } stb__chunked;
2494 
2495 #define STB__PARENT          1
2496 #define STB__CHUNKS          2
2497 
2498 typedef enum
2499 {
2500    STB__nochildren = 0,
2501    STB__chunked    = STB__PARENT,
2502    STB__alloc      = STB__CHUNKS,
2503 
2504    STB__chunk_raw  = 4,
2505 } stb__alloc_type;
2506 
2507 // these functions set the bottom bits of a pointer efficiently
2508 #define STB__DECODE(x,v)  ((void *) ((char *) (x) - (v)))
2509 #define STB__ENCODE(x,v)  ((void *) ((char *) (x) + (v)))
2510 
2511 #define stb__parent(z)       (stb__alloc *) STB__DECODE((z)->parent, STB__PARENT)
2512 #define stb__chunks(z)       (stb__chunk *) STB__DECODE((z)->chunks, STB__CHUNKS)
2513 
2514 #define stb__setparent(z,p)  (z)->parent = (stb__alloc *) STB__ENCODE((p), STB__PARENT)
2515 #define stb__setchunks(z,c)  (z)->chunks = (stb__chunk *) STB__ENCODE((c), STB__CHUNKS)
2516 
2517 static stb__alloc stb__alloc_global =
2518 {
2519    NULL,
2520    NULL,
2521    NULL,
2522    (stb__chunk *) STB__ENCODE(NULL, STB__CHUNKS)
2523 };
2524 
stb__identify(void * p)2525 static stb__alloc_type stb__identify(void *p)
2526 {
2527    void **q = (void **) p;
2528    return (stb__alloc_type) ((stb_uinta) q[-1] & 3);
2529 }
2530 
stb__prevn(void * p)2531 static void *** stb__prevn(void *p)
2532 {
2533    if (stb__identify(p) == STB__alloc) {
2534       stb__alloc      *s = (stb__alloc *) p - 1;
2535       return &s->prevn;
2536    } else {
2537       stb__nochildren *s = (stb__nochildren *) p - 1;
2538       return &s->prevn;
2539    }
2540 }
2541 
stb_free(void * p)2542 void stb_free(void *p)
2543 {
2544    if (p == NULL) return;
2545 
2546    // count frees so that unit tests can see what's happening
2547    ++stb_alloc_count_free;
2548 
2549    switch(stb__identify(p)) {
2550       case STB__chunked:
2551          // freeing a chunked-block with children does nothing;
2552          // they only get freed when the parent does
2553          // surely this is wrong, and it should free them immediately?
2554          // otherwise how are they getting put on the right chain?
2555          return;
2556       case STB__nochildren: {
2557          stb__nochildren *s = (stb__nochildren *) p - 1;
2558          // unlink from sibling chain
2559          *(s->prevn) = s->next;
2560          if (s->next)
2561             *stb__prevn(s->next) = s->prevn;
2562          free(s);
2563          return;
2564       }
2565       case STB__alloc: {
2566          stb__alloc *s = (stb__alloc *) p - 1;
2567          stb__chunk *c, *n;
2568          void *q;
2569 
2570          // unlink from sibling chain, if any
2571          *(s->prevn) = s->next;
2572          if (s->next)
2573             *stb__prevn(s->next) = s->prevn;
2574 
2575          // first free chunks
2576          c = (stb__chunk *) stb__chunks(s);
2577          while (c != NULL) {
2578             n = c->next;
2579             stb_alloc_count_free += c->alloc;
2580             free(c);
2581             c = n;
2582          }
2583 
2584          // validating
2585          stb__setchunks(s,NULL);
2586          s->prevn = NULL;
2587          s->next = NULL;
2588 
2589          // now free children
2590          while ((q = s->child) != NULL) {
2591             stb_free(q);
2592          }
2593 
2594          // now free self
2595          free(s);
2596          return;
2597       }
2598       default:
2599          assert(0); /* NOTREACHED */
2600    }
2601 }
2602 
stb_malloc_validate(void * p,void * parent)2603 void stb_malloc_validate(void *p, void *parent)
2604 {
2605    if (p == NULL) return;
2606 
2607    switch(stb__identify(p)) {
2608       case STB__chunked:
2609          return;
2610       case STB__nochildren: {
2611          stb__nochildren *n = (stb__nochildren *) p - 1;
2612          if (n->prevn)
2613             assert(*n->prevn == p);
2614          if (n->next) {
2615             assert(*stb__prevn(n->next) == &n->next);
2616             stb_malloc_validate(n, parent);
2617          }
2618          return;
2619       }
2620       case STB__alloc: {
2621          stb__alloc *s = (stb__alloc *) p - 1;
2622 
2623          if (s->prevn)
2624             assert(*s->prevn == p);
2625 
2626          if (s->child) {
2627             assert(*stb__prevn(s->child) == &s->child);
2628             stb_malloc_validate(s->child, p);
2629          }
2630 
2631          if (s->next) {
2632             assert(*stb__prevn(s->next) == &s->next);
2633             stb_malloc_validate(s->next, parent);
2634          }
2635          return;
2636       }
2637       default:
2638          assert(0); /* NOTREACHED */
2639    }
2640 }
2641 
stb__try_chunk(stb__chunk * c,int size,int align,int pre_align)2642 static void * stb__try_chunk(stb__chunk *c, int size, int align, int pre_align)
2643 {
2644    char *memblock = (char *) (c+1), *q;
2645    stb_inta iq;
2646    int start_offset;
2647 
2648    // we going to allocate at the end of the chunk, not the start. confusing,
2649    // but it means we don't need both a 'limit' and a 'cur', just a 'cur'.
2650    // the block ends at: p + c->data_left
2651    //   then we move back by size
2652    start_offset = c->data_left - size;
2653 
2654    // now we need to check the alignment of that
2655    q = memblock + start_offset;
2656    iq = (stb_inta) q;
2657    assert(sizeof(q) == sizeof(iq));
2658 
2659    // suppose align = 2
2660    // then we need to retreat iq far enough that (iq & (2-1)) == 0
2661    // to get (iq & (align-1)) = 0 requires subtracting (iq & (align-1))
2662 
2663    start_offset -= iq & (align-1);
2664    assert(((stb_uinta) (memblock+start_offset) & (align-1)) == 0);
2665 
2666    // now, if that + pre_align works, go for it!
2667    start_offset -= pre_align;
2668 
2669    if (start_offset >= 0) {
2670       c->data_left = start_offset;
2671       return memblock + start_offset;
2672    }
2673 
2674    return NULL;
2675 }
2676 
stb__sort_chunks(stb__alloc * src)2677 static void stb__sort_chunks(stb__alloc *src)
2678 {
2679    // of the first two chunks, put the chunk with more data left in it first
2680    stb__chunk *c = stb__chunks(src), *d;
2681    if (c == NULL) return;
2682    d = c->next;
2683    if (d == NULL) return;
2684    if (c->data_left > d->data_left) return;
2685 
2686    c->next = d->next;
2687    d->next = c;
2688    stb__setchunks(src, d);
2689 }
2690 
stb__alloc_chunk(stb__alloc * src,int size,int align,int pre_align)2691 static void * stb__alloc_chunk(stb__alloc *src, int size, int align, int pre_align)
2692 {
2693    void *p;
2694    stb__chunk *c = stb__chunks(src);
2695 
2696    if (c && size <= stb_alloc_chunk_size) {
2697 
2698       p = stb__try_chunk(c, size, align, pre_align);
2699       if (p) { ++c->alloc; return p; }
2700 
2701       // try a second chunk to reduce wastage
2702       if (c->next) {
2703          p = stb__try_chunk(c->next, size, align, pre_align);
2704          if (p) { ++c->alloc; return p; }
2705 
2706          // put the bigger chunk first, since the second will get buried
2707          // the upshot of this is that, until it gets allocated from, chunk #2
2708          // is always the largest remaining chunk. (could formalize
2709          // this with a heap!)
2710          stb__sort_chunks(src);
2711          c = stb__chunks(src);
2712       }
2713    }
2714 
2715    // allocate a new chunk
2716    {
2717       stb__chunk *n;
2718 
2719       int chunk_size = stb_alloc_chunk_size;
2720       // we're going to allocate a new chunk to put this in
2721       if (size > chunk_size)
2722          chunk_size = size;
2723 
2724       assert(sizeof(*n) + pre_align <= 16);
2725 
2726       // loop trying to allocate a large enough chunk
2727       // the loop is because the alignment may cause problems if it's big...
2728       // and we don't know what our chunk alignment is going to be
2729       while (1) {
2730          n = (stb__chunk *) malloc(16 + chunk_size);
2731          if (n == NULL) return NULL;
2732 
2733          n->data_left = chunk_size - sizeof(*n);
2734 
2735          p = stb__try_chunk(n, size, align, pre_align);
2736          if (p != NULL) {
2737             n->next = c;
2738             stb__setchunks(src, n);
2739 
2740             // if we just used up the whole block immediately,
2741             // move the following chunk up
2742             n->alloc = 1;
2743             if (size == chunk_size)
2744                stb__sort_chunks(src);
2745 
2746             return p;
2747          }
2748 
2749          free(n);
2750          chunk_size += 16+align;
2751       }
2752    }
2753 }
2754 
stb__get_context(void * context)2755 static stb__alloc * stb__get_context(void *context)
2756 {
2757    if (context == NULL) {
2758       return &stb__alloc_global;
2759    } else {
2760       int u = stb__identify(context);
2761       // if context is chunked, grab parent
2762       if (u == STB__chunked) {
2763          stb__chunked *s = (stb__chunked *) context - 1;
2764          return stb__parent(s);
2765       } else {
2766          return (stb__alloc *) context - 1;
2767       }
2768    }
2769 }
2770 
stb__insert_alloc(stb__alloc * src,stb__alloc * s)2771 static void stb__insert_alloc(stb__alloc *src, stb__alloc *s)
2772 {
2773    s->prevn = &src->child;
2774    s->next  = src->child;
2775    src->child = s+1;
2776    if (s->next)
2777       *stb__prevn(s->next) = &s->next;
2778 }
2779 
stb__insert_nochild(stb__alloc * src,stb__nochildren * s)2780 static void stb__insert_nochild(stb__alloc *src, stb__nochildren *s)
2781 {
2782    s->prevn = &src->child;
2783    s->next  = src->child;
2784    src->child = s+1;
2785    if (s->next)
2786       *stb__prevn(s->next) = &s->next;
2787 }
2788 
malloc_base(void * context,size_t size,stb__alloc_type t,int align)2789 static void * malloc_base(void *context, size_t size, stb__alloc_type t, int align)
2790 {
2791    void *p;
2792 
2793    stb__alloc *src = stb__get_context(context);
2794 
2795    if (align <= 0) {
2796       // compute worst-case C packed alignment
2797       // e.g. a 24-byte struct is 8-aligned
2798       int align_proposed = 1 << stb_lowbit8(size);
2799 
2800       if (align_proposed < 0)
2801          align_proposed = 4;
2802 
2803       if (align_proposed == 0) {
2804          if (size == 0)
2805             align_proposed = 1;
2806          else
2807             align_proposed = 256;
2808       }
2809 
2810       // a negative alignment means 'don't align any larger
2811       // than this'; so -16 means we align 1,2,4,8, or 16
2812 
2813       if (align < 0) {
2814          if (align_proposed > -align)
2815             align_proposed = -align;
2816       }
2817 
2818       align = align_proposed;
2819    }
2820 
2821    assert(stb_is_pow2(align));
2822 
2823    // don't cause misalignment when allocating nochildren
2824    if (t == STB__nochildren && align > 8)
2825       t = STB__alloc;
2826 
2827    switch (t) {
2828       case STB__alloc: {
2829          stb__alloc *s = (stb__alloc *) malloc(size + sizeof(*s));
2830          if (s == NULL) return NULL;
2831          p = s+1;
2832          s->child = NULL;
2833          stb__insert_alloc(src, s);
2834 
2835          stb__setchunks(s,NULL);
2836          break;
2837       }
2838 
2839       case STB__nochildren: {
2840          stb__nochildren *s = (stb__nochildren *) malloc(size + sizeof(*s));
2841          if (s == NULL) return NULL;
2842          p = s+1;
2843          stb__insert_nochild(src, s);
2844          break;
2845       }
2846 
2847       case STB__chunk_raw: {
2848          p = stb__alloc_chunk(src, size, align, 0);
2849          if (p == NULL) return NULL;
2850          break;
2851       }
2852 
2853       case STB__chunked: {
2854          stb__chunked *s;
2855          if (align < sizeof(stb_uintptr)) align = sizeof(stb_uintptr);
2856          s = (stb__chunked *) stb__alloc_chunk(src, size, align, sizeof(*s));
2857          if (s == NULL) return NULL;
2858          stb__setparent(s, src);
2859          p = s+1;
2860          break;
2861       }
2862 
2863       default: p = NULL; assert(0); /* NOTREACHED */
2864    }
2865 
2866    ++stb_alloc_count_alloc;
2867    return p;
2868 }
2869 
stb_malloc_global(size_t size)2870 void *stb_malloc_global(size_t size)
2871 {
2872    return malloc_base(NULL, size, STB__alloc, stb_alloc_alignment);
2873 }
2874 
stb_malloc(void * context,size_t size)2875 void *stb_malloc(void *context, size_t size)
2876 {
2877    return malloc_base(context, size, STB__alloc, stb_alloc_alignment);
2878 }
2879 
stb_malloc_nofree(void * context,size_t size)2880 void *stb_malloc_nofree(void *context, size_t size)
2881 {
2882    return malloc_base(context, size, STB__chunked, stb_alloc_alignment);
2883 }
2884 
stb_malloc_leaf(void * context,size_t size)2885 void *stb_malloc_leaf(void *context, size_t size)
2886 {
2887    return malloc_base(context, size, STB__nochildren, stb_alloc_alignment);
2888 }
2889 
stb_malloc_raw(void * context,size_t size)2890 void *stb_malloc_raw(void *context, size_t size)
2891 {
2892    return malloc_base(context, size, STB__chunk_raw, stb_alloc_alignment);
2893 }
2894 
stb_malloc_string(void * context,size_t size)2895 char *stb_malloc_string(void *context, size_t size)
2896 {
2897    return (char *) malloc_base(context, size, STB__chunk_raw, 1);
2898 }
2899 
stb_realloc(void * ptr,size_t newsize)2900 void *stb_realloc(void *ptr, size_t newsize)
2901 {
2902    stb__alloc_type t;
2903 
2904    if (ptr == NULL) return stb_malloc(NULL, newsize);
2905    if (newsize == 0) { stb_free(ptr); return NULL; }
2906 
2907    t = stb__identify(ptr);
2908    assert(t == STB__alloc || t == STB__nochildren);
2909 
2910    if (t == STB__alloc) {
2911       stb__alloc *s = (stb__alloc *) ptr - 1;
2912 
2913       s = (stb__alloc *) realloc(s, newsize + sizeof(*s));
2914       if (s == NULL) return NULL;
2915 
2916       ptr = s+1;
2917 
2918       // update pointers
2919       (*s->prevn) = ptr;
2920       if (s->next)
2921          *stb__prevn(s->next) = &s->next;
2922 
2923       if (s->child)
2924          *stb__prevn(s->child) = &s->child;
2925 
2926       return ptr;
2927    } else {
2928       stb__nochildren *s = (stb__nochildren *) ptr - 1;
2929 
2930       s = (stb__nochildren *) realloc(ptr, newsize + sizeof(s));
2931       if (s == NULL) return NULL;
2932 
2933       // update pointers
2934       (*s->prevn) = s+1;
2935       if (s->next)
2936          *stb__prevn(s->next) = &s->next;
2937 
2938       return s+1;
2939    }
2940 }
2941 
stb_realloc_c(void * context,void * ptr,size_t newsize)2942 void *stb_realloc_c(void *context, void *ptr, size_t newsize)
2943 {
2944    if (ptr == NULL) return stb_malloc(context, newsize);
2945    if (newsize == 0) { stb_free(ptr); return NULL; }
2946    // @TODO: verify you haven't changed contexts
2947    return stb_realloc(ptr, newsize);
2948 }
2949 
stb_reassign(void * new_context,void * ptr)2950 void stb_reassign(void *new_context, void *ptr)
2951 {
2952    stb__alloc *src = stb__get_context(new_context);
2953 
2954    stb__alloc_type t = stb__identify(ptr);
2955    assert(t == STB__alloc || t == STB__nochildren);
2956 
2957    if (t == STB__alloc) {
2958       stb__alloc *s = (stb__alloc *) ptr - 1;
2959 
2960       // unlink from old
2961       *(s->prevn) = s->next;
2962       if (s->next)
2963          *stb__prevn(s->next) = s->prevn;
2964 
2965       stb__insert_alloc(src, s);
2966    } else {
2967       stb__nochildren *s = (stb__nochildren *) ptr - 1;
2968 
2969       // unlink from old
2970       *(s->prevn) = s->next;
2971       if (s->next)
2972          *stb__prevn(s->next) = s->prevn;
2973 
2974       stb__insert_nochild(src, s);
2975    }
2976 }
2977 
2978 #endif
2979 
2980 
2981 //////////////////////////////////////////////////////////////////////////////
2982 //
2983 //                                stb_arr
2984 //
2985 //  An stb_arr is directly useable as a pointer (use the actual type in your
2986 //  definition), but when it resizes, it returns a new pointer and you can't
2987 //  use the old one, so you have to be careful to copy-in-out as necessary.
2988 //
2989 //  Use a NULL pointer as a 0-length array.
2990 //
2991 //     float *my_array = NULL, *temp;
2992 //
2993 //     // add elements on the end one at a time
2994 //     stb_arr_push(my_array, 0.0f);
2995 //     stb_arr_push(my_array, 1.0f);
2996 //     stb_arr_push(my_array, 2.0f);
2997 //
2998 //     assert(my_array[1] == 2.0f);
2999 //
3000 //     // add an uninitialized element at the end, then assign it
3001 //     *stb_arr_add(my_array) = 3.0f;
3002 //
3003 //     // add three uninitialized elements at the end
3004 //     temp = stb_arr_addn(my_array,3);
3005 //     temp[0] = 4.0f;
3006 //     temp[1] = 5.0f;
3007 //     temp[2] = 6.0f;
3008 //
3009 //     assert(my_array[5] == 5.0f);
3010 //
3011 //     // remove the last one
3012 //     stb_arr_pop(my_array);
3013 //
3014 //     assert(stb_arr_len(my_array) == 6);
3015 
3016 
3017 #ifdef STB_MALLOC_WRAPPER
3018   #define STB__PARAMS    , char *file, int line
3019   #define STB__ARGS      ,       file,     line
3020 #else
3021   #define STB__PARAMS
3022   #define STB__ARGS
3023 #endif
3024 
3025 // calling this function allocates an empty stb_arr attached to p
3026 // (whereas NULL isn't attached to anything)
3027 STB_EXTERN void stb_arr_malloc(void **target, void *context);
3028 
3029 // call this function with a non-NULL value to have all successive
3030 // stbs that are created be attached to the associated parent. Note
3031 // that once a given stb_arr is non-empty, it stays attached to its
3032 // current parent, even if you call this function again.
3033 // it turns the previous value, so you can restore it
3034 STB_EXTERN void* stb_arr_malloc_parent(void *p);
3035 
3036 // simple functions written on top of other functions
3037 #define stb_arr_empty(a)       (  stb_arr_len(a) == 0 )
3038 #define stb_arr_add(a)         (  stb_arr_addn((a),1) )
3039 #define stb_arr_push(a,v)      ( *stb_arr_add(a)=(v)  )
3040 
3041 typedef struct
3042 {
3043    int len, limit;
3044    int stb_malloc;
3045    unsigned int signature;
3046 } stb__arr;
3047 
3048 #define stb_arr_signature      0x51bada7b  // ends with 0123 in decimal
3049 
3050 // access the header block stored before the data
3051 #define stb_arrhead(a)         /*lint --e(826)*/ (((stb__arr *) (a)) - 1)
3052 #define stb_arrhead2(a)        /*lint --e(826)*/ (((stb__arr *) (a)) - 1)
3053 
3054 #ifdef STB_DEBUG
3055 #define stb_arr_check(a)       assert(!a || stb_arrhead(a)->signature == stb_arr_signature)
3056 #define stb_arr_check2(a)      assert(!a || stb_arrhead2(a)->signature == stb_arr_signature)
3057 #else
3058 #define stb_arr_check(a)       ((void) 0)
3059 #define stb_arr_check2(a)      ((void) 0)
3060 #endif
3061 
3062 // ARRAY LENGTH
3063 
3064 // get the array length; special case if pointer is NULL
3065 #define stb_arr_len(a)         (a ? stb_arrhead(a)->len : 0)
3066 #define stb_arr_len2(a)        ((stb__arr *) (a) ? stb_arrhead2(a)->len : 0)
3067 #define stb_arr_lastn(a)       (stb_arr_len(a)-1)
3068 
3069 // check whether a given index is valid -- tests 0 <= i < stb_arr_len(a)
3070 #define stb_arr_valid(a,i)     (a ? (int) (i) < stb_arrhead(a)->len : 0)
3071 
3072 // change the array length so is is exactly N entries long, creating
3073 // uninitialized entries as needed
3074 #define stb_arr_setlen(a,n)  \
3075             (stb__arr_setlen((void **) &(a), sizeof(a[0]), (n)))
3076 
3077 // change the array length so that N is a valid index (that is, so
3078 // it is at least N entries long), creating uninitialized entries as needed
3079 #define stb_arr_makevalid(a,n)  \
3080             (stb_arr_len(a) < (n)+1 ? stb_arr_setlen(a,(n)+1),(a) : (a))
3081 
3082 // remove the last element of the array, returning it
3083 #define stb_arr_pop(a)         ((stb_arr_check(a), (a))[--stb_arrhead(a)->len])
3084 
3085 // access the last element in the array
3086 #define stb_arr_last(a)        ((stb_arr_check(a), (a))[stb_arr_len(a)-1])
3087 
3088 // is iterator at end of list?
3089 #define stb_arr_end(a,i)       ((i) >= &(a)[stb_arr_len(a)])
3090 
3091 // (internal) change the allocated length of the array
3092 #define stb_arr__grow(a,n)     (stb_arr_check(a), stb_arrhead(a)->len += (n))
3093 
3094 // add N new unitialized elements to the end of the array
3095 #define stb_arr__addn(a,n)     /*lint --e(826)*/ \
3096                                ((stb_arr_len(a)+(n) > stb_arrcurmax(a))      \
3097                                  ? (stb__arr_addlen((void **) &(a),sizeof(*a),(n)),0) \
3098                                  : ((stb_arr__grow(a,n), 0)))
3099 
3100 // add N new unitialized elements to the end of the array, and return
3101 // a pointer to the first new one
3102 #define stb_arr_addn(a,n)      (stb_arr__addn((a),n),(a)+stb_arr_len(a)-(n))
3103 
3104 // add N new uninitialized elements starting at index 'i'
3105 #define stb_arr_insertn(a,i,n) (stb__arr_insertn((void **) &(a), sizeof(*a), i, n))
3106 
3107 // insert an element at i
3108 #define stb_arr_insert(a,i,v)  (stb__arr_insertn((void **) &(a), sizeof(*a), i, 1), ((a)[i] = v))
3109 
3110 // delete N elements from the middle starting at index 'i'
3111 #define stb_arr_deleten(a,i,n) (stb__arr_deleten((void **) &(a), sizeof(*a), i, n))
3112 
3113 // delete the i'th element
3114 #define stb_arr_delete(a,i)   stb_arr_deleten(a,i,1)
3115 
3116 // delete the i'th element, swapping down from the end
3117 #define stb_arr_fastdelete(a,i)  \
3118    (stb_swap(&a[i], &a[stb_arrhead(a)->len-1], sizeof(*a)), stb_arr_pop(a))
3119 
3120 
3121 // ARRAY STORAGE
3122 
3123 // get the array maximum storage; special case if NULL
3124 #define stb_arrcurmax(a)       (a ? stb_arrhead(a)->limit : 0)
3125 #define stb_arrcurmax2(a)      (a ? stb_arrhead2(a)->limit : 0)
3126 
3127 // set the maxlength of the array to n in anticipation of further growth
3128 #define stb_arr_setsize(a,n)   (stb_arr_check(a), stb__arr_setsize((void **) &(a),sizeof((a)[0]),n))
3129 
3130 // make sure maxlength is large enough for at least N new allocations
3131 #define stb_arr_atleast(a,n)   (stb_arr_len(a)+(n) > stb_arrcurmax(a)      \
3132                                  ? stb_arr_setsize((a), (n)) : 0)
3133 
3134 // make a copy of a given array (copies contents via 'memcpy'!)
3135 #define stb_arr_copy(a)        stb__arr_copy(a, sizeof((a)[0]))
3136 
3137 // compute the storage needed to store all the elements of the array
3138 #define stb_arr_storage(a)     (stb_arr_len(a) * sizeof((a)[0]))
3139 
3140 #define stb_arr_for(v,arr)     for((v)=(arr); (v) < (arr)+stb_arr_len(arr); ++(v))
3141 
3142 // IMPLEMENTATION
3143 
3144 STB_EXTERN void stb_arr_free_(void **p);
3145 STB_EXTERN void *stb__arr_copy_(void *p, int elem_size);
3146 STB_EXTERN void stb__arr_setsize_(void **p, int size, int limit  STB__PARAMS);
3147 STB_EXTERN void stb__arr_setlen_(void **p, int size, int newlen  STB__PARAMS);
3148 STB_EXTERN void stb__arr_addlen_(void **p, int size, int addlen  STB__PARAMS);
3149 STB_EXTERN void stb__arr_deleten_(void **p, int size, int loc, int n  STB__PARAMS);
3150 STB_EXTERN void stb__arr_insertn_(void **p, int size, int loc, int n  STB__PARAMS);
3151 
3152 #define stb_arr_free(p)            stb_arr_free_((void **) &(p))
3153 #define stb__arr_copy              stb__arr_copy_
3154 
3155 #ifndef STB_MALLOC_WRAPPER
3156   #define stb__arr_setsize         stb__arr_setsize_
3157   #define stb__arr_setlen          stb__arr_setlen_
3158   #define stb__arr_addlen          stb__arr_addlen_
3159   #define stb__arr_deleten         stb__arr_deleten_
3160   #define stb__arr_insertn         stb__arr_insertn_
3161 #else
3162   #define stb__arr_addlen(p,s,n)    stb__arr_addlen_(p,s,n,__FILE__,__LINE__)
3163   #define stb__arr_setlen(p,s,n)    stb__arr_setlen_(p,s,n,__FILE__,__LINE__)
3164   #define stb__arr_setsize(p,s,n)   stb__arr_setsize_(p,s,n,__FILE__,__LINE__)
3165   #define stb__arr_deleten(p,s,i,n) stb__arr_deleten_(p,s,i,n,__FILE__,__LINE__)
3166   #define stb__arr_insertn(p,s,i,n) stb__arr_insertn_(p,s,i,n,__FILE__,__LINE__)
3167 #endif
3168 
3169 #ifdef STB_DEFINE
3170 static void *stb__arr_context;
3171 
stb_arr_malloc_parent(void * p)3172 void *stb_arr_malloc_parent(void *p)
3173 {
3174    void *q = stb__arr_context;
3175    stb__arr_context = p;
3176    return q;
3177 }
3178 
stb_arr_malloc(void ** target,void * context)3179 void stb_arr_malloc(void **target, void *context)
3180 {
3181    stb__arr *q = (stb__arr *) stb_malloc(context, sizeof(*q));
3182    q->len = q->limit = 0;
3183    q->stb_malloc = 1;
3184    q->signature = stb_arr_signature;
3185    *target = (void *) (q+1);
3186 }
3187 
stb__arr_malloc(int size)3188 static void * stb__arr_malloc(int size)
3189 {
3190    if (stb__arr_context)
3191       return stb_malloc(stb__arr_context, size);
3192    return malloc(size);
3193 }
3194 
stb__arr_copy_(void * p,int elem_size)3195 void * stb__arr_copy_(void *p, int elem_size)
3196 {
3197    stb__arr *q;
3198    if (p == NULL) return p;
3199    q = (stb__arr *) stb__arr_malloc(sizeof(*q) + elem_size * stb_arrhead2(p)->limit);
3200    stb_arr_check2(p);
3201    memcpy(q, stb_arrhead2(p), sizeof(*q) + elem_size * stb_arrhead2(p)->len);
3202    q->stb_malloc = !!stb__arr_context;
3203    return q+1;
3204 }
3205 
stb_arr_free_(void ** pp)3206 void stb_arr_free_(void **pp)
3207 {
3208    void *p = *pp;
3209    stb_arr_check2(p);
3210    if (p) {
3211       stb__arr *q = stb_arrhead2(p);
3212       if (q->stb_malloc)
3213          stb_free(q);
3214       else
3215          free(q);
3216    }
3217    *pp = NULL;
3218 }
3219 
stb__arrsize_(void ** pp,int size,int limit,int len STB__PARAMS)3220 static void stb__arrsize_(void **pp, int size, int limit, int len  STB__PARAMS)
3221 {
3222    void *p = *pp;
3223    stb__arr *a;
3224    stb_arr_check2(p);
3225    if (p == NULL) {
3226       if (len == 0 && size == 0) return;
3227       a = (stb__arr *) stb__arr_malloc(sizeof(*a) + size*limit);
3228       a->limit = limit;
3229       a->len   = len;
3230       a->stb_malloc = !!stb__arr_context;
3231       a->signature = stb_arr_signature;
3232    } else {
3233       a = stb_arrhead2(p);
3234       a->len = len;
3235       if (a->limit < limit) {
3236          void *p;
3237          if (a->limit >= 4 && limit < a->limit * 2)
3238             limit = a->limit * 2;
3239          if (a->stb_malloc)
3240             p = stb_realloc(a, sizeof(*a) + limit*size);
3241          else
3242             #ifdef STB_MALLOC_WRAPPER
3243             p = stb__realloc(a, sizeof(*a) + limit*size, file, line);
3244             #else
3245             p = realloc(a, sizeof(*a) + limit*size);
3246             #endif
3247          if (p) {
3248             a = (stb__arr *) p;
3249             a->limit = limit;
3250          } else {
3251             // throw an error!
3252          }
3253       }
3254    }
3255    a->len   = stb_min(a->len, a->limit);
3256    *pp = a+1;
3257 }
3258 
stb__arr_setsize_(void ** pp,int size,int limit STB__PARAMS)3259 void stb__arr_setsize_(void **pp, int size, int limit  STB__PARAMS)
3260 {
3261    void *p = *pp;
3262    stb_arr_check2(p);
3263    stb__arrsize_(pp, size, limit, stb_arr_len2(p)  STB__ARGS);
3264 }
3265 
stb__arr_setlen_(void ** pp,int size,int newlen STB__PARAMS)3266 void stb__arr_setlen_(void **pp, int size, int newlen  STB__PARAMS)
3267 {
3268    void *p = *pp;
3269    stb_arr_check2(p);
3270    if (stb_arrcurmax2(p) < newlen || p == NULL) {
3271       stb__arrsize_(pp, size, newlen, newlen  STB__ARGS);
3272    } else {
3273       stb_arrhead2(p)->len = newlen;
3274    }
3275 }
3276 
stb__arr_addlen_(void ** p,int size,int addlen STB__PARAMS)3277 void stb__arr_addlen_(void **p, int size, int addlen  STB__PARAMS)
3278 {
3279    stb__arr_setlen_(p, size, stb_arr_len2(*p) + addlen  STB__ARGS);
3280 }
3281 
stb__arr_insertn_(void ** pp,int size,int i,int n STB__PARAMS)3282 void stb__arr_insertn_(void **pp, int size, int i, int n  STB__PARAMS)
3283 {
3284    void *p = *pp;
3285    if (n) {
3286       int z;
3287 
3288       if (p == NULL) {
3289          stb__arr_addlen_(pp, size, n  STB__ARGS);
3290          return;
3291       }
3292 
3293       z = stb_arr_len2(p);
3294       stb__arr_addlen_(&p, size, n  STB__ARGS);
3295       memmove((char *) p + (i+n)*size, (char *) p + i*size, size * (z-i));
3296    }
3297    *pp = p;
3298 }
3299 
stb__arr_deleten_(void ** pp,int size,int i,int n STB__PARAMS)3300 void stb__arr_deleten_(void **pp, int size, int i, int n  STB__PARAMS)
3301 {
3302    void *p = *pp;
3303    if (n) {
3304       memmove((char *) p + i*size, (char *) p + (i+n)*size, size * (stb_arr_len2(p)-(i+n)));
3305       stb_arrhead2(p)->len -= n;
3306    }
3307    *pp = p;
3308 }
3309 
3310 #endif
3311 
3312 //////////////////////////////////////////////////////////////////////////////
3313 //
3314 //                               Hashing
3315 //
3316 //      typical use for this is to make a power-of-two hash table.
3317 //
3318 //      let N = size of table (2^n)
3319 //      let H = stb_hash(str)
3320 //      let S = stb_rehash(H) | 1
3321 //
3322 //      then hash probe sequence P(i) for i=0..N-1
3323 //         P(i) = (H + S*i) & (N-1)
3324 //
3325 //      the idea is that H has 32 bits of hash information, but the
3326 //      table has only, say, 2^20 entries so only uses 20 of the bits.
3327 //      then by rehashing the original H we get 2^12 different probe
3328 //      sequences for a given initial probe location. (So it's optimal
3329 //      for 64K tables and its optimality decreases past that.)
3330 //
3331 //      ok, so I've added something that generates _two separate_
3332 //      32-bit hashes simultaneously which should scale better to
3333 //      very large tables.
3334 
3335 
3336 STB_EXTERN unsigned int stb_hash(char *str);
3337 STB_EXTERN unsigned int stb_hashptr(void *p);
3338 STB_EXTERN unsigned int stb_hashlen(char *str, int len);
3339 STB_EXTERN unsigned int stb_rehash_improved(unsigned int v);
3340 STB_EXTERN unsigned int stb_hash_fast(void *p, int len);
3341 STB_EXTERN unsigned int stb_hash2(char *str, unsigned int *hash2_ptr);
3342 STB_EXTERN unsigned int stb_hash_number(unsigned int hash);
3343 
3344 #define stb_rehash(x)  ((x) + ((x) >> 6) + ((x) >> 19))
3345 
3346 #ifdef STB_DEFINE
stb_hash(char * str)3347 unsigned int stb_hash(char *str)
3348 {
3349    unsigned int hash = 0;
3350    while (*str)
3351       hash = (hash << 7) + (hash >> 25) + *str++;
3352    return hash + (hash >> 16);
3353 }
3354 
stb_hashlen(char * str,int len)3355 unsigned int stb_hashlen(char *str, int len)
3356 {
3357    unsigned int hash = 0;
3358    while (len-- > 0 && *str)
3359       hash = (hash << 7) + (hash >> 25) + *str++;
3360    return hash + (hash >> 16);
3361 }
3362 
stb_hashptr(void * p)3363 unsigned int stb_hashptr(void *p)
3364 {
3365    unsigned int x = (unsigned int) p;
3366 
3367    // typically lacking in low bits and high bits
3368    x = stb_rehash(x);
3369    x += x << 16;
3370 
3371    // pearson's shuffle
3372    x ^= x << 3;
3373    x += x >> 5;
3374    x ^= x << 2;
3375    x += x >> 15;
3376    x ^= x << 10;
3377    return stb_rehash(x);
3378 }
3379 
stb_rehash_improved(unsigned int v)3380 unsigned int stb_rehash_improved(unsigned int v)
3381 {
3382    return stb_hashptr((void *)(size_t) v);
3383 }
3384 
stb_hash2(char * str,unsigned int * hash2_ptr)3385 unsigned int stb_hash2(char *str, unsigned int *hash2_ptr)
3386 {
3387    unsigned int hash1 = 0x3141592c;
3388    unsigned int hash2 = 0x77f044ed;
3389    while (*str) {
3390       hash1 = (hash1 << 7) + (hash1 >> 25) + *str;
3391       hash2 = (hash2 << 11) + (hash2 >> 21) + *str;
3392       ++str;
3393    }
3394    *hash2_ptr = hash2 + (hash1 >> 16);
3395    return       hash1 + (hash2 >> 16);
3396 }
3397 
3398 // Paul Hsieh hash
3399 #define stb__get16_slow(p) ((p)[0] + ((p)[1] << 8))
3400 #if defined(_MSC_VER)
3401    #define stb__get16(p) (*((unsigned short *) (p)))
3402 #else
3403    #define stb__get16(p) stb__get16_slow(p)
3404 #endif
3405 
stb_hash_fast(void * p,int len)3406 unsigned int stb_hash_fast(void *p, int len)
3407 {
3408    unsigned char *q = (unsigned char *) p;
3409    unsigned int hash = len;
3410 
3411    if (len <= 0 || q == NULL) return 0;
3412 
3413    /* Main loop */
3414    if (((int) q & 1) == 0) {
3415       for (;len > 3; len -= 4) {
3416          unsigned int val;
3417          hash +=  stb__get16(q);
3418          val   = (stb__get16(q+2) << 11);
3419          hash  = (hash << 16) ^ hash ^ val;
3420          q    += 4;
3421          hash += hash >> 11;
3422       }
3423    } else {
3424       for (;len > 3; len -= 4) {
3425          unsigned int val;
3426          hash +=  stb__get16_slow(q);
3427          val   = (stb__get16_slow(q+2) << 11);
3428          hash  = (hash << 16) ^ hash ^ val;
3429          q    += 4;
3430          hash += hash >> 11;
3431       }
3432    }
3433 
3434    /* Handle end cases */
3435    switch (len) {
3436       case 3: hash += stb__get16_slow(q);
3437               hash ^= hash << 16;
3438               hash ^= q[2] << 18;
3439               hash += hash >> 11;
3440               break;
3441       case 2: hash += stb__get16_slow(q);
3442               hash ^= hash << 11;
3443               hash += hash >> 17;
3444               break;
3445       case 1: hash += q[0];
3446               hash ^= hash << 10;
3447               hash += hash >> 1;
3448               break;
3449       case 0: break;
3450    }
3451 
3452    /* Force "avalanching" of final 127 bits */
3453    hash ^= hash << 3;
3454    hash += hash >> 5;
3455    hash ^= hash << 4;
3456    hash += hash >> 17;
3457    hash ^= hash << 25;
3458    hash += hash >> 6;
3459 
3460    return hash;
3461 }
3462 
stb_hash_number(unsigned int hash)3463 unsigned int stb_hash_number(unsigned int hash)
3464 {
3465    hash ^= hash << 3;
3466    hash += hash >> 5;
3467    hash ^= hash << 4;
3468    hash += hash >> 17;
3469    hash ^= hash << 25;
3470    hash += hash >> 6;
3471    return hash;
3472 }
3473 
3474 #endif
3475 
3476 //////////////////////////////////////////////////////////////////////////////
3477 //
3478 //                     Perfect hashing for ints/pointers
3479 //
3480 //   This is mainly useful for making faster pointer-indexed tables
3481 //   that don't change frequently. E.g. for stb_ischar().
3482 //
3483 
3484 typedef struct
3485 {
3486    stb_uint32  addend;
3487    stb_uint    multiplicand;
3488    stb_uint    b_mask;
3489    stb_uint8   small_bmap[16];
3490    stb_uint16  *large_bmap;
3491 
3492    stb_uint table_mask;
3493    stb_uint32 *table;
3494 } stb_perfect;
3495 
3496 STB_EXTERN int stb_perfect_create(stb_perfect *,unsigned int*,int n);
3497 STB_EXTERN void stb_perfect_destroy(stb_perfect *);
3498 STB_EXTERN int stb_perfect_hash(stb_perfect *, unsigned int x);
3499 extern int stb_perfect_hash_max_failures;
3500 
3501 #ifdef STB_DEFINE
3502 
3503 int stb_perfect_hash_max_failures;
3504 
stb_perfect_hash(stb_perfect * p,unsigned int x)3505 int stb_perfect_hash(stb_perfect *p, unsigned int x)
3506 {
3507    stb_uint m = x * p->multiplicand;
3508    stb_uint y = x >> 16;
3509    stb_uint bv = (m >> 24) + y;
3510    stb_uint av = (m + y) >> 12;
3511    if (p->table == NULL) return -1;  // uninitialized table fails
3512    bv &= p->b_mask;
3513    av &= p->table_mask;
3514    if (p->large_bmap)
3515       av ^= p->large_bmap[bv];
3516    else
3517       av ^= p->small_bmap[bv];
3518    return p->table[av] == x ? av : -1;
3519 }
3520 
stb__perfect_prehash(stb_perfect * p,stb_uint x,stb_uint16 * a,stb_uint16 * b)3521 static void stb__perfect_prehash(stb_perfect *p, stb_uint x, stb_uint16 *a, stb_uint16 *b)
3522 {
3523    stb_uint m = x * p->multiplicand;
3524    stb_uint y = x >> 16;
3525    stb_uint bv = (m >> 24) + y;
3526    stb_uint av = (m + y) >> 12;
3527    bv &= p->b_mask;
3528    av &= p->table_mask;
3529    *b = bv;
3530    *a = av;
3531 }
3532 
stb__perfect_rand(void)3533 static unsigned long stb__perfect_rand(void)
3534 {
3535    static unsigned long stb__rand;
3536    stb__rand = stb__rand * 2147001325 + 715136305;
3537    return 0x31415926 ^ ((stb__rand >> 16) + (stb__rand << 16));
3538 }
3539 
3540 typedef struct {
3541    unsigned short count;
3542    unsigned short b;
3543    unsigned short map;
3544    unsigned short *entries;
3545 } stb__slot;
3546 
stb__slot_compare(const void * p,const void * q)3547 static int stb__slot_compare(const void *p, const void *q)
3548 {
3549    stb__slot *a = (stb__slot *) p;
3550    stb__slot *b = (stb__slot *) q;
3551    return a->count > b->count ? -1 : a->count < b->count;  // sort large to small
3552 }
3553 
stb_perfect_create(stb_perfect * p,unsigned int * v,int n)3554 int stb_perfect_create(stb_perfect *p, unsigned int *v, int n)
3555 {
3556    unsigned int buffer1[64], buffer2[64], buffer3[64], buffer4[64], buffer5[32];
3557    unsigned short *as = (unsigned short *) stb_temp(buffer1, sizeof(*v)*n);
3558    unsigned short *bs = (unsigned short *) stb_temp(buffer2, sizeof(*v)*n);
3559    unsigned short *entries = (unsigned short *) stb_temp(buffer4, sizeof(*entries) * n);
3560    int size = 1 << stb_log2_ceil(n), bsize=8;
3561    int failure = 0,i,j,k;
3562 
3563    assert(n <= 32768);
3564    p->large_bmap = NULL;
3565 
3566    for(;;) {
3567       stb__slot *bcount = (stb__slot *) stb_temp(buffer3, sizeof(*bcount) * bsize);
3568       unsigned short *bloc = (unsigned short *) stb_temp(buffer5, sizeof(*bloc) * bsize);
3569       unsigned short *e;
3570       int bad=0;
3571 
3572       p->addend = stb__perfect_rand();
3573       p->multiplicand = stb__perfect_rand() | 1;
3574       p->table_mask = size-1;
3575       p->b_mask = bsize-1;
3576       p->table = (stb_uint32 *) malloc(size * sizeof(*p->table));
3577 
3578       for (i=0; i < bsize; ++i) {
3579          bcount[i].b     = i;
3580          bcount[i].count = 0;
3581          bcount[i].map   = 0;
3582       }
3583       for (i=0; i < n; ++i) {
3584          stb__perfect_prehash(p, v[i], as+i, bs+i);
3585          ++bcount[bs[i]].count;
3586       }
3587       qsort(bcount, bsize, sizeof(*bcount), stb__slot_compare);
3588       e = entries; // now setup up their entries index
3589       for (i=0; i < bsize; ++i) {
3590          bcount[i].entries = e;
3591          e += bcount[i].count;
3592          bcount[i].count = 0;
3593          bloc[bcount[i].b] = i;
3594       }
3595       // now fill them out
3596       for (i=0; i < n; ++i) {
3597          int b = bs[i];
3598          int w = bloc[b];
3599          bcount[w].entries[bcount[w].count++] = i;
3600       }
3601       stb_tempfree(buffer5,bloc);
3602       // verify
3603       for (i=0; i < bsize; ++i)
3604          for (j=0; j < bcount[i].count; ++j)
3605             assert(bs[bcount[i].entries[j]] == bcount[i].b);
3606       memset(p->table, 0, size*sizeof(*p->table));
3607 
3608       // check if any b has duplicate a
3609       for (i=0; i < bsize; ++i) {
3610          if (bcount[i].count > 1) {
3611             for (j=0; j < bcount[i].count; ++j) {
3612                if (p->table[as[bcount[i].entries[j]]])
3613                   bad = 1;
3614                p->table[as[bcount[i].entries[j]]] = 1;
3615             }
3616             for (j=0; j < bcount[i].count; ++j) {
3617                p->table[as[bcount[i].entries[j]]] = 0;
3618             }
3619             if (bad) break;
3620          }
3621       }
3622 
3623       if (!bad) {
3624          // go through the bs and populate the table, first fit
3625          for (i=0; i < bsize; ++i) {
3626             if (bcount[i].count) {
3627                // go through the candidate table[b] values
3628                for (j=0; j < size; ++j) {
3629                   // go through the a values and see if they fit
3630                   for (k=0; k < bcount[i].count; ++k) {
3631                      int a = as[bcount[i].entries[k]];
3632                      if (p->table[(a^j)&p->table_mask]) {
3633                         break; // fails
3634                      }
3635                   }
3636                   // if succeeded, accept
3637                   if (k == bcount[i].count) {
3638                      bcount[i].map = j;
3639                      for (k=0; k < bcount[i].count; ++k) {
3640                         int a = as[bcount[i].entries[k]];
3641                         p->table[(a^j)&p->table_mask] = 1;
3642                      }
3643                      break;
3644                   }
3645                }
3646                if (j == size)
3647                   break; // no match for i'th entry, so break out in failure
3648             }
3649          }
3650          if (i == bsize) {
3651             // success... fill out map
3652             if (bsize <= 16 && size <= 256) {
3653                p->large_bmap = NULL;
3654                for (i=0; i < bsize; ++i)
3655                   p->small_bmap[bcount[i].b] = (stb_uint8) bcount[i].map;
3656             } else {
3657                p->large_bmap = (unsigned short *) malloc(sizeof(*p->large_bmap) * bsize);
3658                for (i=0; i < bsize; ++i)
3659                   p->large_bmap[bcount[i].b] = bcount[i].map;
3660             }
3661 
3662             // initialize table to v[0], so empty slots will fail
3663             for (i=0; i < size; ++i)
3664                p->table[i] = v[0];
3665 
3666             for (i=0; i < n; ++i)
3667                if (p->large_bmap)
3668                   p->table[as[i] ^ p->large_bmap[bs[i]]] = v[i];
3669                else
3670                   p->table[as[i] ^ p->small_bmap[bs[i]]] = v[i];
3671 
3672             // and now validate that none of them collided
3673             for (i=0; i < n; ++i)
3674                assert(stb_perfect_hash(p, v[i]) >= 0);
3675 
3676             stb_tempfree(buffer3, bcount);
3677             break;
3678          }
3679       }
3680       free(p->table);
3681       p->table = NULL;
3682       stb_tempfree(buffer3, bcount);
3683 
3684       ++failure;
3685       if (failure >= 4 && bsize < size) bsize *= 2;
3686       if (failure >= 8 && (failure & 3) == 0 && size < 4*n) {
3687          size *= 2;
3688          bsize *= 2;
3689       }
3690       if (failure == 6) {
3691          // make sure the input data is unique, so we don't infinite loop
3692          unsigned int *data = (unsigned int *) stb_temp(buffer3, n * sizeof(*data));
3693          memcpy(data, v, sizeof(*data) * n);
3694          qsort(data, n, sizeof(*data), stb_intcmp(0));
3695          for (i=1; i < n; ++i) {
3696             if (data[i] == data[i-1])
3697                size = 0; // size is return value, so 0 it
3698          }
3699          stb_tempfree(buffer3, data);
3700          if (!size) break;
3701       }
3702    }
3703 
3704    if (failure > stb_perfect_hash_max_failures)
3705       stb_perfect_hash_max_failures = failure;
3706 
3707    stb_tempfree(buffer1, as);
3708    stb_tempfree(buffer2, bs);
3709    stb_tempfree(buffer4, entries);
3710 
3711    return size;
3712 }
3713 
stb_perfect_destroy(stb_perfect * p)3714 void stb_perfect_destroy(stb_perfect *p)
3715 {
3716    if (p->large_bmap) free(p->large_bmap);
3717    if (p->table     ) free(p->table);
3718    p->large_bmap = NULL;
3719    p->table      = NULL;
3720    p->b_mask     = 0;
3721    p->table_mask = 0;
3722 }
3723 #endif
3724 
3725 //////////////////////////////////////////////////////////////////////////////
3726 //
3727 //                     Perfect hash clients
3728 
3729 STB_EXTERN int    stb_ischar(char s, char *set);
3730 
3731 #ifdef STB_DEFINE
3732 
stb_ischar(char c,char * set)3733 int stb_ischar(char c, char *set)
3734 {
3735    static unsigned char bit[8] = { 1,2,4,8,16,32,64,128 };
3736    static stb_perfect p;
3737    static unsigned char (*tables)[256];
3738    static char ** sets = NULL;
3739 
3740    int z = stb_perfect_hash(&p, (int) set);
3741    if (z < 0) {
3742       int i,k,n,j,f;
3743       // special code that means free all existing data
3744       if (set == NULL) {
3745          stb_arr_free(sets);
3746          free(tables);
3747          tables = NULL;
3748          stb_perfect_destroy(&p);
3749          return 0;
3750       }
3751       stb_arr_push(sets, set);
3752       stb_perfect_destroy(&p);
3753       n = stb_perfect_create(&p, (unsigned int *) (char **) sets, stb_arr_len(sets));
3754       assert(n != 0);
3755       k = (n+7) >> 3;
3756       tables = (unsigned char (*)[256]) realloc(tables, sizeof(*tables) * k);
3757       memset(tables, 0, sizeof(*tables) * k);
3758       for (i=0; i < stb_arr_len(sets); ++i) {
3759          k = stb_perfect_hash(&p, (int) sets[i]);
3760          assert(k >= 0);
3761          n = k >> 3;
3762          f = bit[k&7];
3763          for (j=0; !j || sets[i][j]; ++j) {
3764             tables[n][(unsigned char) sets[i][j]] |= f;
3765          }
3766       }
3767       z = stb_perfect_hash(&p, (int) set);
3768    }
3769    return tables[z >> 3][(unsigned char) c] & bit[z & 7];
3770 }
3771 
3772 #endif
3773 
3774 //////////////////////////////////////////////////////////////////////////////
3775 //
3776 //                     Instantiated data structures
3777 //
3778 // This is an attempt to implement a templated data structure.
3779 //
3780 // Hash table: call stb_define_hash(TYPE,N,KEY,K1,K2,HASH,VALUE)
3781 //     TYPE     -- will define a structure type containing the hash table
3782 //     N        -- the name, will prefix functions named:
3783 //                        N create
3784 //                        N destroy
3785 //                        N get
3786 //                        N set, N add, N update,
3787 //                        N remove
3788 //     KEY      -- the type of the key. 'x == y' must be valid
3789 //       K1,K2  -- keys never used by the app, used as flags in the hashtable
3790 //       HASH   -- a piece of code ending with 'return' that hashes key 'k'
3791 //     VALUE    -- the type of the value. 'x = y' must be valid
3792 //
3793 //  Note that stb_define_hash_base can be used to define more sophisticated
3794 //  hash tables, e.g. those that make copies of the key or use special
3795 //  comparisons (e.g. strcmp).
3796 
3797 #define STB_(prefix,name)     stb__##prefix##name
3798 #define STB__(prefix,name)    prefix##name
3799 #define STB__use(x)           x
3800 #define STB__skip(x)
3801 
3802 #define stb_declare_hash(PREFIX,TYPE,N,KEY,VALUE) \
3803    typedef struct stb__st_##TYPE TYPE;\
3804    PREFIX int STB__(N, init)(TYPE *h, int count);\
3805    PREFIX int STB__(N, memory_usage)(TYPE *h);\
3806    PREFIX TYPE * STB__(N, create)(void);\
3807    PREFIX TYPE * STB__(N, copy)(TYPE *h);\
3808    PREFIX void STB__(N, destroy)(TYPE *h);\
3809    PREFIX int STB__(N,get_flag)(TYPE *a, KEY k, VALUE *v);\
3810    PREFIX VALUE STB__(N,get)(TYPE *a, KEY k);\
3811    PREFIX int STB__(N, set)(TYPE *a, KEY k, VALUE v);\
3812    PREFIX int STB__(N, add)(TYPE *a, KEY k, VALUE v);\
3813    PREFIX int STB__(N, update)(TYPE*a,KEY k,VALUE v);\
3814    PREFIX int STB__(N, remove)(TYPE *a, KEY k, VALUE *v);
3815 
3816 #define STB_nocopy(x)        (x)
3817 #define STB_nodelete(x)      0
3818 #define STB_nofields
3819 #define STB_nonullvalue(x)
3820 #define STB_nullvalue(x)     x
3821 #define STB_safecompare(x)   x
3822 #define STB_nosafe(x)
3823 #define STB_noprefix
3824 
3825 #ifdef __GNUC__
3826 #define STB__nogcc(x)
3827 #else
3828 #define STB__nogcc(x)  x
3829 #endif
3830 
3831 #define stb_define_hash_base(PREFIX,TYPE,FIELDS,N,NC,LOAD_FACTOR,             \
3832                              KEY,EMPTY,DEL,COPY,DISPOSE,SAFE,                 \
3833                              VCOMPARE,CCOMPARE,HASH,                          \
3834                              VALUE,HASVNULL,VNULL)                            \
3835                                                                               \
3836 typedef struct                                                                \
3837 {                                                                             \
3838    KEY   k;                                                                   \
3839    VALUE v;                                                                   \
3840 } STB_(N,_hashpair);                                                          \
3841                                                                               \
3842 STB__nogcc( typedef struct stb__st_##TYPE TYPE;  )                            \
3843 struct stb__st_##TYPE {                                                       \
3844    FIELDS                                                                     \
3845    STB_(N,_hashpair) *table;                                                  \
3846    unsigned int mask;                                                         \
3847    int count, limit;                                                          \
3848    int deleted;                                                               \
3849                                                                               \
3850    int delete_threshhold;                                                     \
3851    int grow_threshhold;                                                       \
3852    int shrink_threshhold;                                                     \
3853    unsigned char alloced, has_empty, has_del;                                 \
3854    VALUE ev; VALUE dv;                                                        \
3855 };                                                                            \
3856                                                                               \
3857 static unsigned int STB_(N, hash)(KEY k)                                      \
3858 {                                                                             \
3859    HASH                                                                       \
3860 }                                                                             \
3861                                                                               \
3862 PREFIX int STB__(N, init)(TYPE *h, int count)                                        \
3863 {                                                                             \
3864    int i;                                                                     \
3865    if (count < 4) count = 4;                                                  \
3866    h->limit = count;                                                          \
3867    h->count = 0;                                                              \
3868    h->mask  = count-1;                                                        \
3869    h->deleted = 0;                                                            \
3870    h->grow_threshhold = (int) (count * LOAD_FACTOR);                          \
3871    h->has_empty = h->has_del = 0;                                             \
3872    h->alloced = 0;                                                            \
3873    if (count <= 64)                                                           \
3874       h->shrink_threshhold = 0;                                               \
3875    else                                                                       \
3876       h->shrink_threshhold = (int) (count * (LOAD_FACTOR/2.25));              \
3877    h->delete_threshhold = (int) (count * (1-LOAD_FACTOR)/2);                  \
3878    h->table = (STB_(N,_hashpair)*) malloc(sizeof(h->table[0]) * count);       \
3879    if (h->table == NULL) return 0;                                            \
3880    /* ideally this gets turned into a memset32 automatically */               \
3881    for (i=0; i < count; ++i)                                                  \
3882       h->table[i].k = EMPTY;                                                  \
3883    return 1;                                                                  \
3884 }                                                                             \
3885                                                                               \
3886 PREFIX int STB__(N, memory_usage)(TYPE *h)                                           \
3887 {                                                                             \
3888    return sizeof(*h) + h->limit * sizeof(h->table[0]);                        \
3889 }                                                                             \
3890                                                                               \
3891 PREFIX TYPE * STB__(N, create)(void)                                                 \
3892 {                                                                             \
3893    TYPE *h = (TYPE *) malloc(sizeof(*h));                                     \
3894    if (h) {                                                                   \
3895       if (STB__(N, init)(h, 16))                                              \
3896          h->alloced = 1;                                                      \
3897       else { free(h); h=NULL; }                                               \
3898    }                                                                          \
3899    return h;                                                                  \
3900 }                                                                             \
3901                                                                               \
3902 PREFIX void STB__(N, destroy)(TYPE *a)                                               \
3903 {                                                                             \
3904    int i;                                                                     \
3905    for (i=0; i < a->limit; ++i)                                               \
3906       if (!CCOMPARE(a->table[i].k,EMPTY) && !CCOMPARE(a->table[i].k, DEL))    \
3907          DISPOSE(a->table[i].k);                                              \
3908    free(a->table);                                                            \
3909    if (a->alloced)                                                            \
3910       free(a);                                                                \
3911 }                                                                             \
3912                                                                               \
3913 static void STB_(N, rehash)(TYPE *a, int count);                              \
3914                                                                               \
3915 PREFIX int STB__(N,get_flag)(TYPE *a, KEY k, VALUE *v)                               \
3916 {                                                                             \
3917    unsigned int h = STB_(N, hash)(k);                                         \
3918    unsigned int n = h & a->mask, s;                                           \
3919    if (CCOMPARE(k,EMPTY)){ if (a->has_empty) *v = a->ev; return a->has_empty;}\
3920    if (CCOMPARE(k,DEL)) { if (a->has_del  ) *v = a->dv; return a->has_del;   }\
3921    if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                               \
3922    SAFE(if (!CCOMPARE(a->table[n].k,DEL)))                                    \
3923    if (VCOMPARE(a->table[n].k,k)) { *v = a->table[n].v; return 1; }            \
3924    s = stb_rehash(h) | 1;                                                     \
3925    for(;;) {                                                                  \
3926       n = (n + s) & a->mask;                                                  \
3927       if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                            \
3928       SAFE(if (CCOMPARE(a->table[n].k,DEL)) continue;)                        \
3929       if (VCOMPARE(a->table[n].k,k))                                           \
3930          { *v = a->table[n].v; return 1; }                                    \
3931    }                                                                          \
3932 }                                                                             \
3933                                                                               \
3934 HASVNULL(                                                                     \
3935    PREFIX VALUE STB__(N,get)(TYPE *a, KEY k)                                         \
3936    {                                                                          \
3937       VALUE v;                                                                \
3938       if (STB__(N,get_flag)(a,k,&v)) return v;                                \
3939       else                           return VNULL;                            \
3940    }                                                                          \
3941 )                                                                             \
3942                                                                               \
3943 PREFIX int STB__(N,getkey)(TYPE *a, KEY k, KEY *kout)                                \
3944 {                                                                             \
3945    unsigned int h = STB_(N, hash)(k);                                         \
3946    unsigned int n = h & a->mask, s;                                           \
3947    if (CCOMPARE(k,EMPTY)||CCOMPARE(k,DEL)) return 0;                          \
3948    if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                               \
3949    SAFE(if (!CCOMPARE(a->table[n].k,DEL)))                                    \
3950    if (VCOMPARE(a->table[n].k,k)) { *kout = a->table[n].k; return 1; }         \
3951    s = stb_rehash(h) | 1;                                                     \
3952    for(;;) {                                                                  \
3953       n = (n + s) & a->mask;                                                  \
3954       if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                            \
3955       SAFE(if (CCOMPARE(a->table[n].k,DEL)) continue;)                        \
3956       if (VCOMPARE(a->table[n].k,k))                                          \
3957          { *kout = a->table[n].k; return 1; }                                 \
3958    }                                                                          \
3959 }                                                                             \
3960                                                                               \
3961 static int STB_(N,addset)(TYPE *a, KEY k, VALUE v,                            \
3962                              int allow_new, int allow_old, int copy)          \
3963 {                                                                             \
3964    unsigned int h = STB_(N, hash)(k);                                         \
3965    unsigned int n = h & a->mask;                                              \
3966    int b = -1;                                                                \
3967    if (CCOMPARE(k,EMPTY)) {                                                   \
3968       if (a->has_empty ? allow_old : allow_new) {                             \
3969           n=a->has_empty; a->ev = v; a->has_empty = 1; return !n;             \
3970       } else return 0;                                                        \
3971    }                                                                          \
3972    if (CCOMPARE(k,DEL)) {                                                     \
3973       if (a->has_del ? allow_old : allow_new) {                               \
3974           n=a->has_del; a->dv = v; a->has_del = 1; return !n;                 \
3975       } else return 0;                                                        \
3976    }                                                                          \
3977    if (!CCOMPARE(a->table[n].k, EMPTY)) {                                     \
3978       unsigned int s;                                                         \
3979       if (CCOMPARE(a->table[n].k, DEL))                                       \
3980          b = n;                                                               \
3981       else if (VCOMPARE(a->table[n].k,k)) {                                   \
3982          if (allow_old)                                                       \
3983             a->table[n].v = v;                                                \
3984          return !allow_new;                                                   \
3985       }                                                                       \
3986       s = stb_rehash(h) | 1;                                                  \
3987       for(;;) {                                                               \
3988          n = (n + s) & a->mask;                                               \
3989          if (CCOMPARE(a->table[n].k, EMPTY)) break;                           \
3990          if (CCOMPARE(a->table[n].k, DEL)) {                                  \
3991             if (b < 0) b = n;                                                 \
3992          } else if (VCOMPARE(a->table[n].k,k)) {                              \
3993             if (allow_old)                                                    \
3994                a->table[n].v = v;                                             \
3995             return !allow_new;                                                \
3996          }                                                                    \
3997       }                                                                       \
3998    }                                                                          \
3999    if (!allow_new) return 0;                                                  \
4000    if (b < 0) b = n; else --a->deleted;                                       \
4001    a->table[b].k = copy ? COPY(k) : k;                                        \
4002    a->table[b].v = v;                                                         \
4003    ++a->count;                                                                \
4004    if (a->count > a->grow_threshhold)                                         \
4005       STB_(N,rehash)(a, a->limit*2);                                          \
4006    return 1;                                                                  \
4007 }                                                                             \
4008                                                                               \
4009 PREFIX int STB__(N, set)(TYPE *a, KEY k, VALUE v){return STB_(N,addset)(a,k,v,1,1,1);}\
4010 PREFIX int STB__(N, add)(TYPE *a, KEY k, VALUE v){return STB_(N,addset)(a,k,v,1,0,1);}\
4011 PREFIX int STB__(N, update)(TYPE*a,KEY k,VALUE v){return STB_(N,addset)(a,k,v,0,1,1);}\
4012                                                                               \
4013 PREFIX int STB__(N, remove)(TYPE *a, KEY k, VALUE *v)                                \
4014 {                                                                             \
4015    unsigned int h = STB_(N, hash)(k);                                         \
4016    unsigned int n = h & a->mask, s;                                           \
4017    if (CCOMPARE(k,EMPTY)) { if (a->has_empty) { if(v)*v = a->ev; a->has_empty=0; return 1; } return 0; } \
4018    if (CCOMPARE(k,DEL))   { if (a->has_del  ) { if(v)*v = a->dv; a->has_del  =0; return 1; } return 0; } \
4019    if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                               \
4020    if (SAFE(CCOMPARE(a->table[n].k,DEL) || ) !VCOMPARE(a->table[n].k,k)) {     \
4021       s = stb_rehash(h) | 1;                                                  \
4022       for(;;) {                                                               \
4023          n = (n + s) & a->mask;                                               \
4024          if (CCOMPARE(a->table[n].k,EMPTY)) return 0;                         \
4025          SAFE(if (CCOMPARE(a->table[n].k, DEL)) continue;)                    \
4026          if (VCOMPARE(a->table[n].k,k)) break;                                 \
4027       }                                                                       \
4028    }                                                                          \
4029    DISPOSE(a->table[n].k);                                                    \
4030    a->table[n].k = DEL;                                                       \
4031    --a->count;                                                                \
4032    ++a->deleted;                                                              \
4033    if (v != NULL)                                                             \
4034       *v = a->table[n].v;                                                     \
4035    if (a->count < a->shrink_threshhold)                                       \
4036       STB_(N, rehash)(a, a->limit >> 1);                                      \
4037    else if (a->deleted > a->delete_threshhold)                                \
4038       STB_(N, rehash)(a, a->limit);                                           \
4039    return 1;                                                                  \
4040 }                                                                             \
4041                                                                               \
4042 PREFIX TYPE * STB__(NC, copy)(TYPE *a)                                        \
4043 {                                                                             \
4044    int i;                                                                     \
4045    TYPE *h = (TYPE *) malloc(sizeof(*h));                                     \
4046    if (!h) return NULL;                                                       \
4047    if (!STB__(N, init)(h, a->limit)) { free(h); return NULL; }                \
4048    h->count = a->count;                                                       \
4049    h->deleted = a->deleted;                                                   \
4050    h->alloced = 1;                                                            \
4051    h->ev = a->ev; h->dv = a->dv;                                              \
4052    h->has_empty = a->has_empty; h->has_del = a->has_del;                      \
4053    memcpy(h->table, a->table, h->limit * sizeof(h->table[0]));                \
4054    for (i=0; i < a->limit; ++i)                                               \
4055       if (!CCOMPARE(h->table[i].k,EMPTY) && !CCOMPARE(h->table[i].k,DEL))     \
4056          h->table[i].k = COPY(h->table[i].k);                                 \
4057    return h;                                                                  \
4058 }                                                                             \
4059                                                                               \
4060 static void STB_(N, rehash)(TYPE *a, int count)                               \
4061 {                                                                             \
4062    int i;                                                                     \
4063    TYPE b;                                                                    \
4064    STB__(N, init)(&b, count);                                                 \
4065    for (i=0; i < a->limit; ++i)                                               \
4066       if (!CCOMPARE(a->table[i].k,EMPTY) && !CCOMPARE(a->table[i].k,DEL))     \
4067          STB_(N,addset)(&b, a->table[i].k, a->table[i].v,1,1,0);              \
4068    free(a->table);                                                            \
4069    a->table = b.table;                                                        \
4070    a->mask = b.mask;                                                          \
4071    a->count = b.count;                                                        \
4072    a->limit = b.limit;                                                        \
4073    a->deleted = b.deleted;                                                    \
4074    a->delete_threshhold = b.delete_threshhold;                                \
4075    a->grow_threshhold = b.grow_threshhold;                                    \
4076    a->shrink_threshhold = b.shrink_threshhold;                                \
4077 }
4078 
4079 #define STB_equal(a,b)  ((a) == (b))
4080 
4081 #define stb_define_hash(TYPE,N,KEY,EMPTY,DEL,HASH,VALUE)                      \
4082    stb_define_hash_base(STB_noprefix, TYPE,STB_nofields,N,NC,0.85f,              \
4083               KEY,EMPTY,DEL,STB_nocopy,STB_nodelete,STB_nosafe,               \
4084               STB_equal,STB_equal,HASH,                                       \
4085               VALUE,STB_nonullvalue,0)
4086 
4087 #define stb_define_hash_vnull(TYPE,N,KEY,EMPTY,DEL,HASH,VALUE,VNULL)          \
4088    stb_define_hash_base(STB_noprefix, TYPE,STB_nofields,N,NC,0.85f,              \
4089               KEY,EMPTY,DEL,STB_nocopy,STB_nodelete,STB_nosafe,               \
4090               STB_equal,STB_equal,HASH,                                       \
4091               VALUE,STB_nullvalue,VNULL)
4092 
4093 //////////////////////////////////////////////////////////////////////////////
4094 //
4095 //                        stb_ptrmap
4096 //
4097 // An stb_ptrmap data structure is an O(1) hash table between pointers. One
4098 // application is to let you store "extra" data associated with pointers,
4099 // which is why it was originally called stb_extra.
4100 
4101 stb_declare_hash(STB_EXTERN, stb_ptrmap, stb_ptrmap_, void *, void *)
4102 stb_declare_hash(STB_EXTERN, stb_idict, stb_idict_, stb_int32, stb_int32)
4103 
4104 STB_EXTERN void        stb_ptrmap_delete(stb_ptrmap *e, void (*free_func)(void *));
4105 STB_EXTERN stb_ptrmap *stb_ptrmap_new(void);
4106 
4107 STB_EXTERN stb_idict * stb_idict_new_size(int size);
4108 STB_EXTERN void        stb_idict_remove_all(stb_idict *e);
4109 
4110 #ifdef STB_DEFINE
4111 
4112 #define STB_EMPTY ((void *) 2)
4113 #define STB_EDEL  ((void *) 6)
4114 
4115 stb_define_hash_base(STB_noprefix,stb_ptrmap, STB_nofields, stb_ptrmap_,stb_ptrmap_,0.85f,
4116               void *,STB_EMPTY,STB_EDEL,STB_nocopy,STB_nodelete,STB_nosafe,
4117               STB_equal,STB_equal,return stb_hashptr(k);,
4118               void *,STB_nullvalue,NULL)
4119 
stb_ptrmap_new(void)4120 stb_ptrmap *stb_ptrmap_new(void)
4121 {
4122    return stb_ptrmap_create();
4123 }
4124 
stb_ptrmap_delete(stb_ptrmap * e,void (* free_func)(void *))4125 void stb_ptrmap_delete(stb_ptrmap *e, void (*free_func)(void *))
4126 {
4127    int i;
4128    if (free_func)
4129       for (i=0; i < e->limit; ++i)
4130          if (e->table[i].k != STB_EMPTY && e->table[i].k != STB_EDEL) {
4131             if (free_func == free)
4132                free(e->table[i].v); // allow STB_MALLOC_WRAPPER to operate
4133             else
4134                free_func(e->table[i].v);
4135          }
4136    stb_ptrmap_destroy(e);
4137 }
4138 
4139 // extra fields needed for stua_dict
4140 #define STB_IEMPTY  ((int) 1)
4141 #define STB_IDEL    ((int) 3)
4142 stb_define_hash_base(STB_noprefix, stb_idict, short type; short gc; STB_nofields, stb_idict_,stb_idict_,0.85f,
4143               stb_int32,STB_IEMPTY,STB_IDEL,STB_nocopy,STB_nodelete,STB_nosafe,
4144               STB_equal,STB_equal,
4145               return stb_rehash_improved(k);,stb_int32,STB_nonullvalue,0)
4146 
stb_idict_new_size(int size)4147 stb_idict * stb_idict_new_size(int size)
4148 {
4149    stb_idict *e = (stb_idict *) malloc(sizeof(*e));
4150    if (e) {
4151       if (!stb_is_pow2(size))
4152          size = 1 << stb_log2_ceil(size);
4153       stb_idict_init(e, size);
4154       e->alloced = 1;
4155    }
4156    return e;
4157 }
4158 
stb_idict_remove_all(stb_idict * e)4159 void stb_idict_remove_all(stb_idict *e)
4160 {
4161    int n;
4162    for (n=0; n < e->limit; ++n)
4163       e->table[n].k = STB_IEMPTY;
4164    e->has_empty = e->has_del = 0;
4165 }
4166 #endif
4167 
4168 //////////////////////////////////////////////////////////////////////////////
4169 //
4170 //                        stb_sparse_ptr_matrix
4171 //
4172 // An stb_ptrmap data structure is an O(1) hash table storing an arbitrary
4173 // block of data for a given pair of pointers.
4174 //
4175 // If create=0, returns
4176 
4177 typedef struct stb__st_stb_spmatrix stb_spmatrix;
4178 
4179 STB_EXTERN stb_spmatrix * stb_sparse_ptr_matrix_new(int val_size);
4180 STB_EXTERN void           stb_sparse_ptr_matrix_free(stb_spmatrix *z);
4181 STB_EXTERN void         * stb_sparse_ptr_matrix_get(stb_spmatrix *z, void *a, void *b, int create);
4182 
4183 #ifdef STB_DEFINE
4184 typedef struct
4185 {
4186    void *a;
4187    void *b;
4188 } stb__ptrpair;
4189 
4190 static stb__ptrpair stb__ptrpair_empty = { (void *) 1, (void *) 1 };
4191 static stb__ptrpair stb__ptrpair_del   = { (void *) 2, (void *) 2 };
4192 
4193 #define STB__equal_ptrpair(x,y) ((x).a == (y).a && (x).b == (y).b)
4194 
4195 stb_define_hash_base(static, stb_spmatrix, int val_size; void *arena;, stb__spmatrix_,stb__spmatrix_, 0.85,
4196      stb__ptrpair, stb__ptrpair_empty, stb__ptrpair_del,
4197      STB_nocopy, STB_nodelete, STB_nosafe,
4198      STB__equal_ptrpair, STB__equal_ptrpair, return stb_rehash(stb_hashptr(k.a))+stb_hashptr(k.b);,
4199      void *, STB_nullvalue, 0)
4200 
stb_sparse_ptr_matrix_new(int val_size)4201 stb_spmatrix *stb_sparse_ptr_matrix_new(int val_size)
4202 {
4203    stb_spmatrix *m = stb__spmatrix_create();
4204    if (m) m->val_size = val_size;
4205    if (m) m->arena = stb_malloc_global(1);
4206    return m;
4207 }
4208 
stb_sparse_ptr_matrix_free(stb_spmatrix * z)4209 void stb_sparse_ptr_matrix_free(stb_spmatrix *z)
4210 {
4211    if (z->arena) stb_free(z->arena);
4212    stb__spmatrix_destroy(z);
4213 }
4214 
stb_sparse_ptr_matrix_get(stb_spmatrix * z,void * a,void * b,int create)4215 void *stb_sparse_ptr_matrix_get(stb_spmatrix *z, void *a, void *b, int create)
4216 {
4217    stb__ptrpair t = { a,b };
4218    void *data = stb__spmatrix_get(z, t);
4219    if (!data && create) {
4220       data = stb_malloc_raw(z->arena, z->val_size);
4221       if (!data) return NULL;
4222       memset(data, 0, z->val_size);
4223       stb__spmatrix_add(z, t, data);
4224    }
4225    return data;
4226 }
4227 #endif
4228 
4229 
4230 
4231 //////////////////////////////////////////////////////////////////////////////
4232 //
4233 //                  SDICT: Hash Table for Strings (symbol table)
4234 //
4235 //           if "use_arena=1", then strings will be copied
4236 //           into blocks and never freed until the sdict is freed;
4237 //           otherwise they're malloc()ed and free()d on the fly.
4238 //           (specify use_arena=1 if you never stb_sdict_remove)
4239 
4240 stb_declare_hash(STB_EXTERN, stb_sdict, stb_sdict_, char *, void *)
4241 
4242 STB_EXTERN stb_sdict * stb_sdict_new(int use_arena);
4243 STB_EXTERN stb_sdict * stb_sdict_copy(stb_sdict*);
4244 STB_EXTERN void        stb_sdict_delete(stb_sdict *);
4245 STB_EXTERN void *      stb_sdict_change(stb_sdict *, char *str, void *p);
4246 STB_EXTERN int         stb_sdict_count(stb_sdict *d);
4247 
4248 #define stb_sdict_for(d,i,q,z)                                          \
4249    for(i=0; i < (d)->limit ? q=(d)->table[i].k,z=(d)->table[i].v,1 : 0; ++i)    \
4250       if (q==NULL||q==(void *) 1);else   // reversed makes macro friendly
4251 
4252 #ifdef STB_DEFINE
4253 
4254 #define STB_DEL ((void *) 1)
4255 #define STB_SDEL  ((char *) 1)
4256 
4257 #define stb_sdict__copy(x)                                       \
4258    strcpy(a->arena ? stb_malloc_string(a->arena, strlen(x)+1)    \
4259                    : (char *) malloc(strlen(x)+1), x)
4260 
4261 #define stb_sdict__dispose(x)  if (!a->arena) free(x)
4262 
4263 stb_define_hash_base(STB_noprefix, stb_sdict, void*arena;, stb_sdict_,stb_sdictinternal_, 0.85f,
4264         char *, NULL, STB_SDEL, stb_sdict__copy, stb_sdict__dispose,
4265                         STB_safecompare, !strcmp, STB_equal, return stb_hash(k);,
4266         void *, STB_nullvalue, NULL)
4267 
stb_sdict_count(stb_sdict * a)4268 int stb_sdict_count(stb_sdict *a)
4269 {
4270    return a->count;
4271 }
4272 
stb_sdict_new(int use_arena)4273 stb_sdict * stb_sdict_new(int use_arena)
4274 {
4275    stb_sdict *d = stb_sdict_create();
4276    if (d == NULL) return NULL;
4277    d->arena = use_arena ? stb_malloc_global(1) : NULL;
4278    return d;
4279 }
4280 
stb_sdict_copy(stb_sdict * old)4281 stb_sdict* stb_sdict_copy(stb_sdict *old)
4282 {
4283    stb_sdict *n;
4284    void *old_arena = old->arena;
4285    void *new_arena = old_arena ? stb_malloc_global(1) : NULL;
4286    old->arena = new_arena;
4287    n = stb_sdictinternal_copy(old);
4288    old->arena = old_arena;
4289    if (n)
4290       n->arena = new_arena;
4291    else if (new_arena)
4292       stb_free(new_arena);
4293    return n;
4294 }
4295 
4296 
stb_sdict_delete(stb_sdict * d)4297 void stb_sdict_delete(stb_sdict *d)
4298 {
4299    if (d->arena)
4300       stb_free(d->arena);
4301    stb_sdict_destroy(d);
4302 }
4303 
stb_sdict_change(stb_sdict * d,char * str,void * p)4304 void * stb_sdict_change(stb_sdict *d, char *str, void *p)
4305 {
4306    void *q = stb_sdict_get(d, str);
4307    stb_sdict_set(d, str, p);
4308    return q;
4309 }
4310 #endif
4311 
4312 //////////////////////////////////////////////////////////////////////////////
4313 //
4314 //                     Instantiated data structures
4315 //
4316 // This is an attempt to implement a templated data structure.
4317 // What you do is define a struct foo, and then include several
4318 // pointer fields to struct foo in your struct. Then you call
4319 // the instantiator, which creates the functions that implement
4320 // the data structure. This requires massive undebuggable #defines,
4321 // so we limit the cases where we do this.
4322 //
4323 // AA tree is an encoding of a 2-3 tree whereas RB trees encode a 2-3-4 tree;
4324 // much simpler code due to fewer cases.
4325 
4326 #define stb__bst_parent(x)    x
4327 #define stb__bst_noparent(x)
4328 
4329 #define stb_bst_fields(N)                                   \
4330     *STB_(N,left), *STB_(N,right);                          \
4331     unsigned char STB_(N,level)
4332 
4333 #define stb_bst_fields_parent(N)                            \
4334     *STB_(N,left), *STB_(N,right),  *STB_(N,parent);        \
4335     unsigned char STB_(N,level)
4336 
4337 #define STB__level(N,x)         ((x) ? (x)->STB_(N,level) : 0)
4338 
4339 #define stb_bst_base(TYPE, N, TREE, M, compare, PAR)                         \
4340                                                                              \
4341 static int STB_(N,_compare)(TYPE *p, TYPE *q)                                \
4342 {                                                                            \
4343    compare                                                                   \
4344 }                                                                            \
4345                                                                              \
4346 static void STB_(N,setleft)(TYPE *q, TYPE *v)                                \
4347 {                                                                            \
4348    q->STB_(N,left) = v;                                                      \
4349    PAR(if (v) v->STB_(N,parent) = q;)                                        \
4350 }                                                                            \
4351                                                                              \
4352 static void STB_(N,setright)(TYPE *q, TYPE *v)                               \
4353 {                                                                            \
4354    q->STB_(N,right) = v;                                                     \
4355    PAR(if (v) v->STB_(N,parent) = q;)                                        \
4356 }                                                                            \
4357                                                                              \
4358 static TYPE *STB_(N,skew)(TYPE *q)                                           \
4359 {                                                                            \
4360    if (q == NULL) return q;                                                  \
4361    if (q->STB_(N,left)                                                       \
4362         && q->STB_(N,left)->STB_(N,level) == q->STB_(N,level)) {             \
4363       TYPE *p       = q->STB_(N,left);                                       \
4364       STB_(N,setleft)(q, p->STB_(N,right));                                  \
4365       STB_(N,setright)(p, q);                                                \
4366       return p;                                                              \
4367    }                                                                         \
4368    return q;                                                                 \
4369 }                                                                            \
4370                                                                              \
4371 static TYPE *STB_(N,split)(TYPE *p)                                          \
4372 {                                                                            \
4373    TYPE *q = p->STB_(N,right);                                               \
4374    if (q && q->STB_(N,right)                                                 \
4375          && q->STB_(N,right)->STB_(N,level) == p->STB_(N,level)) {           \
4376       STB_(N,setright)(p, q->STB_(N,left));                                  \
4377       STB_(N,setleft)(q,p);                                                  \
4378       ++q->STB_(N,level);                                                    \
4379       return q;                                                              \
4380    }                                                                         \
4381    return p;                                                                 \
4382 }                                                                            \
4383                                                                              \
4384 TYPE *STB__(N,insert)(TYPE *tree, TYPE *item)                                \
4385 {                                                                            \
4386    int c;                                                                    \
4387    if (tree == NULL) {                                                       \
4388       item->STB_(N,left) = NULL;                                             \
4389       item->STB_(N,right) = NULL;                                            \
4390       item->STB_(N,level) = 1;                                               \
4391       PAR(item->STB_(N,parent) = NULL;)                                      \
4392       return item;                                                           \
4393    }                                                                         \
4394    c = STB_(N,_compare)(item,tree);                                          \
4395    if (c == 0) {                                                             \
4396       if (item != tree) {                                                    \
4397          STB_(N,setleft)(item, tree->STB_(N,left));                          \
4398          STB_(N,setright)(item, tree->STB_(N,right));                        \
4399          item->STB_(N,level) = tree->STB_(N,level);                          \
4400          PAR(item->STB_(N,parent) = NULL;)                                   \
4401       }                                                                      \
4402       return item;                                                           \
4403    }                                                                         \
4404    if (c < 0)                                                                \
4405       STB_(N,setleft )(tree, STB__(N,insert)(tree->STB_(N,left), item));     \
4406    else                                                                      \
4407       STB_(N,setright)(tree, STB__(N,insert)(tree->STB_(N,right), item));    \
4408    tree = STB_(N,skew)(tree);                                                \
4409    tree = STB_(N,split)(tree);                                               \
4410    PAR(tree->STB_(N,parent) = NULL;)                                         \
4411    return tree;                                                              \
4412 }                                                                            \
4413                                                                              \
4414 TYPE *STB__(N,remove)(TYPE *tree, TYPE *item)                                \
4415 {                                                                            \
4416    static TYPE *delnode, *leaf, *restore;                                    \
4417    if (tree == NULL) return NULL;                                            \
4418    leaf = tree;                                                              \
4419    if (STB_(N,_compare)(item, tree) < 0) {                                   \
4420       STB_(N,setleft)(tree, STB__(N,remove)(tree->STB_(N,left), item));      \
4421    } else {                                                                  \
4422       TYPE *r;                                                               \
4423       delnode = tree;                                                        \
4424       r = STB__(N,remove)(tree->STB_(N,right), item);                        \
4425       /* maybe move 'leaf' up to this location */                            \
4426       if (restore == tree) { tree = leaf; leaf = restore = NULL;  }          \
4427       STB_(N,setright)(tree,r);                                              \
4428       assert(tree->STB_(N,right) != tree);                                   \
4429    }                                                                         \
4430    if (tree == leaf) {                                                       \
4431       if (delnode == item) {                                                 \
4432          tree = tree->STB_(N,right);                                         \
4433          assert(leaf->STB_(N,left) == NULL);                                 \
4434          /* move leaf (the right sibling) up to delnode */                   \
4435          STB_(N,setleft )(leaf, item->STB_(N,left ));                        \
4436          STB_(N,setright)(leaf, item->STB_(N,right));                        \
4437          leaf->STB_(N,level) = item->STB_(N,level);                          \
4438          if (leaf != item)                                                   \
4439             restore = delnode;                                               \
4440       }                                                                      \
4441       delnode = NULL;                                                        \
4442    } else {                                                                  \
4443       if (STB__level(N,tree->STB_(N,left) ) < tree->STB_(N,level)-1 ||       \
4444           STB__level(N,tree->STB_(N,right)) < tree->STB_(N,level)-1) {       \
4445          --tree->STB_(N,level);                                              \
4446          if (STB__level(N,tree->STB_(N,right)) > tree->STB_(N,level))        \
4447             tree->STB_(N,right)->STB_(N,level) = tree->STB_(N,level);        \
4448          tree = STB_(N,skew)(tree);                                          \
4449          STB_(N,setright)(tree, STB_(N,skew)(tree->STB_(N,right)));          \
4450          if (tree->STB_(N,right))                                            \
4451             STB_(N,setright)(tree->STB_(N,right),                            \
4452                   STB_(N,skew)(tree->STB_(N,right)->STB_(N,right)));         \
4453          tree = STB_(N,split)(tree);                                         \
4454          if (tree->STB_(N,right))                                            \
4455             STB_(N,setright)(tree,  STB_(N,split)(tree->STB_(N,right)));     \
4456       }                                                                      \
4457    }                                                                         \
4458    PAR(if (tree) tree->STB_(N,parent) = NULL;)                               \
4459    return tree;                                                              \
4460 }                                                                            \
4461                                                                              \
4462 TYPE *STB__(N,last)(TYPE *tree)                                              \
4463 {                                                                            \
4464    if (tree)                                                                 \
4465       while (tree->STB_(N,right)) tree = tree->STB_(N,right);                \
4466    return tree;                                                              \
4467 }                                                                            \
4468                                                                              \
4469 TYPE *STB__(N,first)(TYPE *tree)                                             \
4470 {                                                                            \
4471    if (tree)                                                                 \
4472       while (tree->STB_(N,left)) tree = tree->STB_(N,left);                  \
4473    return tree;                                                              \
4474 }                                                                            \
4475                                                                              \
4476 TYPE *STB__(N,next)(TYPE *tree, TYPE *item)                                  \
4477 {                                                                            \
4478    TYPE *next = NULL;                                                        \
4479    if (item->STB_(N,right))                                                  \
4480       return STB__(N,first)(item->STB_(N,right));                            \
4481    PAR(                                                                      \
4482       while(item->STB_(N,parent)) {                                          \
4483          TYPE *up = item->STB_(N,parent);                                    \
4484          if (up->STB_(N,left) == item) return up;                            \
4485          item = up;                                                          \
4486       }                                                                      \
4487       return NULL;                                                           \
4488    )                                                                         \
4489    while (tree != item) {                                                    \
4490       if (STB_(N,_compare)(item, tree) < 0) {                                \
4491          next = tree;                                                        \
4492          tree = tree->STB_(N,left);                                          \
4493       } else {                                                               \
4494          tree = tree->STB_(N,right);                                         \
4495       }                                                                      \
4496    }                                                                         \
4497    return next;                                                              \
4498 }                                                                            \
4499                                                                              \
4500 TYPE *STB__(N,prev)(TYPE *tree, TYPE *item)                                  \
4501 {                                                                            \
4502    TYPE *next = NULL;                                                        \
4503    if (item->STB_(N,left))                                                   \
4504       return STB__(N,last)(item->STB_(N,left));                              \
4505    PAR(                                                                      \
4506       while(item->STB_(N,parent)) {                                          \
4507          TYPE *up = item->STB_(N,parent);                                    \
4508          if (up->STB_(N,right) == item) return up;                           \
4509          item = up;                                                          \
4510       }                                                                      \
4511       return NULL;                                                           \
4512    )                                                                         \
4513    while (tree != item) {                                                    \
4514       if (STB_(N,_compare)(item, tree) < 0) {                                \
4515          tree = tree->STB_(N,left);                                          \
4516       } else {                                                               \
4517          next = tree;                                                        \
4518          tree = tree->STB_(N,right);                                         \
4519       }                                                                      \
4520    }                                                                         \
4521    return next;                                                              \
4522 }                                                                            \
4523                                                                              \
4524 STB__DEBUG(                                                                  \
4525    void STB__(N,_validate)(TYPE *tree, int root)                             \
4526    {                                                                         \
4527       if (tree == NULL) return;                                              \
4528       PAR(if(root) assert(tree->STB_(N,parent) == NULL);)                    \
4529       assert(STB__level(N,tree->STB_(N,left) ) == tree->STB_(N,level)-1);    \
4530       assert(STB__level(N,tree->STB_(N,right)) <= tree->STB_(N,level));      \
4531       assert(STB__level(N,tree->STB_(N,right)) >= tree->STB_(N,level)-1);    \
4532       if (tree->STB_(N,right)) {                                             \
4533         assert(STB__level(N,tree->STB_(N,right)->STB_(N,right))              \
4534                                                !=    tree->STB_(N,level));   \
4535         PAR(assert(tree->STB_(N,right)->STB_(N,parent) == tree);)            \
4536       }                                                                      \
4537       PAR(if(tree->STB_(N,left)) assert(tree->STB_(N,left)->STB_(N,parent) == tree);) \
4538       STB__(N,_validate)(tree->STB_(N,left) ,0);                             \
4539       STB__(N,_validate)(tree->STB_(N,right),0);                             \
4540    }                                                                         \
4541 )                                                                            \
4542                                                                              \
4543 typedef struct                                                               \
4544 {                                                                            \
4545    TYPE *root;                                                               \
4546 } TREE;                                                                      \
4547                                                                              \
4548 void  STB__(M,Insert)(TREE *tree, TYPE *item)                                \
4549 { tree->root = STB__(N,insert)(tree->root, item); }                          \
4550 void  STB__(M,Remove)(TREE *tree, TYPE *item)                                \
4551 { tree->root = STB__(N,remove)(tree->root, item); }                          \
4552 TYPE *STB__(M,Next)(TREE *tree, TYPE *item)                                  \
4553 { return STB__(N,next)(tree->root, item); }                                  \
4554 TYPE *STB__(M,Prev)(TREE *tree, TYPE *item)                                  \
4555 { return STB__(N,prev)(tree->root, item); }                                  \
4556 TYPE *STB__(M,First)(TREE *tree) { return STB__(N,first)(tree->root); }      \
4557 TYPE *STB__(M,Last) (TREE *tree) { return STB__(N,last) (tree->root); }      \
4558 void STB__(M,Init)(TREE *tree) { tree->root = NULL; }
4559 
4560 
4561 #define stb_bst_find(N,tree,fcompare)                                        \
4562 {                                                                            \
4563    int c;                                                                    \
4564    while (tree != NULL) {                                                    \
4565       fcompare                                                               \
4566       if (c == 0) return tree;                                               \
4567       if (c < 0)  tree = tree->STB_(N,left);                                 \
4568       else        tree = tree->STB_(N,right);                                \
4569    }                                                                         \
4570    return NULL;                                                              \
4571 }
4572 
4573 #define stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,PAR)                  \
4574    stb_bst_base(TYPE,N,TREE,M,                                               \
4575          VTYPE a = p->vfield; VTYPE b = q->vfield; return (compare);, PAR )  \
4576                                                                              \
4577 TYPE *STB__(N,find)(TYPE *tree, VTYPE a)                                     \
4578    stb_bst_find(N,tree,VTYPE b = tree->vfield; c = (compare);)               \
4579 TYPE *STB__(M,Find)(TREE *tree, VTYPE a)                                     \
4580 { return STB__(N,find)(tree->root, a); }
4581 
4582 #define stb_bst(TYPE,N,TREE,M,vfield,VTYPE,compare) \
4583    stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,stb__bst_noparent)
4584 #define stb_bst_parent(TYPE,N,TREE,M,vfield,VTYPE,compare) \
4585    stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,stb__bst_parent)
4586 
4587 
4588 
4589 //////////////////////////////////////////////////////////////////////////////
4590 //
4591 //                             Pointer Nulling
4592 //
4593 //  This lets you automatically NULL dangling pointers to "registered"
4594 //  objects. Note that you have to make sure you call the appropriate
4595 //  functions when you free or realloc blocks of memory that contain
4596 //  pointers or pointer targets. stb.h can automatically do this for
4597 //  stb_arr, or for all frees/reallocs if it's wrapping them.
4598 //
4599 
4600 #ifdef STB_NPTR
4601 
4602 STB_EXTERN void stb_nptr_set(void *address_of_pointer, void *value_to_write);
4603 STB_EXTERN void stb_nptr_didset(void *address_of_pointer);
4604 
4605 STB_EXTERN void stb_nptr_didfree(void *address_being_freed, int len);
4606 STB_EXTERN void stb_nptr_free(void *address_being_freed, int len);
4607 
4608 STB_EXTERN void stb_nptr_didrealloc(void *new_address, void *old_address, int len);
4609 STB_EXTERN void stb_nptr_recache(void); // recache all known pointers
4610                                        // do this after pointer sets outside your control, slow
4611 
4612 #ifdef STB_DEFINE
4613 // for fast updating on free/realloc, we need to be able to find
4614 // all the objects (pointers and targets) within a given block;
4615 // this precludes hashing
4616 
4617 // we use a three-level hierarchy of memory to minimize storage:
4618 //   level 1: 65536 pointers to stb__memory_node (always uses 256 KB)
4619 //   level 2: each stb__memory_node represents a 64K block of memory
4620 //            with 256 stb__memory_leafs (worst case 64MB)
4621 //   level 3: each stb__memory_leaf represents 256 bytes of memory
4622 //            using a list of target locations and a list of pointers
4623 //            (which are hopefully fairly short normally!)
4624 
4625 // this approach won't work in 64-bit, which has a much larger address
4626 // space. need to redesign
4627 
4628 #define STB__NPTR_ROOT_LOG2   16
4629 #define STB__NPTR_ROOT_NUM    (1 << STB__NPTR_ROOT_LOG2)
4630 #define STB__NPTR_ROOT_SHIFT  (32 - STB__NPTR_ROOT_LOG2)
4631 
4632 #define STB__NPTR_NODE_LOG2   5
4633 #define STB__NPTR_NODE_NUM    (1 << STB__NPTR_NODE_LOG2)
4634 #define STB__NPTR_NODE_MASK   (STB__NPTR_NODE_NUM-1)
4635 #define STB__NPTR_NODE_SHIFT  (STB__NPTR_ROOT_SHIFT - STB__NPTR_NODE_LOG2)
4636 #define STB__NPTR_NODE_OFFSET(x)   (((x) >> STB__NPTR_NODE_SHIFT) & STB__NPTR_NODE_MASK)
4637 
4638 typedef struct stb__st_nptr
4639 {
4640    void *ptr;   // address of actual pointer
4641    struct stb__st_nptr *next;   // next pointer with same target
4642    struct stb__st_nptr **prev;  // prev pointer with same target, address of 'next' field (or first)
4643    struct stb__st_nptr *next_in_block;
4644 } stb__nptr;
4645 
4646 typedef struct stb__st_nptr_target
4647 {
4648    void *ptr;   // address of target
4649    stb__nptr *first; // address of first nptr pointing to this
4650    struct stb__st_nptr_target *next_in_block;
4651 } stb__nptr_target;
4652 
4653 typedef struct
4654 {
4655    stb__nptr *pointers;
4656    stb__nptr_target *targets;
4657 } stb__memory_leaf;
4658 
4659 typedef struct
4660 {
4661    stb__memory_leaf *children[STB__NPTR_NODE_NUM];
4662 } stb__memory_node;
4663 
4664 stb__memory_node *stb__memtab_root[STB__NPTR_ROOT_NUM];
4665 
stb__nptr_find_leaf(void * mem)4666 static stb__memory_leaf *stb__nptr_find_leaf(void *mem)
4667 {
4668    stb_uint32 address = (stb_uint32) mem;
4669    stb__memory_node *z = stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT];
4670    if (z)
4671       return z->children[STB__NPTR_NODE_OFFSET(address)];
4672    else
4673       return NULL;
4674 }
4675 
stb__nptr_alloc(int size)4676 static void * stb__nptr_alloc(int size)
4677 {
4678    return stb__realloc_raw(0,size);
4679 }
4680 
stb__nptr_free(void * p)4681 static void stb__nptr_free(void *p)
4682 {
4683    stb__realloc_raw(p,0);
4684 }
4685 
stb__nptr_make_leaf(void * mem)4686 static stb__memory_leaf *stb__nptr_make_leaf(void *mem)
4687 {
4688    stb_uint32 address = (stb_uint32) mem;
4689    stb__memory_node *z = stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT];
4690    stb__memory_leaf *f;
4691    if (!z) {
4692       int i;
4693       z = (stb__memory_node *) stb__nptr_alloc(sizeof(*stb__memtab_root[0]));
4694       stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT] = z;
4695       for (i=0; i < 256; ++i)
4696          z->children[i] = 0;
4697    }
4698    f = (stb__memory_leaf *) stb__nptr_alloc(sizeof(*f));
4699    z->children[STB__NPTR_NODE_OFFSET(address)] = f;
4700    f->pointers = NULL;
4701    f->targets = NULL;
4702    return f;
4703 }
4704 
stb__nptr_find_target(void * target,int force)4705 static stb__nptr_target *stb__nptr_find_target(void *target, int force)
4706 {
4707    stb__memory_leaf *p = stb__nptr_find_leaf(target);
4708    if (p) {
4709       stb__nptr_target *t = p->targets;
4710       while (t) {
4711          if (t->ptr == target)
4712             return t;
4713          t = t->next_in_block;
4714       }
4715    }
4716    if (force) {
4717       stb__nptr_target *t = (stb__nptr_target*) stb__nptr_alloc(sizeof(*t));
4718       if (!p) p = stb__nptr_make_leaf(target);
4719       t->ptr = target;
4720       t->first = NULL;
4721       t->next_in_block = p->targets;
4722       p->targets = t;
4723       return t;
4724    } else
4725       return NULL;
4726 }
4727 
stb__nptr_find_pointer(void * ptr,int force)4728 static stb__nptr *stb__nptr_find_pointer(void *ptr, int force)
4729 {
4730    stb__memory_leaf *p = stb__nptr_find_leaf(ptr);
4731    if (p) {
4732       stb__nptr *t = p->pointers;
4733       while (t) {
4734          if (t->ptr == ptr)
4735             return t;
4736          t = t->next_in_block;
4737       }
4738    }
4739    if (force) {
4740       stb__nptr *t = (stb__nptr *) stb__nptr_alloc(sizeof(*t));
4741       if (!p) p = stb__nptr_make_leaf(ptr);
4742       t->ptr = ptr;
4743       t->next = NULL;
4744       t->prev = NULL;
4745       t->next_in_block = p->pointers;
4746       p->pointers = t;
4747       return t;
4748    } else
4749       return NULL;
4750 }
4751 
stb_nptr_set(void * address_of_pointer,void * value_to_write)4752 void stb_nptr_set(void *address_of_pointer, void *value_to_write)
4753 {
4754    if (*(void **)address_of_pointer != value_to_write) {
4755       *(void **) address_of_pointer = value_to_write;
4756       stb_nptr_didset(address_of_pointer);
4757    }
4758 }
4759 
stb_nptr_didset(void * address_of_pointer)4760 void stb_nptr_didset(void *address_of_pointer)
4761 {
4762    // first unlink from old chain
4763    void *new_address;
4764    stb__nptr *p = stb__nptr_find_pointer(address_of_pointer, 1); // force building if doesn't exist
4765    if (p->prev) { // if p->prev is NULL, we just built it, or it was NULL
4766       *(p->prev) = p->next;
4767       if (p->next) p->next->prev = p->prev;
4768    }
4769    // now add to new chain
4770    new_address = *(void **)address_of_pointer;
4771    if (new_address != NULL) {
4772       stb__nptr_target *t = stb__nptr_find_target(new_address, 1);
4773       p->next = t->first;
4774       if (p->next) p->next->prev = &p->next;
4775       p->prev = &t->first;
4776       t->first = p;
4777    } else {
4778       p->prev = NULL;
4779       p->next = NULL;
4780    }
4781 }
4782 
stb__nptr_block(void * address,int len,void (* function)(stb__memory_leaf * f,int datum,void * start,void * end),int datum)4783 void stb__nptr_block(void *address, int len, void (*function)(stb__memory_leaf *f, int datum, void *start, void *end), int datum)
4784 {
4785    void *end_address = (void *) ((char *) address + len - 1);
4786    stb__memory_node *n;
4787    stb_uint32 start = (stb_uint32) address;
4788    stb_uint32 end   = start + len - 1;
4789 
4790    int b0 = start >> STB__NPTR_ROOT_SHIFT;
4791    int b1 = end >> STB__NPTR_ROOT_SHIFT;
4792    int b=b0,i,e0,e1;
4793 
4794    e0 = STB__NPTR_NODE_OFFSET(start);
4795 
4796    if (datum <= 0) {
4797       // first block
4798       n = stb__memtab_root[b0];
4799       if (n) {
4800          if (b0 != b1)
4801             e1 = STB__NPTR_NODE_NUM-1;
4802          else
4803             e1 = STB__NPTR_NODE_OFFSET(end);
4804          for (i=e0; i <= e1; ++i)
4805             if (n->children[i])
4806                function(n->children[i], datum, address, end_address);
4807       }
4808       if (b1 > b0) {
4809          // blocks other than the first and last block
4810          for (b=b0+1; b < b1; ++b) {
4811             n = stb__memtab_root[b];
4812             if (n)
4813                for (i=0; i <= STB__NPTR_NODE_NUM-1; ++i)
4814                   if (n->children[i])
4815                      function(n->children[i], datum, address, end_address);
4816          }
4817          // last block
4818          n = stb__memtab_root[b1];
4819          if (n) {
4820             e1 = STB__NPTR_NODE_OFFSET(end);
4821             for (i=0; i <= e1; ++i)
4822                if (n->children[i])
4823                   function(n->children[i], datum, address, end_address);
4824          }
4825       }
4826    } else {
4827       if (b1 > b0) {
4828          // last block
4829          n = stb__memtab_root[b1];
4830          if (n) {
4831             e1 = STB__NPTR_NODE_OFFSET(end);
4832             for (i=e1; i >= 0; --i)
4833                if (n->children[i])
4834                   function(n->children[i], datum, address, end_address);
4835          }
4836          // blocks other than the first and last block
4837          for (b=b1-1; b > b0; --b) {
4838             n = stb__memtab_root[b];
4839             if (n)
4840                for (i=STB__NPTR_NODE_NUM-1; i >= 0; --i)
4841                   if (n->children[i])
4842                      function(n->children[i], datum, address, end_address);
4843          }
4844       }
4845       // first block
4846       n = stb__memtab_root[b0];
4847       if (n) {
4848          if (b0 != b1)
4849             e1 = STB__NPTR_NODE_NUM-1;
4850          else
4851             e1 = STB__NPTR_NODE_OFFSET(end);
4852          for (i=e1; i >= e0; --i)
4853             if (n->children[i])
4854                function(n->children[i], datum, address, end_address);
4855       }
4856    }
4857 }
4858 
stb__nptr_delete_pointers(stb__memory_leaf * f,int offset,void * start,void * end)4859 static void stb__nptr_delete_pointers(stb__memory_leaf *f, int offset, void *start, void *end)
4860 {
4861    stb__nptr **p = &f->pointers;
4862    while (*p) {
4863       stb__nptr *n = *p;
4864       if (n->ptr >= start && n->ptr <= end) {
4865          // unlink
4866          if (n->prev) {
4867             *(n->prev) = n->next;
4868             if (n->next) n->next->prev = n->prev;
4869          }
4870          *p = n->next_in_block;
4871          stb__nptr_free(n);
4872       } else
4873          p = &(n->next_in_block);
4874    }
4875 }
4876 
stb__nptr_delete_targets(stb__memory_leaf * f,int offset,void * start,void * end)4877 static void stb__nptr_delete_targets(stb__memory_leaf *f, int offset, void *start, void *end)
4878 {
4879    stb__nptr_target **p = &f->targets;
4880    while (*p) {
4881       stb__nptr_target *n = *p;
4882       if (n->ptr >= start && n->ptr <= end) {
4883          // null pointers
4884          stb__nptr *z = n->first;
4885          while (z) {
4886             stb__nptr *y = z->next;
4887             z->prev = NULL;
4888             z->next = NULL;
4889             *(void **) z->ptr = NULL;
4890             z = y;
4891          }
4892          // unlink this target
4893          *p = n->next_in_block;
4894          stb__nptr_free(n);
4895       } else
4896          p = &(n->next_in_block);
4897    }
4898 }
4899 
stb_nptr_didfree(void * address_being_freed,int len)4900 void stb_nptr_didfree(void *address_being_freed, int len)
4901 {
4902    // step one: delete all pointers in this block
4903    stb__nptr_block(address_being_freed, len, stb__nptr_delete_pointers, 0);
4904    // step two: NULL all pointers to this block; do this second to avoid NULLing deleted pointers
4905    stb__nptr_block(address_being_freed, len, stb__nptr_delete_targets, 0);
4906 }
4907 
stb_nptr_free(void * address_being_freed,int len)4908 void stb_nptr_free(void *address_being_freed, int len)
4909 {
4910    free(address_being_freed);
4911    stb_nptr_didfree(address_being_freed, len);
4912 }
4913 
stb__nptr_move_targets(stb__memory_leaf * f,int offset,void * start,void * end)4914 static void stb__nptr_move_targets(stb__memory_leaf *f, int offset, void *start, void *end)
4915 {
4916    stb__nptr_target **t = &f->targets;
4917    while (*t) {
4918       stb__nptr_target *n = *t;
4919       if (n->ptr >= start && n->ptr <= end) {
4920          stb__nptr *z;
4921          stb__memory_leaf *f;
4922          // unlink n
4923          *t = n->next_in_block;
4924          // update n to new address
4925          n->ptr = (void *) ((char *) n->ptr + offset);
4926          f = stb__nptr_find_leaf(n->ptr);
4927          if (!f) f = stb__nptr_make_leaf(n->ptr);
4928          n->next_in_block = f->targets;
4929          f->targets = n;
4930          // now go through all pointers and make them point here
4931          z = n->first;
4932          while (z) {
4933             *(void**) z->ptr = n->ptr;
4934             z = z->next;
4935          }
4936       } else
4937          t = &(n->next_in_block);
4938    }
4939 }
4940 
stb__nptr_move_pointers(stb__memory_leaf * f,int offset,void * start,void * end)4941 static void stb__nptr_move_pointers(stb__memory_leaf *f, int offset, void *start, void *end)
4942 {
4943    stb__nptr **p = &f->pointers;
4944    while (*p) {
4945       stb__nptr *n = *p;
4946       if (n->ptr >= start && n->ptr <= end) {
4947          // unlink
4948          *p = n->next_in_block;
4949          n->ptr = (void *) ((int) n->ptr + offset);
4950          // move to new block
4951          f = stb__nptr_find_leaf(n->ptr);
4952          if (!f) f = stb__nptr_make_leaf(n->ptr);
4953          n->next_in_block = f->pointers;
4954          f->pointers = n;
4955       } else
4956          p = &(n->next_in_block);
4957    }
4958 }
4959 
stb_nptr_realloc(void * new_address,void * old_address,int len)4960 void stb_nptr_realloc(void *new_address, void *old_address, int len)
4961 {
4962    if (new_address == old_address) return;
4963 
4964    // have to move the pointers first, because moving the targets
4965    //      requires writing to the pointers-to-the-targets, and if some of those moved too,
4966    //      we need to make sure we don't write to the old memory
4967 
4968    // step one: move all pointers within the block
4969    stb__nptr_block(old_address, len, stb__nptr_move_pointers, (char *) new_address - (char *) old_address);
4970    // step two: move all targets within the block
4971    stb__nptr_block(old_address, len, stb__nptr_move_targets, (char *) new_address - (char *) old_address);
4972 }
4973 
stb_nptr_move(void * new_address,void * old_address)4974 void stb_nptr_move(void *new_address, void *old_address)
4975 {
4976    stb_nptr_realloc(new_address, old_address, 1);
4977 }
4978 
stb_nptr_recache(void)4979 void stb_nptr_recache(void)
4980 {
4981    int i,j;
4982    for (i=0; i < STB__NPTR_ROOT_NUM; ++i)
4983       if (stb__memtab_root[i])
4984          for (j=0; j < STB__NPTR_NODE_NUM; ++j)
4985             if (stb__memtab_root[i]->children[j]) {
4986                stb__nptr *p = stb__memtab_root[i]->children[j]->pointers;
4987                while (p) {
4988                   stb_nptr_didset(p->ptr);
4989                   p = p->next_in_block;
4990                }
4991             }
4992 }
4993 
4994 #endif // STB_DEFINE
4995 #endif // STB_NPTR
4996 
4997 
4998 //////////////////////////////////////////////////////////////////////////////
4999 //
5000 //                             File Processing
5001 //
5002 
5003 
5004 #ifdef _MSC_VER
5005   #define stb_rename(x,y)   _wrename((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y))
5006   #define stb_mktemp   _mktemp
5007 #else
5008   #define stb_mktemp   mktemp
5009   #define stb_rename   rename
5010 #endif
5011 
5012 STB_EXTERN void     stb_fput_varlen64(FILE *f, stb_uint64 v);
5013 STB_EXTERN stb_uint64  stb_fget_varlen64(FILE *f);
5014 STB_EXTERN int      stb_size_varlen64(stb_uint64 v);
5015 
5016 
5017 #define stb_filec    (char *) stb_file
5018 #define stb_fileu    (unsigned char *) stb_file
5019 STB_EXTERN void *  stb_file(char *filename, size_t *length);
5020 STB_EXTERN void *  stb_file_max(char *filename, size_t *length);
5021 STB_EXTERN size_t  stb_filelen(FILE *f);
5022 STB_EXTERN int     stb_filewrite(char *filename, void *data, size_t length);
5023 STB_EXTERN int     stb_filewritestr(char *filename, char *data);
5024 STB_EXTERN char ** stb_stringfile(char *filename, int *len);
5025 STB_EXTERN char ** stb_stringfile_trimmed(char *name, int *len, char comm);
5026 STB_EXTERN char *  stb_fgets(char *buffer, int buflen, FILE *f);
5027 STB_EXTERN char *  stb_fgets_malloc(FILE *f);
5028 STB_EXTERN int     stb_fexists(char *filename);
5029 STB_EXTERN int     stb_fcmp(char *s1, char *s2);
5030 STB_EXTERN int     stb_feq(char *s1, char *s2);
5031 STB_EXTERN time_t  stb_ftimestamp(char *filename);
5032 
5033 STB_EXTERN int     stb_fullpath(char *abs, int abs_size, char *rel);
5034 STB_EXTERN FILE *  stb_fopen(char *filename, char *mode);
5035 STB_EXTERN int     stb_fclose(FILE *f, int keep);
5036 
5037 enum
5038 {
5039    stb_keep_no = 0,
5040    stb_keep_yes = 1,
5041    stb_keep_if_different = 2,
5042 };
5043 
5044 STB_EXTERN int     stb_copyfile(char *src, char *dest);
5045 
5046 STB_EXTERN void     stb_fput_varlen64(FILE *f, stb_uint64 v);
5047 STB_EXTERN stb_uint64  stb_fget_varlen64(FILE *f);
5048 STB_EXTERN int      stb_size_varlen64(stb_uint64 v);
5049 
5050 STB_EXTERN void    stb_fwrite32(FILE *f, stb_uint32 datum);
5051 STB_EXTERN void    stb_fput_varlen (FILE *f, int v);
5052 STB_EXTERN void    stb_fput_varlenu(FILE *f, unsigned int v);
5053 STB_EXTERN int     stb_fget_varlen (FILE *f);
5054 STB_EXTERN stb_uint stb_fget_varlenu(FILE *f);
5055 STB_EXTERN void    stb_fput_ranged (FILE *f, int v, int b, stb_uint n);
5056 STB_EXTERN int     stb_fget_ranged (FILE *f, int b, stb_uint n);
5057 STB_EXTERN int     stb_size_varlen (int v);
5058 STB_EXTERN int     stb_size_varlenu(unsigned int v);
5059 STB_EXTERN int     stb_size_ranged (int b, stb_uint n);
5060 
5061 STB_EXTERN int     stb_fread(void *data, size_t len, size_t count, void *f);
5062 STB_EXTERN int     stb_fwrite(void *data, size_t len, size_t count, void *f);
5063 
5064 #if 0
5065 typedef struct
5066 {
5067    FILE  *base_file;
5068    char  *buffer;
5069    int    buffer_size;
5070    int    buffer_off;
5071    int    buffer_left;
5072 } STBF;
5073 
5074 STB_EXTERN STBF *stb_tfopen(char *filename, char *mode);
5075 STB_EXTERN int stb_tfread(void *data, size_t len, size_t count, STBF *f);
5076 STB_EXTERN int stb_tfwrite(void *data, size_t len, size_t count, STBF *f);
5077 #endif
5078 
5079 #ifdef STB_DEFINE
5080 
5081 #if 0
stb_tfopen(char * filename,char * mode)5082 STBF *stb_tfopen(char *filename, char *mode)
5083 {
5084    STBF *z;
5085    FILE *f = fopen(filename, mode);
5086    if (!f) return NULL;
5087    z = (STBF *) malloc(sizeof(*z));
5088    if (!z) { fclose(f); return NULL; }
5089    z->base_file = f;
5090    if (!strcmp(mode, "rb") || !strcmp(mode, "wb")) {
5091       z->buffer_size = 4096;
5092       z->buffer_off = z->buffer_size;
5093       z->buffer_left = 0;
5094       z->buffer = malloc(z->buffer_size);
5095       if (!z->buffer) { free(z); fclose(f); return NULL; }
5096    } else {
5097       z->buffer = 0;
5098       z->buffer_size = 0;
5099       z->buffer_left = 0;
5100    }
5101    return z;
5102 }
5103 
stb_tfread(void * data,size_t len,size_t count,STBF * f)5104 int stb_tfread(void *data, size_t len, size_t count, STBF *f)
5105 {
5106    int total = len*count, done=0;
5107    if (!total) return 0;
5108    if (total <= z->buffer_left) {
5109       memcpy(data, z->buffer + z->buffer_off, total);
5110       z->buffer_off += total;
5111       z->buffer_left -= total;
5112       return count;
5113    } else {
5114       char *out = (char *) data;
5115 
5116       // consume all buffered data
5117       memcpy(data, z->buffer + z->buffer_off, z->buffer_left);
5118       done = z->buffer_left;
5119       out += z->buffer_left;
5120       z->buffer_left=0;
5121 
5122       if (total-done > (z->buffer_size >> 1)) {
5123          done += fread(out
5124       }
5125    }
5126 }
5127 #endif
5128 
5129 void stb_fwrite32(FILE *f, stb_uint32 x)
5130 {
5131    fwrite(&x, 4, 1, f);
5132 }
5133 
5134 #if defined(_MSC_VER) || defined(__MINGW32__)
5135    #define stb__stat   _stat
5136 #else
5137    #define stb__stat   stat
5138 #endif
5139 
5140 int stb_fexists(char *filename)
5141 {
5142    struct stb__stat buf;
5143    return stb__windows(
5144              _wstat((const wchar_t *)stb__from_utf8(filename), &buf),
5145                stat(filename,&buf)
5146           ) == 0;
5147 }
5148 
5149 time_t stb_ftimestamp(char *filename)
5150 {
5151    struct stb__stat buf;
5152    if (stb__windows(
5153              _wstat((const wchar_t *)stb__from_utf8(filename), &buf),
5154                stat(filename,&buf)
5155           ) == 0)
5156    {
5157       return buf.st_mtime;
5158    } else {
5159       return 0;
5160    }
5161 }
5162 
5163 size_t  stb_filelen(FILE *f)
5164 {
5165    size_t len, pos;
5166    pos = ftell(f);
5167    fseek(f, 0, SEEK_END);
5168    len = ftell(f);
5169    fseek(f, pos, SEEK_SET);
5170    return len;
5171 }
5172 
5173 void *stb_file(char *filename, size_t *length)
5174 {
5175    FILE *f = stb__fopen(filename, "rb");
5176    char *buffer;
5177    size_t len, len2;
5178    if (!f) return NULL;
5179    len = stb_filelen(f);
5180    buffer = (char *) malloc(len+2); // nul + extra
5181    len2 = fread(buffer, 1, len, f);
5182    if (len2 == len) {
5183       if (length) *length = len;
5184       buffer[len] = 0;
5185    } else {
5186       free(buffer);
5187       buffer = NULL;
5188    }
5189    fclose(f);
5190    return buffer;
5191 }
5192 
5193 int stb_filewrite(char *filename, void *data, size_t length)
5194 {
5195    FILE *f = stb_fopen(filename, "wb");
5196    if (f) {
5197       unsigned char *data_ptr = (unsigned char *) data;
5198       size_t remaining = length;
5199       while (remaining > 0) {
5200          size_t len2 = remaining > 65536 ? 65536 : remaining;
5201          size_t len3 = fwrite(data_ptr, 1, len2, f);
5202          if (len2 != len3) {
5203             fprintf(stderr, "Failed while writing %s\n", filename);
5204             break;
5205          }
5206          remaining -= len2;
5207          data_ptr += len2;
5208       }
5209       stb_fclose(f, stb_keep_if_different);
5210    }
5211    return f != NULL;
5212 }
5213 
5214 int stb_filewritestr(char *filename, char *data)
5215 {
5216    return stb_filewrite(filename, data, strlen(data));
5217 }
5218 
5219 void *  stb_file_max(char *filename, size_t *length)
5220 {
5221    FILE *f = stb__fopen(filename, "rb");
5222    char *buffer;
5223    size_t len, maxlen;
5224    if (!f) return NULL;
5225    maxlen = *length;
5226    buffer = (char *) malloc(maxlen+1);
5227    len = fread(buffer, 1, maxlen, f);
5228    buffer[len] = 0;
5229    fclose(f);
5230    *length = len;
5231    return buffer;
5232 }
5233 
5234 char ** stb_stringfile(char *filename, int *plen)
5235 {
5236    FILE *f = stb__fopen(filename, "rb");
5237    char *buffer, **list=NULL, *s;
5238    size_t len, count, i;
5239 
5240    if (!f) return NULL;
5241    len = stb_filelen(f);
5242    buffer = (char *) malloc(len+1);
5243    len = fread(buffer, 1, len, f);
5244    buffer[len] = 0;
5245    fclose(f);
5246 
5247    // two passes through: first time count lines, second time set them
5248    for (i=0; i < 2; ++i) {
5249       s = buffer;
5250       if (i == 1)
5251          list[0] = s;
5252       count = 1;
5253       while (*s) {
5254          if (*s == '\n' || *s == '\r') {
5255             // detect if both cr & lf are together
5256             int crlf = (s[0] + s[1]) == ('\n' + '\r');
5257             if (i == 1) *s = 0;
5258             if (crlf) ++s;
5259             if (s[1]) {  // it's not over yet
5260                if (i == 1) list[count] = s+1;
5261                ++count;
5262             }
5263          }
5264          ++s;
5265       }
5266       if (i == 0) {
5267          list = (char **) malloc(sizeof(*list) * (count+1) + len+1);
5268          if (!list) return NULL;
5269          list[count] = 0;
5270          // recopy the file so there's just a single allocation to free
5271          memcpy(&list[count+1], buffer, len+1);
5272          free(buffer);
5273          buffer = (char *) &list[count+1];
5274          if (plen) *plen = count;
5275       }
5276    }
5277    return list;
5278 }
5279 
5280 char ** stb_stringfile_trimmed(char *name, int *len, char comment)
5281 {
5282    int i,n,o=0;
5283    char **s = stb_stringfile(name, &n);
5284    if (s == NULL) return NULL;
5285    for (i=0; i < n; ++i) {
5286       char *p = stb_skipwhite(s[i]);
5287       if (*p && *p != comment)
5288          s[o++] = p;
5289    }
5290    s[o] = NULL;
5291    if (len) *len = o;
5292    return s;
5293 }
5294 
5295 char * stb_fgets(char *buffer, int buflen, FILE *f)
5296 {
5297    char *p;
5298    buffer[0] = 0;
5299    p = fgets(buffer, buflen, f);
5300    if (p) {
5301       int n = strlen(p)-1;
5302       if (n >= 0)
5303          if (p[n] == '\n')
5304             p[n] = 0;
5305    }
5306    return p;
5307 }
5308 
5309 char * stb_fgets_malloc(FILE *f)
5310 {
5311    // avoid reallocing for small strings
5312    char quick_buffer[800];
5313    quick_buffer[sizeof(quick_buffer)-2] = 0;
5314    if (!fgets(quick_buffer, sizeof(quick_buffer), f))
5315       return NULL;
5316 
5317    if (quick_buffer[sizeof(quick_buffer)-2] == 0) {
5318       int n = strlen(quick_buffer);
5319       if (n > 0 && quick_buffer[n-1] == '\n')
5320          quick_buffer[n-1] = 0;
5321       return strdup(quick_buffer);
5322    } else {
5323       char *p;
5324       char *a = strdup(quick_buffer);
5325       int len = sizeof(quick_buffer)-1;
5326 
5327       while (!feof(f)) {
5328          if (a[len-1] == '\n') break;
5329          a = (char *) realloc(a, len*2);
5330          p = &a[len];
5331          p[len-2] = 0;
5332          if (!fgets(p, len, f))
5333             break;
5334          if (p[len-2] == 0) {
5335             len += strlen(p);
5336             break;
5337          }
5338          len = len + (len-1);
5339       }
5340       if (a[len-1] == '\n')
5341          a[len-1] = 0;
5342       return a;
5343    }
5344 }
5345 
5346 int stb_fullpath(char *abs, int abs_size, char *rel)
5347 {
5348    #ifdef _MSC_VER
5349    return _fullpath(abs, rel, abs_size) != NULL;
5350    #else
5351    if (rel[0] == '/' || rel[0] == '~') {
5352       if ((int) strlen(rel) >= abs_size)
5353          return 0;
5354       strcpy(abs,rel);
5355       return STB_TRUE;
5356    } else {
5357       int n;
5358       getcwd(abs, abs_size);
5359       n = strlen(abs);
5360       if (n+(int) strlen(rel)+2 <= abs_size) {
5361          abs[n] = '/';
5362          strcpy(abs+n+1, rel);
5363          return STB_TRUE;
5364       } else {
5365          return STB_FALSE;
5366       }
5367    }
5368    #endif
5369 }
5370 
5371 static int stb_fcmp_core(FILE *f, FILE *g)
5372 {
5373    char buf1[1024],buf2[1024];
5374    int n1,n2, res=0;
5375 
5376    while (1) {
5377       n1 = fread(buf1, 1, sizeof(buf1), f);
5378       n2 = fread(buf2, 1, sizeof(buf2), g);
5379       res = memcmp(buf1,buf2,stb_min(n1,n2));
5380       if (res)
5381          break;
5382       if (n1 != n2) {
5383          res = n1 < n2 ? -1 : 1;
5384          break;
5385       }
5386       if (n1 == 0)
5387          break;
5388    }
5389 
5390    fclose(f);
5391    fclose(g);
5392    return res;
5393 }
5394 
5395 int stb_fcmp(char *s1, char *s2)
5396 {
5397    FILE *f = stb__fopen(s1, "rb");
5398    FILE *g = stb__fopen(s2, "rb");
5399 
5400    if (f == NULL || g == NULL) {
5401       if (f) fclose(f);
5402       if (g) {
5403          fclose(g);
5404          return STB_TRUE;
5405       }
5406       return f != NULL;
5407    }
5408 
5409    return stb_fcmp_core(f,g);
5410 }
5411 
5412 int stb_feq(char *s1, char *s2)
5413 {
5414    FILE *f = stb__fopen(s1, "rb");
5415    FILE *g = stb__fopen(s2, "rb");
5416 
5417    if (f == NULL || g == NULL) {
5418       if (f) fclose(f);
5419       if (g) fclose(g);
5420       return f == g;
5421    }
5422 
5423    // feq is faster because it shortcuts if they're different length
5424    if (stb_filelen(f) != stb_filelen(g)) {
5425       fclose(f);
5426       fclose(g);
5427       return 0;
5428    }
5429 
5430    return !stb_fcmp_core(f,g);
5431 }
5432 
5433 static stb_ptrmap *stb__files;
5434 
5435 typedef struct
5436 {
5437    char *temp_name;
5438    char *name;
5439    int   errors;
5440 } stb__file_data;
5441 
5442 FILE *  stb_fopen(char *filename, char *mode)
5443 {
5444    FILE *f;
5445    char name_full[4096];
5446    char temp_full[sizeof(name_full) + 12];
5447    int p;
5448 #ifdef _MSC_VER
5449    int j;
5450 #endif
5451    if (mode[0] != 'w' && !strchr(mode, '+'))
5452       return stb__fopen(filename, mode);
5453 
5454    // save away the full path to the file so if the program
5455    // changes the cwd everything still works right! unix has
5456    // better ways to do this, but we have to work in windows
5457    name_full[0] = '\0'; // stb_fullpath reads name_full[0]
5458    if (stb_fullpath(name_full, sizeof(name_full), filename)==0)
5459       return 0;
5460 
5461    // try to generate a temporary file in the same directory
5462    p = strlen(name_full)-1;
5463    while (p > 0 && name_full[p] != '/' && name_full[p] != '\\'
5464                 && name_full[p] != ':' && name_full[p] != '~')
5465       --p;
5466    ++p;
5467 
5468    memcpy(temp_full, name_full, p);
5469 
5470    #ifdef _MSC_VER
5471    // try multiple times to make a temp file... just in
5472    // case some other process makes the name first
5473    for (j=0; j < 32; ++j) {
5474       strcpy(temp_full+p, "stmpXXXXXX");
5475       if (stb_mktemp(temp_full) == NULL)
5476          return 0;
5477 
5478       f = fopen(temp_full, mode);
5479       if (f != NULL)
5480          break;
5481    }
5482    #else
5483    {
5484       strcpy(temp_full+p, "stmpXXXXXX");
5485       #ifdef __MINGW32__
5486          int fd = open(mktemp(temp_full), O_RDWR);
5487       #else
5488          int fd = mkstemp(temp_full);
5489       #endif
5490       if (fd == -1) return NULL;
5491       f = fdopen(fd, mode);
5492       if (f == NULL) {
5493          unlink(temp_full);
5494          close(fd);
5495          return NULL;
5496       }
5497    }
5498    #endif
5499    if (f != NULL) {
5500       stb__file_data *d = (stb__file_data *) malloc(sizeof(*d));
5501       if (!d) { assert(0);  /* NOTREACHED */fclose(f); return NULL; }
5502       if (stb__files == NULL) stb__files = stb_ptrmap_create();
5503       d->temp_name = strdup(temp_full);
5504       d->name      = strdup(name_full);
5505       d->errors    = 0;
5506       stb_ptrmap_add(stb__files, f, d);
5507       return f;
5508    }
5509 
5510    return NULL;
5511 }
5512 
5513 int     stb_fclose(FILE *f, int keep)
5514 {
5515    stb__file_data *d;
5516 
5517    int ok = STB_FALSE;
5518    if (f == NULL) return 0;
5519 
5520    if (ferror(f))
5521       keep = stb_keep_no;
5522 
5523    fclose(f);
5524 
5525    if (stb__files && stb_ptrmap_remove(stb__files, f, (void **) &d)) {
5526       if (stb__files->count == 0) {
5527          stb_ptrmap_destroy(stb__files);
5528          stb__files = NULL;
5529       }
5530    } else
5531       return STB_TRUE; // not special
5532 
5533    if (keep == stb_keep_if_different) {
5534       // check if the files are identical
5535       if (stb_feq(d->name, d->temp_name)) {
5536          keep = stb_keep_no;
5537          ok = STB_TRUE;  // report success if no change
5538       }
5539    }
5540 
5541    if (keep != stb_keep_no) {
5542       if (stb_fexists(d->name) && remove(d->name)) {
5543          // failed to delete old, so don't keep new
5544          keep = stb_keep_no;
5545       } else {
5546          if (!stb_rename(d->temp_name, d->name))
5547             ok = STB_TRUE;
5548          else
5549             keep=stb_keep_no;
5550       }
5551    }
5552 
5553    if (keep == stb_keep_no)
5554       remove(d->temp_name);
5555 
5556    free(d->temp_name);
5557    free(d->name);
5558    free(d);
5559 
5560    return ok;
5561 }
5562 
5563 int stb_copyfile(char *src, char *dest)
5564 {
5565    char raw_buffer[1024];
5566    char *buffer;
5567    int buf_size = 65536;
5568 
5569    FILE *f, *g;
5570 
5571    // if file already exists at destination, do nothing
5572    if (stb_feq(src, dest)) return STB_TRUE;
5573 
5574    // open file
5575    f = stb__fopen(src, "rb");
5576    if (f == NULL) return STB_FALSE;
5577 
5578    // open file for writing
5579    g = stb__fopen(dest, "wb");
5580    if (g == NULL) {
5581       fclose(f);
5582       return STB_FALSE;
5583    }
5584 
5585    buffer = (char *) malloc(buf_size);
5586    if (buffer == NULL) {
5587       buffer = raw_buffer;
5588       buf_size = sizeof(raw_buffer);
5589    }
5590 
5591    while (!feof(f)) {
5592       int n = fread(buffer, 1, buf_size, f);
5593       if (n != 0)
5594          fwrite(buffer, 1, n, g);
5595    }
5596 
5597    fclose(f);
5598    if (buffer != raw_buffer)
5599       free(buffer);
5600 
5601    fclose(g);
5602    return STB_TRUE;
5603 }
5604 
5605 // varlen:
5606 //    v' = (v >> 31) + (v < 0 ? ~v : v)<<1;  // small abs(v) => small v'
5607 // output v as big endian v'+k for v' <= k:
5608 //   1 byte :  v' <= 0x00000080          (  -64 <= v <   64)   7 bits
5609 //   2 bytes:  v' <= 0x00004000          (-8192 <= v < 8192)  14 bits
5610 //   3 bytes:  v' <= 0x00200000                               21 bits
5611 //   4 bytes:  v' <= 0x10000000                               28 bits
5612 // the number of most significant 1-bits in the first byte
5613 // equals the number of bytes after the first
5614 
5615 #define stb__varlen_xform(v)     (v<0 ? (~v << 1)+1 : (v << 1))
5616 
5617 int stb_size_varlen(int v) { return stb_size_varlenu(stb__varlen_xform(v)); }
5618 int stb_size_varlenu(unsigned int v)
5619 {
5620    if (v < 0x00000080) return 1;
5621    if (v < 0x00004000) return 2;
5622    if (v < 0x00200000) return 3;
5623    if (v < 0x10000000) return 4;
5624    return 5;
5625 }
5626 
5627 void    stb_fput_varlen(FILE *f, int v) { stb_fput_varlenu(f, stb__varlen_xform(v)); }
5628 
5629 void    stb_fput_varlenu(FILE *f, unsigned int z)
5630 {
5631    if (z >= 0x10000000) fputc(0xF0,f);
5632    if (z >= 0x00200000) fputc((z < 0x10000000 ? 0xE0 : 0)+(z>>24),f);
5633    if (z >= 0x00004000) fputc((z < 0x00200000 ? 0xC0 : 0)+(z>>16),f);
5634    if (z >= 0x00000080) fputc((z < 0x00004000 ? 0x80 : 0)+(z>> 8),f);
5635    fputc(z,f);
5636 }
5637 
5638 #define stb_fgetc(f)    ((unsigned char) fgetc(f))
5639 
5640 int     stb_fget_varlen(FILE *f)
5641 {
5642    unsigned int z = stb_fget_varlenu(f);
5643    return (z & 1) ? ~(z>>1) : (z>>1);
5644 }
5645 
5646 unsigned int stb_fget_varlenu(FILE *f)
5647 {
5648    unsigned int z;
5649    unsigned char d;
5650    d = stb_fgetc(f);
5651 
5652    if (d >= 0x80) {
5653       if (d >= 0xc0) {
5654          if (d >= 0xe0) {
5655             if (d == 0xf0) z = stb_fgetc(f) << 24;
5656             else           z = (d - 0xe0) << 24;
5657             z += stb_fgetc(f) << 16;
5658          }
5659          else
5660             z = (d - 0xc0) << 16;
5661          z += stb_fgetc(f) << 8;
5662       } else
5663          z = (d - 0x80) <<  8;
5664       z += stb_fgetc(f);
5665    } else
5666       z = d;
5667    return z;
5668 }
5669 
5670 stb_uint64   stb_fget_varlen64(FILE *f)
5671 {
5672    stb_uint64 z;
5673    unsigned char d;
5674    d = stb_fgetc(f);
5675 
5676    if (d >= 0x80) {
5677       if (d >= 0xc0) {
5678          if (d >= 0xe0) {
5679             if (d >= 0xf0) {
5680                if (d >= 0xf8) {
5681                   if (d >= 0xfc) {
5682                      if (d >= 0xfe) {
5683                         if (d >= 0xff)
5684                            z = (stb_uint64) stb_fgetc(f) << 56;
5685                         else
5686                            z = (stb_uint64) (d - 0xfe) << 56;
5687                         z |= (stb_uint64) stb_fgetc(f) << 48;
5688                      } else z = (stb_uint64) (d - 0xfc) << 48;
5689                      z |= (stb_uint64) stb_fgetc(f) << 40;
5690                   } else z = (stb_uint64) (d - 0xf8) << 40;
5691                   z |= (stb_uint64) stb_fgetc(f) << 32;
5692                } else z = (stb_uint64) (d - 0xf0) << 32;
5693                z |= (stb_uint) stb_fgetc(f) << 24;
5694             } else z = (stb_uint) (d - 0xe0) << 24;
5695             z |= (stb_uint) stb_fgetc(f) << 16;
5696          } else z = (stb_uint) (d - 0xc0) << 16;
5697          z |= (stb_uint) stb_fgetc(f) << 8;
5698       } else z = (stb_uint) (d - 0x80) << 8;
5699       z |= stb_fgetc(f);
5700    } else
5701       z = d;
5702 
5703    return (z & 1) ? ~(z >> 1) : (z >> 1);
5704 }
5705 
5706 int stb_size_varlen64(stb_uint64 v)
5707 {
5708    if (v < 0x00000080) return 1;
5709    if (v < 0x00004000) return 2;
5710    if (v < 0x00200000) return 3;
5711    if (v < 0x10000000) return 4;
5712    if (v < STB_IMM_UINT64(0x0000000800000000)) return 5;
5713    if (v < STB_IMM_UINT64(0x0000040000000000)) return 6;
5714    if (v < STB_IMM_UINT64(0x0002000000000000)) return 7;
5715    if (v < STB_IMM_UINT64(0x0100000000000000)) return 8;
5716    return 9;
5717 }
5718 
5719 void    stb_fput_varlen64(FILE *f, stb_uint64 v)
5720 {
5721    stb_uint64 z = stb__varlen_xform(v);
5722    int first=1;
5723    if (z >= STB_IMM_UINT64(0x100000000000000)) {
5724       fputc(0xff,f);
5725       first=0;
5726    }
5727    if (z >= STB_IMM_UINT64(0x02000000000000)) fputc((first ? 0xFE : 0)+(char)(z>>56),f), first=0;
5728    if (z >= STB_IMM_UINT64(0x00040000000000)) fputc((first ? 0xFC : 0)+(char)(z>>48),f), first=0;
5729    if (z >= STB_IMM_UINT64(0x00000800000000)) fputc((first ? 0xF8 : 0)+(char)(z>>40),f), first=0;
5730    if (z >= STB_IMM_UINT64(0x00000010000000)) fputc((first ? 0xF0 : 0)+(char)(z>>32),f), first=0;
5731    if (z >= STB_IMM_UINT64(0x00000000200000)) fputc((first ? 0xE0 : 0)+(char)(z>>24),f), first=0;
5732    if (z >= STB_IMM_UINT64(0x00000000004000)) fputc((first ? 0xC0 : 0)+(char)(z>>16),f), first=0;
5733    if (z >= STB_IMM_UINT64(0x00000000000080)) fputc((first ? 0x80 : 0)+(char)(z>> 8),f), first=0;
5734    fputc((char)z,f);
5735 }
5736 
5737 void    stb_fput_ranged(FILE *f, int v, int b, stb_uint n)
5738 {
5739    v -= b;
5740    if (n <= (1 << 31))
5741       assert((stb_uint) v < n);
5742    if (n > (1 << 24)) fputc(v >> 24, f);
5743    if (n > (1 << 16)) fputc(v >> 16, f);
5744    if (n > (1 <<  8)) fputc(v >>  8, f);
5745    fputc(v,f);
5746 }
5747 
5748 int     stb_fget_ranged(FILE *f, int b, stb_uint n)
5749 {
5750    unsigned int v=0;
5751    if (n > (1 << 24)) v += stb_fgetc(f) << 24;
5752    if (n > (1 << 16)) v += stb_fgetc(f) << 16;
5753    if (n > (1 <<  8)) v += stb_fgetc(f) <<  8;
5754    v += stb_fgetc(f);
5755    return b+v;
5756 }
5757 
5758 int     stb_size_ranged(int b, stb_uint n)
5759 {
5760    if (n > (1 << 24)) return 4;
5761    if (n > (1 << 16)) return 3;
5762    if (n > (1 <<  8)) return 2;
5763    return 1;
5764 }
5765 
5766 void stb_fput_string(FILE *f, char *s)
5767 {
5768    int len = strlen(s);
5769    stb_fput_varlenu(f, len);
5770    fwrite(s, 1, len, f);
5771 }
5772 
5773 // inverse of the above algorithm
5774 char *stb_fget_string(FILE *f, void *p)
5775 {
5776    char *s;
5777    int len = stb_fget_varlenu(f);
5778    if (len > 4096) return NULL;
5779    s = p ? stb_malloc_string(p, len+1) : (char *) malloc(len+1);
5780    fread(s, 1, len, f);
5781    s[len] = 0;
5782    return s;
5783 }
5784 
5785 char *stb_strdup(char *str, void *pool)
5786 {
5787    int len = strlen(str);
5788    char *p = stb_malloc_string(pool, len+1);
5789    strcpy(p, str);
5790    return p;
5791 }
5792 
5793 // strip the trailing '/' or '\\' from a directory so we can refer to it
5794 // as a file for _stat()
5795 char *stb_strip_final_slash(char *t)
5796 {
5797    if (t[0]) {
5798       char *z = t + strlen(t) - 1;
5799       // *z is the last character
5800       if (*z == '\\' || *z == '/')
5801          if (z != t+2 || t[1] != ':') // but don't strip it if it's e.g. "c:/"
5802             *z = 0;
5803       if (*z == '\\')
5804          *z = '/'; // canonicalize to make sure it matches db
5805    }
5806    return t;
5807 }
5808 
5809 char *stb_strip_final_slash_regardless(char *t)
5810 {
5811    if (t[0]) {
5812       char *z = t + strlen(t) - 1;
5813       // *z is the last character
5814       if (*z == '\\' || *z == '/')
5815          *z = 0;
5816       if (*z == '\\')
5817          *z = '/'; // canonicalize to make sure it matches db
5818    }
5819    return t;
5820 }
5821 #endif
5822 
5823 //////////////////////////////////////////////////////////////////////////////
5824 //
5825 //                 Options parsing
5826 //
5827 
5828 STB_EXTERN char **stb_getopt_param(int *argc, char **argv, char *param);
5829 STB_EXTERN char **stb_getopt(int *argc, char **argv);
5830 STB_EXTERN void   stb_getopt_free(char **opts);
5831 
5832 #ifdef STB_DEFINE
5833 
5834 void   stb_getopt_free(char **opts)
5835 {
5836    int i;
5837    char ** o2 = opts;
5838    for (i=0; i < stb_arr_len(o2); ++i)
5839       free(o2[i]);
5840    stb_arr_free(o2);
5841 }
5842 
5843 char **stb_getopt(int *argc, char **argv)
5844 {
5845    return stb_getopt_param(argc, argv, "");
5846 }
5847 
5848 char **stb_getopt_param(int *argc, char **argv, char *param)
5849 {
5850    char ** opts=NULL;
5851    int i,j=1;
5852    for (i=1; i < *argc; ++i) {
5853       if (argv[i][0] != '-') {
5854          argv[j++] = argv[i];
5855       } else {
5856          if (argv[i][1] == 0) { // plain - == don't parse further options
5857             ++i;
5858             while (i < *argc)
5859                argv[j++] = argv[i++];
5860             break;
5861          } else {
5862             int k;
5863             char *q = argv[i];  // traverse options list
5864             for (k=1; q[k]; ++k) {
5865                char *s;
5866                if (strchr(param, q[k])) {  // does it take a parameter?
5867                   char *t = &q[k+1], z = q[k];
5868                   int len=0;
5869                   if (*t == 0) {
5870                      if (i == *argc-1) { // takes a parameter, but none found
5871                         *argc = 0;
5872                         stb_getopt_free(opts);
5873                         return NULL;
5874                      }
5875                      t = argv[++i];
5876                   } else
5877                      k += strlen(t);
5878                   len = strlen(t);
5879                   s = (char *) malloc(len+2);
5880                   if (!s) return NULL;
5881                   s[0] = z;
5882                   strcpy(s+1, t);
5883                } else {
5884                   // no parameter
5885                   s = (char *) malloc(2);
5886                   if (!s) return NULL;
5887                   s[0] = q[k];
5888                   s[1] = 0;
5889                }
5890                stb_arr_push(opts, s);
5891             }
5892          }
5893       }
5894    }
5895    stb_arr_push(opts, NULL);
5896    *argc = j;
5897    return opts;
5898 }
5899 #endif
5900 
5901 
5902 //////////////////////////////////////////////////////////////////////////////
5903 //
5904 //                 Portable directory reading
5905 //
5906 
5907 STB_EXTERN char **stb_readdir_files  (char *dir);
5908 STB_EXTERN char **stb_readdir_files_mask(char *dir, char *wild);
5909 STB_EXTERN char **stb_readdir_subdirs(char *dir);
5910 STB_EXTERN char **stb_readdir_subdirs_mask(char *dir, char *wild);
5911 STB_EXTERN void   stb_readdir_free   (char **files);
5912 STB_EXTERN char **stb_readdir_recursive(char *dir, char *filespec);
5913 STB_EXTERN void stb_delete_directory_recursive(char *dir);
5914 
5915 #ifdef STB_DEFINE
5916 
5917 #ifdef _MSC_VER
5918 #include <io.h>
5919 #else
5920 #include <unistd.h>
5921 #include <dirent.h>
5922 #endif
5923 
5924 void stb_readdir_free(char **files)
5925 {
5926    char **f2 = files;
5927    int i;
5928    for (i=0; i < stb_arr_len(f2); ++i)
5929       free(f2[i]);
5930    stb_arr_free(f2);
5931 }
5932 
5933 static int isdotdirname(char *name)
5934 {
5935    if (name[0] == '.')
5936       return (name[1] == '.') ? !name[2] : !name[1];
5937    return 0;
5938 }
5939 
5940 STB_EXTERN int stb_wildmatchi(char *expr, char *candidate);
5941 static char **readdir_raw(char *dir, int return_subdirs, char *mask)
5942 {
5943    char **results = NULL;
5944    char buffer[4096], with_slash[4096];
5945    size_t n;
5946 
5947    #ifdef _MSC_VER
5948       stb__wchar *ws;
5949       struct _wfinddata_t data;
5950    #ifdef _WIN64
5951       const intptr_t none = -1;
5952       intptr_t z;
5953    #else
5954       const long none = -1;
5955       long z;
5956    #endif
5957    #else // !_MSC_VER
5958       const DIR *none = NULL;
5959       DIR *z;
5960    #endif
5961 
5962    n = stb_strscpy(buffer,dir,sizeof(buffer));
5963    if (!n || n >= sizeof(buffer))
5964       return NULL;
5965    stb_fixpath(buffer);
5966    n--;
5967 
5968    if (n > 0 && (buffer[n-1] != '/')) {
5969       buffer[n++] = '/';
5970    }
5971    buffer[n] = 0;
5972    if (!stb_strscpy(with_slash,buffer,sizeof(with_slash)))
5973       return NULL;
5974 
5975    #ifdef _MSC_VER
5976       if (!stb_strscpy(buffer+n,"*.*",sizeof(buffer)-n))
5977          return NULL;
5978       ws = stb__from_utf8(buffer);
5979       z = _wfindfirst((const wchar_t *)ws, &data);
5980    #else
5981       z = opendir(dir);
5982    #endif
5983 
5984    if (z != none) {
5985       int nonempty = STB_TRUE;
5986       #ifndef _MSC_VER
5987       struct dirent *data = readdir(z);
5988       nonempty = (data != NULL);
5989       #endif
5990 
5991       if (nonempty) {
5992 
5993          do {
5994             int is_subdir;
5995             #ifdef _MSC_VER
5996             char *name = stb__to_utf8((stb__wchar *)data.name);
5997             if (name == NULL) {
5998                fprintf(stderr, "%s to convert '%S' to %s!\n", "Unable", data.name, "utf8");
5999                continue;
6000             }
6001             is_subdir = !!(data.attrib & _A_SUBDIR);
6002             #else
6003             char *name = data->d_name;
6004             if (!stb_strscpy(buffer+n,name,sizeof(buffer)-n))
6005                break;
6006             // Could follow DT_LNK, but would need to check for recursive links.
6007             is_subdir = !!(data->d_type & DT_DIR);
6008             #endif
6009 
6010             if (is_subdir == return_subdirs) {
6011                if (!is_subdir || !isdotdirname(name)) {
6012                   if (!mask || stb_wildmatchi(mask, name)) {
6013                      char buffer[4096],*p=buffer;
6014                      if ( stb_snprintf(buffer, sizeof(buffer), "%s%s", with_slash, name) < 0 )
6015                         break;
6016                      if (buffer[0] == '.' && buffer[1] == '/')
6017                         p = buffer+2;
6018                      stb_arr_push(results, strdup(p));
6019                   }
6020                }
6021             }
6022          }
6023          #ifdef _MSC_VER
6024          while (0 == _wfindnext(z, &data));
6025          #else
6026          while ((data = readdir(z)) != NULL);
6027          #endif
6028       }
6029       #ifdef _MSC_VER
6030          _findclose(z);
6031       #else
6032          closedir(z);
6033       #endif
6034    }
6035    return results;
6036 }
6037 
6038 char **stb_readdir_files  (char *dir) { return readdir_raw(dir, 0, NULL); }
6039 char **stb_readdir_subdirs(char *dir) { return readdir_raw(dir, 1, NULL); }
6040 char **stb_readdir_files_mask(char *dir, char *wild) { return readdir_raw(dir, 0, wild); }
6041 char **stb_readdir_subdirs_mask(char *dir, char *wild) { return readdir_raw(dir, 1, wild); }
6042 
6043 int stb__rec_max=0x7fffffff;
6044 static char **stb_readdir_rec(char **sofar, char *dir, char *filespec)
6045 {
6046    char **files;
6047    char ** dirs;
6048    char **p;
6049 
6050    if (stb_arr_len(sofar) >= stb__rec_max) return sofar;
6051 
6052    files = stb_readdir_files_mask(dir, filespec);
6053    stb_arr_for(p, files) {
6054       stb_arr_push(sofar, strdup(*p));
6055       if (stb_arr_len(sofar) >= stb__rec_max) break;
6056    }
6057    stb_readdir_free(files);
6058    if (stb_arr_len(sofar) >= stb__rec_max) return sofar;
6059 
6060    dirs = stb_readdir_subdirs(dir);
6061    stb_arr_for(p, dirs)
6062       sofar = stb_readdir_rec(sofar, *p, filespec);
6063    stb_readdir_free(dirs);
6064    return sofar;
6065 }
6066 
6067 char **stb_readdir_recursive(char *dir, char *filespec)
6068 {
6069    return stb_readdir_rec(NULL, dir, filespec);
6070 }
6071 
6072 void stb_delete_directory_recursive(char *dir)
6073 {
6074    char **list = stb_readdir_subdirs(dir);
6075    int i;
6076    for (i=0; i < stb_arr_len(list); ++i)
6077       stb_delete_directory_recursive(list[i]);
6078    stb_arr_free(list);
6079    list = stb_readdir_files(dir);
6080    for (i=0; i < stb_arr_len(list); ++i)
6081       if (!remove(list[i])) {
6082          // on windows, try again after making it writeable; don't ALWAYS
6083          // do this first since that would be slow in the normal case
6084          #ifdef _MSC_VER
6085          _chmod(list[i], _S_IWRITE);
6086          remove(list[i]);
6087          #endif
6088       }
6089    stb_arr_free(list);
6090    stb__windows(_rmdir,rmdir)(dir);
6091 }
6092 
6093 #endif
6094 
6095 //////////////////////////////////////////////////////////////////////////////
6096 //
6097 //   construct trees from filenames; useful for cmirror summaries
6098 
6099 typedef struct stb_dirtree2 stb_dirtree2;
6100 
6101 struct stb_dirtree2
6102 {
6103    stb_dirtree2 **subdirs;
6104 
6105    // make convenient for stb_summarize_tree
6106    int num_subdir;
6107    float weight;
6108 
6109    // actual data
6110    char *fullpath;
6111    char *relpath;
6112    char **files;
6113 };
6114 
6115 STB_EXTERN stb_dirtree2 *stb_dirtree2_from_files_relative(char *src, char **filelist, int count);
6116 STB_EXTERN stb_dirtree2 *stb_dirtree2_from_files(char **filelist, int count);
6117 STB_EXTERN int stb_dir_is_prefix(char *dir, int dirlen, char *file);
6118 
6119 #ifdef STB_DEFINE
6120 
6121 int stb_dir_is_prefix(char *dir, int dirlen, char *file)
6122 {
6123    if (dirlen == 0) return STB_TRUE;
6124    if (stb_strnicmp(dir, file, dirlen)) return STB_FALSE;
6125    if (file[dirlen] == '/' || file[dirlen] == '\\') return STB_TRUE;
6126    return STB_FALSE;
6127 }
6128 
6129 stb_dirtree2 *stb_dirtree2_from_files_relative(char *src, char **filelist, int count)
6130 {
6131    char buffer1[1024];
6132    int i;
6133    int dlen = strlen(src), elen;
6134    stb_dirtree2 *d;
6135    char ** descendents = NULL;
6136    char ** files = NULL;
6137    char *s;
6138    if (!count) return NULL;
6139    // first find all the ones that belong here... note this is will take O(NM) with N files and M subdirs
6140    for (i=0; i < count; ++i) {
6141       if (stb_dir_is_prefix(src, dlen, filelist[i])) {
6142          stb_arr_push(descendents, filelist[i]);
6143       }
6144    }
6145    if (descendents == NULL)
6146       return NULL;
6147    elen = dlen;
6148    // skip a leading slash
6149    if (elen == 0 && (descendents[0][0] == '/' || descendents[0][0] == '\\'))
6150       ++elen;
6151    else if (elen)
6152       ++elen;
6153    // now extract all the ones that have their root here
6154    for (i=0; i < stb_arr_len(descendents);) {
6155       if (!stb_strchr2(descendents[i]+elen, '/', '\\')) {
6156          stb_arr_push(files, descendents[i]);
6157          descendents[i] = descendents[stb_arr_len(descendents)-1];
6158          stb_arr_pop(descendents);
6159       } else
6160          ++i;
6161    }
6162    // now create a record
6163    d = (stb_dirtree2 *) malloc(sizeof(*d));
6164    d->files = files;
6165    d->subdirs = NULL;
6166    d->fullpath = strdup(src);
6167    s = stb_strrchr2(d->fullpath, '/', '\\');
6168    if (s)
6169       ++s;
6170    else
6171       s = d->fullpath;
6172    d->relpath = s;
6173    // now create the children
6174    qsort(descendents, stb_arr_len(descendents), sizeof(char *), stb_qsort_stricmp(0));
6175    buffer1[0] = 0;
6176    for (i=0; i < stb_arr_len(descendents); ++i) {
6177       char buffer2[1024];
6178       char *s = descendents[i] + elen, *t;
6179       t = stb_strchr2(s, '/', '\\');
6180       assert(t);
6181       stb_strncpy(buffer2, descendents[i], t-descendents[i]+1);
6182       if (stb_stricmp(buffer1, buffer2)) {
6183          stb_dirtree2 *t = stb_dirtree2_from_files_relative(buffer2, descendents, stb_arr_len(descendents));
6184          assert(t != NULL);
6185          strcpy(buffer1, buffer2);
6186          stb_arr_push(d->subdirs, t);
6187       }
6188    }
6189    d->num_subdir = stb_arr_len(d->subdirs);
6190    d->weight = 0;
6191    return d;
6192 }
6193 
6194 stb_dirtree2 *stb_dirtree2_from_files(char **filelist, int count)
6195 {
6196    return stb_dirtree2_from_files_relative("", filelist, count);
6197 }
6198 #endif
6199 
6200 //////////////////////////////////////////////////////////////////////////////
6201 //
6202 //                 Checksums: CRC-32, ADLER32, SHA-1
6203 //
6204 //    CRC-32 and ADLER32 allow streaming blocks
6205 //    SHA-1 requires either a complete buffer, max size 2^32 - 73
6206 //          or it can checksum directly from a file, max 2^61
6207 
6208 #define STB_ADLER32_SEED   1
6209 #define STB_CRC32_SEED     0    // note that we logical NOT this in the code
6210 
6211 STB_EXTERN stb_uint
6212   stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen);
6213 STB_EXTERN stb_uint
6214   stb_crc32_block(stb_uint crc32, stb_uchar *buffer, stb_uint len);
6215 STB_EXTERN stb_uint stb_crc32(unsigned char *buffer, stb_uint len);
6216 
6217 STB_EXTERN void stb_sha1(
6218   unsigned char output[20], unsigned char *buffer, unsigned int len);
6219 STB_EXTERN int stb_sha1_file(unsigned char output[20], char *file);
6220 
6221 STB_EXTERN void stb_sha1_readable(char display[27], unsigned char sha[20]);
6222 
6223 #ifdef STB_DEFINE
6224 stb_uint stb_crc32_block(stb_uint crc, unsigned char *buffer, stb_uint len)
6225 {
6226    static stb_uint crc_table[256];
6227    stb_uint i,j,s;
6228    crc = ~crc;
6229 
6230    if (crc_table[1] == 0)
6231       for(i=0; i < 256; i++) {
6232          for (s=i, j=0; j < 8; ++j)
6233             s = (s >> 1) ^ (s & 1 ? 0xedb88320 : 0);
6234          crc_table[i] = s;
6235       }
6236    for (i=0; i < len; ++i)
6237       crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];
6238    return ~crc;
6239 }
6240 
6241 stb_uint stb_crc32(unsigned char *buffer, stb_uint len)
6242 {
6243    return stb_crc32_block(0, buffer, len);
6244 }
6245 
6246 stb_uint stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen)
6247 {
6248    const unsigned long ADLER_MOD = 65521;
6249    unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16;
6250    unsigned long blocklen, i;
6251 
6252    blocklen = buflen % 5552;
6253    while (buflen) {
6254       for (i=0; i + 7 < blocklen; i += 8) {
6255          s1 += buffer[0], s2 += s1;
6256          s1 += buffer[1], s2 += s1;
6257          s1 += buffer[2], s2 += s1;
6258          s1 += buffer[3], s2 += s1;
6259          s1 += buffer[4], s2 += s1;
6260          s1 += buffer[5], s2 += s1;
6261          s1 += buffer[6], s2 += s1;
6262          s1 += buffer[7], s2 += s1;
6263 
6264          buffer += 8;
6265       }
6266 
6267       for (; i < blocklen; ++i)
6268          s1 += *buffer++, s2 += s1;
6269 
6270       s1 %= ADLER_MOD, s2 %= ADLER_MOD;
6271       buflen -= blocklen;
6272       blocklen = 5552;
6273    }
6274    return (s2 << 16) + s1;
6275 }
6276 
6277 static void stb__sha1(stb_uchar *chunk, stb_uint h[5])
6278 {
6279    int i;
6280    stb_uint a,b,c,d,e;
6281    stb_uint w[80];
6282 
6283    for (i=0; i < 16; ++i)
6284       w[i] = stb_big32(&chunk[i*4]);
6285    for (i=16; i < 80; ++i) {
6286       stb_uint t;
6287       t = w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16];
6288       w[i] = (t + t) | (t >> 31);
6289    }
6290 
6291    a = h[0];
6292    b = h[1];
6293    c = h[2];
6294    d = h[3];
6295    e = h[4];
6296 
6297    #define STB__SHA1(k,f)                                            \
6298    {                                                                 \
6299       stb_uint temp = (a << 5) + (a >> 27) + (f) + e + (k) + w[i];  \
6300       e = d;                                                       \
6301       d = c;                                                     \
6302       c = (b << 30) + (b >> 2);                               \
6303       b = a;                                              \
6304       a = temp;                                    \
6305    }
6306 
6307    i=0;
6308    for (; i < 20; ++i) STB__SHA1(0x5a827999, d ^ (b & (c ^ d))       );
6309    for (; i < 40; ++i) STB__SHA1(0x6ed9eba1, b ^ c ^ d               );
6310    for (; i < 60; ++i) STB__SHA1(0x8f1bbcdc, (b & c) + (d & (b ^ c)) );
6311    for (; i < 80; ++i) STB__SHA1(0xca62c1d6, b ^ c ^ d               );
6312 
6313    #undef STB__SHA1
6314 
6315    h[0] += a;
6316    h[1] += b;
6317    h[2] += c;
6318    h[3] += d;
6319    h[4] += e;
6320 }
6321 
6322 void stb_sha1(stb_uchar output[20], stb_uchar *buffer, stb_uint len)
6323 {
6324    unsigned char final_block[128];
6325    stb_uint end_start, final_len, j;
6326    int i;
6327 
6328    stb_uint h[5];
6329 
6330    h[0] = 0x67452301;
6331    h[1] = 0xefcdab89;
6332    h[2] = 0x98badcfe;
6333    h[3] = 0x10325476;
6334    h[4] = 0xc3d2e1f0;
6335 
6336    // we need to write padding to the last one or two
6337    // blocks, so build those first into 'final_block'
6338 
6339    // we have to write one special byte, plus the 8-byte length
6340 
6341    // compute the block where the data runs out
6342    end_start = len & ~63;
6343 
6344    // compute the earliest we can encode the length
6345    if (((len+9) & ~63) == end_start) {
6346       // it all fits in one block, so fill a second-to-last block
6347       end_start -= 64;
6348    }
6349 
6350    final_len = end_start + 128;
6351 
6352    // now we need to copy the data in
6353    assert(end_start + 128 >= len+9);
6354    assert(end_start < len || len < 64-9);
6355 
6356    j = 0;
6357    if (end_start > len)
6358       j = (stb_uint) - (int) end_start;
6359 
6360    for (; end_start + j < len; ++j)
6361       final_block[j] = buffer[end_start + j];
6362    final_block[j++] = 0x80;
6363    while (j < 128-5) // 5 byte length, so write 4 extra padding bytes
6364       final_block[j++] = 0;
6365    // big-endian size
6366    final_block[j++] = len >> 29;
6367    final_block[j++] = len >> 21;
6368    final_block[j++] = len >> 13;
6369    final_block[j++] = len >>  5;
6370    final_block[j++] = len <<  3;
6371    assert(j == 128 && end_start + j == final_len);
6372 
6373    for (j=0; j < final_len; j += 64) { // 512-bit chunks
6374       if (j+64 >= end_start+64)
6375          stb__sha1(&final_block[j - end_start], h);
6376       else
6377          stb__sha1(&buffer[j], h);
6378    }
6379 
6380    for (i=0; i < 5; ++i) {
6381       output[i*4 + 0] = h[i] >> 24;
6382       output[i*4 + 1] = h[i] >> 16;
6383       output[i*4 + 2] = h[i] >>  8;
6384       output[i*4 + 3] = h[i] >>  0;
6385    }
6386 }
6387 
6388 #ifdef _MSC_VER
6389 int stb_sha1_file(stb_uchar output[20], char *file)
6390 {
6391    int i;
6392    stb_uint64 length=0;
6393    unsigned char buffer[128];
6394 
6395    FILE *f = stb__fopen(file, "rb");
6396    stb_uint h[5];
6397 
6398    if (f == NULL) return 0; // file not found
6399 
6400    h[0] = 0x67452301;
6401    h[1] = 0xefcdab89;
6402    h[2] = 0x98badcfe;
6403    h[3] = 0x10325476;
6404    h[4] = 0xc3d2e1f0;
6405 
6406    for(;;) {
6407       int n = fread(buffer, 1, 64, f);
6408       if (n == 64) {
6409          stb__sha1(buffer, h);
6410          length += n;
6411       } else {
6412          int block = 64;
6413 
6414          length += n;
6415 
6416          buffer[n++] = 0x80;
6417 
6418          // if there isn't enough room for the length, double the block
6419          if (n + 8 > 64)
6420             block = 128;
6421 
6422          // pad to end
6423          memset(buffer+n, 0, block-8-n);
6424 
6425          i = block - 8;
6426          buffer[i++] = (stb_uchar) (length >> 53);
6427          buffer[i++] = (stb_uchar) (length >> 45);
6428          buffer[i++] = (stb_uchar) (length >> 37);
6429          buffer[i++] = (stb_uchar) (length >> 29);
6430          buffer[i++] = (stb_uchar) (length >> 21);
6431          buffer[i++] = (stb_uchar) (length >> 13);
6432          buffer[i++] = (stb_uchar) (length >>  5);
6433          buffer[i++] = (stb_uchar) (length <<  3);
6434          assert(i == block);
6435          stb__sha1(buffer, h);
6436          if (block == 128)
6437             stb__sha1(buffer+64, h);
6438          else
6439             assert(block == 64);
6440          break;
6441       }
6442    }
6443    fclose(f);
6444 
6445    for (i=0; i < 5; ++i) {
6446       output[i*4 + 0] = h[i] >> 24;
6447       output[i*4 + 1] = h[i] >> 16;
6448       output[i*4 + 2] = h[i] >>  8;
6449       output[i*4 + 3] = h[i] >>  0;
6450    }
6451 
6452    return 1;
6453 }
6454 #endif // _MSC_VER
6455 
6456 // client can truncate this wherever they like
6457 void stb_sha1_readable(char display[27], unsigned char sha[20])
6458 {
6459    char encoding[65] = "0123456789abcdefghijklmnopqrstuv"
6460                        "wxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%$";
6461    int num_bits = 0, acc=0;
6462    int i=0,o=0;
6463    while (o < 26) {
6464       int v;
6465       // expand the accumulator
6466       if (num_bits < 6) {
6467          assert(i != 20);
6468          acc += sha[i++] << num_bits;
6469          num_bits += 8;
6470       }
6471       v = acc & ((1 << 6) - 1);
6472       display[o++] = encoding[v];
6473       acc >>= 6;
6474       num_bits -= 6;
6475    }
6476    assert(num_bits == 20*8 - 26*6);
6477    display[o++] = encoding[acc];
6478 }
6479 
6480 #endif // STB_DEFINE
6481 
6482 ///////////////////////////////////////////////////////////
6483 //
6484 // simplified WINDOWS registry interface... hopefully
6485 // we'll never actually use this?
6486 
6487 #if defined(_WIN32)
6488 
6489 STB_EXTERN void * stb_reg_open(char *mode, char *where); // mode: "rHKLM" or "rHKCU" or "w.."
6490 STB_EXTERN void   stb_reg_close(void *reg);
6491 STB_EXTERN int    stb_reg_read(void *zreg, char *str, void *data, unsigned long len);
6492 STB_EXTERN int    stb_reg_read_string(void *zreg, char *str, char *data, int len);
6493 STB_EXTERN void   stb_reg_write(void *zreg, char *str, void *data, unsigned long len);
6494 STB_EXTERN void   stb_reg_write_string(void *zreg, char *str, char *data);
6495 
6496 #if defined(STB_DEFINE) && !defined(STB_NO_REGISTRY)
6497 
6498 #define STB_HAS_REGISTRY
6499 
6500 #ifndef _WINDOWS_
6501 
6502 #define HKEY void *
6503 
6504 STB_EXTERN __declspec(dllimport) long __stdcall RegCloseKey ( HKEY hKey );
6505 STB_EXTERN __declspec(dllimport) long __stdcall RegCreateKeyExA ( HKEY hKey, const char * lpSubKey,
6506     int  Reserved, char * lpClass, int  dwOptions,
6507     int samDesired, void *lpSecurityAttributes,     HKEY * phkResult,     int * lpdwDisposition );
6508 STB_EXTERN __declspec(dllimport) long __stdcall RegDeleteKeyA ( HKEY hKey, const char * lpSubKey );
6509 STB_EXTERN __declspec(dllimport) long __stdcall RegQueryValueExA ( HKEY hKey, const char * lpValueName,
6510     int * lpReserved, unsigned long * lpType, unsigned char * lpData, unsigned long * lpcbData );
6511 STB_EXTERN __declspec(dllimport) long __stdcall RegSetValueExA ( HKEY hKey, const char * lpValueName,
6512     int  Reserved, int  dwType, const unsigned char* lpData, int  cbData );
6513 STB_EXTERN __declspec(dllimport) long __stdcall  RegOpenKeyExA ( HKEY hKey, const char * lpSubKey,
6514     int ulOptions, int samDesired, HKEY * phkResult );
6515 
6516 #endif // _WINDOWS_
6517 
6518 #define STB__REG_OPTION_NON_VOLATILE  0
6519 #define STB__REG_KEY_ALL_ACCESS       0x000f003f
6520 #define STB__REG_KEY_READ             0x00020019
6521 
6522 void *stb_reg_open(char *mode, char *where)
6523 {
6524    long res;
6525    HKEY base;
6526    HKEY zreg;
6527    if (!stb_stricmp(mode+1, "cu") || !stb_stricmp(mode+1, "hkcu"))
6528       base = (HKEY) 0x80000001; // HKCU
6529    else if (!stb_stricmp(mode+1, "lm") || !stb_stricmp(mode+1, "hklm"))
6530       base = (HKEY) 0x80000002; // HKLM
6531    else
6532       return NULL;
6533 
6534    if (mode[0] == 'r')
6535       res = RegOpenKeyExA(base, where, 0, STB__REG_KEY_READ, &zreg);
6536    else if (mode[0] == 'w')
6537       res = RegCreateKeyExA(base, where,  0, NULL, STB__REG_OPTION_NON_VOLATILE, STB__REG_KEY_ALL_ACCESS, NULL, &zreg, NULL);
6538    else
6539       return NULL;
6540 
6541    return res ? NULL : zreg;
6542 }
6543 
6544 void stb_reg_close(void *reg)
6545 {
6546    RegCloseKey((HKEY) reg);
6547 }
6548 
6549 #define STB__REG_SZ         1
6550 #define STB__REG_BINARY     3
6551 #define STB__REG_DWORD      4
6552 
6553 int stb_reg_read(void *zreg, char *str, void *data, unsigned long len)
6554 {
6555    unsigned long type;
6556    unsigned long alen = len;
6557    if (0 == RegQueryValueExA((HKEY) zreg, str, 0, &type, (unsigned char *) data, &len))
6558       if (type == STB__REG_BINARY || type == STB__REG_SZ || type == STB__REG_DWORD) {
6559          if (len < alen)
6560             *((char *) data + len) = 0;
6561          return 1;
6562       }
6563    return 0;
6564 }
6565 
6566 void stb_reg_write(void *zreg, char *str, void *data, unsigned long len)
6567 {
6568    if (zreg)
6569       RegSetValueExA((HKEY) zreg, str, 0, STB__REG_BINARY, (const unsigned char *) data, len);
6570 }
6571 
6572 int stb_reg_read_string(void *zreg, char *str, char *data, int len)
6573 {
6574    if (!stb_reg_read(zreg, str, data, len)) return 0;
6575    data[len-1] = 0; // force a 0 at the end of the string no matter what
6576    return 1;
6577 }
6578 
6579 void stb_reg_write_string(void *zreg, char *str, char *data)
6580 {
6581    if (zreg)
6582       RegSetValueExA((HKEY) zreg, str, 0, STB__REG_SZ, (const unsigned char *)  data, strlen(data)+1);
6583 }
6584 #endif  // STB_DEFINE
6585 #endif  // _WIN32
6586 
6587 
6588 //////////////////////////////////////////////////////////////////////////////
6589 //
6590 //     stb_cfg - This is like the registry, but the config info
6591 //               is all stored in plain old files where we can
6592 //               backup and restore them easily. The LOCATION of
6593 //               the config files is gotten from... the registry!
6594 
6595 #ifndef STB_NO_STB_STRINGS
6596 typedef struct stb_cfg_st stb_cfg;
6597 
6598 STB_EXTERN stb_cfg * stb_cfg_open(char *config, char *mode); // mode = "r", "w"
6599 STB_EXTERN void      stb_cfg_close(stb_cfg *cfg);
6600 STB_EXTERN int       stb_cfg_read(stb_cfg *cfg, char *key, void *value, int len);
6601 STB_EXTERN void      stb_cfg_write(stb_cfg *cfg, char *key, void *value, int len);
6602 STB_EXTERN int       stb_cfg_read_string(stb_cfg *cfg, char *key, char *value, int len);
6603 STB_EXTERN void      stb_cfg_write_string(stb_cfg *cfg, char *key, char *value);
6604 STB_EXTERN int       stb_cfg_delete(stb_cfg *cfg, char *key);
6605 STB_EXTERN void      stb_cfg_set_directory(char *dir);
6606 
6607 #ifdef STB_DEFINE
6608 
6609 typedef struct
6610 {
6611    char *key;
6612    void *value;
6613    int value_len;
6614 } stb__cfg_item;
6615 
6616 struct stb_cfg_st
6617 {
6618    stb__cfg_item *data;
6619    char *loaded_file;   // this needs to be freed
6620    FILE *f; // write the data to this file on close
6621 };
6622 
6623 static char *stb__cfg_sig = "sTbCoNfIg!\0\0";
6624 static char stb__cfg_dir[512];
6625 STB_EXTERN void stb_cfg_set_directory(char *dir)
6626 {
6627    strcpy(stb__cfg_dir, dir);
6628 }
6629 
6630 STB_EXTERN stb_cfg * stb_cfg_open(char *config, char *mode)
6631 {
6632    size_t len;
6633    stb_cfg *z;
6634    char file[512];
6635    if (mode[0] != 'r' && mode[0] != 'w') return NULL;
6636 
6637    if (!stb__cfg_dir[0]) {
6638       #ifdef _WIN32
6639       strcpy(stb__cfg_dir, "c:/stb");
6640       #else
6641       strcpy(stb__cfg_dir, "~/.stbconfig");
6642       #endif
6643 
6644       #ifdef STB_HAS_REGISTRY
6645       {
6646          void *reg = stb_reg_open("rHKLM", "Software\\SilverSpaceship\\stb");
6647          if (reg) {
6648             stb_reg_read_string(reg, "config_dir", stb__cfg_dir, sizeof(stb__cfg_dir));
6649             stb_reg_close(reg);
6650          }
6651       }
6652       #endif
6653    }
6654 
6655    sprintf(file, "%s/%s.cfg", stb__cfg_dir, config);
6656 
6657    z = (stb_cfg *) stb_malloc(0, sizeof(*z));
6658    z->data = NULL;
6659 
6660    z->loaded_file = stb_filec(file, &len);
6661    if (z->loaded_file) {
6662       char *s = z->loaded_file;
6663       if (!memcmp(s, stb__cfg_sig, 12)) {
6664          char *s = z->loaded_file + 12;
6665          while (s < z->loaded_file + len) {
6666             stb__cfg_item a;
6667             int n = *(stb_int16 *) s;
6668             a.key = s+2;
6669             s = s+2 + n;
6670             a.value_len = *(int *) s;
6671             s += 4;
6672             a.value = s;
6673             s += a.value_len;
6674             stb_arr_push(z->data, a);
6675          }
6676          assert(s == z->loaded_file + len);
6677       }
6678    }
6679 
6680    if (mode[0] == 'w')
6681       z->f = fopen(file, "wb");
6682    else
6683       z->f = NULL;
6684 
6685    return z;
6686 }
6687 
6688 void stb_cfg_close(stb_cfg *z)
6689 {
6690    if (z->f) {
6691       int i;
6692       // write the file out
6693       fwrite(stb__cfg_sig, 12, 1, z->f);
6694       for (i=0; i < stb_arr_len(z->data); ++i) {
6695          stb_int16 n = strlen(z->data[i].key)+1;
6696          fwrite(&n, 2, 1, z->f);
6697          fwrite(z->data[i].key, n, 1, z->f);
6698          fwrite(&z->data[i].value_len, 4, 1, z->f);
6699          fwrite(z->data[i].value, z->data[i].value_len, 1, z->f);
6700       }
6701       fclose(z->f);
6702    }
6703    stb_arr_free(z->data);
6704    stb_free(z);
6705 }
6706 
6707 int stb_cfg_read(stb_cfg *z, char *key, void *value, int len)
6708 {
6709    int i;
6710    for (i=0; i < stb_arr_len(z->data); ++i) {
6711       if (!stb_stricmp(z->data[i].key, key)) {
6712          int n = stb_min(len, z->data[i].value_len);
6713          memcpy(value, z->data[i].value, n);
6714          if (n < len)
6715             *((char *) value + n) = 0;
6716          return 1;
6717       }
6718    }
6719    return 0;
6720 }
6721 
6722 void stb_cfg_write(stb_cfg *z, char *key, void *value, int len)
6723 {
6724    int i;
6725    for (i=0; i < stb_arr_len(z->data); ++i)
6726       if (!stb_stricmp(z->data[i].key, key))
6727          break;
6728    if (i == stb_arr_len(z->data)) {
6729       stb__cfg_item p;
6730       p.key = stb_strdup(key, z);
6731       p.value = NULL;
6732       p.value_len = 0;
6733       stb_arr_push(z->data, p);
6734    }
6735    z->data[i].value = stb_malloc(z, len);
6736    z->data[i].value_len = len;
6737    memcpy(z->data[i].value, value, len);
6738 }
6739 
6740 int stb_cfg_delete(stb_cfg *z, char *key)
6741 {
6742    int i;
6743    for (i=0; i < stb_arr_len(z->data); ++i)
6744       if (!stb_stricmp(z->data[i].key, key)) {
6745          stb_arr_fastdelete(z->data, i);
6746          return 1;
6747       }
6748    return 0;
6749 }
6750 
6751 int stb_cfg_read_string(stb_cfg *z, char *key, char *value, int len)
6752 {
6753    if (!stb_cfg_read(z, key, value, len)) return 0;
6754    value[len-1] = 0;
6755    return 1;
6756 }
6757 
6758 void stb_cfg_write_string(stb_cfg *z, char *key, char *value)
6759 {
6760    stb_cfg_write(z, key, value, strlen(value)+1);
6761 }
6762 #endif
6763 
6764 //////////////////////////////////////////////////////////////////////////////
6765 //
6766 //     stb_dirtree  - load a description of a directory tree
6767 //                      uses a cache and stat()s the directories for changes
6768 //                      MUCH faster on NTFS, _wrong_ on FAT32, so should
6769 //                      ignore the db on FAT32
6770 
6771 #ifdef _WIN32
6772 
6773 typedef struct
6774 {
6775    char   * path;           // full path from passed-in root
6776    time_t   last_modified;
6777    int      num_files;
6778    int      flag;
6779 } stb_dirtree_dir;
6780 
6781 typedef struct
6782 {
6783    char *name;              // name relative to path
6784    int   dir;               // index into dirs[] array
6785    stb_int64 size;      // size, max 4GB
6786    time_t   last_modified;
6787    int      flag;
6788 } stb_dirtree_file;
6789 
6790 typedef struct
6791 {
6792    stb_dirtree_dir  *dirs;
6793    stb_dirtree_file *files;
6794 
6795    // internal use
6796    void             * string_pool;   // used to free data en masse
6797 } stb_dirtree;
6798 
6799 extern void         stb_dirtree_free          ( stb_dirtree *d );
6800 extern stb_dirtree *stb_dirtree_get           ( char *dir);
6801 extern stb_dirtree *stb_dirtree_get_dir       ( char *dir, char *cache_dir);
6802 extern stb_dirtree *stb_dirtree_get_with_file ( char *dir, char *cache_file);
6803 
6804 // get a list of all the files recursively underneath 'dir'
6805 //
6806 // cache_file is used to store a copy of the directory tree to speed up
6807 // later calls. It must be unique to 'dir' and the current working
6808 // directory! Otherwise who knows what will happen (a good solution
6809 // is to put it _in_ dir, but this API doesn't force that).
6810 //
6811 // Also, it might be possible to break this if you have two different processes
6812 // do a call to stb_dirtree_get() with the same cache file at about the same
6813 // time, but I _think_ it might just work.
6814 
6815 // i needed to build an identical data structure representing the state of
6816 // a mirrored copy WITHOUT bothering to rescan it (i.e. we're mirroring to
6817 // it WITHOUT scanning it, e.g. it's over the net), so this requires access
6818 // to all of the innards.
6819 extern void stb_dirtree_db_add_dir(stb_dirtree *active, char *path, time_t last);
6820 extern void stb_dirtree_db_add_file(stb_dirtree *active, char *name, int dir, stb_int64 size, time_t last);
6821 extern void stb_dirtree_db_read(stb_dirtree *target, char *filename, char *dir);
6822 extern void stb_dirtree_db_write(stb_dirtree *target, char *filename, char *dir);
6823 
6824 #ifdef STB_DEFINE
6825 static void stb__dirtree_add_dir(char *path, time_t last, stb_dirtree *active)
6826 {
6827    stb_dirtree_dir d;
6828    d.last_modified = last;
6829    d.num_files = 0;
6830    d.path = stb_strdup(path, active->string_pool);
6831    stb_arr_push(active->dirs, d);
6832 }
6833 
6834 static void stb__dirtree_add_file(char *name, int dir, stb_int64 size, time_t last, stb_dirtree *active)
6835 {
6836    stb_dirtree_file f;
6837    f.dir = dir;
6838    f.size = size;
6839    f.last_modified = last;
6840    f.name = stb_strdup(name, active->string_pool);
6841    ++active->dirs[dir].num_files;
6842    stb_arr_push(active->files, f);
6843 }
6844 
6845 // version 02 supports > 4GB files
6846 static char stb__signature[12] = { 's', 'T', 'b', 'D', 'i', 'R', 't', 'R', 'e', 'E', '0', '2' };
6847 
6848 static void stb__dirtree_save_db(char *filename, stb_dirtree *data, char *root)
6849 {
6850    int i, num_dirs_final=0, num_files_final;
6851    char *info = root ? root : "";
6852    int *remap;
6853    FILE *f = fopen(filename, "wb");
6854    if (!f) return;
6855 
6856    fwrite(stb__signature, sizeof(stb__signature), 1, f);
6857    fwrite(info, strlen(info)+1, 1, f);
6858    // need to be slightly tricky and not write out NULLed directories, nor the root
6859 
6860    // build remapping table of all dirs we'll be writing out
6861    remap = (int *) malloc(sizeof(remap[0]) * stb_arr_len(data->dirs));
6862    for (i=0; i < stb_arr_len(data->dirs); ++i) {
6863       if (data->dirs[i].path == NULL || (root && 0==stb_stricmp(data->dirs[i].path, root))) {
6864          remap[i] = -1;
6865       } else {
6866          remap[i] = num_dirs_final++;
6867       }
6868    }
6869 
6870    fwrite(&num_dirs_final, 4, 1, f);
6871    for (i=0; i < stb_arr_len(data->dirs); ++i) {
6872       if (remap[i] >= 0) {
6873          fwrite(&data->dirs[i].last_modified, 4, 1, f);
6874          stb_fput_string(f, data->dirs[i].path);
6875       }
6876    }
6877 
6878    num_files_final = 0;
6879    for (i=0; i < stb_arr_len(data->files); ++i)
6880       if (remap[data->files[i].dir] >= 0 && data->files[i].name)
6881          ++num_files_final;
6882 
6883    fwrite(&num_files_final, 4, 1, f);
6884    for (i=0; i < stb_arr_len(data->files); ++i) {
6885       if (remap[data->files[i].dir] >= 0 && data->files[i].name) {
6886          stb_fput_ranged(f, remap[data->files[i].dir], 0, num_dirs_final);
6887          stb_fput_varlen64(f, data->files[i].size);
6888          fwrite(&data->files[i].last_modified, 4, 1, f);
6889          stb_fput_string(f, data->files[i].name);
6890       }
6891    }
6892 
6893    fclose(f);
6894 }
6895 
6896 // note: stomps any existing data, rather than appending
6897 static void stb__dirtree_load_db(char *filename, stb_dirtree *data, char *dir)
6898 {
6899    char sig[2048];
6900    int i,n;
6901    FILE *f = fopen(filename, "rb");
6902 
6903    if (!f) return;
6904 
6905    data->string_pool = stb_malloc(0,1);
6906 
6907    fread(sig, sizeof(stb__signature), 1, f);
6908    if (memcmp(stb__signature, sig, sizeof(stb__signature))) { fclose(f); return; }
6909    if (!fread(sig, strlen(dir)+1, 1, f))                    { fclose(f); return; }
6910    if (stb_stricmp(sig,dir))                                { fclose(f); return; }
6911 
6912    // we can just read them straight in, because they're guaranteed to be valid
6913    fread(&n, 4, 1, f);
6914    stb_arr_setlen(data->dirs, n);
6915    for(i=0; i < stb_arr_len(data->dirs); ++i) {
6916       fread(&data->dirs[i].last_modified, 4, 1, f);
6917       data->dirs[i].path = stb_fget_string(f, data->string_pool);
6918       if (data->dirs[i].path == NULL) goto bail;
6919    }
6920    fread(&n, 4, 1, f);
6921    stb_arr_setlen(data->files, n);
6922    for (i=0; i < stb_arr_len(data->files); ++i) {
6923       data->files[i].dir  = stb_fget_ranged(f, 0, stb_arr_len(data->dirs));
6924       data->files[i].size = stb_fget_varlen64(f);
6925       fread(&data->files[i].last_modified, 4, 1, f);
6926       data->files[i].name = stb_fget_string(f, data->string_pool);
6927       if (data->files[i].name == NULL) goto bail;
6928    }
6929 
6930    if (0) {
6931       bail:
6932          stb_arr_free(data->dirs);
6933          stb_arr_free(data->files);
6934    }
6935    fclose(f);
6936 }
6937 
6938 static int stb__dircount, stb__dircount_mask, stb__showfile;
6939 static void stb__dirtree_scandir(char *path, time_t last_time, stb_dirtree *active)
6940 {
6941    // this is dumb depth first; theoretically it might be faster
6942    // to fully traverse each directory before visiting its children,
6943    // but it's complicated and didn't seem like a gain in the test app
6944 
6945    int n;
6946 
6947    struct _wfinddatai64_t c_file;
6948    long hFile;
6949    stb__wchar full_path[1024];
6950    int has_slash;
6951    if (stb__showfile) printf("<");
6952 
6953    has_slash = (path[0] && path[strlen(path)-1] == '/');
6954 
6955    // @TODO: do this concatenation without using swprintf to avoid this mess:
6956 #if defined(_MSC_VER) && _MSC_VER < 1400
6957    if (has_slash)
6958       swprintf(full_path, L"%s*", stb__from_utf8(path));
6959    else
6960       swprintf(full_path, L"%s/*", stb__from_utf8(path));
6961 #else
6962    if (has_slash)
6963       swprintf(full_path, 1024, L"%s*", stb__from_utf8(path));
6964    else
6965       swprintf(full_path, 1024, L"%s/*", stb__from_utf8(path));
6966 #endif
6967 
6968    // it's possible this directory is already present: that means it was in the
6969    // cache, but its parent wasn't... in that case, we're done with it
6970    if (stb__showfile) printf("C[%d]", stb_arr_len(active->dirs));
6971    for (n=0; n < stb_arr_len(active->dirs); ++n)
6972       if (0 == stb_stricmp(active->dirs[n].path, path)) {
6973          if (stb__showfile) printf("D");
6974          return;
6975       }
6976    if (stb__showfile) printf("E");
6977 
6978    // otherwise, we need to add it
6979    stb__dirtree_add_dir(path, last_time, active);
6980    n = stb_arr_lastn(active->dirs);
6981 
6982    if (stb__showfile) printf("[");
6983    if( (hFile = _wfindfirsti64( full_path, &c_file )) != -1L ) {
6984       do {
6985          if (stb__showfile) printf(")");
6986          if (c_file.attrib & _A_SUBDIR) {
6987             // ignore subdirectories starting with '.', e.g. "." and ".."
6988             if (c_file.name[0] != '.') {
6989                char *new_path = (char *) full_path;
6990                char *temp = stb__to_utf8(c_file.name);
6991 
6992                if (has_slash)
6993                   sprintf(new_path, "%s%s", path, temp);
6994                else
6995                   sprintf(new_path, "%s/%s", path, temp);
6996 
6997                if (stb__dircount_mask) {
6998                   ++stb__dircount;
6999                   if (!(stb__dircount & stb__dircount_mask)) {
7000                      printf("%s\r", new_path);
7001                   }
7002                }
7003 
7004                stb__dirtree_scandir(new_path, c_file.time_write, active);
7005             }
7006          } else {
7007             char *temp = stb__to_utf8(c_file.name);
7008             stb__dirtree_add_file(temp, n, c_file.size, c_file.time_write, active);
7009          }
7010          if (stb__showfile) printf("(");
7011       } while( _wfindnexti64( hFile, &c_file ) == 0 );
7012       if (stb__showfile) printf("]");
7013       _findclose( hFile );
7014    }
7015    if (stb__showfile) printf(">\n");
7016 }
7017 
7018 // scan the database and see if it's all valid
7019 static int stb__dirtree_update_db(stb_dirtree *db, stb_dirtree *active)
7020 {
7021    int changes_detected = STB_FALSE;
7022    int i;
7023    int *remap;
7024    int *rescan=NULL;
7025    remap = (int *) malloc(sizeof(remap[0]) * stb_arr_len(db->dirs));
7026    memset(remap, 0, sizeof(remap[0]) * stb_arr_len(db->dirs));
7027    rescan = NULL;
7028 
7029    for (i=0; i < stb_arr_len(db->dirs); ++i) {
7030       struct _stat info;
7031       if (stb__dircount_mask) {
7032          ++stb__dircount;
7033          if (!(stb__dircount & stb__dircount_mask)) {
7034             printf(".");
7035          }
7036       }
7037       if (0 == _stat(db->dirs[i].path, &info)) {
7038          if (info.st_mode & _S_IFDIR) {
7039             // it's still a directory, as expected
7040             int n = abs(info.st_mtime - db->dirs[i].last_modified);
7041             if (n > 1 && n != 3600) {  // the 3600 is a hack because sometimes this jumps for no apparent reason, even when no time zone or DST issues are at play
7042                // it's changed! force a rescan
7043                // we don't want to scan it until we've stat()d its
7044                // subdirs, though, so we queue it
7045                if (stb__showfile) printf("Changed: %s - %08x:%08x\n", db->dirs[i].path, db->dirs[i].last_modified, info.st_mtime);
7046                stb_arr_push(rescan, i);
7047                // update the last_mod time
7048                db->dirs[i].last_modified = info.st_mtime;
7049                // ignore existing files in this dir
7050                remap[i] = -1;
7051                changes_detected = STB_TRUE;
7052             } else {
7053                // it hasn't changed, just copy it through unchanged
7054                stb__dirtree_add_dir(db->dirs[i].path, db->dirs[i].last_modified, active);
7055                remap[i] = stb_arr_lastn(active->dirs);
7056             }
7057          } else {
7058             // this path used to refer to a directory, but now it's a file!
7059             // assume that the parent directory is going to be forced to rescan anyway
7060             goto delete_entry;
7061          }
7062       } else {
7063         delete_entry:
7064          // directory no longer exists, so don't copy it
7065          // we don't free it because it's in the string pool now
7066          db->dirs[i].path = NULL;
7067          remap[i] = -1;
7068          changes_detected = STB_TRUE;
7069       }
7070    }
7071 
7072    // at this point, we have:
7073    //
7074    //   <rescan> holds a list of directory indices that need to be scanned due to being out of date
7075    //   <remap> holds the directory index in <active> for each dir in <db>, if it exists; -1 if not
7076    //           directories in <rescan> are not in <active> yet
7077 
7078    // so we can go ahead and remap all the known files right now
7079    for (i=0; i < stb_arr_len(db->files); ++i) {
7080       int dir = db->files[i].dir;
7081       if (remap[dir] >= 0) {
7082          stb__dirtree_add_file(db->files[i].name, remap[dir], db->files[i].size, db->files[i].last_modified, active);
7083       }
7084    }
7085 
7086    // at this point we're done with db->files, and done with remap
7087    free(remap);
7088 
7089    // now scan those directories using the standard scan
7090    for (i=0; i < stb_arr_len(rescan); ++i) {
7091       int z = rescan[i];
7092       stb__dirtree_scandir(db->dirs[z].path, db->dirs[z].last_modified, active);
7093    }
7094    stb_arr_free(rescan);
7095 
7096    return changes_detected;
7097 }
7098 
7099 static void stb__dirtree_free_raw(stb_dirtree *d)
7100 {
7101    stb_free(d->string_pool);
7102    stb_arr_free(d->dirs);
7103    stb_arr_free(d->files);
7104 }
7105 
7106 stb_dirtree *stb_dirtree_get_with_file(char *dir, char *cache_file)
7107 {
7108    stb_dirtree *output = (stb_dirtree *) malloc(sizeof(*output));
7109    stb_dirtree db,active;
7110    int prev_dir_count, cache_mismatch;
7111 
7112    char *stripped_dir; // store the directory name without a trailing '/' or '\\'
7113 
7114    // load the database of last-known state on disk
7115    db.string_pool = NULL;
7116    db.files = NULL;
7117    db.dirs = NULL;
7118 
7119    stripped_dir = stb_strip_final_slash(strdup(dir));
7120 
7121    if (cache_file != NULL)
7122       stb__dirtree_load_db(cache_file, &db, stripped_dir);
7123    else if (stb__showfile)
7124       printf("No cache file\n");
7125 
7126    active.files = NULL;
7127    active.dirs = NULL;
7128    active.string_pool = stb_malloc(0,1); // @TODO: share string pools between both?
7129 
7130    // check all the directories in the database; make note if
7131    // anything we scanned had changed, and rescan those things
7132    cache_mismatch = stb__dirtree_update_db(&db, &active);
7133 
7134    // check the root tree
7135    prev_dir_count = stb_arr_len(active.dirs);  // record how many directories we've seen
7136 
7137    stb__dirtree_scandir(stripped_dir, 0, &active);  // no last_modified time available for root
7138 
7139    if (stb__dircount_mask)
7140       printf("                                                                              \r");
7141 
7142    // done with the DB; write it back out if any changes, i.e. either
7143    //      1. any inconsistency found between cached information and actual disk
7144    //   or 2. if scanning the root found any new directories--which we detect because
7145    //         more than one directory got added to the active db during that scan
7146    if (cache_mismatch || stb_arr_len(active.dirs) > prev_dir_count+1)
7147       stb__dirtree_save_db(cache_file, &active, stripped_dir);
7148 
7149    free(stripped_dir);
7150 
7151    stb__dirtree_free_raw(&db);
7152 
7153    *output = active;
7154    return output;
7155 }
7156 
7157 stb_dirtree *stb_dirtree_get_dir(char *dir, char *cache_dir)
7158 {
7159    int i;
7160    stb_uint8 sha[20];
7161    char dir_lower[1024];
7162    char cache_file[1024],*s;
7163    if (cache_dir == NULL)
7164       return stb_dirtree_get_with_file(dir, NULL);
7165    strcpy(dir_lower, dir);
7166    stb_tolower(dir_lower);
7167    stb_sha1(sha, (unsigned char *) dir_lower, strlen(dir_lower));
7168    strcpy(cache_file, cache_dir);
7169    s = cache_file + strlen(cache_file);
7170    if (s[-1] != '//' && s[-1] != '\\') *s++ = '/';
7171    strcpy(s, "dirtree_");
7172    s += strlen(s);
7173    for (i=0; i < 8; ++i) {
7174       char *hex = "0123456789abcdef";
7175       stb_uint z = sha[i];
7176       *s++ = hex[z >> 4];
7177       *s++ = hex[z & 15];
7178    }
7179    strcpy(s, ".bin");
7180    return stb_dirtree_get_with_file(dir, cache_file);
7181 }
7182 
7183 stb_dirtree *stb_dirtree_get(char *dir)
7184 {
7185    char cache_dir[256];
7186    strcpy(cache_dir, "c:/stb");
7187    #ifdef STB_HAS_REGISTRY
7188    {
7189       void *reg = stb_reg_open("rHKLM", "Software\\SilverSpaceship\\stb");
7190       if (reg) {
7191          stb_reg_read(reg, "dirtree", cache_dir, sizeof(cache_dir));
7192          stb_reg_close(reg);
7193       }
7194    }
7195    #endif
7196    return stb_dirtree_get_dir(dir, cache_dir);
7197 }
7198 
7199 void stb_dirtree_free(stb_dirtree *d)
7200 {
7201    stb__dirtree_free_raw(d);
7202    free(d);
7203 }
7204 
7205 void stb_dirtree_db_add_dir(stb_dirtree *active, char *path, time_t last)
7206 {
7207    stb__dirtree_add_dir(path, last, active);
7208 }
7209 
7210 void stb_dirtree_db_add_file(stb_dirtree *active, char *name, int dir, stb_int64 size, time_t last)
7211 {
7212    stb__dirtree_add_file(name, dir, size, last, active);
7213 }
7214 
7215 void stb_dirtree_db_read(stb_dirtree *target, char *filename, char *dir)
7216 {
7217    char *s = stb_strip_final_slash(strdup(dir));
7218    target->dirs = 0;
7219    target->files = 0;
7220    target->string_pool = 0;
7221    stb__dirtree_load_db(filename, target, s);
7222    free(s);
7223 }
7224 
7225 void stb_dirtree_db_write(stb_dirtree *target, char *filename, char *dir)
7226 {
7227    stb__dirtree_save_db(filename, target, 0); // don't strip out any directories
7228 }
7229 
7230 #endif // STB_DEFINE
7231 
7232 #endif // _WIN32
7233 #endif // STB_NO_STB_STRINGS
7234 
7235 //////////////////////////////////////////////////////////////////////////////
7236 //
7237 //  STB_MALLOC_WRAPPER
7238 //
7239 //    you can use the wrapper functions with your own malloc wrapper,
7240 //    or define STB_MALLOC_WRAPPER project-wide to have
7241 //    malloc/free/realloc/strdup all get vectored to it
7242 
7243 // this has too many very specific error messages you could google for and find in stb.h,
7244 // so don't use it if they don't want any stb.h-identifiable strings
7245 #if defined(STB_DEFINE) && !defined(STB_NO_STB_STRINGS)
7246 
7247 typedef struct
7248 {
7249    void *p;
7250    char *file;
7251    int  line;
7252    int  size;
7253 } stb_malloc_record;
7254 
7255 #ifndef STB_MALLOC_HISTORY_COUNT
7256 #define STB_MALLOC_HISTORY_COUNT 50 // 800 bytes
7257 #endif
7258 
7259 stb_malloc_record *stb__allocations;
7260 static int stb__alloc_size, stb__alloc_limit, stb__alloc_mask;
7261 int stb__alloc_count;
7262 
7263 stb_malloc_record stb__alloc_history[STB_MALLOC_HISTORY_COUNT];
7264 int stb__history_pos;
7265 
7266 static int stb__hashfind(void *p)
7267 {
7268    stb_uint32 h = stb_hashptr(p);
7269    int s,n = h & stb__alloc_mask;
7270    if (stb__allocations[n].p == p)
7271       return n;
7272    s = stb_rehash(h)|1;
7273    for(;;) {
7274       if (stb__allocations[n].p == NULL)
7275          return -1;
7276       n = (n+s) & stb__alloc_mask;
7277       if (stb__allocations[n].p == p)
7278          return n;
7279    }
7280 }
7281 
7282 int stb_wrapper_allocsize(void *p)
7283 {
7284    int n = stb__hashfind(p);
7285    if (n < 0) return 0;
7286    return stb__allocations[n].size;
7287 }
7288 
7289 static int stb__historyfind(void *p)
7290 {
7291    int n = stb__history_pos;
7292    int i;
7293    for (i=0; i < STB_MALLOC_HISTORY_COUNT; ++i) {
7294       if (--n < 0) n = STB_MALLOC_HISTORY_COUNT-1;
7295       if (stb__alloc_history[n].p == p)
7296          return n;
7297    }
7298    return -1;
7299 }
7300 
7301 static void stb__add_alloc(void *p, int sz, char *file, int line);
7302 static void stb__grow_alloc(void)
7303 {
7304    int i,old_num = stb__alloc_size;
7305    stb_malloc_record *old = stb__allocations;
7306    if (stb__alloc_size == 0)
7307       stb__alloc_size = 64;
7308    else
7309       stb__alloc_size *= 2;
7310 
7311    stb__allocations = (stb_malloc_record *) stb__realloc_raw(NULL, stb__alloc_size * sizeof(stb__allocations[0]));
7312    if (stb__allocations == NULL)
7313       stb_fatal("Internal error: couldn't grow malloc wrapper table");
7314    memset(stb__allocations, 0, stb__alloc_size * sizeof(stb__allocations[0]));
7315    stb__alloc_limit = (stb__alloc_size*3)>>2;
7316    stb__alloc_mask = stb__alloc_size-1;
7317 
7318    stb__alloc_count = 0;
7319 
7320    for (i=0; i < old_num; ++i)
7321       if (old[i].p > STB_DEL) {
7322          stb__add_alloc(old[i].p, old[i].size, old[i].file, old[i].line);
7323          assert(stb__hashfind(old[i].p) >= 0);
7324       }
7325    for (i=0; i < old_num; ++i)
7326       if (old[i].p > STB_DEL)
7327          assert(stb__hashfind(old[i].p) >= 0);
7328    stb__realloc_raw(old, 0);
7329 }
7330 
7331 static void stb__add_alloc(void *p, int sz, char *file, int line)
7332 {
7333    stb_uint32 h;
7334    int n;
7335    if (stb__alloc_count >= stb__alloc_limit)
7336       stb__grow_alloc();
7337    h = stb_hashptr(p);
7338    n = h & stb__alloc_mask;
7339    if (stb__allocations[n].p > STB_DEL) {
7340       int s = stb_rehash(h)|1;
7341       do {
7342          n = (n+s) & stb__alloc_mask;
7343       } while (stb__allocations[n].p > STB_DEL);
7344    }
7345    assert(stb__allocations[n].p == NULL || stb__allocations[n].p == STB_DEL);
7346    stb__allocations[n].p = p;
7347    stb__allocations[n].size = sz;
7348    stb__allocations[n].line = line;
7349    stb__allocations[n].file = file;
7350    ++stb__alloc_count;
7351 }
7352 
7353 static void stb__remove_alloc(int n, char *file, int line)
7354 {
7355    stb__alloc_history[stb__history_pos] = stb__allocations[n];
7356    stb__alloc_history[stb__history_pos].file = file;
7357    stb__alloc_history[stb__history_pos].line = line;
7358    if (++stb__history_pos == STB_MALLOC_HISTORY_COUNT)
7359       stb__history_pos = 0;
7360    stb__allocations[n].p = STB_DEL;
7361    --stb__alloc_count;
7362 }
7363 
7364 void stb_wrapper_malloc(void *p, int sz, char *file, int line)
7365 {
7366    if (!p) return;
7367    stb__add_alloc(p,sz,file,line);
7368 }
7369 
7370 void stb_wrapper_free(void *p, char *file, int line)
7371 {
7372    int n;
7373 
7374    if (p == NULL) return;
7375 
7376    n = stb__hashfind(p);
7377 
7378    if (n >= 0)
7379       stb__remove_alloc(n, file, line);
7380    else {
7381       // tried to free something we hadn't allocated!
7382       n = stb__historyfind(p);
7383       assert(0); /* NOTREACHED */
7384       if (n >= 0)
7385          stb_fatal("Attempted to free %d-byte block %p at %s:%d previously freed/realloced at %s:%d",
7386                        stb__alloc_history[n].size, p,
7387                        file, line,
7388                        stb__alloc_history[n].file, stb__alloc_history[n].line);
7389       else
7390          stb_fatal("Attempted to free unknown block %p at %s:%d", p, file,line);
7391    }
7392 }
7393 
7394 void stb_wrapper_check(void *p)
7395 {
7396    int n;
7397 
7398    if (p == NULL) return;
7399 
7400    n = stb__hashfind(p);
7401 
7402    if (n >= 0) return;
7403 
7404    for (n=0; n < stb__alloc_size; ++n)
7405       if (stb__allocations[n].p == p)
7406          stb_fatal("Internal error: pointer %p was allocated, but hash search failed", p);
7407 
7408    // tried to free something that wasn't allocated!
7409    n = stb__historyfind(p);
7410    if (n >= 0)
7411       stb_fatal("Checked %d-byte block %p previously freed/realloced at %s:%d",
7412                     stb__alloc_history[n].size, p,
7413                     stb__alloc_history[n].file, stb__alloc_history[n].line);
7414    stb_fatal("Checked unknown block %p");
7415 }
7416 
7417 void stb_wrapper_realloc(void *p, void *q, int sz, char *file, int line)
7418 {
7419    int n;
7420    if (p == NULL) { stb_wrapper_malloc(q, sz, file, line); return; }
7421    if (q == NULL) return; // nothing happened
7422 
7423    n = stb__hashfind(p);
7424    if (n == -1) {
7425       // tried to free something we hadn't allocated!
7426       // this is weird, though, because we got past the realloc!
7427       n = stb__historyfind(p);
7428       assert(0); /* NOTREACHED */
7429       if (n >= 0)
7430          stb_fatal("Attempted to realloc %d-byte block %p at %s:%d previously freed/realloced at %s:%d",
7431                        stb__alloc_history[n].size, p,
7432                        file, line,
7433                        stb__alloc_history[n].file, stb__alloc_history[n].line);
7434       else
7435          stb_fatal("Attempted to realloc unknown block %p at %s:%d", p, file,line);
7436    } else {
7437       if (q == p) {
7438          stb__allocations[n].size = sz;
7439          stb__allocations[n].file = file;
7440          stb__allocations[n].line = line;
7441       } else {
7442          stb__remove_alloc(n, file, line);
7443          stb__add_alloc(q,sz,file,line);
7444       }
7445    }
7446 }
7447 
7448 void stb_wrapper_listall(void (*func)(void *ptr, int sz, char *file, int line))
7449 {
7450    int i;
7451    for (i=0; i < stb__alloc_size; ++i)
7452       if (stb__allocations[i].p > STB_DEL)
7453          func(stb__allocations[i].p   , stb__allocations[i].size,
7454               stb__allocations[i].file, stb__allocations[i].line);
7455 }
7456 
7457 void stb_wrapper_dump(char *filename)
7458 {
7459    int i;
7460    FILE *f = fopen(filename, "w");
7461    if (!f) return;
7462    for (i=0; i < stb__alloc_size; ++i)
7463       if (stb__allocations[i].p > STB_DEL)
7464          fprintf(f, "%p %7d - %4d %s\n",
7465             stb__allocations[i].p   , stb__allocations[i].size,
7466             stb__allocations[i].line, stb__allocations[i].file);
7467 }
7468 #endif // STB_DEFINE
7469 
7470 
7471 //////////////////////////////////////////////////////////////////////////////
7472 //
7473 //                  stb_pointer_set
7474 //
7475 //
7476 // For data structures that support querying by key, data structure
7477 // classes always hand-wave away the issue of what to do if two entries
7478 // have the same key: basically, store a linked list of all the nodes
7479 // which have the same key (a LISP-style list).
7480 //
7481 // The thing is, it's not that trivial. If you have an O(log n)
7482 // lookup data structure, but then n/4 items have the same value,
7483 // you don't want to spend O(n) time scanning that list when
7484 // deleting an item if you already have a pointer to the item.
7485 // (You have to spend O(n) time enumerating all the items with
7486 // a given key, sure, and you can't accelerate deleting a particular
7487 // item if you only have the key, not a pointer to the item.)
7488 //
7489 // I'm going to call this data structure, whatever it turns out to
7490 // be, a "pointer set", because we don't store any associated data for
7491 // items in this data structure, we just answer the question of
7492 // whether an item is in it or not (it's effectively one bit per pointer).
7493 // Technically they don't have to be pointers; you could cast ints
7494 // to (void *) if you want, but you can't store 0 or 1 because of the
7495 // hash table.
7496 //
7497 // Since the fastest data structure we might want to add support for
7498 // identical-keys to is a hash table with O(1)-ish lookup time,
7499 // that means that the conceptual "linked list of all items with
7500 // the same indexed value" that we build needs to have the same
7501 // performance; that way when we index a table we think is arbitrary
7502 // ints, but in fact half of them are 0, we don't get screwed.
7503 //
7504 // Therefore, it needs to be a hash table, at least when it gets
7505 // large. On the other hand, when the data has totally arbitrary ints
7506 // or floats, there won't be many collisions, and we'll have tons of
7507 // 1-item bitmaps. That will be grossly inefficient as hash tables;
7508 // trade-off; the hash table is reasonably efficient per-item when
7509 // it's large, but not when it's small. So we need to do something
7510 // Judy-like and use different strategies depending on the size.
7511 //
7512 // Like Judy, we'll use the bottom bit to encode the strategy:
7513 //
7514 //      bottom bits:
7515 //          00     -   direct pointer
7516 //          01     -   4-item bucket (16 bytes, no length, NULLs)
7517 //          10     -   N-item array
7518 //          11     -   hash table
7519 
7520 typedef struct stb_ps stb_ps;
7521 
7522 STB_EXTERN int      stb_ps_find  (stb_ps *ps, void *value);
7523 STB_EXTERN stb_ps * stb_ps_add   (stb_ps *ps, void *value);
7524 STB_EXTERN stb_ps * stb_ps_remove(stb_ps *ps, void *value);
7525 STB_EXTERN stb_ps * stb_ps_remove_any(stb_ps *ps, void **value);
7526 STB_EXTERN void     stb_ps_delete(stb_ps *ps);
7527 STB_EXTERN int      stb_ps_count (stb_ps *ps);
7528 
7529 STB_EXTERN stb_ps * stb_ps_copy  (stb_ps *ps);
7530 STB_EXTERN int      stb_ps_subset(stb_ps *bigger, stb_ps *smaller);
7531 STB_EXTERN int      stb_ps_eq    (stb_ps *p0, stb_ps *p1);
7532 
7533 STB_EXTERN void ** stb_ps_getlist  (stb_ps *ps, int *count);
7534 STB_EXTERN int     stb_ps_writelist(stb_ps *ps, void **list, int size );
7535 
7536 // enum and fastlist don't allocate storage, but you must consume the
7537 // list before there's any chance the data structure gets screwed up;
7538 STB_EXTERN int     stb_ps_enum     (stb_ps *ps, void *data,
7539                                        int (*func)(void *value, void*data) );
7540 STB_EXTERN void ** stb_ps_fastlist(stb_ps *ps, int *count);
7541 //  result:
7542 //     returns a list, *count is the length of that list,
7543 //     but some entries of the list may be invalid;
7544 //     test with 'stb_ps_fastlist_valid(x)'
7545 
7546 #define stb_ps_fastlist_valid(x)   ((stb_uinta) (x) > 1)
7547 
7548 #ifdef STB_DEFINE
7549 
7550 enum
7551 {
7552    STB_ps_direct = 0,
7553    STB_ps_bucket = 1,
7554    STB_ps_array  = 2,
7555    STB_ps_hash   = 3,
7556 };
7557 
7558 #define STB_BUCKET_SIZE  4
7559 
7560 typedef struct
7561 {
7562    void *p[STB_BUCKET_SIZE];
7563 } stb_ps_bucket;
7564 #define GetBucket(p)    ((stb_ps_bucket *) ((char *) (p) - STB_ps_bucket))
7565 #define EncodeBucket(p) ((stb_ps *) ((char *) (p) + STB_ps_bucket))
7566 
7567 static void stb_bucket_free(stb_ps_bucket *b)
7568 {
7569    free(b);
7570 }
7571 
7572 static stb_ps_bucket *stb_bucket_create2(void *v0, void *v1)
7573 {
7574    stb_ps_bucket *b = (stb_ps_bucket*) malloc(sizeof(*b));
7575    b->p[0] = v0;
7576    b->p[1] = v1;
7577    b->p[2] = NULL;
7578    b->p[3] = NULL;
7579    return b;
7580 }
7581 
7582 static stb_ps_bucket * stb_bucket_create3(void **v)
7583 {
7584    stb_ps_bucket *b = (stb_ps_bucket*) malloc(sizeof(*b));
7585    b->p[0] = v[0];
7586    b->p[1] = v[1];
7587    b->p[2] = v[2];
7588    b->p[3] = NULL;
7589    return b;
7590 }
7591 
7592 
7593 // could use stb_arr, but this will save us memory
7594 typedef struct
7595 {
7596    int count;
7597    void *p[1];
7598 } stb_ps_array;
7599 #define GetArray(p)     ((stb_ps_array *) ((char *) (p) - STB_ps_array))
7600 #define EncodeArray(p)  ((stb_ps *) ((char *) (p) + STB_ps_array))
7601 
7602 static int stb_ps_array_max = 13;
7603 
7604 typedef struct
7605 {
7606    int size, mask;
7607    int count, count_deletes;
7608    int grow_threshhold;
7609    int shrink_threshhold;
7610    int rehash_threshhold;
7611    int any_offset;
7612    void *table[1];
7613 } stb_ps_hash;
7614 #define GetHash(p)      ((stb_ps_hash *) ((char *) (p) - STB_ps_hash))
7615 #define EncodeHash(p)   ((stb_ps *) ((char *) (p) + STB_ps_hash))
7616 
7617 #define stb_ps_empty(v)   (((stb_uint32) v) <= 1)
7618 
7619 static stb_ps_hash *stb_ps_makehash(int size, int old_size, void **old_data)
7620 {
7621    int i;
7622    stb_ps_hash *h = (stb_ps_hash *) malloc(sizeof(*h) + (size-1) * sizeof(h->table[0]));
7623    assert(stb_is_pow2(size));
7624    h->size = size;
7625    h->mask = size-1;
7626    h->shrink_threshhold = (int) (0.3f * size);
7627    h->  grow_threshhold = (int) (0.8f * size);
7628    h->rehash_threshhold = (int) (0.9f * size);
7629    h->count = 0;
7630    h->count_deletes = 0;
7631    h->any_offset = 0;
7632    memset(h->table, 0, size * sizeof(h->table[0]));
7633    for (i=0; i < old_size; ++i)
7634       if (!stb_ps_empty(old_data[i]))
7635          stb_ps_add(EncodeHash(h), old_data[i]);
7636    return h;
7637 }
7638 
7639 void stb_ps_delete(stb_ps *ps)
7640 {
7641    switch (3 & (int) ps) {
7642       case STB_ps_direct: break;
7643       case STB_ps_bucket: stb_bucket_free(GetBucket(ps)); break;
7644       case STB_ps_array : free(GetArray(ps)); break;
7645       case STB_ps_hash  : free(GetHash(ps)); break;
7646    }
7647 }
7648 
7649 stb_ps *stb_ps_copy(stb_ps *ps)
7650 {
7651    int i;
7652    // not a switch: order based on expected performance/power-law distribution
7653    switch (3 & (int) ps) {
7654       case STB_ps_direct: return ps;
7655       case STB_ps_bucket: {
7656          stb_ps_bucket *n = (stb_ps_bucket *) malloc(sizeof(*n));
7657          *n = *GetBucket(ps);
7658          return EncodeBucket(n);
7659       }
7660       case STB_ps_array: {
7661          stb_ps_array *a = GetArray(ps);
7662          stb_ps_array *n = (stb_ps_array *) malloc(sizeof(*n) + stb_ps_array_max * sizeof(n->p[0]));
7663          n->count = a->count;
7664          for (i=0; i < a->count; ++i)
7665             n->p[i] = a->p[i];
7666          return EncodeArray(n);
7667       }
7668       case STB_ps_hash: {
7669          stb_ps_hash *h = GetHash(ps);
7670          stb_ps_hash *n = stb_ps_makehash(h->size, h->size, h->table);
7671          return EncodeHash(n);
7672       }
7673    }
7674    assert(0); /* NOTREACHED */
7675    return NULL;
7676 }
7677 
7678 int stb_ps_find(stb_ps *ps, void *value)
7679 {
7680    int i, code = 3 & (int) ps;
7681     assert((3 & (int) value) == STB_ps_direct);
7682    assert(stb_ps_fastlist_valid(value));
7683    // not a switch: order based on expected performance/power-law distribution
7684    if (code == STB_ps_direct)
7685       return value == ps;
7686    if (code == STB_ps_bucket) {
7687       stb_ps_bucket *b = GetBucket(ps);
7688       assert(STB_BUCKET_SIZE == 4);
7689       if (b->p[0] == value || b->p[1] == value ||
7690           b->p[2] == value || b->p[3] == value)
7691           return STB_TRUE;
7692       return STB_FALSE;
7693    }
7694    if (code == STB_ps_array) {
7695       stb_ps_array *a = GetArray(ps);
7696       for (i=0; i < a->count; ++i)
7697          if (a->p[i] == value)
7698             return STB_TRUE;
7699       return STB_FALSE;
7700    } else {
7701       stb_ps_hash *h = GetHash(ps);
7702       stb_uint32 hash = stb_hashptr(value);
7703       stb_uint32 s, n = hash & h->mask;
7704       void **t = h->table;
7705       if (t[n] == value) return STB_TRUE;
7706       if (t[n] == NULL) return STB_FALSE;
7707       s = stb_rehash(hash) | 1;
7708       do {
7709          n = (n + s) & h->mask;
7710          if (t[n] == value) return STB_TRUE;
7711       } while (t[n] != NULL);
7712       return STB_FALSE;
7713    }
7714 }
7715 
7716 stb_ps *  stb_ps_add   (stb_ps *ps, void *value)
7717 {
7718    #ifdef STB_DEBUG
7719    assert(!stb_ps_find(ps,value));
7720    #endif
7721    if (value == NULL) return ps; // ignore NULL adds to avoid bad breakage
7722    assert((3 & (int) value) == STB_ps_direct);
7723    assert(stb_ps_fastlist_valid(value));
7724    assert(value != STB_DEL);     // STB_DEL is less likely
7725 
7726    switch (3 & (int) ps) {
7727       case STB_ps_direct:
7728          if (ps == NULL) return (stb_ps *) value;
7729          return EncodeBucket(stb_bucket_create2(ps,value));
7730 
7731       case STB_ps_bucket: {
7732          stb_ps_bucket *b = GetBucket(ps);
7733          stb_ps_array  *a;
7734          assert(STB_BUCKET_SIZE == 4);
7735          if (b->p[0] == NULL) { b->p[0] = value; return ps; }
7736          if (b->p[1] == NULL) { b->p[1] = value; return ps; }
7737          if (b->p[2] == NULL) { b->p[2] = value; return ps; }
7738          if (b->p[3] == NULL) { b->p[3] = value; return ps; }
7739          a = (stb_ps_array *) malloc(sizeof(*a) + 7 * sizeof(a->p[0])); // 8 slots, must be 2^k
7740          memcpy(a->p, b, sizeof(*b));
7741          a->p[4] = value;
7742          a->count = 5;
7743          stb_bucket_free(b);
7744          return EncodeArray(a);
7745       }
7746 
7747       case STB_ps_array: {
7748          stb_ps_array *a = GetArray(ps);
7749          if (a->count == stb_ps_array_max) {
7750             // promote from array to hash
7751             stb_ps_hash *h = stb_ps_makehash(2 << stb_log2_ceil(a->count), a->count, a->p);
7752             free(a);
7753             return stb_ps_add(EncodeHash(h), value);
7754          }
7755          // do we need to resize the array? the array doubles in size when it
7756          // crosses a power-of-two
7757          if ((a->count & (a->count-1))==0) {
7758             int newsize = a->count*2;
7759             // clamp newsize to max if:
7760             //    1. it's larger than max
7761             //    2. newsize*1.5 is larger than max (to avoid extra resizing)
7762             if (newsize + a->count > stb_ps_array_max)
7763                newsize = stb_ps_array_max;
7764             a = (stb_ps_array *) realloc(a, sizeof(*a) + (newsize-1) * sizeof(a->p[0]));
7765          }
7766          a->p[a->count++] = value;
7767          return EncodeArray(a);
7768       }
7769       case STB_ps_hash: {
7770          stb_ps_hash *h = GetHash(ps);
7771          stb_uint32 hash = stb_hashptr(value);
7772          stb_uint32 n = hash & h->mask;
7773          void **t = h->table;
7774          // find first NULL or STB_DEL entry
7775          if (!stb_ps_empty(t[n])) {
7776             stb_uint32 s = stb_rehash(hash) | 1;
7777             do {
7778                n = (n + s) & h->mask;
7779             } while (!stb_ps_empty(t[n]));
7780          }
7781          if (t[n] == STB_DEL)
7782             -- h->count_deletes;
7783          t[n] = value;
7784          ++ h->count;
7785          if (h->count == h->grow_threshhold) {
7786             stb_ps_hash *h2 = stb_ps_makehash(h->size*2, h->size, t);
7787             free(h);
7788             return EncodeHash(h2);
7789          }
7790          if (h->count + h->count_deletes == h->rehash_threshhold) {
7791             stb_ps_hash *h2 = stb_ps_makehash(h->size, h->size, t);
7792             free(h);
7793             return EncodeHash(h2);
7794          }
7795          return ps;
7796       }
7797    }
7798    return NULL; /* NOTREACHED */
7799 }
7800 
7801 stb_ps *stb_ps_remove(stb_ps *ps, void *value)
7802 {
7803    #ifdef STB_DEBUG
7804    assert(stb_ps_find(ps, value));
7805    #endif
7806    assert((3 & (int) value) == STB_ps_direct);
7807    if (value == NULL) return ps; // ignore NULL removes to avoid bad breakage
7808    switch (3 & (int) ps) {
7809       case STB_ps_direct:
7810          return ps == value ? NULL : ps;
7811       case STB_ps_bucket: {
7812          stb_ps_bucket *b = GetBucket(ps);
7813          int count=0;
7814          assert(STB_BUCKET_SIZE == 4);
7815          if (b->p[0] == value) b->p[0] = NULL; else count += (b->p[0] != NULL);
7816          if (b->p[1] == value) b->p[1] = NULL; else count += (b->p[1] != NULL);
7817          if (b->p[2] == value) b->p[2] = NULL; else count += (b->p[2] != NULL);
7818          if (b->p[3] == value) b->p[3] = NULL; else count += (b->p[3] != NULL);
7819          if (count == 1) { // shrink bucket at size 1
7820             value = b->p[0];
7821             if (value == NULL) value = b->p[1];
7822             if (value == NULL) value = b->p[2];
7823             if (value == NULL) value = b->p[3];
7824             assert(value != NULL);
7825             stb_bucket_free(b);
7826             return (stb_ps *) value; // return STB_ps_direct of value
7827          }
7828          return ps;
7829       }
7830       case STB_ps_array: {
7831          stb_ps_array *a = GetArray(ps);
7832          int i;
7833          for (i=0; i < a->count; ++i) {
7834             if (a->p[i] == value) {
7835                a->p[i] = a->p[--a->count];
7836                if (a->count == 3) { // shrink to bucket!
7837                   stb_ps_bucket *b = stb_bucket_create3(a->p);
7838                   free(a);
7839                   return EncodeBucket(b);
7840                }
7841                return ps;
7842             }
7843          }
7844          return ps;
7845       }
7846       case STB_ps_hash: {
7847          stb_ps_hash *h = GetHash(ps);
7848          stb_uint32 hash = stb_hashptr(value);
7849          stb_uint32 s, n = hash & h->mask;
7850          void **t = h->table;
7851          if (t[n] != value) {
7852             s = stb_rehash(hash) | 1;
7853             do {
7854                n = (n + s) & h->mask;
7855             } while (t[n] != value);
7856          }
7857          t[n] = STB_DEL;
7858          -- h->count;
7859          ++ h->count_deletes;
7860          // should we shrink down to an array?
7861          if (h->count < stb_ps_array_max) {
7862             int n = 1 << stb_log2_floor(stb_ps_array_max);
7863             if (h->count < n) {
7864                stb_ps_array *a = (stb_ps_array *) malloc(sizeof(*a) + (n-1) * sizeof(a->p[0]));
7865                int i,j=0;
7866                for (i=0; i < h->size; ++i)
7867                   if (!stb_ps_empty(t[i]))
7868                      a->p[j++] = t[i];
7869                assert(j == h->count);
7870                a->count = j;
7871                free(h);
7872                return EncodeArray(a);
7873             }
7874          }
7875          if (h->count == h->shrink_threshhold) {
7876             stb_ps_hash *h2 = stb_ps_makehash(h->size >> 1, h->size, t);
7877             free(h);
7878             return EncodeHash(h2);
7879          }
7880          return ps;
7881       }
7882    }
7883    return ps; /* NOTREACHED */
7884 }
7885 
7886 stb_ps *stb_ps_remove_any(stb_ps *ps, void **value)
7887 {
7888    assert(ps != NULL);
7889    switch (3 & (int) ps) {
7890       case STB_ps_direct:
7891          *value = ps;
7892          return NULL;
7893       case STB_ps_bucket: {
7894          stb_ps_bucket *b = GetBucket(ps);
7895          int count=0, slast=0, last=0;
7896          assert(STB_BUCKET_SIZE == 4);
7897          if (b->p[0]) { ++count;               last = 0; }
7898          if (b->p[1]) { ++count; slast = last; last = 1; }
7899          if (b->p[2]) { ++count; slast = last; last = 2; }
7900          if (b->p[3]) { ++count; slast = last; last = 3; }
7901          *value = b->p[last];
7902          b->p[last] = 0;
7903          if (count == 2) {
7904             void *leftover = b->p[slast]; // second to last
7905             stb_bucket_free(b);
7906             return (stb_ps *) leftover;
7907          }
7908          return ps;
7909       }
7910       case STB_ps_array: {
7911          stb_ps_array *a = GetArray(ps);
7912          *value = a->p[a->count-1];
7913          if (a->count == 4)
7914             return stb_ps_remove(ps, *value);
7915          --a->count;
7916          return ps;
7917       }
7918       case STB_ps_hash: {
7919          stb_ps_hash *h = GetHash(ps);
7920          void **t = h->table;
7921          stb_uint32 n = h->any_offset;
7922          while (stb_ps_empty(t[n]))
7923             n = (n + 1) & h->mask;
7924          *value = t[n];
7925          h->any_offset = (n+1) & h->mask;
7926          // check if we need to skip down to the previous type
7927          if (h->count-1 < stb_ps_array_max || h->count-1 == h->shrink_threshhold)
7928             return stb_ps_remove(ps, *value);
7929          t[n] = STB_DEL;
7930          -- h->count;
7931          ++ h->count_deletes;
7932          return ps;
7933       }
7934    }
7935    return ps; /* NOTREACHED */
7936 }
7937 
7938 
7939 void ** stb_ps_getlist(stb_ps *ps, int *count)
7940 {
7941    int i,n=0;
7942    void **p = NULL;
7943    switch (3 & (int) ps) {
7944       case STB_ps_direct:
7945          if (ps == NULL) { *count = 0; return NULL; }
7946          p = (void **) malloc(sizeof(*p) * 1);
7947          p[0] = ps;
7948          *count = 1;
7949          return p;
7950       case STB_ps_bucket: {
7951          stb_ps_bucket *b = GetBucket(ps);
7952          p = (void **) malloc(sizeof(*p) * STB_BUCKET_SIZE);
7953          for (i=0; i < STB_BUCKET_SIZE; ++i)
7954             if (b->p[i] != NULL)
7955                p[n++] = b->p[i];
7956          break;
7957       }
7958       case STB_ps_array: {
7959          stb_ps_array *a = GetArray(ps);
7960          p = (void **) malloc(sizeof(*p) * a->count);
7961          memcpy(p, a->p, sizeof(*p) * a->count);
7962          *count = a->count;
7963          return p;
7964       }
7965       case STB_ps_hash: {
7966          stb_ps_hash *h = GetHash(ps);
7967          p = (void **) malloc(sizeof(*p) * h->count);
7968          for (i=0; i < h->size; ++i)
7969             if (!stb_ps_empty(h->table[i]))
7970                p[n++] = h->table[i];
7971          break;
7972       }
7973    }
7974    *count = n;
7975    return p;
7976 }
7977 
7978 int stb_ps_writelist(stb_ps *ps, void **list, int size )
7979 {
7980    int i,n=0;
7981    switch (3 & (int) ps) {
7982       case STB_ps_direct:
7983          if (ps == NULL || size <= 0) return 0;
7984          list[0] = ps;
7985          return 1;
7986       case STB_ps_bucket: {
7987          stb_ps_bucket *b = GetBucket(ps);
7988          for (i=0; i < STB_BUCKET_SIZE; ++i)
7989             if (b->p[i] != NULL && n < size)
7990                list[n++] = b->p[i];
7991          return n;
7992       }
7993       case STB_ps_array: {
7994          stb_ps_array *a = GetArray(ps);
7995          n = stb_min(size, a->count);
7996          memcpy(list, a->p, sizeof(*list) * n);
7997          return n;
7998       }
7999       case STB_ps_hash: {
8000          stb_ps_hash *h = GetHash(ps);
8001          if (size <= 0) return 0;
8002          for (i=0; i < h->count; ++i) {
8003             if (!stb_ps_empty(h->table[i])) {
8004                list[n++] = h->table[i];
8005                if (n == size) break;
8006             }
8007          }
8008          return n;
8009       }
8010    }
8011    return 0; /* NOTREACHED */
8012 }
8013 
8014 int stb_ps_enum(stb_ps *ps, void *data, int (*func)(void *value, void *data))
8015 {
8016    int i;
8017    switch (3 & (int) ps) {
8018       case STB_ps_direct:
8019          if (ps == NULL) return STB_TRUE;
8020          return func(ps, data);
8021       case STB_ps_bucket: {
8022          stb_ps_bucket *b = GetBucket(ps);
8023          for (i=0; i < STB_BUCKET_SIZE; ++i)
8024             if (b->p[i] != NULL)
8025                if (!func(b->p[i], data))
8026                   return STB_FALSE;
8027          return STB_TRUE;
8028       }
8029       case STB_ps_array: {
8030          stb_ps_array *a = GetArray(ps);
8031          for (i=0; i < a->count; ++i)
8032             if (!func(a->p[i], data))
8033                return STB_FALSE;
8034          return STB_TRUE;
8035       }
8036       case STB_ps_hash: {
8037          stb_ps_hash *h = GetHash(ps);
8038          for (i=0; i < h->count; ++i)
8039             if (!stb_ps_empty(h->table[i]))
8040                if (!func(h->table[i], data))
8041                   return STB_FALSE;
8042          return STB_TRUE;
8043       }
8044    }
8045    return STB_TRUE; /* NOTREACHED */
8046 }
8047 
8048 int stb_ps_count (stb_ps *ps)
8049 {
8050    switch (3 & (int) ps) {
8051       case STB_ps_direct:
8052          return ps != NULL;
8053       case STB_ps_bucket: {
8054          stb_ps_bucket *b = GetBucket(ps);
8055          return (b->p[0] != NULL) + (b->p[1] != NULL) +
8056                 (b->p[2] != NULL) + (b->p[3] != NULL);
8057       }
8058       case STB_ps_array: {
8059          stb_ps_array *a = GetArray(ps);
8060          return a->count;
8061       }
8062       case STB_ps_hash: {
8063          stb_ps_hash *h = GetHash(ps);
8064          return h->count;
8065       }
8066    }
8067    return 0;
8068 }
8069 
8070 void ** stb_ps_fastlist(stb_ps *ps, int *count)
8071 {
8072    static void *storage;
8073 
8074    switch (3 & (int) ps) {
8075       case STB_ps_direct:
8076          if (ps == NULL) { *count = 0; return NULL; }
8077          storage = ps;
8078          *count = 1;
8079          return &storage;
8080       case STB_ps_bucket: {
8081          stb_ps_bucket *b = GetBucket(ps);
8082          *count = STB_BUCKET_SIZE;
8083          return b->p;
8084       }
8085       case STB_ps_array: {
8086          stb_ps_array *a = GetArray(ps);
8087          *count = a->count;
8088          return a->p;
8089       }
8090       case STB_ps_hash: {
8091          stb_ps_hash *h = GetHash(ps);
8092          *count = h->size;
8093          return h->table;
8094       }
8095    }
8096    return NULL; /* NOTREACHED */
8097 }
8098 
8099 int stb_ps_subset(stb_ps *bigger, stb_ps *smaller)
8100 {
8101    int i, listlen;
8102    void **list = stb_ps_fastlist(smaller, &listlen);
8103    for(i=0; i < listlen; ++i)
8104       if (stb_ps_fastlist_valid(list[i]))
8105          if (!stb_ps_find(bigger, list[i]))
8106             return 0;
8107    return 1;
8108 }
8109 
8110 int stb_ps_eq(stb_ps *p0, stb_ps *p1)
8111 {
8112    if (stb_ps_count(p0) != stb_ps_count(p1))
8113       return 0;
8114    return stb_ps_subset(p0, p1);
8115 }
8116 
8117 #undef GetBucket
8118 #undef GetArray
8119 #undef GetHash
8120 
8121 #undef EncodeBucket
8122 #undef EncodeArray
8123 #undef EncodeHash
8124 
8125 #endif
8126 
8127 
8128 //////////////////////////////////////////////////////////////////////////////
8129 //
8130 //               Random Numbers via Meresenne Twister or LCG
8131 //
8132 
8133 STB_EXTERN unsigned long stb_srandLCG(unsigned long seed);
8134 STB_EXTERN unsigned long stb_randLCG(void);
8135 STB_EXTERN double        stb_frandLCG(void);
8136 
8137 STB_EXTERN void          stb_srand(unsigned long seed);
8138 STB_EXTERN unsigned long stb_rand(void);
8139 STB_EXTERN double        stb_frand(void);
8140 STB_EXTERN void          stb_shuffle(void *p, size_t n, size_t sz,
8141                                         unsigned long seed);
8142 STB_EXTERN void stb_reverse(void *p, size_t n, size_t sz);
8143 
8144 STB_EXTERN unsigned long stb_randLCG_explicit(unsigned long seed);
8145 
8146 #define stb_rand_define(x,y)                                         \
8147                                                                      \
8148    unsigned long x(void)                                             \
8149    {                                                                 \
8150       static unsigned long stb__rand = y;                            \
8151       stb__rand = stb__rand * 2147001325 + 715136305; /* BCPL */     \
8152       return 0x31415926 ^ ((stb__rand >> 16) + (stb__rand << 16));   \
8153    }
8154 
8155 #ifdef STB_DEFINE
8156 unsigned long stb_randLCG_explicit(unsigned long seed)
8157 {
8158    return seed * 2147001325 + 715136305;
8159 }
8160 
8161 static unsigned long stb__rand_seed=0;
8162 
8163 unsigned long stb_srandLCG(unsigned long seed)
8164 {
8165    unsigned long previous = stb__rand_seed;
8166    stb__rand_seed = seed;
8167    return previous;
8168 }
8169 
8170 unsigned long stb_randLCG(void)
8171 {
8172    stb__rand_seed = stb__rand_seed * 2147001325 + 715136305; // BCPL generator
8173    // shuffle non-random bits to the middle, and xor to decorrelate with seed
8174    return 0x31415926 ^ ((stb__rand_seed >> 16) + (stb__rand_seed << 16));
8175 }
8176 
8177 double stb_frandLCG(void)
8178 {
8179    return stb_randLCG() / ((double) (1 << 16) * (1 << 16));
8180 }
8181 
8182 void stb_shuffle(void *p, size_t n, size_t sz, unsigned long seed)
8183 {
8184    char *a;
8185    unsigned long old_seed;
8186    int i;
8187    if (seed)
8188       old_seed = stb_srandLCG(seed);
8189    a = (char *) p + (n-1) * sz;
8190 
8191    for (i=n; i > 1; --i) {
8192       int j = stb_randLCG() % i;
8193       stb_swap(a, (char *) p + j * sz, sz);
8194       a -= sz;
8195    }
8196    if (seed)
8197       stb_srandLCG(old_seed);
8198 }
8199 
8200 void stb_reverse(void *p, size_t n, size_t sz)
8201 {
8202    int i,j = n-1;
8203    for (i=0; i < j; ++i,--j) {
8204       stb_swap((char *) p + i * sz, (char *) p + j * sz, sz);
8205    }
8206 }
8207 
8208 // public domain Mersenne Twister by Michael Brundage
8209 #define STB__MT_LEN       624
8210 
8211 int stb__mt_index = STB__MT_LEN*sizeof(unsigned long)+1;
8212 unsigned long stb__mt_buffer[STB__MT_LEN];
8213 
8214 void stb_srand(unsigned long seed)
8215 {
8216    int i;
8217    unsigned long old = stb_srandLCG(seed);
8218    for (i = 0; i < STB__MT_LEN; i++)
8219       stb__mt_buffer[i] = stb_randLCG();
8220    stb_srandLCG(old);
8221    stb__mt_index = STB__MT_LEN*sizeof(unsigned long);
8222 }
8223 
8224 #define STB__MT_IA           397
8225 #define STB__MT_IB           (STB__MT_LEN - STB__MT_IA)
8226 #define STB__UPPER_MASK      0x80000000
8227 #define STB__LOWER_MASK      0x7FFFFFFF
8228 #define STB__MATRIX_A        0x9908B0DF
8229 #define STB__TWIST(b,i,j)    ((b)[i] & STB__UPPER_MASK) | ((b)[j] & STB__LOWER_MASK)
8230 #define STB__MAGIC(s)        (((s)&1)*STB__MATRIX_A)
8231 
8232 unsigned long stb_rand()
8233 {
8234    unsigned long * b = stb__mt_buffer;
8235    int idx = stb__mt_index;
8236    unsigned long s,r;
8237    int i;
8238 
8239    if (idx >= STB__MT_LEN*sizeof(unsigned long)) {
8240       if (idx > STB__MT_LEN*sizeof(unsigned long))
8241          stb_srand(0);
8242       idx = 0;
8243       i = 0;
8244       for (; i < STB__MT_IB; i++) {
8245          s = STB__TWIST(b, i, i+1);
8246          b[i] = b[i + STB__MT_IA] ^ (s >> 1) ^ STB__MAGIC(s);
8247       }
8248       for (; i < STB__MT_LEN-1; i++) {
8249          s = STB__TWIST(b, i, i+1);
8250          b[i] = b[i - STB__MT_IB] ^ (s >> 1) ^ STB__MAGIC(s);
8251       }
8252 
8253       s = STB__TWIST(b, STB__MT_LEN-1, 0);
8254       b[STB__MT_LEN-1] = b[STB__MT_IA-1] ^ (s >> 1) ^ STB__MAGIC(s);
8255    }
8256    stb__mt_index = idx + sizeof(unsigned long);
8257 
8258    r = *(unsigned long *)((unsigned char *)b + idx);
8259 
8260    r ^= (r >> 11);
8261    r ^= (r << 7) & 0x9D2C5680;
8262    r ^= (r << 15) & 0xEFC60000;
8263    r ^= (r >> 18);
8264 
8265    return r;
8266 }
8267 
8268 double stb_frand(void)
8269 {
8270    return stb_rand() / ((double) (1 << 16) * (1 << 16));
8271 }
8272 
8273 #endif
8274 
8275 
8276 //////////////////////////////////////////////////////////////////////////////
8277 //
8278 //                        stb_dupe
8279 //
8280 // stb_dupe is a duplicate-finding system for very, very large data
8281 // structures--large enough that sorting is too slow, but not so large
8282 // that we can't keep all the data in memory. using it works as follows:
8283 //
8284 //     1. create an stb_dupe:
8285 //          provide a hash function
8286 //          provide an equality function
8287 //          provide an estimate for the size
8288 //          optionally provide a comparison function
8289 //
8290 //     2. traverse your data, 'adding' pointers to the stb_dupe
8291 //
8292 //     3. finish and ask for duplicates
8293 //
8294 //        the stb_dupe will discard its intermediate data and build
8295 //        a collection of sorted lists of duplicates, with non-duplicate
8296 //        entries omitted entirely
8297 //
8298 //
8299 //  Implementation strategy:
8300 //
8301 //     while collecting the N items, we keep a hash table of approximate
8302 //     size sqrt(N). (if you tell use the N up front, the hash table is
8303 //     just that size exactly)
8304 //
8305 //     each entry in the hash table is just an stb__arr of pointers (no need
8306 //     to use stb_ps, because we don't need to delete from these)
8307 //
8308 //     for step 3, for each entry in the hash table, we apply stb_dupe to it
8309 //     recursively. once the size gets small enough (or doesn't decrease
8310 //     significantly), we switch to either using qsort() on the comparison
8311 //     function, or else we just do the icky N^2 gather
8312 
8313 
8314 typedef struct stb_dupe stb_dupe;
8315 
8316 typedef int (*stb_compare_func)(void *a, void *b);
8317 typedef int (*stb_hash_func)(void *a, unsigned int seed);
8318 
8319 STB_EXTERN void stb_dupe_free(stb_dupe *sd);
8320 STB_EXTERN stb_dupe *stb_dupe_create(stb_hash_func hash,
8321                           stb_compare_func eq, int size, stb_compare_func ineq);
8322 STB_EXTERN void stb_dupe_add(stb_dupe *sd, void *item);
8323 STB_EXTERN void stb_dupe_finish(stb_dupe *sd);
8324 STB_EXTERN int stb_dupe_numsets(stb_dupe *sd);
8325 STB_EXTERN void **stb_dupe_set(stb_dupe *sd, int num);
8326 STB_EXTERN int stb_dupe_set_count(stb_dupe *sd, int num);
8327 
8328 struct stb_dupe
8329 {
8330    void ***hash_table;
8331    int hash_size;
8332    int size_log2;
8333    int population;
8334 
8335    int hash_shift;
8336    stb_hash_func     hash;
8337 
8338    stb_compare_func  eq;
8339    stb_compare_func  ineq;
8340 
8341    void ***dupes;
8342 };
8343 
8344 #ifdef STB_DEFINE
8345 
8346 int stb_dupe_numsets(stb_dupe *sd)
8347 {
8348    assert(sd->hash_table == NULL);
8349    return stb_arr_len(sd->dupes);
8350 }
8351 
8352 void **stb_dupe_set(stb_dupe *sd, int num)
8353 {
8354    assert(sd->hash_table == NULL);
8355    return sd->dupes[num];
8356 }
8357 
8358 int stb_dupe_set_count(stb_dupe *sd, int num)
8359 {
8360    assert(sd->hash_table == NULL);
8361    return stb_arr_len(sd->dupes[num]);
8362 }
8363 
8364 stb_dupe *stb_dupe_create(stb_hash_func hash, stb_compare_func eq, int size,
8365                                               stb_compare_func ineq)
8366 {
8367    int i, hsize;
8368    stb_dupe *sd = (stb_dupe *) malloc(sizeof(*sd));
8369 
8370    sd->size_log2 = 4;
8371    hsize = 1 << sd->size_log2;
8372    while (hsize * hsize < size) {
8373       ++sd->size_log2;
8374       hsize *= 2;
8375    }
8376 
8377    sd->hash = hash;
8378    sd->eq   = eq;
8379    sd->ineq = ineq;
8380    sd->hash_shift = 0;
8381 
8382    sd->population = 0;
8383    sd->hash_size = hsize;
8384    sd->hash_table = (void ***) malloc(sizeof(*sd->hash_table) * hsize);
8385    for (i=0; i < hsize; ++i)
8386       sd->hash_table[i] = NULL;
8387 
8388    sd->dupes = NULL;
8389 
8390    return sd;
8391 }
8392 
8393 void stb_dupe_add(stb_dupe *sd, void *item)
8394 {
8395    stb_uint32 hash = sd->hash(item, sd->hash_shift);
8396    int z = hash & (sd->hash_size-1);
8397    stb_arr_push(sd->hash_table[z], item);
8398    ++sd->population;
8399 }
8400 
8401 void stb_dupe_free(stb_dupe *sd)
8402 {
8403    int i;
8404    for (i=0; i < stb_arr_len(sd->dupes); ++i)
8405       if (sd->dupes[i])
8406          stb_arr_free(sd->dupes[i]);
8407    stb_arr_free(sd->dupes);
8408    free(sd);
8409 }
8410 
8411 static stb_compare_func stb__compare;
8412 
8413 static int stb__dupe_compare(const void *a, const void *b)
8414 {
8415    void *p = *(void **) a;
8416    void *q = *(void **) b;
8417 
8418    return stb__compare(p,q);
8419 }
8420 
8421 void stb_dupe_finish(stb_dupe *sd)
8422 {
8423    int i,j,k;
8424    assert(sd->dupes == NULL);
8425    for (i=0; i < sd->hash_size; ++i) {
8426       void ** list = sd->hash_table[i];
8427       if (list != NULL) {
8428          int n = stb_arr_len(list);
8429          // @TODO: measure to find good numbers instead of just making them up!
8430          int thresh = (sd->ineq ? 200 : 20);
8431          // if n is large enough to be worth it, and n is smaller than
8432          // before (so we can guarantee we'll use a smaller hash table);
8433          // and there are enough hash bits left, assuming full 32-bit hash
8434          if (n > thresh && n < (sd->population >> 3) && sd->hash_shift + sd->size_log2*2 < 32) {
8435 
8436             // recursively process this row using stb_dupe, O(N log log N)
8437 
8438             stb_dupe *d = stb_dupe_create(sd->hash, sd->eq, n, sd->ineq);
8439             d->hash_shift = stb_randLCG_explicit(sd->hash_shift);
8440             for (j=0; j < n; ++j)
8441                stb_dupe_add(d, list[j]);
8442             stb_arr_free(sd->hash_table[i]);
8443             stb_dupe_finish(d);
8444             for (j=0; j < stb_arr_len(d->dupes); ++j) {
8445                stb_arr_push(sd->dupes, d->dupes[j]);
8446                d->dupes[j] = NULL; // take over ownership
8447             }
8448             stb_dupe_free(d);
8449 
8450          } else if (sd->ineq) {
8451 
8452             // process this row using qsort(), O(N log N)
8453             stb__compare = sd->ineq;
8454             qsort(list, n, sizeof(list[0]), stb__dupe_compare);
8455 
8456             // find equal subsequences of the list
8457             for (j=0; j < n-1; ) {
8458                // find a subsequence from j..k
8459                for (k=j; k < n; ++k)
8460                   // only use ineq so eq can be left undefined
8461                   if (sd->ineq(list[j], list[k]))
8462                      break;
8463                // k is the first one not in the subsequence
8464                if (k-j > 1) {
8465                   void **mylist = NULL;
8466                   stb_arr_setlen(mylist, k-j);
8467                   memcpy(mylist, list+j, sizeof(list[j]) * (k-j));
8468                   stb_arr_push(sd->dupes, mylist);
8469                }
8470                j = k;
8471             }
8472             stb_arr_free(sd->hash_table[i]);
8473          } else {
8474 
8475             // process this row using eq(), O(N^2)
8476             for (j=0; j < n; ++j) {
8477                if (list[j] != NULL) {
8478                   void **output  = NULL;
8479                   for (k=j+1; k < n; ++k) {
8480                      if (sd->eq(list[j], list[k])) {
8481                         if (output == NULL)
8482                            stb_arr_push(output, list[j]);
8483                         stb_arr_push(output, list[k]);
8484                         list[k] = NULL;
8485                      }
8486                   }
8487                   list[j] = NULL;
8488                   if (output)
8489                      stb_arr_push(sd->dupes, output);
8490                }
8491             }
8492             stb_arr_free(sd->hash_table[i]);
8493          }
8494       }
8495    }
8496    free(sd->hash_table);
8497    sd->hash_table = NULL;
8498 }
8499 #endif
8500 
8501 //////////////////////////////////////////////////////////////////////////////
8502 //
8503 //                       templatized Sort routine
8504 //
8505 // This is an attempt to implement a templated sorting algorithm.
8506 // To use it, you have to explicitly instantiate it as a _function_,
8507 // then you call that function. This allows the comparison to be inlined,
8508 // giving the sort similar performance to C++ sorts.
8509 //
8510 // It implements quicksort with three-way-median partitioning (generally
8511 // well-behaved), with a final insertion sort pass.
8512 //
8513 // When you define the compare expression, you should assume you have
8514 // elements of your array pointed to by 'a' and 'b', and perform the comparison
8515 // on those. OR you can use one or more statements; first say '0;', then
8516 // write whatever code you want, and compute the result into a variable 'c'.
8517 
8518 #define stb_declare_sort(FUNCNAME, TYPE)    \
8519                        void FUNCNAME(TYPE *p, int n)
8520 #define stb_define_sort(FUNCNAME,TYPE,COMPARE) \
8521                        stb__define_sort(       void, FUNCNAME,TYPE,COMPARE)
8522 #define stb_define_sort_static(FUNCNAME,TYPE,COMPARE) \
8523                        stb__define_sort(static void, FUNCNAME,TYPE,COMPARE)
8524 
8525 #define stb__define_sort(MODE, FUNCNAME, TYPE, COMPARE)                       \
8526                                                                               \
8527 static void STB_(FUNCNAME,_ins_sort)(TYPE *p, int n)                          \
8528 {                                                                             \
8529    int i,j;                                                                   \
8530    for (i=1; i < n; ++i) {                                                    \
8531       TYPE t = p[i], *a = &t;                                                 \
8532       j = i;                                                                  \
8533       while (j > 0) {                                                         \
8534          TYPE *b = &p[j-1];                                                   \
8535          int c = COMPARE;                                                     \
8536          if (!c) break;                                                       \
8537          p[j] = p[j-1];                                                       \
8538          --j;                                                                 \
8539       }                                                                       \
8540       if (i != j)                                                             \
8541          p[j] = t;                                                            \
8542    }                                                                          \
8543 }                                                                             \
8544                                                                               \
8545 static void STB_(FUNCNAME,_quicksort)(TYPE *p, int n)                         \
8546 {                                                                             \
8547    /* threshhold for transitioning to insertion sort */                       \
8548    while (n > 12) {                                                           \
8549       TYPE *a,*b,t;                                                           \
8550       int c01,c12,c,m,i,j;                                                    \
8551                                                                               \
8552       /* compute median of three */                                           \
8553       m = n >> 1;                                                             \
8554       a = &p[0];                                                              \
8555       b = &p[m];                                                              \
8556       c = COMPARE;                                                            \
8557       c01 = c;                                                                \
8558       a = &p[m];                                                              \
8559       b = &p[n-1];                                                            \
8560       c = COMPARE;                                                            \
8561       c12 = c;                                                                \
8562       /* if 0 >= mid >= end, or 0 < mid < end, then use mid */                \
8563       if (c01 != c12) {                                                       \
8564          /* otherwise, we'll need to swap something else to middle */         \
8565          int z;                                                               \
8566          a = &p[0];                                                           \
8567          b = &p[n-1];                                                         \
8568          c = COMPARE;                                                         \
8569          /* 0>mid && mid<n:  0>n => n; 0<n => 0 */                            \
8570          /* 0<mid && mid>n:  0>n => 0; 0<n => n */                            \
8571          z = (c == c12) ? 0 : n-1;                                            \
8572          t = p[z];                                                            \
8573          p[z] = p[m];                                                         \
8574          p[m] = t;                                                            \
8575       }                                                                       \
8576       /* now p[m] is the median-of-three */                                   \
8577       /* swap it to the beginning so it won't move around */                  \
8578       t = p[0];                                                               \
8579       p[0] = p[m];                                                            \
8580       p[m] = t;                                                               \
8581                                                                               \
8582       /* partition loop */                                                    \
8583       i=1;                                                                    \
8584       j=n-1;                                                                  \
8585       for(;;) {                                                               \
8586          /* handling of equality is crucial here */                           \
8587          /* for sentinels & efficiency with duplicates */                     \
8588          b = &p[0];                                                           \
8589          for (;;++i) {                                                        \
8590             a=&p[i];                                                          \
8591             c = COMPARE;                                                      \
8592             if (!c) break;                                                    \
8593          }                                                                    \
8594          a = &p[0];                                                           \
8595          for (;;--j) {                                                        \
8596             b=&p[j];                                                          \
8597             c = COMPARE;                                                      \
8598             if (!c) break;                                                    \
8599          }                                                                    \
8600          /* make sure we haven't crossed */                                   \
8601          if (i >= j) break;                                                   \
8602          t = p[i];                                                            \
8603          p[i] = p[j];                                                         \
8604          p[j] = t;                                                            \
8605                                                                               \
8606          ++i;                                                                 \
8607          --j;                                                                 \
8608       }                                                                       \
8609       /* recurse on smaller side, iterate on larger */                        \
8610       if (j < (n-i)) {                                                        \
8611          STB_(FUNCNAME,_quicksort)(p,j);                                       \
8612          p = p+i;                                                             \
8613          n = n-i;                                                             \
8614       } else {                                                                \
8615          STB_(FUNCNAME,_quicksort)(p+i, n-i);                                  \
8616          n = j;                                                               \
8617       }                                                                       \
8618    }                                                                          \
8619 }                                                                             \
8620                                                                               \
8621 MODE FUNCNAME(TYPE *p, int n)                                                 \
8622 {                                                                             \
8623    STB_(FUNCNAME, _quicksort)(p, n);                                           \
8624    STB_(FUNCNAME, _ins_sort)(p, n);                                            \
8625 }                                                                             \
8626 
8627 
8628 //////////////////////////////////////////////////////////////////////////////
8629 //
8630 //      stb_bitset   an array of booleans indexed by integers
8631 //
8632 
8633 typedef stb_uint32 stb_bitset;
8634 
8635 STB_EXTERN  stb_bitset *stb_bitset_new(int value, int len);
8636 
8637 #define stb_bitset_clearall(arr,len)     (memset(arr,   0, 4 * (len)))
8638 #define stb_bitset_setall(arr,len)       (memset(arr, 255, 4 * (len)))
8639 
8640 #define stb_bitset_setbit(arr,n)         ((arr)[(n) >> 5] |=  (1 << (n & 31)))
8641 #define stb_bitset_clearbit(arr,n)       ((arr)[(n) >> 5] &= ~(1 << (n & 31)))
8642 #define stb_bitset_testbit(arr,n)        ((arr)[(n) >> 5] &   (1 << (n & 31)))
8643 
8644 STB_EXTERN  stb_bitset *stb_bitset_union(stb_bitset *p0, stb_bitset *p1, int len);
8645 
8646 STB_EXTERN  int *stb_bitset_getlist(stb_bitset *out, int start, int end);
8647 
8648 STB_EXTERN  int  stb_bitset_eq(stb_bitset *p0, stb_bitset *p1, int len);
8649 STB_EXTERN  int  stb_bitset_disjoint(stb_bitset *p0, stb_bitset *p1, int len);
8650 STB_EXTERN  int  stb_bitset_disjoint_0(stb_bitset *p0, stb_bitset *p1, int len);
8651 STB_EXTERN  int  stb_bitset_subset(stb_bitset *bigger, stb_bitset *smaller, int len);
8652 STB_EXTERN  int  stb_bitset_unioneq_changed(stb_bitset *p0, stb_bitset *p1, int len);
8653 
8654 #ifdef STB_DEFINE
8655 int stb_bitset_eq(stb_bitset *p0, stb_bitset *p1, int len)
8656 {
8657    int i;
8658    for (i=0; i < len; ++i)
8659       if (p0[i] != p1[i]) return 0;
8660    return 1;
8661 }
8662 
8663 int stb_bitset_disjoint(stb_bitset *p0, stb_bitset *p1, int len)
8664 {
8665    int i;
8666    for (i=0; i < len; ++i)
8667       if (p0[i] & p1[i]) return 0;
8668    return 1;
8669 }
8670 
8671 int stb_bitset_disjoint_0(stb_bitset *p0, stb_bitset *p1, int len)
8672 {
8673    int i;
8674    for (i=0; i < len; ++i)
8675       if ((p0[i] | p1[i]) != 0xffffffff) return 0;
8676    return 1;
8677 }
8678 
8679 int stb_bitset_subset(stb_bitset *bigger, stb_bitset *smaller, int len)
8680 {
8681    int i;
8682    for (i=0; i < len; ++i)
8683       if ((bigger[i] & smaller[i]) != smaller[i]) return 0;
8684    return 1;
8685 }
8686 
8687 stb_bitset *stb_bitset_union(stb_bitset *p0, stb_bitset *p1, int len)
8688 {
8689    int i;
8690    stb_bitset *d = (stb_bitset *) malloc(sizeof(*d) * len);
8691    for (i=0; i < len; ++i) d[i] = p0[i] | p1[i];
8692    return d;
8693 }
8694 
8695 int stb_bitset_unioneq_changed(stb_bitset *p0, stb_bitset *p1, int len)
8696 {
8697    int i, changed=0;
8698    for (i=0; i < len; ++i) {
8699       stb_bitset d = p0[i] | p1[i];
8700       if (d != p0[i]) {
8701          p0[i] = d;
8702          changed = 1;
8703       }
8704    }
8705    return changed;
8706 }
8707 
8708 stb_bitset *stb_bitset_new(int value, int len)
8709 {
8710    int i;
8711    stb_bitset *d = (stb_bitset *) malloc(sizeof(*d) * len);
8712    if (value) value = 0xffffffff;
8713    for (i=0; i < len; ++i) d[i] = value;
8714    return d;
8715 }
8716 
8717 int *stb_bitset_getlist(stb_bitset *out, int start, int end)
8718 {
8719    int *list = NULL;
8720    int i;
8721    for (i=start; i < end; ++i)
8722       if (stb_bitset_testbit(out, i))
8723          stb_arr_push(list, i);
8724    return list;
8725 }
8726 #endif
8727 
8728 //////////////////////////////////////////////////////////////////////////////
8729 //
8730 //      stb_wordwrap    quality word-wrapping for fixed-width fonts
8731 //
8732 
8733 STB_EXTERN int stb_wordwrap(int *pairs, int pair_max, int count, char *str);
8734 STB_EXTERN int *stb_wordwrapalloc(int count, char *str);
8735 
8736 #ifdef STB_DEFINE
8737 
8738 int stb_wordwrap(int *pairs, int pair_max, int count, char *str)
8739 {
8740    int n=0,i=0, start=0,nonwhite=0;
8741    if (pairs == NULL) pair_max = 0x7ffffff0;
8742    else pair_max *= 2;
8743    // parse
8744    for(;;) {
8745       int s=i; // first whitespace char; last nonwhite+1
8746       int w;   // word start
8747       // accept whitespace
8748       while (isspace(str[i])) {
8749          if (str[i] == '\n' || str[i] == '\r') {
8750             if (str[i] + str[i+1] == '\n' + '\r') ++i;
8751             if (n >= pair_max) return -1;
8752             if (pairs) pairs[n] = start, pairs[n+1] = s-start;
8753             n += 2;
8754             nonwhite=0;
8755             start = i+1;
8756             s = start;
8757          }
8758          ++i;
8759       }
8760       if (i >= start+count) {
8761          // we've gone off the end using whitespace
8762          if (nonwhite) {
8763             if (n >= pair_max) return -1;
8764             if (pairs) pairs[n] = start, pairs[n+1] = s-start;
8765             n += 2;
8766             start = s = i;
8767             nonwhite=0;
8768          } else {
8769             // output all the whitespace
8770             while (i >= start+count) {
8771                if (n >= pair_max) return -1;
8772                if (pairs) pairs[n] = start, pairs[n+1] = count;
8773                n += 2;
8774                start += count;
8775             }
8776             s = start;
8777          }
8778       }
8779 
8780       if (str[i] == 0) break;
8781       // now scan out a word and see if it fits
8782       w = i;
8783       while (str[i] && !isspace(str[i])) {
8784          ++i;
8785       }
8786       // wrapped?
8787       if (i > start + count) {
8788          // huge?
8789          if (i-s <= count) {
8790             if (n >= pair_max) return -1;
8791             if (pairs) pairs[n] = start, pairs[n+1] = s-start;
8792             n += 2;
8793             start = w;
8794          } else {
8795             // This word is longer than one line. If we wrap it onto N lines
8796             // there are leftover chars. do those chars fit on the cur line?
8797             // But if we have leading whitespace, we force it to start here.
8798             if ((w-start) + ((i-w) % count) <= count || !nonwhite) {
8799                // output a full line
8800                if (n >= pair_max) return -1;
8801                if (pairs) pairs[n] = start, pairs[n+1] = count;
8802                n += 2;
8803                start += count;
8804                w = start;
8805             } else {
8806                // output a partial line, trimming trailing whitespace
8807                if (s != start) {
8808                   if (n >= pair_max) return -1;
8809                   if (pairs) pairs[n] = start, pairs[n+1] = s-start;
8810                   n += 2;
8811                   start = w;
8812                }
8813             }
8814             // now output full lines as needed
8815             while (start + count <= i) {
8816                if (n >= pair_max) return -1;
8817                if (pairs) pairs[n] = start, pairs[n+1] = count;
8818                n += 2;
8819                start += count;
8820             }
8821          }
8822       }
8823       nonwhite=1;
8824    }
8825    if (start < i) {
8826       if (n >= pair_max) return -1;
8827       if (pairs) pairs[n] = start, pairs[n+1] = i-start;
8828       n += 2;
8829    }
8830    return n>>1;
8831 }
8832 
8833 int *stb_wordwrapalloc(int count, char *str)
8834 {
8835    int n = stb_wordwrap(NULL,0,count,str);
8836    int *z = NULL;
8837    stb_arr_setlen(z, n*2);
8838    stb_wordwrap(z, n, count, str);
8839    return z;
8840 }
8841 #endif
8842 
8843 
8844 //////////////////////////////////////////////////////////////////////////////
8845 //
8846 //         stb_match:    wildcards and regexping
8847 //
8848 
8849 STB_EXTERN int stb_wildmatch (char *expr, char *candidate);
8850 STB_EXTERN int stb_wildmatchi(char *expr, char *candidate);
8851 STB_EXTERN int stb_wildfind  (char *expr, char *candidate);
8852 STB_EXTERN int stb_wildfindi (char *expr, char *candidate);
8853 
8854 STB_EXTERN int stb_regex(char *regex, char *candidate);
8855 
8856 typedef struct stb_matcher stb_matcher;
8857 
8858 STB_EXTERN stb_matcher *stb_regex_matcher(char *regex);
8859 STB_EXTERN int stb_matcher_match(stb_matcher *m, char *str);
8860 STB_EXTERN int stb_matcher_find(stb_matcher *m, char *str);
8861 STB_EXTERN void stb_matcher_free(stb_matcher *f);
8862 
8863 STB_EXTERN stb_matcher *stb_lex_matcher(void);
8864 STB_EXTERN int stb_lex_item(stb_matcher *m, char *str, int result);
8865 STB_EXTERN int stb_lex_item_wild(stb_matcher *matcher, char *regex, int result);
8866 STB_EXTERN int stb_lex(stb_matcher *m, char *str, int *len);
8867 
8868 
8869 
8870 #ifdef STB_DEFINE
8871 
8872 static int stb__match_qstring(char *candidate, char *qstring, int qlen, int insensitive)
8873 {
8874    int i;
8875    if (insensitive) {
8876       for (i=0; i < qlen; ++i)
8877          if (qstring[i] == '?') {
8878             if (!candidate[i]) return 0;
8879          } else
8880             if (tolower(qstring[i]) != tolower(candidate[i]))
8881                return 0;
8882    } else {
8883       for (i=0; i < qlen; ++i)
8884          if (qstring[i] == '?') {
8885             if (!candidate[i]) return 0;
8886          } else
8887             if (qstring[i] != candidate[i])
8888                return 0;
8889    }
8890    return 1;
8891 }
8892 
8893 static int stb__find_qstring(char *candidate, char *qstring, int qlen, int insensitive)
8894 {
8895    char c;
8896 
8897    int offset=0;
8898    while (*qstring == '?') {
8899       ++qstring;
8900       --qlen;
8901       ++candidate;
8902       if (qlen == 0) return 0;
8903       if (*candidate == 0) return -1;
8904    }
8905 
8906    c = *qstring++;
8907    --qlen;
8908    if (insensitive) c = tolower(c);
8909 
8910    while (candidate[offset]) {
8911       if (c == (insensitive ? tolower(candidate[offset]) : candidate[offset]))
8912          if (stb__match_qstring(candidate+offset+1, qstring, qlen, insensitive))
8913             return offset;
8914       ++offset;
8915    }
8916 
8917    return -1;
8918 }
8919 
8920 int stb__wildmatch_raw2(char *expr, char *candidate, int search, int insensitive)
8921 {
8922    int where=0;
8923    int start = -1;
8924 
8925    if (!search) {
8926       // parse to first '*'
8927       if (*expr != '*')
8928          start = 0;
8929       while (*expr != '*') {
8930          if (!*expr)
8931             return *candidate == 0 ? 0 : -1;
8932          if (*expr == '?') {
8933             if (!*candidate) return -1;
8934          } else {
8935             if (insensitive) {
8936                if (tolower(*candidate) != tolower(*expr))
8937                   return -1;
8938             } else
8939                if (*candidate != *expr)
8940                   return -1;
8941          }
8942          ++candidate, ++expr, ++where;
8943       }
8944    } else {
8945       // 0-length search string
8946       if (!*expr)
8947          return 0;
8948    }
8949 
8950    assert(search || *expr == '*');
8951    if (!search)
8952       ++expr;
8953 
8954    // implicit '*' at this point
8955 
8956    while (*expr) {
8957       int o=0;
8958       // combine redundant * characters
8959       while (expr[0] == '*') ++expr;
8960 
8961       // ok, at this point, expr[-1] == '*',
8962       // and expr[0] != '*'
8963 
8964       if (!expr[0]) return start >= 0 ? start : 0;
8965 
8966       // now find next '*'
8967       o = 0;
8968       while (expr[o] != '*') {
8969          if (expr[o] == 0)
8970             break;
8971          ++o;
8972       }
8973       // if no '*', scan to end, then match at end
8974       if (expr[o] == 0 && !search) {
8975          int z;
8976          for (z=0; z < o; ++z)
8977             if (candidate[z] == 0)
8978                return -1;
8979          while (candidate[z])
8980             ++z;
8981          // ok, now check if they match
8982          if (stb__match_qstring(candidate+z-o, expr, o, insensitive))
8983             return start >= 0 ? start : 0;
8984          return -1;
8985       } else {
8986          // if yes '*', then do stb__find_qmatch on the intervening chars
8987          int n = stb__find_qstring(candidate, expr, o, insensitive);
8988          if (n < 0)
8989             return -1;
8990          if (start < 0)
8991             start = where + n;
8992          expr += o;
8993          candidate += n+o;
8994       }
8995 
8996       if (*expr == 0) {
8997          assert(search);
8998          return start;
8999       }
9000 
9001       assert(*expr == '*');
9002       ++expr;
9003    }
9004 
9005    return start >= 0 ? start : 0;
9006 }
9007 
9008 int stb__wildmatch_raw(char *expr, char *candidate, int search, int insensitive)
9009 {
9010    char buffer[256];
9011    // handle multiple search strings
9012    char *s = strchr(expr, ';');
9013    char *last = expr;
9014    while (s) {
9015       int z;
9016       // need to allow for non-writeable strings... assume they're small
9017       if (s - last < 256) {
9018          stb_strncpy(buffer, last, s-last+1);
9019          z = stb__wildmatch_raw2(buffer, candidate, search, insensitive);
9020       } else {
9021          *s = 0;
9022          z = stb__wildmatch_raw2(last, candidate, search, insensitive);
9023          *s = ';';
9024       }
9025       if (z >= 0) return z;
9026       last = s+1;
9027       s = strchr(last, ';');
9028    }
9029    return stb__wildmatch_raw2(last, candidate, search, insensitive);
9030 }
9031 
9032 int stb_wildmatch(char *expr, char *candidate)
9033 {
9034    return stb__wildmatch_raw(expr, candidate, 0,0) >= 0;
9035 }
9036 
9037 int stb_wildmatchi(char *expr, char *candidate)
9038 {
9039    return stb__wildmatch_raw(expr, candidate, 0,1) >= 0;
9040 }
9041 
9042 int stb_wildfind(char *expr, char *candidate)
9043 {
9044    return stb__wildmatch_raw(expr, candidate, 1,0);
9045 }
9046 
9047 int stb_wildfindi(char *expr, char *candidate)
9048 {
9049    return stb__wildmatch_raw(expr, candidate, 1,1);
9050 }
9051 
9052 typedef struct
9053 {
9054    stb_int16 transition[256];
9055 } stb_dfa;
9056 
9057 // an NFA node represents a state you're in; it then has
9058 // an arbitrary number of edges dangling off of it
9059 // note this isn't utf8-y
9060 typedef struct
9061 {
9062    stb_int16  match; // character/set to match
9063    stb_uint16 node;  // output node to go to
9064 } stb_nfa_edge;
9065 
9066 typedef struct
9067 {
9068    stb_int16 goal;   // does reaching this win the prize?
9069    stb_uint8 active; // is this in the active list
9070    stb_nfa_edge *out;
9071    stb_uint16 *eps;  // list of epsilon closures
9072 } stb_nfa_node;
9073 
9074 #define STB__DFA_UNDEF  -1
9075 #define STB__DFA_GOAL   -2
9076 #define STB__DFA_END    -3
9077 #define STB__DFA_MGOAL  -4
9078 #define STB__DFA_VALID  0
9079 
9080 #define STB__NFA_STOP_GOAL -1
9081 
9082 // compiled regexp
9083 struct stb_matcher
9084 {
9085    stb_uint16 start_node;
9086    stb_int16 dfa_start;
9087    stb_uint32 *charset;
9088    int num_charset;
9089    int match_start;
9090    stb_nfa_node *nodes;
9091    int does_lex;
9092 
9093    // dfa matcher
9094    stb_dfa    * dfa;
9095    stb_uint32 * dfa_mapping;
9096    stb_int16  * dfa_result;
9097    int num_words_per_dfa;
9098 };
9099 
9100 static int stb__add_node(stb_matcher *matcher)
9101 {
9102    stb_nfa_node z;
9103    z.active = 0;
9104    z.eps    = 0;
9105    z.goal   = 0;
9106    z.out    = 0;
9107    stb_arr_push(matcher->nodes, z);
9108    return stb_arr_len(matcher->nodes)-1;
9109 }
9110 
9111 static void stb__add_epsilon(stb_matcher *matcher, int from, int to)
9112 {
9113    assert(from != to);
9114    if (matcher->nodes[from].eps == NULL)
9115       stb_arr_malloc((void **) &matcher->nodes[from].eps, matcher);
9116    stb_arr_push(matcher->nodes[from].eps, to);
9117 }
9118 
9119 static void stb__add_edge(stb_matcher *matcher, int from, int to, int type)
9120 {
9121    stb_nfa_edge z = { type, to };
9122    if (matcher->nodes[from].out == NULL)
9123       stb_arr_malloc((void **) &matcher->nodes[from].out, matcher);
9124    stb_arr_push(matcher->nodes[from].out, z);
9125 }
9126 
9127 static char *stb__reg_parse_alt(stb_matcher *m, int s, char *r, stb_uint16 *e);
9128 static char *stb__reg_parse(stb_matcher *matcher, int start, char *regex, stb_uint16 *end)
9129 {
9130    int n;
9131    int last_start = -1;
9132    stb_uint16 last_end = start;
9133 
9134    while (*regex) {
9135       switch (*regex) {
9136          case '(':
9137             last_start = last_end;
9138             regex = stb__reg_parse_alt(matcher, last_end, regex+1, &last_end);
9139             if (regex == NULL || *regex != ')')
9140                return NULL;
9141             ++regex;
9142             break;
9143 
9144          case '|':
9145          case ')':
9146             *end = last_end;
9147             return regex;
9148 
9149          case '?':
9150             if (last_start < 0) return NULL;
9151             stb__add_epsilon(matcher, last_start, last_end);
9152             ++regex;
9153             break;
9154 
9155          case '*':
9156             if (last_start < 0) return NULL;
9157             stb__add_epsilon(matcher, last_start, last_end);
9158 
9159             // fall through
9160 
9161          case '+':
9162             if (last_start < 0) return NULL;
9163             stb__add_epsilon(matcher, last_end, last_start);
9164             // prevent links back to last_end from chaining to last_start
9165             n = stb__add_node(matcher);
9166             stb__add_epsilon(matcher, last_end, n);
9167             last_end = n;
9168             ++regex;
9169             break;
9170 
9171          case '{':   // not supported!
9172             // @TODO: given {n,m}, clone last_start to last_end m times,
9173             // and include epsilons from start to first m-n blocks
9174             return NULL;
9175 
9176          case '\\':
9177             ++regex;
9178             if (!*regex) return NULL;
9179 
9180             // fallthrough
9181          default: // match exactly this character
9182             n = stb__add_node(matcher);
9183             stb__add_edge(matcher, last_end, n, *regex);
9184             last_start = last_end;
9185             last_end = n;
9186             ++regex;
9187             break;
9188 
9189          case '$':
9190             n = stb__add_node(matcher);
9191             stb__add_edge(matcher, last_end, n, '\n');
9192             last_start = last_end;
9193             last_end = n;
9194             ++regex;
9195             break;
9196 
9197          case '.':
9198             n = stb__add_node(matcher);
9199             stb__add_edge(matcher, last_end, n, -1);
9200             last_start = last_end;
9201             last_end = n;
9202             ++regex;
9203             break;
9204 
9205          case '[': {
9206             stb_uint8 flags[256];
9207             int invert = 0,z;
9208             ++regex;
9209             if (matcher->num_charset == 0) {
9210                matcher->charset = (stb_uint *) stb_malloc(matcher, sizeof(*matcher->charset) * 256);
9211                memset(matcher->charset, 0, sizeof(*matcher->charset) * 256);
9212             }
9213 
9214             memset(flags,0,sizeof(flags));
9215 
9216             // leading ^ is special
9217             if (*regex == '^')
9218                ++regex, invert = 1;
9219 
9220             // leading ] is special
9221             if (*regex == ']') {
9222                flags[']'] = 1;
9223                ++regex;
9224             }
9225             while (*regex != ']') {
9226                stb_uint a;
9227                if (!*regex) return NULL;
9228                a = *regex++;
9229                if (regex[0] == '-' && regex[1] != ']') {
9230                   stb_uint i,b = regex[1];
9231                   regex += 2;
9232                   if (b == 0) return NULL;
9233                   if (a > b) return NULL;
9234                   for (i=a; i <= b; ++i)
9235                      flags[i] = 1;
9236                } else
9237                   flags[a] = 1;
9238             }
9239             ++regex;
9240             if (invert) {
9241                int i;
9242                for (i=0; i < 256; ++i)
9243                   flags[i] = 1-flags[i];
9244             }
9245 
9246             // now check if any existing charset matches
9247             for (z=0; z < matcher->num_charset; ++z) {
9248                int i, k[2] = { 0, 1 << z};
9249                for (i=0; i < 256; ++i) {
9250                   unsigned int f = k[flags[i]];
9251                   if ((matcher->charset[i] & k[1]) != f)
9252                      break;
9253                }
9254                if (i == 256) break;
9255             }
9256 
9257             if (z == matcher->num_charset) {
9258                int i;
9259                ++matcher->num_charset;
9260                if (matcher->num_charset > 32) {
9261                   assert(0); /* NOTREACHED */
9262                   return NULL; // too many charsets, oops
9263                }
9264                for (i=0; i < 256; ++i)
9265                   if (flags[i])
9266                      matcher->charset[i] |= (1 << z);
9267             }
9268 
9269             n = stb__add_node(matcher);
9270             stb__add_edge(matcher, last_end, n, -2 - z);
9271             last_start = last_end;
9272             last_end = n;
9273             break;
9274          }
9275       }
9276    }
9277    *end = last_end;
9278    return regex;
9279 }
9280 
9281 static char *stb__reg_parse_alt(stb_matcher *matcher, int start, char *regex, stb_uint16 *end)
9282 {
9283    stb_uint16 last_end = start;
9284    stb_uint16 main_end;
9285 
9286    int head, tail;
9287 
9288    head = stb__add_node(matcher);
9289    stb__add_epsilon(matcher, start, head);
9290 
9291    regex = stb__reg_parse(matcher, head, regex, &last_end);
9292    if (regex == NULL) return NULL;
9293    if (*regex == 0 || *regex == ')') {
9294       *end = last_end;
9295       return regex;
9296    }
9297 
9298    main_end = last_end;
9299    tail = stb__add_node(matcher);
9300 
9301    stb__add_epsilon(matcher, last_end, tail);
9302 
9303    // start alternatives from the same starting node; use epsilon
9304    // transitions to combine their endings
9305    while(*regex && *regex != ')') {
9306       assert(*regex == '|');
9307       head = stb__add_node(matcher);
9308       stb__add_epsilon(matcher, start, head);
9309       regex = stb__reg_parse(matcher, head, regex+1, &last_end);
9310       if (regex == NULL)
9311          return NULL;
9312       stb__add_epsilon(matcher, last_end, tail);
9313    }
9314 
9315    *end = tail;
9316    return regex;
9317 }
9318 
9319 static char *stb__wild_parse(stb_matcher *matcher, int start, char *str, stb_uint16 *end)
9320 {
9321    int n;
9322    stb_uint16 last_end;
9323 
9324    last_end = stb__add_node(matcher);
9325    stb__add_epsilon(matcher, start, last_end);
9326 
9327    while (*str) {
9328       switch (*str) {
9329             // fallthrough
9330          default: // match exactly this character
9331             n = stb__add_node(matcher);
9332             if (toupper(*str) == tolower(*str)) {
9333                stb__add_edge(matcher, last_end, n, *str);
9334             } else {
9335                stb__add_edge(matcher, last_end, n, tolower(*str));
9336                stb__add_edge(matcher, last_end, n, toupper(*str));
9337             }
9338             last_end = n;
9339             ++str;
9340             break;
9341 
9342          case '?':
9343             n = stb__add_node(matcher);
9344             stb__add_edge(matcher, last_end, n, -1);
9345             last_end = n;
9346             ++str;
9347             break;
9348 
9349          case '*':
9350             n = stb__add_node(matcher);
9351             stb__add_edge(matcher, last_end, n, -1);
9352             stb__add_epsilon(matcher, last_end, n);
9353             stb__add_epsilon(matcher, n, last_end);
9354             last_end = n;
9355             ++str;
9356             break;
9357       }
9358    }
9359 
9360    // now require end of string to match
9361    n = stb__add_node(matcher);
9362    stb__add_edge(matcher, last_end, n, 0);
9363    last_end = n;
9364 
9365    *end = last_end;
9366    return str;
9367 }
9368 
9369 static int stb__opt(stb_matcher *m, int n)
9370 {
9371    for(;;) {
9372       stb_nfa_node *p = &m->nodes[n];
9373       if (p->goal)                  return n;
9374       if (stb_arr_len(p->out))      return n;
9375       if (stb_arr_len(p->eps) != 1) return n;
9376       n = p->eps[0];
9377    }
9378 }
9379 
9380 static void stb__optimize(stb_matcher *m)
9381 {
9382    // if the target of any edge is a node with exactly
9383    // one out-epsilon, shorten it
9384    int i,j;
9385    for (i=0; i < stb_arr_len(m->nodes); ++i) {
9386       stb_nfa_node *p = &m->nodes[i];
9387       for (j=0; j < stb_arr_len(p->out); ++j)
9388          p->out[j].node = stb__opt(m,p->out[j].node);
9389       for (j=0; j < stb_arr_len(p->eps); ++j)
9390          p->eps[j]      = stb__opt(m,p->eps[j]     );
9391    }
9392    m->start_node = stb__opt(m,m->start_node);
9393 }
9394 
9395 void stb_matcher_free(stb_matcher *f)
9396 {
9397    stb_free(f);
9398 }
9399 
9400 static stb_matcher *stb__alloc_matcher(void)
9401 {
9402    stb_matcher *matcher = (stb_matcher *) stb_malloc(0,sizeof(*matcher));
9403 
9404    matcher->start_node  = 0;
9405    stb_arr_malloc((void **) &matcher->nodes, matcher);
9406    matcher->num_charset = 0;
9407    matcher->match_start = 0;
9408    matcher->does_lex    = 0;
9409 
9410    matcher->dfa_start   = STB__DFA_UNDEF;
9411    stb_arr_malloc((void **) &matcher->dfa, matcher);
9412    stb_arr_malloc((void **) &matcher->dfa_mapping, matcher);
9413    stb_arr_malloc((void **) &matcher->dfa_result, matcher);
9414 
9415    stb__add_node(matcher);
9416 
9417    return matcher;
9418 }
9419 
9420 static void stb__lex_reset(stb_matcher *matcher)
9421 {
9422    // flush cached dfa data
9423    stb_arr_setlen(matcher->dfa, 0);
9424    stb_arr_setlen(matcher->dfa_mapping, 0);
9425    stb_arr_setlen(matcher->dfa_result, 0);
9426    matcher->dfa_start = STB__DFA_UNDEF;
9427 }
9428 
9429 stb_matcher *stb_regex_matcher(char *regex)
9430 {
9431    char *z;
9432    stb_uint16 end;
9433    stb_matcher *matcher = stb__alloc_matcher();
9434    if (*regex == '^') {
9435       matcher->match_start = 1;
9436       ++regex;
9437    }
9438 
9439    z = stb__reg_parse_alt(matcher, matcher->start_node, regex, &end);
9440 
9441    if (!z || *z) {
9442       stb_free(matcher);
9443       return NULL;
9444    }
9445 
9446    ((matcher->nodes)[(int) end]).goal = STB__NFA_STOP_GOAL;
9447 
9448    return matcher;
9449 }
9450 
9451 stb_matcher *stb_lex_matcher(void)
9452 {
9453    stb_matcher *matcher = stb__alloc_matcher();
9454 
9455    matcher->match_start = 1;
9456    matcher->does_lex    = 1;
9457 
9458    return matcher;
9459 }
9460 
9461 int stb_lex_item(stb_matcher *matcher, char *regex, int result)
9462 {
9463    char *z;
9464    stb_uint16 end;
9465 
9466    z = stb__reg_parse_alt(matcher, matcher->start_node, regex, &end);
9467 
9468    if (z == NULL)
9469       return 0;
9470 
9471    stb__lex_reset(matcher);
9472 
9473    matcher->nodes[(int) end].goal = result;
9474    return 1;
9475 }
9476 
9477 int stb_lex_item_wild(stb_matcher *matcher, char *regex, int result)
9478 {
9479    char *z;
9480    stb_uint16 end;
9481 
9482    z = stb__wild_parse(matcher, matcher->start_node, regex, &end);
9483 
9484    if (z == NULL)
9485       return 0;
9486 
9487    stb__lex_reset(matcher);
9488 
9489    matcher->nodes[(int) end].goal = result;
9490    return 1;
9491 }
9492 
9493 static void stb__clear(stb_matcher *m, stb_uint16 *list)
9494 {
9495    int i;
9496    for (i=0; i < stb_arr_len(list); ++i)
9497       m->nodes[(int) list[i]].active = 0;
9498 }
9499 
9500 static int stb__clear_goalcheck(stb_matcher *m, stb_uint16 *list)
9501 {
9502    int i, t=0;
9503    for (i=0; i < stb_arr_len(list); ++i) {
9504       t += m->nodes[(int) list[i]].goal;
9505       m->nodes[(int) list[i]].active = 0;
9506    }
9507    return t;
9508 }
9509 
9510 static stb_uint16 * stb__add_if_inactive(stb_matcher *m, stb_uint16 *list, int n)
9511 {
9512    if (!m->nodes[n].active) {
9513       stb_arr_push(list, n);
9514       m->nodes[n].active = 1;
9515    }
9516    return list;
9517 }
9518 
9519 static stb_uint16 * stb__eps_closure(stb_matcher *m, stb_uint16 *list)
9520 {
9521    int i,n = stb_arr_len(list);
9522 
9523    for(i=0; i < n; ++i) {
9524       stb_uint16 *e = m->nodes[(int) list[i]].eps;
9525       if (e) {
9526          int j,k = stb_arr_len(e);
9527          for (j=0; j < k; ++j)
9528             list = stb__add_if_inactive(m, list, e[j]);
9529          n = stb_arr_len(list);
9530       }
9531    }
9532 
9533    return list;
9534 }
9535 
9536 int stb_matcher_match(stb_matcher *m, char *str)
9537 {
9538    int result = 0;
9539    int i,j,y,z;
9540    stb_uint16 *previous = NULL;
9541    stb_uint16 *current = NULL;
9542    stb_uint16 *temp;
9543 
9544    stb_arr_setsize(previous, 4);
9545    stb_arr_setsize(current, 4);
9546 
9547    previous = stb__add_if_inactive(m, previous, m->start_node);
9548    previous = stb__eps_closure(m,previous);
9549    stb__clear(m, previous);
9550 
9551    while (*str && stb_arr_len(previous)) {
9552       y = stb_arr_len(previous);
9553       for (i=0; i < y; ++i) {
9554          stb_nfa_node *n = &m->nodes[(int) previous[i]];
9555          z = stb_arr_len(n->out);
9556          for (j=0; j < z; ++j) {
9557             if (n->out[j].match >= 0) {
9558                if (n->out[j].match == *str)
9559                   current = stb__add_if_inactive(m, current, n->out[j].node);
9560             } else if (n->out[j].match == -1) {
9561                if (*str != '\n')
9562                   current = stb__add_if_inactive(m, current, n->out[j].node);
9563             } else if (n->out[j].match < -1) {
9564                int z = -n->out[j].match - 2;
9565                if (m->charset[(stb_uint8) *str] & (1 << z))
9566                   current = stb__add_if_inactive(m, current, n->out[j].node);
9567             }
9568          }
9569       }
9570       stb_arr_setlen(previous, 0);
9571 
9572       temp = previous;
9573       previous = current;
9574       current = temp;
9575 
9576       previous = stb__eps_closure(m,previous);
9577       stb__clear(m, previous);
9578 
9579       ++str;
9580    }
9581 
9582    // transition to pick up a '$' at the end
9583    y = stb_arr_len(previous);
9584    for (i=0; i < y; ++i)
9585       m->nodes[(int) previous[i]].active = 1;
9586 
9587    for (i=0; i < y; ++i) {
9588       stb_nfa_node *n = &m->nodes[(int) previous[i]];
9589       z = stb_arr_len(n->out);
9590       for (j=0; j < z; ++j) {
9591          if (n->out[j].match == '\n')
9592             current = stb__add_if_inactive(m, current, n->out[j].node);
9593       }
9594    }
9595 
9596    previous = stb__eps_closure(m,previous);
9597    stb__clear(m, previous);
9598 
9599    y = stb_arr_len(previous);
9600    for (i=0; i < y; ++i)
9601       if (m->nodes[(int) previous[i]].goal)
9602          result = 1;
9603 
9604    stb_arr_free(previous);
9605    stb_arr_free(current);
9606 
9607    return result && *str == 0;
9608 }
9609 
9610 stb_int16 stb__get_dfa_node(stb_matcher *m, stb_uint16 *list)
9611 {
9612    stb_uint16 node;
9613    stb_uint32 data[8], *state, *newstate;
9614    int i,j,n;
9615 
9616    state = (stb_uint32 *) stb_temp(data, m->num_words_per_dfa * 4);
9617    memset(state, 0, m->num_words_per_dfa*4);
9618 
9619    n = stb_arr_len(list);
9620    for (i=0; i < n; ++i) {
9621       int x = list[i];
9622       state[x >> 5] |= 1 << (x & 31);
9623    }
9624 
9625    // @TODO use a hash table
9626    n = stb_arr_len(m->dfa_mapping);
9627    i=j=0;
9628    for(; j < n; ++i, j += m->num_words_per_dfa) {
9629       // @TODO special case for <= 32
9630       if (!memcmp(state, m->dfa_mapping + j, m->num_words_per_dfa*4)) {
9631          node = i;
9632          goto done;
9633       }
9634    }
9635 
9636    assert(stb_arr_len(m->dfa) == i);
9637    node = i;
9638 
9639    newstate = stb_arr_addn(m->dfa_mapping, m->num_words_per_dfa);
9640    memcpy(newstate, state, m->num_words_per_dfa*4);
9641 
9642    // set all transitions to 'unknown'
9643    stb_arr_add(m->dfa);
9644    memset(m->dfa[i].transition, -1, sizeof(m->dfa[i].transition));
9645 
9646    if (m->does_lex) {
9647       int result = -1;
9648       n = stb_arr_len(list);
9649       for (i=0; i < n; ++i) {
9650          if (m->nodes[(int) list[i]].goal > result)
9651             result = m->nodes[(int) list[i]].goal;
9652       }
9653 
9654       stb_arr_push(m->dfa_result, result);
9655    }
9656 
9657 done:
9658    stb_tempfree(data, state);
9659    return node;
9660 }
9661 
9662 static int stb__matcher_dfa(stb_matcher *m, char *str_c, int *len)
9663 {
9664    stb_uint8 *str = (stb_uint8 *) str_c;
9665    stb_int16 node,prevnode;
9666    stb_dfa *trans;
9667    int match_length = 0;
9668    stb_int16 match_result=0;
9669 
9670    if (m->dfa_start == STB__DFA_UNDEF) {
9671       stb_uint16 *list;
9672 
9673       m->num_words_per_dfa = (stb_arr_len(m->nodes)+31) >> 5;
9674       stb__optimize(m);
9675 
9676       list = stb__add_if_inactive(m, NULL, m->start_node);
9677       list = stb__eps_closure(m,list);
9678       if (m->does_lex) {
9679          m->dfa_start = stb__get_dfa_node(m,list);
9680          stb__clear(m, list);
9681          // DON'T allow start state to be a goal state!
9682          // this allows people to specify regexes that can match 0
9683          // characters without them actually matching (also we don't
9684          // check _before_ advancing anyway
9685          if (m->dfa_start <= STB__DFA_MGOAL)
9686             m->dfa_start = -(m->dfa_start - STB__DFA_MGOAL);
9687       } else {
9688          if (stb__clear_goalcheck(m, list))
9689             m->dfa_start = STB__DFA_GOAL;
9690          else
9691             m->dfa_start = stb__get_dfa_node(m,list);
9692       }
9693       stb_arr_free(list);
9694    }
9695 
9696    prevnode = STB__DFA_UNDEF;
9697    node = m->dfa_start;
9698    trans = m->dfa;
9699 
9700    if (m->dfa_start == STB__DFA_GOAL)
9701       return 1;
9702 
9703    for(;;) {
9704       assert(node >= STB__DFA_VALID);
9705 
9706       // fast inner DFA loop; especially if STB__DFA_VALID is 0
9707 
9708       do {
9709          prevnode = node;
9710          node = trans[node].transition[*str++];
9711       } while (node >= STB__DFA_VALID);
9712 
9713       assert(node >= STB__DFA_MGOAL - stb_arr_len(m->dfa));
9714       assert(node < stb_arr_len(m->dfa));
9715 
9716       // special case for lex: need _longest_ match, so notice goal
9717       // state without stopping
9718       if (node <= STB__DFA_MGOAL) {
9719          match_length = str - (stb_uint8 *) str_c;
9720          node = -(node - STB__DFA_MGOAL);
9721          match_result = node;
9722          continue;
9723       }
9724 
9725       // slow NFA->DFA conversion
9726 
9727       // or we hit the goal or the end of the string, but those
9728       // can only happen once per search...
9729 
9730       if (node == STB__DFA_UNDEF) {
9731          // build a list  -- @TODO special case <= 32 states
9732          // heck, use a more compact data structure for <= 16 and <= 8 ?!
9733 
9734          // @TODO keep states/newstates around instead of reallocating them
9735          stb_uint16 *states = NULL;
9736          stb_uint16 *newstates = NULL;
9737          int i,j,y,z;
9738          stb_uint32 *flags = &m->dfa_mapping[prevnode * m->num_words_per_dfa];
9739          assert(prevnode != STB__DFA_UNDEF);
9740          stb_arr_setsize(states, 4);
9741          stb_arr_setsize(newstates,4);
9742          for (j=0; j < m->num_words_per_dfa; ++j) {
9743             for (i=0; i < 32; ++i) {
9744                if (*flags & (1 << i))
9745                   stb_arr_push(states, j*32+i);
9746             }
9747             ++flags;
9748          }
9749          // states is now the states we were in in the previous node;
9750          // so now we can compute what node it transitions to on str[-1]
9751 
9752          y = stb_arr_len(states);
9753          for (i=0; i < y; ++i) {
9754             stb_nfa_node *n = &m->nodes[(int) states[i]];
9755             z = stb_arr_len(n->out);
9756             for (j=0; j < z; ++j) {
9757                if (n->out[j].match >= 0) {
9758                   if (n->out[j].match == str[-1] || (str[-1] == 0 && n->out[j].match == '\n'))
9759                      newstates = stb__add_if_inactive(m, newstates, n->out[j].node);
9760                } else if (n->out[j].match == -1) {
9761                   if (str[-1] != '\n' && str[-1])
9762                      newstates = stb__add_if_inactive(m, newstates, n->out[j].node);
9763                } else if (n->out[j].match < -1) {
9764                   int z = -n->out[j].match - 2;
9765                   if (m->charset[str[-1]] & (1 << z))
9766                      newstates = stb__add_if_inactive(m, newstates, n->out[j].node);
9767                }
9768             }
9769          }
9770          // AND add in the start state!
9771          if (!m->match_start || (str[-1] == '\n' && !m->does_lex))
9772             newstates = stb__add_if_inactive(m, newstates, m->start_node);
9773          // AND epsilon close it
9774          newstates = stb__eps_closure(m, newstates);
9775          // if it's a goal state, then that's all there is to it
9776          if (stb__clear_goalcheck(m, newstates)) {
9777             if (m->does_lex) {
9778                match_length = str - (stb_uint8 *) str_c;
9779                node = stb__get_dfa_node(m,newstates);
9780                match_result = node;
9781                node = -node + STB__DFA_MGOAL;
9782                trans = m->dfa; // could have gotten realloc()ed
9783             } else
9784                node = STB__DFA_GOAL;
9785          } else if (str[-1] == 0 || stb_arr_len(newstates) == 0) {
9786             node = STB__DFA_END;
9787          } else {
9788             node = stb__get_dfa_node(m,newstates);
9789             trans = m->dfa; // could have gotten realloc()ed
9790          }
9791          trans[prevnode].transition[str[-1]] = node;
9792          if (node <= STB__DFA_MGOAL)
9793             node = -(node - STB__DFA_MGOAL);
9794          stb_arr_free(newstates);
9795          stb_arr_free(states);
9796       }
9797 
9798       if (node == STB__DFA_GOAL) {
9799          return 1;
9800       }
9801       if (node == STB__DFA_END) {
9802          if (m->does_lex) {
9803             if (match_result) {
9804                if (len) *len = match_length;
9805                return m->dfa_result[(int) match_result];
9806             }
9807          }
9808          return 0;
9809       }
9810 
9811       assert(node != STB__DFA_UNDEF);
9812    }
9813 }
9814 
9815 int stb_matcher_find(stb_matcher *m, char *str)
9816 {
9817    assert(m->does_lex == 0);
9818    return stb__matcher_dfa(m, str, NULL);
9819 }
9820 
9821 int stb_lex(stb_matcher *m, char *str, int *len)
9822 {
9823    assert(m->does_lex);
9824    return stb__matcher_dfa(m, str, len);
9825 }
9826 
9827 int stb_regex(char *regex, char *str)
9828 {
9829    static stb_perfect p;
9830    static stb_matcher ** matchers;
9831    static char        ** regexps;
9832    static char        ** regexp_cache;
9833    static unsigned short *mapping;
9834    int z = stb_perfect_hash(&p, (int) regex);
9835    if (z >= 0) {
9836       if (strcmp(regex, regexp_cache[(int) mapping[z]])) {
9837          int i = mapping[z];
9838          stb_matcher_free(matchers[i]);
9839          free(regexp_cache[i]);
9840          regexps[i] = regex;
9841          regexp_cache[i] = strdup(regex);
9842          matchers[i] = stb_regex_matcher(regex);
9843       }
9844    } else {
9845       int i,n;
9846       if (regex == NULL) {
9847          for (i=0; i < stb_arr_len(matchers); ++i) {
9848             stb_matcher_free(matchers[i]);
9849             free(regexp_cache[i]);
9850          }
9851          stb_arr_free(matchers);
9852          stb_arr_free(regexps);
9853          stb_arr_free(regexp_cache);
9854          stb_perfect_destroy(&p);
9855          free(mapping); mapping = NULL;
9856          return -1;
9857       }
9858       stb_arr_push(regexps, regex);
9859       stb_arr_push(regexp_cache, strdup(regex));
9860       stb_arr_push(matchers, stb_regex_matcher(regex));
9861       stb_perfect_destroy(&p);
9862       n = stb_perfect_create(&p, (unsigned int *) (char **) regexps, stb_arr_len(regexps));
9863       mapping = (unsigned short *) realloc(mapping, n * sizeof(*mapping));
9864       for (i=0; i < stb_arr_len(regexps); ++i)
9865          mapping[stb_perfect_hash(&p, (int) regexps[i])] = i;
9866       z = stb_perfect_hash(&p, (int) regex);
9867    }
9868    return stb_matcher_find(matchers[(int) mapping[z]], str);
9869 }
9870 
9871 #endif // STB_DEFINE
9872 
9873 
9874 #if 0
9875 //////////////////////////////////////////////////////////////////////////////
9876 //
9877 //                      C source-code introspection
9878 //
9879 
9880 // runtime structure
9881 typedef struct
9882 {
9883    char *name;
9884    char *type;     // base type
9885    char *comment;  // content of comment field
9886    int   size;     // size of base type
9887    int   offset;   // field offset
9888    int   arrcount[8]; // array sizes; -1 = pointer indirection; 0 = end of list
9889 } stb_info_field;
9890 
9891 typedef struct
9892 {
9893    char *structname;
9894    int size;
9895    int num_fields;
9896    stb_info_field *fields;
9897 } stb_info_struct;
9898 
9899 extern stb_info_struct stb_introspect_output[];
9900 
9901 //
9902 
9903 STB_EXTERN void stb_introspect_precompiled(stb_info_struct *compiled);
9904 STB_EXTERN void stb__introspect(char *path, char *file);
9905 
9906 #define stb_introspect_ship()            stb__introspect(NULL, NULL, stb__introspect_output)
9907 
9908 #ifdef STB_SHIP
9909 #define stb_introspect()                 stb_introspect_ship()
9910 #define stb_introspect_path(p)           stb_introspect_ship()
9911 #else
9912 // bootstrapping: define stb_introspect() (or 'path') the first time
9913 #define stb_introspect()                 stb__introspect(NULL, __FILE__, NULL)
9914 #define stb_introspect_auto()            stb__introspect(NULL, __FILE__, stb__introspect_output)
9915 
9916 #define stb_introspect_path(p)           stb__introspect(p, __FILE__, NULL)
9917 #define stb_introspect_path(p)           stb__introspect(p, __FILE__, NULL)
9918 #endif
9919 
9920 #ifdef STB_DEFINE
9921 
9922 #ifndef STB_INTROSPECT_CPP
9923    #ifdef __cplusplus
9924    #define STB_INTROSPECT_CPP 1
9925    #else
9926    #define STB_INTROSPECT_CPP 0
9927    #endif
9928 #endif
9929 
9930 void stb_introspect_precompiled(stb_info_struct *compiled)
9931 {
9932 
9933 }
9934 
9935 
9936 static void stb__introspect_filename(char *buffer, char *path)
9937 {
9938    #if STB_INTROSPECT_CPP
9939    sprintf(buffer, "%s/stb_introspect.cpp", path);
9940    #else
9941    sprintf(buffer, "%s/stb_introspect.c", path);
9942    #endif
9943 }
9944 
9945 static void stb__introspect_compute(char *path, char *file)
9946 {
9947    int i;
9948    char ** include_list = NULL;
9949    char ** introspect_list = NULL;
9950    FILE *f;
9951    f = fopen(file, "w");
9952    if (!f) return;
9953 
9954    fputs("// if you get compiler errors, change the following 0 to a 1:\n", f);
9955    fputs("#define STB_INTROSPECT_INVALID 0\n\n", f);
9956    fputs("// this will force the code to compile, and force the introspector\n", f);
9957    fputs("// to run and then exit, allowing you to recompile\n\n\n", f);
9958    fputs("#include \"stb.h\"\n\n",f );
9959    fputs("#if STB_INTROSPECT_INVALID\n", f);
9960    fputs("   stb_info_struct stb__introspect_output[] = { (void *) 1 }\n", f);
9961    fputs("#else\n\n", f);
9962    for (i=0; i < stb_arr_len(include_list); ++i)
9963       fprintf(f, " #include \"%s\"\n", include_list[i]);
9964 
9965    fputs(" stb_info_struct stb__introspect_output[] =\n{\n", f);
9966    for (i=0; i < stb_arr_len(introspect_list); ++i)
9967       fprintf(f, "  stb_introspect_%s,\n", introspect_list[i]);
9968    fputs(" };\n", f);
9969    fputs("#endif\n", f);
9970    fclose(f);
9971 }
9972 
9973 static stb_info_struct *stb__introspect_info;
9974 
9975 #ifndef STB_SHIP
9976 
9977 #endif
9978 
9979 void stb__introspect(char *path, char *file, stb_info_struct *compiled)
9980 {
9981    static int first=1;
9982    if (!first) return;
9983    first=0;
9984 
9985    stb__introspect_info = compiled;
9986 
9987    #ifndef STB_SHIP
9988    if (path || file) {
9989       int bail_flag = compiled && compiled[0].structname == (void *) 1;
9990       int needs_building = bail_flag;
9991       struct stb__stat st;
9992       char buffer[1024], buffer2[1024];
9993       if (!path) {
9994          stb_splitpath(buffer, file, STB_PATH);
9995          path = buffer;
9996       }
9997       // bail if the source path doesn't exist
9998       if (!stb_fexists(path)) return;
9999 
10000       stb__introspect_filename(buffer2, path);
10001 
10002       // get source/include files timestamps, compare to output-file timestamp;
10003       // if mismatched, regenerate
10004 
10005       if (stb__stat(buffer2, &st))
10006          needs_building = STB_TRUE;
10007 
10008       {
10009          // find any file that contains an introspection command and is newer
10010          // if needs_building is already true, we don't need to do this test,
10011          // but we still need these arrays, so go ahead and get them
10012          char **all[3];
10013          all[0] = stb_readdir_files_mask(path, "*.h");
10014          all[1] = stb_readdir_files_mask(path, "*.c");
10015          all[2] = stb_readdir_files_mask(path, "*.cpp");
10016          int i,j;
10017          if (needs_building) {
10018             for (j=0; j < 3; ++j) {
10019                for (i=0; i < stb_arr_len(all[j]); ++i) {
10020                   struct stb__stat st2;
10021                   if (!stb__stat(all[j][i], &st2)) {
10022                      if (st.st_mtime < st2.st_mtime) {
10023                         char *z = stb_filec(all[j][i], NULL);
10024                         int found=STB_FALSE;
10025                         while (y) {
10026                            y = strstr(y, "//si");
10027                            if (y && isspace(y[4])) {
10028                               found = STB_TRUE;
10029                               break;
10030                            }
10031                         }
10032                         needs_building = STB_TRUE;
10033                         goto done;
10034                      }
10035                   }
10036                }
10037             }
10038            done:;
10039          }
10040                char *z = stb_filec(all[i], NULL), *y = z;
10041                int found=STB_FALSE;
10042                while (y) {
10043                   y = strstr(y, "//si");
10044                   if (y && isspace(y[4])) {
10045                      found = STB_TRUE;
10046                      break;
10047                   }
10048                }
10049                if (found)
10050                   stb_arr_push(introspect_h, strdup(all[i]));
10051                free(z);
10052             }
10053          }
10054          stb_readdir_free(all);
10055          if (!needs_building) {
10056             for (i=0; i < stb_arr_len(introspect_h); ++i) {
10057                struct stb__stat st2;
10058                if (!stb__stat(introspect_h[i], &st2))
10059                   if (st.st_mtime < st2.st_mtime)
10060                      needs_building = STB_TRUE;
10061             }
10062          }
10063 
10064          if (needs_building) {
10065             stb__introspect_compute(path, buffer2);
10066          }
10067       }
10068    }
10069    #endif
10070 }
10071 #endif
10072 #endif
10073 
10074 #ifdef STB_INTROSPECT
10075 // compile-time code-generator
10076 #define INTROSPECT(x)   int main(int argc, char **argv) { stb__introspect(__FILE__); return 0; }
10077 #define FILE(x)
10078 
10079 void stb__introspect(char *filename)
10080 {
10081    char *file = stb_file(filename, NULL);
10082    char *s = file, *t, **p;
10083    char *out_name = "stb_introspect.c";
10084    char *out_path;
10085    STB_ARR(char) filelist = NULL;
10086    int i,n;
10087    if (!file) stb_fatal("Couldn't open %s", filename);
10088 
10089    out_path = stb_splitpathdup(filename, STB_PATH);
10090 
10091    // search for the macros
10092    while (*s) {
10093       char buffer[256];
10094       while (*s && !isupper(*s)) ++s;
10095       s = stb_strtok_invert(buffer, s, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
10096       s = stb_skipwhite(s);
10097       if (*s == '(') {
10098          ++s;
10099          t = strchr(s, ')');
10100          if (t == NULL) stb_fatal("Error parsing %s", filename);
10101 
10102       }
10103    }
10104 }
10105 
10106 
10107 
10108 #endif
10109 
10110 
10111 //////////////////////////////////////////////////////////////////////////////
10112 //
10113 //             STB-C sliding-window dictionary compression
10114 //
10115 //  This uses a DEFLATE-style sliding window, but no bitwise entropy.
10116 //  Everything is on byte boundaries, so you could then apply a byte-wise
10117 //  entropy code, though that's nowhere near as effective.
10118 //
10119 //  An STB-C stream begins with a 16-byte header:
10120 //      4 bytes: 0x57 0xBC 0x00 0x00
10121 //      8 bytes: big-endian size of decompressed data, 64-bits
10122 //      4 bytes: big-endian size of window (how far back decompressor may need)
10123 //
10124 //  The following symbols appear in the stream (these were determined ad hoc,
10125 //  not by analysis):
10126 //
10127 //  [dict]      00000100 yyyyyyyy yyyyyyyy yyyyyyyy xxxxxxxx xxxxxxxx
10128 //  [END]       00000101 11111010 cccccccc cccccccc cccccccc cccccccc
10129 //  [dict]      00000110 yyyyyyyy yyyyyyyy yyyyyyyy xxxxxxxx
10130 //  [literals]  00000111 zzzzzzzz zzzzzzzz
10131 //  [literals]  00001zzz zzzzzzzz
10132 //  [dict]      00010yyy yyyyyyyy yyyyyyyy xxxxxxxx xxxxxxxx
10133 //  [dict]      00011yyy yyyyyyyy yyyyyyyy xxxxxxxx
10134 //  [literals]  001zzzzz
10135 //  [dict]      01yyyyyy yyyyyyyy xxxxxxxx
10136 //  [dict]      1xxxxxxx yyyyyyyy
10137 //
10138 //      xxxxxxxx: match length - 1
10139 //      yyyyyyyy: backwards distance - 1
10140 //      zzzzzzzz: num literals - 1
10141 //      cccccccc: adler32 checksum of decompressed data
10142 //   (all big-endian)
10143 
10144 
10145 STB_EXTERN stb_uint stb_decompress_length(stb_uchar *input);
10146 STB_EXTERN stb_uint stb_decompress(stb_uchar *out,stb_uchar *in,stb_uint len);
10147 STB_EXTERN stb_uint stb_compress  (stb_uchar *out,stb_uchar *in,stb_uint len);
10148 STB_EXTERN void stb_compress_window(int z);
10149 STB_EXTERN void stb_compress_hashsize(unsigned int z);
10150 
10151 STB_EXTERN int stb_compress_tofile(char *filename, char *in,  stb_uint  len);
10152 STB_EXTERN int stb_compress_intofile(FILE *f, char *input,    stb_uint  len);
10153 STB_EXTERN char *stb_decompress_fromfile(char *filename,      stb_uint *len);
10154 
10155 STB_EXTERN int stb_compress_stream_start(FILE *f);
10156 STB_EXTERN void stb_compress_stream_end(int close);
10157 STB_EXTERN void stb_write(char *data, int data_len);
10158 
10159 #ifdef STB_DEFINE
10160 
10161 stb_uint stb_decompress_length(stb_uchar *input)
10162 {
10163    return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11];
10164 }
10165 
10166 ////////////////////           decompressor         ///////////////////////
10167 
10168 // simple implementation that just writes whole thing into big block
10169 
10170 static unsigned char *stb__barrier;
10171 static unsigned char *stb__barrier2;
10172 static unsigned char *stb__barrier3;
10173 static unsigned char *stb__barrier4;
10174 
10175 static stb_uchar *stb__dout;
10176 static void stb__match(stb_uchar *data, stb_uint length)
10177 {
10178    // INVERSE of memmove... write each byte before copying the next...
10179    assert (stb__dout + length <= stb__barrier);
10180    if (stb__dout + length > stb__barrier) { stb__dout += length; return; }
10181    if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; }
10182    while (length--) *stb__dout++ = *data++;
10183 }
10184 
10185 static void stb__lit(stb_uchar *data, stb_uint length)
10186 {
10187    assert (stb__dout + length <= stb__barrier);
10188    if (stb__dout + length > stb__barrier) { stb__dout += length; return; }
10189    if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }
10190    memcpy(stb__dout, data, length);
10191    stb__dout += length;
10192 }
10193 
10194 #define stb__in2(x)   ((i[x] << 8) + i[(x)+1])
10195 #define stb__in3(x)   ((i[x] << 16) + stb__in2((x)+1))
10196 #define stb__in4(x)   ((i[x] << 24) + stb__in3((x)+1))
10197 
10198 static stb_uchar *stb_decompress_token(stb_uchar *i)
10199 {
10200    if (*i >= 0x20) { // use fewer if's for cases that expand small
10201       if (*i >= 0x80)       stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2;
10202       else if (*i >= 0x40)  stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3;
10203       else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1);
10204    } else { // more ifs for cases that expand large, since overhead is amortized
10205       if (*i >= 0x18)       stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4;
10206       else if (*i >= 0x10)  stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5;
10207       else if (*i >= 0x08)  stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1);
10208       else if (*i == 0x07)  stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1);
10209       else if (*i == 0x06)  stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5;
10210       else if (*i == 0x04)  stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6;
10211    }
10212    return i;
10213 }
10214 
10215 stb_uint stb_decompress(stb_uchar *output, stb_uchar *i, stb_uint length)
10216 {
10217    stb_uint olen;
10218    if (stb__in4(0) != 0x57bC0000) return 0;
10219    if (stb__in4(4) != 0)          return 0; // error! stream is > 4GB
10220    olen = stb_decompress_length(i);
10221    stb__barrier2 = i;
10222    stb__barrier3 = i+length;
10223    stb__barrier = output + olen;
10224    stb__barrier4 = output;
10225    i += 16;
10226 
10227    stb__dout = output;
10228    while (1) {
10229       stb_uchar *old_i = i;
10230       i = stb_decompress_token(i);
10231       if (i == old_i) {
10232          if (*i == 0x05 && i[1] == 0xfa) {
10233             assert(stb__dout == output + olen);
10234             if (stb__dout != output + olen) return 0;
10235             if (stb_adler32(1, output, olen) != (stb_uint) stb__in4(2))
10236                return 0;
10237             return olen;
10238          } else {
10239             assert(0); /* NOTREACHED */
10240             return 0;
10241          }
10242       }
10243       assert(stb__dout <= output + olen);
10244       if (stb__dout > output + olen)
10245          return 0;
10246    }
10247 }
10248 
10249 char *stb_decompress_fromfile(char *filename, unsigned int *len)
10250 {
10251    unsigned int n;
10252    char *q;
10253    unsigned char *p;
10254    FILE *f = fopen(filename, "rb");   if (f == NULL) return NULL;
10255    fseek(f, 0, SEEK_END);
10256    n = ftell(f);
10257    fseek(f, 0, SEEK_SET);
10258    p = (unsigned char * ) malloc(n); if (p == NULL) return NULL;
10259    fread(p, 1, n, f);
10260    fclose(f);
10261    if (p == NULL) return NULL;
10262    if (p[0] != 0x57 || p[1] != 0xBc || p[2] || p[3]) { free(p); return NULL; }
10263    q = (char *) malloc(stb_decompress_length(p)+1);
10264    if (!q) { free(p); return NULL; }
10265    *len = stb_decompress((unsigned char *) q, p, n);
10266    if (*len) q[*len] = 0;
10267    free(p);
10268    return q;
10269 }
10270 
10271 #if 0
10272 //  streaming decompressor
10273 
10274 static struct
10275 {
10276    stb__uchar *in_buffer;
10277    stb__uchar *match;
10278 
10279    stb__uint pending_literals;
10280    stb__uint pending_match;
10281 } xx;
10282 
10283 
10284 
10285 static void stb__match(stb_uchar *data, stb_uint length)
10286 {
10287    // INVERSE of memmove... write each byte before copying the next...
10288    assert (stb__dout + length <= stb__barrier);
10289    if (stb__dout + length > stb__barrier) { stb__dout += length; return; }
10290    if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }
10291    while (length--) *stb__dout++ = *data++;
10292 }
10293 
10294 static void stb__lit(stb_uchar *data, stb_uint length)
10295 {
10296    assert (stb__dout + length <= stb__barrier);
10297    if (stb__dout + length > stb__barrier) { stb__dout += length; return; }
10298    if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }
10299    memcpy(stb__dout, data, length);
10300    stb__dout += length;
10301 }
10302 
10303 static void sx_match(stb_uchar *data, stb_uint length)
10304 {
10305    xx.match = data;
10306    xx.pending_match = length;
10307 }
10308 
10309 static void sx_lit(stb_uchar *data, stb_uint length)
10310 {
10311    xx.pending_lit = length;
10312 }
10313 
10314 static int stb_decompress_token_state(void)
10315 {
10316    stb__uchar *i = xx.in_buffer;
10317 
10318    if (*i >= 0x20) { // use fewer if's for cases that expand small
10319       if (*i >= 0x80)       sx_match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2;
10320       else if (*i >= 0x40)  sx_match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3;
10321       else /* *i >= 0x20 */ sx_lit(i+1, i[0] - 0x20 + 1), i += 1;
10322    } else { // more ifs for cases that expand large, since overhead is amortized
10323       if (*i >= 0x18)       sx_match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4;
10324       else if (*i >= 0x10)  sx_match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5;
10325       else if (*i >= 0x08)  sx_lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2;
10326       else if (*i == 0x07)  sx_lit(i+3, stb__in2(1) + 1), i += 3;
10327       else if (*i == 0x06)  sx_match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5;
10328       else if (*i == 0x04)  sx_match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6;
10329       else return 0;
10330    }
10331    xx.in_buffer = i;
10332    return 1;
10333 }
10334 #endif
10335 
10336 
10337 
10338 ////////////////////           compressor         ///////////////////////
10339 
10340 static unsigned int stb_matchlen(stb_uchar *m1, stb_uchar *m2, stb_uint maxlen)
10341 {
10342    stb_uint i;
10343    for (i=0; i < maxlen; ++i)
10344       if (m1[i] != m2[i]) return i;
10345    return i;
10346 }
10347 
10348 // simple implementation that just takes the source data in a big block
10349 
10350 static stb_uchar *stb__out;
10351 static FILE      *stb__outfile;
10352 static stb_uint   stb__outbytes;
10353 
10354 static void stb__write(unsigned char v)
10355 {
10356    fputc(v, stb__outfile);
10357    ++stb__outbytes;
10358 }
10359 
10360 #define stb_out(v)    (stb__out ? *stb__out++ = (stb_uchar) (v) : stb__write((stb_uchar) (v)))
10361 
10362 static void stb_out2(stb_uint v)
10363 {
10364    stb_out(v >> 8);
10365    stb_out(v);
10366 }
10367 
10368 static void stb_out3(stb_uint v) { stb_out(v >> 16); stb_out(v >> 8); stb_out(v); }
10369 static void stb_out4(stb_uint v) { stb_out(v >> 24); stb_out(v >> 16);
10370                                    stb_out(v >> 8 ); stb_out(v);                  }
10371 
10372 static void outliterals(stb_uchar *in, int numlit)
10373 {
10374    while (numlit > 65536) {
10375       outliterals(in,65536);
10376       in     += 65536;
10377       numlit -= 65536;
10378    }
10379 
10380    if      (numlit ==     0)    ;
10381    else if (numlit <=    32)    stb_out (0x000020 + numlit-1);
10382    else if (numlit <=  2048)    stb_out2(0x000800 + numlit-1);
10383    else /*  numlit <= 65536) */ stb_out3(0x070000 + numlit-1);
10384 
10385    if (stb__out) {
10386       memcpy(stb__out,in,numlit);
10387       stb__out += numlit;
10388    } else
10389       fwrite(in, 1, numlit, stb__outfile);
10390 }
10391 
10392 static int stb__window = 0x40000; // 256K
10393 void stb_compress_window(int z)
10394 {
10395    if (z >= 0x1000000) z = 0x1000000; // limit of implementation
10396    if (z <      0x100) z = 0x100;   // insanely small
10397    stb__window = z;
10398 }
10399 
10400 static int stb_not_crap(int best, int dist)
10401 {
10402    return   ((best > 2  &&  dist <= 0x00100)
10403           || (best > 5  &&  dist <= 0x04000)
10404           || (best > 7  &&  dist <= 0x80000));
10405 }
10406 
10407 static  stb_uint stb__hashsize = 32768;
10408 void stb_compress_hashsize(unsigned int y)
10409 {
10410    unsigned int z = 1024;
10411    while (z < y) z <<= 1;
10412    stb__hashsize = z >> 2;   // pass in bytes, store #pointers
10413 }
10414 
10415 // note that you can play with the hashing functions all you
10416 // want without needing to change the decompressor
10417 #define stb__hc(q,h,c)      (((h) << 7) + ((h) >> 25) + q[c])
10418 #define stb__hc2(q,h,c,d)   (((h) << 14) + ((h) >> 18) + (q[c] << 7) + q[d])
10419 #define stb__hc3(q,c,d,e)   ((q[c] << 14) + (q[d] << 7) + q[e])
10420 
10421 static stb_uint32 stb__running_adler;
10422 
10423 static int stb_compress_chunk(stb_uchar *history,
10424                               stb_uchar *start,
10425                               stb_uchar *end,
10426                               int length,
10427                               int *pending_literals,
10428                               stb_uchar **chash,
10429                               stb_uint mask)
10430 {
10431    int window = stb__window;
10432    stb_uint match_max;
10433    stb_uchar *lit_start = start - *pending_literals;
10434    stb_uchar *q = start;
10435 
10436    #define STB__SCRAMBLE(h)   (((h) + ((h) >> 16)) & mask)
10437 
10438    // stop short of the end so we don't scan off the end doing
10439    // the hashing; this means we won't compress the last few bytes
10440    // unless they were part of something longer
10441    while (q < start+length && q+12 < end) {
10442       int m;
10443       stb_uint h1,h2,h3,h4, h;
10444       stb_uchar *t;
10445       int best = 2, dist=0;
10446 
10447       if (q+65536 > end)
10448          match_max = end-q;
10449       else
10450          match_max = 65536;
10451 
10452       #define stb__nc(b,d)  ((d) <= window && ((b) > 9 || stb_not_crap(b,d)))
10453 
10454       #define STB__TRY(t,p)  /* avoid retrying a match we already tried */ \
10455                       if (p ? dist != q-t : 1)                             \
10456                       if ((m = stb_matchlen(t, q, match_max)) > best)     \
10457                       if (stb__nc(m,q-(t)))                                \
10458                           best = m, dist = q - (t)
10459 
10460       // rather than search for all matches, only try 4 candidate locations,
10461       // chosen based on 4 different hash functions of different lengths.
10462       // this strategy is inspired by LZO; hashing is unrolled here using the
10463       // 'hc' macro
10464       h = stb__hc3(q,0, 1, 2); h1 = STB__SCRAMBLE(h);
10465                                       t = chash[h1]; if (t) STB__TRY(t,0);
10466       h = stb__hc2(q,h, 3, 4); h2 = STB__SCRAMBLE(h);
10467       h = stb__hc2(q,h, 5, 6);        t = chash[h2]; if (t) STB__TRY(t,1);
10468       h = stb__hc2(q,h, 7, 8); h3 = STB__SCRAMBLE(h);
10469       h = stb__hc2(q,h, 9,10);        t = chash[h3]; if (t) STB__TRY(t,1);
10470       h = stb__hc2(q,h,11,12); h4 = STB__SCRAMBLE(h);
10471                                       t = chash[h4]; if (t) STB__TRY(t,1);
10472 
10473       // because we use a shared hash table, can only update it
10474       // _after_ we've probed all of them
10475       chash[h1] = chash[h2] = chash[h3] = chash[h4] = q;
10476 
10477       if (best > 2)
10478          assert(dist > 0);
10479 
10480       // see if our best match qualifies
10481       if (best < 3) { // fast path literals
10482          ++q;
10483       } else if (best > 2  &&  best <= 0x80    &&  dist <= 0x100) {
10484          outliterals(lit_start, q-lit_start); lit_start = (q += best);
10485          stb_out(0x80 + best-1);
10486          stb_out(dist-1);
10487       } else if (best > 5  &&  best <= 0x100   &&  dist <= 0x4000) {
10488          outliterals(lit_start, q-lit_start); lit_start = (q += best);
10489          stb_out2(0x4000 + dist-1);
10490          stb_out(best-1);
10491       } else if (best > 7  &&  best <= 0x100   &&  dist <= 0x80000) {
10492          outliterals(lit_start, q-lit_start); lit_start = (q += best);
10493          stb_out3(0x180000 + dist-1);
10494          stb_out(best-1);
10495       } else if (best > 8  &&  best <= 0x10000 &&  dist <= 0x80000) {
10496          outliterals(lit_start, q-lit_start); lit_start = (q += best);
10497          stb_out3(0x100000 + dist-1);
10498          stb_out2(best-1);
10499       } else if (best > 9                      &&  dist <= 0x1000000) {
10500          if (best > 65536) best = 65536;
10501          outliterals(lit_start, q-lit_start); lit_start = (q += best);
10502          if (best <= 0x100) {
10503             stb_out(0x06);
10504             stb_out3(dist-1);
10505             stb_out(best-1);
10506          } else {
10507             stb_out(0x04);
10508             stb_out3(dist-1);
10509             stb_out2(best-1);
10510          }
10511       } else {  // fallback literals if no match was a balanced tradeoff
10512          ++q;
10513       }
10514    }
10515 
10516    // if we didn't get all the way, add the rest to literals
10517    if (q-start < length)
10518       q = start+length;
10519 
10520    // the literals are everything from lit_start to q
10521    *pending_literals = (q - lit_start);
10522 
10523    stb__running_adler = stb_adler32(stb__running_adler, start, q - start);
10524    return q - start;
10525 }
10526 
10527 static int stb_compress_inner(stb_uchar *input, stb_uint length)
10528 {
10529    int literals = 0;
10530    stb_uint len,i;
10531 
10532    stb_uchar **chash;
10533    chash = (stb_uchar**) malloc(stb__hashsize * sizeof(stb_uchar*));
10534    if (chash == NULL) return 0; // failure
10535    for (i=0; i < stb__hashsize; ++i)
10536       chash[i] = NULL;
10537 
10538    // stream signature
10539    stb_out(0x57); stb_out(0xbc);
10540    stb_out2(0);
10541 
10542    stb_out4(0);       // 64-bit length requires 32-bit leading 0
10543    stb_out4(length);
10544    stb_out4(stb__window);
10545 
10546    stb__running_adler = 1;
10547 
10548    len = stb_compress_chunk(input, input, input+length, length, &literals, chash, stb__hashsize-1);
10549    assert(len == length);
10550 
10551    outliterals(input+length - literals, literals);
10552 
10553    free(chash);
10554 
10555    stb_out2(0x05fa); // end opcode
10556 
10557    stb_out4(stb__running_adler);
10558 
10559    return 1; // success
10560 }
10561 
10562 stb_uint stb_compress(stb_uchar *out, stb_uchar *input, stb_uint length)
10563 {
10564    stb__out = out;
10565    stb__outfile = NULL;
10566 
10567    stb_compress_inner(input, length);
10568 
10569    return stb__out - out;
10570 }
10571 
10572 int stb_compress_tofile(char *filename, char *input, unsigned int length)
10573 {
10574    //int maxlen = length + 512 + (length >> 2); // total guess
10575    //char *buffer = (char *) malloc(maxlen);
10576    //int blen = stb_compress((stb_uchar*)buffer, (stb_uchar*)input, length);
10577 
10578    stb__out = NULL;
10579    stb__outfile = fopen(filename, "wb");
10580    if (!stb__outfile) return 0;
10581 
10582    stb__outbytes = 0;
10583 
10584    if (!stb_compress_inner((stb_uchar*)input, length))
10585       return 0;
10586 
10587    fclose(stb__outfile);
10588 
10589    return stb__outbytes;
10590 }
10591 
10592 int stb_compress_intofile(FILE *f, char *input, unsigned int length)
10593 {
10594    //int maxlen = length + 512 + (length >> 2); // total guess
10595    //char *buffer = (char*)malloc(maxlen);
10596    //int blen = stb_compress((stb_uchar*)buffer, (stb_uchar*)input, length);
10597 
10598    stb__out = NULL;
10599    stb__outfile = f;
10600    if (!stb__outfile) return 0;
10601 
10602    stb__outbytes = 0;
10603 
10604    if (!stb_compress_inner((stb_uchar*)input, length))
10605       return 0;
10606 
10607    return stb__outbytes;
10608 }
10609 
10610 //////////////////////    streaming I/O version    /////////////////////
10611 
10612 
10613 static size_t stb_out_backpatch_id(void)
10614 {
10615    if (stb__out)
10616       return (size_t) stb__out;
10617    else
10618       return ftell(stb__outfile);
10619 }
10620 
10621 static void stb_out_backpatch(size_t id, stb_uint value)
10622 {
10623    stb_uchar data[4] = { value >> 24, value >> 16, value >> 8, value };
10624    if (stb__out) {
10625       memcpy((void *) id, data, 4);
10626    } else {
10627       stb_uint where = ftell(stb__outfile);
10628       fseek(stb__outfile, id, SEEK_SET);
10629       fwrite(data, 4, 1, stb__outfile);
10630       fseek(stb__outfile, where, SEEK_SET);
10631    }
10632 }
10633 
10634 // ok, the wraparound buffer was a total failure. let's instead
10635 // use a copying-in-place buffer, which lets us share the code.
10636 // This is way less efficient but it'll do for now.
10637 
10638 static struct
10639 {
10640    stb_uchar *buffer;
10641    int size;           // physical size of buffer in bytes
10642 
10643    int valid;          // amount of valid data in bytes
10644    int start;          // bytes of data already output
10645 
10646    int window;
10647    int fsize;
10648 
10649    int pending_literals; // bytes not-quite output but counted in start
10650    int length_id;
10651 
10652    stb_uint total_bytes;
10653 
10654    stb_uchar **chash;
10655    stb_uint    hashmask;
10656 } xtb;
10657 
10658 static int stb_compress_streaming_start(void)
10659 {
10660    stb_uint i;
10661    xtb.size = stb__window * 3;
10662    xtb.buffer = (stb_uchar*)malloc(xtb.size);
10663    if (!xtb.buffer) return 0;
10664 
10665    xtb.chash = (stb_uchar**)malloc(sizeof(*xtb.chash) * stb__hashsize);
10666    if (!xtb.chash) {
10667       free(xtb.buffer);
10668       return 0;
10669    }
10670 
10671    for (i=0; i < stb__hashsize; ++i)
10672       xtb.chash[i] = NULL;
10673 
10674    xtb.hashmask = stb__hashsize-1;
10675 
10676    xtb.valid        = 0;
10677    xtb.start        = 0;
10678    xtb.window       = stb__window;
10679    xtb.fsize        = stb__window;
10680    xtb.pending_literals = 0;
10681    xtb.total_bytes  = 0;
10682 
10683       // stream signature
10684    stb_out(0x57); stb_out(0xbc); stb_out2(0);
10685 
10686    stb_out4(0);       // 64-bit length requires 32-bit leading 0
10687 
10688    xtb.length_id = stb_out_backpatch_id();
10689    stb_out4(0);       // we don't know the output length yet
10690 
10691    stb_out4(stb__window);
10692 
10693    stb__running_adler = 1;
10694 
10695    return 1;
10696 }
10697 
10698 static int stb_compress_streaming_end(void)
10699 {
10700    // flush out any remaining data
10701    stb_compress_chunk(xtb.buffer, xtb.buffer+xtb.start, xtb.buffer+xtb.valid,
10702                       xtb.valid-xtb.start, &xtb.pending_literals, xtb.chash, xtb.hashmask);
10703 
10704    // write out pending literals
10705    outliterals(xtb.buffer + xtb.valid - xtb.pending_literals, xtb.pending_literals);
10706 
10707    stb_out2(0x05fa); // end opcode
10708    stb_out4(stb__running_adler);
10709 
10710    stb_out_backpatch(xtb.length_id, xtb.total_bytes);
10711 
10712    free(xtb.buffer);
10713    free(xtb.chash);
10714    return 1;
10715 }
10716 
10717 void stb_write(char *data, int data_len)
10718 {
10719    stb_uint i;
10720 
10721    // @TODO: fast path for filling the buffer and doing nothing else
10722    //   if (xtb.valid + data_len < xtb.size)
10723 
10724    xtb.total_bytes += data_len;
10725 
10726    while (data_len) {
10727       // fill buffer
10728       if (xtb.valid < xtb.size) {
10729          int amt = xtb.size - xtb.valid;
10730          if (data_len < amt) amt = data_len;
10731          memcpy(xtb.buffer + xtb.valid, data, amt);
10732          data_len -= amt;
10733          data     += amt;
10734          xtb.valid += amt;
10735       }
10736       if (xtb.valid < xtb.size)
10737          return;
10738 
10739       // at this point, the buffer is full
10740 
10741       // if we can process some data, go for it; make sure
10742       // we leave an 'fsize's worth of data, though
10743       if (xtb.start + xtb.fsize < xtb.valid) {
10744          int amount = (xtb.valid - xtb.fsize) - xtb.start;
10745          int n;
10746          assert(amount > 0);
10747          n = stb_compress_chunk(xtb.buffer, xtb.buffer + xtb.start, xtb.buffer + xtb.valid,
10748                                 amount, &xtb.pending_literals, xtb.chash, xtb.hashmask);
10749          xtb.start += n;
10750       }
10751 
10752       assert(xtb.start + xtb.fsize >= xtb.valid);
10753       // at this point, our future size is too small, so we
10754       // need to flush some history. we, in fact, flush exactly
10755       // one window's worth of history
10756 
10757       {
10758          int flush = xtb.window;
10759          assert(xtb.start >= flush);
10760          assert(xtb.valid >= flush);
10761 
10762          // if 'pending literals' extends back into the shift region,
10763          // write them out
10764          if (xtb.start - xtb.pending_literals < flush) {
10765             outliterals(xtb.buffer + xtb.start - xtb.pending_literals, xtb.pending_literals);
10766             xtb.pending_literals = 0;
10767          }
10768 
10769          // now shift the window
10770          memmove(xtb.buffer, xtb.buffer + flush, xtb.valid - flush);
10771          xtb.start -= flush;
10772          xtb.valid -= flush;
10773 
10774          for (i=0; i <= xtb.hashmask; ++i)
10775             if (xtb.chash[i] < xtb.buffer + flush)
10776                xtb.chash[i] = NULL;
10777             else
10778                xtb.chash[i] -= flush;
10779       }
10780       // and now that we've made room for more data, go back to the top
10781    }
10782 }
10783 
10784 int stb_compress_stream_start(FILE *f)
10785 {
10786    stb__out = NULL;
10787    stb__outfile = f;
10788 
10789    if (f == NULL)
10790       return 0;
10791 
10792    if (!stb_compress_streaming_start())
10793       return 0;
10794 
10795    return 1;
10796 }
10797 
10798 void stb_compress_stream_end(int close)
10799 {
10800    stb_compress_streaming_end();
10801    if (close && stb__outfile) {
10802       fclose(stb__outfile);
10803    }
10804 }
10805 
10806 #endif // STB_DEFINE
10807 
10808 //////////////////////////////////////////////////////////////////////////////
10809 //
10810 //  File abstraction... tired of not having this... we can write
10811 //  compressors to be layers over these that auto-close their children.
10812 
10813 
10814 typedef struct stbfile
10815 {
10816    int (*getbyte)(struct stbfile *);  // -1 on EOF
10817    unsigned int (*getdata)(struct stbfile *, void *block, unsigned int len);
10818 
10819    int (*putbyte)(struct stbfile *, int byte);
10820    unsigned int (*putdata)(struct stbfile *, void *block, unsigned int len);
10821 
10822    unsigned int (*size)(struct stbfile *);
10823 
10824    unsigned int (*tell)(struct stbfile *);
10825    void (*backpatch)(struct stbfile *, unsigned int tell, void *block, unsigned int len);
10826 
10827    void (*close)(struct stbfile *);
10828 
10829    FILE *f;  // file to fread/fwrite
10830    unsigned char *buffer; // input/output buffer
10831    unsigned char *indata, *inend; // input buffer
10832    union {
10833       int various;
10834       void *ptr;
10835    };
10836 } stbfile;
10837 
10838 STB_EXTERN unsigned int stb_getc(stbfile *f); // read
10839 STB_EXTERN int stb_putc(stbfile *f, int ch); // write
10840 STB_EXTERN unsigned int stb_getdata(stbfile *f, void *buffer, unsigned int len); // read
10841 STB_EXTERN unsigned int stb_putdata(stbfile *f, void *buffer, unsigned int len); // write
10842 STB_EXTERN unsigned int stb_tell(stbfile *f); // read
10843 STB_EXTERN unsigned int stb_size(stbfile *f); // read/write
10844 STB_EXTERN void stb_backpatch(stbfile *f, unsigned int tell, void *buffer, unsigned int len); // write
10845 
10846 #ifdef STB_DEFINE
10847 
10848 unsigned int stb_getc(stbfile *f) { return f->getbyte(f); }
10849 int stb_putc(stbfile *f, int ch)  { return f->putbyte(f, ch); }
10850 
10851 unsigned int stb_getdata(stbfile *f, void *buffer, unsigned int len)
10852 {
10853    return f->getdata(f, buffer, len);
10854 }
10855 unsigned int stb_putdata(stbfile *f, void *buffer, unsigned int len)
10856 {
10857    return f->putdata(f, buffer, len);
10858 }
10859 void stb_close(stbfile *f)
10860 {
10861    f->close(f);
10862    free(f);
10863 }
10864 unsigned int stb_tell(stbfile *f) { return f->tell(f); }
10865 unsigned int stb_size(stbfile *f) { return f->size(f); }
10866 void stb_backpatch(stbfile *f, unsigned int tell, void *buffer, unsigned int len)
10867 {
10868    f->backpatch(f,tell,buffer,len);
10869 }
10870 
10871 // FILE * implementation
10872 static int stb__fgetbyte(stbfile *f) { return fgetc(f->f); }
10873 static int stb__fputbyte(stbfile *f, int ch) { return fputc(ch, f->f)==0; }
10874 static unsigned int stb__fgetdata(stbfile *f, void *buffer, unsigned int len) { return fread(buffer,1,len,f->f); }
10875 static unsigned int stb__fputdata(stbfile *f, void *buffer, unsigned int len) { return fwrite(buffer,1,len,f->f); }
10876 static unsigned int stb__fsize(stbfile *f) { return stb_filelen(f->f); }
10877 static unsigned int stb__ftell(stbfile *f) { return ftell(f->f); }
10878 static void stb__fbackpatch(stbfile *f, unsigned int where, void *buffer, unsigned int len)
10879 {
10880    fseek(f->f, where, SEEK_SET);
10881    fwrite(buffer, 1, len, f->f);
10882    fseek(f->f, 0, SEEK_END);
10883 }
10884 static void         stb__fclose(stbfile *f) { fclose(f->f); }
10885 
10886 stbfile *stb_openf(FILE *f)
10887 {
10888    stbfile m = { stb__fgetbyte, stb__fgetdata,
10889                  stb__fputbyte, stb__fputdata,
10890                  stb__fsize, stb__ftell, stb__fbackpatch, stb__fclose,
10891                  0,0,0, };
10892    stbfile *z = (stbfile *) malloc(sizeof(*z));
10893    if (z) {
10894       *z = m;
10895       z->f = f;
10896    }
10897    return z;
10898 }
10899 
10900 static int stb__nogetbyte(stbfile *f) { assert(0); return -1; }
10901 static unsigned int stb__nogetdata(stbfile *f, void *buffer, unsigned int len) { assert(0); return 0; }
10902 static int stb__noputbyte(stbfile *f, int ch) { assert(0); return 0; }
10903 static unsigned int stb__noputdata(stbfile *f, void *buffer, unsigned int len) { assert(0); return 0; }
10904 static void stb__nobackpatch(stbfile *f, unsigned int where, void *buffer, unsigned int len) { assert(0); }
10905 
10906 static int stb__bgetbyte(stbfile *s)
10907 {
10908    if (s->indata < s->inend)
10909       return *s->indata++;
10910    else
10911       return -1;
10912 }
10913 
10914 static unsigned int stb__bgetdata(stbfile *s, void *buffer, unsigned int len)
10915 {
10916    if (s->indata + len > s->inend)
10917       len = s->inend - s->indata;
10918    memcpy(buffer, s->indata, len);
10919    s->indata += len;
10920    return len;
10921 }
10922 static unsigned int stb__bsize(stbfile *s) { return s->inend - s->buffer; }
10923 static unsigned int stb__btell(stbfile *s) { return s->indata - s->buffer; }
10924 
10925 static void stb__bclose(stbfile *s)
10926 {
10927    if (s->various)
10928       free(s->buffer);
10929 }
10930 
10931 stbfile *stb_open_inbuffer(void *buffer, unsigned int len)
10932 {
10933    stbfile m = { stb__bgetbyte, stb__bgetdata,
10934                  stb__noputbyte, stb__noputdata,
10935                  stb__bsize, stb__btell, stb__nobackpatch, stb__bclose };
10936    stbfile *z = (stbfile *) malloc(sizeof(*z));
10937    if (z) {
10938       *z = m;
10939       z->buffer = (unsigned char *) buffer;
10940       z->indata = z->buffer;
10941       z->inend = z->indata + len;
10942    }
10943    return z;
10944 }
10945 
10946 stbfile *stb_open_inbuffer_free(void *buffer, unsigned int len)
10947 {
10948    stbfile *z = stb_open_inbuffer(buffer, len);
10949    if (z)
10950       z->various = 1; // free
10951    return z;
10952 }
10953 
10954 #ifndef STB_VERSION
10955 // if we've been cut-and-pasted elsewhere, you get a limited
10956 // version of stb_open, without the 'k' flag and utf8 support
10957 static void stb__fclose2(stbfile *f)
10958 {
10959    fclose(f->f);
10960 }
10961 
10962 stbfile *stb_open(char *filename, char *mode)
10963 {
10964    FILE *f = fopen(filename, mode);
10965    stbfile *s;
10966    if (f == NULL) return NULL;
10967    s = stb_openf(f);
10968    if (s)
10969       s->close = stb__fclose2;
10970    return s;
10971 }
10972 #else
10973 // the full version depends on some code in stb.h; this
10974 // also includes the memory buffer output format implemented with stb_arr
10975 static void stb__fclose2(stbfile *f)
10976 {
10977    stb_fclose(f->f, f->various);
10978 }
10979 
10980 stbfile *stb_open(char *filename, char *mode)
10981 {
10982    FILE *f = stb_fopen(filename, mode[0] == 'k' ? mode+1 : mode);
10983    stbfile *s;
10984    if (f == NULL) return NULL;
10985    s = stb_openf(f);
10986    if (s) {
10987       s->close = stb__fclose2;
10988       s->various = mode[0] == 'k' ? stb_keep_if_different : stb_keep_yes;
10989    }
10990    return s;
10991 }
10992 
10993 static int stb__aputbyte(stbfile *f, int ch)
10994 {
10995    stb_arr_push(f->buffer, ch);
10996    return 1;
10997 }
10998 static unsigned int stb__aputdata(stbfile *f, void *data, unsigned int len)
10999 {
11000    memcpy(stb_arr_addn(f->buffer, (int) len), data, len);
11001    return len;
11002 }
11003 static unsigned int stb__asize(stbfile *f) { return stb_arr_len(f->buffer); }
11004 static void stb__abackpatch(stbfile *f, unsigned int where, void *data, unsigned int len)
11005 {
11006    memcpy(f->buffer+where, data, len);
11007 }
11008 static void stb__aclose(stbfile *f)
11009 {
11010    *(unsigned char **) f->ptr = f->buffer;
11011 }
11012 
11013 stbfile *stb_open_outbuffer(unsigned char **update_on_close)
11014 {
11015    stbfile m = { stb__nogetbyte, stb__nogetdata,
11016                  stb__aputbyte, stb__aputdata,
11017                  stb__asize, stb__asize, stb__abackpatch, stb__aclose };
11018    stbfile *z = (stbfile *) malloc(sizeof(*z));
11019    if (z) {
11020       z->ptr = update_on_close;
11021       *z = m;
11022    }
11023    return z;
11024 }
11025 #endif
11026 #endif
11027 
11028 
11029 //////////////////////////////////////////////////////////////////////////////
11030 //
11031 //  Arithmetic coder... based on cbloom's notes on the subject, should be
11032 //  less code than a huffman code.
11033 
11034 typedef struct
11035 {
11036    unsigned int range_low;
11037    unsigned int range_high;
11038    unsigned int code, range; // decode
11039    int buffered_u8;
11040    int pending_ffs;
11041    stbfile *output;
11042 } stb_arith;
11043 
11044 STB_EXTERN void stb_arith_init_encode(stb_arith *a, stbfile *out);
11045 STB_EXTERN void stb_arith_init_decode(stb_arith *a, stbfile *in);
11046 STB_EXTERN stbfile *stb_arith_encode_close(stb_arith *a);
11047 STB_EXTERN stbfile *stb_arith_decode_close(stb_arith *a);
11048 
11049 STB_EXTERN void stb_arith_encode(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq);
11050 STB_EXTERN void stb_arith_encode_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq);
11051 STB_EXTERN unsigned int stb_arith_decode_value(stb_arith *a, unsigned int totalfreq);
11052 STB_EXTERN void stb_arith_decode_advance(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq);
11053 STB_EXTERN unsigned int stb_arith_decode_value_log2(stb_arith *a, unsigned int totalfreq2);
11054 STB_EXTERN void stb_arith_decode_advance_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq);
11055 
11056 STB_EXTERN void stb_arith_encode_byte(stb_arith *a, int byte);
11057 STB_EXTERN int  stb_arith_decode_byte(stb_arith *a);
11058 
11059 // this is a memory-inefficient way of doing things, but it's
11060 // fast(?) and simple
11061 typedef struct
11062 {
11063    unsigned short cumfreq;
11064    unsigned short samples;
11065 } stb_arith_symstate_item;
11066 
11067 typedef struct
11068 {
11069    int num_sym;
11070    unsigned int pow2;
11071    int countdown;
11072    stb_arith_symstate_item data[1];
11073 } stb_arith_symstate;
11074 
11075 #ifdef STB_DEFINE
11076 void stb_arith_init_encode(stb_arith *a, stbfile *out)
11077 {
11078    a->range_low = 0;
11079    a->range_high = 0xffffffff;
11080    a->pending_ffs = -1; // means no buffered character currently, to speed up normal case
11081    a->output = out;
11082 }
11083 
11084 static void stb__arith_carry(stb_arith *a)
11085 {
11086    int i;
11087    assert(a->pending_ffs != -1); // can't carry with no data
11088    stb_putc(a->output, a->buffered_u8);
11089    for (i=0; i < a->pending_ffs; ++i)
11090       stb_putc(a->output, 0);
11091 }
11092 
11093 static void stb__arith_putbyte(stb_arith *a, int byte)
11094 {
11095    if (a->pending_ffs) {
11096       if (a->pending_ffs == -1) { // means no buffered data; encoded for fast path efficiency
11097          if (byte == 0xff)
11098             stb_putc(a->output, byte); // just write it immediately
11099          else {
11100             a->buffered_u8 = byte;
11101             a->pending_ffs = 0;
11102          }
11103       } else if (byte == 0xff) {
11104          ++a->pending_ffs;
11105       } else {
11106          int i;
11107          stb_putc(a->output, a->buffered_u8);
11108          for (i=0; i < a->pending_ffs; ++i)
11109             stb_putc(a->output, 0xff);
11110       }
11111    } else if (byte == 0xff) {
11112       ++a->pending_ffs;
11113    } else {
11114       // fast path
11115       stb_putc(a->output, a->buffered_u8);
11116       a->buffered_u8 = byte;
11117    }
11118 }
11119 
11120 static void stb__arith_flush(stb_arith *a)
11121 {
11122    if (a->pending_ffs >= 0) {
11123       int i;
11124       stb_putc(a->output, a->buffered_u8);
11125       for (i=0; i < a->pending_ffs; ++i)
11126          stb_putc(a->output, 0xff);
11127    }
11128 }
11129 
11130 static void stb__renorm_encoder(stb_arith *a)
11131 {
11132    stb__arith_putbyte(a, a->range_low >> 24);
11133    a->range_low <<= 8;
11134    a->range_high = (a->range_high << 8) | 0xff;
11135 }
11136 
11137 static void stb__renorm_decoder(stb_arith *a)
11138 {
11139    int c = stb_getc(a->output);
11140    a->code = (a->code << 8) + (c >= 0 ? c : 0); // if EOF, insert 0
11141 }
11142 
11143 void stb_arith_encode(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq)
11144 {
11145    unsigned int range = a->range_high - a->range_low;
11146    unsigned int old = a->range_low;
11147    range /= totalfreq;
11148    a->range_low += range * cumfreq;
11149    a->range_high = a->range_low + range*freq;
11150    if (a->range_low < old)
11151       stb__arith_carry(a);
11152    while (a->range_high - a->range_low < 0x1000000)
11153       stb__renorm_encoder(a);
11154 }
11155 
11156 void stb_arith_encode_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq)
11157 {
11158    unsigned int range = a->range_high - a->range_low;
11159    unsigned int old = a->range_low;
11160    range >>= totalfreq2;
11161    a->range_low += range * cumfreq;
11162    a->range_high = a->range_low + range*freq;
11163    if (a->range_low < old)
11164       stb__arith_carry(a);
11165    while (a->range_high - a->range_low < 0x1000000)
11166       stb__renorm_encoder(a);
11167 }
11168 
11169 unsigned int stb_arith_decode_value(stb_arith *a, unsigned int totalfreq)
11170 {
11171    unsigned int freqsize = a->range / totalfreq;
11172    unsigned int z = a->code / freqsize;
11173    return z >= totalfreq ? totalfreq-1 : z;
11174 }
11175 
11176 void stb_arith_decode_advance(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq)
11177 {
11178    unsigned int freqsize = a->range / totalfreq; // @OPTIMIZE, share with above divide somehow?
11179    a->code -= freqsize * cumfreq;
11180    a->range = freqsize * freq;
11181    while (a->range < 0x1000000)
11182       stb__renorm_decoder(a);
11183 }
11184 
11185 unsigned int stb_arith_decode_value_log2(stb_arith *a, unsigned int totalfreq2)
11186 {
11187    unsigned int freqsize = a->range >> totalfreq2;
11188    unsigned int z = a->code / freqsize;
11189    return z >= (1U<<totalfreq2) ? (1U<<totalfreq2)-1 : z;
11190 }
11191 
11192 void stb_arith_decode_advance_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq)
11193 {
11194    unsigned int freqsize = a->range >> totalfreq2;
11195    a->code -= freqsize * cumfreq;
11196    a->range = freqsize * freq;
11197    while (a->range < 0x1000000)
11198       stb__renorm_decoder(a);
11199 }
11200 
11201 stbfile *stb_arith_encode_close(stb_arith *a)
11202 {
11203    // put exactly as many bytes as we'll read, so we can turn on/off arithmetic coding in a stream
11204    stb__arith_putbyte(a, a->range_low >> 24);
11205    stb__arith_putbyte(a, a->range_low >> 16);
11206    stb__arith_putbyte(a, a->range_low >>  8);
11207    stb__arith_putbyte(a, a->range_low >>  0);
11208    stb__arith_flush(a);
11209    return a->output;
11210 }
11211 
11212 stbfile *stb_arith_decode_close(stb_arith *a)
11213 {
11214    return a->output;
11215 }
11216 
11217 // this is a simple power-of-two based model -- using
11218 // power of two means we need one divide per decode,
11219 // not two.
11220 #define POW2_LIMIT   12
11221 stb_arith_symstate *stb_arith_state_create(int num_sym)
11222 {
11223    stb_arith_symstate *s = (stb_arith_symstate *) malloc(sizeof(*s) + (num_sym-1) * sizeof(s->data[0]));
11224    if (s) {
11225       int i, cf, cf_next, next;
11226       int start_freq, extra;
11227       s->num_sym = num_sym;
11228       s->pow2 = 4;
11229       while (s->pow2 < 15 && (1 << s->pow2) < 3*num_sym) {
11230          ++s->pow2;
11231       }
11232       start_freq = (1 << s->pow2) / num_sym;
11233       assert(start_freq >= 1);
11234       extra = (1 << s->pow2) % num_sym;
11235       // now set up the initial stats
11236 
11237       if (s->pow2 < POW2_LIMIT)
11238          next = 0;
11239       else
11240          next = 1;
11241 
11242       cf = cf_next = 0;
11243       for (i=0; i < extra; ++i) {
11244          s->data[i].cumfreq = cf;
11245          s->data[i].samples = next;
11246          cf += start_freq+1;
11247          cf_next += next;
11248       }
11249       for (; i < num_sym; ++i) {
11250          s->data[i].cumfreq = cf;
11251          s->data[i].samples = next;
11252          cf += start_freq;
11253          cf_next += next;
11254       }
11255       assert(cf == (1 << s->pow2));
11256       // now, how long should we go until we have 2 << s->pow2 samples?
11257       s->countdown = (2 << s->pow2) - cf - cf_next;
11258    }
11259    return s;
11260 }
11261 
11262 static void stb_arith_state_rescale(stb_arith_symstate *s)
11263 {
11264    if (s->pow2 < POW2_LIMIT) {
11265       int pcf, cf, cf_next, next, i;
11266       ++s->pow2;
11267       if (s->pow2 < POW2_LIMIT)
11268          next = 0;
11269       else
11270          next = 1;
11271       cf = cf_next = 0;
11272       pcf = 0;
11273       for (i=0; i < s->num_sym; ++i) {
11274          int sample = s->data[i].cumfreq - pcf + s->data[i].samples;
11275          s->data[i].cumfreq = cf;
11276          cf += sample;
11277          s->data[i].samples = next;
11278          cf_next += next;
11279       }
11280       assert(cf == (1 << s->pow2));
11281       s->countdown = (2 << s->pow2) - cf - cf_next;
11282    } else {
11283       int pcf, cf, cf_next, i;
11284       cf = cf_next = 0;
11285       pcf = 0;
11286       for (i=0; i < s->num_sym; ++i) {
11287          int sample = (s->data[i].cumfreq - pcf + s->data[i].samples) >> 1;
11288          s->data[i].cumfreq = cf;
11289          cf += sample;
11290          s->data[i].samples = 1;
11291          cf_next += 1;
11292       }
11293       assert(cf == (1 << s->pow2)); // this isn't necessarily true, due to rounding down!
11294       s->countdown = (2 << s->pow2) - cf - cf_next;
11295    }
11296 }
11297 
11298 void stb_arith_encode_byte(stb_arith *a, int byte)
11299 {
11300 }
11301 
11302 int  stb_arith_decode_byte(stb_arith *a)
11303 {
11304    return -1;
11305 }
11306 #endif
11307 
11308 //////////////////////////////////////////////////////////////////////////////
11309 //
11310 //                         Threads
11311 //
11312 
11313 #ifndef _WIN32
11314 #ifdef STB_THREADS
11315 #error "threads not implemented except for Windows"
11316 #endif
11317 #endif
11318 
11319 // call this function to free any global variables for memory testing
11320 STB_EXTERN void stb_thread_cleanup(void);
11321 
11322 typedef void * (*stb_thread_func)(void *);
11323 
11324 // do not rely on these types, this is an implementation detail.
11325 // compare against STB_THREAD_NULL and ST_SEMAPHORE_NULL
11326 typedef void *stb_thread;
11327 typedef void *stb_semaphore;
11328 typedef void *stb_mutex;
11329 typedef struct stb__sync *stb_sync;
11330 
11331 #define STB_SEMAPHORE_NULL    NULL
11332 #define STB_THREAD_NULL       NULL
11333 #define STB_MUTEX_NULL        NULL
11334 #define STB_SYNC_NULL         NULL
11335 
11336 // get the number of processors (limited to those in the affinity mask for this process).
11337 STB_EXTERN int stb_processor_count(void);
11338 // force to run on a single core -- needed for RDTSC to work, e.g. for iprof
11339 STB_EXTERN void stb_force_uniprocessor(void);
11340 
11341 // stb_work functions: queue up work to be done by some worker threads
11342 
11343 // set number of threads to serve the queue; you can change this on the fly,
11344 // but if you decrease it, it won't decrease until things currently on the
11345 // queue are finished
11346 STB_EXTERN void          stb_work_numthreads(int n);
11347 // set maximum number of units in the queue; you can only set this BEFORE running any work functions
11348 STB_EXTERN int           stb_work_maxunits(int n);
11349 // enqueue some work to be done (can do this from any thread, or even from a piece of work);
11350 // return value of f is stored in *return_code if non-NULL
11351 STB_EXTERN int           stb_work(stb_thread_func f, void *d, volatile void **return_code);
11352 // as above, but stb_sync_reach is called on 'rel' after work is complete
11353 STB_EXTERN int           stb_work_reach(stb_thread_func f, void *d, volatile void **return_code, stb_sync rel);
11354 
11355 
11356 // necessary to call this when using volatile to order writes/reads
11357 STB_EXTERN void          stb_barrier(void);
11358 
11359 // support for independent queues with their own threads
11360 
11361 typedef struct stb__workqueue stb_workqueue;
11362 
11363 STB_EXTERN stb_workqueue*stb_workq_new(int numthreads, int max_units);
11364 STB_EXTERN stb_workqueue*stb_workq_new_flags(int numthreads, int max_units, int no_add_mutex, int no_remove_mutex);
11365 STB_EXTERN void          stb_workq_delete(stb_workqueue *q);
11366 STB_EXTERN void          stb_workq_numthreads(stb_workqueue *q, int n);
11367 STB_EXTERN int           stb_workq(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code);
11368 STB_EXTERN int           stb_workq_reach(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel);
11369 STB_EXTERN int           stb_workq_length(stb_workqueue *q);
11370 
11371 STB_EXTERN stb_thread    stb_create_thread (stb_thread_func f, void *d);
11372 STB_EXTERN stb_thread    stb_create_thread2(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel);
11373 STB_EXTERN void          stb_destroy_thread(stb_thread t);
11374 
11375 STB_EXTERN stb_semaphore stb_sem_new(int max_val);
11376 STB_EXTERN stb_semaphore stb_sem_new_extra(int max_val, int start_val);
11377 STB_EXTERN void          stb_sem_delete (stb_semaphore s);
11378 STB_EXTERN void          stb_sem_waitfor(stb_semaphore s);
11379 STB_EXTERN void          stb_sem_release(stb_semaphore s);
11380 
11381 STB_EXTERN stb_mutex     stb_mutex_new(void);
11382 STB_EXTERN void          stb_mutex_delete(stb_mutex m);
11383 STB_EXTERN void          stb_mutex_begin(stb_mutex m);
11384 STB_EXTERN void          stb_mutex_end(stb_mutex m);
11385 
11386 STB_EXTERN stb_sync      stb_sync_new(void);
11387 STB_EXTERN void          stb_sync_delete(stb_sync s);
11388 STB_EXTERN int           stb_sync_set_target(stb_sync s, int count);
11389 STB_EXTERN void          stb_sync_reach_and_wait(stb_sync s);    // wait for 'target' reachers
11390 STB_EXTERN int           stb_sync_reach(stb_sync s);
11391 
11392 typedef struct stb__threadqueue stb_threadqueue;
11393 #define STB_THREADQ_DYNAMIC   0
11394 STB_EXTERN stb_threadqueue *stb_threadq_new(int item_size, int num_items, int many_add, int many_remove);
11395 STB_EXTERN void             stb_threadq_delete(stb_threadqueue *tq);
11396 STB_EXTERN int              stb_threadq_get(stb_threadqueue *tq, void *output);
11397 STB_EXTERN void             stb_threadq_get_block(stb_threadqueue *tq, void *output);
11398 STB_EXTERN int              stb_threadq_add(stb_threadqueue *tq, void *input);
11399 // can return FALSE if STB_THREADQ_DYNAMIC and attempt to grow fails
11400 STB_EXTERN int              stb_threadq_add_block(stb_threadqueue *tq, void *input);
11401 
11402 #ifdef STB_THREADS
11403 #ifdef STB_DEFINE
11404 
11405 typedef struct
11406 {
11407    stb_thread_func f;
11408    void *d;
11409    volatile void **return_val;
11410    stb_semaphore sem;
11411 } stb__thread;
11412 
11413 // this is initialized along all possible paths to create threads, therefore
11414 // it's always initialized before any other threads are create, therefore
11415 // it's free of races AS LONG AS you only create threads through stb_*
11416 static stb_mutex stb__threadmutex, stb__workmutex;
11417 
11418 static void stb__threadmutex_init(void)
11419 {
11420    if (stb__threadmutex == STB_SEMAPHORE_NULL) {
11421       stb__threadmutex = stb_mutex_new();
11422       stb__workmutex = stb_mutex_new();
11423    }
11424 }
11425 
11426 #ifdef STB_THREAD_TEST
11427 volatile float stb__t1=1, stb__t2;
11428 
11429 static void stb__wait(int n)
11430 {
11431    float z = 0;
11432    int i;
11433    for (i=0; i < n; ++i)
11434       z += 1 / (stb__t1+i);
11435    stb__t2 = z;
11436 }
11437 #else
11438 #define stb__wait(x)
11439 #endif
11440 
11441 #ifdef _WIN32
11442 
11443 // avoid including windows.h -- note that our definitions aren't
11444 // exactly the same (we don't define the security descriptor struct)
11445 // so if you want to include windows.h, make sure you do it first.
11446 #include <process.h>
11447 
11448 #ifndef _WINDOWS_  // check windows.h guard
11449 #define STB__IMPORT   STB_EXTERN __declspec(dllimport)
11450 #define STB__DW       unsigned long
11451 
11452 STB__IMPORT int     __stdcall TerminateThread(void *, STB__DW);
11453 STB__IMPORT void *  __stdcall CreateSemaphoreA(void *sec, long,long,char*);
11454 STB__IMPORT int     __stdcall CloseHandle(void *);
11455 STB__IMPORT STB__DW __stdcall WaitForSingleObject(void *, STB__DW);
11456 STB__IMPORT int     __stdcall ReleaseSemaphore(void *, long, long *);
11457 STB__IMPORT void    __stdcall Sleep(STB__DW);
11458 #endif
11459 
11460 // necessary to call this when using volatile to order writes/reads
11461 void stb_barrier(void)
11462 {
11463    #ifdef MemoryBarrier
11464    MemoryBarrier();
11465    #else
11466    long temp;
11467    __asm xchg temp,eax;
11468    #endif
11469 }
11470 
11471 static void stb__thread_run(void *t)
11472 {
11473    void *res;
11474    stb__thread info = * (stb__thread *) t;
11475    free(t);
11476    res = info.f(info.d);
11477    if (info.return_val)
11478       *info.return_val = res;
11479    if (info.sem != STB_SEMAPHORE_NULL)
11480       stb_sem_release(info.sem);
11481 }
11482 
11483 static stb_thread stb_create_thread_raw(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel)
11484 {
11485 #ifdef _MT
11486 #if defined(STB_FASTMALLOC) && !defined(STB_FASTMALLOC_ITS_OKAY_I_ONLY_MALLOC_IN_ONE_THREAD)
11487    stb_fatal("Error! Cannot use STB_FASTMALLOC with threads.\n");
11488    return STB_THREAD_NULL;
11489 #else
11490    unsigned long id;
11491    stb__thread *data = (stb__thread *) malloc(sizeof(*data));
11492    if (!data) return NULL;
11493    stb__threadmutex_init();
11494    data->f = f;
11495    data->d = d;
11496    data->return_val = return_code;
11497    data->sem = rel;
11498    id = _beginthread(stb__thread_run, 0, data);
11499    if (id == -1) return NULL;
11500    return (void *) id;
11501 #endif
11502 #else
11503 #ifdef STB_NO_STB_STRINGS
11504    stb_fatal("Invalid compilation");
11505 #else
11506    stb_fatal("Must compile mult-threaded to use stb_thread/stb_work.");
11507 #endif
11508    return NULL;
11509 #endif
11510 }
11511 
11512 // trivial win32 wrappers
11513 void          stb_destroy_thread(stb_thread t)   { TerminateThread(t,0); }
11514 stb_semaphore stb_sem_new(int maxv)                {return CreateSemaphoreA(NULL,0,maxv,NULL); }
11515 stb_semaphore stb_sem_new_extra(int maxv,int start){return CreateSemaphoreA(NULL,start,maxv,NULL); }
11516 void          stb_sem_delete(stb_semaphore s)    { if (s != NULL) CloseHandle(s); }
11517 void          stb_sem_waitfor(stb_semaphore s)   { WaitForSingleObject(s, 0xffffffff); } // INFINITE
11518 void          stb_sem_release(stb_semaphore s)   { ReleaseSemaphore(s,1,NULL); }
11519 static void   stb__thread_sleep(int ms)          { Sleep(ms); }
11520 
11521 #ifndef _WINDOWS_
11522 STB__IMPORT int __stdcall GetProcessAffinityMask(void *, STB__DW *, STB__DW *);
11523 STB__IMPORT void * __stdcall GetCurrentProcess(void);
11524 STB__IMPORT int __stdcall SetProcessAffinityMask(void *, STB__DW);
11525 #endif
11526 
11527 int stb_processor_count(void)
11528 {
11529    unsigned long proc,sys;
11530    GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys);
11531    return stb_bitcount(proc);
11532 }
11533 
11534 void stb_force_uniprocessor(void)
11535 {
11536    unsigned long proc,sys;
11537    GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys);
11538    if (stb_bitcount(proc) > 1) {
11539       int z;
11540       for (z=0; z < 32; ++z)
11541          if (proc & (1 << z))
11542             break;
11543       if (z < 32) {
11544          proc = 1 << z;
11545          SetProcessAffinityMask(GetCurrentProcess(), proc);
11546       }
11547    }
11548 }
11549 
11550 #ifdef _WINDOWS_
11551 #define STB_MUTEX_NATIVE
11552 void *stb_mutex_new(void)
11553 {
11554    CRITICAL_SECTION *p = (CRITICAL_SECTION *) malloc(sizeof(*p));
11555    if (p)
11556 #if _WIN32_WINNT >= 0x0500
11557       InitializeCriticalSectionAndSpinCount(p, 500);
11558 #else
11559       InitializeCriticalSection(p);
11560 #endif
11561    return p;
11562 }
11563 
11564 void stb_mutex_delete(void *p)
11565 {
11566    if (p) {
11567       DeleteCriticalSection((CRITICAL_SECTION *) p);
11568       free(p);
11569    }
11570 }
11571 
11572 void stb_mutex_begin(void *p)
11573 {
11574    stb__wait(500);
11575    if (p)
11576       EnterCriticalSection((CRITICAL_SECTION *) p);
11577 }
11578 
11579 void stb_mutex_end(void *p)
11580 {
11581    if (p)
11582       LeaveCriticalSection((CRITICAL_SECTION *) p);
11583    stb__wait(500);
11584 }
11585 #endif // _WINDOWS_
11586 
11587 #if 0
11588 // for future reference,
11589 // InterlockedCompareExchange for x86:
11590  int cas64_mp(void * dest, void * xcmp, void * xxchg) {
11591         __asm
11592         {
11593                 mov             esi, [xxchg]            ; exchange
11594                 mov             ebx, [esi + 0]
11595                 mov             ecx, [esi + 4]
11596 
11597                 mov             esi, [xcmp]                     ; comparand
11598                 mov             eax, [esi + 0]
11599                 mov             edx, [esi + 4]
11600 
11601                 mov             edi, [dest]                     ; destination
11602                 lock cmpxchg8b  [edi]
11603                 jz              yyyy;
11604 
11605                 mov             [esi + 0], eax;
11606                 mov             [esi + 4], edx;
11607 
11608 yyyy:
11609                 xor             eax, eax;
11610                 setz    al;
11611         };
11612 
11613 inline unsigned __int64 _InterlockedCompareExchange64(volatile unsigned __int64 *dest
11614                            ,unsigned __int64 exchange
11615                            ,unsigned __int64 comperand)
11616 {
11617     //value returned in eax::edx
11618     __asm {
11619         lea esi,comperand;
11620         lea edi,exchange;
11621 
11622         mov eax,[esi];
11623         mov edx,4[esi];
11624         mov ebx,[edi];
11625         mov ecx,4[edi];
11626         mov esi,dest;
11627         lock CMPXCHG8B [esi];
11628     }
11629 #endif // #if 0
11630 
11631 #endif // _WIN32
11632 
11633 stb_thread stb_create_thread2(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel)
11634 {
11635    return stb_create_thread_raw(f,d,return_code,rel);
11636 }
11637 
11638 stb_thread stb_create_thread(stb_thread_func f, void *d)
11639 {
11640    return stb_create_thread2(f,d,NULL,STB_SEMAPHORE_NULL);
11641 }
11642 
11643 // mutex implemented by wrapping semaphore
11644 #ifndef STB_MUTEX_NATIVE
11645 stb_mutex stb_mutex_new(void)            { return stb_sem_new_extra(1,1); }
11646 void      stb_mutex_delete(stb_mutex m)  { stb_sem_delete (m);      }
11647 void      stb_mutex_begin(stb_mutex m)   { stb__wait(500); if (m) stb_sem_waitfor(m); }
11648 void      stb_mutex_end(stb_mutex m)     { if (m) stb_sem_release(m); stb__wait(500); }
11649 #endif
11650 
11651 // thread merge operation
11652 struct stb__sync
11653 {
11654    int target;  // target number of threads to hit it
11655    int sofar;   // total threads that hit it
11656    int waiting; // total threads waiting
11657 
11658    stb_mutex start;   // mutex to prevent starting again before finishing previous
11659    stb_mutex mutex;   // mutex while tweaking state
11660    stb_semaphore release; // semaphore wake up waiting threads
11661       // we have to wake them up one at a time, rather than using a single release
11662       // call, because win32 semaphores don't let you dynamically change the max count!
11663 };
11664 
11665 stb_sync stb_sync_new(void)
11666 {
11667    stb_sync s = (stb_sync) malloc(sizeof(*s));
11668    if (!s) return s;
11669 
11670    s->target = s->sofar = s->waiting = 0;
11671    s->mutex   = stb_mutex_new();
11672    s->start   = stb_mutex_new();
11673    s->release = stb_sem_new(1);
11674    if (s->mutex == STB_MUTEX_NULL || s->release == STB_SEMAPHORE_NULL || s->start == STB_MUTEX_NULL) {
11675       stb_mutex_delete(s->mutex);
11676       stb_mutex_delete(s->mutex);
11677       stb_sem_delete(s->release);
11678       free(s);
11679       return NULL;
11680    }
11681    return s;
11682 }
11683 
11684 void stb_sync_delete(stb_sync s)
11685 {
11686    if (s->waiting) {
11687       // it's bad to delete while there are threads waiting!
11688       // shall we wait for them to reach, or just bail? just bail
11689       assert(0);
11690    }
11691    stb_mutex_delete(s->mutex);
11692    stb_mutex_delete(s->release);
11693    free(s);
11694 }
11695 
11696 int stb_sync_set_target(stb_sync s, int count)
11697 {
11698    // don't allow setting a target until the last one is fully released;
11699    // note that this can lead to inefficient pipelining, and maybe we'd
11700    // be better off ping-ponging between two internal syncs?
11701    // I tried seeing how often this happened using TryEnterCriticalSection
11702    // and could _never_ get it to happen in imv(stb), even with more threads
11703    // than processors. So who knows!
11704    stb_mutex_begin(s->start);
11705 
11706    // this mutex is pointless, since it's not valid for threads
11707    // to call reach() before anyone calls set_target() anyway
11708    stb_mutex_begin(s->mutex);
11709 
11710    assert(s->target == 0); // enforced by start mutex
11711    s->target  = count;
11712    s->sofar   = 0;
11713    s->waiting = 0;
11714    stb_mutex_end(s->mutex);
11715    return STB_TRUE;
11716 }
11717 
11718 void stb__sync_release(stb_sync s)
11719 {
11720    if (s->waiting)
11721       stb_sem_release(s->release);
11722    else {
11723       s->target = 0;
11724       stb_mutex_end(s->start);
11725    }
11726 }
11727 
11728 int stb_sync_reach(stb_sync s)
11729 {
11730    int n;
11731    stb_mutex_begin(s->mutex);
11732    assert(s->sofar < s->target);
11733    n = ++s->sofar; // record this value to avoid possible race if we did 'return s->sofar';
11734    if (s->sofar == s->target)
11735       stb__sync_release(s);
11736    stb_mutex_end(s->mutex);
11737    return n;
11738 }
11739 
11740 void stb_sync_reach_and_wait(stb_sync s)
11741 {
11742    stb_mutex_begin(s->mutex);
11743    assert(s->sofar < s->target);
11744    ++s->sofar;
11745    if (s->sofar == s->target) {
11746       stb__sync_release(s);
11747       stb_mutex_end(s->mutex);
11748    } else {
11749       ++s->waiting; // we're waiting, so one more waiter
11750       stb_mutex_end(s->mutex); // release the mutex to other threads
11751 
11752       stb_sem_waitfor(s->release); // wait for merge completion
11753 
11754       stb_mutex_begin(s->mutex); // on merge completion, grab the mutex
11755       --s->waiting; // we're done waiting
11756       stb__sync_release(s);    // restart the next waiter
11757       stb_mutex_end(s->mutex); // and now we're done
11758       // this ends the same as the first case, but it's a lot
11759       // clearer to understand without sharing the code
11760    }
11761 }
11762 
11763 struct stb__threadqueue
11764 {
11765    stb_mutex add, remove;
11766    stb_semaphore nonempty, nonfull;
11767    int head_blockers;  // number of threads blocking--used to know whether to release(avail)
11768    int tail_blockers;
11769    int head, tail, array_size, growable;
11770    int item_size;
11771    char *data;
11772 };
11773 
11774 static int stb__tq_wrap(volatile stb_threadqueue *z, int p)
11775 {
11776    if (p == z->array_size)
11777       return p - z->array_size;
11778    else
11779       return p;
11780 }
11781 
11782 int stb__threadq_get_raw(stb_threadqueue *tq2, void *output, int block)
11783 {
11784    volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;
11785    if (tq->head == tq->tail && !block) return 0;
11786 
11787    stb_mutex_begin(tq->remove);
11788 
11789    while (tq->head == tq->tail) {
11790       if (!block) {
11791          stb_mutex_end(tq->remove);
11792          return 0;
11793       }
11794       ++tq->head_blockers;
11795       stb_mutex_end(tq->remove);
11796 
11797       stb_sem_waitfor(tq->nonempty);
11798 
11799       stb_mutex_begin(tq->remove);
11800       --tq->head_blockers;
11801    }
11802 
11803    memcpy(output, tq->data + tq->head*tq->item_size, tq->item_size);
11804    stb_barrier();
11805    tq->head = stb__tq_wrap(tq, tq->head+1);
11806 
11807    stb_sem_release(tq->nonfull);
11808    if (tq->head_blockers) // can't check if actually non-empty due to race?
11809       stb_sem_release(tq->nonempty); // if there are other blockers, wake one
11810 
11811    stb_mutex_end(tq->remove);
11812    return STB_TRUE;
11813 }
11814 
11815 int stb__threadq_grow(volatile stb_threadqueue *tq)
11816 {
11817    int n;
11818    char *p;
11819    assert(tq->remove != STB_MUTEX_NULL); // must have this to allow growth!
11820    stb_mutex_begin(tq->remove);
11821 
11822    n = tq->array_size * 2;
11823    p = (char *) realloc(tq->data, n * tq->item_size);
11824    if (p == NULL) {
11825       stb_mutex_end(tq->remove);
11826       stb_mutex_end(tq->add);
11827       return STB_FALSE;
11828    }
11829    if (tq->tail < tq->head) {
11830       memcpy(p + tq->array_size * tq->item_size, p, tq->tail * tq->item_size);
11831       tq->tail += tq->array_size;
11832    }
11833    tq->data = p;
11834    tq->array_size = n;
11835 
11836    stb_mutex_end(tq->remove);
11837    return STB_TRUE;
11838 }
11839 
11840 int stb__threadq_add_raw(stb_threadqueue *tq2, void *input, int block)
11841 {
11842    int tail,pos;
11843    volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;
11844    stb_mutex_begin(tq->add);
11845    for(;;) {
11846       pos = tq->tail;
11847       tail = stb__tq_wrap(tq, pos+1);
11848       if (tail != tq->head) break;
11849 
11850       // full
11851       if (tq->growable) {
11852          if (!stb__threadq_grow(tq)) {
11853             stb_mutex_end(tq->add);
11854             return STB_FALSE; // out of memory
11855          }
11856       } else if (!block) {
11857          stb_mutex_end(tq->add);
11858          return STB_FALSE;
11859       } else {
11860          ++tq->tail_blockers;
11861          stb_mutex_end(tq->add);
11862 
11863          stb_sem_waitfor(tq->nonfull);
11864 
11865          stb_mutex_begin(tq->add);
11866          --tq->tail_blockers;
11867       }
11868    }
11869    memcpy(tq->data + tq->item_size * pos, input, tq->item_size);
11870    stb_barrier();
11871    tq->tail = tail;
11872    stb_sem_release(tq->nonempty);
11873    if (tq->tail_blockers) // can't check if actually non-full due to race?
11874       stb_sem_release(tq->nonfull);
11875    stb_mutex_end(tq->add);
11876    return STB_TRUE;
11877 }
11878 
11879 int stb_threadq_length(stb_threadqueue *tq2)
11880 {
11881    int a,b,n;
11882    volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;
11883    stb_mutex_begin(tq->add);
11884    a = tq->head;
11885    b = tq->tail;
11886    n = tq->array_size;
11887    stb_mutex_end(tq->add);
11888    if (a > b) b += n;
11889    return b-a;
11890 }
11891 
11892 int stb_threadq_get(stb_threadqueue *tq, void *output)
11893 {
11894    return stb__threadq_get_raw(tq, output, STB_FALSE);
11895 }
11896 
11897 void stb_threadq_get_block(stb_threadqueue *tq, void *output)
11898 {
11899    stb__threadq_get_raw(tq, output, STB_TRUE);
11900 }
11901 
11902 int stb_threadq_add(stb_threadqueue *tq, void *input)
11903 {
11904    return stb__threadq_add_raw(tq, input, STB_FALSE);
11905 }
11906 
11907 int stb_threadq_add_block(stb_threadqueue *tq, void *input)
11908 {
11909    return stb__threadq_add_raw(tq, input, STB_TRUE);
11910 }
11911 
11912 void stb_threadq_delete(stb_threadqueue *tq)
11913 {
11914    if (tq) {
11915       free(tq->data);
11916       stb_mutex_delete(tq->add);
11917       stb_mutex_delete(tq->remove);
11918       stb_sem_delete(tq->nonempty);
11919       stb_sem_delete(tq->nonfull);
11920       free(tq);
11921    }
11922 }
11923 
11924 #define STB_THREADQUEUE_DYNAMIC   0
11925 stb_threadqueue *stb_threadq_new(int item_size, int num_items, int many_add, int many_remove)
11926 {
11927    int error=0;
11928    stb_threadqueue *tq = (stb_threadqueue *) malloc(sizeof(*tq));
11929    if (tq == NULL) return NULL;
11930 
11931    if (num_items == STB_THREADQUEUE_DYNAMIC) {
11932       tq->growable = STB_TRUE;
11933       num_items = 32;
11934    } else
11935       tq->growable = STB_FALSE;
11936 
11937    tq->item_size = item_size;
11938    tq->array_size = num_items+1;
11939 
11940    tq->add = tq->remove = STB_MUTEX_NULL;
11941    tq->nonempty = tq->nonfull = STB_SEMAPHORE_NULL;
11942    tq->data = NULL;
11943    if (many_add)
11944       { tq->add    = stb_mutex_new(); if (tq->add    == STB_MUTEX_NULL) goto error; }
11945    if (many_remove || tq->growable)
11946       { tq->remove = stb_mutex_new(); if (tq->remove == STB_MUTEX_NULL) goto error; }
11947    tq->nonempty = stb_sem_new(1); if (tq->nonempty == STB_SEMAPHORE_NULL) goto error;
11948    tq->nonfull  = stb_sem_new(1); if (tq->nonfull  == STB_SEMAPHORE_NULL) goto error;
11949    tq->data = (char *) malloc(tq->item_size * tq->array_size);
11950    if (tq->data == NULL) goto error;
11951 
11952    tq->head = tq->tail = 0;
11953    tq->head_blockers = tq->tail_blockers = 0;
11954 
11955    return tq;
11956 
11957 error:
11958    stb_threadq_delete(tq);
11959    return NULL;
11960 }
11961 
11962 typedef struct
11963 {
11964    stb_thread_func f;
11965    void *d;
11966    volatile void **retval;
11967    stb_sync sync;
11968 } stb__workinfo;
11969 
11970 //static volatile stb__workinfo *stb__work;
11971 
11972 struct stb__workqueue
11973 {
11974    int numthreads;
11975    stb_threadqueue *tq;
11976 };
11977 
11978 static stb_workqueue *stb__work_global;
11979 
11980 static void *stb__thread_workloop(void *p)
11981 {
11982    volatile stb_workqueue *q = (volatile stb_workqueue *) p;
11983    for(;;) {
11984       void *z;
11985       stb__workinfo w;
11986       stb_threadq_get_block(q->tq, &w);
11987       if (w.f == NULL) // null work is a signal to end the thread
11988          return NULL;
11989       z = w.f(w.d);
11990       if (w.retval) { stb_barrier(); *w.retval = z; }
11991       if (w.sync != STB_SYNC_NULL) stb_sync_reach(w.sync);
11992    }
11993 }
11994 
11995 stb_workqueue *stb_workq_new(int num_threads, int max_units)
11996 {
11997    return stb_workq_new_flags(num_threads, max_units, 0,0);
11998 }
11999 
12000 stb_workqueue *stb_workq_new_flags(int numthreads, int max_units, int no_add_mutex, int no_remove_mutex)
12001 {
12002    stb_workqueue *q = (stb_workqueue *) malloc(sizeof(*q));
12003    if (q == NULL) return NULL;
12004    q->tq = stb_threadq_new(sizeof(stb__workinfo), max_units, !no_add_mutex, !no_remove_mutex);
12005    if (q->tq == NULL) { free(q); return NULL; }
12006    q->numthreads = 0;
12007    stb_workq_numthreads(q, numthreads);
12008    return q;
12009 }
12010 
12011 void stb_workq_delete(stb_workqueue *q)
12012 {
12013    while (stb_workq_length(q) != 0)
12014       stb__thread_sleep(1);
12015    stb_threadq_delete(q->tq);
12016    free(q);
12017 }
12018 
12019 static int stb__work_maxitems = STB_THREADQUEUE_DYNAMIC;
12020 
12021 static void stb_work_init(int num_threads)
12022 {
12023    if (stb__work_global == NULL) {
12024       stb__threadmutex_init();
12025       stb_mutex_begin(stb__workmutex);
12026       stb_barrier();
12027       if (*(stb_workqueue * volatile *) &stb__work_global == NULL)
12028          stb__work_global = stb_workq_new(num_threads, stb__work_maxitems);
12029       stb_mutex_end(stb__workmutex);
12030    }
12031 }
12032 
12033 static int stb__work_raw(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)
12034 {
12035    stb__workinfo w;
12036    if (q == NULL) {
12037       stb_work_init(1);
12038       q = stb__work_global;
12039    }
12040    w.f = f;
12041    w.d = d;
12042    w.retval = return_code;
12043    w.sync = rel;
12044    return stb_threadq_add(q->tq, &w);
12045 }
12046 
12047 int stb_workq_length(stb_workqueue *q)
12048 {
12049    return stb_threadq_length(q->tq);
12050 }
12051 
12052 int stb_workq(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code)
12053 {
12054    if (f == NULL) return 0;
12055    return stb_workq_reach(q, f, d, return_code, NULL);
12056 }
12057 
12058 int stb_workq_reach(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)
12059 {
12060    if (f == NULL) return 0;
12061    return stb__work_raw(q, f, d, return_code, rel);
12062 }
12063 
12064 static void stb__workq_numthreads(stb_workqueue *q, int n)
12065 {
12066    while (q->numthreads < n) {
12067       stb_create_thread(stb__thread_workloop, q);
12068       ++q->numthreads;
12069    }
12070    while (q->numthreads > n) {
12071       stb__work_raw(q, NULL, NULL, NULL, NULL);
12072       --q->numthreads;
12073    }
12074 }
12075 
12076 void stb_workq_numthreads(stb_workqueue *q, int n)
12077 {
12078    stb_mutex_begin(stb__threadmutex);
12079    stb__workq_numthreads(q,n);
12080    stb_mutex_end(stb__threadmutex);
12081 }
12082 
12083 int stb_work_maxunits(int n)
12084 {
12085    if (stb__work_global == NULL) {
12086       stb__work_maxitems = n;
12087       stb_work_init(1);
12088    }
12089    return stb__work_maxitems;
12090 }
12091 
12092 int stb_work(stb_thread_func f, void *d, volatile void **return_code)
12093 {
12094    return stb_workq(stb__work_global, f,d,return_code);
12095 }
12096 
12097 int stb_work_reach(stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)
12098 {
12099    return stb_workq_reach(stb__work_global, f,d,return_code,rel);
12100 }
12101 
12102 void stb_work_numthreads(int n)
12103 {
12104    if (stb__work_global == NULL)
12105       stb_work_init(n);
12106    else
12107       stb_workq_numthreads(stb__work_global, n);
12108 }
12109 #endif // STB_DEFINE
12110 
12111 
12112 //////////////////////////////////////////////////////////////////////////////
12113 //
12114 // Background disk I/O
12115 //
12116 //
12117 
12118 #define STB_BGIO_READ_ALL   (-1)
12119 STB_EXTERN int stb_bgio_read    (char *filename, int offset, int len, stb_uchar **result, int *olen);
12120 STB_EXTERN int stb_bgio_readf   (FILE *f       , int offset, int len, stb_uchar **result, int *olen);
12121 STB_EXTERN int stb_bgio_read_to (char *filename, int offset, int len, stb_uchar  *buffer, int *olen);
12122 STB_EXTERN int stb_bgio_readf_to(FILE *f       , int offset, int len, stb_uchar  *buffer, int *olen);
12123 
12124 typedef struct
12125 {
12126    int have_data;
12127    int is_valid;
12128    int is_dir;
12129    time_t filetime;
12130    stb_int64 filesize;
12131 } stb_bgstat;
12132 
12133 STB_EXTERN int stb_bgio_stat    (char *filename, stb_bgstat *result);
12134 
12135 #ifdef STB_DEFINE
12136 
12137 static stb_workqueue *stb__diskio;
12138 static stb_mutex stb__diskio_mutex;
12139 
12140 void stb_thread_cleanup(void)
12141 {
12142    if (stb__work_global) stb_workq_delete(stb__work_global); stb__work_global = NULL;
12143    if (stb__threadmutex) stb_mutex_delete(stb__threadmutex); stb__threadmutex = NULL;
12144    if (stb__workmutex)   stb_mutex_delete(stb__workmutex);   stb__workmutex   = NULL;
12145    if (stb__diskio)      stb_workq_delete(stb__diskio);      stb__diskio      = NULL;
12146    if (stb__diskio_mutex)stb_mutex_delete(stb__diskio_mutex);stb__diskio_mutex= NULL;
12147 }
12148 
12149 
12150 typedef struct
12151 {
12152    char *filename;
12153    FILE *f;
12154    int offset;
12155    int len;
12156 
12157    stb_bgstat *stat_out;
12158    stb_uchar *output;
12159    stb_uchar **result;
12160    int *len_output;
12161    int *flag;
12162 } stb__disk_command;
12163 
12164 #define STB__MAX_DISK_COMMAND 100
12165 static stb__disk_command stb__dc_queue[STB__MAX_DISK_COMMAND];
12166 static int stb__dc_offset;
12167 
12168 void stb__io_init(void)
12169 {
12170    if (!stb__diskio) {
12171       stb__threadmutex_init();
12172       stb_mutex_begin(stb__threadmutex);
12173       stb_barrier();
12174       if (*(stb_thread * volatile *) &stb__diskio == NULL) {
12175          stb__diskio_mutex = stb_mutex_new();
12176          // use many threads so OS can try to schedule seeks
12177          stb__diskio = stb_workq_new_flags(16,STB__MAX_DISK_COMMAND,STB_FALSE,STB_FALSE);
12178       }
12179       stb_mutex_end(stb__threadmutex);
12180    }
12181 }
12182 
12183 static void * stb__io_error(stb__disk_command *dc)
12184 {
12185    if (dc->len_output) *dc->len_output = 0;
12186    if (dc->result) *dc->result = NULL;
12187    if (dc->flag) *dc->flag = -1;
12188    return NULL;
12189 }
12190 
12191 static void * stb__io_task(void *p)
12192 {
12193    stb__disk_command *dc = (stb__disk_command *) p;
12194    int len;
12195    FILE *f;
12196    stb_uchar *buf;
12197 
12198    if (dc->stat_out) {
12199       struct _stati64 s;
12200       if (!_stati64(dc->filename, &s)) {
12201          dc->stat_out->filesize = s.st_size;
12202          dc->stat_out->filetime = s.st_mtime;
12203          dc->stat_out->is_dir = s.st_mode & _S_IFDIR;
12204          dc->stat_out->is_valid = (s.st_mode & _S_IFREG) || dc->stat_out->is_dir;
12205       } else
12206          dc->stat_out->is_valid = 0;
12207       stb_barrier();
12208       dc->stat_out->have_data = 1;
12209       free(dc->filename);
12210       return 0;
12211    }
12212    if (dc->f) {
12213       #ifdef WIN32
12214       f = _fdopen(_dup(_fileno(dc->f)), "rb");
12215       #else
12216       f = fdopen(dup(fileno(dc->f)), "rb");
12217       #endif
12218       if (!f)
12219          return stb__io_error(dc);
12220    } else {
12221       f = fopen(dc->filename, "rb");
12222       free(dc->filename);
12223       if (!f)
12224          return stb__io_error(dc);
12225    }
12226 
12227    len = dc->len;
12228    if (len < 0) {
12229       fseek(f, 0, SEEK_END);
12230       len = ftell(f) - dc->offset;
12231    }
12232 
12233    if (fseek(f, dc->offset, SEEK_SET)) {
12234       fclose(f);
12235       return stb__io_error(dc);
12236    }
12237 
12238    if (dc->output)
12239       buf = dc->output;
12240    else {
12241       buf = (stb_uchar *) malloc(len);
12242       if (buf == NULL) {
12243          fclose(f);
12244          return stb__io_error(dc);
12245       }
12246    }
12247 
12248    len = fread(buf, 1, len, f);
12249    fclose(f);
12250    if (dc->len_output) *dc->len_output = len;
12251    if (dc->result) *dc->result = buf;
12252    if (dc->flag) *dc->flag = 1;
12253 
12254    return NULL;
12255 }
12256 
12257 int stb__io_add(char *fname, FILE *f, int off, int len, stb_uchar *out, stb_uchar **result, int *olen, int *flag, stb_bgstat *stat)
12258 {
12259    int res;
12260    stb__io_init();
12261    // do memory allocation outside of mutex
12262    if (fname) fname = strdup(fname);
12263    stb_mutex_begin(stb__diskio_mutex);
12264    {
12265       stb__disk_command *dc = &stb__dc_queue[stb__dc_offset];
12266       dc->filename = fname;
12267       dc->f = f;
12268       dc->offset = off;
12269       dc->len = len;
12270       dc->output = out;
12271       dc->result = result;
12272       dc->len_output = olen;
12273       dc->flag = flag;
12274       dc->stat_out = stat;
12275       res = stb_workq(stb__diskio, stb__io_task, dc, NULL);
12276       if (res)
12277          stb__dc_offset = (stb__dc_offset + 1 == STB__MAX_DISK_COMMAND ? 0 : stb__dc_offset+1);
12278    }
12279    stb_mutex_end(stb__diskio_mutex);
12280    return res;
12281 }
12282 
12283 int stb_bgio_read(char *filename, int offset, int len, stb_uchar **result, int *olen)
12284 {
12285    return stb__io_add(filename,NULL,offset,len,NULL,result,olen,NULL,NULL);
12286 }
12287 
12288 int stb_bgio_readf(FILE *f, int offset, int len, stb_uchar **result, int *olen)
12289 {
12290    return stb__io_add(NULL,f,offset,len,NULL,result,olen,NULL,NULL);
12291 }
12292 
12293 int stb_bgio_read_to(char *filename, int offset, int len, stb_uchar *buffer, int *olen)
12294 {
12295    return stb__io_add(filename,NULL,offset,len,buffer,NULL,olen,NULL,NULL);
12296 }
12297 
12298 int stb_bgio_readf_to(FILE *f, int offset, int len, stb_uchar *buffer, int *olen)
12299 {
12300    return stb__io_add(NULL,f,offset,len,buffer,NULL,olen,NULL,NULL);
12301 }
12302 
12303 STB_EXTERN int stb_bgio_stat    (char *filename, stb_bgstat *result)
12304 {
12305    result->have_data = 0;
12306    return stb__io_add(filename,NULL,0,0,0,NULL,0,NULL, result);
12307 }
12308 #endif
12309 #endif
12310 
12311 
12312 
12313 //////////////////////////////////////////////////////////////////////////////
12314 //
12315 //                         Fast malloc implementation
12316 //
12317 //   This is a clone of TCMalloc, but without the thread support.
12318 //      1. large objects are allocated directly, page-aligned
12319 //      2. small objects are allocated in homogeonous heaps, 0 overhead
12320 //
12321 //   We keep an allocation table for pages a la TCMalloc. This would
12322 //   require 4MB for the entire address space, but we only allocate
12323 //   the parts that are in use. The overhead from using homogenous heaps
12324 //   everywhere is 3MB. (That is, if you allocate 1 object of each size,
12325 //   you'll use 3MB.)
12326 
12327 #if defined(STB_DEFINE) && (defined(_WIN32) || defined(STB_FASTMALLOC))
12328 
12329 #ifdef _WIN32
12330    #ifndef _WINDOWS_
12331    #ifndef STB__IMPORT
12332    #define STB__IMPORT   STB_EXTERN __declspec(dllimport)
12333    #define STB__DW       unsigned long
12334    #endif
12335    STB__IMPORT void * __stdcall VirtualAlloc(void *p, unsigned long size, unsigned long type, unsigned long protect);
12336    STB__IMPORT int   __stdcall VirtualFree(void *p, unsigned long size, unsigned long freetype);
12337    #endif
12338    #define stb__alloc_pages_raw(x)     (stb_uint32) VirtualAlloc(NULL, (x), 0x3000, 0x04)
12339    #define stb__dealloc_pages_raw(p)   VirtualFree((void *) p, 0, 0x8000)
12340 #else
12341    #error "Platform not currently supported"
12342 #endif
12343 
12344 typedef struct stb__span
12345 {
12346    int                start, len;
12347    struct stb__span  *next, *prev;
12348    void              *first_free;
12349    unsigned short     list; // 1..256 free; 257..511 sizeclass; 0=large block
12350    short              allocations; // # outstanding allocations for sizeclass
12351 } stb__span;  // 24
12352 
12353 static stb__span **stb__span_for_page;
12354 static int stb__firstpage, stb__lastpage;
12355 static void stb__update_page_range(int first, int last)
12356 {
12357    stb__span **sfp;
12358    int i, f,l;
12359    if (first >= stb__firstpage && last <= stb__lastpage) return;
12360    if (stb__span_for_page == NULL) {
12361       f = first;
12362       l = f+stb_max(last-f, 16384);
12363       l = stb_min(l, 1<<20);
12364    } else if (last > stb__lastpage) {
12365       f = stb__firstpage;
12366       l = f + (stb__lastpage - f) * 2;
12367       l = stb_clamp(last, l,1<<20);
12368    } else {
12369       l = stb__lastpage;
12370       f = l - (l - stb__firstpage) * 2;
12371       f = stb_clamp(f, 0,first);
12372    }
12373    sfp = (stb__span **) stb__alloc_pages_raw(sizeof(void *) * (l-f));
12374    for (i=f; i < stb__firstpage; ++i) sfp[i - f] = NULL;
12375    for (   ; i < stb__lastpage ; ++i) sfp[i - f] = stb__span_for_page[i - stb__firstpage];
12376    for (   ; i < l             ; ++i) sfp[i - f] = NULL;
12377    if (stb__span_for_page) stb__dealloc_pages_raw(stb__span_for_page);
12378    stb__firstpage = f;
12379    stb__lastpage  = l;
12380    stb__span_for_page = sfp;
12381 }
12382 
12383 static stb__span *stb__span_free=NULL;
12384 static stb__span *stb__span_first, *stb__span_end;
12385 static stb__span *stb__span_alloc(void)
12386 {
12387    stb__span *s = stb__span_free;
12388    if (s)
12389       stb__span_free = s->next;
12390    else {
12391       if (!stb__span_first) {
12392          stb__span_first = (stb__span *) stb__alloc_pages_raw(65536);
12393          if (stb__span_first == NULL) return NULL;
12394          stb__span_end = stb__span_first + (65536 / sizeof(stb__span));
12395       }
12396       s = stb__span_first++;
12397       if (stb__span_first == stb__span_end) stb__span_first = NULL;
12398    }
12399    return s;
12400 }
12401 
12402 static stb__span *stb__spanlist[512];
12403 
12404 static void stb__spanlist_unlink(stb__span *s)
12405 {
12406    if (s->prev)
12407       s->prev->next = s->next;
12408    else {
12409       int n = s->list;
12410       assert(stb__spanlist[n] == s);
12411       stb__spanlist[n] = s->next;
12412    }
12413    if (s->next)
12414       s->next->prev = s->prev;
12415    s->next = s->prev = NULL;
12416    s->list = 0;
12417 }
12418 
12419 static void stb__spanlist_add(int n, stb__span *s)
12420 {
12421    s->list = n;
12422    s->next = stb__spanlist[n];
12423    s->prev = NULL;
12424    stb__spanlist[n] = s;
12425    if (s->next) s->next->prev = s;
12426 }
12427 
12428 #define stb__page_shift       12
12429 #define stb__page_size        (1 << stb__page_shift)
12430 #define stb__page_number(x)   ((x) >> stb__page_shift)
12431 #define stb__page_address(x)  ((x) << stb__page_shift)
12432 
12433 static void stb__set_span_for_page(stb__span *s)
12434 {
12435    int i;
12436    for (i=0; i < s->len; ++i)
12437       stb__span_for_page[s->start + i - stb__firstpage] = s;
12438 }
12439 
12440 static stb__span *stb__coalesce(stb__span *a, stb__span *b)
12441 {
12442    assert(a->start + a->len == b->start);
12443    if (a->list) stb__spanlist_unlink(a);
12444    if (b->list) stb__spanlist_unlink(b);
12445    a->len += b->len;
12446    b->len = 0;
12447    b->next = stb__span_free;
12448    stb__span_free = b;
12449    stb__set_span_for_page(a);
12450    return a;
12451 }
12452 
12453 static void stb__free_span(stb__span *s)
12454 {
12455    stb__span *n = NULL;
12456    if (s->start > stb__firstpage) {
12457       n = stb__span_for_page[s->start-1 - stb__firstpage];
12458       if (n && n->allocations == -2 && n->start + n->len == s->start) s = stb__coalesce(n,s);
12459    }
12460    if (s->start + s->len < stb__lastpage) {
12461       n = stb__span_for_page[s->start + s->len - stb__firstpage];
12462       if (n && n->allocations == -2 && s->start + s->len == n->start) s = stb__coalesce(s,n);
12463    }
12464    s->allocations = -2;
12465    stb__spanlist_add(s->len > 256 ? 256 : s->len, s);
12466 }
12467 
12468 static stb__span *stb__alloc_pages(int num)
12469 {
12470    stb__span *s = stb__span_alloc();
12471    int p;
12472    if (!s) return NULL;
12473    p = stb__alloc_pages_raw(num << stb__page_shift);
12474    if (p == 0) { s->next = stb__span_free; stb__span_free = s; return 0; }
12475    assert(stb__page_address(stb__page_number(p)) == p);
12476    p = stb__page_number(p);
12477    stb__update_page_range(p, p+num);
12478    s->start = p;
12479    s->len   = num;
12480    s->next  = NULL;
12481    s->prev  = NULL;
12482    stb__set_span_for_page(s);
12483    return s;
12484 }
12485 
12486 static stb__span *stb__alloc_span(int pagecount)
12487 {
12488    int i;
12489    stb__span *p = NULL;
12490    for(i=pagecount; i < 256; ++i)
12491       if (stb__spanlist[i]) {
12492          p = stb__spanlist[i];
12493          break;
12494       }
12495    if (!p) {
12496       p = stb__spanlist[256];
12497       while (p && p->len < pagecount)
12498          p = p->next;
12499    }
12500    if (!p) {
12501       p = stb__alloc_pages(pagecount < 16 ? 16 : pagecount);
12502       if (p == NULL) return 0;
12503    } else
12504       stb__spanlist_unlink(p);
12505 
12506    if (p->len > pagecount) {
12507       stb__span *q = stb__span_alloc();
12508       if (q) {
12509          q->start = p->start + pagecount;
12510          q->len   = p->len   - pagecount;
12511          p->len   = pagecount;
12512          for (i=0; i < q->len; ++i)
12513             stb__span_for_page[q->start+i - stb__firstpage] = q;
12514          stb__spanlist_add(q->len > 256 ? 256 : q->len, q);
12515       }
12516    }
12517    return p;
12518 }
12519 
12520 #define STB__MAX_SMALL_SIZE     32768
12521 #define STB__MAX_SIZE_CLASSES   256
12522 
12523 static unsigned char stb__class_base[32];
12524 static unsigned char stb__class_shift[32];
12525 static unsigned char stb__pages_for_class[STB__MAX_SIZE_CLASSES];
12526 static           int stb__size_for_class[STB__MAX_SIZE_CLASSES];
12527 
12528 stb__span *stb__get_nonempty_sizeclass(int c)
12529 {
12530    int s = c + 256, i, size, tsize; // remap to span-list index
12531    char *z;
12532    void *q;
12533    stb__span *p = stb__spanlist[s];
12534    if (p) {
12535       if (p->first_free) return p; // fast path: it's in the first one in list
12536       for (p=p->next; p; p=p->next)
12537          if (p->first_free) {
12538             // move to front for future queries
12539             stb__spanlist_unlink(p);
12540             stb__spanlist_add(s, p);
12541             return p;
12542          }
12543    }
12544    // no non-empty ones, so allocate a new one
12545    p = stb__alloc_span(stb__pages_for_class[c]);
12546    if (!p) return NULL;
12547    // create the free list up front
12548    size = stb__size_for_class[c];
12549    tsize = stb__pages_for_class[c] << stb__page_shift;
12550    i = 0;
12551    z = (char *) stb__page_address(p->start);
12552    q = NULL;
12553    while (i + size <= tsize) {
12554       * (void **) z = q; q = z;
12555       z += size;
12556       i += size;
12557    }
12558    p->first_free = q;
12559    p->allocations = 0;
12560    stb__spanlist_add(s,p);
12561    return p;
12562 }
12563 
12564 static int stb__sizeclass(size_t sz)
12565 {
12566    int z = stb_log2_floor(sz); // -1 below to group e.g. 13,14,15,16 correctly
12567    return stb__class_base[z] + ((sz-1) >> stb__class_shift[z]);
12568 }
12569 
12570 static void stb__init_sizeclass(void)
12571 {
12572    int i, size, overhead;
12573    int align_shift = 2;  // allow 4-byte and 12-byte blocks as well, vs. TCMalloc
12574    int next_class = 1;
12575    int last_log = 0;
12576 
12577    for (i = 0; i < align_shift; i++) {
12578       stb__class_base [i] = next_class;
12579       stb__class_shift[i] = align_shift;
12580    }
12581 
12582    for (size = 1 << align_shift; size <= STB__MAX_SMALL_SIZE; size += 1 << align_shift) {
12583       i = stb_log2_floor(size);
12584       if (i > last_log) {
12585          if (size == 16) ++align_shift; // switch from 4-byte to 8-byte alignment
12586          else if (size >= 128 && align_shift < 8) ++align_shift;
12587          stb__class_base[i]  = next_class - ((size-1) >> align_shift);
12588          stb__class_shift[i] = align_shift;
12589          last_log = i;
12590       }
12591       stb__size_for_class[next_class++] = size;
12592    }
12593 
12594    for (i=1; i <= STB__MAX_SMALL_SIZE; ++i)
12595       assert(i <= stb__size_for_class[stb__sizeclass(i)]);
12596 
12597    overhead = 0;
12598    for (i = 1; i < next_class; i++) {
12599       int s = stb__size_for_class[i];
12600       size = stb__page_size;
12601       while (size % s > size >> 3)
12602          size += stb__page_size;
12603       stb__pages_for_class[i] = (unsigned char) (size >> stb__page_shift);
12604       overhead += size;
12605    }
12606    assert(overhead < (4 << 20)); // make sure it's under 4MB of overhead
12607 }
12608 
12609 #ifdef STB_DEBUG
12610 #define stb__smemset(a,b,c)  memset((void *) a, b, c)
12611 #elif defined(STB_FASTMALLOC_INIT)
12612 #define stb__smemset(a,b,c)  memset((void *) a, b, c)
12613 #else
12614 #define stb__smemset(a,b,c)
12615 #endif
12616 void *stb_smalloc(size_t sz)
12617 {
12618    stb__span *s;
12619    if (sz == 0) return NULL;
12620    if (stb__size_for_class[1] == 0) stb__init_sizeclass();
12621    if (sz > STB__MAX_SMALL_SIZE) {
12622       s = stb__alloc_span((sz + stb__page_size - 1) >> stb__page_shift);
12623       if (s == NULL) return NULL;
12624       s->list = 0;
12625       s->next = s->prev = NULL;
12626       s->allocations = -32767;
12627       stb__smemset(stb__page_address(s->start), 0xcd, (sz+3)&~3);
12628       return (void *) stb__page_address(s->start);
12629    } else {
12630       void *p;
12631       int c = stb__sizeclass(sz);
12632       s = stb__spanlist[256+c];
12633       if (!s || !s->first_free)
12634          s = stb__get_nonempty_sizeclass(c);
12635       if (s == NULL) return NULL;
12636       p = s->first_free;
12637       s->first_free = * (void **) p;
12638       ++s->allocations;
12639       stb__smemset(p,0xcd, sz);
12640       return p;
12641    }
12642 }
12643 
12644 int stb_ssize(void *p)
12645 {
12646    stb__span *s;
12647    if (p == NULL) return 0;
12648    s = stb__span_for_page[stb__page_number((stb_uint) p) - stb__firstpage];
12649    if (s->list >= 256) {
12650       return stb__size_for_class[s->list - 256];
12651    } else {
12652       assert(s->list == 0);
12653       return s->len << stb__page_shift;
12654    }
12655 }
12656 
12657 void stb_sfree(void *p)
12658 {
12659    stb__span *s;
12660    if (p == NULL) return;
12661    s = stb__span_for_page[stb__page_number((stb_uint) p) - stb__firstpage];
12662    if (s->list >= 256) {
12663       stb__smemset(p, 0xfe, stb__size_for_class[s->list-256]);
12664       * (void **) p = s->first_free;
12665       s->first_free = p;
12666       if (--s->allocations == 0) {
12667          stb__spanlist_unlink(s);
12668          stb__free_span(s);
12669       }
12670    } else {
12671       assert(s->list == 0);
12672       stb__smemset(p, 0xfe, stb_ssize(p));
12673       stb__free_span(s);
12674    }
12675 }
12676 
12677 void *stb_srealloc(void *p, size_t sz)
12678 {
12679    size_t cur_size;
12680    if (p == NULL) return stb_smalloc(sz);
12681    if (sz == 0) { stb_sfree(p); return NULL; }
12682    cur_size = stb_ssize(p);
12683    if (sz > cur_size || sz <= (cur_size >> 1)) {
12684       void *q;
12685       if (sz > cur_size && sz < (cur_size << 1)) sz = cur_size << 1;
12686       q = stb_smalloc(sz); if (q == NULL) return NULL;
12687       memcpy(q, p, sz < cur_size ? sz : cur_size);
12688       stb_sfree(p);
12689       return q;
12690    }
12691    return p;
12692 }
12693 
12694 void *stb_scalloc(size_t n, size_t sz)
12695 {
12696    void *p;
12697    if (n == 0 || sz == 0) return NULL;
12698    if (stb_log2_ceil(n) + stb_log2_ceil(n) >= 32) return NULL;
12699    p = stb_smalloc(n*sz);
12700    if (p) memset(p, 0, n*sz);
12701    return p;
12702 }
12703 
12704 char *stb_sstrdup(char *s)
12705 {
12706    int n = strlen(s);
12707    char *p = (char *) stb_smalloc(n+1);
12708    if (p) strcpy(p,s);
12709    return p;
12710 }
12711 #endif // STB_DEFINE
12712 
12713 
12714 
12715 //////////////////////////////////////////////////////////////////////////////
12716 //
12717 //                         Source code constants
12718 //
12719 // This is a trivial system to let you specify constants in source code,
12720 // then while running you can change the constants.
12721 //
12722 // Note that you can't wrap the #defines, because we need to know their
12723 // names. So we provide a pre-wrapped version without 'STB_' for convenience;
12724 // to request it, #define STB_CONVENIENT_H, yielding:
12725 //       KI -- integer
12726 //       KU -- unsigned integer
12727 //       KF -- float
12728 //       KD -- double
12729 //       KS -- string constant
12730 //
12731 // Defaults to functioning in debug build, not in release builds.
12732 // To force on, define STB_ALWAYS_H
12733 
12734 #ifdef STB_CONVENIENT_H
12735 #define KI(x) STB_I(x)
12736 #define KU(x) STB_UI(x)
12737 #define KF(x) STB_F(x)
12738 #define KD(x) STB_D(x)
12739 #define KS(x) STB_S(x)
12740 #endif
12741 
12742 STB_EXTERN void stb_source_path(char *str);
12743 #ifdef STB_DEFINE
12744 char *stb__source_path;
12745 void stb_source_path(char *path)
12746 {
12747    stb__source_path = path;
12748 }
12749 
12750 char *stb__get_sourcefile_path(char *file)
12751 {
12752    static char filebuf[512];
12753    if (stb__source_path) {
12754       sprintf(filebuf, "%s/%s", stb__source_path, file);
12755       if (stb_fexists(filebuf)) return filebuf;
12756    }
12757 
12758    if (stb_fexists(file)) return file;
12759 
12760    sprintf(filebuf, "../%s", file);
12761    if (!stb_fexists(filebuf)) return filebuf;
12762 
12763    return file;
12764 }
12765 #endif
12766 
12767 #define STB_F(x)   ((float) STB_H(x))
12768 #define STB_UI(x)  ((unsigned int) STB_I(x))
12769 
12770 #if !defined(STB_DEBUG) && !defined(STB_ALWAYS_H)
12771 #define STB_D(x)   ((double) (x))
12772 #define STB_I(x)   ((int) (x))
12773 #define STB_S(x)   ((char *) (x))
12774 #else
12775 #define STB_D(x)   stb__double_constant(__FILE__, __LINE__-1, (x))
12776 #define STB_I(x)   stb__int_constant(__FILE__, __LINE__-1, (x))
12777 #define STB_S(x)   stb__string_constant(__FILE__, __LINE__-1, (x))
12778 
12779 STB_EXTERN double stb__double_constant(char *file, int line, double x);
12780 STB_EXTERN int    stb__int_constant(char *file, int line, int x);
12781 STB_EXTERN char * stb__string_constant(char *file, int line, char *str);
12782 
12783 #ifdef STB_DEFINE
12784 
12785 enum
12786 {
12787    STB__CTYPE_int,
12788    STB__CTYPE_uint,
12789    STB__CTYPE_float,
12790    STB__CTYPE_double,
12791    STB__CTYPE_string,
12792 };
12793 
12794 typedef struct
12795 {
12796    int line;
12797    int type;
12798    union {
12799       int ival;
12800       double dval;
12801       char *sval;
12802    };
12803 } stb__Entry;
12804 
12805 typedef struct
12806 {
12807    stb__Entry *entries;
12808    char *filename;
12809    time_t timestamp;
12810    char **file_data;
12811    int file_len;
12812    unsigned short *line_index;
12813 } stb__FileEntry;
12814 
12815 static void stb__constant_parse(stb__FileEntry *f, int i)
12816 {
12817    char *s;
12818    int n;
12819    if (!stb_arr_valid(f->entries, i)) return;
12820    n = f->entries[i].line;
12821    if (n >= f->file_len) return;
12822    s = f->file_data[n];
12823    switch (f->entries[i].type) {
12824       case STB__CTYPE_float:
12825          while (*s) {
12826             if (!strncmp(s, "STB_D(", 6)) { s+=6; goto matched_float; }
12827             if (!strncmp(s, "STB_F(", 6)) { s+=6; goto matched_float; }
12828             if (!strncmp(s, "KD(", 3)) { s+=3; goto matched_float; }
12829             if (!strncmp(s, "KF(", 3)) { s+=3; goto matched_float; }
12830             ++s;
12831          }
12832          break;
12833       matched_float:
12834          f->entries[i].dval = strtod(s, NULL);
12835          break;
12836       case STB__CTYPE_int:
12837          while (*s) {
12838             if (!strncmp(s, "STB_I(", 6)) { s+=6; goto matched_int; }
12839             if (!strncmp(s, "STB_UI(", 7)) { s+=7; goto matched_int; }
12840             if (!strncmp(s, "KI(", 3)) { s+=3; goto matched_int; }
12841             if (!strncmp(s, "KU(", 3)) { s+=3; goto matched_int; }
12842             ++s;
12843          }
12844          break;
12845       matched_int: {
12846          int neg=0;
12847          s = stb_skipwhite(s);
12848          while (*s == '-') { neg = !neg; s = stb_skipwhite(s+1); } // handle '- - 5', pointlessly
12849          if (s[0] == '0' && tolower(s[1]) == 'x')
12850             f->entries[i].ival = strtol(s, NULL, 16);
12851          else if (s[0] == '0')
12852             f->entries[i].ival = strtol(s, NULL, 8);
12853          else
12854             f->entries[i].ival = strtol(s, NULL, 10);
12855          if (neg) f->entries[i].ival = -f->entries[i].ival;
12856          break;
12857       }
12858       case STB__CTYPE_string:
12859          // @TODO
12860          break;
12861    }
12862 }
12863 
12864 static stb_sdict *stb__constant_file_hash;
12865 
12866 stb__Entry *stb__constant_get_entry(char *filename, int line, int type)
12867 {
12868    int i;
12869    stb__FileEntry *f;
12870    if (stb__constant_file_hash == NULL)
12871       stb__constant_file_hash = stb_sdict_new(STB_TRUE);
12872    f = (stb__FileEntry*) stb_sdict_get(stb__constant_file_hash, filename);
12873    if (f == NULL) {
12874       char *s = stb__get_sourcefile_path(filename);
12875       if (s == NULL || !stb_fexists(s)) return 0;
12876       f = (stb__FileEntry *) malloc(sizeof(*f));
12877       f->timestamp = stb_ftimestamp(s);
12878       f->file_data = stb_stringfile(s, &f->file_len);
12879       f->filename = strdup(s); // cache the full path
12880       f->entries = NULL;
12881       f->line_index = 0;
12882       stb_arr_setlen(f->line_index, f->file_len);
12883       memset(f->line_index, 0xff, stb_arr_storage(f->line_index));
12884    } else {
12885       time_t t = stb_ftimestamp(f->filename);
12886       if (f->timestamp != t) {
12887          f->timestamp = t;
12888          free(f->file_data);
12889          f->file_data = stb_stringfile(f->filename, &f->file_len);
12890          stb_arr_setlen(f->line_index, f->file_len);
12891          for (i=0; i < stb_arr_len(f->entries); ++i)
12892             stb__constant_parse(f, i);
12893       }
12894    }
12895 
12896    if (line >= f->file_len) return 0;
12897 
12898    if (f->line_index[line] >= stb_arr_len(f->entries)) {
12899       // need a new entry
12900       int n = stb_arr_len(f->entries);
12901       stb__Entry e;
12902       e.line = line;
12903       if (line < f->file_len)
12904          f->line_index[line] = n;
12905       e.type = type;
12906       stb_arr_push(f->entries, e);
12907       stb__constant_parse(f, n);
12908    }
12909    return f->entries + f->line_index[line];
12910 }
12911 
12912 double stb__double_constant(char *file, int line, double x)
12913 {
12914    stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_float);
12915    if (!e) return x;
12916    return e->dval;
12917 }
12918 
12919 int    stb__int_constant(char *file, int line, int x)
12920 {
12921    stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_int);
12922    if (!e) return x;
12923    return e->ival;
12924 }
12925 
12926 char * stb__string_constant(char *file, int line, char *x)
12927 {
12928    stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_string);
12929    if (!e) return x;
12930    return e->sval;
12931 }
12932 
12933 #endif // STB_DEFINE
12934 #endif // !STB_DEBUG && !STB_ALWAYS_H
12935 
12936 
12937 #ifdef STB_STUA
12938 //////////////////////////////////////////////////////////////////////////
12939 //
12940 //  stua: little scripting language
12941 //
12942 //     define STB_STUA to compile it
12943 //
12944 //     see http://nothings.org/stb/stb_stua.html for documentation
12945 //
12946 //  basic parsing model:
12947 //
12948 //   lexical analysis
12949 //      use stb_lex() to parse tokens; keywords get their own tokens
12950 //
12951 //   parsing:
12952 //      recursive descent parser. too much of a hassle to make an unambiguous
12953 //      LR(1) grammar, and one-pass generation is clumsier (recursive descent
12954 //      makes it easier to e.g. compile nested functions). on the other hand,
12955 //      dictionary syntax required hackery to get extra lookahead.
12956 //
12957 //   codegen:
12958 //      output into an evaluation tree, using array indices as 'pointers'
12959 //
12960 //   run:
12961 //      traverse the tree; support for 'break/continue/return' is tricky
12962 //
12963 //   garbage collection:
12964 //      stu__mark and sweep; explicit stack with non-stu__compile_global_scope roots
12965 
12966 typedef stb_int32 stua_obj;
12967 
12968 typedef stb_idict stua_dict;
12969 
12970 STB_EXTERN void stua_run_script(char *s);
12971 STB_EXTERN void stua_uninit(void);
12972 
12973 extern stua_obj stua_globals;
12974 
12975 STB_EXTERN double   stua_number(stua_obj z);
12976 
12977 STB_EXTERN stua_obj stua_getnil(void);
12978 STB_EXTERN stua_obj stua_getfalse(void);
12979 STB_EXTERN stua_obj stua_gettrue(void);
12980 STB_EXTERN stua_obj stua_string(char *z);
12981 STB_EXTERN stua_obj stua_make_number(double d);
12982 STB_EXTERN stua_obj stua_box(int type, void *data, int size);
12983 
12984 enum
12985 {
12986    STUA_op_negate=129,
12987    STUA_op_shl,   STUA_op_ge,
12988    STUA_op_shr,   STUA_op_le,
12989    STUA_op_shru,
12990    STUA_op_last
12991 };
12992 
12993 #define STUA_NO_VALUE   2     // equivalent to a tagged NULL
12994 STB_EXTERN stua_obj (*stua_overload)(int op, stua_obj a, stua_obj b, stua_obj c);
12995 
12996 STB_EXTERN stua_obj stua_error(char *err, ...);
12997 
12998 STB_EXTERN stua_obj stua_pushroot(stua_obj o);
12999 STB_EXTERN void     stua_poproot (   void   );
13000 
13001 
13002 #ifdef STB_DEFINE
13003 // INTERPRETER
13004 
13005 // 31-bit floating point implementation
13006 //   force the (1 << 30) bit (2nd highest bit) to be zero by re-biasing the exponent;
13007 //   then shift and set the bottom bit
13008 
13009 static stua_obj stu__floatp(float *f)
13010 {
13011    unsigned int n = *(unsigned int *) f;
13012    unsigned int e = n & (0xff << 23);
13013 
13014    assert(sizeof(int) == 4 && sizeof(float) == 4);
13015 
13016    if (!e)                    // zero?
13017       n = n;                  //   no change
13018    else if (e < (64 << 23))   // underflow of the packed encoding?
13019       n = (n & 0x80000000);   //   signed 0
13020    else if (e > (190 << 23))  // overflow of the encoding? (or INF or NAN)
13021       n = (n & 0x80000000) + (127 << 23); // new INF encoding
13022    else
13023       n -= 0x20000000;
13024 
13025    // now we need to shuffle the bits so that the spare bit is at the bottom
13026    assert((n & 0x40000000) == 0);
13027    return (n & 0x80000000) + (n << 1) + 1;
13028 }
13029 
13030 static unsigned char stu__getfloat_addend[256];
13031 static float stu__getfloat(stua_obj v)
13032 {
13033    unsigned int n;
13034    unsigned int e = ((unsigned int) v) >> 24;
13035 
13036    n = (int) v >> 1;  // preserve high bit
13037    n += stu__getfloat_addend[e] << 24;
13038    return *(float *) &n;
13039 }
13040 
13041 stua_obj stua_float(float f)
13042 {
13043    return stu__floatp(&f);
13044 }
13045 
13046 static void stu__float_init(void)
13047 {
13048    int i;
13049    stu__getfloat_addend[0]    = 0;   // do nothing to biased exponent of 0
13050    for (i=1; i < 127; ++i)
13051       stu__getfloat_addend[i] = 32;  // undo the -0x20000000
13052    stu__getfloat_addend[127]  = 64;  // convert packed INF to INF (0x3f -> 0x7f)
13053 
13054    for (i=0; i < 128; ++i) // for signed floats, remove the bit we just shifted down
13055       stu__getfloat_addend[128+i] = stu__getfloat_addend[i] - 64;
13056 }
13057 
13058 // Tagged data type implementation
13059 
13060                                                  // TAGS:
13061 #define stu__int_tag          0  // of 2 bits    //   00   int
13062 #define stu__float_tag        1  // of 1 bit     //   01   float
13063 #define stu__ptr_tag          2  // of 2 bits    //   10   boxed
13064                                                  //   11   float
13065 
13066 #define stu__tag(x)           ((x) & 3)
13067 #define stu__number(x)        (stu__tag(x) != stu__ptr_tag)
13068 #define stu__isint(x)         (stu__tag(x) == stu__int_tag)
13069 
13070 #define stu__int(x)           ((x) >> 2)
13071 #define stu__float(x)         (stu__getfloat(x))
13072 
13073 #define stu__makeint(v)       ((v)*4+stu__int_tag)
13074 
13075 // boxed data, and tag support for boxed data
13076 
13077 enum
13078 {
13079    STU___float    = 1,   STU___int      = 2,
13080    STU___number   = 3,   STU___string   = 4,
13081    STU___function = 5,   STU___dict     = 6,
13082    STU___boolean  = 7,   STU___error    = 8,
13083 };
13084 
13085 // boxed data
13086 #define STU__BOX  short type, stua_gc
13087 typedef struct stu__box { STU__BOX; } stu__box;
13088 
13089 stu__box stu__nil   = { 0, 1 };
13090 stu__box stu__true  = { STU___boolean, 1, };
13091 stu__box stu__false = { STU___boolean, 1, };
13092 
13093 #define stu__makeptr(v)  ((stua_obj)     (v) + stu__ptr_tag)
13094 
13095 #define stua_nil    stu__makeptr(&stu__nil)
13096 #define stua_true   stu__makeptr(&stu__true)
13097 #define stua_false  stu__makeptr(&stu__false)
13098 
13099 stua_obj stua_getnil(void)   { return stua_nil; }
13100 stua_obj stua_getfalse(void) { return stua_false; }
13101 stua_obj stua_gettrue(void)  { return stua_true; }
13102 
13103 #define stu__ptr(x)      ((stu__box *) ((x) - stu__ptr_tag))
13104 
13105 #define stu__checkt(t,x) ((t) == STU___float  ? ((x) & 1) == stu__float_tag : \
13106                           (t) == STU___int    ? stu__isint(x)               : \
13107                           (t) == STU___number ? stu__number(x)              : \
13108                           stu__tag(x) == stu__ptr_tag && stu__ptr(x)->type == (t))
13109 
13110 typedef struct
13111 {
13112    STU__BOX;
13113    void *ptr;
13114 } stu__wrapper;
13115 
13116 // implementation of a 'function' or function + closure
13117 
13118 typedef struct stu__func
13119 {
13120    STU__BOX;
13121    stua_obj closure_source;  // 0 - regular function; 4 - C function
13122                              // if closure, pointer to source function
13123    union {
13124       stua_obj closure_data; // partial-application data
13125       void *store;           // pointer to free that holds 'code'
13126       stua_obj (*func)(stua_dict *context);
13127    } f;
13128    // closure ends here
13129    short *code;
13130    int num_param;
13131    stua_obj *param;  // list of parameter strings
13132 } stu__func;
13133 
13134 // apply this to 'short *code' to get at data
13135 #define stu__const(f)  ((stua_obj *) (f))
13136 
13137 static void stu__free_func(stu__func *f)
13138 {
13139    if (f->closure_source == 0)          free(f->f.store);
13140    if ((stb_uint) f->closure_source <= 4)   free(f->param);
13141    free(f);
13142 }
13143 
13144 #define stu__pd(x)       ((stua_dict *)    stu__ptr(x))
13145 #define stu__pw(x)       ((stu__wrapper *) stu__ptr(x))
13146 #define stu__pf(x)       ((stu__func *)    stu__ptr(x))
13147 
13148 
13149 // garbage-collection
13150 
13151 
13152 static stu__box ** stu__gc_ptrlist;
13153 static stua_obj * stu__gc_root_stack;
13154 
13155 stua_obj stua_pushroot(stua_obj o) { stb_arr_push(stu__gc_root_stack, o); return o; }
13156 void     stua_poproot (   void   ) { stb_arr_pop(stu__gc_root_stack); }
13157 
13158 static stb_sdict *stu__strings;
13159 static void stu__mark(stua_obj z)
13160 {
13161    int i;
13162    stu__box *p = stu__ptr(z);
13163    if (p->stua_gc == 1) return; // already marked
13164    assert(p->stua_gc == 0);
13165    p->stua_gc = 1;
13166    switch(p->type) {
13167       case STU___function: {
13168          stu__func *f = (stu__func *) p;
13169          if ((stb_uint) f->closure_source <= 4) {
13170             if (f->closure_source == 0) {
13171                for (i=1; i <= f->code[0]; ++i)
13172                   if (!stu__number(((stua_obj *) f->code)[-i]))
13173                      stu__mark(((stua_obj *) f->code)[-i]);
13174             }
13175             for (i=0; i < f->num_param; ++i)
13176                stu__mark(f->param[i]);
13177          } else {
13178             stu__mark(f->closure_source);
13179             stu__mark(f->f.closure_data);
13180          }
13181          break;
13182       }
13183       case STU___dict: {
13184          stua_dict *e = (stua_dict *) p;
13185          for (i=0; i < e->limit; ++i)
13186             if (e->table[i].k != STB_IEMPTY && e->table[i].k != STB_IDEL) {
13187                if (!stu__number(e->table[i].k)) stu__mark((int) e->table[i].k);
13188                if (!stu__number(e->table[i].v)) stu__mark((int) e->table[i].v);
13189             }
13190          break;
13191       }
13192    }
13193 }
13194 
13195 static int stu__num_allocs, stu__size_allocs;
13196 static stua_obj stu__flow_val = stua_nil; // used for break & return
13197 
13198 static void stua_gc(int force)
13199 {
13200    int i;
13201    if (!force && stu__num_allocs == 0 && stu__size_allocs == 0) return;
13202    stu__num_allocs = stu__size_allocs = 0;
13203    //printf("[gc]\n");
13204 
13205    // clear marks
13206    for (i=0; i < stb_arr_len(stu__gc_ptrlist); ++i)
13207        stu__gc_ptrlist[i]->stua_gc = 0;
13208 
13209    // stu__mark everything reachable
13210    stu__nil.stua_gc = stu__true.stua_gc = stu__false.stua_gc = 1;
13211    stu__mark(stua_globals);
13212    if (!stu__number(stu__flow_val))
13213       stu__mark(stu__flow_val);
13214    for (i=0; i < stb_arr_len(stu__gc_root_stack); ++i)
13215       if (!stu__number(stu__gc_root_stack[i]))
13216          stu__mark(stu__gc_root_stack[i]);
13217 
13218    // sweep unreachables
13219    for (i=0; i < stb_arr_len(stu__gc_ptrlist);) {
13220       stu__box *z = stu__gc_ptrlist[i];
13221       if (!z->stua_gc) {
13222          switch (z->type) {
13223             case STU___dict:        stb_idict_destroy((stua_dict *) z); break;
13224             case STU___error:       free(((stu__wrapper *) z)->ptr); break;
13225             case STU___string:      stb_sdict_remove(stu__strings, (char*) ((stu__wrapper *) z)->ptr, NULL); free(z); break;
13226             case STU___function:    stu__free_func((stu__func *) z); break;
13227          }
13228          // swap in the last item over this, and repeat
13229          z = stb_arr_pop(stu__gc_ptrlist);
13230          stu__gc_ptrlist[i] = z;
13231       } else
13232          ++i;
13233    }
13234 }
13235 
13236 static void stu__consider_gc(stua_obj x)
13237 {
13238    if (stu__size_allocs < 100000) return;
13239    if (stu__num_allocs < 10 && stu__size_allocs < 1000000) return;
13240    stb_arr_push(stu__gc_root_stack, x);
13241    stua_gc(0);
13242    stb_arr_pop(stu__gc_root_stack);
13243 }
13244 
13245 static stua_obj stu__makeobj(int type, void *data, int size, int safe_to_gc)
13246 {
13247    stua_obj x = stu__makeptr(data);
13248    ((stu__box *) data)->type = type;
13249    stb_arr_push(stu__gc_ptrlist, (stu__box *) data);
13250    stu__num_allocs  += 1;
13251    stu__size_allocs += size;
13252    if (safe_to_gc) stu__consider_gc(x);
13253    return x;
13254 }
13255 
13256 stua_obj stua_box(int type, void *data, int size)
13257 {
13258    stu__wrapper *p = (stu__wrapper *) malloc(sizeof(*p));
13259    p->ptr = data;
13260    return stu__makeobj(type, p, size, 0);
13261 }
13262 
13263 // a stu string can be directly compared for equality, because
13264 // they go into a hash table
13265 stua_obj stua_string(char *z)
13266 {
13267    stu__wrapper *b = (stu__wrapper *) stb_sdict_get(stu__strings, z);
13268    if (b == NULL) {
13269       int o = stua_box(STU___string, NULL, strlen(z) + sizeof(*b));
13270       b = stu__pw(o);
13271       stb_sdict_add(stu__strings, z, b);
13272       stb_sdict_getkey(stu__strings, z, (char **) &b->ptr);
13273    }
13274    return stu__makeptr(b);
13275 }
13276 
13277 // stb_obj dictionary is just an stb_idict
13278 static void     stu__set(stua_dict *d, stua_obj k, stua_obj v)
13279 { if (stb_idict_set(d, k, v)) stu__size_allocs += 8; }
13280 
13281 static stua_obj stu__get(stua_dict *d, stua_obj k, stua_obj res)
13282 {
13283    stb_idict_get_flag(d, k, &res);
13284    return res;
13285 }
13286 
13287 static stua_obj make_string(char *z, int len)
13288 {
13289    stua_obj s;
13290    char temp[256], *q = (char *) stb_temp(temp, len+1), *p = q;
13291    while (len > 0) {
13292       if (*z == '\\') {
13293               if (z[1] == 'n') *p = '\n';
13294          else if (z[1] == 'r') *p = '\r';
13295          else if (z[1] == 't') *p = '\t';
13296          else                  *p = z[1];
13297          p += 1; z += 2; len -= 2;
13298       } else {
13299          *p++ = *z++; len -= 1;
13300       }
13301    }
13302    *p = 0;
13303    s = stua_string(q);
13304    stb_tempfree(temp, q);
13305    return s;
13306 }
13307 
13308 enum token_names
13309 {
13310    T__none=128,
13311    ST_shl = STUA_op_shl,    ST_ge  = STUA_op_ge,
13312    ST_shr = STUA_op_shr,    ST_le = STUA_op_le,
13313    ST_shru = STUA_op_shru,  STU__negate = STUA_op_negate,
13314    ST__reset_numbering = STUA_op_last,
13315    ST_white,
13316    ST_id, ST_float, ST_decimal, ST_hex, ST_char,ST_string, ST_number,
13317    // make sure the keywords come _AFTER_ ST_id, so stb_lex prefer them
13318    ST_if,      ST_while,    ST_for,     ST_eq,  ST_nil,
13319    ST_then,    ST_do,       ST_in,      ST_ne,  ST_true,
13320    ST_else,    ST_break,    ST_let,     ST_and, ST_false,
13321    ST_elseif,  ST_continue, ST_into,    ST_or,  ST_repeat,
13322    ST_end,     ST_as,       ST_return,  ST_var, ST_func,
13323    ST_catch,   ST__frame,
13324    ST__max_terminals,
13325 
13326    STU__defaultparm, STU__seq,
13327 };
13328 
13329 static stua_dict  * stu__globaldict;
13330        stua_obj     stua_globals;
13331 
13332 static enum
13333 {
13334    FLOW_normal,  FLOW_continue,   FLOW_break,  FLOW_return,  FLOW_error,
13335 } stu__flow;
13336 
13337 stua_obj stua_error(char *z, ...)
13338 {
13339    stua_obj a;
13340    char temp[4096], *x;
13341    va_list v; va_start(v,z); vsprintf(temp, z, v); va_end(v);
13342    x = strdup(temp);
13343    a = stua_box(STU___error, x, strlen(x));
13344    stu__flow = FLOW_error;
13345    stu__flow_val = a;
13346    return stua_nil;
13347 }
13348 
13349 double stua_number(stua_obj z)
13350 {
13351    return stu__tag(z) == stu__int_tag ? stu__int(z) : stu__float(z);
13352 }
13353 
13354 stua_obj stua_make_number(double d)
13355 {
13356    double e = floor(d);
13357    if (e == d && e < (1 << 29) && e >= -(1 << 29))
13358       return stu__makeint((int) e);
13359    else
13360       return stua_float((float) d);
13361 }
13362 
13363 stua_obj (*stua_overload)(int op, stua_obj a, stua_obj b, stua_obj c) = NULL;
13364 
13365 static stua_obj stu__op(int op, stua_obj a, stua_obj b, stua_obj c)
13366 {
13367    stua_obj r = STUA_NO_VALUE;
13368    if (op == '+') {
13369       if (stu__checkt(STU___string, a) && stu__checkt(STU___string, b)) {
13370          ;// @TODO: string concatenation
13371       } else if (stu__checkt(STU___function, a) && stu__checkt(STU___dict, b)) {
13372          stu__func *f = (stu__func *) malloc(12);
13373          assert(offsetof(stu__func, code)==12);
13374          f->closure_source = a;
13375          f->f.closure_data = b;
13376          return stu__makeobj(STU___function, f, 16, 1);
13377       }
13378    }
13379    if (stua_overload) r = stua_overload(op,a,b,c);
13380    if (stu__flow != FLOW_error && r == STUA_NO_VALUE)
13381       stua_error("Typecheck for operator %d", op), r=stua_nil;
13382    return r;
13383 }
13384 
13385 #define STU__EVAL2(a,b)             \
13386           a = stu__eval(stu__f[n+1]);  if (stu__flow) break; stua_pushroot(a); \
13387           b = stu__eval(stu__f[n+2]);  stua_poproot(); if (stu__flow) break;
13388 
13389 #define STU__FB(op)              \
13390           STU__EVAL2(a,b)           \
13391           if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag) \
13392              return ((a) op (b));                 \
13393           if (stu__number(a) && stu__number(b)) \
13394              return stua_make_number(stua_number(a) op stua_number(b)); \
13395           return stu__op(stu__f[n], a,b, stua_nil)
13396 
13397 #define STU__F(op)              \
13398           STU__EVAL2(a,b)           \
13399           if (stu__number(a) && stu__number(b)) \
13400              return stua_make_number(stua_number(a) op stua_number(b)); \
13401           return stu__op(stu__f[n], a,b, stua_nil)
13402 
13403 #define STU__I(op)               \
13404           STU__EVAL2(a,b)           \
13405           if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag) \
13406              return stu__makeint(stu__int(a) op stu__int(b));                 \
13407           return stu__op(stu__f[n], a,b, stua_nil)
13408 
13409 #define STU__C(op)               \
13410           STU__EVAL2(a,b)           \
13411           if (stu__number(a) && stu__number(b)) \
13412              return (stua_number(a) op stua_number(b)) ? stua_true : stua_false; \
13413           return stu__op(stu__f[n], a,b, stua_nil)
13414 
13415 #define STU__CE(op)              \
13416           STU__EVAL2(a,b)           \
13417           return (a op b) ? stua_true : stua_false
13418 
13419 static short *stu__f;
13420 static stua_obj  stu__f_obj;
13421 static stua_dict       *stu__c;
13422 static stua_obj stu__funceval(stua_obj fo, stua_obj co);
13423 
13424 static int stu__cond(stua_obj x)
13425 {
13426    if (stu__flow) return 0;
13427    if (!stu__checkt(STU___boolean, x))
13428       x = stu__op('!', x, stua_nil, stua_nil);
13429    if (x == stua_true ) return 1;
13430    if (x == stua_false) return 0;
13431    stu__flow = FLOW_error;
13432    return 0;
13433 }
13434 
13435 // had to manually eliminate tailcall recursion for debugging complex stuff
13436 #define TAILCALL(x)   n = (x); goto top;
13437 static stua_obj stu__eval(int n)
13438 {
13439 top:
13440    if (stu__flow >= FLOW_return) return stua_nil; // is this needed?
13441    if (n < 0) return stu__const(stu__f)[n];
13442    assert(n != 0 && n != 1);
13443    switch (stu__f[n]) {
13444       stua_obj a,b,c;
13445       case ST_catch:   a = stu__eval(stu__f[n+1]);
13446                        if (stu__flow == FLOW_error) { a=stu__flow_val; stu__flow = FLOW_normal; }
13447                        return a;
13448       case ST_var:     b = stu__eval(stu__f[n+2]); if (stu__flow) break;
13449                        stu__set(stu__c, stu__const(stu__f)[stu__f[n+1]], b);
13450                        return b;
13451       case STU__seq:   stu__eval(stu__f[n+1]); if (stu__flow) break;
13452                        TAILCALL(stu__f[n+2]);
13453       case ST_if:      if (!stu__cond(stu__eval(stu__f[n+1]))) return stua_nil;
13454                        TAILCALL(stu__f[n+2]);
13455       case ST_else:    a = stu__cond(stu__eval(stu__f[n+1]));
13456                        TAILCALL(stu__f[n + 2 + !a]);
13457                        #define STU__HANDLE_BREAK            \
13458                           if (stu__flow >= FLOW_break) {    \
13459                              if (stu__flow == FLOW_break) { \
13460                                 a = stu__flow_val;          \
13461                                 stu__flow = FLOW_normal;    \
13462                                 stu__flow_val = stua_nil;   \
13463                                 return a;                   \
13464                              }                              \
13465                              return stua_nil;               \
13466                           }
13467       case ST_as:      stu__eval(stu__f[n+3]);
13468                        STU__HANDLE_BREAK
13469                        // fallthrough!
13470       case ST_while:   a = stua_nil; stua_pushroot(a);
13471                        while (stu__cond(stu__eval(stu__f[n+1]))) {
13472                           stua_poproot();
13473                           a = stu__eval(stu__f[n+2]);
13474                           STU__HANDLE_BREAK
13475                           stu__flow = FLOW_normal;  // clear 'continue' flag
13476                           stua_pushroot(a);
13477                           if (stu__f[n+3]) stu__eval(stu__f[n+3]);
13478                           STU__HANDLE_BREAK
13479                           stu__flow = FLOW_normal;  // clear 'continue' flag
13480                        }
13481                        stua_poproot();
13482                        return a;
13483       case ST_break:   stu__flow = FLOW_break;  stu__flow_val = stu__eval(stu__f[n+1]); break;
13484       case ST_continue:stu__flow = FLOW_continue; break;
13485       case ST_return:  stu__flow = FLOW_return; stu__flow_val = stu__eval(stu__f[n+1]); break;
13486       case ST__frame:  return stu__f_obj;
13487       case '[':        STU__EVAL2(a,b);
13488                        if (stu__checkt(STU___dict, a))
13489                           return stu__get(stu__pd(a), b, stua_nil);
13490                        return stu__op(stu__f[n], a, b, stua_nil);
13491       case '=':        a = stu__eval(stu__f[n+2]); if (stu__flow) break;
13492                        n = stu__f[n+1];
13493                        if (stu__f[n] == ST_id) {
13494                           if (!stb_idict_update(stu__c, stu__const(stu__f)[stu__f[n+1]], a))
13495                              if (!stb_idict_update(stu__globaldict, stu__const(stu__f)[stu__f[n+1]], a))
13496                                 return stua_error("Assignment to undefined variable");
13497                        } else if (stu__f[n] == '[') {
13498                           stua_pushroot(a);
13499                           b = stu__eval(stu__f[n+1]); if (stu__flow) { stua_poproot(); break; }
13500                           stua_pushroot(b);
13501                           c = stu__eval(stu__f[n+2]); stua_poproot(); stua_poproot();
13502                           if (stu__flow) break;
13503                           if (!stu__checkt(STU___dict, b)) return stua_nil;
13504                           stu__set(stu__pd(b), c, a);
13505                        } else {
13506                           return stu__op(stu__f[n], stu__eval(n), a, stua_nil);
13507                        }
13508                        return a;
13509       case STU__defaultparm:
13510                        a = stu__eval(stu__f[n+2]);
13511                        stu__flow = FLOW_normal;
13512                        if (stb_idict_add(stu__c, stu__const(stu__f)[stu__f[n+1]], a))
13513                           stu__size_allocs += 8;
13514                        return stua_nil;
13515       case ST_id:      a = stu__get(stu__c, stu__const(stu__f)[stu__f[n+1]], STUA_NO_VALUE); // try local variable
13516                        return a != STUA_NO_VALUE       // else try stu__compile_global_scope variable
13517                             ? a : stu__get(stu__globaldict, stu__const(stu__f)[stu__f[n+1]], stua_nil);
13518       case STU__negate:a = stu__eval(stu__f[n+1]); if (stu__flow) break;
13519                        return stu__isint(a) ? -a : stu__op(stu__f[n], a, stua_nil, stua_nil);
13520       case '~':        a = stu__eval(stu__f[n+1]); if (stu__flow) break;
13521                        return stu__isint(a) ? (~a)&~3 : stu__op(stu__f[n], a, stua_nil, stua_nil);
13522       case '!':        a = stu__eval(stu__f[n+1]); if (stu__flow) break;
13523                        a = stu__cond(a); if (stu__flow) break;
13524                        return a ? stua_true : stua_false;
13525       case ST_eq: STU__CE(==); case ST_le: STU__C(<=); case '<': STU__C(<);
13526       case ST_ne: STU__CE(!=); case ST_ge: STU__C(>=); case '>': STU__C(>);
13527       case '+' : STU__FB(+);  case '*': STU__F(*);  case '&': STU__I(&); case ST_shl: STU__I(<<);
13528       case '-' : STU__FB(-);  case '/': STU__F(/);  case '|': STU__I(|); case ST_shr: STU__I(>>);
13529                              case '%': STU__I(%);  case '^': STU__I(^);
13530       case ST_shru:    STU__EVAL2(a,b);
13531                        if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag)
13532                           return stu__makeint((unsigned) stu__int(a) >> stu__int(b));
13533                        return stu__op(stu__f[n], a,b, stua_nil);
13534       case ST_and:      a = stu__eval(stu__f[n+1]); b = stu__cond(a); if (stu__flow) break;
13535                        return a ? stu__eval(stu__f[n+2]) : a;
13536       case ST_or :      a = stu__eval(stu__f[n+1]); b = stu__cond(a); if (stu__flow) break;
13537                        return a ? b : stu__eval(stu__f[n+2]);
13538       case'(':case':': STU__EVAL2(a,b);
13539                        if (!stu__checkt(STU___function, a))
13540                            return stu__op(stu__f[n], a,b, stua_nil);
13541                        if (!stu__checkt(STU___dict, b))
13542                            return stua_nil;
13543                        if (stu__f[n] == ':')
13544                           b = stu__makeobj(STU___dict, stb_idict_copy(stu__pd(b)), stb_idict_memory_usage(stu__pd(b)), 0);
13545                        a = stu__funceval(a,b);
13546                        return a;
13547       case '{' :    {
13548                        stua_dict *d;
13549                        d = stb_idict_new_size(stu__f[n+1] > 40 ? 64 : 16);
13550                        if (d == NULL)
13551                           return stua_nil; // breakpoint fodder
13552                        c = stu__makeobj(STU___dict, d, 32, 1);
13553                        stua_pushroot(c);
13554                        a = stu__f[n+1];
13555                        for (b=0; b < a; ++b) {
13556                           stua_obj x = stua_pushroot(stu__eval(stu__f[n+2 + b*2 + 0]));
13557                           stua_obj y = stu__eval(stu__f[n+2 + b*2 + 1]);
13558                           stua_poproot();
13559                           if (stu__flow) { stua_poproot(); return stua_nil; }
13560                           stu__set(d, x, y);
13561                        }
13562                        stua_poproot();
13563                        return c;
13564                     }
13565       default:         if (stu__f[n] < 0) return stu__const(stu__f)[stu__f[n]];
13566                        assert(0); /* NOTREACHED */ // internal error!
13567    }
13568    return stua_nil;
13569 }
13570 
13571 int stb__stua_nesting;
13572 static stua_obj stu__funceval(stua_obj fo, stua_obj co)
13573 {
13574    stu__func *f = stu__pf(fo);
13575    stua_dict *context = stu__pd(co);
13576    int i,j;
13577    stua_obj p;
13578    short *tf = stu__f;     // save previous function
13579    stua_dict *tc = stu__c;
13580 
13581    if (stu__flow == FLOW_error) return stua_nil;
13582    assert(stu__flow == FLOW_normal);
13583 
13584    stua_pushroot(fo);
13585    stua_pushroot(co);
13586    stu__consider_gc(stua_nil);
13587 
13588    while ((stb_uint) f->closure_source > 4) {
13589       // add data from closure to context
13590       stua_dict *e = (stua_dict *) stu__pd(f->f.closure_data);
13591       for (i=0; i < e->limit; ++i)
13592          if (e->table[i].k != STB_IEMPTY && e->table[i].k != STB_IDEL)
13593             if (stb_idict_add(context, e->table[i].k, e->table[i].v))
13594                stu__size_allocs += 8;
13595             // use add so if it's already defined, we don't override it; that way
13596             // explicit parameters win over applied ones, and most recent applications
13597             // win over previous ones
13598       f = stu__pf(f->closure_source);
13599    }
13600 
13601    for (j=0, i=0; i < f->num_param; ++i)
13602       // if it doesn't already exist, add it from the numbered parameters
13603       if (stb_idict_add(context, f->param[i], stu__get(context, stu__int(j), stua_nil)))
13604          ++j;
13605 
13606    // @TODO: if (stu__get(context, stu__int(f->num_param+1)) != STUA_NO_VALUE) // error: too many parameters
13607    // @TODO: ditto too few parameters
13608 
13609    if (f->closure_source == 4)
13610       p = f->f.func(context);
13611    else {
13612       stu__f = f->code, stu__c = context;
13613       stu__f_obj = co;
13614       ++stb__stua_nesting;
13615       if (stu__f[1])
13616          p = stu__eval(stu__f[1]);
13617       else
13618          p = stua_nil;
13619       --stb__stua_nesting;
13620       stu__f = tf, stu__c = tc;  // restore previous function
13621       if (stu__flow == FLOW_return) {
13622          stu__flow = FLOW_normal;
13623          p = stu__flow_val;
13624          stu__flow_val = stua_nil;
13625       }
13626    }
13627 
13628    stua_poproot();
13629    stua_poproot();
13630 
13631    return p;
13632 }
13633 
13634 // Parser
13635 
13636 static int stu__tok;
13637 static stua_obj stu__tokval;
13638 
13639 static char *stu__curbuf, *stu__bufstart;
13640 
13641 static stb_matcher *stu__lex_matcher;
13642 
13643 static unsigned char stu__prec[ST__max_terminals], stu__end[ST__max_terminals];
13644 
13645 static void stu__nexttoken(void)
13646 {
13647    int len;
13648 
13649 retry:
13650    stu__tok = stb_lex(stu__lex_matcher, stu__curbuf, &len);
13651    if (stu__tok == 0)
13652       return;
13653    switch(stu__tok) {
13654       case ST_white  : stu__curbuf += len; goto retry;
13655       case T__none  : stu__tok = *stu__curbuf; break;
13656       case ST_string:  stu__tokval = make_string(stu__curbuf+1, len-2); break;
13657       case ST_id    :  stu__tokval = make_string(stu__curbuf, len); break;
13658       case ST_hex    : stu__tokval = stu__makeint(strtol(stu__curbuf+2,NULL,16)); stu__tok = ST_number; break;
13659       case ST_decimal: stu__tokval = stu__makeint(strtol(stu__curbuf  ,NULL,10)); stu__tok = ST_number; break;
13660       case ST_float  : stu__tokval = stua_float((float) atof(stu__curbuf))       ; stu__tok = ST_number; break;
13661       case ST_char   : stu__tokval = stu__curbuf[2] == '\\' ? stu__curbuf[3] : stu__curbuf[2];
13662                       if (stu__curbuf[3] == 't') stu__tokval = '\t';
13663                       if (stu__curbuf[3] == 'n') stu__tokval = '\n';
13664                       if (stu__curbuf[3] == 'r') stu__tokval = '\r';
13665                       stu__tokval = stu__makeint(stu__tokval);
13666                       stu__tok  = ST_number;
13667                       break;
13668    }
13669    stu__curbuf += len;
13670 }
13671 
13672 static struct { int stu__tok; char *regex; } stu__lexemes[] =
13673 {
13674    ST_white  , "([ \t\n\r]|/\\*(.|\n)*\\*/|//[^\r\n]*([\r\n]|$))+",
13675    ST_id     , "[_a-zA-Z][_a-zA-Z0-9]*",
13676    ST_hex    , "0x[0-9a-fA-F]+",
13677    ST_decimal, "[0-9]+[0-9]*",
13678    ST_float  , "[0-9]+\\.?[0-9]*([eE][-+]?[0-9]+)?",
13679    ST_float  , "\\.[0-9]+([eE][-+]?[0-9]+)?",
13680    ST_char   , "c'(\\\\.|[^\\'])'",
13681    ST_string , "\"(\\\\.|[^\\\"\n\r])*\"",
13682    ST_string , "\'(\\\\.|[^\\\'\n\r])*\'",
13683 
13684    #define stua_key4(a,b,c,d)  ST_##a, #a, ST_##b, #b, ST_##c, #c, ST_##d, #d,
13685    stua_key4(if,then,else,elseif)    stua_key4(while,do,for,in)
13686    stua_key4(func,var,let,break)     stua_key4(nil,true,false,end)
13687    stua_key4(return,continue,as,repeat) stua_key4(_frame,catch,catch,catch)
13688 
13689    ST_shl, "<<",   ST_and, "&&",  ST_eq,  "==",  ST_ge, ">=",
13690    ST_shr, ">>",   ST_or , "||",  ST_ne,  "!=",  ST_le, "<=",
13691    ST_shru,">>>",  ST_into, "=>",
13692    T__none, ".",
13693 };
13694 
13695 typedef struct
13696 {
13697    stua_obj  *data;    // constants being compiled
13698    short     *code;    // code being compiled
13699    stua_dict *locals;
13700    short     *non_local_refs;
13701 } stu__comp_func;
13702 
13703 static stu__comp_func stu__pfunc;
13704 static stu__comp_func *func_stack = NULL;
13705 static void stu__push_func_comp(void)
13706 {
13707    stb_arr_push(func_stack, stu__pfunc);
13708    stu__pfunc.data = NULL;
13709    stu__pfunc.code = NULL;
13710    stu__pfunc.locals = stb_idict_new_size(16);
13711    stu__pfunc.non_local_refs = NULL;
13712    stb_arr_push(stu__pfunc.code, 0); // number of data items
13713    stb_arr_push(stu__pfunc.code, 1); // starting execution address
13714 }
13715 
13716 static void stu__pop_func_comp(void)
13717 {
13718    stb_arr_free(stu__pfunc.code);
13719    stb_arr_free(stu__pfunc.data);
13720    stb_idict_destroy(stu__pfunc.locals);
13721    stb_arr_free(stu__pfunc.non_local_refs);
13722    stu__pfunc = stb_arr_pop(func_stack);
13723 }
13724 
13725 // if an id is a reference to an outer lexical scope, this
13726 // function returns the "name" of it, and updates the stack
13727 // structures to make sure the names are propogated in.
13728 static int stu__nonlocal_id(stua_obj var_obj)
13729 {
13730    stua_obj dummy, var = var_obj;
13731    int i, n = stb_arr_len(func_stack), j,k;
13732    if (stb_idict_get_flag(stu__pfunc.locals, var, &dummy)) return 0;
13733    for (i=n-1; i > 1; --i) {
13734       if (stb_idict_get_flag(func_stack[i].locals, var, &dummy))
13735          break;
13736    }
13737    if (i <= 1) return 0; // stu__compile_global_scope
13738    j = i; // need to access variable from j'th frame
13739    for (i=0; i < stb_arr_len(stu__pfunc.non_local_refs); ++i)
13740       if (stu__pfunc.non_local_refs[i] == j) return j-n;
13741    stb_arr_push(stu__pfunc.non_local_refs, j-n);
13742    // now make sure all the parents propogate it down
13743    for (k=n-1; k > 1; --k) {
13744       if (j-k >= 0) return j-n; // comes direct from this parent
13745       for(i=0; i < stb_arr_len(func_stack[k].non_local_refs); ++i)
13746          if (func_stack[k].non_local_refs[i] == j-k)
13747             return j-n;
13748       stb_arr_push(func_stack[k].non_local_refs, j-k);
13749    }
13750    assert (k != 1);
13751 
13752    return j-n;
13753 }
13754 
13755 static int stu__off(void)                { return stb_arr_len(stu__pfunc.code); }
13756 static void stu__cc(int a)
13757 {
13758    assert(a >= -2000 && a < 5000);
13759    stb_arr_push(stu__pfunc.code, a);
13760 }
13761 static int stu__cc1(int a)                      { stu__cc(a); return stu__off()-1; }
13762 static int stu__cc2(int a, int b)               { stu__cc(a); stu__cc(b); return stu__off()-2; }
13763 static int stu__cc3(int a, int b, int c)        {
13764  if (a == '=') assert(c != 0);
13765  stu__cc(a); stu__cc(b); stu__cc(c); return stu__off()-3; }
13766 static int stu__cc4(int a, int b, int c, int d) { stu__cc(a); stu__cc(b); stu__cc(c); stu__cc(d); return stu__off()-4; }
13767 
13768 static int stu__cdv(stua_obj p)
13769 {
13770    int i;
13771    assert(p != STUA_NO_VALUE);
13772    for (i=0; i < stb_arr_len(stu__pfunc.data); ++i)
13773       if (stu__pfunc.data[i] == p)
13774          break;
13775    if (i == stb_arr_len(stu__pfunc.data))
13776       stb_arr_push(stu__pfunc.data, p);
13777    return ~i;
13778 }
13779 
13780 static int stu__cdt(void)
13781 {
13782    int z = stu__cdv(stu__tokval);
13783    stu__nexttoken();
13784    return z;
13785 }
13786 
13787 static int stu__seq(int a, int b)
13788 {
13789    return !a ? b : !b ? a : stu__cc3(STU__seq, a,b);
13790 }
13791 
13792 static char stu__comp_err_str[1024];
13793 static int stu__comp_err_line;
13794 static int stu__err(char *str, ...)
13795 {
13796    va_list v;
13797    char *s = stu__bufstart;
13798    stu__comp_err_line = 1;
13799    while (s < stu__curbuf) {
13800       if (s[0] == '\n' || s[0] == '\r') {
13801          if (s[0]+s[1] == '\n' + '\r') ++s;
13802          ++stu__comp_err_line;
13803       }
13804       ++s;
13805    }
13806    va_start(v, str);
13807    vsprintf(stu__comp_err_str, str, v);
13808    va_end(v);
13809    return 0;
13810 }
13811 
13812 static int stu__accept(int p)
13813 {
13814    if (stu__tok != p) return 0;
13815    stu__nexttoken();
13816    return 1;
13817 }
13818 
13819 static int stu__demand(int p)
13820 {
13821    if (stu__accept(p)) return 1;
13822    return stu__err("Didn't find expected stu__tok");
13823 }
13824 
13825 static int stu__demandv(int p, stua_obj *val)
13826 {
13827    if (stu__tok == p || p==0) {
13828       *val = stu__tokval;
13829       stu__nexttoken();
13830       return 1;
13831    } else
13832       return 0;
13833 }
13834 
13835 static int stu__expr(int p);
13836 int stu__nexpr(int p) { stu__nexttoken(); return stu__expr(p); }
13837 static int stu__statements(int once, int as);
13838 
13839 static int stu__parse_if(void)      // parse both ST_if and ST_elseif
13840 {
13841    int b,c,a;
13842    a = stu__nexpr(1);               if (!a) return 0;
13843    if (!stu__demand(ST_then))       return stu__err("expecting THEN");
13844    b = stu__statements(0,0);        if (!b) return 0;
13845    if (b == 1) b = -1;
13846 
13847    if (stu__tok == ST_elseif) {
13848       return stu__parse_if();
13849    } else if (stu__accept(ST_else)) {
13850       c = stu__statements(0,0); if (!c) return 0;
13851       if (!stu__demand(ST_end)) return stu__err("expecting END after else clause");
13852       return stu__cc4(ST_else, a, b, c);
13853    } else {
13854       if (!stu__demand(ST_end)) return stu__err("expecting END in if statement");
13855       return stu__cc3(ST_if, a, b);
13856    }
13857 }
13858 
13859 int stu__varinit(int z, int in_globals)
13860 {
13861    int a,b;
13862    stu__nexttoken();
13863    while (stu__demandv(ST_id, &b)) {
13864       if (!stb_idict_add(stu__pfunc.locals, b, 1))
13865          if (!in_globals) return stu__err("Redefined variable %s.", stu__pw(b)->ptr);
13866       if (stu__accept('=')) {
13867          a = stu__expr(1);       if (!a) return 0;
13868       } else
13869          a = stu__cdv(stua_nil);
13870       z = stu__seq(z, stu__cc3(ST_var, stu__cdv(b), a));
13871       if (!stu__accept(',')) break;
13872    }
13873    return z;
13874 }
13875 
13876 static int stu__compile_unary(int z, int outparm, int require_inparm)
13877 {
13878    int op = stu__tok, a, b;
13879    stu__nexttoken();
13880    if (outparm) {
13881       if (require_inparm || (stu__tok && stu__tok != ST_end && stu__tok != ST_else && stu__tok != ST_elseif && stu__tok !=';')) {
13882          a = stu__expr(1); if (!a) return 0;
13883       } else
13884          a = stu__cdv(stua_nil);
13885       b = stu__cc2(op, a);
13886    } else
13887       b = stu__cc1(op);
13888    return stu__seq(z,b);
13889 }
13890 
13891 static int stu__assign(void)
13892 {
13893    int z;
13894    stu__accept(ST_let);
13895    z = stu__expr(1); if (!z) return 0;
13896    if (stu__accept('=')) {
13897       int y,p = (z >= 0 ? stu__pfunc.code[z] : 0);
13898       if (z < 0 || (p != ST_id && p != '[')) return stu__err("Invalid lvalue in assignment");
13899       y = stu__assign();         if (!y) return 0;
13900       z = stu__cc3('=', z, y);
13901    }
13902    return z;
13903 }
13904 
13905 static int stu__statements(int once, int stop_while)
13906 {
13907    int a,b, c, z=0;
13908    for(;;) {
13909       switch (stu__tok) {
13910          case ST_if     : a = stu__parse_if(); if (!a) return 0;
13911                           z = stu__seq(z, a);
13912                           break;
13913          case ST_while  : if (stop_while) return (z ? z:1);
13914                           a = stu__nexpr(1); if (!a) return 0;
13915                           if (stu__accept(ST_as)) c = stu__statements(0,0); else c = 0;
13916                           if (!stu__demand(ST_do)) return stu__err("expecting DO");
13917                           b = stu__statements(0,0); if (!b) return 0;
13918                           if (!stu__demand(ST_end)) return stu__err("expecting END");
13919                           if (b == 1) b = -1;
13920                           z = stu__seq(z, stu__cc4(ST_while, a, b, c));
13921                           break;
13922          case ST_repeat : stu__nexttoken();
13923                           c = stu__statements(0,1); if (!c) return 0;
13924                           if (!stu__demand(ST_while)) return stu__err("expecting WHILE");
13925                           a = stu__expr(1); if (!a) return 0;
13926                           if (!stu__demand(ST_do)) return stu__err("expecting DO");
13927                           b = stu__statements(0,0); if (!b) return 0;
13928                           if (!stu__demand(ST_end)) return stu__err("expecting END");
13929                           if (b == 1) b = -1;
13930                           z = stu__seq(z, stu__cc4(ST_as, a, b, c));
13931                           break;
13932          case ST_catch  : a = stu__nexpr(1); if (!a) return 0;
13933                           z = stu__seq(z, stu__cc2(ST_catch, a));
13934                           break;
13935          case ST_var    : z = stu__varinit(z,0); break;
13936          case ST_return : z = stu__compile_unary(z,1,1); break;
13937          case ST_continue:z = stu__compile_unary(z,0,0); break;
13938          case ST_break  : z = stu__compile_unary(z,1,0); break;
13939          case ST_into   : if (z == 0 && !once) return stu__err("=> cannot be first statement in block");
13940                           a = stu__nexpr(99);
13941                           b = (a >= 0? stu__pfunc.code[a] : 0);
13942                           if (a < 0 || (b != ST_id && b != '[')) return stu__err("Invalid lvalue on right side of =>");
13943                           z = stu__cc3('=', a, z);
13944                           break;
13945          default        : if (stu__end[stu__tok]) return once ? 0 : (z ? z:1);
13946                           a = stu__assign(); if (!a) return 0;
13947                           stu__accept(';');
13948                           if (stu__tok && !stu__end[stu__tok]) {
13949                              if (a < 0)
13950                                 return stu__err("Constant has no effect");
13951                              if (stu__pfunc.code[a] != '(' && stu__pfunc.code[a] != '=')
13952                                 return stu__err("Expression has no effect");
13953                           }
13954                           z = stu__seq(z, a);
13955                           break;
13956       }
13957       if (!z) return 0;
13958       stu__accept(';');
13959       if (once && stu__tok != ST_into) return z;
13960    }
13961 }
13962 
13963 static int stu__postexpr(int z, int p);
13964 static int stu__dictdef(int end, int *count)
13965 {
13966    int z,n=0,i,flags=0;
13967    short *dict=NULL;
13968    stu__nexttoken();
13969    while (stu__tok != end) {
13970       if (stu__tok == ST_id) {
13971          stua_obj id = stu__tokval;
13972          stu__nexttoken();
13973          if (stu__tok == '=') {
13974             flags |= 1;
13975             stb_arr_push(dict, stu__cdv(id));
13976             z = stu__nexpr(1); if (!z) return 0;
13977          } else {
13978             z = stu__cc2(ST_id, stu__cdv(id));
13979             z = stu__postexpr(z,1); if (!z) return 0;
13980             flags |= 2;
13981             stb_arr_push(dict, stu__cdv(stu__makeint(n++)));
13982          }
13983       } else {
13984          z = stu__expr(1); if (!z) return 0;
13985          flags |= 2;
13986          stb_arr_push(dict, stu__cdv(stu__makeint(n++)));
13987       }
13988       if (end != ')' && flags == 3) { z=stu__err("can't mix initialized and uninitialized defs"); goto done;}
13989       stb_arr_push(dict, z);
13990       if (!stu__accept(',')) break;
13991    }
13992    if (!stu__demand(end))
13993       return stu__err(end == ')' ? "Expecting ) at end of function call"
13994                                  : "Expecting } at end of dictionary definition");
13995    z = stu__cc2('{', stb_arr_len(dict)/2);
13996    for (i=0; i < stb_arr_len(dict); ++i)
13997       stu__cc(dict[i]);
13998    if (count) *count = n;
13999 done:
14000    stb_arr_free(dict);
14001    return z;
14002 }
14003 
14004 static int stu__comp_id(void)
14005 {
14006    int z,d;
14007    d = stu__nonlocal_id(stu__tokval);
14008    if (d == 0)
14009       return z = stu__cc2(ST_id, stu__cdt());
14010    // access a non-local frame by naming it with the appropriate int
14011    assert(d < 0);
14012    z = stu__cdv(d);            // relative frame # is the 'variable' in our local frame
14013    z = stu__cc2(ST_id, z);     // now access that dictionary
14014    return stu__cc3('[', z, stu__cdt()); // now access the variable from that dir
14015 }
14016 
14017 static stua_obj stu__funcdef(stua_obj *id, stua_obj *func);
14018 static int stu__expr(int p)
14019 {
14020    int z;
14021    // unary
14022    switch (stu__tok) {
14023       case ST_number: z = stu__cdt(); break;
14024       case ST_string: z = stu__cdt(); break;  // @TODO - string concatenation like C
14025       case ST_id    : z = stu__comp_id(); break;
14026       case ST__frame: z = stu__cc1(ST__frame); stu__nexttoken(); break;
14027       case ST_func  : z = stu__funcdef(NULL,NULL); break;
14028       case ST_if    : z = stu__parse_if(); break;
14029       case ST_nil   : z = stu__cdv(stua_nil); stu__nexttoken(); break;
14030       case ST_true  : z = stu__cdv(stua_true); stu__nexttoken(); break;
14031       case ST_false : z = stu__cdv(stua_false); stu__nexttoken(); break;
14032       case '-'      : z = stu__nexpr(99); if (z) z=stu__cc2(STU__negate,z); else return z; break;
14033       case '!'      : z = stu__nexpr(99); if (z) z=stu__cc2('!',z); else return z; break;
14034       case '~'      : z = stu__nexpr(99); if (z) z=stu__cc2('~',z); else return z; break;
14035       case '{'      : z = stu__dictdef('}', NULL); break;
14036       default       : return stu__err("Unexpected token");
14037       case '('      : stu__nexttoken(); z = stu__statements(0,0); if (!stu__demand(')')) return stu__err("Expecting )");
14038    }
14039    return stu__postexpr(z,p);
14040 }
14041 
14042 static int stu__postexpr(int z, int p)
14043 {
14044    int q;
14045    // postfix
14046    while (stu__tok == '(' || stu__tok == '[' || stu__tok == '.') {
14047       if (stu__accept('.')) {
14048          // MUST be followed by a plain identifier! use [] for other stuff
14049          if (stu__tok != ST_id) return stu__err("Must follow . with plain name; try [] instead");
14050          z = stu__cc3('[', z, stu__cdv(stu__tokval));
14051          stu__nexttoken();
14052       } else if (stu__accept('[')) {
14053          while (stu__tok != ']') {
14054             int r = stu__expr(1); if (!r) return 0;
14055             z = stu__cc3('[', z, r);
14056             if (!stu__accept(',')) break;
14057          }
14058          if (!stu__demand(']')) return stu__err("Expecting ]");
14059       } else {
14060          int n, p = stu__dictdef(')', &n); if (!p) return 0;
14061          #if 0 // this is incorrect!
14062          if (z > 0 && stu__pfunc.code[z] == ST_id) {
14063             stua_obj q = stu__get(stu__globaldict, stu__pfunc.data[-stu__pfunc.code[z+1]-1], stua_nil);
14064             if (stu__checkt(STU___function, q))
14065                if ((stu__pf(q))->num_param != n)
14066                   return stu__err("Incorrect number of parameters");
14067          }
14068          #endif
14069          z = stu__cc3('(', z, p);
14070       }
14071    }
14072    // binop - this implementation taken from lcc
14073    for (q=stu__prec[stu__tok]; q >= p; --q) {
14074       while (stu__prec[stu__tok] == q) {
14075          int o = stu__tok, y = stu__nexpr(p+1); if (!y) return 0;
14076          z = stu__cc3(o,z,y);
14077       }
14078    }
14079    return z;
14080 }
14081 
14082 static stua_obj stu__finish_func(stua_obj *param, int start)
14083 {
14084    int n, size;
14085    stu__func *f = (stu__func *) malloc(sizeof(*f));
14086    f->closure_source = 0;
14087    f->num_param = stb_arr_len(param);
14088    f->param = (int *) stb_copy(param, f->num_param * sizeof(*f->param));
14089    size = stb_arr_storage(stu__pfunc.code) + stb_arr_storage(stu__pfunc.data) + sizeof(*f) + 8;
14090    f->f.store = malloc(stb_arr_storage(stu__pfunc.code) + stb_arr_storage(stu__pfunc.data));
14091    f->code = (short *) ((char *) f->f.store + stb_arr_storage(stu__pfunc.data));
14092    memcpy(f->code, stu__pfunc.code, stb_arr_storage(stu__pfunc.code));
14093    f->code[1] = start;
14094    f->code[0] = stb_arr_len(stu__pfunc.data);
14095    for (n=0; n < f->code[0]; ++n)
14096       ((stua_obj *) f->code)[-1-n] = stu__pfunc.data[n];
14097    return stu__makeobj(STU___function, f, size, 0);
14098 }
14099 
14100 static int stu__funcdef(stua_obj *id, stua_obj *result)
14101 {
14102    int n,z=0,i,q;
14103    stua_obj *param = NULL;
14104    short *nonlocal;
14105    stua_obj v,f=stua_nil;
14106    assert(stu__tok == ST_func);
14107    stu__nexttoken();
14108    if (id) {
14109       if (!stu__demandv(ST_id, id)) return stu__err("Expecting function name");
14110    } else
14111       stu__accept(ST_id);
14112    if (!stu__demand('(')) return stu__err("Expecting ( for function parameter");
14113    stu__push_func_comp();
14114    while (stu__tok != ')') {
14115       if (!stu__demandv(ST_id, &v)) { z=stu__err("Expecting parameter name"); goto done; }
14116       stb_idict_add(stu__pfunc.locals, v, 1);
14117       if (stu__tok == '=') {
14118          n = stu__nexpr(1); if (!n) { z=0; goto done; }
14119          z = stu__seq(z, stu__cc3(STU__defaultparm, stu__cdv(v), n));
14120       } else
14121          stb_arr_push(param, v);
14122       if (!stu__accept(',')) break;
14123    }
14124    if (!stu__demand(')'))   { z=stu__err("Expecting ) at end of parameter list"); goto done; }
14125    n = stu__statements(0,0);   if (!n) { z=0; goto done; }
14126    if (!stu__demand(ST_end)) { z=stu__err("Expecting END at end of function"); goto done; }
14127    if (n == 1) n = 0;
14128    n = stu__seq(z,n);
14129    f = stu__finish_func(param, n);
14130    if (result) { *result = f; z=1; stu__pop_func_comp(); }
14131    else {
14132       nonlocal = stu__pfunc.non_local_refs;
14133       stu__pfunc.non_local_refs = NULL;
14134       stu__pop_func_comp();
14135       z = stu__cdv(f);
14136       if (nonlocal) {  // build a closure with references to the needed frames
14137          short *initcode = NULL;
14138          for (i=0; i < stb_arr_len(nonlocal); ++i) {
14139             int k = nonlocal[i], p;
14140             stb_arr_push(initcode, stu__cdv(k));
14141             if (k == -1) p = stu__cc1(ST__frame);
14142             else { p = stu__cdv(stu__makeint(k+1)); p = stu__cc2(ST_id, p); }
14143             stb_arr_push(initcode, p);
14144          }
14145          q = stu__cc2('{', stb_arr_len(nonlocal));
14146          for (i=0; i < stb_arr_len(initcode); ++i)
14147             stu__cc(initcode[i]);
14148          z = stu__cc3('+', z, q);
14149          stb_arr_free(initcode);
14150       }
14151       stb_arr_free(nonlocal);
14152    }
14153 done:
14154    stb_arr_free(param);
14155    if (!z) stu__pop_func_comp();
14156    return z;
14157 }
14158 
14159 static int stu__compile_global_scope(void)
14160 {
14161    stua_obj o;
14162    int z=0;
14163 
14164    stu__push_func_comp();
14165    while (stu__tok != 0) {
14166       if (stu__tok == ST_func) {
14167          stua_obj id, f;
14168          if (!stu__funcdef(&id,&f))
14169             goto error;
14170          stu__set(stu__globaldict, id, f);
14171       } else if (stu__tok == ST_var) {
14172          z = stu__varinit(z,1); if (!z) goto error;
14173       } else {
14174          int y = stu__statements(1,0); if (!y) goto error;
14175          z = stu__seq(z,y);
14176       }
14177       stu__accept(';');
14178    }
14179    o = stu__finish_func(NULL, z);
14180    stu__pop_func_comp();
14181 
14182    o = stu__funceval(o, stua_globals); // initialize stu__globaldict
14183    if (stu__flow == FLOW_error)
14184       printf("Error: %s\n", ((stu__wrapper *) stu__ptr(stu__flow_val))->ptr);
14185    return 1;
14186 error:
14187    stu__pop_func_comp();
14188    return 0;
14189 }
14190 
14191 stua_obj stu__myprint(stua_dict *context)
14192 {
14193    stua_obj x = stu__get(context, stua_string("x"), stua_nil);
14194    if ((x & 1) == stu__float_tag) printf("%f", stu__getfloat(x));
14195    else if (stu__tag(x) == stu__int_tag) printf("%d", stu__int(x));
14196    else {
14197        stu__wrapper *s = stu__pw(x);
14198        if (s->type == STU___string || s->type == STU___error)
14199           printf("%s", s->ptr);
14200        else if (s->type == STU___dict) printf("{{dictionary}}");
14201        else if (s->type == STU___function) printf("[[function]]");
14202        else
14203           printf("[[ERROR:%s]]", s->ptr);
14204    }
14205    return x;
14206 }
14207 
14208 void stua_init(void)
14209 {
14210    if (!stu__globaldict) {
14211       int i;
14212       stua_obj s;
14213       stu__func *f;
14214 
14215       stu__prec[ST_and] = stu__prec[ST_or] =                     1;
14216       stu__prec[ST_eq ] = stu__prec[ST_ne] = stu__prec[ST_le] =
14217        stu__prec[ST_ge] = stu__prec['>' ]  = stu__prec['<'] =    2;
14218       stu__prec[':']    =                                        3;
14219       stu__prec['&']    = stu__prec['|']   = stu__prec['^'] =    4;
14220       stu__prec['+']    = stu__prec['-']   =                     5;
14221       stu__prec['*']    = stu__prec['/']   = stu__prec['%'] =
14222        stu__prec[ST_shl]= stu__prec[ST_shr]= stu__prec[ST_shru]= 6;
14223 
14224       stu__end[')']   = stu__end[ST_end] = stu__end[ST_else] = 1;
14225       stu__end[ST_do] = stu__end[ST_elseif] = 1;
14226 
14227       stu__float_init();
14228       stu__lex_matcher = stb_lex_matcher();
14229       for (i=0; i < sizeof(stu__lexemes)/sizeof(stu__lexemes[0]); ++i)
14230          stb_lex_item(stu__lex_matcher, stu__lexemes[i].regex, stu__lexemes[i].stu__tok);
14231 
14232       stu__globaldict = stb_idict_new_size(64);
14233       stua_globals    = stu__makeobj(STU___dict, stu__globaldict, 0,0);
14234       stu__strings    = stb_sdict_new(0);
14235 
14236       stu__curbuf = stu__bufstart = "func _print(x) end\n"
14237       "func print()\n  var x=0 while _frame[x] != nil as x=x+1 do _print(_frame[x]) end end\n";
14238       stu__nexttoken();
14239       if (!stu__compile_global_scope())
14240          printf("Compile error in line %d: %s\n", stu__comp_err_line, stu__comp_err_str);
14241 
14242       s = stu__get(stu__globaldict, stua_string("_print"), stua_nil);
14243       if (stu__tag(s) == stu__ptr_tag && stu__ptr(s)->type == STU___function) {
14244          f = stu__pf(s);
14245          free(f->f.store);
14246          f->closure_source = 4;
14247          f->f.func = stu__myprint;
14248          f->code = NULL;
14249       }
14250    }
14251 }
14252 
14253 void stua_uninit(void)
14254 {
14255    if (stu__globaldict) {
14256       stb_idict_remove_all(stu__globaldict);
14257       stb_arr_setlen(stu__gc_root_stack, 0);
14258       stua_gc(1);
14259       stb_idict_destroy(stu__globaldict);
14260       stb_sdict_delete(stu__strings);
14261       stb_matcher_free(stu__lex_matcher);
14262       stb_arr_free(stu__gc_ptrlist);
14263       stb_arr_free(func_stack);
14264       stb_arr_free(stu__gc_root_stack);
14265       stu__globaldict = NULL;
14266    }
14267 }
14268 
14269 void stua_run_script(char *s)
14270 {
14271    stua_init();
14272 
14273    stu__curbuf = stu__bufstart = s;
14274    stu__nexttoken();
14275 
14276    stu__flow = FLOW_normal;
14277 
14278    if (!stu__compile_global_scope())
14279       printf("Compile error in line %d: %s\n", stu__comp_err_line, stu__comp_err_str);
14280    stua_gc(1);
14281 }
14282 #endif // STB_DEFINE
14283 #endif // STB_STUA
14284 
14285 #undef STB_EXTERN
14286 #endif // STB_INCLUDE_STB_H
14287 
14288 /*
14289 ------------------------------------------------------------------------------
14290 This software is available under 2 licenses -- choose whichever you prefer.
14291 ------------------------------------------------------------------------------
14292 ALTERNATIVE A - MIT License
14293 Copyright (c) 2017 Sean Barrett
14294 Permission is hereby granted, free of charge, to any person obtaining a copy of
14295 this software and associated documentation files (the "Software"), to deal in
14296 the Software without restriction, including without limitation the rights to
14297 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
14298 of the Software, and to permit persons to whom the Software is furnished to do
14299 so, subject to the following conditions:
14300 The above copyright notice and this permission notice shall be included in all
14301 copies or substantial portions of the Software.
14302 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14303 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14304 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14305 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
14306 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
14307 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
14308 SOFTWARE.
14309 ------------------------------------------------------------------------------
14310 ALTERNATIVE B - Public Domain (www.unlicense.org)
14311 This is free and unencumbered software released into the public domain.
14312 Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
14313 software, either in source code form or as a compiled binary, for any purpose,
14314 commercial or non-commercial, and by any means.
14315 In jurisdictions that recognize copyright laws, the author or authors of this
14316 software dedicate any and all copyright interest in the software to the public
14317 domain. We make this dedication for the benefit of the public at large and to
14318 the detriment of our heirs and successors. We intend this dedication to be an
14319 overt act of relinquishment in perpetuity of all present and future rights to
14320 this software under copyright law.
14321 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14322 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14323 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14324 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
14325 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
14326 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14327 ------------------------------------------------------------------------------
14328 */
14329