Merge branch 'dev' into working
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sean Barrett · committed by Sean Barrett · parents 52ad6bd, 5c0cc31 · Browse files · 11 files·+14776 added−14709 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+14776 added−14709 removed
- tests:+0 added−0 removed
- other:+14776 added−14709 removed
Provenance
- Commit
c497f72- Tree
e4ccd66- Author
Sean Barrett <seanb@radgametools.com>- Committer
Sean Barrett <seanb@radgametools.com>- Parent 1
52ad6bd- Parent 2
5c0cc31
11 files changed+14776 added−14709 removed
This commit is too large to show whole: its files are listed by path, without their changes.
added:deprecated/stb.h+14454 added
1+/* stb.h - v2.37 - Sean's Tool Box -- public domain -- http://nothings.org/stb.h2+ no warranty is offered or implied; use this code at your own risk3+4+ This is a single header file with a bunch of useful utilities5+ for getting stuff done in C/C++.6+7+ Documentation: http://nothings.org/stb/stb_h.html8+ Unit tests: http://nothings.org/stb/stb.c9+10+ ============================================================================11+ You MUST12+13+ #define STB_DEFINE14+15+ in EXACTLY _one_ C or C++ file that includes this header, BEFORE the16+ include, like this:17+18+ #define STB_DEFINE19+ #include "stb.h"20+21+ All other files should just #include "stb.h" without the #define.22+ ============================================================================23+24+Version History25+26+ 2.36 various fixes27+ 2.35 fix clang-cl issues with swprintf28+ 2.34 fix warnings29+ 2.33 more fixes to random numbers30+ 2.32 stb_intcmprev, stb_uidict, fix random numbers on Linux31+ 2.31 stb_ucharcmp32+ 2.30 MinGW fix33+ 2.29 attempt to fix use of swprintf()34+ 2.28 various new functionality35+ 2.27 test _WIN32 not WIN32 in STB_THREADS36+ 2.26 various warning & bugfixes37+ 2.25 various warning & bugfixes38+ 2.24 various warning & bugfixes39+ 2.23 fix 2.2240+ 2.22 64-bit fixes from '!='; fix stb_sdict_copy() to have preferred name41+ 2.21 utf-8 decoder rejects "overlong" encodings; attempted 64-bit improvements42+ 2.20 fix to hash "copy" function--reported by someone with handle "!="43+ 2.19 ???44+ 2.18 stb_readdir_subdirs_mask45+ 2.17 stb_cfg_dir46+ 2.16 fix stb_bgio_, add stb_bgio_stat(); begin a streaming wrapper47+ 2.15 upgraded hash table template to allow:48+ - aggregate keys (explicit comparison func for EMPTY and DEL keys)49+ - "static" implementations (so they can be culled if unused)50+ 2.14 stb_mprintf51+ 2.13 reduce identifiable strings in STB_NO_STB_STRINGS52+ 2.12 fix STB_ONLY -- lots of uint32s, TRUE/FALSE things had crept in53+ 2.11 fix bug in stb_dirtree_get() which caused "c://path" sorts of stuff54+ 2.10 STB_F(), STB_I() inline constants (also KI,KU,KF,KD)55+ 2.09 stb_box_face_vertex_axis_side56+ 2.08 bugfix stb_trimwhite()57+ 2.07 colored printing in windows (why are we in 1985?)58+ 2.06 comparison functions are now functions-that-return-functions and59+ accept a struct-offset as a parameter (not thread-safe)60+ 2.05 compile and pass tests under Linux (but no threads); thread cleanup61+ 2.04 stb_cubic_bezier_1d, smoothstep, avoid dependency on registry62+ 2.03 ?63+ 2.02 remove integrated documentation64+ 2.01 integrate various fixes; stb_force_uniprocessor65+ 2.00 revised stb_dupe to use multiple hashes66+ 1.99 stb_charcmp67+ 1.98 stb_arr_deleten, stb_arr_insertn68+ 1.97 fix stb_newell_normal()69+ 1.96 stb_hash_number()70+ 1.95 hack stb__rec_max; clean up recursion code to use new functions71+ 1.94 stb_dirtree; rename stb_extra to stb_ptrmap72+ 1.93 stb_sem_new() API cleanup (no blockflag-starts blocked; use 'extra')73+ 1.92 stb_threadqueue--multi reader/writer queue, fixed size or resizeable74+ 1.91 stb_bgio_* for reading disk asynchronously75+ 1.90 stb_mutex uses CRITICAL_REGION; new stb_sync primitive for thread76+ joining; workqueue supports stb_sync instead of stb_semaphore77+ 1.89 support ';' in constant-string wildcards; stb_mutex wrapper (can78+ implement with EnterCriticalRegion eventually)79+ 1.88 portable threading API (only for win32 so far); worker thread queue80+ 1.87 fix wildcard handling in stb_readdir_recursive81+ 1.86 support ';' in wildcards82+ 1.85 make stb_regex work with non-constant strings;83+ beginnings of stb_introspect()84+ 1.84 (forgot to make notes)85+ 1.83 whoops, stb_keep_if_different wasn't deleting the temp file86+ 1.82 bring back stb_compress from stb_file.h for cmirror87+ 1.81 various bugfixes, STB_FASTMALLOC_INIT inits FASTMALLOC in release88+ 1.80 stb_readdir returns utf8; write own utf8-utf16 because lib was wrong89+ 1.79 stb_write90+ 1.78 calloc() support for malloc wrapper, STB_FASTMALLOC91+ 1.77 STB_FASTMALLOC92+ 1.76 STB_STUA - Lua-like language; (stb_image, stb_csample, stb_bilinear)93+ 1.75 alloc/free array of blocks; stb_hheap bug; a few stb_ps_ funcs;94+ hash*getkey, hash*copy; stb_bitset; stb_strnicmp; bugfix stb_bst95+ 1.74 stb_replaceinplace; use stdlib C function to convert utf8 to UTF-1696+ 1.73 fix performance bug & leak in stb_ischar (C++ port lost a 'static')97+ 1.72 remove stb_block, stb_block_manager, stb_decompress (to stb_file.h)98+ 1.71 stb_trimwhite, stb_tokens_nested, etc.99+ 1.70 back out 1.69 because it might problemize mixed builds; stb_filec()100+ 1.69 (stb_file returns 'char *' in C++)101+ 1.68 add a special 'tree root' data type for stb_bst; stb_arr_end102+ 1.67 full C++ port. (stb_block_manager)103+ 1.66 stb_newell_normal104+ 1.65 stb_lex_item_wild -- allow wildcard items which MUST match entirely105+ 1.64 stb_data106+ 1.63 stb_log_name107+ 1.62 stb_define_sort; C++ cleanup108+ 1.61 stb_hash_fast -- Paul Hsieh's hash function (beats Bob Jenkins'?)109+ 1.60 stb_delete_directory_recursive110+ 1.59 stb_readdir_recursive111+ 1.58 stb_bst variant with parent pointer for O(1) iteration, not O(log N)112+ 1.57 replace LCG random with Mersenne Twister (found a public domain one)113+ 1.56 stb_perfect_hash, stb_ischar, stb_regex114+ 1.55 new stb_bst API allows multiple BSTs per node (e.g. secondary keys)115+ 1.54 bugfix: stb_define_hash, stb_wildmatch, regexp116+ 1.53 stb_define_hash; recoded stb_extra, stb_sdict use it117+ 1.52 stb_rand_define, stb_bst, stb_reverse118+ 1.51 fix 'stb_arr_setlen(NULL, 0)'119+ 1.50 stb_wordwrap120+ 1.49 minor improvements to enable the scripting language121+ 1.48 better approach for stb_arr using stb_malloc; more invasive, clearer122+ 1.47 stb_lex (lexes stb.h at 1.5ML/s on 3Ghz P4; 60/70% of optimal/flex)123+ 1.46 stb_wrapper_*, STB_MALLOC_WRAPPER124+ 1.45 lightly tested DFA acceleration of regexp searching125+ 1.44 wildcard matching & searching; regexp matching & searching126+ 1.43 stb_temp127+ 1.42 allow stb_arr to use stb_malloc/realloc; note this is global128+ 1.41 make it compile in C++; (disable stb_arr in C++)129+ 1.40 stb_dupe tweak; stb_swap; stb_substr130+ 1.39 stb_dupe; improve stb_file_max to be less stupid131+ 1.38 stb_sha1_file: generate sha1 for file, even > 4GB132+ 1.37 stb_file_max; partial support for utf8 filenames in Windows133+ 1.36 remove STB__NO_PREFIX - poor interaction with IDE, not worth it134+ streamline stb_arr to make it separately publishable135+ 1.35 bugfixes for stb_sdict, stb_malloc(0), stristr136+ 1.34 (streaming interfaces for stb_compress)137+ 1.33 stb_alloc; bug in stb_getopt; remove stb_overflow138+ 1.32 (stb_compress returns, smaller&faster; encode window & 64-bit len)139+ 1.31 stb_prefix_count140+ 1.30 (STB__NO_PREFIX - remove stb_ prefixes for personal projects)141+ 1.29 stb_fput_varlen64, etc.142+ 1.28 stb_sha1143+ 1.27 ?144+ 1.26 stb_extra145+ 1.25 ?146+ 1.24 stb_copyfile147+ 1.23 stb_readdir148+ 1.22 ?149+ 1.21 ?150+ 1.20 ?151+ 1.19 ?152+ 1.18 ?153+ 1.17 ?154+ 1.16 ?155+ 1.15 stb_fixpath, stb_splitpath, stb_strchr2156+ 1.14 stb_arr157+ 1.13 ?stb, stb_log, stb_fatal158+ 1.12 ?stb_hash2159+ 1.11 miniML160+ 1.10 stb_crc32, stb_adler32161+ 1.09 stb_sdict162+ 1.08 stb_bitreverse, stb_ispow2, stb_big32163+ stb_fopen, stb_fput_varlen, stb_fput_ranged164+ stb_fcmp, stb_feq165+ 1.07 (stb_encompress)166+ 1.06 stb_compress167+ 1.05 stb_tokens, (stb_hheap)168+ 1.04 stb_rand169+ 1.03 ?(s-strings)170+ 1.02 ?stb_filelen, stb_tokens171+ 1.01 stb_tolower172+ 1.00 stb_hash, stb_intcmp173+ stb_file, stb_stringfile, stb_fgets174+ stb_prefix, stb_strlower, stb_strtok175+ stb_image176+ (stb_array), (stb_arena)177+178+Parenthesized items have since been removed.179+180+LICENSE181+182+ See end of file for license information.183+184+CREDITS185+186+ Written by Sean Barrett.187+188+ Fixes:189+ Philipp Wiesemann190+ Robert Nix191+ r-lyeh192+ blackpawn193+ github:Mojofreem194+ Ryan Whitworth195+ Vincent Isambart196+ Mike Sartain197+ Eugene Opalev198+ Tim Sjostrand199+ github:infatum200+ Dave Butler (Croepha)201+ Ethan Lee (flibitijibibo)202+ Brian Collins203+ Kyle Langley204+*/205+206+#include <stdarg.h>207+208+#ifndef STB__INCLUDE_STB_H209+#define STB__INCLUDE_STB_H210+211+#define STB_VERSION 1212+213+#ifdef STB_INTROSPECT214+ #define STB_DEFINE215+#endif216+217+#ifdef STB_DEFINE_THREADS218+ #ifndef STB_DEFINE219+ #define STB_DEFINE220+ #endif221+ #ifndef STB_THREADS222+ #define STB_THREADS223+ #endif224+#endif225+226+#if defined(_WIN32) && !defined(__MINGW32__)227+ #ifndef _CRT_SECURE_NO_WARNINGS228+ #define _CRT_SECURE_NO_WARNINGS229+ #endif230+ #ifndef _CRT_NONSTDC_NO_DEPRECATE231+ #define _CRT_NONSTDC_NO_DEPRECATE232+ #endif233+ #ifndef _CRT_NON_CONFORMING_SWPRINTFS234+ #define _CRT_NON_CONFORMING_SWPRINTFS235+ #endif236+ #if !defined(_MSC_VER) || _MSC_VER > 1700237+ #include <intrin.h> // _BitScanReverse238+ #endif239+#endif240+241+#include <stdlib.h> // stdlib could have min/max242+#include <stdio.h> // need FILE243+#include <string.h> // stb_define_hash needs memcpy/memset244+#include <time.h> // stb_dirtree245+#ifdef __MINGW32__246+ #include <fcntl.h> // O_RDWR247+#endif248+249+#ifdef STB_PERSONAL250+ typedef int Bool;251+ #define False 0252+ #define True 1253+#endif254+255+#ifdef STB_MALLOC_WRAPPER_PAGED256+ #define STB_MALLOC_WRAPPER_DEBUG257+#endif258+#ifdef STB_MALLOC_WRAPPER_DEBUG259+ #define STB_MALLOC_WRAPPER260+#endif261+#ifdef STB_MALLOC_WRAPPER_FASTMALLOC262+ #define STB_FASTMALLOC263+ #define STB_MALLOC_WRAPPER264+#endif265+266+#ifdef STB_FASTMALLOC267+ #ifndef _WIN32268+ #undef STB_FASTMALLOC269+ #endif270+#endif271+272+#ifdef STB_DEFINE273+ #include <assert.h>274+ #include <stdarg.h>275+ #include <stddef.h>276+ #include <ctype.h>277+ #include <math.h>278+ #ifndef _WIN32279+ #include <unistd.h>280+ #else281+ #include <io.h> // _mktemp282+ #include <direct.h> // _rmdir283+ #endif284+ #include <sys/types.h> // stat()/_stat()285+ #include <sys/stat.h> // stat()/_stat()286+#endif287+288+#define stb_min(a,b) ((a) < (b) ? (a) : (b))289+#define stb_max(a,b) ((a) > (b) ? (a) : (b))290+291+#ifndef STB_ONLY292+ #if !defined(__cplusplus) && !defined(min) && !defined(max)293+ #define min(x,y) stb_min(x,y)294+ #define max(x,y) stb_max(x,y)295+ #endif296+297+ #ifndef M_PI298+ #define M_PI 3.14159265358979323846f299+ #endif300+301+ #ifndef TRUE302+ #define TRUE 1303+ #define FALSE 0304+ #endif305+306+ #ifndef deg2rad307+ #define deg2rad(a) ((a)*(M_PI/180))308+ #endif309+ #ifndef rad2deg310+ #define rad2deg(a) ((a)*(180/M_PI))311+ #endif312+313+ #ifndef swap314+ #ifndef __cplusplus315+ #define swap(TYPE,a,b) \316+ do { TYPE stb__t; stb__t = (a); (a) = (b); (b) = stb__t; } while (0)317+ #endif318+ #endif319+320+ typedef unsigned char uint8 ;321+ typedef signed char int8 ;322+ typedef unsigned short uint16;323+ typedef signed short int16;324+ #if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32)325+ typedef unsigned long uint32;326+ typedef signed long int32;327+ #else328+ typedef unsigned int uint32;329+ typedef signed int int32;330+ #endif331+332+ typedef unsigned char uchar ;333+ typedef unsigned short ushort;334+ typedef unsigned int uint ;335+ typedef unsigned long ulong ;336+337+ // produce compile errors if the sizes aren't right338+ typedef char stb__testsize16[sizeof(int16)==2];339+ typedef char stb__testsize32[sizeof(int32)==4];340+#endif341+342+#ifndef STB_TRUE343+ #define STB_TRUE 1344+ #define STB_FALSE 0345+#endif346+347+// if we're STB_ONLY, can't rely on uint32 or even uint, so all the348+// variables we'll use herein need typenames prefixed with 'stb':349+typedef unsigned char stb_uchar;350+typedef unsigned char stb_uint8;351+typedef unsigned int stb_uint;352+typedef unsigned short stb_uint16;353+typedef short stb_int16;354+typedef signed char stb_int8;355+#if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32)356+ typedef unsigned long stb_uint32;357+ typedef long stb_int32;358+#else359+ typedef unsigned int stb_uint32;360+ typedef int stb_int32;361+#endif362+typedef char stb__testsize2_16[sizeof(stb_uint16)==2 ? 1 : -1];363+typedef char stb__testsize2_32[sizeof(stb_uint32)==4 ? 1 : -1];364+365+#ifdef _MSC_VER366+ typedef unsigned __int64 stb_uint64;367+ typedef __int64 stb_int64;368+ #define STB_IMM_UINT64(literalui64) (literalui64##ui64)369+ #define STB_IMM_INT64(literali64) (literali64##i64)370+#else371+ // ??372+ typedef unsigned long long stb_uint64;373+ typedef long long stb_int64;374+ #define STB_IMM_UINT64(literalui64) (literalui64##ULL)375+ #define STB_IMM_INT64(literali64) (literali64##LL)376+#endif377+typedef char stb__testsize2_64[sizeof(stb_uint64)==8 ? 1 : -1];378+379+// add platform-specific ways of checking for sizeof(char*) == 8,380+// and make those define STB_PTR64381+#if defined(_WIN64) || defined(__x86_64__) || defined(__ia64__) || defined(__LP64__)382+ #define STB_PTR64383+#endif384+385+#ifdef STB_PTR64386+typedef char stb__testsize2_ptr[sizeof(char *) == 8];387+typedef stb_uint64 stb_uinta;388+typedef stb_int64 stb_inta;389+#else390+typedef char stb__testsize2_ptr[sizeof(char *) == 4];391+typedef stb_uint32 stb_uinta;392+typedef stb_int32 stb_inta;393+#endif394+typedef char stb__testsize2_uinta[sizeof(stb_uinta)==sizeof(char*) ? 1 : -1];395+396+// if so, we should define an int type that is the pointer size. until then,397+// we'll have to make do with this (which is not the same at all!)398+399+typedef union400+{401+ unsigned int i;402+ void * p;403+} stb_uintptr;404+405+406+#ifdef __cplusplus407+ #define STB_EXTERN extern "C"408+#else409+ #define STB_EXTERN extern410+#endif411+412+// check for well-known debug defines413+#if defined(DEBUG) || defined(_DEBUG) || defined(DBG)414+ #ifndef NDEBUG415+ #define STB_DEBUG416+ #endif417+#endif418+419+#ifdef STB_DEBUG420+ #include <assert.h>421+#endif422+423+//////////////////////////////////////////////////////////////////////////////424+//425+// C library function platform handling426+//427+428+#ifdef STB_DEFINE429+430+#if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__)431+static FILE * stb_p_fopen(const char *filename, const char *mode)432+{433+ FILE *f;434+ if (0 == fopen_s(&f, filename, mode))435+ return f;436+ else437+ return NULL;438+}439+static FILE * stb_p_wfopen(const wchar_t *filename, const wchar_t *mode)440+{441+ FILE *f;442+ if (0 == _wfopen_s(&f, filename, mode))443+ return f;444+ else445+ return NULL;446+}447+static char *stb_p_strcpy_s(char *a, size_t size, const char *b)448+{449+ strcpy_s(a,size,b);450+ return a;451+}452+static char *stb_p_strncpy_s(char *a, size_t size, const char *b, size_t count)453+{454+ strncpy_s(a,size,b,count);455+ return a;456+}457+#define stb_p_mktemp(s) (_mktemp_s(s, strlen(s)+1) == 0)458+#define stb_p_sprintf sprintf_s459+#define stb_p_size(x) ,(x)460+#else461+#define stb_p_fopen fopen462+#define stb_p_wfopen _wfopen463+#define stb_p_strcpy_s(a,s,b) strcpy(a,b)464+#define stb_p_strncpy_s(a,s,b,c) strncpy(a,b,c)465+#define stb_p_mktemp(s) (mktemp(s) != NULL)466+467+#define stb_p_sprintf sprintf468+#define stb_p_size(x)469+#endif470+471+#if defined(_WIN32)472+#define stb_p_vsnprintf _vsnprintf473+#else474+#define stb_p_vsnprintf vsnprintf475+#endif476+#endif // STB_DEFINE477+478+#if defined(_WIN32) && (_MSC_VER >= 1300)479+#define stb_p_stricmp _stricmp480+#define stb_p_strnicmp _strnicmp481+#define stb_p_strdup _strdup482+#else483+#define stb_p_strdup strdup484+#define stb_p_stricmp stricmp485+#define stb_p_strnicmp strnicmp486+#endif487+488+STB_EXTERN void stb_wrapper_malloc(void *newp, size_t sz, char *file, int line);489+STB_EXTERN void stb_wrapper_free(void *oldp, char *file, int line);490+STB_EXTERN void stb_wrapper_realloc(void *oldp, void *newp, size_t sz, char *file, int line);491+STB_EXTERN void stb_wrapper_calloc(size_t num, size_t sz, char *file, int line);492+STB_EXTERN void stb_wrapper_listall(void (*func)(void *ptr, size_t sz, char *file, int line));493+STB_EXTERN void stb_wrapper_dump(char *filename);494+STB_EXTERN size_t stb_wrapper_allocsize(void *oldp);495+STB_EXTERN void stb_wrapper_check(void *oldp);496+497+#ifdef STB_DEFINE498+// this is a special function used inside malloc wrapper499+// to do allocations that aren't tracked (to avoid500+// reentrancy). Of course if someone _else_ wraps realloc,501+// this breaks, but if they're doing that AND the malloc502+// wrapper they need to explicitly check for reentrancy.503+//504+// only define realloc_raw() and we do realloc(NULL,sz)505+// for malloc() and realloc(p,0) for free().506+static void * stb__realloc_raw(void *p, int sz)507+{508+ if (p == NULL) return malloc(sz);509+ if (sz == 0) { free(p); return NULL; }510+ return realloc(p,sz);511+}512+#endif513+514+#ifdef _WIN32515+STB_EXTERN void * stb_smalloc(size_t sz);516+STB_EXTERN void stb_sfree(void *p);517+STB_EXTERN void * stb_srealloc(void *p, size_t sz);518+STB_EXTERN void * stb_scalloc(size_t n, size_t sz);519+STB_EXTERN char * stb_sstrdup(char *s);520+#endif521+522+#ifdef STB_FASTMALLOC523+#define malloc stb_smalloc524+#define free stb_sfree525+#define realloc stb_srealloc526+#define strdup stb_sstrdup527+#define calloc stb_scalloc528+#endif529+530+#ifndef STB_MALLOC_ALLCHECK531+ #define stb__check(p) 1532+#else533+ #ifndef STB_MALLOC_WRAPPER534+ #error STB_MALLOC_ALLCHECK requires STB_MALLOC_WRAPPER535+ #else536+ #define stb__check(p) stb_mcheck(p)537+ #endif538+#endif539+540+#ifdef STB_MALLOC_WRAPPER541+ STB_EXTERN void * stb__malloc(size_t, char *, int);542+ STB_EXTERN void * stb__realloc(void *, size_t, char *, int);543+ STB_EXTERN void * stb__calloc(size_t n, size_t s, char *, int);544+ STB_EXTERN void stb__free(void *, char *file, int);545+ STB_EXTERN char * stb__strdup(char *s, char *file, int);546+ STB_EXTERN void stb_malloc_checkall(void);547+ STB_EXTERN void stb_malloc_check_counter(int init_delay, int rep_delay);548+ #ifndef STB_MALLOC_WRAPPER_DEBUG549+ #define stb_mcheck(p) 1550+ #else551+ STB_EXTERN int stb_mcheck(void *);552+ #endif553+554+555+ #ifdef STB_DEFINE556+557+ #ifdef STB_MALLOC_WRAPPER_DEBUG558+ #define STB__PAD 32559+ #define STB__BIAS 16560+ #define STB__SIG 0x51b01234561+ #define STB__FIXSIZE(sz) (((sz+3) & ~3) + STB__PAD)562+ #define STB__ptr(x,y) ((char *) (x) + (y))563+ #else564+ #define STB__ptr(x,y) (x)565+ #define STB__FIXSIZE(sz) (sz)566+ #endif567+568+ #ifdef STB_MALLOC_WRAPPER_DEBUG569+ int stb_mcheck(void *p)570+ {571+ unsigned int sz;572+ if (p == NULL) return 1;573+ p = ((char *) p) - STB__BIAS;574+ sz = * (unsigned int *) p;575+ assert(* (unsigned int *) STB__ptr(p,4) == STB__SIG);576+ assert(* (unsigned int *) STB__ptr(p,8) == STB__SIG);577+ assert(* (unsigned int *) STB__ptr(p,12) == STB__SIG);578+ assert(* (unsigned int *) STB__ptr(p,sz-4) == STB__SIG+1);579+ assert(* (unsigned int *) STB__ptr(p,sz-8) == STB__SIG+1);580+ assert(* (unsigned int *) STB__ptr(p,sz-12) == STB__SIG+1);581+ assert(* (unsigned int *) STB__ptr(p,sz-16) == STB__SIG+1);582+ stb_wrapper_check(STB__ptr(p, STB__BIAS));583+ return 1;584+ }585+586+ static void stb__check2(void *p, size_t sz, char *file, int line)587+ {588+ stb_mcheck(p);589+ }590+591+ void stb_malloc_checkall(void)592+ {593+ stb_wrapper_listall(stb__check2);594+ }595+ #else596+ void stb_malloc_checkall(void) { }597+ #endif598+599+ static int stb__malloc_wait=(1 << 30), stb__malloc_next_wait = (1 << 30), stb__malloc_iter;600+ void stb_malloc_check_counter(int init_delay, int rep_delay)601+ {602+ stb__malloc_wait = init_delay;603+ stb__malloc_next_wait = rep_delay;604+ }605+606+ void stb_mcheck_all(void)607+ {608+ #ifdef STB_MALLOC_WRAPPER_DEBUG609+ ++stb__malloc_iter;610+ if (--stb__malloc_wait <= 0) {611+ stb_malloc_checkall();612+ stb__malloc_wait = stb__malloc_next_wait;613+ }614+ #endif615+ }616+617+ #ifdef STB_MALLOC_WRAPPER_PAGED618+ #define STB__WINDOWS_PAGE (1 << 12)619+ #ifndef _WINDOWS_620+ STB_EXTERN __declspec(dllimport) void * __stdcall VirtualAlloc(void *p, unsigned long size, unsigned long type, unsigned long protect);621+ STB_EXTERN __declspec(dllimport) int __stdcall VirtualFree(void *p, unsigned long size, unsigned long freetype);622+ #endif623+ #endif624+625+ static void *stb__malloc_final(size_t sz)626+ {627+ #ifdef STB_MALLOC_WRAPPER_PAGED628+ size_t aligned = (sz + STB__WINDOWS_PAGE - 1) & ~(STB__WINDOWS_PAGE-1);629+ char *p = VirtualAlloc(NULL, aligned + STB__WINDOWS_PAGE, 0x2000, 0x04); // RESERVE, READWRITE630+ if (p == NULL) return p;631+ VirtualAlloc(p, aligned, 0x1000, 0x04); // COMMIT, READWRITE632+ return p;633+ #else634+ return malloc(sz);635+ #endif636+ }637+638+ static void stb__free_final(void *p)639+ {640+ #ifdef STB_MALLOC_WRAPPER_PAGED641+ VirtualFree(p, 0, 0x8000); // RELEASE642+ #else643+ free(p);644+ #endif645+ }646+647+ int stb__malloc_failure;648+ #ifdef STB_MALLOC_WRAPPER_PAGED649+ static void *stb__realloc_final(void *p, size_t sz, size_t old_sz)650+ {651+ void *q = stb__malloc_final(sz);652+ if (q == NULL)653+ return ++stb__malloc_failure, q;654+ // @TODO: deal with p being smaller!655+ memcpy(q, p, sz < old_sz ? sz : old_sz);656+ stb__free_final(p);657+ return q;658+ }659+ #endif660+661+ void stb__free(void *p, char *file, int line)662+ {663+ stb_mcheck_all();664+ if (!p) return;665+ #ifdef STB_MALLOC_WRAPPER_DEBUG666+ stb_mcheck(p);667+ #endif668+ stb_wrapper_free(p,file,line);669+ #ifdef STB_MALLOC_WRAPPER_DEBUG670+ p = STB__ptr(p,-STB__BIAS);671+ * (unsigned int *) STB__ptr(p,0) = 0xdeadbeef;672+ * (unsigned int *) STB__ptr(p,4) = 0xdeadbeef;673+ * (unsigned int *) STB__ptr(p,8) = 0xdeadbeef;674+ * (unsigned int *) STB__ptr(p,12) = 0xdeadbeef;675+ #endif676+ stb__free_final(p);677+ }678+679+ void * stb__malloc(size_t sz, char *file, int line)680+ {681+ void *p;682+ stb_mcheck_all();683+ if (sz == 0) return NULL;684+ p = stb__malloc_final(STB__FIXSIZE(sz));685+ if (p == NULL) p = stb__malloc_final(STB__FIXSIZE(sz));686+ if (p == NULL) p = stb__malloc_final(STB__FIXSIZE(sz));687+ if (p == NULL) {688+ ++stb__malloc_failure;689+ #ifdef STB_MALLOC_WRAPPER_DEBUG690+ stb_malloc_checkall();691+ #endif692+ return p;693+ }694+ #ifdef STB_MALLOC_WRAPPER_DEBUG695+ * (int *) STB__ptr(p,0) = STB__FIXSIZE(sz);696+ * (unsigned int *) STB__ptr(p,4) = STB__SIG;697+ * (unsigned int *) STB__ptr(p,8) = STB__SIG;698+ * (unsigned int *) STB__ptr(p,12) = STB__SIG;699+ * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-4) = STB__SIG+1;700+ * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-8) = STB__SIG+1;701+ * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-12) = STB__SIG+1;702+ * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-16) = STB__SIG+1;703+ p = STB__ptr(p, STB__BIAS);704+ #endif705+ stb_wrapper_malloc(p,sz,file,line);706+ return p;707+ }708+709+ void * stb__realloc(void *p, size_t sz, char *file, int line)710+ {711+ void *q;712+713+ stb_mcheck_all();714+ if (p == NULL) return stb__malloc(sz,file,line);715+ if (sz == 0 ) { stb__free(p,file,line); return NULL; }716+717+ #ifdef STB_MALLOC_WRAPPER_DEBUG718+ stb_mcheck(p);719+ p = STB__ptr(p,-STB__BIAS);720+ #endif721+ #ifdef STB_MALLOC_WRAPPER_PAGED722+ {723+ size_t n = stb_wrapper_allocsize(STB__ptr(p,STB__BIAS));724+ if (!n)725+ stb_wrapper_check(STB__ptr(p,STB__BIAS));726+ q = stb__realloc_final(p, STB__FIXSIZE(sz), STB__FIXSIZE(n));727+ }728+ #else729+ q = realloc(p, STB__FIXSIZE(sz));730+ #endif731+ if (q == NULL)732+ return ++stb__malloc_failure, q;733+ #ifdef STB_MALLOC_WRAPPER_DEBUG734+ * (int *) STB__ptr(q,0) = STB__FIXSIZE(sz);735+ * (unsigned int *) STB__ptr(q,4) = STB__SIG;736+ * (unsigned int *) STB__ptr(q,8) = STB__SIG;737+ * (unsigned int *) STB__ptr(q,12) = STB__SIG;738+ * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-4) = STB__SIG+1;739+ * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-8) = STB__SIG+1;740+ * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-12) = STB__SIG+1;741+ * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-16) = STB__SIG+1;742+743+ q = STB__ptr(q, STB__BIAS);744+ p = STB__ptr(p, STB__BIAS);745+ #endif746+ stb_wrapper_realloc(p,q,sz,file,line);747+ return q;748+ }749+750+ STB_EXTERN int stb_log2_ceil(size_t);751+ static void *stb__calloc(size_t n, size_t sz, char *file, int line)752+ {753+ void *q;754+ stb_mcheck_all();755+ if (n == 0 || sz == 0) return NULL;756+ if (stb_log2_ceil(n) + stb_log2_ceil(sz) >= 32) return NULL;757+ q = stb__malloc(n*sz, file, line);758+ if (q) memset(q, 0, n*sz);759+ return q;760+ }761+762+ char * stb__strdup(char *s, char *file, int line)763+ {764+ char *p;765+ stb_mcheck_all();766+ p = stb__malloc(strlen(s)+1, file, line);767+ if (!p) return p;768+ stb_p_strcpy_s(p, strlen(s)+1, s);769+ return p;770+ }771+ #endif // STB_DEFINE772+773+ #ifdef STB_FASTMALLOC774+ #undef malloc775+ #undef realloc776+ #undef free777+ #undef strdup778+ #undef calloc779+ #endif780+781+ // include everything that might define these, BEFORE making macros782+ #include <stdlib.h>783+ #include <string.h>784+ #include <malloc.h>785+786+ #define malloc(s) stb__malloc ( s, __FILE__, __LINE__)787+ #define realloc(p,s) stb__realloc(p,s, __FILE__, __LINE__)788+ #define calloc(n,s) stb__calloc (n,s, __FILE__, __LINE__)789+ #define free(p) stb__free (p, __FILE__, __LINE__)790+ #define strdup(p) stb__strdup (p, __FILE__, __LINE__)791+#endif792+793+//////////////////////////////////////////////////////////////////////////////794+//795+// Windows pretty display796+//797+798+STB_EXTERN void stbprint(const char *fmt, ...);799+STB_EXTERN char *stb_sprintf(const char *fmt, ...);800+STB_EXTERN char *stb_mprintf(const char *fmt, ...);801+STB_EXTERN int stb_snprintf(char *s, size_t n, const char *fmt, ...);802+STB_EXTERN int stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v);803+804+#ifdef STB_DEFINE805+int stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v)806+{807+ int res;808+ #ifdef _WIN32809+ #ifdef __STDC_WANT_SECURE_LIB__810+ res = _vsnprintf_s(s, n, _TRUNCATE, fmt, v);811+ #else812+ res = stb_p_vsnprintf(s,n,fmt,v);813+ #endif814+ #else815+ res = vsnprintf(s,n,fmt,v);816+ #endif817+ if (n) s[n-1] = 0;818+ // Unix returns length output would require, Windows returns negative when truncated.819+ return (res >= (int) n || res < 0) ? -1 : res;820+}821+822+int stb_snprintf(char *s, size_t n, const char *fmt, ...)823+{824+ int res;825+ va_list v;826+ va_start(v,fmt);827+ res = stb_vsnprintf(s, n, fmt, v);828+ va_end(v);829+ return res;830+}831+832+char *stb_sprintf(const char *fmt, ...)833+{834+ static char buffer[1024];835+ va_list v;836+ va_start(v,fmt);837+ stb_vsnprintf(buffer,1024,fmt,v);838+ va_end(v);839+ return buffer;840+}841+842+char *stb_mprintf(const char *fmt, ...)843+{844+ static char buffer[1024];845+ va_list v;846+ va_start(v,fmt);847+ stb_vsnprintf(buffer,1024,fmt,v);848+ va_end(v);849+ return stb_p_strdup(buffer);850+}851+852+#ifdef _WIN32853+854+#ifndef _WINDOWS_855+STB_EXTERN __declspec(dllimport) int __stdcall WriteConsoleA(void *, const void *, unsigned int, unsigned int *, void *);856+STB_EXTERN __declspec(dllimport) void * __stdcall GetStdHandle(unsigned int);857+STB_EXTERN __declspec(dllimport) int __stdcall SetConsoleTextAttribute(void *, unsigned short);858+#endif859+860+static void stb__print_one(void *handle, char *s, ptrdiff_t len)861+{862+ if (len)863+ if (0==WriteConsoleA(handle, s, (unsigned) len, NULL,NULL))864+ // if it fails, maybe redirected, so output normally...865+ // but it's supriously reporting failure now on Win7 and later866+ {}//fwrite(s, 1, (unsigned) len, stdout);867+}868+869+static void stb__print(char *s)870+{871+ void *handle = GetStdHandle((unsigned int) -11); // STD_OUTPUT_HANDLE872+ int pad=0; // number of padding characters to add873+874+ char *t = s;875+ while (*s) {876+ int lpad;877+ while (*s && *s != '{') {878+ if (pad) {879+ if (*s == '\r' || *s == '\n')880+ pad = 0;881+ else if (s[0] == ' ' && s[1] == ' ') {882+ stb__print_one(handle, t, s-t);883+ t = s;884+ while (pad) {885+ stb__print_one(handle, t, 1);886+ --pad;887+ }888+ }889+ }890+ ++s;891+ }892+ if (!*s) break;893+ stb__print_one(handle, t, s-t);894+ if (s[1] == '{') {895+ ++s;896+ continue;897+ }898+899+ if (s[1] == '#') {900+ t = s+3;901+ if (isxdigit(s[2]))902+ if (isdigit(s[2]))903+ SetConsoleTextAttribute(handle, s[2] - '0');904+ else905+ SetConsoleTextAttribute(handle, tolower(s[2]) - 'a' + 10);906+ else {907+ SetConsoleTextAttribute(handle, 0x0f);908+ t=s+2;909+ }910+ } else if (s[1] == '!') {911+ SetConsoleTextAttribute(handle, 0x0c);912+ t = s+2;913+ } else if (s[1] == '@') {914+ SetConsoleTextAttribute(handle, 0x09);915+ t = s+2;916+ } else if (s[1] == '$') {917+ SetConsoleTextAttribute(handle, 0x0a);918+ t = s+2;919+ } else {920+ SetConsoleTextAttribute(handle, 0x08); // 0,7,8,15 => shades of grey921+ t = s+1;922+ }923+924+ lpad = (int) (t-s);925+ s = t;926+ while (*s && *s != '}') ++s;927+ if (!*s) break;928+ stb__print_one(handle, t, s-t);929+ if (s[1] == '}') {930+ t = s+2;931+ } else {932+ pad += 1+lpad;933+ t = s+1;934+ }935+ s=t;936+ SetConsoleTextAttribute(handle, 0x07);937+ }938+ stb__print_one(handle, t, s-t);939+ SetConsoleTextAttribute(handle, 0x07);940+}941+942+void stbprint(const char *fmt, ...)943+{944+ int res;945+ char buffer[1024];946+ char *tbuf = buffer;947+ va_list v;948+949+ va_start(v,fmt);950+ res = stb_vsnprintf(buffer, sizeof(buffer), fmt, v);951+ va_end(v);952+953+ if (res < 0) {954+ tbuf = (char *) malloc(16384);955+ va_start(v,fmt);956+ res = stb_vsnprintf(tbuf,16384, fmt, v);957+ va_end(v);958+ tbuf[16383] = 0;959+ }960+961+ stb__print(tbuf);962+963+ if (tbuf != buffer)964+ free(tbuf);965+}966+967+#else // _WIN32968+void stbprint(const char *fmt, ...)969+{970+ va_list v;971+ va_start(v,fmt);972+ vprintf(fmt,v);973+ va_end(v);974+}975+#endif // _WIN32976+#endif // STB_DEFINE977+978+979+980+//////////////////////////////////////////////////////////////////////////////981+//982+// Windows UTF8 filename handling983+//984+// Windows stupidly treats 8-bit filenames as some dopey code page,985+// rather than utf-8. If we want to use utf8 filenames, we have to986+// convert them to WCHAR explicitly and call WCHAR versions of the987+// file functions. So, ok, we do.988+989+990+#ifdef _WIN32991+ #define stb__fopen(x,y) stb_p_wfopen((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y))992+ #define stb__windows(x,y) x993+#else994+ #define stb__fopen(x,y) stb_p_fopen(x,y)995+ #define stb__windows(x,y) y996+#endif997+998+999+typedef unsigned short stb__wchar;1000+1001+STB_EXTERN stb__wchar * stb_from_utf8(stb__wchar *buffer, const char *str, int n);1002+STB_EXTERN char * stb_to_utf8 (char *buffer, const stb__wchar *str, int n);1003+1004+STB_EXTERN stb__wchar *stb__from_utf8(const char *str);1005+STB_EXTERN stb__wchar *stb__from_utf8_alt(const char *str);1006+STB_EXTERN char *stb__to_utf8(const stb__wchar *str);1007+1008+1009+#ifdef STB_DEFINE1010+stb__wchar * stb_from_utf8(stb__wchar *buffer, const char *ostr, int n)1011+{1012+ unsigned char *str = (unsigned char *) ostr;1013+ stb_uint32 c;1014+ int i=0;1015+ --n;1016+ while (*str) {1017+ if (i >= n)1018+ return NULL;1019+ if (!(*str & 0x80))1020+ buffer[i++] = *str++;1021+ else if ((*str & 0xe0) == 0xc0) {1022+ if (*str < 0xc2) return NULL;1023+ c = (*str++ & 0x1f) << 6;1024+ if ((*str & 0xc0) != 0x80) return NULL;1025+ buffer[i++] = c + (*str++ & 0x3f);1026+ } else if ((*str & 0xf0) == 0xe0) {1027+ if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return NULL;1028+ if (*str == 0xed && str[1] > 0x9f) return NULL; // str[1] < 0x80 is checked below1029+ c = (*str++ & 0x0f) << 12;1030+ if ((*str & 0xc0) != 0x80) return NULL;1031+ c += (*str++ & 0x3f) << 6;1032+ if ((*str & 0xc0) != 0x80) return NULL;1033+ buffer[i++] = c + (*str++ & 0x3f);1034+ } else if ((*str & 0xf8) == 0xf0) {1035+ if (*str > 0xf4) return NULL;1036+ if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return NULL;1037+ if (*str == 0xf4 && str[1] > 0x8f) return NULL; // str[1] < 0x80 is checked below1038+ c = (*str++ & 0x07) << 18;1039+ if ((*str & 0xc0) != 0x80) return NULL;1040+ c += (*str++ & 0x3f) << 12;1041+ if ((*str & 0xc0) != 0x80) return NULL;1042+ c += (*str++ & 0x3f) << 6;1043+ if ((*str & 0xc0) != 0x80) return NULL;1044+ c += (*str++ & 0x3f);1045+ // utf-8 encodings of values used in surrogate pairs are invalid1046+ if ((c & 0xFFFFF800) == 0xD800) return NULL;1047+ if (c >= 0x10000) {1048+ c -= 0x10000;1049+ if (i + 2 > n) return NULL;1050+ buffer[i++] = 0xD800 | (0x3ff & (c >> 10));1051+ buffer[i++] = 0xDC00 | (0x3ff & (c ));1052+ }1053+ } else1054+ return NULL;1055+ }1056+ buffer[i] = 0;1057+ return buffer;1058+}1059+1060+char * stb_to_utf8(char *buffer, const stb__wchar *str, int n)1061+{1062+ int i=0;1063+ --n;1064+ while (*str) {1065+ if (*str < 0x80) {1066+ if (i+1 > n) return NULL;1067+ buffer[i++] = (char) *str++;1068+ } else if (*str < 0x800) {1069+ if (i+2 > n) return NULL;1070+ buffer[i++] = 0xc0 + (*str >> 6);1071+ buffer[i++] = 0x80 + (*str & 0x3f);1072+ str += 1;1073+ } else if (*str >= 0xd800 && *str < 0xdc00) {1074+ stb_uint32 c;1075+ if (i+4 > n) return NULL;1076+ c = ((str[0] - 0xd800) << 10) + ((str[1]) - 0xdc00) + 0x10000;1077+ buffer[i++] = 0xf0 + (c >> 18);1078+ buffer[i++] = 0x80 + ((c >> 12) & 0x3f);1079+ buffer[i++] = 0x80 + ((c >> 6) & 0x3f);1080+ buffer[i++] = 0x80 + ((c ) & 0x3f);1081+ str += 2;1082+ } else if (*str >= 0xdc00 && *str < 0xe000) {1083+ return NULL;1084+ } else {1085+ if (i+3 > n) return NULL;1086+ buffer[i++] = 0xe0 + (*str >> 12);1087+ buffer[i++] = 0x80 + ((*str >> 6) & 0x3f);1088+ buffer[i++] = 0x80 + ((*str ) & 0x3f);1089+ str += 1;1090+ }1091+ }1092+ buffer[i] = 0;1093+ return buffer;1094+}1095+1096+stb__wchar *stb__from_utf8(const char *str)1097+{1098+ static stb__wchar buffer[4096];1099+ return stb_from_utf8(buffer, str, 4096);1100+}1101+1102+stb__wchar *stb__from_utf8_alt(const char *str)1103+{1104+ static stb__wchar buffer[4096];1105+ return stb_from_utf8(buffer, str, 4096);1106+}1107+1108+char *stb__to_utf8(const stb__wchar *str)1109+{1110+ static char buffer[4096];1111+ return stb_to_utf8(buffer, str, 4096);1112+}1113+1114+#endif1115+1116+//////////////////////////////////////////////////////////////////////////////1117+//1118+// Miscellany1119+//1120+1121+STB_EXTERN void stb_fatal(const char *fmt, ...);1122+STB_EXTERN void stb_(char *fmt, ...);1123+STB_EXTERN void stb_append_to_file(char *file, char *fmt, ...);1124+STB_EXTERN void stb_log(int active);1125+STB_EXTERN void stb_log_fileline(int active);1126+STB_EXTERN void stb_log_name(char *filename);1127+1128+STB_EXTERN void stb_swap(void *p, void *q, size_t sz);1129+STB_EXTERN void *stb_copy(void *p, size_t sz);1130+STB_EXTERN void stb_pointer_array_free(void *p, int len);1131+STB_EXTERN void **stb_array_block_alloc(int count, int blocksize);1132+1133+#define stb_arrcount(x) (sizeof(x)/sizeof((x)[0]))1134+1135+1136+STB_EXTERN int stb__record_fileline(const char *f, int n);1137+1138+#ifdef STB_DEFINE1139+1140+static char *stb__file;1141+static int stb__line;1142+1143+int stb__record_fileline(const char *f, int n)1144+{1145+ stb__file = (char*) f;1146+ stb__line = n;1147+ return 0;1148+}1149+1150+void stb_fatal(const char *s, ...)1151+{1152+ va_list a;1153+ if (stb__file)1154+ fprintf(stderr, "[%s:%d] ", stb__file, stb__line);1155+ va_start(a,s);1156+ fputs("Fatal error: ", stderr);1157+ vfprintf(stderr, s, a);1158+ va_end(a);1159+ fputs("\n", stderr);1160+ #ifdef STB_DEBUG1161+ #ifdef _MSC_VER1162+ #ifndef STB_PTR641163+ __asm int 3; // trap to debugger!1164+ #else1165+ __debugbreak();1166+ #endif1167+ #else1168+ __builtin_trap();1169+ #endif1170+ #endif1171+ exit(1);1172+}1173+1174+static int stb__log_active=1, stb__log_fileline=1;1175+1176+void stb_log(int active)1177+{1178+ stb__log_active = active;1179+}1180+1181+void stb_log_fileline(int active)1182+{1183+ stb__log_fileline = active;1184+}1185+1186+#ifdef STB_NO_STB_STRINGS1187+const char *stb__log_filename = "temp.log";1188+#else1189+const char *stb__log_filename = "stb.log";1190+#endif1191+1192+void stb_log_name(char *s)1193+{1194+ stb__log_filename = s;1195+}1196+1197+void stb_(char *s, ...)1198+{1199+ if (stb__log_active) {1200+ FILE *f = stb_p_fopen(stb__log_filename, "a");1201+ if (f) {1202+ va_list a;1203+ if (stb__log_fileline && stb__file)1204+ fprintf(f, "[%s:%4d] ", stb__file, stb__line);1205+ va_start(a,s);1206+ vfprintf(f, s, a);1207+ va_end(a);1208+ fputs("\n", f);1209+ fclose(f);1210+ }1211+ }1212+}1213+1214+void stb_append_to_file(char *filename, char *s, ...)1215+{1216+ FILE *f = stb_p_fopen(filename, "a");1217+ if (f) {1218+ va_list a;1219+ va_start(a,s);1220+ vfprintf(f, s, a);1221+ va_end(a);1222+ fputs("\n", f);1223+ fclose(f);1224+ }1225+}1226+1227+1228+typedef struct { char d[4]; } stb__4;1229+typedef struct { char d[8]; } stb__8;1230+1231+// optimize the small cases, though you shouldn't be calling this for those!1232+void stb_swap(void *p, void *q, size_t sz)1233+{1234+ char buffer[256];1235+ if (p == q) return;1236+ if (sz == 4) {1237+ stb__4 temp = * ( stb__4 *) p;1238+ * (stb__4 *) p = * ( stb__4 *) q;1239+ * (stb__4 *) q = temp;1240+ return;1241+ } else if (sz == 8) {1242+ stb__8 temp = * ( stb__8 *) p;1243+ * (stb__8 *) p = * ( stb__8 *) q;1244+ * (stb__8 *) q = temp;1245+ return;1246+ }1247+1248+ while (sz > sizeof(buffer)) {1249+ stb_swap(p, q, sizeof(buffer));1250+ p = (char *) p + sizeof(buffer);1251+ q = (char *) q + sizeof(buffer);1252+ sz -= sizeof(buffer);1253+ }1254+1255+ memcpy(buffer, p , sz);1256+ memcpy(p , q , sz);1257+ memcpy(q , buffer, sz);1258+}1259+1260+void *stb_copy(void *p, size_t sz)1261+{1262+ void *q = malloc(sz);1263+ memcpy(q, p, sz);1264+ return q;1265+}1266+1267+void stb_pointer_array_free(void *q, int len)1268+{1269+ void **p = (void **) q;1270+ int i;1271+ for (i=0; i < len; ++i)1272+ free(p[i]);1273+}1274+1275+void **stb_array_block_alloc(int count, int blocksize)1276+{1277+ int i;1278+ char *p = (char *) malloc(sizeof(void *) * count + count * blocksize);1279+ void **q;1280+ if (p == NULL) return NULL;1281+ q = (void **) p;1282+ p += sizeof(void *) * count;1283+ for (i=0; i < count; ++i)1284+ q[i] = p + i * blocksize;1285+ return q;1286+}1287+#endif1288+1289+#ifdef STB_DEBUG1290+ // tricky hack to allow recording FILE,LINE even in varargs functions1291+ #define STB__RECORD_FILE(x) (stb__record_fileline(__FILE__, __LINE__),(x))1292+ #define stb_log STB__RECORD_FILE(stb_log)1293+ #define stb_ STB__RECORD_FILE(stb_)1294+ #ifndef STB_FATAL_CLEAN1295+ #define stb_fatal STB__RECORD_FILE(stb_fatal)1296+ #endif1297+ #define STB__DEBUG(x) x1298+#else1299+ #define STB__DEBUG(x)1300+#endif1301+1302+//////////////////////////////////////////////////////////////////////////////1303+//1304+// stb_temp1305+//1306+1307+#define stb_temp(block, sz) stb__temp(block, sizeof(block), (sz))1308+1309+STB_EXTERN void * stb__temp(void *b, int b_sz, int want_sz);1310+STB_EXTERN void stb_tempfree(void *block, void *ptr);1311+1312+#ifdef STB_DEFINE1313+1314+void * stb__temp(void *b, int b_sz, int want_sz)1315+{1316+ if (b_sz >= want_sz)1317+ return b;1318+ else1319+ return malloc(want_sz);1320+}1321+1322+void stb_tempfree(void *b, void *p)1323+{1324+ if (p != b)1325+ free(p);1326+}1327+#endif1328+1329+1330+//////////////////////////////////////////////////////////////////////////////1331+//1332+// math/sampling operations1333+//1334+1335+1336+#define stb_lerp(t,a,b) ( (a) + (t) * (float) ((b)-(a)) )1337+#define stb_unlerp(t,a,b) ( ((t) - (a)) / (float) ((b) - (a)) )1338+1339+#define stb_clamp(x,xmin,xmax) ((x) < (xmin) ? (xmin) : (x) > (xmax) ? (xmax) : (x))1340+1341+STB_EXTERN void stb_newell_normal(float *normal, int num_vert, float **vert, int normalize);1342+STB_EXTERN int stb_box_face_vertex_axis_side(int face_number, int vertex_number, int axis);1343+STB_EXTERN void stb_linear_controller(float *curpos, float target_pos, float acc, float deacc, float dt);1344+1345+STB_EXTERN int stb_float_eq(float x, float y, float delta, int max_ulps);1346+STB_EXTERN int stb_is_prime(unsigned int m);1347+STB_EXTERN unsigned int stb_power_of_two_nearest_prime(int n);1348+1349+STB_EXTERN float stb_smoothstep(float t);1350+STB_EXTERN float stb_cubic_bezier_1d(float t, float p0, float p1, float p2, float p3);1351+1352+STB_EXTERN double stb_linear_remap(double x, double a, double b,1353+ double c, double d);1354+1355+#ifdef STB_DEFINE1356+float stb_smoothstep(float t)1357+{1358+ return (3 - 2*t)*(t*t);1359+}1360+1361+float stb_cubic_bezier_1d(float t, float p0, float p1, float p2, float p3)1362+{1363+ float it = 1-t;1364+ return it*it*it*p0 + 3*it*it*t*p1 + 3*it*t*t*p2 + t*t*t*p3;1365+}1366+1367+void stb_newell_normal(float *normal, int num_vert, float **vert, int normalize)1368+{1369+ int i,j;1370+ float p;1371+ normal[0] = normal[1] = normal[2] = 0;1372+ for (i=num_vert-1,j=0; j < num_vert; i=j++) {1373+ float *u = vert[i];1374+ float *v = vert[j];1375+ normal[0] += (u[1] - v[1]) * (u[2] + v[2]);1376+ normal[1] += (u[2] - v[2]) * (u[0] + v[0]);1377+ normal[2] += (u[0] - v[0]) * (u[1] + v[1]);1378+ }1379+ if (normalize) {1380+ p = normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2];1381+ p = (float) (1.0 / sqrt(p));1382+ normal[0] *= p;1383+ normal[1] *= p;1384+ normal[2] *= p;1385+ }1386+}1387+1388+int stb_box_face_vertex_axis_side(int face_number, int vertex_number, int axis)1389+{1390+ static int box_vertices[6][4][3] =1391+ {1392+ { { 1,1,1 }, { 1,0,1 }, { 1,0,0 }, { 1,1,0 } },1393+ { { 0,0,0 }, { 0,0,1 }, { 0,1,1 }, { 0,1,0 } },1394+ { { 0,0,0 }, { 0,1,0 }, { 1,1,0 }, { 1,0,0 } },1395+ { { 0,0,0 }, { 1,0,0 }, { 1,0,1 }, { 0,0,1 } },1396+ { { 1,1,1 }, { 0,1,1 }, { 0,0,1 }, { 1,0,1 } },1397+ { { 1,1,1 }, { 1,1,0 }, { 0,1,0 }, { 0,1,1 } },1398+ };1399+ assert(face_number >= 0 && face_number < 6);1400+ assert(vertex_number >= 0 && vertex_number < 4);1401+ assert(axis >= 0 && axis < 3);1402+ return box_vertices[face_number][vertex_number][axis];1403+}1404+1405+void stb_linear_controller(float *curpos, float target_pos, float acc, float deacc, float dt)1406+{1407+ float sign = 1, p, cp = *curpos;1408+ if (cp == target_pos) return;1409+ if (target_pos < cp) {1410+ target_pos = -target_pos;1411+ cp = -cp;1412+ sign = -1;1413+ }1414+ // first decelerate1415+ if (cp < 0) {1416+ p = cp + deacc * dt;1417+ if (p > 0) {1418+ p = 0;1419+ dt = dt - cp / deacc;1420+ if (dt < 0) dt = 0;1421+ } else {1422+ dt = 0;1423+ }1424+ cp = p;1425+ }1426+ // now accelerate1427+ p = cp + acc*dt;1428+ if (p > target_pos) p = target_pos;1429+ *curpos = p * sign;1430+ // @TODO: testing1431+}1432+1433+float stb_quadratic_controller(float target_pos, float curpos, float maxvel, float maxacc, float dt, float *curvel)1434+{1435+ return 0; // @TODO1436+}1437+1438+int stb_float_eq(float x, float y, float delta, int max_ulps)1439+{1440+ if (fabs(x-y) <= delta) return 1;1441+ if (abs(*(int *)&x - *(int *)&y) <= max_ulps) return 1;1442+ return 0;1443+}1444+1445+int stb_is_prime(unsigned int m)1446+{1447+ unsigned int i,j;1448+ if (m < 2) return 0;1449+ if (m == 2) return 1;1450+ if (!(m & 1)) return 0;1451+ if (m % 3 == 0) return (m == 3);1452+ for (i=5; (j=i*i), j <= m && j > i; i += 6) {1453+ if (m % i == 0) return 0;1454+ if (m % (i+2) == 0) return 0;1455+ }1456+ return 1;1457+}1458+1459+unsigned int stb_power_of_two_nearest_prime(int n)1460+{1461+ static signed char tab[32] = { 0,0,0,0,1,0,-1,0,1,-1,-1,3,-1,0,-1,2,1,1462+ 0,2,0,-1,-4,-1,5,-1,18,-2,15,2,-1,2,0 };1463+ if (!tab[0]) {1464+ int i;1465+ for (i=0; i < 32; ++i)1466+ tab[i] = (1 << i) + 2*tab[i] - 1;1467+ tab[1] = 2;1468+ tab[0] = 1;1469+ }1470+ if (n >= 32) return 0xfffffffb;1471+ return tab[n];1472+}1473+1474+double stb_linear_remap(double x, double x_min, double x_max,1475+ double out_min, double out_max)1476+{1477+ return stb_lerp(stb_unlerp(x,x_min,x_max),out_min,out_max);1478+}1479+#endif1480+1481+// create a macro so it's faster, but you can get at the function pointer1482+#define stb_linear_remap(t,a,b,c,d) stb_lerp(stb_unlerp(t,a,b),c,d)1483+1484+1485+//////////////////////////////////////////////////////////////////////////////1486+//1487+// bit operations1488+//1489+1490+#define stb_big32(c) (((c)[0]<<24) + (c)[1]*65536 + (c)[2]*256 + (c)[3])1491+#define stb_little32(c) (((c)[3]<<24) + (c)[2]*65536 + (c)[1]*256 + (c)[0])1492+#define stb_big16(c) ((c)[0]*256 + (c)[1])1493+#define stb_little16(c) ((c)[1]*256 + (c)[0])1494+1495+STB_EXTERN int stb_bitcount(unsigned int a);1496+STB_EXTERN unsigned int stb_bitreverse8(unsigned char n);1497+STB_EXTERN unsigned int stb_bitreverse(unsigned int n);1498+1499+STB_EXTERN int stb_is_pow2(size_t);1500+STB_EXTERN int stb_log2_ceil(size_t);1501+STB_EXTERN int stb_log2_floor(size_t);1502+1503+STB_EXTERN int stb_lowbit8(unsigned int n);1504+STB_EXTERN int stb_highbit8(unsigned int n);1505+1506+#ifdef STB_DEFINE1507+int stb_bitcount(unsigned int a)1508+{1509+ a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 21510+ a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 41511+ a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits1512+ a = (a + (a >> 8)); // max 16 per 8 bits1513+ a = (a + (a >> 16)); // max 32 per 8 bits1514+ return a & 0xff;1515+}1516+1517+unsigned int stb_bitreverse8(unsigned char n)1518+{1519+ n = ((n & 0xAA) >> 1) + ((n & 0x55) << 1);1520+ n = ((n & 0xCC) >> 2) + ((n & 0x33) << 2);1521+ return (unsigned char) ((n >> 4) + (n << 4));1522+}1523+1524+unsigned int stb_bitreverse(unsigned int n)1525+{1526+ n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);1527+ n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);1528+ n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);1529+ n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);1530+ return (n >> 16) | (n << 16);1531+}1532+1533+int stb_is_pow2(size_t n)1534+{1535+ return (n & (n-1)) == 0;1536+}1537+1538+// tricky use of 4-bit table to identify 5 bit positions (note the '-1')1539+// 3-bit table would require another tree level; 5-bit table wouldn't save one1540+#if defined(_WIN32) && !defined(__MINGW32__)1541+#pragma warning(push)1542+#pragma warning(disable: 4035) // disable warning about no return value1543+int stb_log2_floor(size_t n)1544+{1545+ #if _MSC_VER > 17001546+ unsigned long i;1547+ #ifdef STB_PTR641548+ _BitScanReverse64(&i, n);1549+ #else1550+ _BitScanReverse(&i, n);1551+ #endif1552+ return i != 0 ? i : -1;1553+ #else1554+ __asm {1555+ bsr eax,n1556+ jnz done1557+ mov eax,-11558+ }1559+ done:;1560+ #endif1561+}1562+#pragma warning(pop)1563+#else1564+int stb_log2_floor(size_t n)1565+{1566+ static signed char log2_4[16] = { -1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3 };1567+1568+#ifdef STB_PTR641569+ if (n >= ((size_t) 1u << 32))1570+ return stb_log2_floor(n >> 32);1571+#endif1572+1573+ // 2 compares if n < 16, 3 compares otherwise1574+ if (n < (1U << 14))1575+ if (n < (1U << 4)) return 0 + log2_4[n ];1576+ else if (n < (1U << 9)) return 5 + log2_4[n >> 5];1577+ else return 10 + log2_4[n >> 10];1578+ else if (n < (1U << 24))1579+ if (n < (1U << 19)) return 15 + log2_4[n >> 15];1580+ else return 20 + log2_4[n >> 20];1581+ else if (n < (1U << 29)) return 25 + log2_4[n >> 25];1582+ else return 30 + log2_4[n >> 30];1583+}1584+#endif1585+1586+// define ceil from floor1587+int stb_log2_ceil(size_t n)1588+{1589+ if (stb_is_pow2(n)) return stb_log2_floor(n);1590+ else return 1 + stb_log2_floor(n);1591+}1592+1593+int stb_highbit8(unsigned int n)1594+{1595+ return stb_log2_ceil(n&255);1596+}1597+1598+int stb_lowbit8(unsigned int n)1599+{1600+ static signed char lowbit4[16] = { -1,0,1,0, 2,0,1,0, 3,0,1,0, 2,0,1,0 };1601+ int k = lowbit4[n & 15];1602+ if (k >= 0) return k;1603+ k = lowbit4[(n >> 4) & 15];1604+ if (k >= 0) return k+4;1605+ return k;1606+}1607+#endif1608+1609+1610+1611+//////////////////////////////////////////////////////////////////////////////1612+//1613+// qsort Compare Routines1614+//1615+1616+#ifdef _WIN321617+ #define stb_stricmp(a,b) stb_p_stricmp(a,b)1618+ #define stb_strnicmp(a,b,n) stb_p_strnicmp(a,b,n)1619+#else1620+ #define stb_stricmp(a,b) strcasecmp(a,b)1621+ #define stb_strnicmp(a,b,n) strncasecmp(a,b,n)1622+#endif1623+1624+1625+STB_EXTERN int (*stb_intcmp(int offset))(const void *a, const void *b);1626+STB_EXTERN int (*stb_intcmprev(int offset))(const void *a, const void *b);1627+STB_EXTERN int (*stb_qsort_strcmp(int offset))(const void *a, const void *b);1628+STB_EXTERN int (*stb_qsort_stricmp(int offset))(const void *a, const void *b);1629+STB_EXTERN int (*stb_floatcmp(int offset))(const void *a, const void *b);1630+STB_EXTERN int (*stb_doublecmp(int offset))(const void *a, const void *b);1631+STB_EXTERN int (*stb_charcmp(int offset))(const void *a, const void *b);1632+1633+#ifdef STB_DEFINE1634+static int stb__intcmpoffset, stb__ucharcmpoffset, stb__strcmpoffset;1635+static int stb__floatcmpoffset, stb__doublecmpoffset;1636+static int stb__memcmpoffset, stb__memcmpsize;1637+1638+int stb__intcmp(const void *a, const void *b)1639+{1640+ const int p = *(const int *) ((const char *) a + stb__intcmpoffset);1641+ const int q = *(const int *) ((const char *) b + stb__intcmpoffset);1642+ return p < q ? -1 : p > q;1643+}1644+1645+int stb__intcmprev(const void *a, const void *b)1646+{1647+ const int p = *(const int *) ((const char *) a + stb__intcmpoffset);1648+ const int q = *(const int *) ((const char *) b + stb__intcmpoffset);1649+ return q < p ? -1 : q > p;1650+}1651+1652+int stb__ucharcmp(const void *a, const void *b)1653+{1654+ const int p = *(const unsigned char *) ((const char *) a + stb__ucharcmpoffset);1655+ const int q = *(const unsigned char *) ((const char *) b + stb__ucharcmpoffset);1656+ return p < q ? -1 : p > q;1657+}1658+1659+int stb__floatcmp(const void *a, const void *b)1660+{1661+ const float p = *(const float *) ((const char *) a + stb__floatcmpoffset);1662+ const float q = *(const float *) ((const char *) b + stb__floatcmpoffset);1663+ return p < q ? -1 : p > q;1664+}1665+1666+int stb__doublecmp(const void *a, const void *b)1667+{1668+ const double p = *(const double *) ((const char *) a + stb__doublecmpoffset);1669+ const double q = *(const double *) ((const char *) b + stb__doublecmpoffset);1670+ return p < q ? -1 : p > q;1671+}1672+1673+int stb__qsort_strcmp(const void *a, const void *b)1674+{1675+ const char *p = *(const char **) ((const char *) a + stb__strcmpoffset);1676+ const char *q = *(const char **) ((const char *) b + stb__strcmpoffset);1677+ return strcmp(p,q);1678+}1679+1680+int stb__qsort_stricmp(const void *a, const void *b)1681+{1682+ const char *p = *(const char **) ((const char *) a + stb__strcmpoffset);1683+ const char *q = *(const char **) ((const char *) b + stb__strcmpoffset);1684+ return stb_stricmp(p,q);1685+}1686+1687+int stb__memcmp(const void *a, const void *b)1688+{1689+ return memcmp((char *) a + stb__memcmpoffset, (char *) b + stb__memcmpoffset, stb__memcmpsize);1690+}1691+1692+int (*stb_intcmp(int offset))(const void *, const void *)1693+{1694+ stb__intcmpoffset = offset;1695+ return &stb__intcmp;1696+}1697+1698+int (*stb_intcmprev(int offset))(const void *, const void *)1699+{1700+ stb__intcmpoffset = offset;1701+ return &stb__intcmprev;1702+}1703+1704+int (*stb_ucharcmp(int offset))(const void *, const void *)1705+{1706+ stb__ucharcmpoffset = offset;1707+ return &stb__ucharcmp;1708+}1709+1710+int (*stb_qsort_strcmp(int offset))(const void *, const void *)1711+{1712+ stb__strcmpoffset = offset;1713+ return &stb__qsort_strcmp;1714+}1715+1716+int (*stb_qsort_stricmp(int offset))(const void *, const void *)1717+{1718+ stb__strcmpoffset = offset;1719+ return &stb__qsort_stricmp;1720+}1721+1722+int (*stb_floatcmp(int offset))(const void *, const void *)1723+{1724+ stb__floatcmpoffset = offset;1725+ return &stb__floatcmp;1726+}1727+1728+int (*stb_doublecmp(int offset))(const void *, const void *)1729+{1730+ stb__doublecmpoffset = offset;1731+ return &stb__doublecmp;1732+}1733+1734+int (*stb_memcmp(int offset, int size))(const void *, const void *)1735+{1736+ stb__memcmpoffset = offset;1737+ stb__memcmpsize = size;1738+ return &stb__memcmp;1739+}1740+#endif1741+1742+//////////////////////////////////////////////////////////////////////////////1743+//1744+// Binary Search Toolkit1745+//1746+1747+typedef struct1748+{1749+ int minval, maxval, guess;1750+ int mode, step;1751+} stb_search;1752+1753+STB_EXTERN int stb_search_binary(stb_search *s, int minv, int maxv, int find_smallest);1754+STB_EXTERN int stb_search_open(stb_search *s, int minv, int find_smallest);1755+STB_EXTERN int stb_probe(stb_search *s, int compare, int *result); // return 0 when done1756+1757+#ifdef STB_DEFINE1758+enum1759+{1760+ STB_probe_binary_smallest,1761+ STB_probe_binary_largest,1762+ STB_probe_open_smallest,1763+ STB_probe_open_largest,1764+};1765+1766+static int stb_probe_guess(stb_search *s, int *result)1767+{1768+ switch(s->mode) {1769+ case STB_probe_binary_largest:1770+ if (s->minval == s->maxval) {1771+ *result = s->minval;1772+ return 0;1773+ }1774+ assert(s->minval < s->maxval);1775+ // if a < b, then a < p <= b1776+ s->guess = s->minval + (((unsigned) s->maxval - s->minval + 1) >> 1);1777+ break;1778+1779+ case STB_probe_binary_smallest:1780+ if (s->minval == s->maxval) {1781+ *result = s->minval;1782+ return 0;1783+ }1784+ assert(s->minval < s->maxval);1785+ // if a < b, then a <= p < b1786+ s->guess = s->minval + (((unsigned) s->maxval - s->minval) >> 1);1787+ break;1788+ case STB_probe_open_smallest:1789+ case STB_probe_open_largest:1790+ s->guess = s->maxval; // guess the current maxval1791+ break;1792+ }1793+ *result = s->guess;1794+ return 1;1795+}1796+1797+int stb_probe(stb_search *s, int compare, int *result)1798+{1799+ switch(s->mode) {1800+ case STB_probe_open_smallest:1801+ case STB_probe_open_largest: {1802+ if (compare <= 0) {1803+ // then it lies within minval & maxval1804+ if (s->mode == STB_probe_open_smallest)1805+ s->mode = STB_probe_binary_smallest;1806+ else1807+ s->mode = STB_probe_binary_largest;1808+ } else {1809+ // otherwise, we need to probe larger1810+ s->minval = s->maxval + 1;1811+ s->maxval = s->minval + s->step;1812+ s->step += s->step;1813+ }1814+ break;1815+ }1816+ case STB_probe_binary_smallest: {1817+ // if compare < 0, then s->minval <= a < p1818+ // if compare = 0, then s->minval <= a <= p1819+ // if compare > 0, then p < a <= s->maxval1820+ if (compare <= 0)1821+ s->maxval = s->guess;1822+ else1823+ s->minval = s->guess+1;1824+ break;1825+ }1826+ case STB_probe_binary_largest: {1827+ // if compare < 0, then s->minval <= a < p1828+ // if compare = 0, then p <= a <= s->maxval1829+ // if compare > 0, then p < a <= s->maxval1830+ if (compare < 0)1831+ s->maxval = s->guess-1;1832+ else1833+ s->minval = s->guess;1834+ break;1835+ }1836+ }1837+ return stb_probe_guess(s, result);1838+}1839+1840+int stb_search_binary(stb_search *s, int minv, int maxv, int find_smallest)1841+{1842+ int r;1843+ if (maxv < minv) return minv-1;1844+ s->minval = minv;1845+ s->maxval = maxv;1846+ s->mode = find_smallest ? STB_probe_binary_smallest : STB_probe_binary_largest;1847+ stb_probe_guess(s, &r);1848+ return r;1849+}1850+1851+int stb_search_open(stb_search *s, int minv, int find_smallest)1852+{1853+ int r;1854+ s->step = 4;1855+ s->minval = minv;1856+ s->maxval = minv+s->step;1857+ s->mode = find_smallest ? STB_probe_open_smallest : STB_probe_open_largest;1858+ stb_probe_guess(s, &r);1859+ return r;1860+}1861+#endif1862+1863+//////////////////////////////////////////////////////////////////////////////1864+//1865+// String Processing1866+//1867+1868+#define stb_prefixi(s,t) (0==stb_strnicmp((s),(t),strlen(t)))1869+1870+enum stb_splitpath_flag1871+{1872+ STB_PATH = 1,1873+ STB_FILE = 2,1874+ STB_EXT = 4,1875+ STB_PATH_FILE = STB_PATH + STB_FILE,1876+ STB_FILE_EXT = STB_FILE + STB_EXT,1877+ STB_EXT_NO_PERIOD = 8,1878+};1879+1880+STB_EXTERN char * stb_skipwhite(char *s);1881+STB_EXTERN char * stb_trimwhite(char *s);1882+STB_EXTERN char * stb_skipnewline(char *s);1883+STB_EXTERN char * stb_strncpy(char *s, char *t, int n);1884+STB_EXTERN char * stb_substr(char *t, int n);1885+STB_EXTERN char * stb_duplower(char *s);1886+STB_EXTERN void stb_tolower (char *s);1887+STB_EXTERN char * stb_strchr2 (char *s, char p1, char p2);1888+STB_EXTERN char * stb_strrchr2(char *s, char p1, char p2);1889+STB_EXTERN char * stb_strtok(char *output, char *src, char *delimit);1890+STB_EXTERN char * stb_strtok_keep(char *output, char *src, char *delimit);1891+STB_EXTERN char * stb_strtok_invert(char *output, char *src, char *allowed);1892+STB_EXTERN char * stb_dupreplace(char *s, char *find, char *replace);1893+STB_EXTERN void stb_replaceinplace(char *s, char *find, char *replace);1894+STB_EXTERN char * stb_splitpath(char *output, char *src, int flag);1895+STB_EXTERN char * stb_splitpathdup(char *src, int flag);1896+STB_EXTERN char * stb_replacedir(char *output, char *src, char *dir);1897+STB_EXTERN char * stb_replaceext(char *output, char *src, char *ext);1898+STB_EXTERN void stb_fixpath(char *path);1899+STB_EXTERN char * stb_shorten_path_readable(char *path, int max_len);1900+STB_EXTERN int stb_suffix (char *s, char *t);1901+STB_EXTERN int stb_suffixi(char *s, char *t);1902+STB_EXTERN int stb_prefix (char *s, char *t);1903+STB_EXTERN char * stb_strichr(char *s, char t);1904+STB_EXTERN char * stb_stristr(char *s, char *t);1905+STB_EXTERN int stb_prefix_count(char *s, char *t);1906+STB_EXTERN const char * stb_plural(int n); // "s" or ""1907+STB_EXTERN size_t stb_strscpy(char *d, const char *s, size_t n);1908+1909+STB_EXTERN char **stb_tokens(char *src, char *delimit, int *count);1910+STB_EXTERN char **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out);1911+STB_EXTERN char **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out);1912+STB_EXTERN char **stb_tokens_allowempty(char *src, char *delimit, int *count);1913+STB_EXTERN char **stb_tokens_stripwhite(char *src, char *delimit, int *count);1914+STB_EXTERN char **stb_tokens_withdelim(char *src, char *delimit, int *count);1915+STB_EXTERN char **stb_tokens_quoted(char *src, char *delimit, int *count);1916+// with 'quoted', allow delimiters to appear inside quotation marks, and don't1917+// strip whitespace inside them (and we delete the quotation marks unless they1918+// appear back to back, in which case they're considered escaped)1919+1920+#ifdef STB_DEFINE1921+1922+size_t stb_strscpy(char *d, const char *s, size_t n)1923+{1924+ size_t len = strlen(s);1925+ if (len >= n) {1926+ if (n) d[0] = 0;1927+ return 0;1928+ }1929+ stb_p_strcpy_s(d,n,s);1930+ return len;1931+}1932+1933+const char *stb_plural(int n)1934+{1935+ return n == 1 ? "" : "s";1936+}1937+1938+int stb_prefix(char *s, char *t)1939+{1940+ while (*t)1941+ if (*s++ != *t++)1942+ return STB_FALSE;1943+ return STB_TRUE;1944+}1945+1946+int stb_prefix_count(char *s, char *t)1947+{1948+ int c=0;1949+ while (*t) {1950+ if (*s++ != *t++)1951+ break;1952+ ++c;1953+ }1954+ return c;1955+}1956+1957+int stb_suffix(char *s, char *t)1958+{1959+ size_t n = strlen(s);1960+ size_t m = strlen(t);1961+ if (m <= n)1962+ return 0 == strcmp(s+n-m, t);1963+ else1964+ return 0;1965+}1966+1967+int stb_suffixi(char *s, char *t)1968+{1969+ size_t n = strlen(s);1970+ size_t m = strlen(t);1971+ if (m <= n)1972+ return 0 == stb_stricmp(s+n-m, t);1973+ else1974+ return 0;1975+}1976+1977+// originally I was using this table so that I could create known sentinel1978+// values--e.g. change whitetable[0] to be true if I was scanning for whitespace,1979+// and false if I was scanning for nonwhite. I don't appear to be using that1980+// functionality anymore (I do for tokentable, though), so just replace it1981+// with isspace()1982+char *stb_skipwhite(char *s)1983+{1984+ while (isspace((unsigned char) *s)) ++s;1985+ return s;1986+}1987+1988+char *stb_skipnewline(char *s)1989+{1990+ if (s[0] == '\r' || s[0] == '\n') {1991+ if (s[0]+s[1] == '\r' + '\n') ++s;1992+ ++s;1993+ }1994+ return s;1995+}1996+1997+char *stb_trimwhite(char *s)1998+{1999+ int i,n;2000+ s = stb_skipwhite(s);2001+ n = (int) strlen(s);2002+ for (i=n-1; i >= 0; --i)2003+ if (!isspace(s[i]))2004+ break;2005+ s[i+1] = 0;2006+ return s;2007+}2008+2009+char *stb_strncpy(char *s, char *t, int n)2010+{2011+ stb_p_strncpy_s(s,n+1,t,n);2012+ s[n] = 0;2013+ return s;2014+}2015+2016+char *stb_substr(char *t, int n)2017+{2018+ char *a;2019+ int z = (int) strlen(t);2020+ if (z < n) n = z;2021+ a = (char *) malloc(n+1);2022+ stb_p_strncpy_s(a,n+1,t,n);2023+ a[n] = 0;2024+ return a;2025+}2026+2027+char *stb_duplower(char *s)2028+{2029+ char *p = stb_p_strdup(s), *q = p;2030+ while (*q) {2031+ *q = tolower(*q);2032+ ++q;2033+ }2034+ return p;2035+}2036+2037+void stb_tolower(char *s)2038+{2039+ while (*s) {2040+ *s = tolower(*s);2041+ ++s;2042+ }2043+}2044+2045+char *stb_strchr2(char *s, char x, char y)2046+{2047+ for(; *s; ++s)2048+ if (*s == x || *s == y)2049+ return s;2050+ return NULL;2051+}2052+2053+char *stb_strrchr2(char *s, char x, char y)2054+{2055+ char *r = NULL;2056+ for(; *s; ++s)2057+ if (*s == x || *s == y)2058+ r = s;2059+ return r;2060+}2061+2062+char *stb_strichr(char *s, char t)2063+{2064+ if (tolower(t) == toupper(t))2065+ return strchr(s,t);2066+ return stb_strchr2(s, (char) tolower(t), (char) toupper(t));2067+}2068+2069+char *stb_stristr(char *s, char *t)2070+{2071+ size_t n = strlen(t);2072+ char *z;2073+ if (n==0) return s;2074+ while ((z = stb_strichr(s, *t)) != NULL) {2075+ if (0==stb_strnicmp(z, t, n))2076+ return z;2077+ s = z+1;2078+ }2079+ return NULL;2080+}2081+2082+static char *stb_strtok_raw(char *output, char *src, char *delimit, int keep, int invert)2083+{2084+ if (invert) {2085+ while (*src && strchr(delimit, *src) != NULL) {2086+ *output++ = *src++;2087+ }2088+ } else {2089+ while (*src && strchr(delimit, *src) == NULL) {2090+ *output++ = *src++;2091+ }2092+ }2093+ *output = 0;2094+ if (keep)2095+ return src;2096+ else2097+ return *src ? src+1 : src;2098+}2099+2100+char *stb_strtok(char *output, char *src, char *delimit)2101+{2102+ return stb_strtok_raw(output, src, delimit, 0, 0);2103+}2104+2105+char *stb_strtok_keep(char *output, char *src, char *delimit)2106+{2107+ return stb_strtok_raw(output, src, delimit, 1, 0);2108+}2109+2110+char *stb_strtok_invert(char *output, char *src, char *delimit)2111+{2112+ return stb_strtok_raw(output, src, delimit, 1,1);2113+}2114+2115+static char **stb_tokens_raw(char *src_, char *delimit, int *count,2116+ int stripwhite, int allow_empty, char *start, char *end)2117+{2118+ int nested = 0;2119+ unsigned char *src = (unsigned char *) src_;2120+ static char stb_tokentable[256]; // rely on static initializion to 02121+ static char stable[256],etable[256];2122+ char *out;2123+ char **result;2124+ int num=0;2125+ unsigned char *s;2126+2127+ s = (unsigned char *) delimit; while (*s) stb_tokentable[*s++] = 1;2128+ if (start) {2129+ s = (unsigned char *) start; while (*s) stable[*s++] = 1;2130+ s = (unsigned char *) end; if (s) while (*s) stable[*s++] = 1;2131+ s = (unsigned char *) end; if (s) while (*s) etable[*s++] = 1;2132+ }2133+ stable[0] = 1;2134+2135+ // two passes through: the first time, counting how many2136+ s = (unsigned char *) src;2137+ while (*s) {2138+ // state: just found delimiter2139+ // skip further delimiters2140+ if (!allow_empty) {2141+ stb_tokentable[0] = 0;2142+ while (stb_tokentable[*s])2143+ ++s;2144+ if (!*s) break;2145+ }2146+ ++num;2147+ // skip further non-delimiters2148+ stb_tokentable[0] = 1;2149+ if (stripwhite == 2) { // quoted strings2150+ while (!stb_tokentable[*s]) {2151+ if (*s != '"')2152+ ++s;2153+ else {2154+ ++s;2155+ if (*s == '"')2156+ ++s; // "" -> ", not start a string2157+ else {2158+ // begin a string2159+ while (*s) {2160+ if (s[0] == '"') {2161+ if (s[1] == '"') s += 2; // "" -> "2162+ else { ++s; break; } // terminating "2163+ } else2164+ ++s;2165+ }2166+ }2167+ }2168+ }2169+ } else2170+ while (nested || !stb_tokentable[*s]) {2171+ if (stable[*s]) {2172+ if (!*s) break;2173+ if (end ? etable[*s] : nested)2174+ --nested;2175+ else2176+ ++nested;2177+ }2178+ ++s;2179+ }2180+ if (allow_empty) {2181+ if (*s) ++s;2182+ }2183+ }2184+ // now num has the actual count... malloc our output structure2185+ // need space for all the strings: strings won't be any longer than2186+ // original input, since for every '\0' there's at least one delimiter2187+ result = (char **) malloc(sizeof(*result) * (num+1) + (s-src+1));2188+ if (result == NULL) return result;2189+ out = (char *) (result + (num+1));2190+ // second pass: copy out the data2191+ s = (unsigned char *) src;2192+ num = 0;2193+ nested = 0;2194+ while (*s) {2195+ char *last_nonwhite;2196+ // state: just found delimiter2197+ // skip further delimiters2198+ if (!allow_empty) {2199+ stb_tokentable[0] = 0;2200+ if (stripwhite)2201+ while (stb_tokentable[*s] || isspace(*s))2202+ ++s;2203+ else2204+ while (stb_tokentable[*s])2205+ ++s;2206+ } else if (stripwhite) {2207+ while (isspace(*s)) ++s;2208+ }2209+ if (!*s) break;2210+ // we're past any leading delimiters and whitespace2211+ result[num] = out;2212+ ++num;2213+ // copy non-delimiters2214+ stb_tokentable[0] = 1;2215+ last_nonwhite = out-1;2216+ if (stripwhite == 2) {2217+ while (!stb_tokentable[*s]) {2218+ if (*s != '"') {2219+ if (!isspace(*s)) last_nonwhite = out;2220+ *out++ = *s++;2221+ } else {2222+ ++s;2223+ if (*s == '"') {2224+ if (!isspace(*s)) last_nonwhite = out;2225+ *out++ = *s++; // "" -> ", not start string2226+ } else {2227+ // begin a quoted string2228+ while (*s) {2229+ if (s[0] == '"') {2230+ if (s[1] == '"') { *out++ = *s; s += 2; }2231+ else { ++s; break; } // terminating "2232+ } else2233+ *out++ = *s++;2234+ }2235+ last_nonwhite = out-1; // all in quotes counts as non-white2236+ }2237+ }2238+ }2239+ } else {2240+ while (nested || !stb_tokentable[*s]) {2241+ if (!isspace(*s)) last_nonwhite = out;2242+ if (stable[*s]) {2243+ if (!*s) break;2244+ if (end ? etable[*s] : nested)2245+ --nested;2246+ else2247+ ++nested;2248+ }2249+ *out++ = *s++;2250+ }2251+ }2252+2253+ if (stripwhite) // rewind to last non-whitespace char2254+ out = last_nonwhite+1;2255+ *out++ = '\0';2256+2257+ if (*s) ++s; // skip delimiter2258+ }2259+ s = (unsigned char *) delimit; while (*s) stb_tokentable[*s++] = 0;2260+ if (start) {2261+ s = (unsigned char *) start; while (*s) stable[*s++] = 1;2262+ s = (unsigned char *) end; if (s) while (*s) stable[*s++] = 1;2263+ s = (unsigned char *) end; if (s) while (*s) etable[*s++] = 1;2264+ }2265+ if (count != NULL) *count = num;2266+ result[num] = 0;2267+ return result;2268+}2269+2270+char **stb_tokens(char *src, char *delimit, int *count)2271+{2272+ return stb_tokens_raw(src,delimit,count,0,0,0,0);2273+}2274+2275+char **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out)2276+{2277+ return stb_tokens_raw(src,delimit,count,0,0,nest_in,nest_out);2278+}2279+2280+char **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out)2281+{2282+ return stb_tokens_raw(src,delimit,count,0,1,nest_in,nest_out);2283+}2284+2285+char **stb_tokens_allowempty(char *src, char *delimit, int *count)2286+{2287+ return stb_tokens_raw(src,delimit,count,0,1,0,0);2288+}2289+2290+char **stb_tokens_stripwhite(char *src, char *delimit, int *count)2291+{2292+ return stb_tokens_raw(src,delimit,count,1,1,0,0);2293+}2294+2295+char **stb_tokens_quoted(char *src, char *delimit, int *count)2296+{2297+ return stb_tokens_raw(src,delimit,count,2,1,0,0);2298+}2299+2300+char *stb_dupreplace(char *src, char *find, char *replace)2301+{2302+ size_t len_find = strlen(find);2303+ size_t len_replace = strlen(replace);2304+ int count = 0;2305+2306+ char *s,*p,*q;2307+2308+ s = strstr(src, find);2309+ if (s == NULL) return stb_p_strdup(src);2310+ do {2311+ ++count;2312+ s = strstr(s + len_find, find);2313+ } while (s != NULL);2314+2315+ p = (char *) malloc(strlen(src) + count * (len_replace - len_find) + 1);2316+ if (p == NULL) return p;2317+ q = p;2318+ s = src;2319+ for (;;) {2320+ char *t = strstr(s, find);2321+ if (t == NULL) {2322+ stb_p_strcpy_s(q,strlen(src)+count*(len_replace-len_find)+1,s);2323+ assert(strlen(p) == strlen(src) + count*(len_replace-len_find));2324+ return p;2325+ }2326+ memcpy(q, s, t-s);2327+ q += t-s;2328+ memcpy(q, replace, len_replace);2329+ q += len_replace;2330+ s = t + len_find;2331+ }2332+}2333+2334+void stb_replaceinplace(char *src, char *find, char *replace)2335+{2336+ size_t len_find = strlen(find);2337+ size_t len_replace = strlen(replace);2338+ int delta;2339+2340+ char *s,*p,*q;2341+2342+ delta = (int) (len_replace - len_find);2343+ assert(delta <= 0);2344+ if (delta > 0) return;2345+2346+ p = strstr(src, find);2347+ if (p == NULL) return;2348+2349+ s = q = p;2350+ while (*s) {2351+ memcpy(q, replace, len_replace);2352+ p += len_find;2353+ q += len_replace;2354+ s = strstr(p, find);2355+ if (s == NULL) s = p + strlen(p);2356+ memmove(q, p, s-p);2357+ q += s-p;2358+ p = s;2359+ }2360+ *q = 0;2361+}2362+2363+void stb_fixpath(char *path)2364+{2365+ for(; *path; ++path)2366+ if (*path == '\\')2367+ *path = '/';2368+}2369+2370+void stb__add_section(char *buffer, char *data, ptrdiff_t curlen, ptrdiff_t newlen)2371+{2372+ if (newlen < curlen) {2373+ ptrdiff_t z1 = newlen >> 1, z2 = newlen-z1;2374+ memcpy(buffer, data, z1-1);2375+ buffer[z1-1] = '.';2376+ buffer[z1-0] = '.';2377+ memcpy(buffer+z1+1, data+curlen-z2+1, z2-1);2378+ } else2379+ memcpy(buffer, data, curlen);2380+}2381+2382+char * stb_shorten_path_readable(char *path, int len)2383+{2384+ static char buffer[1024];2385+ ptrdiff_t n = strlen(path),n1,n2,r1,r2;2386+ char *s;2387+ if (n <= len) return path;2388+ if (len > 1024) return path;2389+ s = stb_strrchr2(path, '/', '\\');2390+ if (s) {2391+ n1 = s - path + 1;2392+ n2 = n - n1;2393+ ++s;2394+ } else {2395+ n1 = 0;2396+ n2 = n;2397+ s = path;2398+ }2399+ // now we need to reduce r1 and r2 so that they fit in len2400+ if (n1 < len>>1) {2401+ r1 = n1;2402+ r2 = len - r1;2403+ } else if (n2 < len >> 1) {2404+ r2 = n2;2405+ r1 = len - r2;2406+ } else {2407+ r1 = n1 * len / n;2408+ r2 = n2 * len / n;2409+ if (r1 < len>>2) r1 = len>>2, r2 = len-r1;2410+ if (r2 < len>>2) r2 = len>>2, r1 = len-r2;2411+ }2412+ assert(r1 <= n1 && r2 <= n2);2413+ if (n1)2414+ stb__add_section(buffer, path, n1, r1);2415+ stb__add_section(buffer+r1, s, n2, r2);2416+ buffer[len] = 0;2417+ return buffer;2418+}2419+2420+static char *stb__splitpath_raw(char *buffer, char *path, int flag)2421+{2422+ ptrdiff_t len=0,x,y, n = (int) strlen(path), f1,f2;2423+ char *s = stb_strrchr2(path, '/', '\\');2424+ char *t = strrchr(path, '.');2425+ if (s && t && t < s) t = NULL;2426+ if (s) ++s;2427+2428+ if (flag == STB_EXT_NO_PERIOD)2429+ flag |= STB_EXT;2430+2431+ if (!(flag & (STB_PATH | STB_FILE | STB_EXT))) return NULL;2432+2433+ f1 = s == NULL ? 0 : s-path; // start of filename2434+ f2 = t == NULL ? n : t-path; // just past end of filename2435+2436+ if (flag & STB_PATH) {2437+ x = 0; if (f1 == 0 && flag == STB_PATH) len=2;2438+ } else if (flag & STB_FILE) {2439+ x = f1;2440+ } else {2441+ x = f2;2442+ if (flag & STB_EXT_NO_PERIOD)2443+ if (path[x] == '.')2444+ ++x;2445+ }2446+2447+ if (flag & STB_EXT)2448+ y = n;2449+ else if (flag & STB_FILE)2450+ y = f2;2451+ else2452+ y = f1;2453+2454+ if (buffer == NULL) {2455+ buffer = (char *) malloc(y-x + len + 1);2456+ if (!buffer) return NULL;2457+ }2458+2459+ if (len) { stb_p_strcpy_s(buffer, 3, "./"); return buffer; }2460+ stb_strncpy(buffer, path+(int)x, (int)(y-x));2461+ return buffer;2462+}2463+2464+char *stb_splitpath(char *output, char *src, int flag)2465+{2466+ return stb__splitpath_raw(output, src, flag);2467+}2468+2469+char *stb_splitpathdup(char *src, int flag)2470+{2471+ return stb__splitpath_raw(NULL, src, flag);2472+}2473+2474+char *stb_replacedir(char *output, char *src, char *dir)2475+{2476+ char buffer[4096];2477+ stb_splitpath(buffer, src, STB_FILE | STB_EXT);2478+ if (dir)2479+ stb_p_sprintf(output stb_p_size(9999), "%s/%s", dir, buffer);2480+ else2481+ stb_p_strcpy_s(output, sizeof(buffer), buffer); // @UNSAFE2482+ return output;2483+}2484+2485+char *stb_replaceext(char *output, char *src, char *ext)2486+{2487+ char buffer[4096];2488+ stb_splitpath(buffer, src, STB_PATH | STB_FILE);2489+ if (ext)2490+ stb_p_sprintf(output stb_p_size(9999), "%s.%s", buffer, ext[0] == '.' ? ext+1 : ext);2491+ else2492+ stb_p_strcpy_s(output, sizeof(buffer), buffer); // @UNSAFE2493+ return output;2494+}2495+#endif2496+2497+//////////////////////////////////////////////////////////////////////////////2498+//2499+// stb_alloc - hierarchical allocator2500+//2501+// inspired by http://swapped.cc/halloc2502+//2503+//2504+// When you alloc a given block through stb_alloc, you have these choices:2505+//2506+// 1. does it have a parent?2507+// 2. can it have children?2508+// 3. can it be freed directly?2509+// 4. is it transferrable?2510+// 5. what is its alignment?2511+//2512+// Here are interesting combinations of those:2513+//2514+// children free transfer alignment2515+// arena Y Y N n/a2516+// no-overhead, chunked N N N normal2517+// string pool alloc N N N 12518+// parent-ptr, chunked Y N N normal2519+// low-overhead, unchunked N Y Y normal2520+// general purpose alloc Y Y Y normal2521+//2522+// Unchunked allocations will probably return 16-aligned pointers. If2523+// we 16-align the results, we have room for 4 pointers. For smaller2524+// allocations that allow finer alignment, we can reduce the pointers.2525+//2526+// The strategy is that given a pointer, assuming it has a header (only2527+// the no-overhead allocations have no header), we can determine the2528+// type of the header fields, and the number of them, by stepping backwards2529+// through memory and looking at the tags in the bottom bits.2530+//2531+// Implementation strategy:2532+// chunked allocations come from the middle of chunks, and can't2533+// be freed. thefore they do not need to be on a sibling chain.2534+// they may need child pointers if they have children.2535+//2536+// chunked, with-children2537+// void *parent;2538+//2539+// unchunked, no-children -- reduced storage2540+// void *next_sibling;2541+// void *prev_sibling_nextp;2542+//2543+// unchunked, general2544+// void *first_child;2545+// void *next_sibling;2546+// void *prev_sibling_nextp;2547+// void *chunks;2548+//2549+// so, if we code each of these fields with different bit patterns2550+// (actually same one for next/prev/child), then we can identify which2551+// each one is from the last field.2552+2553+STB_EXTERN void stb_free(void *p);2554+STB_EXTERN void *stb_malloc_global(size_t size);2555+STB_EXTERN void *stb_malloc(void *context, size_t size);2556+STB_EXTERN void *stb_malloc_nofree(void *context, size_t size);2557+STB_EXTERN void *stb_malloc_leaf(void *context, size_t size);2558+STB_EXTERN void *stb_malloc_raw(void *context, size_t size);2559+STB_EXTERN void *stb_realloc(void *ptr, size_t newsize);2560+2561+STB_EXTERN void stb_reassign(void *new_context, void *ptr);2562+STB_EXTERN void stb_malloc_validate(void *p, void *parent);2563+2564+extern int stb_alloc_chunk_size ;2565+extern int stb_alloc_count_free ;2566+extern int stb_alloc_count_alloc;2567+extern int stb_alloc_alignment ;2568+2569+#ifdef STB_DEFINE2570+2571+int stb_alloc_chunk_size = 65536;2572+int stb_alloc_count_free = 0;2573+int stb_alloc_count_alloc = 0;2574+int stb_alloc_alignment = -16;2575+2576+typedef struct stb__chunk2577+{2578+ struct stb__chunk *next;2579+ int data_left;2580+ int alloc;2581+} stb__chunk;2582+2583+typedef struct2584+{2585+ void * next;2586+ void ** prevn;2587+} stb__nochildren;2588+2589+typedef struct2590+{2591+ void ** prevn;2592+ void * child;2593+ void * next;2594+ stb__chunk *chunks;2595+} stb__alloc;2596+2597+typedef struct2598+{2599+ stb__alloc *parent;2600+} stb__chunked;2601+2602+#define STB__PARENT 12603+#define STB__CHUNKS 22604+2605+typedef enum2606+{2607+ STB__nochildren = 0,2608+ STB__chunked = STB__PARENT,2609+ STB__alloc = STB__CHUNKS,2610+2611+ STB__chunk_raw = 4,2612+} stb__alloc_type;2613+2614+// these functions set the bottom bits of a pointer efficiently2615+#define STB__DECODE(x,v) ((void *) ((char *) (x) - (v)))2616+#define STB__ENCODE(x,v) ((void *) ((char *) (x) + (v)))2617+2618+#define stb__parent(z) (stb__alloc *) STB__DECODE((z)->parent, STB__PARENT)2619+#define stb__chunks(z) (stb__chunk *) STB__DECODE((z)->chunks, STB__CHUNKS)2620+2621+#define stb__setparent(z,p) (z)->parent = (stb__alloc *) STB__ENCODE((p), STB__PARENT)2622+#define stb__setchunks(z,c) (z)->chunks = (stb__chunk *) STB__ENCODE((c), STB__CHUNKS)2623+2624+static stb__alloc stb__alloc_global =2625+{2626+ NULL,2627+ NULL,2628+ NULL,2629+ (stb__chunk *) STB__ENCODE(NULL, STB__CHUNKS)2630+};2631+2632+static stb__alloc_type stb__identify(void *p)2633+{2634+ void **q = (void **) p;2635+ return (stb__alloc_type) ((stb_uinta) q[-1] & 3);2636+}2637+2638+static void *** stb__prevn(void *p)2639+{2640+ if (stb__identify(p) == STB__alloc) {2641+ stb__alloc *s = (stb__alloc *) p - 1;2642+ return &s->prevn;2643+ } else {2644+ stb__nochildren *s = (stb__nochildren *) p - 1;2645+ return &s->prevn;2646+ }2647+}2648+2649+void stb_free(void *p)2650+{2651+ if (p == NULL) return;2652+2653+ // count frees so that unit tests can see what's happening2654+ ++stb_alloc_count_free;2655+2656+ switch(stb__identify(p)) {2657+ case STB__chunked:2658+ // freeing a chunked-block with children does nothing;2659+ // they only get freed when the parent does2660+ // surely this is wrong, and it should free them immediately?2661+ // otherwise how are they getting put on the right chain?2662+ return;2663+ case STB__nochildren: {2664+ stb__nochildren *s = (stb__nochildren *) p - 1;2665+ // unlink from sibling chain2666+ *(s->prevn) = s->next;2667+ if (s->next)2668+ *stb__prevn(s->next) = s->prevn;2669+ free(s);2670+ return;2671+ }2672+ case STB__alloc: {2673+ stb__alloc *s = (stb__alloc *) p - 1;2674+ stb__chunk *c, *n;2675+ void *q;2676+2677+ // unlink from sibling chain, if any2678+ *(s->prevn) = s->next;2679+ if (s->next)2680+ *stb__prevn(s->next) = s->prevn;2681+2682+ // first free chunks2683+ c = (stb__chunk *) stb__chunks(s);2684+ while (c != NULL) {2685+ n = c->next;2686+ stb_alloc_count_free += c->alloc;2687+ free(c);2688+ c = n;2689+ }2690+2691+ // validating2692+ stb__setchunks(s,NULL);2693+ s->prevn = NULL;2694+ s->next = NULL;2695+2696+ // now free children2697+ while ((q = s->child) != NULL) {2698+ stb_free(q);2699+ }2700+2701+ // now free self2702+ free(s);2703+ return;2704+ }2705+ default:2706+ assert(0); /* NOTREACHED */2707+ }2708+}2709+2710+void stb_malloc_validate(void *p, void *parent)2711+{2712+ if (p == NULL) return;2713+2714+ switch(stb__identify(p)) {2715+ case STB__chunked:2716+ return;2717+ case STB__nochildren: {2718+ stb__nochildren *n = (stb__nochildren *) p - 1;2719+ if (n->prevn)2720+ assert(*n->prevn == p);2721+ if (n->next) {2722+ assert(*stb__prevn(n->next) == &n->next);2723+ stb_malloc_validate(n, parent);2724+ }2725+ return;2726+ }2727+ case STB__alloc: {2728+ stb__alloc *s = (stb__alloc *) p - 1;2729+2730+ if (s->prevn)2731+ assert(*s->prevn == p);2732+2733+ if (s->child) {2734+ assert(*stb__prevn(s->child) == &s->child);2735+ stb_malloc_validate(s->child, p);2736+ }2737+2738+ if (s->next) {2739+ assert(*stb__prevn(s->next) == &s->next);2740+ stb_malloc_validate(s->next, parent);2741+ }2742+ return;2743+ }2744+ default:2745+ assert(0); /* NOTREACHED */2746+ }2747+}2748+2749+static void * stb__try_chunk(stb__chunk *c, int size, int align, int pre_align)2750+{2751+ char *memblock = (char *) (c+1), *q;2752+ stb_inta iq;2753+ int start_offset;2754+2755+ // we going to allocate at the end of the chunk, not the start. confusing,2756+ // but it means we don't need both a 'limit' and a 'cur', just a 'cur'.2757+ // the block ends at: p + c->data_left2758+ // then we move back by size2759+ start_offset = c->data_left - size;2760+2761+ // now we need to check the alignment of that2762+ q = memblock + start_offset;2763+ iq = (stb_inta) q;2764+ assert(sizeof(q) == sizeof(iq));2765+2766+ // suppose align = 22767+ // then we need to retreat iq far enough that (iq & (2-1)) == 02768+ // to get (iq & (align-1)) = 0 requires subtracting (iq & (align-1))2769+2770+ start_offset -= iq & (align-1);2771+ assert(((stb_uinta) (memblock+start_offset) & (align-1)) == 0);2772+2773+ // now, if that + pre_align works, go for it!2774+ start_offset -= pre_align;2775+2776+ if (start_offset >= 0) {2777+ c->data_left = start_offset;2778+ return memblock + start_offset;2779+ }2780+2781+ return NULL;2782+}2783+2784+static void stb__sort_chunks(stb__alloc *src)2785+{2786+ // of the first two chunks, put the chunk with more data left in it first2787+ stb__chunk *c = stb__chunks(src), *d;2788+ if (c == NULL) return;2789+ d = c->next;2790+ if (d == NULL) return;2791+ if (c->data_left > d->data_left) return;2792+2793+ c->next = d->next;2794+ d->next = c;2795+ stb__setchunks(src, d);2796+}2797+2798+static void * stb__alloc_chunk(stb__alloc *src, int size, int align, int pre_align)2799+{2800+ void *p;2801+ stb__chunk *c = stb__chunks(src);2802+2803+ if (c && size <= stb_alloc_chunk_size) {2804+2805+ p = stb__try_chunk(c, size, align, pre_align);2806+ if (p) { ++c->alloc; return p; }2807+2808+ // try a second chunk to reduce wastage2809+ if (c->next) {2810+ p = stb__try_chunk(c->next, size, align, pre_align);2811+ if (p) { ++c->alloc; return p; }2812+2813+ // put the bigger chunk first, since the second will get buried2814+ // the upshot of this is that, until it gets allocated from, chunk #22815+ // is always the largest remaining chunk. (could formalize2816+ // this with a heap!)2817+ stb__sort_chunks(src);2818+ c = stb__chunks(src);2819+ }2820+ }2821+2822+ // allocate a new chunk2823+ {2824+ stb__chunk *n;2825+2826+ int chunk_size = stb_alloc_chunk_size;2827+ // we're going to allocate a new chunk to put this in2828+ if (size > chunk_size)2829+ chunk_size = size;2830+2831+ assert(sizeof(*n) + pre_align <= 16);2832+2833+ // loop trying to allocate a large enough chunk2834+ // the loop is because the alignment may cause problems if it's big...2835+ // and we don't know what our chunk alignment is going to be2836+ while (1) {2837+ n = (stb__chunk *) malloc(16 + chunk_size);2838+ if (n == NULL) return NULL;2839+2840+ n->data_left = chunk_size - sizeof(*n);2841+2842+ p = stb__try_chunk(n, size, align, pre_align);2843+ if (p != NULL) {2844+ n->next = c;2845+ stb__setchunks(src, n);2846+2847+ // if we just used up the whole block immediately,2848+ // move the following chunk up2849+ n->alloc = 1;2850+ if (size == chunk_size)2851+ stb__sort_chunks(src);2852+2853+ return p;2854+ }2855+2856+ free(n);2857+ chunk_size += 16+align;2858+ }2859+ }2860+}2861+2862+static stb__alloc * stb__get_context(void *context)2863+{2864+ if (context == NULL) {2865+ return &stb__alloc_global;2866+ } else {2867+ int u = stb__identify(context);2868+ // if context is chunked, grab parent2869+ if (u == STB__chunked) {2870+ stb__chunked *s = (stb__chunked *) context - 1;2871+ return stb__parent(s);2872+ } else {2873+ return (stb__alloc *) context - 1;2874+ }2875+ }2876+}2877+2878+static void stb__insert_alloc(stb__alloc *src, stb__alloc *s)2879+{2880+ s->prevn = &src->child;2881+ s->next = src->child;2882+ src->child = s+1;2883+ if (s->next)2884+ *stb__prevn(s->next) = &s->next;2885+}2886+2887+static void stb__insert_nochild(stb__alloc *src, stb__nochildren *s)2888+{2889+ s->prevn = &src->child;2890+ s->next = src->child;2891+ src->child = s+1;2892+ if (s->next)2893+ *stb__prevn(s->next) = &s->next;2894+}2895+2896+static void * malloc_base(void *context, size_t size, stb__alloc_type t, int align)2897+{2898+ void *p;2899+2900+ stb__alloc *src = stb__get_context(context);2901+2902+ if (align <= 0) {2903+ // compute worst-case C packed alignment2904+ // e.g. a 24-byte struct is 8-aligned2905+ int align_proposed = 1 << stb_lowbit8((unsigned int) size);2906+2907+ if (align_proposed < 0)2908+ align_proposed = 4;2909+2910+ if (align_proposed == 0) {2911+ if (size == 0)2912+ align_proposed = 1;2913+ else2914+ align_proposed = 256;2915+ }2916+2917+ // a negative alignment means 'don't align any larger2918+ // than this'; so -16 means we align 1,2,4,8, or 162919+2920+ if (align < 0) {2921+ if (align_proposed > -align)2922+ align_proposed = -align;2923+ }2924+2925+ align = align_proposed;2926+ }2927+2928+ assert(stb_is_pow2(align));2929+2930+ // don't cause misalignment when allocating nochildren2931+ if (t == STB__nochildren && align > 8)2932+ t = STB__alloc;2933+2934+ switch (t) {2935+ case STB__alloc: {2936+ stb__alloc *s = (stb__alloc *) malloc(size + sizeof(*s));2937+ if (s == NULL) return NULL;2938+ p = s+1;2939+ s->child = NULL;2940+ stb__insert_alloc(src, s);2941+2942+ stb__setchunks(s,NULL);2943+ break;2944+ }2945+2946+ case STB__nochildren: {2947+ stb__nochildren *s = (stb__nochildren *) malloc(size + sizeof(*s));2948+ if (s == NULL) return NULL;2949+ p = s+1;2950+ stb__insert_nochild(src, s);2951+ break;2952+ }2953+2954+ case STB__chunk_raw: {2955+ p = stb__alloc_chunk(src, (int) size, align, 0);2956+ if (p == NULL) return NULL;2957+ break;2958+ }2959+2960+ case STB__chunked: {2961+ stb__chunked *s;2962+ if (align < sizeof(stb_uintptr)) align = sizeof(stb_uintptr);2963+ s = (stb__chunked *) stb__alloc_chunk(src, (int) size, align, sizeof(*s));2964+ if (s == NULL) return NULL;2965+ stb__setparent(s, src);2966+ p = s+1;2967+ break;2968+ }2969+2970+ default: p = NULL; assert(0); /* NOTREACHED */2971+ }2972+2973+ ++stb_alloc_count_alloc;2974+ return p;2975+}2976+2977+void *stb_malloc_global(size_t size)2978+{2979+ return malloc_base(NULL, size, STB__alloc, stb_alloc_alignment);2980+}2981+2982+void *stb_malloc(void *context, size_t size)2983+{2984+ return malloc_base(context, size, STB__alloc, stb_alloc_alignment);2985+}2986+2987+void *stb_malloc_nofree(void *context, size_t size)2988+{2989+ return malloc_base(context, size, STB__chunked, stb_alloc_alignment);2990+}2991+2992+void *stb_malloc_leaf(void *context, size_t size)2993+{2994+ return malloc_base(context, size, STB__nochildren, stb_alloc_alignment);2995+}2996+2997+void *stb_malloc_raw(void *context, size_t size)2998+{2999+ return malloc_base(context, size, STB__chunk_raw, stb_alloc_alignment);3000+}3001+3002+char *stb_malloc_string(void *context, size_t size)3003+{3004+ return (char *) malloc_base(context, size, STB__chunk_raw, 1);3005+}3006+3007+void *stb_realloc(void *ptr, size_t newsize)3008+{3009+ stb__alloc_type t;3010+3011+ if (ptr == NULL) return stb_malloc(NULL, newsize);3012+ if (newsize == 0) { stb_free(ptr); return NULL; }3013+3014+ t = stb__identify(ptr);3015+ assert(t == STB__alloc || t == STB__nochildren);3016+3017+ if (t == STB__alloc) {3018+ stb__alloc *s = (stb__alloc *) ptr - 1;3019+3020+ s = (stb__alloc *) realloc(s, newsize + sizeof(*s));3021+ if (s == NULL) return NULL;3022+3023+ ptr = s+1;3024+3025+ // update pointers3026+ (*s->prevn) = ptr;3027+ if (s->next)3028+ *stb__prevn(s->next) = &s->next;3029+3030+ if (s->child)3031+ *stb__prevn(s->child) = &s->child;3032+3033+ return ptr;3034+ } else {3035+ stb__nochildren *s = (stb__nochildren *) ptr - 1;3036+3037+ s = (stb__nochildren *) realloc(ptr, newsize + sizeof(s));3038+ if (s == NULL) return NULL;3039+3040+ // update pointers3041+ (*s->prevn) = s+1;3042+ if (s->next)3043+ *stb__prevn(s->next) = &s->next;3044+3045+ return s+1;3046+ }3047+}3048+3049+void *stb_realloc_c(void *context, void *ptr, size_t newsize)3050+{3051+ if (ptr == NULL) return stb_malloc(context, newsize);3052+ if (newsize == 0) { stb_free(ptr); return NULL; }3053+ // @TODO: verify you haven't changed contexts3054+ return stb_realloc(ptr, newsize);3055+}3056+3057+void stb_reassign(void *new_context, void *ptr)3058+{3059+ stb__alloc *src = stb__get_context(new_context);3060+3061+ stb__alloc_type t = stb__identify(ptr);3062+ assert(t == STB__alloc || t == STB__nochildren);3063+3064+ if (t == STB__alloc) {3065+ stb__alloc *s = (stb__alloc *) ptr - 1;3066+3067+ // unlink from old3068+ *(s->prevn) = s->next;3069+ if (s->next)3070+ *stb__prevn(s->next) = s->prevn;3071+3072+ stb__insert_alloc(src, s);3073+ } else {3074+ stb__nochildren *s = (stb__nochildren *) ptr - 1;3075+3076+ // unlink from old3077+ *(s->prevn) = s->next;3078+ if (s->next)3079+ *stb__prevn(s->next) = s->prevn;3080+3081+ stb__insert_nochild(src, s);3082+ }3083+}3084+3085+#endif3086+3087+3088+//////////////////////////////////////////////////////////////////////////////3089+//3090+// stb_arr3091+//3092+// An stb_arr is directly useable as a pointer (use the actual type in your3093+// definition), but when it resizes, it returns a new pointer and you can't3094+// use the old one, so you have to be careful to copy-in-out as necessary.3095+//3096+// Use a NULL pointer as a 0-length array.3097+//3098+// float *my_array = NULL, *temp;3099+//3100+// // add elements on the end one at a time3101+// stb_arr_push(my_array, 0.0f);3102+// stb_arr_push(my_array, 1.0f);3103+// stb_arr_push(my_array, 2.0f);3104+//3105+// assert(my_array[1] == 2.0f);3106+//3107+// // add an uninitialized element at the end, then assign it3108+// *stb_arr_add(my_array) = 3.0f;3109+//3110+// // add three uninitialized elements at the end3111+// temp = stb_arr_addn(my_array,3);3112+// temp[0] = 4.0f;3113+// temp[1] = 5.0f;3114+// temp[2] = 6.0f;3115+//3116+// assert(my_array[5] == 5.0f);3117+//3118+// // remove the last one3119+// stb_arr_pop(my_array);3120+//3121+// assert(stb_arr_len(my_array) == 6);3122+3123+3124+#ifdef STB_MALLOC_WRAPPER3125+ #define STB__PARAMS , char *file, int line3126+ #define STB__ARGS , file, line3127+#else3128+ #define STB__PARAMS3129+ #define STB__ARGS3130+#endif3131+3132+// calling this function allocates an empty stb_arr attached to p3133+// (whereas NULL isn't attached to anything)3134+STB_EXTERN void stb_arr_malloc(void **target, void *context);3135+3136+// call this function with a non-NULL value to have all successive3137+// stbs that are created be attached to the associated parent. Note3138+// that once a given stb_arr is non-empty, it stays attached to its3139+// current parent, even if you call this function again.3140+// it turns the previous value, so you can restore it3141+STB_EXTERN void* stb_arr_malloc_parent(void *p);3142+3143+// simple functions written on top of other functions3144+#define stb_arr_empty(a) ( stb_arr_len(a) == 0 )3145+#define stb_arr_add(a) ( stb_arr_addn((a),1) )3146+#define stb_arr_push(a,v) ( *stb_arr_add(a)=(v) )3147+3148+typedef struct3149+{3150+ int len, limit;3151+ int stb_malloc;3152+ unsigned int signature;3153+} stb__arr;3154+3155+#define stb_arr_signature 0x51bada7b // ends with 0123 in decimal3156+3157+// access the header block stored before the data3158+#define stb_arrhead(a) /*lint --e(826)*/ (((stb__arr *) (a)) - 1)3159+#define stb_arrhead2(a) /*lint --e(826)*/ (((stb__arr *) (a)) - 1)3160+3161+#ifdef STB_DEBUG3162+#define stb_arr_check(a) assert(!a || stb_arrhead(a)->signature == stb_arr_signature)3163+#define stb_arr_check2(a) assert(!a || stb_arrhead2(a)->signature == stb_arr_signature)3164+#else3165+#define stb_arr_check(a) ((void) 0)3166+#define stb_arr_check2(a) ((void) 0)3167+#endif3168+3169+// ARRAY LENGTH3170+3171+// get the array length; special case if pointer is NULL3172+#define stb_arr_len(a) (a ? stb_arrhead(a)->len : 0)3173+#define stb_arr_len2(a) ((stb__arr *) (a) ? stb_arrhead2(a)->len : 0)3174+#define stb_arr_lastn(a) (stb_arr_len(a)-1)3175+3176+// check whether a given index is valid -- tests 0 <= i < stb_arr_len(a)3177+#define stb_arr_valid(a,i) (a ? (int) (i) < stb_arrhead(a)->len : 0)3178+3179+// change the array length so is is exactly N entries long, creating3180+// uninitialized entries as needed3181+#define stb_arr_setlen(a,n) \3182+ (stb__arr_setlen((void **) &(a), sizeof(a[0]), (n)))3183+3184+// change the array length so that N is a valid index (that is, so3185+// it is at least N entries long), creating uninitialized entries as needed3186+#define stb_arr_makevalid(a,n) \3187+ (stb_arr_len(a) < (n)+1 ? stb_arr_setlen(a,(n)+1),(a) : (a))3188+3189+// remove the last element of the array, returning it3190+#define stb_arr_pop(a) ((stb_arr_check(a), (a))[--stb_arrhead(a)->len])3191+3192+// access the last element in the array3193+#define stb_arr_last(a) ((stb_arr_check(a), (a))[stb_arr_len(a)-1])3194+3195+// is iterator at end of list?3196+#define stb_arr_end(a,i) ((i) >= &(a)[stb_arr_len(a)])3197+3198+// (internal) change the allocated length of the array3199+#define stb_arr__grow(a,n) (stb_arr_check(a), stb_arrhead(a)->len += (n))3200+3201+// add N new uninitialized elements to the end of the array3202+#define stb_arr__addn(a,n) /*lint --e(826)*/ \3203+ ((stb_arr_len(a)+(n) > stb_arrcurmax(a)) \3204+ ? (stb__arr_addlen((void **) &(a),sizeof(*a),(n)),0) \3205+ : ((stb_arr__grow(a,n), 0)))3206+3207+// add N new uninitialized elements to the end of the array, and return3208+// a pointer to the first new one3209+#define stb_arr_addn(a,n) (stb_arr__addn((a),n),(a)+stb_arr_len(a)-(n))3210+3211+// add N new uninitialized elements starting at index 'i'3212+#define stb_arr_insertn(a,i,n) (stb__arr_insertn((void **) &(a), sizeof(*a), (i), (n)))3213+3214+// insert an element at i3215+#define stb_arr_insert(a,i,v) (stb__arr_insertn((void **) &(a), sizeof(*a), (i), (1)), ((a)[i] = v))3216+3217+// delete N elements from the middle starting at index 'i'3218+#define stb_arr_deleten(a,i,n) (stb__arr_deleten((void **) &(a), sizeof(*a), (i), (n)))3219+3220+// delete the i'th element3221+#define stb_arr_delete(a,i) stb_arr_deleten(a,i,1)3222+3223+// delete the i'th element, swapping down from the end3224+#define stb_arr_fastdelete(a,i) \3225+ (stb_swap(&a[i], &a[stb_arrhead(a)->len-1], sizeof(*a)), stb_arr_pop(a))3226+3227+3228+// ARRAY STORAGE3229+3230+// get the array maximum storage; special case if NULL3231+#define stb_arrcurmax(a) (a ? stb_arrhead(a)->limit : 0)3232+#define stb_arrcurmax2(a) (a ? stb_arrhead2(a)->limit : 0)3233+3234+// set the maxlength of the array to n in anticipation of further growth3235+#define stb_arr_setsize(a,n) (stb_arr_check(a), stb__arr_setsize((void **) &(a),sizeof((a)[0]),n))3236+3237+// make sure maxlength is large enough for at least N new allocations3238+#define stb_arr_atleast(a,n) (stb_arr_len(a)+(n) > stb_arrcurmax(a) \3239+ ? stb_arr_setsize((a), (n)) : 0)3240+3241+// make a copy of a given array (copies contents via 'memcpy'!)3242+#define stb_arr_copy(a) stb__arr_copy(a, sizeof((a)[0]))3243+3244+// compute the storage needed to store all the elements of the array3245+#define stb_arr_storage(a) (stb_arr_len(a) * sizeof((a)[0]))3246+3247+#define stb_arr_for(v,arr) for((v)=(arr); (v) < (arr)+stb_arr_len(arr); ++(v))3248+3249+// IMPLEMENTATION3250+3251+STB_EXTERN void stb_arr_free_(void **p);3252+STB_EXTERN void *stb__arr_copy_(void *p, int elem_size);3253+STB_EXTERN void stb__arr_setsize_(void **p, int size, int limit STB__PARAMS);3254+STB_EXTERN void stb__arr_setlen_(void **p, int size, int newlen STB__PARAMS);3255+STB_EXTERN void stb__arr_addlen_(void **p, int size, int addlen STB__PARAMS);3256+STB_EXTERN void stb__arr_deleten_(void **p, int size, int loc, int n STB__PARAMS);3257+STB_EXTERN void stb__arr_insertn_(void **p, int size, int loc, int n STB__PARAMS);3258+3259+#define stb_arr_free(p) stb_arr_free_((void **) &(p))3260+#define stb__arr_copy stb__arr_copy_3261+3262+#ifndef STB_MALLOC_WRAPPER3263+ #define stb__arr_setsize stb__arr_setsize_3264+ #define stb__arr_setlen stb__arr_setlen_3265+ #define stb__arr_addlen stb__arr_addlen_3266+ #define stb__arr_deleten stb__arr_deleten_3267+ #define stb__arr_insertn stb__arr_insertn_3268+#else3269+ #define stb__arr_addlen(p,s,n) stb__arr_addlen_(p,s,n,__FILE__,__LINE__)3270+ #define stb__arr_setlen(p,s,n) stb__arr_setlen_(p,s,n,__FILE__,__LINE__)3271+ #define stb__arr_setsize(p,s,n) stb__arr_setsize_(p,s,n,__FILE__,__LINE__)3272+ #define stb__arr_deleten(p,s,i,n) stb__arr_deleten_(p,s,i,n,__FILE__,__LINE__)3273+ #define stb__arr_insertn(p,s,i,n) stb__arr_insertn_(p,s,i,n,__FILE__,__LINE__)3274+#endif3275+3276+#ifdef STB_DEFINE3277+static void *stb__arr_context;3278+3279+void *stb_arr_malloc_parent(void *p)3280+{3281+ void *q = stb__arr_context;3282+ stb__arr_context = p;3283+ return q;3284+}3285+3286+void stb_arr_malloc(void **target, void *context)3287+{3288+ stb__arr *q = (stb__arr *) stb_malloc(context, sizeof(*q));3289+ q->len = q->limit = 0;3290+ q->stb_malloc = 1;3291+ q->signature = stb_arr_signature;3292+ *target = (void *) (q+1);3293+}3294+3295+static void * stb__arr_malloc(int size)3296+{3297+ if (stb__arr_context)3298+ return stb_malloc(stb__arr_context, size);3299+ return malloc(size);3300+}3301+3302+void * stb__arr_copy_(void *p, int elem_size)3303+{3304+ stb__arr *q;3305+ if (p == NULL) return p;3306+ q = (stb__arr *) stb__arr_malloc(sizeof(*q) + elem_size * stb_arrhead2(p)->limit);3307+ stb_arr_check2(p);3308+ memcpy(q, stb_arrhead2(p), sizeof(*q) + elem_size * stb_arrhead2(p)->len);3309+ q->stb_malloc = !!stb__arr_context;3310+ return q+1;3311+}3312+3313+void stb_arr_free_(void **pp)3314+{3315+ void *p = *pp;3316+ stb_arr_check2(p);3317+ if (p) {3318+ stb__arr *q = stb_arrhead2(p);3319+ if (q->stb_malloc)3320+ stb_free(q);3321+ else3322+ free(q);3323+ }3324+ *pp = NULL;3325+}3326+3327+static void stb__arrsize_(void **pp, int size, int limit, int len STB__PARAMS)3328+{3329+ void *p = *pp;3330+ stb__arr *a;3331+ stb_arr_check2(p);3332+ if (p == NULL) {3333+ if (len == 0 && size == 0) return;3334+ a = (stb__arr *) stb__arr_malloc(sizeof(*a) + size*limit);3335+ a->limit = limit;3336+ a->len = len;3337+ a->stb_malloc = !!stb__arr_context;3338+ a->signature = stb_arr_signature;3339+ } else {3340+ a = stb_arrhead2(p);3341+ a->len = len;3342+ if (a->limit < limit) {3343+ void *p;3344+ if (a->limit >= 4 && limit < a->limit * 2)3345+ limit = a->limit * 2;3346+ if (a->stb_malloc)3347+ p = stb_realloc(a, sizeof(*a) + limit*size);3348+ else3349+ #ifdef STB_MALLOC_WRAPPER3350+ p = stb__realloc(a, sizeof(*a) + limit*size, file, line);3351+ #else3352+ p = realloc(a, sizeof(*a) + limit*size);3353+ #endif3354+ if (p) {3355+ a = (stb__arr *) p;3356+ a->limit = limit;3357+ } else {3358+ // throw an error!3359+ }3360+ }3361+ }3362+ a->len = stb_min(a->len, a->limit);3363+ *pp = a+1;3364+}3365+3366+void stb__arr_setsize_(void **pp, int size, int limit STB__PARAMS)3367+{3368+ void *p = *pp;3369+ stb_arr_check2(p);3370+ stb__arrsize_(pp, size, limit, stb_arr_len2(p) STB__ARGS);3371+}3372+3373+void stb__arr_setlen_(void **pp, int size, int newlen STB__PARAMS)3374+{3375+ void *p = *pp;3376+ stb_arr_check2(p);3377+ if (stb_arrcurmax2(p) < newlen || p == NULL) {3378+ stb__arrsize_(pp, size, newlen, newlen STB__ARGS);3379+ } else {3380+ stb_arrhead2(p)->len = newlen;3381+ }3382+}3383+3384+void stb__arr_addlen_(void **p, int size, int addlen STB__PARAMS)3385+{3386+ stb__arr_setlen_(p, size, stb_arr_len2(*p) + addlen STB__ARGS);3387+}3388+3389+void stb__arr_insertn_(void **pp, int size, int i, int n STB__PARAMS)3390+{3391+ void *p = *pp;3392+ if (n) {3393+ int z;3394+3395+ if (p == NULL) {3396+ stb__arr_addlen_(pp, size, n STB__ARGS);3397+ return;3398+ }3399+3400+ z = stb_arr_len2(p);3401+ stb__arr_addlen_(&p, size, n STB__ARGS);3402+ memmove((char *) p + (i+n)*size, (char *) p + i*size, size * (z-i));3403+ }3404+ *pp = p;3405+}3406+3407+void stb__arr_deleten_(void **pp, int size, int i, int n STB__PARAMS)3408+{3409+ void *p = *pp;3410+ if (n) {3411+ memmove((char *) p + i*size, (char *) p + (i+n)*size, size * (stb_arr_len2(p)-(i+n)));3412+ stb_arrhead2(p)->len -= n;3413+ }3414+ *pp = p;3415+}3416+3417+#endif3418+3419+//////////////////////////////////////////////////////////////////////////////3420+//3421+// Hashing3422+//3423+// typical use for this is to make a power-of-two hash table.3424+//3425+// let N = size of table (2^n)3426+// let H = stb_hash(str)3427+// let S = stb_rehash(H) | 13428+//3429+// then hash probe sequence P(i) for i=0..N-13430+// P(i) = (H + S*i) & (N-1)3431+//3432+// the idea is that H has 32 bits of hash information, but the3433+// table has only, say, 2^20 entries so only uses 20 of the bits.3434+// then by rehashing the original H we get 2^12 different probe3435+// sequences for a given initial probe location. (So it's optimal3436+// for 64K tables and its optimality decreases past that.)3437+//3438+// ok, so I've added something that generates _two separate_3439+// 32-bit hashes simultaneously which should scale better to3440+// very large tables.3441+3442+3443+STB_EXTERN unsigned int stb_hash(char *str);3444+STB_EXTERN unsigned int stb_hashptr(void *p);3445+STB_EXTERN unsigned int stb_hashlen(char *str, int len);3446+STB_EXTERN unsigned int stb_rehash_improved(unsigned int v);3447+STB_EXTERN unsigned int stb_hash_fast(void *p, int len);3448+STB_EXTERN unsigned int stb_hash2(char *str, unsigned int *hash2_ptr);3449+STB_EXTERN unsigned int stb_hash_number(unsigned int hash);3450+3451+#define stb_rehash(x) ((x) + ((x) >> 6) + ((x) >> 19))3452+3453+#ifdef STB_DEFINE3454+unsigned int stb_hash(char *str)3455+{3456+ unsigned int hash = 0;3457+ while (*str)3458+ hash = (hash << 7) + (hash >> 25) + *str++;3459+ return hash + (hash >> 16);3460+}3461+3462+unsigned int stb_hashlen(char *str, int len)3463+{3464+ unsigned int hash = 0;3465+ while (len-- > 0 && *str)3466+ hash = (hash << 7) + (hash >> 25) + *str++;3467+ return hash + (hash >> 16);3468+}3469+3470+unsigned int stb_hashptr(void *p)3471+{3472+ unsigned int x = (unsigned int)(size_t) p;3473+3474+ // typically lacking in low bits and high bits3475+ x = stb_rehash(x);3476+ x += x << 16;3477+3478+ // pearson's shuffle3479+ x ^= x << 3;3480+ x += x >> 5;3481+ x ^= x << 2;3482+ x += x >> 15;3483+ x ^= x << 10;3484+ return stb_rehash(x);3485+}3486+3487+unsigned int stb_rehash_improved(unsigned int v)3488+{3489+ return stb_hashptr((void *)(size_t) v);3490+}3491+3492+unsigned int stb_hash2(char *str, unsigned int *hash2_ptr)3493+{3494+ unsigned int hash1 = 0x3141592c;3495+ unsigned int hash2 = 0x77f044ed;3496+ while (*str) {3497+ hash1 = (hash1 << 7) + (hash1 >> 25) + *str;3498+ hash2 = (hash2 << 11) + (hash2 >> 21) + *str;3499+ ++str;3500+ }3501+ *hash2_ptr = hash2 + (hash1 >> 16);3502+ return hash1 + (hash2 >> 16);3503+}3504+3505+// Paul Hsieh hash3506+#define stb__get16(p) ((p)[0] | ((p)[1] << 8))3507+3508+unsigned int stb_hash_fast(void *p, int len)3509+{3510+ unsigned char *q = (unsigned char *) p;3511+ unsigned int hash = len;3512+3513+ if (len <= 0 || q == NULL) return 0;3514+3515+ /* Main loop */3516+ for (;len > 3; len -= 4) {3517+ unsigned int val;3518+ hash += stb__get16(q);3519+ val = (stb__get16(q+2) << 11);3520+ hash = (hash << 16) ^ hash ^ val;3521+ q += 4;3522+ hash += hash >> 11;3523+ }3524+3525+ /* Handle end cases */3526+ switch (len) {3527+ case 3: hash += stb__get16(q);3528+ hash ^= hash << 16;3529+ hash ^= q[2] << 18;3530+ hash += hash >> 11;3531+ break;3532+ case 2: hash += stb__get16(q);3533+ hash ^= hash << 11;3534+ hash += hash >> 17;3535+ break;3536+ case 1: hash += q[0];3537+ hash ^= hash << 10;3538+ hash += hash >> 1;3539+ break;3540+ case 0: break;3541+ }3542+3543+ /* Force "avalanching" of final 127 bits */3544+ hash ^= hash << 3;3545+ hash += hash >> 5;3546+ hash ^= hash << 4;3547+ hash += hash >> 17;3548+ hash ^= hash << 25;3549+ hash += hash >> 6;3550+3551+ return hash;3552+}3553+3554+unsigned int stb_hash_number(unsigned int hash)3555+{3556+ hash ^= hash << 3;3557+ hash += hash >> 5;3558+ hash ^= hash << 4;3559+ hash += hash >> 17;3560+ hash ^= hash << 25;3561+ hash += hash >> 6;3562+ return hash;3563+}3564+3565+#endif3566+3567+#ifdef STB_PERFECT_HASH3568+//////////////////////////////////////////////////////////////////////////////3569+//3570+// Perfect hashing for ints/pointers3571+//3572+// This is mainly useful for making faster pointer-indexed tables3573+// that don't change frequently. E.g. for stb_ischar().3574+//3575+3576+typedef struct3577+{3578+ stb_uint32 addend;3579+ stb_uint multiplicand;3580+ stb_uint b_mask;3581+ stb_uint8 small_bmap[16];3582+ stb_uint16 *large_bmap;3583+3584+ stb_uint table_mask;3585+ stb_uint32 *table;3586+} stb_perfect;3587+3588+STB_EXTERN int stb_perfect_create(stb_perfect *,unsigned int*,int n);3589+STB_EXTERN void stb_perfect_destroy(stb_perfect *);3590+STB_EXTERN int stb_perfect_hash(stb_perfect *, unsigned int x);3591+extern int stb_perfect_hash_max_failures;3592+3593+#ifdef STB_DEFINE3594+3595+int stb_perfect_hash_max_failures;3596+3597+int stb_perfect_hash(stb_perfect *p, unsigned int x)3598+{3599+ stb_uint m = x * p->multiplicand;3600+ stb_uint y = x >> 16;3601+ stb_uint bv = (m >> 24) + y;3602+ stb_uint av = (m + y) >> 12;3603+ if (p->table == NULL) return -1; // uninitialized table fails3604+ bv &= p->b_mask;3605+ av &= p->table_mask;3606+ if (p->large_bmap)3607+ av ^= p->large_bmap[bv];3608+ else3609+ av ^= p->small_bmap[bv];3610+ return p->table[av] == x ? av : -1;3611+}3612+3613+static void stb__perfect_prehash(stb_perfect *p, stb_uint x, stb_uint16 *a, stb_uint16 *b)3614+{3615+ stb_uint m = x * p->multiplicand;3616+ stb_uint y = x >> 16;3617+ stb_uint bv = (m >> 24) + y;3618+ stb_uint av = (m + y) >> 12;3619+ bv &= p->b_mask;3620+ av &= p->table_mask;3621+ *b = bv;3622+ *a = av;3623+}3624+3625+static unsigned long stb__perfect_rand(void)3626+{3627+ static unsigned long stb__rand;3628+ stb__rand = stb__rand * 2147001325 + 715136305;3629+ return 0x31415926 ^ ((stb__rand >> 16) + (stb__rand << 16));3630+}3631+3632+typedef struct {3633+ unsigned short count;3634+ unsigned short b;3635+ unsigned short map;3636+ unsigned short *entries;3637+} stb__slot;3638+3639+static int stb__slot_compare(const void *p, const void *q)3640+{3641+ stb__slot *a = (stb__slot *) p;3642+ stb__slot *b = (stb__slot *) q;3643+ return a->count > b->count ? -1 : a->count < b->count; // sort large to small3644+}3645+3646+int stb_perfect_create(stb_perfect *p, unsigned int *v, int n)3647+{3648+ unsigned int buffer1[64], buffer2[64], buffer3[64], buffer4[64], buffer5[32];3649+ unsigned short *as = (unsigned short *) stb_temp(buffer1, sizeof(*v)*n);3650+ unsigned short *bs = (unsigned short *) stb_temp(buffer2, sizeof(*v)*n);3651+ unsigned short *entries = (unsigned short *) stb_temp(buffer4, sizeof(*entries) * n);3652+ int size = 1 << stb_log2_ceil(n), bsize=8;3653+ int failure = 0,i,j,k;3654+3655+ assert(n <= 32768);3656+ p->large_bmap = NULL;3657+3658+ for(;;) {3659+ stb__slot *bcount = (stb__slot *) stb_temp(buffer3, sizeof(*bcount) * bsize);3660+ unsigned short *bloc = (unsigned short *) stb_temp(buffer5, sizeof(*bloc) * bsize);3661+ unsigned short *e;3662+ int bad=0;3663+3664+ p->addend = stb__perfect_rand();3665+ p->multiplicand = stb__perfect_rand() | 1;3666+ p->table_mask = size-1;3667+ p->b_mask = bsize-1;3668+ p->table = (stb_uint32 *) malloc(size * sizeof(*p->table));3669+3670+ for (i=0; i < bsize; ++i) {3671+ bcount[i].b = i;3672+ bcount[i].count = 0;3673+ bcount[i].map = 0;3674+ }3675+ for (i=0; i < n; ++i) {3676+ stb__perfect_prehash(p, v[i], as+i, bs+i);3677+ ++bcount[bs[i]].count;3678+ }3679+ qsort(bcount, bsize, sizeof(*bcount), stb__slot_compare);3680+ e = entries; // now setup up their entries index3681+ for (i=0; i < bsize; ++i) {3682+ bcount[i].entries = e;3683+ e += bcount[i].count;3684+ bcount[i].count = 0;3685+ bloc[bcount[i].b] = i;3686+ }3687+ // now fill them out3688+ for (i=0; i < n; ++i) {3689+ int b = bs[i];3690+ int w = bloc[b];3691+ bcount[w].entries[bcount[w].count++] = i;3692+ }3693+ stb_tempfree(buffer5,bloc);3694+ // verify3695+ for (i=0; i < bsize; ++i)3696+ for (j=0; j < bcount[i].count; ++j)3697+ assert(bs[bcount[i].entries[j]] == bcount[i].b);3698+ memset(p->table, 0, size*sizeof(*p->table));3699+3700+ // check if any b has duplicate a3701+ for (i=0; i < bsize; ++i) {3702+ if (bcount[i].count > 1) {3703+ for (j=0; j < bcount[i].count; ++j) {3704+ if (p->table[as[bcount[i].entries[j]]])3705+ bad = 1;3706+ p->table[as[bcount[i].entries[j]]] = 1;3707+ }3708+ for (j=0; j < bcount[i].count; ++j) {3709+ p->table[as[bcount[i].entries[j]]] = 0;3710+ }3711+ if (bad) break;3712+ }3713+ }3714+3715+ if (!bad) {3716+ // go through the bs and populate the table, first fit3717+ for (i=0; i < bsize; ++i) {3718+ if (bcount[i].count) {3719+ // go through the candidate table[b] values3720+ for (j=0; j < size; ++j) {3721+ // go through the a values and see if they fit3722+ for (k=0; k < bcount[i].count; ++k) {3723+ int a = as[bcount[i].entries[k]];3724+ if (p->table[(a^j)&p->table_mask]) {3725+ break; // fails3726+ }3727+ }3728+ // if succeeded, accept3729+ if (k == bcount[i].count) {3730+ bcount[i].map = j;3731+ for (k=0; k < bcount[i].count; ++k) {3732+ int a = as[bcount[i].entries[k]];3733+ p->table[(a^j)&p->table_mask] = 1;3734+ }3735+ break;3736+ }3737+ }3738+ if (j == size)3739+ break; // no match for i'th entry, so break out in failure3740+ }3741+ }3742+ if (i == bsize) {3743+ // success... fill out map3744+ if (bsize <= 16 && size <= 256) {3745+ p->large_bmap = NULL;3746+ for (i=0; i < bsize; ++i)3747+ p->small_bmap[bcount[i].b] = (stb_uint8) bcount[i].map;3748+ } else {3749+ p->large_bmap = (unsigned short *) malloc(sizeof(*p->large_bmap) * bsize);3750+ for (i=0; i < bsize; ++i)3751+ p->large_bmap[bcount[i].b] = bcount[i].map;3752+ }3753+3754+ // initialize table to v[0], so empty slots will fail3755+ for (i=0; i < size; ++i)3756+ p->table[i] = v[0];3757+3758+ for (i=0; i < n; ++i)3759+ if (p->large_bmap)3760+ p->table[as[i] ^ p->large_bmap[bs[i]]] = v[i];3761+ else3762+ p->table[as[i] ^ p->small_bmap[bs[i]]] = v[i];3763+3764+ // and now validate that none of them collided3765+ for (i=0; i < n; ++i)3766+ assert(stb_perfect_hash(p, v[i]) >= 0);3767+3768+ stb_tempfree(buffer3, bcount);3769+ break;3770+ }3771+ }3772+ free(p->table);3773+ p->table = NULL;3774+ stb_tempfree(buffer3, bcount);3775+3776+ ++failure;3777+ if (failure >= 4 && bsize < size) bsize *= 2;3778+ if (failure >= 8 && (failure & 3) == 0 && size < 4*n) {3779+ size *= 2;3780+ bsize *= 2;3781+ }3782+ if (failure == 6) {3783+ // make sure the input data is unique, so we don't infinite loop3784+ unsigned int *data = (unsigned int *) stb_temp(buffer3, n * sizeof(*data));3785+ memcpy(data, v, sizeof(*data) * n);3786+ qsort(data, n, sizeof(*data), stb_intcmp(0));3787+ for (i=1; i < n; ++i) {3788+ if (data[i] == data[i-1])3789+ size = 0; // size is return value, so 0 it3790+ }3791+ stb_tempfree(buffer3, data);3792+ if (!size) break;3793+ }3794+ }3795+3796+ if (failure > stb_perfect_hash_max_failures)3797+ stb_perfect_hash_max_failures = failure;3798+3799+ stb_tempfree(buffer1, as);3800+ stb_tempfree(buffer2, bs);3801+ stb_tempfree(buffer4, entries);3802+3803+ return size;3804+}3805+3806+void stb_perfect_destroy(stb_perfect *p)3807+{3808+ if (p->large_bmap) free(p->large_bmap);3809+ if (p->table ) free(p->table);3810+ p->large_bmap = NULL;3811+ p->table = NULL;3812+ p->b_mask = 0;3813+ p->table_mask = 0;3814+}3815+#endif3816+3817+//////////////////////////////////////////////////////////////////////////////3818+//3819+// Perfect hash clients3820+3821+STB_EXTERN int stb_ischar(char s, char *set);3822+3823+#ifdef STB_DEFINE3824+3825+int stb_ischar(char c, char *set)3826+{3827+ static unsigned char bit[8] = { 1,2,4,8,16,32,64,128 };3828+ static stb_perfect p;3829+ static unsigned char (*tables)[256];3830+ static char ** sets = NULL;3831+3832+ int z = stb_perfect_hash(&p, (int)(size_t) set);3833+ if (z < 0) {3834+ int i,k,n,j,f;3835+ // special code that means free all existing data3836+ if (set == NULL) {3837+ stb_arr_free(sets);3838+ free(tables);3839+ tables = NULL;3840+ stb_perfect_destroy(&p);3841+ return 0;3842+ }3843+ stb_arr_push(sets, set);3844+ stb_perfect_destroy(&p);3845+ n = stb_perfect_create(&p, (unsigned int *) (char **) sets, stb_arr_len(sets));3846+ assert(n != 0);3847+ k = (n+7) >> 3;3848+ tables = (unsigned char (*)[256]) realloc(tables, sizeof(*tables) * k);3849+ memset(tables, 0, sizeof(*tables) * k);3850+ for (i=0; i < stb_arr_len(sets); ++i) {3851+ k = stb_perfect_hash(&p, (int)(size_t) sets[i]);3852+ assert(k >= 0);3853+ n = k >> 3;3854+ f = bit[k&7];3855+ for (j=0; !j || sets[i][j]; ++j) {3856+ tables[n][(unsigned char) sets[i][j]] |= f;3857+ }3858+ }3859+ z = stb_perfect_hash(&p, (int)(size_t) set);3860+ }3861+ return tables[z >> 3][(unsigned char) c] & bit[z & 7];3862+}3863+3864+#endif3865+#endif3866+3867+//////////////////////////////////////////////////////////////////////////////3868+//3869+// Instantiated data structures3870+//3871+// This is an attempt to implement a templated data structure.3872+//3873+// Hash table: call stb_define_hash(TYPE,N,KEY,K1,K2,HASH,VALUE)3874+// TYPE -- will define a structure type containing the hash table3875+// N -- the name, will prefix functions named:3876+// N create3877+// N destroy3878+// N get3879+// N set, N add, N update,3880+// N remove3881+// KEY -- the type of the key. 'x == y' must be valid3882+// K1,K2 -- keys never used by the app, used as flags in the hashtable3883+// HASH -- a piece of code ending with 'return' that hashes key 'k'3884+// VALUE -- the type of the value. 'x = y' must be valid3885+//3886+// Note that stb_define_hash_base can be used to define more sophisticated3887+// hash tables, e.g. those that make copies of the key or use special3888+// comparisons (e.g. strcmp).3889+3890+#define STB_(prefix,name) stb__##prefix##name3891+#define STB__(prefix,name) prefix##name3892+#define STB__use(x) x3893+#define STB__skip(x)3894+3895+#define stb_declare_hash(PREFIX,TYPE,N,KEY,VALUE) \3896+ typedef struct stb__st_##TYPE TYPE;\3897+ PREFIX int STB__(N, init)(TYPE *h, int count);\3898+ PREFIX int STB__(N, memory_usage)(TYPE *h);\3899+ PREFIX TYPE * STB__(N, create)(void);\3900+ PREFIX TYPE * STB__(N, copy)(TYPE *h);\3901+ PREFIX void STB__(N, destroy)(TYPE *h);\3902+ PREFIX int STB__(N,get_flag)(TYPE *a, KEY k, VALUE *v);\3903+ PREFIX VALUE STB__(N,get)(TYPE *a, KEY k);\3904+ PREFIX int STB__(N, set)(TYPE *a, KEY k, VALUE v);\3905+ PREFIX int STB__(N, add)(TYPE *a, KEY k, VALUE v);\3906+ PREFIX int STB__(N, update)(TYPE*a,KEY k,VALUE v);\3907+ PREFIX int STB__(N, remove)(TYPE *a, KEY k, VALUE *v);3908+3909+#define STB_nocopy(x) (x)3910+#define STB_nodelete(x) 03911+#define STB_nofields3912+#define STB_nonullvalue(x)3913+#define STB_nullvalue(x) x3914+#define STB_safecompare(x) x3915+#define STB_nosafe(x)3916+#define STB_noprefix3917+3918+#ifdef __GNUC__3919+#define STB__nogcc(x)3920+#else3921+#define STB__nogcc(x) x3922+#endif3923+3924+#define stb_define_hash_base(PREFIX,TYPE,FIELDS,N,NC,LOAD_FACTOR, \3925+ KEY,EMPTY,DEL,COPY,DISPOSE,SAFE, \3926+ VCOMPARE,CCOMPARE,HASH, \3927+ VALUE,HASVNULL,VNULL) \3928+ \3929+typedef struct \3930+{ \3931+ KEY k; \3932+ VALUE v; \3933+} STB_(N,_hashpair); \3934+ \3935+STB__nogcc( typedef struct stb__st_##TYPE TYPE; ) \3936+struct stb__st_##TYPE { \3937+ FIELDS \3938+ STB_(N,_hashpair) *table; \3939+ unsigned int mask; \3940+ int count, limit; \3941+ int deleted; \3942+ \3943+ int delete_threshhold; \3944+ int grow_threshhold; \3945+ int shrink_threshhold; \3946+ unsigned char alloced, has_empty, has_del; \3947+ VALUE ev; VALUE dv; \3948+}; \3949+ \3950+static unsigned int STB_(N, hash)(KEY k) \3951+{ \3952+ HASH \3953+} \3954+ \3955+PREFIX int STB__(N, init)(TYPE *h, int count) \3956+{ \3957+ int i; \3958+ if (count < 4) count = 4; \3959+ h->limit = count; \3960+ h->count = 0; \3961+ h->mask = count-1; \3962+ h->deleted = 0; \3963+ h->grow_threshhold = (int) (count * LOAD_FACTOR); \3964+ h->has_empty = h->has_del = 0; \3965+ h->alloced = 0; \3966+ if (count <= 64) \3967+ h->shrink_threshhold = 0; \3968+ else \3969+ h->shrink_threshhold = (int) (count * (LOAD_FACTOR/2.25)); \3970+ h->delete_threshhold = (int) (count * (1-LOAD_FACTOR)/2); \3971+ h->table = (STB_(N,_hashpair)*) malloc(sizeof(h->table[0]) * count); \3972+ if (h->table == NULL) return 0; \3973+ /* ideally this gets turned into a memset32 automatically */ \3974+ for (i=0; i < count; ++i) \3975+ h->table[i].k = EMPTY; \3976+ return 1; \3977+} \3978+ \3979+PREFIX int STB__(N, memory_usage)(TYPE *h) \3980+{ \3981+ return sizeof(*h) + h->limit * sizeof(h->table[0]); \3982+} \3983+ \3984+PREFIX TYPE * STB__(N, create)(void) \3985+{ \3986+ TYPE *h = (TYPE *) malloc(sizeof(*h)); \3987+ if (h) { \3988+ if (STB__(N, init)(h, 16)) \3989+ h->alloced = 1; \3990+ else { free(h); h=NULL; } \3991+ } \3992+ return h; \3993+} \3994+ \3995+PREFIX void STB__(N, destroy)(TYPE *a) \3996+{ \3997+ int i; \3998+ for (i=0; i < a->limit; ++i) \3999+ if (!CCOMPARE(a->table[i].k,EMPTY) && !CCOMPARE(a->table[i].k, DEL)) \4000+ DISPOSE(a->table[i].k); \4001+ free(a->table); \4002+ if (a->alloced) \4003+ free(a); \4004+} \4005+ \4006+static void STB_(N, rehash)(TYPE *a, int count); \4007+ \4008+PREFIX int STB__(N,get_flag)(TYPE *a, KEY k, VALUE *v) \4009+{ \4010+ unsigned int h = STB_(N, hash)(k); \4011+ unsigned int n = h & a->mask, s; \4012+ if (CCOMPARE(k,EMPTY)){ if (a->has_empty) *v = a->ev; return a->has_empty;}\4013+ if (CCOMPARE(k,DEL)) { if (a->has_del ) *v = a->dv; return a->has_del; }\4014+ if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \4015+ SAFE(if (!CCOMPARE(a->table[n].k,DEL))) \4016+ if (VCOMPARE(a->table[n].k,k)) { *v = a->table[n].v; return 1; } \4017+ s = stb_rehash(h) | 1; \4018+ for(;;) { \4019+ n = (n + s) & a->mask; \4020+ if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \4021+ SAFE(if (CCOMPARE(a->table[n].k,DEL)) continue;) \4022+ if (VCOMPARE(a->table[n].k,k)) \4023+ { *v = a->table[n].v; return 1; } \4024+ } \4025+} \4026+ \4027+HASVNULL( \4028+ PREFIX VALUE STB__(N,get)(TYPE *a, KEY k) \4029+ { \4030+ VALUE v; \4031+ if (STB__(N,get_flag)(a,k,&v)) return v; \4032+ else return VNULL; \4033+ } \4034+) \4035+ \4036+PREFIX int STB__(N,getkey)(TYPE *a, KEY k, KEY *kout) \4037+{ \4038+ unsigned int h = STB_(N, hash)(k); \4039+ unsigned int n = h & a->mask, s; \4040+ if (CCOMPARE(k,EMPTY)||CCOMPARE(k,DEL)) return 0; \4041+ if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \4042+ SAFE(if (!CCOMPARE(a->table[n].k,DEL))) \4043+ if (VCOMPARE(a->table[n].k,k)) { *kout = a->table[n].k; return 1; } \4044+ s = stb_rehash(h) | 1; \4045+ for(;;) { \4046+ n = (n + s) & a->mask; \4047+ if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \4048+ SAFE(if (CCOMPARE(a->table[n].k,DEL)) continue;) \4049+ if (VCOMPARE(a->table[n].k,k)) \4050+ { *kout = a->table[n].k; return 1; } \4051+ } \4052+} \4053+ \4054+static int STB_(N,addset)(TYPE *a, KEY k, VALUE v, \4055+ int allow_new, int allow_old, int copy) \4056+{ \4057+ unsigned int h = STB_(N, hash)(k); \4058+ unsigned int n = h & a->mask; \4059+ int b = -1; \4060+ if (CCOMPARE(k,EMPTY)) { \4061+ if (a->has_empty ? allow_old : allow_new) { \4062+ n=a->has_empty; a->ev = v; a->has_empty = 1; return !n; \4063+ } else return 0; \4064+ } \4065+ if (CCOMPARE(k,DEL)) { \4066+ if (a->has_del ? allow_old : allow_new) { \4067+ n=a->has_del; a->dv = v; a->has_del = 1; return !n; \4068+ } else return 0; \4069+ } \4070+ if (!CCOMPARE(a->table[n].k, EMPTY)) { \4071+ unsigned int s; \4072+ if (CCOMPARE(a->table[n].k, DEL)) \4073+ b = n; \4074+ else if (VCOMPARE(a->table[n].k,k)) { \4075+ if (allow_old) \4076+ a->table[n].v = v; \4077+ return !allow_new; \4078+ } \4079+ s = stb_rehash(h) | 1; \4080+ for(;;) { \4081+ n = (n + s) & a->mask; \4082+ if (CCOMPARE(a->table[n].k, EMPTY)) break; \4083+ if (CCOMPARE(a->table[n].k, DEL)) { \4084+ if (b < 0) b = n; \4085+ } else if (VCOMPARE(a->table[n].k,k)) { \4086+ if (allow_old) \4087+ a->table[n].v = v; \4088+ return !allow_new; \4089+ } \4090+ } \4091+ } \4092+ if (!allow_new) return 0; \4093+ if (b < 0) b = n; else --a->deleted; \4094+ a->table[b].k = copy ? COPY(k) : k; \4095+ a->table[b].v = v; \4096+ ++a->count; \4097+ if (a->count > a->grow_threshhold) \4098+ STB_(N,rehash)(a, a->limit*2); \4099+ return 1; \4100+} \4101+ \4102+PREFIX int STB__(N, set)(TYPE *a, KEY k, VALUE v){return STB_(N,addset)(a,k,v,1,1,1);}\4103+PREFIX int STB__(N, add)(TYPE *a, KEY k, VALUE v){return STB_(N,addset)(a,k,v,1,0,1);}\4104+PREFIX int STB__(N, update)(TYPE*a,KEY k,VALUE v){return STB_(N,addset)(a,k,v,0,1,1);}\4105+ \4106+PREFIX int STB__(N, remove)(TYPE *a, KEY k, VALUE *v) \4107+{ \4108+ unsigned int h = STB_(N, hash)(k); \4109+ unsigned int n = h & a->mask, s; \4110+ if (CCOMPARE(k,EMPTY)) { if (a->has_empty) { if(v)*v = a->ev; a->has_empty=0; return 1; } return 0; } \4111+ if (CCOMPARE(k,DEL)) { if (a->has_del ) { if(v)*v = a->dv; a->has_del =0; return 1; } return 0; } \4112+ if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \4113+ if (SAFE(CCOMPARE(a->table[n].k,DEL) || ) !VCOMPARE(a->table[n].k,k)) { \4114+ s = stb_rehash(h) | 1; \4115+ for(;;) { \4116+ n = (n + s) & a->mask; \4117+ if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \4118+ SAFE(if (CCOMPARE(a->table[n].k, DEL)) continue;) \4119+ if (VCOMPARE(a->table[n].k,k)) break; \4120+ } \4121+ } \4122+ DISPOSE(a->table[n].k); \4123+ a->table[n].k = DEL; \4124+ --a->count; \4125+ ++a->deleted; \4126+ if (v != NULL) \4127+ *v = a->table[n].v; \4128+ if (a->count < a->shrink_threshhold) \4129+ STB_(N, rehash)(a, a->limit >> 1); \4130+ else if (a->deleted > a->delete_threshhold) \4131+ STB_(N, rehash)(a, a->limit); \4132+ return 1; \4133+} \4134+ \4135+PREFIX TYPE * STB__(NC, copy)(TYPE *a) \4136+{ \4137+ int i; \4138+ TYPE *h = (TYPE *) malloc(sizeof(*h)); \4139+ if (!h) return NULL; \4140+ if (!STB__(N, init)(h, a->limit)) { free(h); return NULL; } \4141+ h->count = a->count; \4142+ h->deleted = a->deleted; \4143+ h->alloced = 1; \4144+ h->ev = a->ev; h->dv = a->dv; \4145+ h->has_empty = a->has_empty; h->has_del = a->has_del; \4146+ memcpy(h->table, a->table, h->limit * sizeof(h->table[0])); \4147+ for (i=0; i < a->limit; ++i) \4148+ if (!CCOMPARE(h->table[i].k,EMPTY) && !CCOMPARE(h->table[i].k,DEL)) \4149+ h->table[i].k = COPY(h->table[i].k); \4150+ return h; \4151+} \4152+ \4153+static void STB_(N, rehash)(TYPE *a, int count) \4154+{ \4155+ int i; \4156+ TYPE b; \4157+ STB__(N, init)(&b, count); \4158+ for (i=0; i < a->limit; ++i) \4159+ if (!CCOMPARE(a->table[i].k,EMPTY) && !CCOMPARE(a->table[i].k,DEL)) \4160+ STB_(N,addset)(&b, a->table[i].k, a->table[i].v,1,1,0); \4161+ free(a->table); \4162+ a->table = b.table; \4163+ a->mask = b.mask; \4164+ a->count = b.count; \4165+ a->limit = b.limit; \4166+ a->deleted = b.deleted; \4167+ a->delete_threshhold = b.delete_threshhold; \4168+ a->grow_threshhold = b.grow_threshhold; \4169+ a->shrink_threshhold = b.shrink_threshhold; \4170+}4171+4172+#define STB_equal(a,b) ((a) == (b))4173+4174+#define stb_define_hash(TYPE,N,KEY,EMPTY,DEL,HASH,VALUE) \4175+ stb_define_hash_base(STB_noprefix, TYPE,STB_nofields,N,NC,0.85f, \4176+ KEY,EMPTY,DEL,STB_nocopy,STB_nodelete,STB_nosafe, \4177+ STB_equal,STB_equal,HASH, \4178+ VALUE,STB_nonullvalue,0)4179+4180+#define stb_define_hash_vnull(TYPE,N,KEY,EMPTY,DEL,HASH,VALUE,VNULL) \4181+ stb_define_hash_base(STB_noprefix, TYPE,STB_nofields,N,NC,0.85f, \4182+ KEY,EMPTY,DEL,STB_nocopy,STB_nodelete,STB_nosafe, \4183+ STB_equal,STB_equal,HASH, \4184+ VALUE,STB_nullvalue,VNULL)4185+4186+//////////////////////////////////////////////////////////////////////////////4187+//4188+// stb_ptrmap4189+//4190+// An stb_ptrmap data structure is an O(1) hash table between pointers. One4191+// application is to let you store "extra" data associated with pointers,4192+// which is why it was originally called stb_extra.4193+4194+stb_declare_hash(STB_EXTERN, stb_ptrmap, stb_ptrmap_, void *, void *)4195+stb_declare_hash(STB_EXTERN, stb_idict, stb_idict_, stb_int32, stb_int32)4196+stb_declare_hash(STB_EXTERN, stb_uidict, stbi_uidict_, stb_uint32, stb_uint32)4197+4198+STB_EXTERN void stb_ptrmap_delete(stb_ptrmap *e, void (*free_func)(void *));4199+STB_EXTERN stb_ptrmap *stb_ptrmap_new(void);4200+4201+STB_EXTERN stb_idict * stb_idict_new_size(int size);4202+STB_EXTERN void stb_idict_remove_all(stb_idict *e);4203+STB_EXTERN void stb_uidict_reset(stb_uidict *e);4204+4205+#ifdef STB_DEFINE4206+4207+#define STB_EMPTY ((void *) 2)4208+#define STB_EDEL ((void *) 6)4209+4210+stb_define_hash_base(STB_noprefix,stb_ptrmap, STB_nofields, stb_ptrmap_,stb_ptrmap_,0.85f,4211+ void *,STB_EMPTY,STB_EDEL,STB_nocopy,STB_nodelete,STB_nosafe,4212+ STB_equal,STB_equal,return stb_hashptr(k);,4213+ void *,STB_nullvalue,NULL)4214+4215+stb_ptrmap *stb_ptrmap_new(void)4216+{4217+ return stb_ptrmap_create();4218+}4219+4220+void stb_ptrmap_delete(stb_ptrmap *e, void (*free_func)(void *))4221+{4222+ int i;4223+ if (free_func)4224+ for (i=0; i < e->limit; ++i)4225+ if (e->table[i].k != STB_EMPTY && e->table[i].k != STB_EDEL) {4226+ if (free_func == free)4227+ free(e->table[i].v); // allow STB_MALLOC_WRAPPER to operate4228+ else4229+ free_func(e->table[i].v);4230+ }4231+ stb_ptrmap_destroy(e);4232+}4233+4234+// extra fields needed for stua_dict4235+#define STB_IEMPTY ((int) 1)4236+#define STB_IDEL ((int) 3)4237+stb_define_hash_base(STB_noprefix, stb_idict, short type; short gc; STB_nofields, stb_idict_,stb_idict_,0.95f,4238+ stb_int32,STB_IEMPTY,STB_IDEL,STB_nocopy,STB_nodelete,STB_nosafe,4239+ STB_equal,STB_equal,4240+ return stb_rehash_improved(k);,stb_int32,STB_nonullvalue,0)4241+4242+stb_idict * stb_idict_new_size(int size)4243+{4244+ stb_idict *e = (stb_idict *) malloc(sizeof(*e));4245+ if (e) {4246+ if (!stb_is_pow2(size))4247+ size = 1 << stb_log2_ceil(size);4248+ stb_idict_init(e, size);4249+ e->alloced = 1;4250+ }4251+ return e;4252+}4253+4254+void stb_idict_remove_all(stb_idict *e)4255+{4256+ int n;4257+ for (n=0; n < e->limit; ++n)4258+ e->table[n].k = STB_IEMPTY;4259+ e->has_empty = e->has_del = 0;4260+ e->count = 0;4261+ e->deleted = 0;4262+}4263+4264+stb_define_hash_base(STB_noprefix, stb_uidict, STB_nofields, stb_uidict_,stb_uidict_,0.85f,4265+ stb_int32,0xffffffff,0xfffffffe,STB_nocopy,STB_nodelete,STB_nosafe,4266+ STB_equal,STB_equal,4267+ return stb_rehash_improved(k);,stb_uint32,STB_nonullvalue,0)4268+4269+void stb_uidict_reset(stb_uidict *e)4270+{4271+ int n;4272+ for (n=0; n < e->limit; ++n)4273+ e->table[n].k = 0xffffffff;4274+ e->has_empty = e->has_del = 0;4275+ e->count = 0;4276+ e->deleted = 0;4277+}4278+#endif4279+4280+//////////////////////////////////////////////////////////////////////////////4281+//4282+// stb_sparse_ptr_matrix4283+//4284+// An stb_ptrmap data structure is an O(1) hash table storing an arbitrary4285+// block of data for a given pair of pointers.4286+//4287+// If create=0, returns4288+4289+typedef struct stb__st_stb_spmatrix stb_spmatrix;4290+4291+STB_EXTERN stb_spmatrix * stb_sparse_ptr_matrix_new(int val_size);4292+STB_EXTERN void stb_sparse_ptr_matrix_free(stb_spmatrix *z);4293+STB_EXTERN void * stb_sparse_ptr_matrix_get(stb_spmatrix *z, void *a, void *b, int create);4294+4295+#ifdef STB_DEFINE4296+typedef struct4297+{4298+ void *a;4299+ void *b;4300+} stb__ptrpair;4301+4302+static stb__ptrpair stb__ptrpair_empty = { (void *) 1, (void *) 1 };4303+static stb__ptrpair stb__ptrpair_del = { (void *) 2, (void *) 2 };4304+4305+#define STB__equal_ptrpair(x,y) ((x).a == (y).a && (x).b == (y).b)4306+4307+stb_define_hash_base(STB_noprefix, stb_spmatrix, int val_size; void *arena;, stb__spmatrix_,stb__spmatrix_, 0.85,4308+ stb__ptrpair, stb__ptrpair_empty, stb__ptrpair_del,4309+ STB_nocopy, STB_nodelete, STB_nosafe,4310+ STB__equal_ptrpair, STB__equal_ptrpair, return stb_rehash(stb_hashptr(k.a))+stb_hashptr(k.b);,4311+ void *, STB_nullvalue, 0)4312+4313+stb_spmatrix *stb_sparse_ptr_matrix_new(int val_size)4314+{4315+ stb_spmatrix *m = stb__spmatrix_create();4316+ if (m) m->val_size = val_size;4317+ if (m) m->arena = stb_malloc_global(1);4318+ return m;4319+}4320+4321+void stb_sparse_ptr_matrix_free(stb_spmatrix *z)4322+{4323+ if (z->arena) stb_free(z->arena);4324+ stb__spmatrix_destroy(z);4325+}4326+4327+void *stb_sparse_ptr_matrix_get(stb_spmatrix *z, void *a, void *b, int create)4328+{4329+ stb__ptrpair t = { a,b };4330+ void *data = stb__spmatrix_get(z, t);4331+ if (!data && create) {4332+ data = stb_malloc_raw(z->arena, z->val_size);4333+ if (!data) return NULL;4334+ memset(data, 0, z->val_size);4335+ stb__spmatrix_add(z, t, data);4336+ }4337+ return data;4338+}4339+#endif4340+4341+4342+4343+//////////////////////////////////////////////////////////////////////////////4344+//4345+// SDICT: Hash Table for Strings (symbol table)4346+//4347+// if "use_arena=1", then strings will be copied4348+// into blocks and never freed until the sdict is freed;4349+// otherwise they're malloc()ed and free()d on the fly.4350+// (specify use_arena=1 if you never stb_sdict_remove)4351+4352+stb_declare_hash(STB_EXTERN, stb_sdict, stb_sdict_, char *, void *)4353+4354+STB_EXTERN stb_sdict * stb_sdict_new(int use_arena);4355+STB_EXTERN stb_sdict * stb_sdict_copy(stb_sdict*);4356+STB_EXTERN void stb_sdict_delete(stb_sdict *);4357+STB_EXTERN void * stb_sdict_change(stb_sdict *, char *str, void *p);4358+STB_EXTERN int stb_sdict_count(stb_sdict *d);4359+4360+STB_EXTERN int stb_sdict_internal_limit(stb_sdict *d);4361+STB_EXTERN char * stb_sdict_internal_key(stb_sdict *d, int n);4362+STB_EXTERN void * stb_sdict_internal_value(stb_sdict *d, int n);4363+4364+#define stb_sdict_for(d,i,q,z) \4365+ for(i=0; i < stb_sdict_internal_limit(d) ? (q=stb_sdict_internal_key(d,i),z=stb_sdict_internal_value(d,i),1) : 0; ++i) \4366+ if (q==NULL||q==(void *) 1);else // reversed makes macro friendly4367+4368+#ifdef STB_DEFINE4369+4370+// if in same translation unit, for speed, don't call accessors4371+#undef stb_sdict_for4372+#define stb_sdict_for(d,i,q,z) \4373+ for(i=0; i < (d)->limit ? (q=(d)->table[i].k,z=(d)->table[i].v,1) : 0; ++i) \4374+ if (q==NULL||q==(void *) 1);else // reversed makes macro friendly4375+4376+#define STB_DEL ((void *) 1)4377+#define STB_SDEL ((char *) 1)4378+4379+#define stb_sdict__copy(x) \4380+ stb_p_strcpy_s(a->arena ? stb_malloc_string(a->arena, strlen(x)+1) \4381+ : (char *) malloc(strlen(x)+1), strlen(x)+1, x)4382+4383+#define stb_sdict__dispose(x) if (!a->arena) free(x)4384+4385+stb_define_hash_base(STB_noprefix, stb_sdict, void*arena;, stb_sdict_,stb_sdictinternal_, 0.85f,4386+ char *, NULL, STB_SDEL, stb_sdict__copy, stb_sdict__dispose,4387+ STB_safecompare, !strcmp, STB_equal, return stb_hash(k);,4388+ void *, STB_nullvalue, NULL)4389+4390+int stb_sdict_count(stb_sdict *a)4391+{4392+ return a->count;4393+}4394+4395+int stb_sdict_internal_limit(stb_sdict *a)4396+{4397+ return a->limit;4398+}4399+char* stb_sdict_internal_key(stb_sdict *a, int n)4400+{4401+ return a->table[n].k;4402+}4403+void* stb_sdict_internal_value(stb_sdict *a, int n)4404+{4405+ return a->table[n].v;4406+}4407+4408+stb_sdict * stb_sdict_new(int use_arena)4409+{4410+ stb_sdict *d = stb_sdict_create();4411+ if (d == NULL) return NULL;4412+ d->arena = use_arena ? stb_malloc_global(1) : NULL;4413+ return d;4414+}4415+4416+stb_sdict* stb_sdict_copy(stb_sdict *old)4417+{4418+ stb_sdict *n;4419+ void *old_arena = old->arena;4420+ void *new_arena = old_arena ? stb_malloc_global(1) : NULL;4421+ old->arena = new_arena;4422+ n = stb_sdictinternal_copy(old);4423+ old->arena = old_arena;4424+ if (n)4425+ n->arena = new_arena;4426+ else if (new_arena)4427+ stb_free(new_arena);4428+ return n;4429+}4430+4431+4432+void stb_sdict_delete(stb_sdict *d)4433+{4434+ if (d->arena)4435+ stb_free(d->arena);4436+ stb_sdict_destroy(d);4437+}4438+4439+void * stb_sdict_change(stb_sdict *d, char *str, void *p)4440+{4441+ void *q = stb_sdict_get(d, str);4442+ stb_sdict_set(d, str, p);4443+ return q;4444+}4445+#endif4446+4447+//////////////////////////////////////////////////////////////////////////////4448+//4449+// Instantiated data structures4450+//4451+// This is an attempt to implement a templated data structure.4452+// What you do is define a struct foo, and then include several4453+// pointer fields to struct foo in your struct. Then you call4454+// the instantiator, which creates the functions that implement4455+// the data structure. This requires massive undebuggable #defines,4456+// so we limit the cases where we do this.4457+//4458+// AA tree is an encoding of a 2-3 tree whereas RB trees encode a 2-3-4 tree;4459+// much simpler code due to fewer cases.4460+4461+#define stb__bst_parent(x) x4462+#define stb__bst_noparent(x)4463+4464+#define stb_bst_fields(N) \4465+ *STB_(N,left), *STB_(N,right); \4466+ unsigned char STB_(N,level)4467+4468+#define stb_bst_fields_parent(N) \4469+ *STB_(N,left), *STB_(N,right), *STB_(N,parent); \4470+ unsigned char STB_(N,level)4471+4472+#define STB__level(N,x) ((x) ? (x)->STB_(N,level) : 0)4473+4474+#define stb_bst_base(TYPE, N, TREE, M, compare, PAR) \4475+ \4476+static int STB_(N,_compare)(TYPE *p, TYPE *q) \4477+{ \4478+ compare \4479+} \4480+ \4481+static void STB_(N,setleft)(TYPE *q, TYPE *v) \4482+{ \4483+ q->STB_(N,left) = v; \4484+ PAR(if (v) v->STB_(N,parent) = q;) \4485+} \4486+ \4487+static void STB_(N,setright)(TYPE *q, TYPE *v) \4488+{ \4489+ q->STB_(N,right) = v; \4490+ PAR(if (v) v->STB_(N,parent) = q;) \4491+} \4492+ \4493+static TYPE *STB_(N,skew)(TYPE *q) \4494+{ \4495+ if (q == NULL) return q; \4496+ if (q->STB_(N,left) \4497+ && q->STB_(N,left)->STB_(N,level) == q->STB_(N,level)) { \4498+ TYPE *p = q->STB_(N,left); \4499+ STB_(N,setleft)(q, p->STB_(N,right)); \4500+ STB_(N,setright)(p, q); \4501+ return p; \4502+ } \4503+ return q; \4504+} \4505+ \4506+static TYPE *STB_(N,split)(TYPE *p) \4507+{ \4508+ TYPE *q = p->STB_(N,right); \4509+ if (q && q->STB_(N,right) \4510+ && q->STB_(N,right)->STB_(N,level) == p->STB_(N,level)) { \4511+ STB_(N,setright)(p, q->STB_(N,left)); \4512+ STB_(N,setleft)(q,p); \4513+ ++q->STB_(N,level); \4514+ return q; \4515+ } \4516+ return p; \4517+} \4518+ \4519+TYPE *STB__(N,insert)(TYPE *tree, TYPE *item) \4520+{ \4521+ int c; \4522+ if (tree == NULL) { \4523+ item->STB_(N,left) = NULL; \4524+ item->STB_(N,right) = NULL; \4525+ item->STB_(N,level) = 1; \4526+ PAR(item->STB_(N,parent) = NULL;) \4527+ return item; \4528+ } \4529+ c = STB_(N,_compare)(item,tree); \4530+ if (c == 0) { \4531+ if (item != tree) { \4532+ STB_(N,setleft)(item, tree->STB_(N,left)); \4533+ STB_(N,setright)(item, tree->STB_(N,right)); \4534+ item->STB_(N,level) = tree->STB_(N,level); \4535+ PAR(item->STB_(N,parent) = NULL;) \4536+ } \4537+ return item; \4538+ } \4539+ if (c < 0) \4540+ STB_(N,setleft )(tree, STB__(N,insert)(tree->STB_(N,left), item)); \4541+ else \4542+ STB_(N,setright)(tree, STB__(N,insert)(tree->STB_(N,right), item)); \4543+ tree = STB_(N,skew)(tree); \4544+ tree = STB_(N,split)(tree); \4545+ PAR(tree->STB_(N,parent) = NULL;) \4546+ return tree; \4547+} \4548+ \4549+TYPE *STB__(N,remove)(TYPE *tree, TYPE *item) \4550+{ \4551+ static TYPE *delnode, *leaf, *restore; \4552+ if (tree == NULL) return NULL; \4553+ leaf = tree; \4554+ if (STB_(N,_compare)(item, tree) < 0) { \4555+ STB_(N,setleft)(tree, STB__(N,remove)(tree->STB_(N,left), item)); \4556+ } else { \4557+ TYPE *r; \4558+ delnode = tree; \4559+ r = STB__(N,remove)(tree->STB_(N,right), item); \4560+ /* maybe move 'leaf' up to this location */ \4561+ if (restore == tree) { tree = leaf; leaf = restore = NULL; } \4562+ STB_(N,setright)(tree,r); \4563+ assert(tree->STB_(N,right) != tree); \4564+ } \4565+ if (tree == leaf) { \4566+ if (delnode == item) { \4567+ tree = tree->STB_(N,right); \4568+ assert(leaf->STB_(N,left) == NULL); \4569+ /* move leaf (the right sibling) up to delnode */ \4570+ STB_(N,setleft )(leaf, item->STB_(N,left )); \4571+ STB_(N,setright)(leaf, item->STB_(N,right)); \4572+ leaf->STB_(N,level) = item->STB_(N,level); \4573+ if (leaf != item) \4574+ restore = delnode; \4575+ } \4576+ delnode = NULL; \4577+ } else { \4578+ if (STB__level(N,tree->STB_(N,left) ) < tree->STB_(N,level)-1 || \4579+ STB__level(N,tree->STB_(N,right)) < tree->STB_(N,level)-1) { \4580+ --tree->STB_(N,level); \4581+ if (STB__level(N,tree->STB_(N,right)) > tree->STB_(N,level)) \4582+ tree->STB_(N,right)->STB_(N,level) = tree->STB_(N,level); \4583+ tree = STB_(N,skew)(tree); \4584+ STB_(N,setright)(tree, STB_(N,skew)(tree->STB_(N,right))); \4585+ if (tree->STB_(N,right)) \4586+ STB_(N,setright)(tree->STB_(N,right), \4587+ STB_(N,skew)(tree->STB_(N,right)->STB_(N,right))); \4588+ tree = STB_(N,split)(tree); \4589+ if (tree->STB_(N,right)) \4590+ STB_(N,setright)(tree, STB_(N,split)(tree->STB_(N,right))); \4591+ } \4592+ } \4593+ PAR(if (tree) tree->STB_(N,parent) = NULL;) \4594+ return tree; \4595+} \4596+ \4597+TYPE *STB__(N,last)(TYPE *tree) \4598+{ \4599+ if (tree) \4600+ while (tree->STB_(N,right)) tree = tree->STB_(N,right); \4601+ return tree; \4602+} \4603+ \4604+TYPE *STB__(N,first)(TYPE *tree) \4605+{ \4606+ if (tree) \4607+ while (tree->STB_(N,left)) tree = tree->STB_(N,left); \4608+ return tree; \4609+} \4610+ \4611+TYPE *STB__(N,next)(TYPE *tree, TYPE *item) \4612+{ \4613+ TYPE *next = NULL; \4614+ if (item->STB_(N,right)) \4615+ return STB__(N,first)(item->STB_(N,right)); \4616+ PAR( \4617+ while(item->STB_(N,parent)) { \4618+ TYPE *up = item->STB_(N,parent); \4619+ if (up->STB_(N,left) == item) return up; \4620+ item = up; \4621+ } \4622+ return NULL; \4623+ ) \4624+ while (tree != item) { \4625+ if (STB_(N,_compare)(item, tree) < 0) { \4626+ next = tree; \4627+ tree = tree->STB_(N,left); \4628+ } else { \4629+ tree = tree->STB_(N,right); \4630+ } \4631+ } \4632+ return next; \4633+} \4634+ \4635+TYPE *STB__(N,prev)(TYPE *tree, TYPE *item) \4636+{ \4637+ TYPE *next = NULL; \4638+ if (item->STB_(N,left)) \4639+ return STB__(N,last)(item->STB_(N,left)); \4640+ PAR( \4641+ while(item->STB_(N,parent)) { \4642+ TYPE *up = item->STB_(N,parent); \4643+ if (up->STB_(N,right) == item) return up; \4644+ item = up; \4645+ } \4646+ return NULL; \4647+ ) \4648+ while (tree != item) { \4649+ if (STB_(N,_compare)(item, tree) < 0) { \4650+ tree = tree->STB_(N,left); \4651+ } else { \4652+ next = tree; \4653+ tree = tree->STB_(N,right); \4654+ } \4655+ } \4656+ return next; \4657+} \4658+ \4659+STB__DEBUG( \4660+ void STB__(N,_validate)(TYPE *tree, int root) \4661+ { \4662+ if (tree == NULL) return; \4663+ PAR(if(root) assert(tree->STB_(N,parent) == NULL);) \4664+ assert(STB__level(N,tree->STB_(N,left) ) == tree->STB_(N,level)-1); \4665+ assert(STB__level(N,tree->STB_(N,right)) <= tree->STB_(N,level)); \4666+ assert(STB__level(N,tree->STB_(N,right)) >= tree->STB_(N,level)-1); \4667+ if (tree->STB_(N,right)) { \4668+ assert(STB__level(N,tree->STB_(N,right)->STB_(N,right)) \4669+ != tree->STB_(N,level)); \4670+ PAR(assert(tree->STB_(N,right)->STB_(N,parent) == tree);) \4671+ } \4672+ PAR(if(tree->STB_(N,left)) assert(tree->STB_(N,left)->STB_(N,parent) == tree);) \4673+ STB__(N,_validate)(tree->STB_(N,left) ,0); \4674+ STB__(N,_validate)(tree->STB_(N,right),0); \4675+ } \4676+) \4677+ \4678+typedef struct \4679+{ \4680+ TYPE *root; \4681+} TREE; \4682+ \4683+void STB__(M,Insert)(TREE *tree, TYPE *item) \4684+{ tree->root = STB__(N,insert)(tree->root, item); } \4685+void STB__(M,Remove)(TREE *tree, TYPE *item) \4686+{ tree->root = STB__(N,remove)(tree->root, item); } \4687+TYPE *STB__(M,Next)(TREE *tree, TYPE *item) \4688+{ return STB__(N,next)(tree->root, item); } \4689+TYPE *STB__(M,Prev)(TREE *tree, TYPE *item) \4690+{ return STB__(N,prev)(tree->root, item); } \4691+TYPE *STB__(M,First)(TREE *tree) { return STB__(N,first)(tree->root); } \4692+TYPE *STB__(M,Last) (TREE *tree) { return STB__(N,last) (tree->root); } \4693+void STB__(M,Init)(TREE *tree) { tree->root = NULL; }4694+4695+4696+#define stb_bst_find(N,tree,fcompare) \4697+{ \4698+ int c; \4699+ while (tree != NULL) { \4700+ fcompare \4701+ if (c == 0) return tree; \4702+ if (c < 0) tree = tree->STB_(N,left); \4703+ else tree = tree->STB_(N,right); \4704+ } \4705+ return NULL; \4706+}4707+4708+#define stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,PAR) \4709+ stb_bst_base(TYPE,N,TREE,M, \4710+ VTYPE a = p->vfield; VTYPE b = q->vfield; return (compare);, PAR ) \4711+ \4712+TYPE *STB__(N,find)(TYPE *tree, VTYPE a) \4713+ stb_bst_find(N,tree,VTYPE b = tree->vfield; c = (compare);) \4714+TYPE *STB__(M,Find)(TREE *tree, VTYPE a) \4715+{ return STB__(N,find)(tree->root, a); }4716+4717+#define stb_bst(TYPE,N,TREE,M,vfield,VTYPE,compare) \4718+ stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,stb__bst_noparent)4719+#define stb_bst_parent(TYPE,N,TREE,M,vfield,VTYPE,compare) \4720+ stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,stb__bst_parent)4721+4722+4723+4724+//////////////////////////////////////////////////////////////////////////////4725+//4726+// Pointer Nulling4727+//4728+// This lets you automatically NULL dangling pointers to "registered"4729+// objects. Note that you have to make sure you call the appropriate4730+// functions when you free or realloc blocks of memory that contain4731+// pointers or pointer targets. stb.h can automatically do this for4732+// stb_arr, or for all frees/reallocs if it's wrapping them.4733+//4734+4735+#ifdef STB_NPTR4736+4737+STB_EXTERN void stb_nptr_set(void *address_of_pointer, void *value_to_write);4738+STB_EXTERN void stb_nptr_didset(void *address_of_pointer);4739+4740+STB_EXTERN void stb_nptr_didfree(void *address_being_freed, int len);4741+STB_EXTERN void stb_nptr_free(void *address_being_freed, int len);4742+4743+STB_EXTERN void stb_nptr_didrealloc(void *new_address, void *old_address, int len);4744+STB_EXTERN void stb_nptr_recache(void); // recache all known pointers4745+ // do this after pointer sets outside your control, slow4746+4747+#ifdef STB_DEFINE4748+// for fast updating on free/realloc, we need to be able to find4749+// all the objects (pointers and targets) within a given block;4750+// this precludes hashing4751+4752+// we use a three-level hierarchy of memory to minimize storage:4753+// level 1: 65536 pointers to stb__memory_node (always uses 256 KB)4754+// level 2: each stb__memory_node represents a 64K block of memory4755+// with 256 stb__memory_leafs (worst case 64MB)4756+// level 3: each stb__memory_leaf represents 256 bytes of memory4757+// using a list of target locations and a list of pointers4758+// (which are hopefully fairly short normally!)4759+4760+// this approach won't work in 64-bit, which has a much larger address4761+// space. need to redesign4762+4763+#define STB__NPTR_ROOT_LOG2 164764+#define STB__NPTR_ROOT_NUM (1 << STB__NPTR_ROOT_LOG2)4765+#define STB__NPTR_ROOT_SHIFT (32 - STB__NPTR_ROOT_LOG2)4766+4767+#define STB__NPTR_NODE_LOG2 54768+#define STB__NPTR_NODE_NUM (1 << STB__NPTR_NODE_LOG2)4769+#define STB__NPTR_NODE_MASK (STB__NPTR_NODE_NUM-1)4770+#define STB__NPTR_NODE_SHIFT (STB__NPTR_ROOT_SHIFT - STB__NPTR_NODE_LOG2)4771+#define STB__NPTR_NODE_OFFSET(x) (((x) >> STB__NPTR_NODE_SHIFT) & STB__NPTR_NODE_MASK)4772+4773+typedef struct stb__st_nptr4774+{4775+ void *ptr; // address of actual pointer4776+ struct stb__st_nptr *next; // next pointer with same target4777+ struct stb__st_nptr **prev; // prev pointer with same target, address of 'next' field (or first)4778+ struct stb__st_nptr *next_in_block;4779+} stb__nptr;4780+4781+typedef struct stb__st_nptr_target4782+{4783+ void *ptr; // address of target4784+ stb__nptr *first; // address of first nptr pointing to this4785+ struct stb__st_nptr_target *next_in_block;4786+} stb__nptr_target;4787+4788+typedef struct4789+{4790+ stb__nptr *pointers;4791+ stb__nptr_target *targets;4792+} stb__memory_leaf;4793+4794+typedef struct4795+{4796+ stb__memory_leaf *children[STB__NPTR_NODE_NUM];4797+} stb__memory_node;4798+4799+stb__memory_node *stb__memtab_root[STB__NPTR_ROOT_NUM];4800+4801+static stb__memory_leaf *stb__nptr_find_leaf(void *mem)4802+{4803+ stb_uint32 address = (stb_uint32) mem;4804+ stb__memory_node *z = stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT];4805+ if (z)4806+ return z->children[STB__NPTR_NODE_OFFSET(address)];4807+ else4808+ return NULL;4809+}4810+4811+static void * stb__nptr_alloc(int size)4812+{4813+ return stb__realloc_raw(0,size);4814+}4815+4816+static void stb__nptr_free(void *p)4817+{4818+ stb__realloc_raw(p,0);4819+}4820+4821+static stb__memory_leaf *stb__nptr_make_leaf(void *mem)4822+{4823+ stb_uint32 address = (stb_uint32) mem;4824+ stb__memory_node *z = stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT];4825+ stb__memory_leaf *f;4826+ if (!z) {4827+ int i;4828+ z = (stb__memory_node *) stb__nptr_alloc(sizeof(*stb__memtab_root[0]));4829+ stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT] = z;4830+ for (i=0; i < 256; ++i)4831+ z->children[i] = 0;4832+ }4833+ f = (stb__memory_leaf *) stb__nptr_alloc(sizeof(*f));4834+ z->children[STB__NPTR_NODE_OFFSET(address)] = f;4835+ f->pointers = NULL;4836+ f->targets = NULL;4837+ return f;4838+}4839+4840+static stb__nptr_target *stb__nptr_find_target(void *target, int force)4841+{4842+ stb__memory_leaf *p = stb__nptr_find_leaf(target);4843+ if (p) {4844+ stb__nptr_target *t = p->targets;4845+ while (t) {4846+ if (t->ptr == target)4847+ return t;4848+ t = t->next_in_block;4849+ }4850+ }4851+ if (force) {4852+ stb__nptr_target *t = (stb__nptr_target*) stb__nptr_alloc(sizeof(*t));4853+ if (!p) p = stb__nptr_make_leaf(target);4854+ t->ptr = target;4855+ t->first = NULL;4856+ t->next_in_block = p->targets;4857+ p->targets = t;4858+ return t;4859+ } else4860+ return NULL;4861+}4862+4863+static stb__nptr *stb__nptr_find_pointer(void *ptr, int force)4864+{4865+ stb__memory_leaf *p = stb__nptr_find_leaf(ptr);4866+ if (p) {4867+ stb__nptr *t = p->pointers;4868+ while (t) {4869+ if (t->ptr == ptr)4870+ return t;4871+ t = t->next_in_block;4872+ }4873+ }4874+ if (force) {4875+ stb__nptr *t = (stb__nptr *) stb__nptr_alloc(sizeof(*t));4876+ if (!p) p = stb__nptr_make_leaf(ptr);4877+ t->ptr = ptr;4878+ t->next = NULL;4879+ t->prev = NULL;4880+ t->next_in_block = p->pointers;4881+ p->pointers = t;4882+ return t;4883+ } else4884+ return NULL;4885+}4886+4887+void stb_nptr_set(void *address_of_pointer, void *value_to_write)4888+{4889+ if (*(void **)address_of_pointer != value_to_write) {4890+ *(void **) address_of_pointer = value_to_write;4891+ stb_nptr_didset(address_of_pointer);4892+ }4893+}4894+4895+void stb_nptr_didset(void *address_of_pointer)4896+{4897+ // first unlink from old chain4898+ void *new_address;4899+ stb__nptr *p = stb__nptr_find_pointer(address_of_pointer, 1); // force building if doesn't exist4900+ if (p->prev) { // if p->prev is NULL, we just built it, or it was NULL4901+ *(p->prev) = p->next;4902+ if (p->next) p->next->prev = p->prev;4903+ }4904+ // now add to new chain4905+ new_address = *(void **)address_of_pointer;4906+ if (new_address != NULL) {4907+ stb__nptr_target *t = stb__nptr_find_target(new_address, 1);4908+ p->next = t->first;4909+ if (p->next) p->next->prev = &p->next;4910+ p->prev = &t->first;4911+ t->first = p;4912+ } else {4913+ p->prev = NULL;4914+ p->next = NULL;4915+ }4916+}4917+4918+void stb__nptr_block(void *address, int len, void (*function)(stb__memory_leaf *f, int datum, void *start, void *end), int datum)4919+{4920+ void *end_address = (void *) ((char *) address + len - 1);4921+ stb__memory_node *n;4922+ stb_uint32 start = (stb_uint32) address;4923+ stb_uint32 end = start + len - 1;4924+4925+ int b0 = start >> STB__NPTR_ROOT_SHIFT;4926+ int b1 = end >> STB__NPTR_ROOT_SHIFT;4927+ int b=b0,i,e0,e1;4928+4929+ e0 = STB__NPTR_NODE_OFFSET(start);4930+4931+ if (datum <= 0) {4932+ // first block4933+ n = stb__memtab_root[b0];4934+ if (n) {4935+ if (b0 != b1)4936+ e1 = STB__NPTR_NODE_NUM-1;4937+ else4938+ e1 = STB__NPTR_NODE_OFFSET(end);4939+ for (i=e0; i <= e1; ++i)4940+ if (n->children[i])4941+ function(n->children[i], datum, address, end_address);4942+ }4943+ if (b1 > b0) {4944+ // blocks other than the first and last block4945+ for (b=b0+1; b < b1; ++b) {4946+ n = stb__memtab_root[b];4947+ if (n)4948+ for (i=0; i <= STB__NPTR_NODE_NUM-1; ++i)4949+ if (n->children[i])4950+ function(n->children[i], datum, address, end_address);4951+ }4952+ // last block4953+ n = stb__memtab_root[b1];4954+ if (n) {4955+ e1 = STB__NPTR_NODE_OFFSET(end);4956+ for (i=0; i <= e1; ++i)4957+ if (n->children[i])4958+ function(n->children[i], datum, address, end_address);4959+ }4960+ }4961+ } else {4962+ if (b1 > b0) {4963+ // last block4964+ n = stb__memtab_root[b1];4965+ if (n) {4966+ e1 = STB__NPTR_NODE_OFFSET(end);4967+ for (i=e1; i >= 0; --i)4968+ if (n->children[i])4969+ function(n->children[i], datum, address, end_address);4970+ }4971+ // blocks other than the first and last block4972+ for (b=b1-1; b > b0; --b) {4973+ n = stb__memtab_root[b];4974+ if (n)4975+ for (i=STB__NPTR_NODE_NUM-1; i >= 0; --i)4976+ if (n->children[i])4977+ function(n->children[i], datum, address, end_address);4978+ }4979+ }4980+ // first block4981+ n = stb__memtab_root[b0];4982+ if (n) {4983+ if (b0 != b1)4984+ e1 = STB__NPTR_NODE_NUM-1;4985+ else4986+ e1 = STB__NPTR_NODE_OFFSET(end);4987+ for (i=e1; i >= e0; --i)4988+ if (n->children[i])4989+ function(n->children[i], datum, address, end_address);4990+ }4991+ }4992+}4993+4994+static void stb__nptr_delete_pointers(stb__memory_leaf *f, int offset, void *start, void *end)4995+{4996+ stb__nptr **p = &f->pointers;4997+ while (*p) {4998+ stb__nptr *n = *p;4999+ if (n->ptr >= start && n->ptr <= end) {5000+ // unlink5001+ if (n->prev) {5002+ *(n->prev) = n->next;5003+ if (n->next) n->next->prev = n->prev;5004+ }5005+ *p = n->next_in_block;5006+ stb__nptr_free(n);5007+ } else5008+ p = &(n->next_in_block);5009+ }5010+}5011+5012+static void stb__nptr_delete_targets(stb__memory_leaf *f, int offset, void *start, void *end)5013+{5014+ stb__nptr_target **p = &f->targets;5015+ while (*p) {5016+ stb__nptr_target *n = *p;5017+ if (n->ptr >= start && n->ptr <= end) {5018+ // null pointers5019+ stb__nptr *z = n->first;5020+ while (z) {5021+ stb__nptr *y = z->next;5022+ z->prev = NULL;5023+ z->next = NULL;5024+ *(void **) z->ptr = NULL;5025+ z = y;5026+ }5027+ // unlink this target5028+ *p = n->next_in_block;5029+ stb__nptr_free(n);5030+ } else5031+ p = &(n->next_in_block);5032+ }5033+}5034+5035+void stb_nptr_didfree(void *address_being_freed, int len)5036+{5037+ // step one: delete all pointers in this block5038+ stb__nptr_block(address_being_freed, len, stb__nptr_delete_pointers, 0);5039+ // step two: NULL all pointers to this block; do this second to avoid NULLing deleted pointers5040+ stb__nptr_block(address_being_freed, len, stb__nptr_delete_targets, 0);5041+}5042+5043+void stb_nptr_free(void *address_being_freed, int len)5044+{5045+ free(address_being_freed);5046+ stb_nptr_didfree(address_being_freed, len);5047+}5048+5049+static void stb__nptr_move_targets(stb__memory_leaf *f, int offset, void *start, void *end)5050+{5051+ stb__nptr_target **t = &f->targets;5052+ while (*t) {5053+ stb__nptr_target *n = *t;5054+ if (n->ptr >= start && n->ptr <= end) {5055+ stb__nptr *z;5056+ stb__memory_leaf *f;5057+ // unlink n5058+ *t = n->next_in_block;5059+ // update n to new address5060+ n->ptr = (void *) ((char *) n->ptr + offset);5061+ f = stb__nptr_find_leaf(n->ptr);5062+ if (!f) f = stb__nptr_make_leaf(n->ptr);5063+ n->next_in_block = f->targets;5064+ f->targets = n;5065+ // now go through all pointers and make them point here5066+ z = n->first;5067+ while (z) {5068+ *(void**) z->ptr = n->ptr;5069+ z = z->next;5070+ }5071+ } else5072+ t = &(n->next_in_block);5073+ }5074+}5075+5076+static void stb__nptr_move_pointers(stb__memory_leaf *f, int offset, void *start, void *end)5077+{5078+ stb__nptr **p = &f->pointers;5079+ while (*p) {5080+ stb__nptr *n = *p;5081+ if (n->ptr >= start && n->ptr <= end) {5082+ // unlink5083+ *p = n->next_in_block;5084+ n->ptr = (void *) ((int) n->ptr + offset);5085+ // move to new block5086+ f = stb__nptr_find_leaf(n->ptr);5087+ if (!f) f = stb__nptr_make_leaf(n->ptr);5088+ n->next_in_block = f->pointers;5089+ f->pointers = n;5090+ } else5091+ p = &(n->next_in_block);5092+ }5093+}5094+5095+void stb_nptr_realloc(void *new_address, void *old_address, int len)5096+{5097+ if (new_address == old_address) return;5098+5099+ // have to move the pointers first, because moving the targets5100+ // requires writing to the pointers-to-the-targets, and if some of those moved too,5101+ // we need to make sure we don't write to the old memory5102+5103+ // step one: move all pointers within the block5104+ stb__nptr_block(old_address, len, stb__nptr_move_pointers, (char *) new_address - (char *) old_address);5105+ // step two: move all targets within the block5106+ stb__nptr_block(old_address, len, stb__nptr_move_targets, (char *) new_address - (char *) old_address);5107+}5108+5109+void stb_nptr_move(void *new_address, void *old_address)5110+{5111+ stb_nptr_realloc(new_address, old_address, 1);5112+}5113+5114+void stb_nptr_recache(void)5115+{5116+ int i,j;5117+ for (i=0; i < STB__NPTR_ROOT_NUM; ++i)5118+ if (stb__memtab_root[i])5119+ for (j=0; j < STB__NPTR_NODE_NUM; ++j)5120+ if (stb__memtab_root[i]->children[j]) {5121+ stb__nptr *p = stb__memtab_root[i]->children[j]->pointers;5122+ while (p) {5123+ stb_nptr_didset(p->ptr);5124+ p = p->next_in_block;5125+ }5126+ }5127+}5128+5129+#endif // STB_DEFINE5130+#endif // STB_NPTR5131+5132+5133+//////////////////////////////////////////////////////////////////////////////5134+//5135+// File Processing5136+//5137+5138+5139+#ifdef _WIN325140+ #define stb_rename(x,y) _wrename((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y))5141+#else5142+ #define stb_rename rename5143+#endif5144+5145+STB_EXTERN void stb_fput_varlen64(FILE *f, stb_uint64 v);5146+STB_EXTERN stb_uint64 stb_fget_varlen64(FILE *f);5147+STB_EXTERN int stb_size_varlen64(stb_uint64 v);5148+5149+5150+#define stb_filec (char *) stb_file5151+#define stb_fileu (unsigned char *) stb_file5152+STB_EXTERN void * stb_file(char *filename, size_t *length);5153+STB_EXTERN void * stb_file_max(char *filename, size_t *length);5154+STB_EXTERN size_t stb_filelen(FILE *f);5155+STB_EXTERN int stb_filewrite(char *filename, void *data, size_t length);5156+STB_EXTERN int stb_filewritestr(char *filename, char *data);5157+STB_EXTERN char ** stb_stringfile(char *filename, int *len);5158+STB_EXTERN char ** stb_stringfile_trimmed(char *name, int *len, char comm);5159+STB_EXTERN char * stb_fgets(char *buffer, int buflen, FILE *f);5160+STB_EXTERN char * stb_fgets_malloc(FILE *f);5161+STB_EXTERN int stb_fexists(char *filename);5162+STB_EXTERN int stb_fcmp(char *s1, char *s2);5163+STB_EXTERN int stb_feq(char *s1, char *s2);5164+STB_EXTERN time_t stb_ftimestamp(char *filename);5165+5166+STB_EXTERN int stb_fullpath(char *abs, int abs_size, char *rel);5167+STB_EXTERN FILE * stb_fopen(char *filename, const char *mode);5168+STB_EXTERN int stb_fclose(FILE *f, int keep);5169+5170+enum5171+{5172+ stb_keep_no = 0,5173+ stb_keep_yes = 1,5174+ stb_keep_if_different = 2,5175+};5176+5177+STB_EXTERN int stb_copyfile(char *src, char *dest);5178+5179+STB_EXTERN void stb_fput_varlen64(FILE *f, stb_uint64 v);5180+STB_EXTERN stb_uint64 stb_fget_varlen64(FILE *f);5181+STB_EXTERN int stb_size_varlen64(stb_uint64 v);5182+5183+STB_EXTERN void stb_fwrite32(FILE *f, stb_uint32 datum);5184+STB_EXTERN void stb_fput_varlen (FILE *f, int v);5185+STB_EXTERN void stb_fput_varlenu(FILE *f, unsigned int v);5186+STB_EXTERN int stb_fget_varlen (FILE *f);5187+STB_EXTERN stb_uint stb_fget_varlenu(FILE *f);5188+STB_EXTERN void stb_fput_ranged (FILE *f, int v, int b, stb_uint n);5189+STB_EXTERN int stb_fget_ranged (FILE *f, int b, stb_uint n);5190+STB_EXTERN int stb_size_varlen (int v);5191+STB_EXTERN int stb_size_varlenu(unsigned int v);5192+STB_EXTERN int stb_size_ranged (int b, stb_uint n);5193+5194+STB_EXTERN int stb_fread(void *data, size_t len, size_t count, void *f);5195+STB_EXTERN int stb_fwrite(void *data, size_t len, size_t count, void *f);5196+5197+#if 05198+typedef struct5199+{5200+ FILE *base_file;5201+ char *buffer;5202+ int buffer_size;5203+ int buffer_off;5204+ int buffer_left;5205+} STBF;5206+5207+STB_EXTERN STBF *stb_tfopen(char *filename, char *mode);5208+STB_EXTERN int stb_tfread(void *data, size_t len, size_t count, STBF *f);5209+STB_EXTERN int stb_tfwrite(void *data, size_t len, size_t count, STBF *f);5210+#endif5211+5212+#ifdef STB_DEFINE5213+5214+#if 05215+STBF *stb_tfopen(char *filename, char *mode)5216+{5217+ STBF *z;5218+ FILE *f = stb_p_fopen(filename, mode);5219+ if (!f) return NULL;5220+ z = (STBF *) malloc(sizeof(*z));5221+ if (!z) { fclose(f); return NULL; }5222+ z->base_file = f;5223+ if (!strcmp(mode, "rb") || !strcmp(mode, "wb")) {5224+ z->buffer_size = 4096;5225+ z->buffer_off = z->buffer_size;5226+ z->buffer_left = 0;5227+ z->buffer = malloc(z->buffer_size);5228+ if (!z->buffer) { free(z); fclose(f); return NULL; }5229+ } else {5230+ z->buffer = 0;5231+ z->buffer_size = 0;5232+ z->buffer_left = 0;5233+ }5234+ return z;5235+}5236+5237+int stb_tfread(void *data, size_t len, size_t count, STBF *f)5238+{5239+ int total = len*count, done=0;5240+ if (!total) return 0;5241+ if (total <= z->buffer_left) {5242+ memcpy(data, z->buffer + z->buffer_off, total);5243+ z->buffer_off += total;5244+ z->buffer_left -= total;5245+ return count;5246+ } else {5247+ char *out = (char *) data;5248+5249+ // consume all buffered data5250+ memcpy(data, z->buffer + z->buffer_off, z->buffer_left);5251+ done = z->buffer_left;5252+ out += z->buffer_left;5253+ z->buffer_left=0;5254+5255+ if (total-done > (z->buffer_size >> 1)) {5256+ done += fread(out5257+ }5258+ }5259+}5260+#endif5261+5262+void stb_fwrite32(FILE *f, stb_uint32 x)5263+{5264+ fwrite(&x, 4, 1, f);5265+}5266+5267+#if defined(_WIN32)5268+ #define stb__stat _stat5269+#else5270+ #define stb__stat stat5271+#endif5272+5273+int stb_fexists(char *filename)5274+{5275+ struct stb__stat buf;5276+ return stb__windows(5277+ _wstat((const wchar_t *)stb__from_utf8(filename), &buf),5278+ stat(filename,&buf)5279+ ) == 0;5280+}5281+5282+time_t stb_ftimestamp(char *filename)5283+{5284+ struct stb__stat buf;5285+ if (stb__windows(5286+ _wstat((const wchar_t *)stb__from_utf8(filename), &buf),5287+ stat(filename,&buf)5288+ ) == 0)5289+ {5290+ return buf.st_mtime;5291+ } else {5292+ return 0;5293+ }5294+}5295+5296+size_t stb_filelen(FILE *f)5297+{5298+ long len, pos;5299+ pos = ftell(f);5300+ fseek(f, 0, SEEK_END);5301+ len = ftell(f);5302+ fseek(f, pos, SEEK_SET);5303+ return (size_t) len;5304+}5305+5306+void *stb_file(char *filename, size_t *length)5307+{5308+ FILE *f = stb__fopen(filename, "rb");5309+ char *buffer;5310+ size_t len, len2;5311+ if (!f) return NULL;5312+ len = stb_filelen(f);5313+ buffer = (char *) malloc(len+2); // nul + extra5314+ len2 = fread(buffer, 1, len, f);5315+ if (len2 == len) {5316+ if (length) *length = len;5317+ buffer[len] = 0;5318+ } else {5319+ free(buffer);5320+ buffer = NULL;5321+ }5322+ fclose(f);5323+ return buffer;5324+}5325+5326+int stb_filewrite(char *filename, void *data, size_t length)5327+{5328+ FILE *f = stb_fopen(filename, "wb");5329+ if (f) {5330+ unsigned char *data_ptr = (unsigned char *) data;5331+ size_t remaining = length;5332+ while (remaining > 0) {5333+ size_t len2 = remaining > 65536 ? 65536 : remaining;5334+ size_t len3 = fwrite(data_ptr, 1, len2, f);5335+ if (len2 != len3) {5336+ fprintf(stderr, "Failed while writing %s\n", filename);5337+ break;5338+ }5339+ remaining -= len2;5340+ data_ptr += len2;5341+ }5342+ stb_fclose(f, stb_keep_if_different);5343+ }5344+ return f != NULL;5345+}5346+5347+int stb_filewritestr(char *filename, char *data)5348+{5349+ return stb_filewrite(filename, data, strlen(data));5350+}5351+5352+void * stb_file_max(char *filename, size_t *length)5353+{5354+ FILE *f = stb__fopen(filename, "rb");5355+ char *buffer;5356+ size_t len, maxlen;5357+ if (!f) return NULL;5358+ maxlen = *length;5359+ buffer = (char *) malloc(maxlen+1);5360+ len = fread(buffer, 1, maxlen, f);5361+ buffer[len] = 0;5362+ fclose(f);5363+ *length = len;5364+ return buffer;5365+}5366+5367+char ** stb_stringfile(char *filename, int *plen)5368+{5369+ FILE *f = stb__fopen(filename, "rb");5370+ char *buffer, **list=NULL, *s;5371+ size_t len, count, i;5372+5373+ if (!f) return NULL;5374+ len = stb_filelen(f);5375+ buffer = (char *) malloc(len+1);5376+ len = fread(buffer, 1, len, f);5377+ buffer[len] = 0;5378+ fclose(f);5379+5380+ // two passes through: first time count lines, second time set them5381+ for (i=0; i < 2; ++i) {5382+ s = buffer;5383+ if (i == 1)5384+ list[0] = s;5385+ count = 1;5386+ while (*s) {5387+ if (*s == '\n' || *s == '\r') {5388+ // detect if both cr & lf are together5389+ int crlf = (s[0] + s[1]) == ('\n' + '\r');5390+ if (i == 1) *s = 0;5391+ if (crlf) ++s;5392+ if (s[1]) { // it's not over yet5393+ if (i == 1) list[count] = s+1;5394+ ++count;5395+ }5396+ }5397+ ++s;5398+ }5399+ if (i == 0) {5400+ list = (char **) malloc(sizeof(*list) * (count+1) + len+1);5401+ if (!list) return NULL;5402+ list[count] = 0;5403+ // recopy the file so there's just a single allocation to free5404+ memcpy(&list[count+1], buffer, len+1);5405+ free(buffer);5406+ buffer = (char *) &list[count+1];5407+ if (plen) *plen = (int) count;5408+ }5409+ }5410+ return list;5411+}5412+5413+char ** stb_stringfile_trimmed(char *name, int *len, char comment)5414+{5415+ int i,n,o=0;5416+ char **s = stb_stringfile(name, &n);5417+ if (s == NULL) return NULL;5418+ for (i=0; i < n; ++i) {5419+ char *p = stb_skipwhite(s[i]);5420+ if (*p && *p != comment)5421+ s[o++] = p;5422+ }5423+ s[o] = NULL;5424+ if (len) *len = o;5425+ return s;5426+}5427+5428+char * stb_fgets(char *buffer, int buflen, FILE *f)5429+{5430+ char *p;5431+ buffer[0] = 0;5432+ p = fgets(buffer, buflen, f);5433+ if (p) {5434+ int n = (int) (strlen(p)-1);5435+ if (n >= 0)5436+ if (p[n] == '\n')5437+ p[n] = 0;5438+ }5439+ return p;5440+}5441+5442+char * stb_fgets_malloc(FILE *f)5443+{5444+ // avoid reallocing for small strings5445+ char quick_buffer[800];5446+ quick_buffer[sizeof(quick_buffer)-2] = 0;5447+ if (!fgets(quick_buffer, sizeof(quick_buffer), f))5448+ return NULL;5449+5450+ if (quick_buffer[sizeof(quick_buffer)-2] == 0) {5451+ size_t n = strlen(quick_buffer);5452+ if (n > 0 && quick_buffer[n-1] == '\n')5453+ quick_buffer[n-1] = 0;5454+ return stb_p_strdup(quick_buffer);5455+ } else {5456+ char *p;5457+ char *a = stb_p_strdup(quick_buffer);5458+ size_t len = sizeof(quick_buffer)-1;5459+5460+ while (!feof(f)) {5461+ if (a[len-1] == '\n') break;5462+ a = (char *) realloc(a, len*2);5463+ p = &a[len];5464+ p[len-2] = 0;5465+ if (!fgets(p, (int) len, f))5466+ break;5467+ if (p[len-2] == 0) {5468+ len += strlen(p);5469+ break;5470+ }5471+ len = len + (len-1);5472+ }5473+ if (a[len-1] == '\n')5474+ a[len-1] = 0;5475+ return a;5476+ }5477+}5478+5479+int stb_fullpath(char *abs, int abs_size, char *rel)5480+{5481+ #ifdef _WIN325482+ return _fullpath(abs, rel, abs_size) != NULL;5483+ #else5484+ if (rel[0] == '/' || rel[0] == '~') {5485+ if ((int) strlen(rel) >= abs_size)5486+ return 0;5487+ stb_p_strcpy_s(abs,65536,rel);5488+ return STB_TRUE;5489+ } else {5490+ int n;5491+ getcwd(abs, abs_size);5492+ n = strlen(abs);5493+ if (n+(int) strlen(rel)+2 <= abs_size) {5494+ abs[n] = '/';5495+ stb_p_strcpy_s(abs+n+1, 65536,rel);5496+ return STB_TRUE;5497+ } else {5498+ return STB_FALSE;5499+ }5500+ }5501+ #endif5502+}5503+5504+static int stb_fcmp_core(FILE *f, FILE *g)5505+{5506+ char buf1[1024],buf2[1024];5507+ int n1,n2, res=0;5508+5509+ while (1) {5510+ n1 = (int) fread(buf1, 1, sizeof(buf1), f);5511+ n2 = (int) fread(buf2, 1, sizeof(buf2), g);5512+ res = memcmp(buf1,buf2,stb_min(n1,n2));5513+ if (res)5514+ break;5515+ if (n1 != n2) {5516+ res = n1 < n2 ? -1 : 1;5517+ break;5518+ }5519+ if (n1 == 0)5520+ break;5521+ }5522+5523+ fclose(f);5524+ fclose(g);5525+ return res;5526+}5527+5528+int stb_fcmp(char *s1, char *s2)5529+{5530+ FILE *f = stb__fopen(s1, "rb");5531+ FILE *g = stb__fopen(s2, "rb");5532+5533+ if (f == NULL || g == NULL) {5534+ if (f) fclose(f);5535+ if (g) {5536+ fclose(g);5537+ return STB_TRUE;5538+ }5539+ return f != NULL;5540+ }5541+5542+ return stb_fcmp_core(f,g);5543+}5544+5545+int stb_feq(char *s1, char *s2)5546+{5547+ FILE *f = stb__fopen(s1, "rb");5548+ FILE *g = stb__fopen(s2, "rb");5549+5550+ if (f == NULL || g == NULL) {5551+ if (f) fclose(f);5552+ if (g) fclose(g);5553+ return f == g;5554+ }5555+5556+ // feq is faster because it shortcuts if they're different length5557+ if (stb_filelen(f) != stb_filelen(g)) {5558+ fclose(f);5559+ fclose(g);5560+ return 0;5561+ }5562+5563+ return !stb_fcmp_core(f,g);5564+}5565+5566+static stb_ptrmap *stb__files;5567+5568+typedef struct5569+{5570+ char *temp_name;5571+ char *name;5572+ int errors;5573+} stb__file_data;5574+5575+static FILE *stb__open_temp_file(char *temp_name, char *src_name, const char *mode)5576+{5577+ size_t p;5578+#ifdef _MSC_VER5579+ int j;5580+#endif5581+ FILE *f;5582+ // try to generate a temporary file in the same directory5583+ p = strlen(src_name)-1;5584+ while (p > 0 && src_name[p] != '/' && src_name[p] != '\\'5585+ && src_name[p] != ':' && src_name[p] != '~')5586+ --p;5587+ ++p;5588+5589+ memcpy(temp_name, src_name, p);5590+5591+ #ifdef _MSC_VER5592+ // try multiple times to make a temp file... just in5593+ // case some other process makes the name first5594+ for (j=0; j < 32; ++j) {5595+ stb_p_strcpy_s(temp_name+p, 65536, "stmpXXXXXX");5596+ if (!stb_p_mktemp(temp_name))5597+ return 0;5598+5599+ f = stb_p_fopen(temp_name, mode);5600+ if (f != NULL)5601+ break;5602+ }5603+ #else5604+ {5605+ stb_p_strcpy_s(temp_name+p, 65536, "stmpXXXXXX");5606+ #ifdef __MINGW32__5607+ int fd = open(stb_p_mktemp(temp_name), O_RDWR);5608+ #else5609+ int fd = mkstemp(temp_name);5610+ #endif5611+ if (fd == -1) return NULL;5612+ f = fdopen(fd, mode);5613+ if (f == NULL) {5614+ unlink(temp_name);5615+ close(fd);5616+ return NULL;5617+ }5618+ }5619+ #endif5620+ return f;5621+}5622+5623+5624+FILE * stb_fopen(char *filename, const char *mode)5625+{5626+ FILE *f;5627+ char name_full[4096];5628+ char temp_full[sizeof(name_full) + 12];5629+5630+ // @TODO: if the file doesn't exist, we can also use the fastpath here5631+ if (mode[0] != 'w' && !strchr(mode, '+'))5632+ return stb__fopen(filename, mode);5633+5634+ // save away the full path to the file so if the program5635+ // changes the cwd everything still works right! unix has5636+ // better ways to do this, but we have to work in windows5637+ name_full[0] = '\0'; // stb_fullpath reads name_full[0]5638+ if (stb_fullpath(name_full, sizeof(name_full), filename)==0)5639+ return 0;5640+5641+ f = stb__open_temp_file(temp_full, name_full, mode);5642+ if (f != NULL) {5643+ stb__file_data *d = (stb__file_data *) malloc(sizeof(*d));5644+ if (!d) { assert(0); /* NOTREACHED */fclose(f); return NULL; }5645+ if (stb__files == NULL) stb__files = stb_ptrmap_create();5646+ d->temp_name = stb_p_strdup(temp_full);5647+ d->name = stb_p_strdup(name_full);5648+ d->errors = 0;5649+ stb_ptrmap_add(stb__files, f, d);5650+ return f;5651+ }5652+5653+ return NULL;5654+}5655+5656+int stb_fclose(FILE *f, int keep)5657+{5658+ stb__file_data *d;5659+5660+ int ok = STB_FALSE;5661+ if (f == NULL) return 0;5662+5663+ if (ferror(f))5664+ keep = stb_keep_no;5665+5666+ fclose(f);5667+5668+ if (stb__files && stb_ptrmap_remove(stb__files, f, (void **) &d)) {5669+ if (stb__files->count == 0) {5670+ stb_ptrmap_destroy(stb__files);5671+ stb__files = NULL;5672+ }5673+ } else5674+ return STB_TRUE; // not special5675+5676+ if (keep == stb_keep_if_different) {5677+ // check if the files are identical5678+ if (stb_feq(d->name, d->temp_name)) {5679+ keep = stb_keep_no;5680+ ok = STB_TRUE; // report success if no change5681+ }5682+ }5683+5684+ if (keep == stb_keep_no) {5685+ remove(d->temp_name);5686+ } else {5687+ if (!stb_fexists(d->name)) {5688+ // old file doesn't exist, so just move the new file over it5689+ stb_rename(d->temp_name, d->name);5690+ } else {5691+ // don't delete the old file yet in case there are troubles! First rename it!5692+ char preserved_old_file[4096];5693+5694+ // generate a temp filename in the same directory (also creates it, which we don't need)5695+ FILE *dummy = stb__open_temp_file(preserved_old_file, d->name, "wb");5696+ if (dummy != NULL) {5697+ // we don't actually want the open file5698+ fclose(dummy);5699+5700+ // discard what we just created5701+ remove(preserved_old_file); // if this fails, there's nothing we can do, and following logic handles it as best as possible anyway5702+5703+ // move the existing file to the preserved name5704+ if (0 != stb_rename(d->name, preserved_old_file)) { // 0 on success5705+ // failed, state is:5706+ // filename -> old file5707+ // tempname -> new file5708+ // keep tempname around so we don't lose data5709+ } else {5710+ // state is:5711+ // preserved -> old file5712+ // tempname -> new file5713+ // move the new file to the old name5714+ if (0 == stb_rename(d->temp_name, d->name)) {5715+ // state is:5716+ // preserved -> old file5717+ // filename -> new file5718+ ok = STB_TRUE;5719+5720+ // 'filename -> new file' has always been the goal, so clean up5721+ remove(preserved_old_file); // nothing to be done if it fails5722+ } else {5723+ // couldn't rename, so try renaming preserved file back5724+5725+ // state is:5726+ // preserved -> old file5727+ // tempname -> new file5728+ stb_rename(preserved_old_file, d->name);5729+ // if the rename failed, there's nothing more we can do5730+ }5731+ }5732+ } else {5733+ // we couldn't get a temp filename. do this the naive way; the worst case failure here5734+ // leaves the filename pointing to nothing and the new file as a tempfile5735+ remove(d->name);5736+ stb_rename(d->temp_name, d->name);5737+ }5738+ }5739+ }5740+5741+ free(d->temp_name);5742+ free(d->name);5743+ free(d);5744+5745+ return ok;5746+}5747+5748+int stb_copyfile(char *src, char *dest)5749+{5750+ char raw_buffer[1024];5751+ char *buffer;5752+ int buf_size = 65536;5753+5754+ FILE *f, *g;5755+5756+ // if file already exists at destination, do nothing5757+ if (stb_feq(src, dest)) return STB_TRUE;5758+5759+ // open file5760+ f = stb__fopen(src, "rb");5761+ if (f == NULL) return STB_FALSE;5762+5763+ // open file for writing5764+ g = stb__fopen(dest, "wb");5765+ if (g == NULL) {5766+ fclose(f);5767+ return STB_FALSE;5768+ }5769+5770+ buffer = (char *) malloc(buf_size);5771+ if (buffer == NULL) {5772+ buffer = raw_buffer;5773+ buf_size = sizeof(raw_buffer);5774+ }5775+5776+ while (!feof(f)) {5777+ size_t n = fread(buffer, 1, buf_size, f);5778+ if (n != 0)5779+ fwrite(buffer, 1, n, g);5780+ }5781+5782+ fclose(f);5783+ if (buffer != raw_buffer)5784+ free(buffer);5785+5786+ fclose(g);5787+ return STB_TRUE;5788+}5789+5790+// varlen:5791+// v' = (v >> 31) + (v < 0 ? ~v : v)<<1; // small abs(v) => small v'5792+// output v as big endian v'+k for v' <= k:5793+// 1 byte : v' <= 0x00000080 ( -64 <= v < 64) 7 bits5794+// 2 bytes: v' <= 0x00004000 (-8192 <= v < 8192) 14 bits5795+// 3 bytes: v' <= 0x00200000 21 bits5796+// 4 bytes: v' <= 0x10000000 28 bits5797+// the number of most significant 1-bits in the first byte5798+// equals the number of bytes after the first5799+5800+#define stb__varlen_xform(v) (v<0 ? (~v << 1)+1 : (v << 1))5801+5802+int stb_size_varlen(int v) { return stb_size_varlenu(stb__varlen_xform(v)); }5803+int stb_size_varlenu(unsigned int v)5804+{5805+ if (v < 0x00000080) return 1;5806+ if (v < 0x00004000) return 2;5807+ if (v < 0x00200000) return 3;5808+ if (v < 0x10000000) return 4;5809+ return 5;5810+}5811+5812+void stb_fput_varlen(FILE *f, int v) { stb_fput_varlenu(f, stb__varlen_xform(v)); }5813+5814+void stb_fput_varlenu(FILE *f, unsigned int z)5815+{5816+ if (z >= 0x10000000) fputc(0xF0,f);5817+ if (z >= 0x00200000) fputc((z < 0x10000000 ? 0xE0 : 0)+(z>>24),f);5818+ if (z >= 0x00004000) fputc((z < 0x00200000 ? 0xC0 : 0)+(z>>16),f);5819+ if (z >= 0x00000080) fputc((z < 0x00004000 ? 0x80 : 0)+(z>> 8),f);5820+ fputc(z,f);5821+}5822+5823+#define stb_fgetc(f) ((unsigned char) fgetc(f))5824+5825+int stb_fget_varlen(FILE *f)5826+{5827+ unsigned int z = stb_fget_varlenu(f);5828+ return (z & 1) ? ~(z>>1) : (z>>1);5829+}5830+5831+unsigned int stb_fget_varlenu(FILE *f)5832+{5833+ unsigned int z;5834+ unsigned char d;5835+ d = stb_fgetc(f);5836+5837+ if (d >= 0x80) {5838+ if (d >= 0xc0) {5839+ if (d >= 0xe0) {5840+ if (d == 0xf0) z = stb_fgetc(f) << 24;5841+ else z = (d - 0xe0) << 24;5842+ z += stb_fgetc(f) << 16;5843+ }5844+ else5845+ z = (d - 0xc0) << 16;5846+ z += stb_fgetc(f) << 8;5847+ } else5848+ z = (d - 0x80) << 8;5849+ z += stb_fgetc(f);5850+ } else5851+ z = d;5852+ return z;5853+}5854+5855+stb_uint64 stb_fget_varlen64(FILE *f)5856+{5857+ stb_uint64 z;5858+ unsigned char d;5859+ d = stb_fgetc(f);5860+5861+ if (d >= 0x80) {5862+ if (d >= 0xc0) {5863+ if (d >= 0xe0) {5864+ if (d >= 0xf0) {5865+ if (d >= 0xf8) {5866+ if (d >= 0xfc) {5867+ if (d >= 0xfe) {5868+ if (d >= 0xff)5869+ z = (stb_uint64) stb_fgetc(f) << 56;5870+ else5871+ z = (stb_uint64) (d - 0xfe) << 56;5872+ z |= (stb_uint64) stb_fgetc(f) << 48;5873+ } else z = (stb_uint64) (d - 0xfc) << 48;5874+ z |= (stb_uint64) stb_fgetc(f) << 40;5875+ } else z = (stb_uint64) (d - 0xf8) << 40;5876+ z |= (stb_uint64) stb_fgetc(f) << 32;5877+ } else z = (stb_uint64) (d - 0xf0) << 32;5878+ z |= (stb_uint) stb_fgetc(f) << 24;5879+ } else z = (stb_uint) (d - 0xe0) << 24;5880+ z |= (stb_uint) stb_fgetc(f) << 16;5881+ } else z = (stb_uint) (d - 0xc0) << 16;5882+ z |= (stb_uint) stb_fgetc(f) << 8;5883+ } else z = (stb_uint) (d - 0x80) << 8;5884+ z |= stb_fgetc(f);5885+ } else5886+ z = d;5887+5888+ return (z & 1) ? ~(z >> 1) : (z >> 1);5889+}5890+5891+int stb_size_varlen64(stb_uint64 v)5892+{5893+ if (v < 0x00000080) return 1;5894+ if (v < 0x00004000) return 2;5895+ if (v < 0x00200000) return 3;5896+ if (v < 0x10000000) return 4;5897+ if (v < STB_IMM_UINT64(0x0000000800000000)) return 5;5898+ if (v < STB_IMM_UINT64(0x0000040000000000)) return 6;5899+ if (v < STB_IMM_UINT64(0x0002000000000000)) return 7;5900+ if (v < STB_IMM_UINT64(0x0100000000000000)) return 8;5901+ return 9;5902+}5903+5904+void stb_fput_varlen64(FILE *f, stb_uint64 v)5905+{5906+ stb_uint64 z = stb__varlen_xform(v);5907+ int first=1;5908+ if (z >= STB_IMM_UINT64(0x100000000000000)) {5909+ fputc(0xff,f);5910+ first=0;5911+ }5912+ if (z >= STB_IMM_UINT64(0x02000000000000)) fputc((first ? 0xFE : 0)+(char)(z>>56),f), first=0;5913+ if (z >= STB_IMM_UINT64(0x00040000000000)) fputc((first ? 0xFC : 0)+(char)(z>>48),f), first=0;5914+ if (z >= STB_IMM_UINT64(0x00000800000000)) fputc((first ? 0xF8 : 0)+(char)(z>>40),f), first=0;5915+ if (z >= STB_IMM_UINT64(0x00000010000000)) fputc((first ? 0xF0 : 0)+(char)(z>>32),f), first=0;5916+ if (z >= STB_IMM_UINT64(0x00000000200000)) fputc((first ? 0xE0 : 0)+(char)(z>>24),f), first=0;5917+ if (z >= STB_IMM_UINT64(0x00000000004000)) fputc((first ? 0xC0 : 0)+(char)(z>>16),f), first=0;5918+ if (z >= STB_IMM_UINT64(0x00000000000080)) fputc((first ? 0x80 : 0)+(char)(z>> 8),f), first=0;5919+ fputc((char)z,f);5920+}5921+5922+void stb_fput_ranged(FILE *f, int v, int b, stb_uint n)5923+{5924+ v -= b;5925+ if (n <= (1 << 31))5926+ assert((stb_uint) v < n);5927+ if (n > (1 << 24)) fputc(v >> 24, f);5928+ if (n > (1 << 16)) fputc(v >> 16, f);5929+ if (n > (1 << 8)) fputc(v >> 8, f);5930+ fputc(v,f);5931+}5932+5933+int stb_fget_ranged(FILE *f, int b, stb_uint n)5934+{5935+ unsigned int v=0;5936+ if (n > (1 << 24)) v += stb_fgetc(f) << 24;5937+ if (n > (1 << 16)) v += stb_fgetc(f) << 16;5938+ if (n > (1 << 8)) v += stb_fgetc(f) << 8;5939+ v += stb_fgetc(f);5940+ return b+v;5941+}5942+5943+int stb_size_ranged(int b, stb_uint n)5944+{5945+ if (n > (1 << 24)) return 4;5946+ if (n > (1 << 16)) return 3;5947+ if (n > (1 << 8)) return 2;5948+ return 1;5949+}5950+5951+void stb_fput_string(FILE *f, char *s)5952+{5953+ size_t len = strlen(s);5954+ stb_fput_varlenu(f, (unsigned int) len);5955+ fwrite(s, 1, len, f);5956+}5957+5958+// inverse of the above algorithm5959+char *stb_fget_string(FILE *f, void *p)5960+{5961+ char *s;5962+ int len = stb_fget_varlenu(f);5963+ if (len > 4096) return NULL;5964+ s = p ? stb_malloc_string(p, len+1) : (char *) malloc(len+1);5965+ fread(s, 1, len, f);5966+ s[len] = 0;5967+ return s;5968+}5969+5970+char *stb_strdup(char *str, void *pool)5971+{5972+ size_t len = strlen(str);5973+ char *p = stb_malloc_string(pool, len+1);5974+ stb_p_strcpy_s(p, len+1, str);5975+ return p;5976+}5977+5978+// strip the trailing '/' or '\\' from a directory so we can refer to it5979+// as a file for _stat()5980+char *stb_strip_final_slash(char *t)5981+{5982+ if (t[0]) {5983+ char *z = t + strlen(t) - 1;5984+ // *z is the last character5985+ if (*z == '\\' || *z == '/')5986+ if (z != t+2 || t[1] != ':') // but don't strip it if it's e.g. "c:/"5987+ *z = 0;5988+ if (*z == '\\')5989+ *z = '/'; // canonicalize to make sure it matches db5990+ }5991+ return t;5992+}5993+5994+char *stb_strip_final_slash_regardless(char *t)5995+{5996+ if (t[0]) {5997+ char *z = t + strlen(t) - 1;5998+ // *z is the last character5999+ if (*z == '\\' || *z == '/')6000+ *z = 0;6001+ if (*z == '\\')6002+ *z = '/'; // canonicalize to make sure it matches db6003+ }6004+ return t;6005+}6006+#endif6007+6008+//////////////////////////////////////////////////////////////////////////////6009+//6010+// Options parsing6011+//6012+6013+STB_EXTERN char **stb_getopt_param(int *argc, char **argv, char *param);6014+STB_EXTERN char **stb_getopt(int *argc, char **argv);6015+STB_EXTERN void stb_getopt_free(char **opts);6016+6017+#ifdef STB_DEFINE6018+6019+void stb_getopt_free(char **opts)6020+{6021+ int i;6022+ char ** o2 = opts;6023+ for (i=0; i < stb_arr_len(o2); ++i)6024+ free(o2[i]);6025+ stb_arr_free(o2);6026+}6027+6028+char **stb_getopt(int *argc, char **argv)6029+{6030+ return stb_getopt_param(argc, argv, (char*) "");6031+}6032+6033+char **stb_getopt_param(int *argc, char **argv, char *param)6034+{6035+ char ** opts=NULL;6036+ int i,j=1;6037+ for (i=1; i < *argc; ++i) {6038+ if (argv[i][0] != '-') {6039+ argv[j++] = argv[i];6040+ } else {6041+ if (argv[i][1] == 0) { // plain - == don't parse further options6042+ ++i;6043+ while (i < *argc)6044+ argv[j++] = argv[i++];6045+ break;6046+ } else if (argv[i][1] == '-') {6047+ // copy argument through including initial '-' for clarity6048+ stb_arr_push(opts, stb_p_strdup(argv[i]));6049+ } else {6050+ int k;6051+ char *q = argv[i]; // traverse options list6052+ for (k=1; q[k]; ++k) {6053+ char *s;6054+ if (strchr(param, q[k])) { // does it take a parameter?6055+ char *t = &q[k+1], z = q[k];6056+ size_t len=0;6057+ if (*t == 0) {6058+ if (i == *argc-1) { // takes a parameter, but none found6059+ *argc = 0;6060+ stb_getopt_free(opts);6061+ return NULL;6062+ }6063+ t = argv[++i];6064+ } else6065+ k += (int) strlen(t);6066+ len = strlen(t);6067+ s = (char *) malloc(len+2);6068+ if (!s) return NULL;6069+ s[0] = z;6070+ stb_p_strcpy_s(s+1, len+2, t);6071+ } else {6072+ // no parameter6073+ s = (char *) malloc(2);6074+ if (!s) return NULL;6075+ s[0] = q[k];6076+ s[1] = 0;6077+ }6078+ stb_arr_push(opts, s);6079+ }6080+ }6081+ }6082+ }6083+ stb_arr_push(opts, NULL);6084+ *argc = j;6085+ return opts;6086+}6087+#endif6088+6089+6090+//////////////////////////////////////////////////////////////////////////////6091+//6092+// Portable directory reading6093+//6094+6095+STB_EXTERN char **stb_readdir_files (char *dir);6096+STB_EXTERN char **stb_readdir_files_mask(char *dir, char *wild);6097+STB_EXTERN char **stb_readdir_subdirs(char *dir);6098+STB_EXTERN char **stb_readdir_subdirs_mask(char *dir, char *wild);6099+STB_EXTERN void stb_readdir_free (char **files);6100+STB_EXTERN char **stb_readdir_recursive(char *dir, char *filespec);6101+STB_EXTERN void stb_delete_directory_recursive(char *dir);6102+6103+#ifdef STB_DEFINE6104+6105+#ifdef _MSC_VER6106+#include <io.h>6107+#else6108+#include <unistd.h>6109+#include <dirent.h>6110+#endif6111+6112+void stb_readdir_free(char **files)6113+{6114+ char **f2 = files;6115+ int i;6116+ for (i=0; i < stb_arr_len(f2); ++i)6117+ free(f2[i]);6118+ stb_arr_free(f2);6119+}6120+6121+static int isdotdirname(char *name)6122+{6123+ if (name[0] == '.')6124+ return (name[1] == '.') ? !name[2] : !name[1];6125+ return 0;6126+}6127+6128+STB_EXTERN int stb_wildmatchi(char *expr, char *candidate);6129+static char **readdir_raw(char *dir, int return_subdirs, char *mask)6130+{6131+ char **results = NULL;6132+ char buffer[4096], with_slash[4096];6133+ size_t n;6134+6135+ #ifdef _MSC_VER6136+ stb__wchar *ws;6137+ struct _wfinddata_t data;6138+ #ifdef _WIN646139+ const intptr_t none = -1;6140+ intptr_t z;6141+ #else6142+ const long none = -1;6143+ long z;6144+ #endif6145+ #else // !_MSC_VER6146+ const DIR *none = NULL;6147+ DIR *z;6148+ #endif6149+6150+ n = stb_strscpy(buffer,dir,sizeof(buffer));6151+ if (!n || n >= sizeof(buffer))6152+ return NULL;6153+ stb_fixpath(buffer);6154+6155+ if (n > 0 && (buffer[n-1] != '/')) {6156+ buffer[n++] = '/';6157+ }6158+ buffer[n] = 0;6159+ if (!stb_strscpy(with_slash,buffer,sizeof(with_slash)))6160+ return NULL;6161+6162+ #ifdef _MSC_VER6163+ if (!stb_strscpy(buffer+n,"*.*",sizeof(buffer)-n))6164+ return NULL;6165+ ws = stb__from_utf8(buffer);6166+ z = _wfindfirst((wchar_t *)ws, &data);6167+ #else6168+ z = opendir(dir);6169+ #endif6170+6171+ if (z != none) {6172+ int nonempty = STB_TRUE;6173+ #ifndef _MSC_VER6174+ struct dirent *data = readdir(z);6175+ nonempty = (data != NULL);6176+ #endif6177+6178+ if (nonempty) {6179+6180+ do {6181+ int is_subdir;6182+ #ifdef _MSC_VER6183+ char *name = stb__to_utf8((stb__wchar *)data.name);6184+ if (name == NULL) {6185+ fprintf(stderr, "%s to convert '%S' to %s!\n", "Unable", data.name, "utf8");6186+ continue;6187+ }6188+ is_subdir = !!(data.attrib & _A_SUBDIR);6189+ #else6190+ char *name = data->d_name;6191+ if (!stb_strscpy(buffer+n,name,sizeof(buffer)-n))6192+ break;6193+ // Could follow DT_LNK, but would need to check for recursive links.6194+ is_subdir = !!(data->d_type & DT_DIR);6195+ #endif6196+6197+ if (is_subdir == return_subdirs) {6198+ if (!is_subdir || !isdotdirname(name)) {6199+ if (!mask || stb_wildmatchi(mask, name)) {6200+ char buffer[4096],*p=buffer;6201+ if ( stb_snprintf(buffer, sizeof(buffer), "%s%s", with_slash, name) < 0 )6202+ break;6203+ if (buffer[0] == '.' && buffer[1] == '/')6204+ p = buffer+2;6205+ stb_arr_push(results, stb_p_strdup(p));6206+ }6207+ }6208+ }6209+ }6210+ #ifdef _MSC_VER6211+ while (0 == _wfindnext(z, &data));6212+ #else6213+ while ((data = readdir(z)) != NULL);6214+ #endif6215+ }6216+ #ifdef _MSC_VER6217+ _findclose(z);6218+ #else6219+ closedir(z);6220+ #endif6221+ }6222+ return results;6223+}6224+6225+char **stb_readdir_files (char *dir) { return readdir_raw(dir, 0, NULL); }6226+char **stb_readdir_subdirs(char *dir) { return readdir_raw(dir, 1, NULL); }6227+char **stb_readdir_files_mask(char *dir, char *wild) { return readdir_raw(dir, 0, wild); }6228+char **stb_readdir_subdirs_mask(char *dir, char *wild) { return readdir_raw(dir, 1, wild); }6229+6230+int stb__rec_max=0x7fffffff;6231+static char **stb_readdir_rec(char **sofar, char *dir, char *filespec)6232+{6233+ char **files;6234+ char ** dirs;6235+ char **p;6236+6237+ if (stb_arr_len(sofar) >= stb__rec_max) return sofar;6238+6239+ files = stb_readdir_files_mask(dir, filespec);6240+ stb_arr_for(p, files) {6241+ stb_arr_push(sofar, stb_p_strdup(*p));6242+ if (stb_arr_len(sofar) >= stb__rec_max) break;6243+ }6244+ stb_readdir_free(files);6245+ if (stb_arr_len(sofar) >= stb__rec_max) return sofar;6246+6247+ dirs = stb_readdir_subdirs(dir);6248+ stb_arr_for(p, dirs)6249+ sofar = stb_readdir_rec(sofar, *p, filespec);6250+ stb_readdir_free(dirs);6251+ return sofar;6252+}6253+6254+char **stb_readdir_recursive(char *dir, char *filespec)6255+{6256+ return stb_readdir_rec(NULL, dir, filespec);6257+}6258+6259+void stb_delete_directory_recursive(char *dir)6260+{6261+ char **list = stb_readdir_subdirs(dir);6262+ int i;6263+ for (i=0; i < stb_arr_len(list); ++i)6264+ stb_delete_directory_recursive(list[i]);6265+ stb_arr_free(list);6266+ list = stb_readdir_files(dir);6267+ for (i=0; i < stb_arr_len(list); ++i)6268+ if (!remove(list[i])) {6269+ // on windows, try again after making it writeable; don't ALWAYS6270+ // do this first since that would be slow in the normal case6271+ #ifdef _MSC_VER6272+ _chmod(list[i], _S_IWRITE);6273+ remove(list[i]);6274+ #endif6275+ }6276+ stb_arr_free(list);6277+ stb__windows(_rmdir,rmdir)(dir);6278+}6279+6280+#endif6281+6282+//////////////////////////////////////////////////////////////////////////////6283+//6284+// construct trees from filenames; useful for cmirror summaries6285+6286+typedef struct stb_dirtree2 stb_dirtree2;6287+6288+struct stb_dirtree26289+{6290+ stb_dirtree2 **subdirs;6291+6292+ // make convenient for stb_summarize_tree6293+ int num_subdir;6294+ float weight;6295+6296+ // actual data6297+ char *fullpath;6298+ char *relpath;6299+ char **files;6300+};6301+6302+STB_EXTERN stb_dirtree2 *stb_dirtree2_from_files_relative(char *src, char **filelist, int count);6303+STB_EXTERN stb_dirtree2 *stb_dirtree2_from_files(char **filelist, int count);6304+STB_EXTERN int stb_dir_is_prefix(char *dir, int dirlen, char *file);6305+6306+#ifdef STB_DEFINE6307+6308+int stb_dir_is_prefix(char *dir, int dirlen, char *file)6309+{6310+ if (dirlen == 0) return STB_TRUE;6311+ if (stb_strnicmp(dir, file, dirlen)) return STB_FALSE;6312+ if (file[dirlen] == '/' || file[dirlen] == '\\') return STB_TRUE;6313+ return STB_FALSE;6314+}6315+6316+stb_dirtree2 *stb_dirtree2_from_files_relative(char *src, char **filelist, int count)6317+{6318+ char buffer1[1024];6319+ int i;6320+ int dlen = (int) strlen(src), elen;6321+ stb_dirtree2 *d;6322+ char ** descendents = NULL;6323+ char ** files = NULL;6324+ char *s;6325+ if (!count) return NULL;6326+ // first find all the ones that belong here... note this is will take O(NM) with N files and M subdirs6327+ for (i=0; i < count; ++i) {6328+ if (stb_dir_is_prefix(src, dlen, filelist[i])) {6329+ stb_arr_push(descendents, filelist[i]);6330+ }6331+ }6332+ if (descendents == NULL)6333+ return NULL;6334+ elen = dlen;6335+ // skip a leading slash6336+ if (elen == 0 && (descendents[0][0] == '/' || descendents[0][0] == '\\'))6337+ ++elen;6338+ else if (elen)6339+ ++elen;6340+ // now extract all the ones that have their root here6341+ for (i=0; i < stb_arr_len(descendents);) {6342+ if (!stb_strchr2(descendents[i]+elen, '/', '\\')) {6343+ stb_arr_push(files, descendents[i]);6344+ descendents[i] = descendents[stb_arr_len(descendents)-1];6345+ stb_arr_pop(descendents);6346+ } else6347+ ++i;6348+ }6349+ // now create a record6350+ d = (stb_dirtree2 *) malloc(sizeof(*d));6351+ d->files = files;6352+ d->subdirs = NULL;6353+ d->fullpath = stb_p_strdup(src);6354+ s = stb_strrchr2(d->fullpath, '/', '\\');6355+ if (s)6356+ ++s;6357+ else6358+ s = d->fullpath;6359+ d->relpath = s;6360+ // now create the children6361+ qsort(descendents, stb_arr_len(descendents), sizeof(char *), stb_qsort_stricmp(0));6362+ buffer1[0] = 0;6363+ for (i=0; i < stb_arr_len(descendents); ++i) {6364+ char buffer2[1024];6365+ char *s = descendents[i] + elen, *t;6366+ t = stb_strchr2(s, '/', '\\');6367+ assert(t);6368+ stb_strncpy(buffer2, descendents[i], (int) (t-descendents[i]+1));6369+ if (stb_stricmp(buffer1, buffer2)) {6370+ stb_dirtree2 *t = stb_dirtree2_from_files_relative(buffer2, descendents, stb_arr_len(descendents));6371+ assert(t != NULL);6372+ stb_p_strcpy_s(buffer1, sizeof(buffer1), buffer2);6373+ stb_arr_push(d->subdirs, t);6374+ }6375+ }6376+ d->num_subdir = stb_arr_len(d->subdirs);6377+ d->weight = 0;6378+ return d;6379+}6380+6381+stb_dirtree2 *stb_dirtree2_from_files(char **filelist, int count)6382+{6383+ return stb_dirtree2_from_files_relative((char*) "", filelist, count);6384+}6385+#endif6386+6387+//////////////////////////////////////////////////////////////////////////////6388+//6389+// Checksums: CRC-32, ADLER32, SHA-16390+//6391+// CRC-32 and ADLER32 allow streaming blocks6392+// SHA-1 requires either a complete buffer, max size 2^32 - 736393+// or it can checksum directly from a file, max 2^616394+6395+#define STB_ADLER32_SEED 16396+#define STB_CRC32_SEED 0 // note that we logical NOT this in the code6397+6398+STB_EXTERN stb_uint6399+ stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen);6400+STB_EXTERN stb_uint6401+ stb_crc32_block(stb_uint crc32, stb_uchar *buffer, stb_uint len);6402+STB_EXTERN stb_uint stb_crc32(unsigned char *buffer, stb_uint len);6403+6404+STB_EXTERN void stb_sha1(6405+ unsigned char output[20], unsigned char *buffer, unsigned int len);6406+STB_EXTERN int stb_sha1_file(unsigned char output[20], char *file);6407+6408+STB_EXTERN void stb_sha1_readable(char display[27], unsigned char sha[20]);6409+6410+#ifdef STB_DEFINE6411+stb_uint stb_crc32_block(stb_uint crc, unsigned char *buffer, stb_uint len)6412+{6413+ static stb_uint crc_table[256];6414+ stb_uint i,j,s;6415+ crc = ~crc;6416+6417+ if (crc_table[1] == 0)6418+ for(i=0; i < 256; i++) {6419+ for (s=i, j=0; j < 8; ++j)6420+ s = (s >> 1) ^ (s & 1 ? 0xedb88320 : 0);6421+ crc_table[i] = s;6422+ }6423+ for (i=0; i < len; ++i)6424+ crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];6425+ return ~crc;6426+}6427+6428+stb_uint stb_crc32(unsigned char *buffer, stb_uint len)6429+{6430+ return stb_crc32_block(0, buffer, len);6431+}6432+6433+stb_uint stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen)6434+{6435+ const unsigned long ADLER_MOD = 65521;6436+ unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16;6437+ unsigned long blocklen, i;6438+6439+ blocklen = buflen % 5552;6440+ while (buflen) {6441+ for (i=0; i + 7 < blocklen; i += 8) {6442+ s1 += buffer[0], s2 += s1;6443+ s1 += buffer[1], s2 += s1;6444+ s1 += buffer[2], s2 += s1;6445+ s1 += buffer[3], s2 += s1;6446+ s1 += buffer[4], s2 += s1;6447+ s1 += buffer[5], s2 += s1;6448+ s1 += buffer[6], s2 += s1;6449+ s1 += buffer[7], s2 += s1;6450+6451+ buffer += 8;6452+ }6453+6454+ for (; i < blocklen; ++i)6455+ s1 += *buffer++, s2 += s1;6456+6457+ s1 %= ADLER_MOD, s2 %= ADLER_MOD;6458+ buflen -= blocklen;6459+ blocklen = 5552;6460+ }6461+ return (s2 << 16) + s1;6462+}6463+6464+static void stb__sha1(stb_uchar *chunk, stb_uint h[5])6465+{6466+ int i;6467+ stb_uint a,b,c,d,e;6468+ stb_uint w[80];6469+6470+ for (i=0; i < 16; ++i)6471+ w[i] = stb_big32(&chunk[i*4]);6472+ for (i=16; i < 80; ++i) {6473+ stb_uint t;6474+ t = w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16];6475+ w[i] = (t + t) | (t >> 31);6476+ }6477+6478+ a = h[0];6479+ b = h[1];6480+ c = h[2];6481+ d = h[3];6482+ e = h[4];6483+6484+ #define STB__SHA1(k,f) \6485+ { \6486+ stb_uint temp = (a << 5) + (a >> 27) + (f) + e + (k) + w[i]; \6487+ e = d; \6488+ d = c; \6489+ c = (b << 30) + (b >> 2); \6490+ b = a; \6491+ a = temp; \6492+ }6493+6494+ i=0;6495+ for (; i < 20; ++i) STB__SHA1(0x5a827999, d ^ (b & (c ^ d)) );6496+ for (; i < 40; ++i) STB__SHA1(0x6ed9eba1, b ^ c ^ d );6497+ for (; i < 60; ++i) STB__SHA1(0x8f1bbcdc, (b & c) + (d & (b ^ c)) );6498+ for (; i < 80; ++i) STB__SHA1(0xca62c1d6, b ^ c ^ d );6499+6500+ #undef STB__SHA16501+6502+ h[0] += a;6503+ h[1] += b;6504+ h[2] += c;6505+ h[3] += d;6506+ h[4] += e;6507+}6508+6509+void stb_sha1(stb_uchar output[20], stb_uchar *buffer, stb_uint len)6510+{6511+ unsigned char final_block[128];6512+ stb_uint end_start, final_len, j;6513+ int i;6514+6515+ stb_uint h[5];6516+6517+ h[0] = 0x67452301;6518+ h[1] = 0xefcdab89;6519+ h[2] = 0x98badcfe;6520+ h[3] = 0x10325476;6521+ h[4] = 0xc3d2e1f0;6522+6523+ // we need to write padding to the last one or two6524+ // blocks, so build those first into 'final_block'6525+6526+ // we have to write one special byte, plus the 8-byte length6527+6528+ // compute the block where the data runs out6529+ end_start = len & ~63;6530+6531+ // compute the earliest we can encode the length6532+ if (((len+9) & ~63) == end_start) {6533+ // it all fits in one block, so fill a second-to-last block6534+ end_start -= 64;6535+ }6536+6537+ final_len = end_start + 128;6538+6539+ // now we need to copy the data in6540+ assert(end_start + 128 >= len+9);6541+ assert(end_start < len || len < 64-9);6542+6543+ j = 0;6544+ if (end_start > len)6545+ j = (stb_uint) - (int) end_start;6546+6547+ for (; end_start + j < len; ++j)6548+ final_block[j] = buffer[end_start + j];6549+ final_block[j++] = 0x80;6550+ while (j < 128-5) // 5 byte length, so write 4 extra padding bytes6551+ final_block[j++] = 0;6552+ // big-endian size6553+ final_block[j++] = len >> 29;6554+ final_block[j++] = len >> 21;6555+ final_block[j++] = len >> 13;6556+ final_block[j++] = len >> 5;6557+ final_block[j++] = len << 3;6558+ assert(j == 128 && end_start + j == final_len);6559+6560+ for (j=0; j < final_len; j += 64) { // 512-bit chunks6561+ if (j+64 >= end_start+64)6562+ stb__sha1(&final_block[j - end_start], h);6563+ else6564+ stb__sha1(&buffer[j], h);6565+ }6566+6567+ for (i=0; i < 5; ++i) {6568+ output[i*4 + 0] = h[i] >> 24;6569+ output[i*4 + 1] = h[i] >> 16;6570+ output[i*4 + 2] = h[i] >> 8;6571+ output[i*4 + 3] = h[i] >> 0;6572+ }6573+}6574+6575+#ifdef _MSC_VER6576+int stb_sha1_file(stb_uchar output[20], char *file)6577+{6578+ int i;6579+ stb_uint64 length=0;6580+ unsigned char buffer[128];6581+6582+ FILE *f = stb__fopen(file, "rb");6583+ stb_uint h[5];6584+6585+ if (f == NULL) return 0; // file not found6586+6587+ h[0] = 0x67452301;6588+ h[1] = 0xefcdab89;6589+ h[2] = 0x98badcfe;6590+ h[3] = 0x10325476;6591+ h[4] = 0xc3d2e1f0;6592+6593+ for(;;) {6594+ size_t n = fread(buffer, 1, 64, f);6595+ if (n == 64) {6596+ stb__sha1(buffer, h);6597+ length += n;6598+ } else {6599+ int block = 64;6600+6601+ length += n;6602+6603+ buffer[n++] = 0x80;6604+6605+ // if there isn't enough room for the length, double the block6606+ if (n + 8 > 64)6607+ block = 128;6608+6609+ // pad to end6610+ memset(buffer+n, 0, block-8-n);6611+6612+ i = block - 8;6613+ buffer[i++] = (stb_uchar) (length >> 53);6614+ buffer[i++] = (stb_uchar) (length >> 45);6615+ buffer[i++] = (stb_uchar) (length >> 37);6616+ buffer[i++] = (stb_uchar) (length >> 29);6617+ buffer[i++] = (stb_uchar) (length >> 21);6618+ buffer[i++] = (stb_uchar) (length >> 13);6619+ buffer[i++] = (stb_uchar) (length >> 5);6620+ buffer[i++] = (stb_uchar) (length << 3);6621+ assert(i == block);6622+ stb__sha1(buffer, h);6623+ if (block == 128)6624+ stb__sha1(buffer+64, h);6625+ else6626+ assert(block == 64);6627+ break;6628+ }6629+ }6630+ fclose(f);6631+6632+ for (i=0; i < 5; ++i) {6633+ output[i*4 + 0] = h[i] >> 24;6634+ output[i*4 + 1] = h[i] >> 16;6635+ output[i*4 + 2] = h[i] >> 8;6636+ output[i*4 + 3] = h[i] >> 0;6637+ }6638+6639+ return 1;6640+}6641+#endif // _MSC_VER6642+6643+// client can truncate this wherever they like6644+void stb_sha1_readable(char display[27], unsigned char sha[20])6645+{6646+ char encoding[65] = "0123456789abcdefghijklmnopqrstuv"6647+ "wxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%$";6648+ int num_bits = 0, acc=0;6649+ int i=0,o=0;6650+ while (o < 26) {6651+ int v;6652+ // expand the accumulator6653+ if (num_bits < 6) {6654+ assert(i != 20);6655+ acc += sha[i++] << num_bits;6656+ num_bits += 8;6657+ }6658+ v = acc & ((1 << 6) - 1);6659+ display[o++] = encoding[v];6660+ acc >>= 6;6661+ num_bits -= 6;6662+ }6663+ assert(num_bits == 20*8 - 26*6);6664+ display[o++] = encoding[acc];6665+}6666+6667+#endif // STB_DEFINE6668+6669+///////////////////////////////////////////////////////////6670+//6671+// simplified WINDOWS registry interface... hopefully6672+// we'll never actually use this?6673+6674+#if defined(_WIN32)6675+6676+STB_EXTERN void * stb_reg_open(const char *mode, const char *where); // mode: "rHKLM" or "rHKCU" or "w.."6677+STB_EXTERN void stb_reg_close(void *reg);6678+STB_EXTERN int stb_reg_read(void *zreg, const char *str, void *data, unsigned long len);6679+STB_EXTERN int stb_reg_read_string(void *zreg, const char *str, char *data, int len);6680+STB_EXTERN void stb_reg_write(void *zreg, const char *str, const void *data, unsigned long len);6681+STB_EXTERN void stb_reg_write_string(void *zreg, const char *str, const char *data);6682+6683+#if defined(STB_DEFINE) && !defined(STB_NO_REGISTRY)6684+6685+#define STB_HAS_REGISTRY6686+6687+#ifndef _WINDOWS_6688+6689+#define HKEY void *6690+6691+STB_EXTERN __declspec(dllimport) long __stdcall RegCloseKey ( HKEY hKey );6692+STB_EXTERN __declspec(dllimport) long __stdcall RegCreateKeyExA ( HKEY hKey, const char * lpSubKey,6693+ int Reserved, char * lpClass, int dwOptions,6694+ int samDesired, void *lpSecurityAttributes, HKEY * phkResult, int * lpdwDisposition );6695+STB_EXTERN __declspec(dllimport) long __stdcall RegDeleteKeyA ( HKEY hKey, const char * lpSubKey );6696+STB_EXTERN __declspec(dllimport) long __stdcall RegQueryValueExA ( HKEY hKey, const char * lpValueName,6697+ int * lpReserved, unsigned long * lpType, unsigned char * lpData, unsigned long * lpcbData );6698+STB_EXTERN __declspec(dllimport) long __stdcall RegSetValueExA ( HKEY hKey, const char * lpValueName,6699+ int Reserved, int dwType, const unsigned char* lpData, int cbData );6700+STB_EXTERN __declspec(dllimport) long __stdcall RegOpenKeyExA ( HKEY hKey, const char * lpSubKey,6701+ int ulOptions, int samDesired, HKEY * phkResult );6702+6703+#endif // _WINDOWS_6704+6705+#define STB__REG_OPTION_NON_VOLATILE 06706+#define STB__REG_KEY_ALL_ACCESS 0x000f003f6707+#define STB__REG_KEY_READ 0x000200196708+6709+#ifdef _M_AMD646710+#define STB__HKEY_CURRENT_USER 0x80000001ull6711+#define STB__HKEY_LOCAL_MACHINE 0x80000002ull6712+#else6713+#define STB__HKEY_CURRENT_USER 0x800000016714+#define STB__HKEY_LOCAL_MACHINE 0x800000026715+#endif6716+6717+void *stb_reg_open(const char *mode, const char *where)6718+{6719+ long res;6720+ HKEY base;6721+ HKEY zreg;6722+ if (!stb_stricmp(mode+1, "cu") || !stb_stricmp(mode+1, "hkcu"))6723+ base = (HKEY) STB__HKEY_CURRENT_USER;6724+ else if (!stb_stricmp(mode+1, "lm") || !stb_stricmp(mode+1, "hklm"))6725+ base = (HKEY) STB__HKEY_LOCAL_MACHINE;6726+ else6727+ return NULL;6728+6729+ if (mode[0] == 'r')6730+ res = RegOpenKeyExA(base, where, 0, STB__REG_KEY_READ, &zreg);6731+ else if (mode[0] == 'w')6732+ res = RegCreateKeyExA(base, where, 0, NULL, STB__REG_OPTION_NON_VOLATILE, STB__REG_KEY_ALL_ACCESS, NULL, &zreg, NULL);6733+ else6734+ return NULL;6735+6736+ return res ? NULL : zreg;6737+}6738+6739+void stb_reg_close(void *reg)6740+{6741+ RegCloseKey((HKEY) reg);6742+}6743+6744+#define STB__REG_SZ 16745+#define STB__REG_BINARY 36746+#define STB__REG_DWORD 46747+6748+int stb_reg_read(void *zreg, const char *str, void *data, unsigned long len)6749+{6750+ unsigned long type;6751+ unsigned long alen = len;6752+ if (0 == RegQueryValueExA((HKEY) zreg, str, 0, &type, (unsigned char *) data, &len))6753+ if (type == STB__REG_BINARY || type == STB__REG_SZ || type == STB__REG_DWORD) {6754+ if (len < alen)6755+ *((char *) data + len) = 0;6756+ return 1;6757+ }6758+ return 0;6759+}6760+6761+void stb_reg_write(void *zreg, const char *str, const void *data, unsigned long len)6762+{6763+ if (zreg)6764+ RegSetValueExA((HKEY) zreg, str, 0, STB__REG_BINARY, (const unsigned char *) data, len);6765+}6766+6767+int stb_reg_read_string(void *zreg, const char *str, char *data, int len)6768+{6769+ if (!stb_reg_read(zreg, str, data, len)) return 0;6770+ data[len-1] = 0; // force a 0 at the end of the string no matter what6771+ return 1;6772+}6773+6774+void stb_reg_write_string(void *zreg, const char *str, const char *data)6775+{6776+ if (zreg)6777+ RegSetValueExA((HKEY) zreg, str, 0, STB__REG_SZ, (const unsigned char *) data, (int) strlen(data)+1);6778+}6779+#endif // STB_DEFINE6780+#endif // _WIN326781+6782+6783+//////////////////////////////////////////////////////////////////////////////6784+//6785+// stb_cfg - This is like the registry, but the config info6786+// is all stored in plain old files where we can6787+// backup and restore them easily. The LOCATION of6788+// the config files is gotten from... the registry!6789+6790+#ifndef STB_NO_STB_STRINGS6791+typedef struct stb_cfg_st stb_cfg;6792+6793+STB_EXTERN stb_cfg * stb_cfg_open(char *config, const char *mode); // mode = "r", "w"6794+STB_EXTERN void stb_cfg_close(stb_cfg *cfg);6795+STB_EXTERN int stb_cfg_read(stb_cfg *cfg, char *key, void *value, int len);6796+STB_EXTERN void stb_cfg_write(stb_cfg *cfg, char *key, void *value, int len);6797+STB_EXTERN int stb_cfg_read_string(stb_cfg *cfg, char *key, char *value, int len);6798+STB_EXTERN void stb_cfg_write_string(stb_cfg *cfg, char *key, char *value);6799+STB_EXTERN int stb_cfg_delete(stb_cfg *cfg, char *key);6800+STB_EXTERN void stb_cfg_set_directory(char *dir);6801+6802+#ifdef STB_DEFINE6803+6804+typedef struct6805+{6806+ char *key;6807+ void *value;6808+ int value_len;6809+} stb__cfg_item;6810+6811+struct stb_cfg_st6812+{6813+ stb__cfg_item *data;6814+ char *loaded_file; // this needs to be freed6815+ FILE *f; // write the data to this file on close6816+};6817+6818+static const char *stb__cfg_sig = "sTbCoNfIg!\0\0";6819+static char stb__cfg_dir[512];6820+STB_EXTERN void stb_cfg_set_directory(char *dir)6821+{6822+ stb_p_strcpy_s(stb__cfg_dir, sizeof(stb__cfg_dir), dir);6823+}6824+6825+STB_EXTERN stb_cfg * stb_cfg_open(char *config, const char *mode)6826+{6827+ size_t len;6828+ stb_cfg *z;6829+ char file[512];6830+ if (mode[0] != 'r' && mode[0] != 'w') return NULL;6831+6832+ if (!stb__cfg_dir[0]) {6833+ #ifdef _WIN326834+ stb_p_strcpy_s(stb__cfg_dir, sizeof(stb__cfg_dir), "c:/stb");6835+ #else6836+ strcpy(stb__cfg_dir, "~/.stbconfig");6837+ #endif6838+6839+ #ifdef STB_HAS_REGISTRY6840+ {6841+ void *reg = stb_reg_open("rHKLM", "Software\\SilverSpaceship\\stb");6842+ if (reg) {6843+ stb_reg_read_string(reg, "config_dir", stb__cfg_dir, sizeof(stb__cfg_dir));6844+ stb_reg_close(reg);6845+ }6846+ }6847+ #endif6848+ }6849+6850+ stb_p_sprintf(file stb_p_size(sizeof(file)), "%s/%s.cfg", stb__cfg_dir, config);6851+6852+ z = (stb_cfg *) stb_malloc(0, sizeof(*z));6853+ z->data = NULL;6854+6855+ z->loaded_file = stb_filec(file, &len);6856+ if (z->loaded_file) {6857+ char *s = z->loaded_file;6858+ if (!memcmp(s, stb__cfg_sig, 12)) {6859+ char *s = z->loaded_file + 12;6860+ while (s < z->loaded_file + len) {6861+ stb__cfg_item a;6862+ int n = *(stb_int16 *) s;6863+ a.key = s+2;6864+ s = s+2 + n;6865+ a.value_len = *(int *) s;6866+ s += 4;6867+ a.value = s;6868+ s += a.value_len;6869+ stb_arr_push(z->data, a);6870+ }6871+ assert(s == z->loaded_file + len);6872+ }6873+ }6874+6875+ if (mode[0] == 'w')6876+ z->f = stb_p_fopen(file, "wb");6877+ else6878+ z->f = NULL;6879+6880+ return z;6881+}6882+6883+void stb_cfg_close(stb_cfg *z)6884+{6885+ if (z->f) {6886+ int i;6887+ // write the file out6888+ fwrite(stb__cfg_sig, 12, 1, z->f);6889+ for (i=0; i < stb_arr_len(z->data); ++i) {6890+ stb_int16 n = (stb_int16) strlen(z->data[i].key)+1;6891+ fwrite(&n, 2, 1, z->f);6892+ fwrite(z->data[i].key, n, 1, z->f);6893+ fwrite(&z->data[i].value_len, 4, 1, z->f);6894+ fwrite(z->data[i].value, z->data[i].value_len, 1, z->f);6895+ }6896+ fclose(z->f);6897+ }6898+ stb_arr_free(z->data);6899+ stb_free(z);6900+}6901+6902+int stb_cfg_read(stb_cfg *z, char *key, void *value, int len)6903+{6904+ int i;6905+ for (i=0; i < stb_arr_len(z->data); ++i) {6906+ if (!stb_stricmp(z->data[i].key, key)) {6907+ int n = stb_min(len, z->data[i].value_len);6908+ memcpy(value, z->data[i].value, n);6909+ if (n < len)6910+ *((char *) value + n) = 0;6911+ return 1;6912+ }6913+ }6914+ return 0;6915+}6916+6917+void stb_cfg_write(stb_cfg *z, char *key, void *value, int len)6918+{6919+ int i;6920+ for (i=0; i < stb_arr_len(z->data); ++i)6921+ if (!stb_stricmp(z->data[i].key, key))6922+ break;6923+ if (i == stb_arr_len(z->data)) {6924+ stb__cfg_item p;6925+ p.key = stb_strdup(key, z);6926+ p.value = NULL;6927+ p.value_len = 0;6928+ stb_arr_push(z->data, p);6929+ }6930+ z->data[i].value = stb_malloc(z, len);6931+ z->data[i].value_len = len;6932+ memcpy(z->data[i].value, value, len);6933+}6934+6935+int stb_cfg_delete(stb_cfg *z, char *key)6936+{6937+ int i;6938+ for (i=0; i < stb_arr_len(z->data); ++i)6939+ if (!stb_stricmp(z->data[i].key, key)) {6940+ stb_arr_fastdelete(z->data, i);6941+ return 1;6942+ }6943+ return 0;6944+}6945+6946+int stb_cfg_read_string(stb_cfg *z, char *key, char *value, int len)6947+{6948+ if (!stb_cfg_read(z, key, value, len)) return 0;6949+ value[len-1] = 0;6950+ return 1;6951+}6952+6953+void stb_cfg_write_string(stb_cfg *z, char *key, char *value)6954+{6955+ stb_cfg_write(z, key, value, (int) strlen(value)+1);6956+}6957+#endif6958+6959+//////////////////////////////////////////////////////////////////////////////6960+//6961+// stb_dirtree - load a description of a directory tree6962+// uses a cache and stat()s the directories for changes6963+// MUCH faster on NTFS, _wrong_ on FAT32, so should6964+// ignore the db on FAT326965+6966+#ifdef _WIN326967+6968+typedef struct6969+{6970+ char * path; // full path from passed-in root6971+ time_t last_modified;6972+ int num_files;6973+ int flag;6974+} stb_dirtree_dir;6975+6976+typedef struct6977+{6978+ char *name; // name relative to path6979+ int dir; // index into dirs[] array6980+ stb_int64 size; // size, max 4GB6981+ time_t last_modified;6982+ int flag;6983+} stb_dirtree_file;6984+6985+typedef struct6986+{6987+ stb_dirtree_dir *dirs;6988+ stb_dirtree_file *files;6989+6990+ // internal use6991+ void * string_pool; // used to free data en masse6992+} stb_dirtree;6993+6994+extern void stb_dirtree_free ( stb_dirtree *d );6995+extern stb_dirtree *stb_dirtree_get ( char *dir);6996+extern stb_dirtree *stb_dirtree_get_dir ( char *dir, char *cache_dir);6997+extern stb_dirtree *stb_dirtree_get_with_file ( char *dir, char *cache_file);6998+6999+// get a list of all the files recursively underneath 'dir'7000+//7001+// cache_file is used to store a copy of the directory tree to speed up7002+// later calls. It must be unique to 'dir' and the current working7003+// directory! Otherwise who knows what will happen (a good solution7004+// is to put it _in_ dir, but this API doesn't force that).7005+//7006+// Also, it might be possible to break this if you have two different processes7007+// do a call to stb_dirtree_get() with the same cache file at about the same7008+// time, but I _think_ it might just work.7009+7010+// i needed to build an identical data structure representing the state of7011+// a mirrored copy WITHOUT bothering to rescan it (i.e. we're mirroring to7012+// it WITHOUT scanning it, e.g. it's over the net), so this requires access7013+// to all of the innards.7014+extern void stb_dirtree_db_add_dir(stb_dirtree *active, char *path, time_t last);7015+extern void stb_dirtree_db_add_file(stb_dirtree *active, char *name, int dir, stb_int64 size, time_t last);7016+extern void stb_dirtree_db_read(stb_dirtree *target, char *filename, char *dir);7017+extern void stb_dirtree_db_write(stb_dirtree *target, char *filename, char *dir);7018+7019+#ifdef STB_DEFINE7020+static void stb__dirtree_add_dir(char *path, time_t last, stb_dirtree *active)7021+{7022+ stb_dirtree_dir d;7023+ d.last_modified = last;7024+ d.num_files = 0;7025+ d.path = stb_strdup(path, active->string_pool);7026+ stb_arr_push(active->dirs, d);7027+}7028+7029+static void stb__dirtree_add_file(char *name, int dir, stb_int64 size, time_t last, stb_dirtree *active)7030+{7031+ stb_dirtree_file f;7032+ f.dir = dir;7033+ f.size = size;7034+ f.last_modified = last;7035+ f.name = stb_strdup(name, active->string_pool);7036+ ++active->dirs[dir].num_files;7037+ stb_arr_push(active->files, f);7038+}7039+7040+// version 02 supports > 4GB files7041+static char stb__signature[12] = { 's', 'T', 'b', 'D', 'i', 'R', 't', 'R', 'e', 'E', '0', '2' };7042+7043+static void stb__dirtree_save_db(char *filename, stb_dirtree *data, char *root)7044+{7045+ int i, num_dirs_final=0, num_files_final;7046+ char *info = root ? root : (char*)"";7047+ int *remap;7048+ FILE *f = stb_p_fopen(filename, "wb");7049+ if (!f) return;7050+7051+ fwrite(stb__signature, sizeof(stb__signature), 1, f);7052+ fwrite(info, strlen(info)+1, 1, f);7053+ // need to be slightly tricky and not write out NULLed directories, nor the root7054+7055+ // build remapping table of all dirs we'll be writing out7056+ remap = (int *) malloc(sizeof(remap[0]) * stb_arr_len(data->dirs));7057+ for (i=0; i < stb_arr_len(data->dirs); ++i) {7058+ if (data->dirs[i].path == NULL || (root && 0==stb_stricmp(data->dirs[i].path, root))) {7059+ remap[i] = -1;7060+ } else {7061+ remap[i] = num_dirs_final++;7062+ }7063+ }7064+7065+ fwrite(&num_dirs_final, 4, 1, f);7066+ for (i=0; i < stb_arr_len(data->dirs); ++i) {7067+ if (remap[i] >= 0) {7068+ fwrite(&data->dirs[i].last_modified, 4, 1, f);7069+ stb_fput_string(f, data->dirs[i].path);7070+ }7071+ }7072+7073+ num_files_final = 0;7074+ for (i=0; i < stb_arr_len(data->files); ++i)7075+ if (remap[data->files[i].dir] >= 0 && data->files[i].name)7076+ ++num_files_final;7077+7078+ fwrite(&num_files_final, 4, 1, f);7079+ for (i=0; i < stb_arr_len(data->files); ++i) {7080+ if (remap[data->files[i].dir] >= 0 && data->files[i].name) {7081+ stb_fput_ranged(f, remap[data->files[i].dir], 0, num_dirs_final);7082+ stb_fput_varlen64(f, data->files[i].size);7083+ fwrite(&data->files[i].last_modified, 4, 1, f);7084+ stb_fput_string(f, data->files[i].name);7085+ }7086+ }7087+7088+ fclose(f);7089+}7090+7091+// note: stomps any existing data, rather than appending7092+static void stb__dirtree_load_db(char *filename, stb_dirtree *data, char *dir)7093+{7094+ char sig[2048];7095+ int i,n;7096+ FILE *f = stb_p_fopen(filename, "rb");7097+7098+ if (!f) return;7099+7100+ data->string_pool = stb_malloc(0,1);7101+7102+ fread(sig, sizeof(stb__signature), 1, f);7103+ if (memcmp(stb__signature, sig, sizeof(stb__signature))) { fclose(f); return; }7104+ if (!fread(sig, strlen(dir)+1, 1, f)) { fclose(f); return; }7105+ if (stb_stricmp(sig,dir)) { fclose(f); return; }7106+7107+ // we can just read them straight in, because they're guaranteed to be valid7108+ fread(&n, 4, 1, f);7109+ stb_arr_setlen(data->dirs, n);7110+ for(i=0; i < stb_arr_len(data->dirs); ++i) {7111+ fread(&data->dirs[i].last_modified, 4, 1, f);7112+ data->dirs[i].path = stb_fget_string(f, data->string_pool);7113+ if (data->dirs[i].path == NULL) goto bail;7114+ }7115+ fread(&n, 4, 1, f);7116+ stb_arr_setlen(data->files, n);7117+ for (i=0; i < stb_arr_len(data->files); ++i) {7118+ data->files[i].dir = stb_fget_ranged(f, 0, stb_arr_len(data->dirs));7119+ data->files[i].size = stb_fget_varlen64(f);7120+ fread(&data->files[i].last_modified, 4, 1, f);7121+ data->files[i].name = stb_fget_string(f, data->string_pool);7122+ if (data->files[i].name == NULL) goto bail;7123+ }7124+7125+ if (0) {7126+ bail:7127+ stb_arr_free(data->dirs);7128+ stb_arr_free(data->files);7129+ }7130+ fclose(f);7131+}7132+7133+FILE *hlog;7134+7135+static int stb__dircount, stb__dircount_mask, stb__showfile;7136+static void stb__dirtree_scandir(char *path, time_t last_time, stb_dirtree *active)7137+{7138+ // this is dumb depth first; theoretically it might be faster7139+ // to fully traverse each directory before visiting its children,7140+ // but it's complicated and didn't seem like a gain in the test app7141+7142+ int n;7143+7144+ struct _wfinddatai64_t c_file;7145+ long hFile;7146+ stb__wchar full_path[1024];7147+ int has_slash;7148+ if (stb__showfile) printf("<");7149+7150+ has_slash = (path[0] && path[strlen(path)-1] == '/');7151+7152+ // @TODO: do this concatenation without using swprintf to avoid this mess:7153+#if (defined(_MSC_VER) && _MSC_VER < 1400) // || (defined(__clang__))7154+ // confusingly, Windows Kits\10 needs to go down this path?!?7155+ // except now it doesn't, I don't know what changed7156+ if (has_slash)7157+ swprintf(full_path, L"%s*", stb__from_utf8(path));7158+ else7159+ swprintf(full_path, L"%s/*", stb__from_utf8(path));7160+#else7161+ if (has_slash)7162+ swprintf((wchar_t *) full_path, (size_t) 1024, L"%s*", (wchar_t *) stb__from_utf8(path));7163+ else7164+ swprintf((wchar_t *) full_path, (size_t) 1024, L"%s/*", (wchar_t *) stb__from_utf8(path));7165+#endif7166+7167+ // it's possible this directory is already present: that means it was in the7168+ // cache, but its parent wasn't... in that case, we're done with it7169+ if (stb__showfile) printf("C[%d]", stb_arr_len(active->dirs));7170+ for (n=0; n < stb_arr_len(active->dirs); ++n)7171+ if (0 == stb_stricmp(active->dirs[n].path, path)) {7172+ if (stb__showfile) printf("D");7173+ return;7174+ }7175+ if (stb__showfile) printf("E");7176+7177+ // otherwise, we need to add it7178+ stb__dirtree_add_dir(path, last_time, active);7179+ n = stb_arr_lastn(active->dirs);7180+7181+ if (stb__showfile) printf("[");7182+ if( (hFile = (long) _wfindfirsti64( (wchar_t *) full_path, &c_file )) != -1L ) {7183+ do {7184+ if (stb__showfile) printf(")");7185+ if (c_file.attrib & _A_SUBDIR) {7186+ // ignore subdirectories starting with '.', e.g. "." and ".."7187+ if (c_file.name[0] != '.') {7188+ char *new_path = (char *) full_path;7189+ char *temp = stb__to_utf8((stb__wchar *) c_file.name);7190+7191+ if (has_slash)7192+ stb_p_sprintf(new_path stb_p_size(sizeof(full_path)), "%s%s", path, temp);7193+ else7194+ stb_p_sprintf(new_path stb_p_size(sizeof(full_path)), "%s/%s", path, temp);7195+7196+ if (stb__dircount_mask) {7197+ ++stb__dircount;7198+ if (!(stb__dircount & stb__dircount_mask)) {7199+ char dummy_path[128], *pad;7200+ stb_strncpy(dummy_path, new_path, sizeof(dummy_path)-1);7201+ if (strlen(dummy_path) > 96) {7202+ stb_p_strcpy_s(dummy_path+96/2-1,128, "...");7203+ stb_p_strcpy_s(dummy_path+96/2+2,128, new_path + strlen(new_path)-96/2+2);7204+ }7205+ pad = dummy_path + strlen(dummy_path);7206+ while (pad < dummy_path+98)7207+ *pad++ = ' ';7208+ *pad = 0;7209+ printf("%s\r", dummy_path);7210+ #if 07211+ if (hlog == 0) {7212+ hlog = stb_p_fopen("c:/x/temp.log", "w");7213+ fprintf(hlog, "%s\n", dummy_path);7214+ }7215+ #endif7216+ }7217+ }7218+7219+ stb__dirtree_scandir(new_path, c_file.time_write, active);7220+ }7221+ } else {7222+ char *temp = stb__to_utf8((stb__wchar *) c_file.name);7223+ stb__dirtree_add_file(temp, n, c_file.size, c_file.time_write, active);7224+ }7225+ if (stb__showfile) printf("(");7226+ } while( _wfindnexti64( hFile, &c_file ) == 0 );7227+ if (stb__showfile) printf("]");7228+ _findclose( hFile );7229+ }7230+ if (stb__showfile) printf(">\n");7231+}7232+7233+// scan the database and see if it's all valid7234+static int stb__dirtree_update_db(stb_dirtree *db, stb_dirtree *active)7235+{7236+ int changes_detected = STB_FALSE;7237+ int i;7238+ int *remap;7239+ int *rescan=NULL;7240+ remap = (int *) malloc(sizeof(remap[0]) * stb_arr_len(db->dirs));7241+ memset(remap, 0, sizeof(remap[0]) * stb_arr_len(db->dirs));7242+ rescan = NULL;7243+7244+ for (i=0; i < stb_arr_len(db->dirs); ++i) {7245+ struct _stat info;7246+ if (stb__dircount_mask) {7247+ ++stb__dircount;7248+ if (!(stb__dircount & stb__dircount_mask)) {7249+ printf(".");7250+ }7251+ }7252+ if (0 == _stat(db->dirs[i].path, &info)) {7253+ if (info.st_mode & _S_IFDIR) {7254+ // it's still a directory, as expected7255+ int n = abs((int) (info.st_mtime - db->dirs[i].last_modified));7256+ 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 play7257+ // it's changed! force a rescan7258+ // we don't want to scan it until we've stat()d its7259+ // subdirs, though, so we queue it7260+ if (stb__showfile) printf("Changed: %s - %08x:%08x\n", db->dirs[i].path, (unsigned int) db->dirs[i].last_modified, (unsigned int) info.st_mtime);7261+ stb_arr_push(rescan, i);7262+ // update the last_mod time7263+ db->dirs[i].last_modified = info.st_mtime;7264+ // ignore existing files in this dir7265+ remap[i] = -1;7266+ changes_detected = STB_TRUE;7267+ } else {7268+ // it hasn't changed, just copy it through unchanged7269+ stb__dirtree_add_dir(db->dirs[i].path, db->dirs[i].last_modified, active);7270+ remap[i] = stb_arr_lastn(active->dirs);7271+ }7272+ } else {7273+ // this path used to refer to a directory, but now it's a file!7274+ // assume that the parent directory is going to be forced to rescan anyway7275+ goto delete_entry;7276+ }7277+ } else {7278+ delete_entry:7279+ // directory no longer exists, so don't copy it7280+ // we don't free it because it's in the string pool now7281+ db->dirs[i].path = NULL;7282+ remap[i] = -1;7283+ changes_detected = STB_TRUE;7284+ }7285+ }7286+7287+ // at this point, we have:7288+ //7289+ // <rescan> holds a list of directory indices that need to be scanned due to being out of date7290+ // <remap> holds the directory index in <active> for each dir in <db>, if it exists; -1 if not7291+ // directories in <rescan> are not in <active> yet7292+7293+ // so we can go ahead and remap all the known files right now7294+ for (i=0; i < stb_arr_len(db->files); ++i) {7295+ int dir = db->files[i].dir;7296+ if (remap[dir] >= 0) {7297+ stb__dirtree_add_file(db->files[i].name, remap[dir], db->files[i].size, db->files[i].last_modified, active);7298+ }7299+ }7300+7301+ // at this point we're done with db->files, and done with remap7302+ free(remap);7303+7304+ // now scan those directories using the standard scan7305+ for (i=0; i < stb_arr_len(rescan); ++i) {7306+ int z = rescan[i];7307+ stb__dirtree_scandir(db->dirs[z].path, db->dirs[z].last_modified, active);7308+ }7309+ stb_arr_free(rescan);7310+7311+ return changes_detected;7312+}7313+7314+static void stb__dirtree_free_raw(stb_dirtree *d)7315+{7316+ stb_free(d->string_pool);7317+ stb_arr_free(d->dirs);7318+ stb_arr_free(d->files);7319+}7320+7321+stb_dirtree *stb_dirtree_get_with_file(char *dir, char *cache_file)7322+{7323+ stb_dirtree *output = (stb_dirtree *) malloc(sizeof(*output));7324+ stb_dirtree db,active;7325+ int prev_dir_count, cache_mismatch;7326+7327+ char *stripped_dir; // store the directory name without a trailing '/' or '\\'7328+7329+ // load the database of last-known state on disk7330+ db.string_pool = NULL;7331+ db.files = NULL;7332+ db.dirs = NULL;7333+7334+ stripped_dir = stb_strip_final_slash(stb_p_strdup(dir));7335+7336+ if (cache_file != NULL)7337+ stb__dirtree_load_db(cache_file, &db, stripped_dir);7338+ else if (stb__showfile)7339+ printf("No cache file\n");7340+7341+ active.files = NULL;7342+ active.dirs = NULL;7343+ active.string_pool = stb_malloc(0,1); // @TODO: share string pools between both?7344+7345+ // check all the directories in the database; make note if7346+ // anything we scanned had changed, and rescan those things7347+ cache_mismatch = stb__dirtree_update_db(&db, &active);7348+7349+ // check the root tree7350+ prev_dir_count = stb_arr_len(active.dirs); // record how many directories we've seen7351+7352+ stb__dirtree_scandir(stripped_dir, 0, &active); // no last_modified time available for root7353+7354+ if (stb__dircount_mask)7355+ printf(" \r");7356+7357+ // done with the DB; write it back out if any changes, i.e. either7358+ // 1. any inconsistency found between cached information and actual disk7359+ // or 2. if scanning the root found any new directories--which we detect because7360+ // more than one directory got added to the active db during that scan7361+ if (cache_mismatch || stb_arr_len(active.dirs) > prev_dir_count+1)7362+ stb__dirtree_save_db(cache_file, &active, stripped_dir);7363+7364+ free(stripped_dir);7365+7366+ stb__dirtree_free_raw(&db);7367+7368+ *output = active;7369+ return output;7370+}7371+7372+stb_dirtree *stb_dirtree_get_dir(char *dir, char *cache_dir)7373+{7374+ int i;7375+ stb_uint8 sha[20];7376+ char dir_lower[1024];7377+ char cache_file[1024],*s;7378+ if (cache_dir == NULL)7379+ return stb_dirtree_get_with_file(dir, NULL);7380+ stb_p_strcpy_s(dir_lower, sizeof(dir_lower), dir);7381+ stb_tolower(dir_lower);7382+ stb_sha1(sha, (unsigned char *) dir_lower, (unsigned int) strlen(dir_lower));7383+ stb_p_strcpy_s(cache_file, sizeof(cache_file), cache_dir);7384+ s = cache_file + strlen(cache_file);7385+ if (s[-1] != '/' && s[-1] != '\\') *s++ = '/';7386+ stb_p_strcpy_s(s, sizeof(cache_file), "dirtree_");7387+ s += strlen(s);7388+ for (i=0; i < 8; ++i) {7389+ char *hex = (char*)"0123456789abcdef";7390+ stb_uint z = sha[i];7391+ *s++ = hex[z >> 4];7392+ *s++ = hex[z & 15];7393+ }7394+ stb_p_strcpy_s(s, sizeof(cache_file), ".bin");7395+ return stb_dirtree_get_with_file(dir, cache_file);7396+}7397+7398+stb_dirtree *stb_dirtree_get(char *dir)7399+{7400+ char cache_dir[256];7401+ stb_p_strcpy_s(cache_dir, sizeof(cache_dir), "c:/bindata");7402+ #ifdef STB_HAS_REGISTRY7403+ {7404+ void *reg = stb_reg_open("rHKLM", "Software\\SilverSpaceship\\stb");7405+ if (reg) {7406+ stb_reg_read(reg, "dirtree", cache_dir, sizeof(cache_dir));7407+ stb_reg_close(reg);7408+ }7409+ }7410+ #endif7411+ return stb_dirtree_get_dir(dir, cache_dir);7412+}7413+7414+void stb_dirtree_free(stb_dirtree *d)7415+{7416+ stb__dirtree_free_raw(d);7417+ free(d);7418+}7419+7420+void stb_dirtree_db_add_dir(stb_dirtree *active, char *path, time_t last)7421+{7422+ stb__dirtree_add_dir(path, last, active);7423+}7424+7425+void stb_dirtree_db_add_file(stb_dirtree *active, char *name, int dir, stb_int64 size, time_t last)7426+{7427+ stb__dirtree_add_file(name, dir, size, last, active);7428+}7429+7430+void stb_dirtree_db_read(stb_dirtree *target, char *filename, char *dir)7431+{7432+ char *s = stb_strip_final_slash(stb_p_strdup(dir));7433+ target->dirs = 0;7434+ target->files = 0;7435+ target->string_pool = 0;7436+ stb__dirtree_load_db(filename, target, s);7437+ free(s);7438+}7439+7440+void stb_dirtree_db_write(stb_dirtree *target, char *filename, char *dir)7441+{7442+ stb__dirtree_save_db(filename, target, 0); // don't strip out any directories7443+}7444+7445+#endif // STB_DEFINE7446+7447+#endif // _WIN327448+#endif // STB_NO_STB_STRINGS7449+7450+//////////////////////////////////////////////////////////////////////////////7451+//7452+// STB_MALLOC_WRAPPER7453+//7454+// you can use the wrapper functions with your own malloc wrapper,7455+// or define STB_MALLOC_WRAPPER project-wide to have7456+// malloc/free/realloc/strdup all get vectored to it7457+7458+// this has too many very specific error messages you could google for and find in stb.h,7459+// so don't use it if they don't want any stb.h-identifiable strings7460+#if defined(STB_DEFINE) && !defined(STB_NO_STB_STRINGS)7461+7462+typedef struct7463+{7464+ void *p;7465+ char *file;7466+ int line;7467+ size_t size;7468+} stb_malloc_record;7469+7470+#ifndef STB_MALLOC_HISTORY_COUNT7471+#define STB_MALLOC_HISTORY_COUNT 50 // 800 bytes7472+#endif7473+7474+stb_malloc_record *stb__allocations;7475+static int stb__alloc_size, stb__alloc_limit, stb__alloc_mask;7476+int stb__alloc_count;7477+7478+stb_malloc_record stb__alloc_history[STB_MALLOC_HISTORY_COUNT];7479+int stb__history_pos;7480+7481+static int stb__hashfind(void *p)7482+{7483+ stb_uint32 h = stb_hashptr(p);7484+ int s,n = h & stb__alloc_mask;7485+ if (stb__allocations[n].p == p)7486+ return n;7487+ s = stb_rehash(h)|1;7488+ for(;;) {7489+ if (stb__allocations[n].p == NULL)7490+ return -1;7491+ n = (n+s) & stb__alloc_mask;7492+ if (stb__allocations[n].p == p)7493+ return n;7494+ }7495+}7496+7497+size_t stb_wrapper_allocsize(void *p)7498+{7499+ int n = stb__hashfind(p);7500+ if (n < 0) return 0;7501+ return stb__allocations[n].size;7502+}7503+7504+static int stb__historyfind(void *p)7505+{7506+ int n = stb__history_pos;7507+ int i;7508+ for (i=0; i < STB_MALLOC_HISTORY_COUNT; ++i) {7509+ if (--n < 0) n = STB_MALLOC_HISTORY_COUNT-1;7510+ if (stb__alloc_history[n].p == p)7511+ return n;7512+ }7513+ return -1;7514+}7515+7516+static void stb__add_alloc(void *p, size_t sz, char *file, int line);7517+static void stb__grow_alloc(void)7518+{7519+ int i,old_num = stb__alloc_size;7520+ stb_malloc_record *old = stb__allocations;7521+ if (stb__alloc_size == 0)7522+ stb__alloc_size = 64;7523+ else7524+ stb__alloc_size *= 2;7525+7526+ stb__allocations = (stb_malloc_record *) stb__realloc_raw(NULL, stb__alloc_size * sizeof(stb__allocations[0]));7527+ if (stb__allocations == NULL)7528+ stb_fatal("Internal error: couldn't grow malloc wrapper table");7529+ memset(stb__allocations, 0, stb__alloc_size * sizeof(stb__allocations[0]));7530+ stb__alloc_limit = (stb__alloc_size*3)>>2;7531+ stb__alloc_mask = stb__alloc_size-1;7532+7533+ stb__alloc_count = 0;7534+7535+ for (i=0; i < old_num; ++i)7536+ if (old[i].p > STB_DEL) {7537+ stb__add_alloc(old[i].p, old[i].size, old[i].file, old[i].line);7538+ assert(stb__hashfind(old[i].p) >= 0);7539+ }7540+ for (i=0; i < old_num; ++i)7541+ if (old[i].p > STB_DEL)7542+ assert(stb__hashfind(old[i].p) >= 0);7543+ stb__realloc_raw(old, 0);7544+}7545+7546+static void stb__add_alloc(void *p, size_t sz, char *file, int line)7547+{7548+ stb_uint32 h;7549+ int n;7550+ if (stb__alloc_count >= stb__alloc_limit)7551+ stb__grow_alloc();7552+ h = stb_hashptr(p);7553+ n = h & stb__alloc_mask;7554+ if (stb__allocations[n].p > STB_DEL) {7555+ int s = stb_rehash(h)|1;7556+ do {7557+ n = (n+s) & stb__alloc_mask;7558+ } while (stb__allocations[n].p > STB_DEL);7559+ }7560+ assert(stb__allocations[n].p == NULL || stb__allocations[n].p == STB_DEL);7561+ stb__allocations[n].p = p;7562+ stb__allocations[n].size = sz;7563+ stb__allocations[n].line = line;7564+ stb__allocations[n].file = file;7565+ ++stb__alloc_count;7566+}7567+7568+static void stb__remove_alloc(int n, char *file, int line)7569+{7570+ stb__alloc_history[stb__history_pos] = stb__allocations[n];7571+ stb__alloc_history[stb__history_pos].file = file;7572+ stb__alloc_history[stb__history_pos].line = line;7573+ if (++stb__history_pos == STB_MALLOC_HISTORY_COUNT)7574+ stb__history_pos = 0;7575+ stb__allocations[n].p = STB_DEL;7576+ --stb__alloc_count;7577+}7578+7579+void stb_wrapper_malloc(void *p, size_t sz, char *file, int line)7580+{7581+ if (!p) return;7582+ stb__add_alloc(p,sz,file,line);7583+}7584+7585+void stb_wrapper_free(void *p, char *file, int line)7586+{7587+ int n;7588+7589+ if (p == NULL) return;7590+7591+ n = stb__hashfind(p);7592+7593+ if (n >= 0)7594+ stb__remove_alloc(n, file, line);7595+ else {7596+ // tried to free something we hadn't allocated!7597+ n = stb__historyfind(p);7598+ assert(0); /* NOTREACHED */7599+ if (n >= 0)7600+ stb_fatal("Attempted to free %d-byte block %p at %s:%d previously freed/realloced at %s:%d",7601+ stb__alloc_history[n].size, p,7602+ file, line,7603+ stb__alloc_history[n].file, stb__alloc_history[n].line);7604+ else7605+ stb_fatal("Attempted to free unknown block %p at %s:%d", p, file,line);7606+ }7607+}7608+7609+void stb_wrapper_check(void *p)7610+{7611+ int n;7612+7613+ if (p == NULL) return;7614+7615+ n = stb__hashfind(p);7616+7617+ if (n >= 0) return;7618+7619+ for (n=0; n < stb__alloc_size; ++n)7620+ if (stb__allocations[n].p == p)7621+ stb_fatal("Internal error: pointer %p was allocated, but hash search failed", p);7622+7623+ // tried to free something that wasn't allocated!7624+ n = stb__historyfind(p);7625+ if (n >= 0)7626+ stb_fatal("Checked %d-byte block %p previously freed/realloced at %s:%d",7627+ stb__alloc_history[n].size, p,7628+ stb__alloc_history[n].file, stb__alloc_history[n].line);7629+ stb_fatal("Checked unknown block %p");7630+}7631+7632+void stb_wrapper_realloc(void *p, void *q, size_t sz, char *file, int line)7633+{7634+ int n;7635+ if (p == NULL) { stb_wrapper_malloc(q, sz, file, line); return; }7636+ if (q == NULL) return; // nothing happened7637+7638+ n = stb__hashfind(p);7639+ if (n == -1) {7640+ // tried to free something we hadn't allocated!7641+ // this is weird, though, because we got past the realloc!7642+ n = stb__historyfind(p);7643+ assert(0); /* NOTREACHED */7644+ if (n >= 0)7645+ stb_fatal("Attempted to realloc %d-byte block %p at %s:%d previously freed/realloced at %s:%d",7646+ stb__alloc_history[n].size, p,7647+ file, line,7648+ stb__alloc_history[n].file, stb__alloc_history[n].line);7649+ else7650+ stb_fatal("Attempted to realloc unknown block %p at %s:%d", p, file,line);7651+ } else {7652+ if (q == p) {7653+ stb__allocations[n].size = sz;7654+ stb__allocations[n].file = file;7655+ stb__allocations[n].line = line;7656+ } else {7657+ stb__remove_alloc(n, file, line);7658+ stb__add_alloc(q,sz,file,line);7659+ }7660+ }7661+}7662+7663+void stb_wrapper_listall(void (*func)(void *ptr, size_t sz, char *file, int line))7664+{7665+ int i;7666+ for (i=0; i < stb__alloc_size; ++i)7667+ if (stb__allocations[i].p > STB_DEL)7668+ func(stb__allocations[i].p , stb__allocations[i].size,7669+ stb__allocations[i].file, stb__allocations[i].line);7670+}7671+7672+void stb_wrapper_dump(char *filename)7673+{7674+ int i;7675+ FILE *f = stb_p_fopen(filename, "w");7676+ if (!f) return;7677+ for (i=0; i < stb__alloc_size; ++i)7678+ if (stb__allocations[i].p > STB_DEL)7679+ fprintf(f, "%p %7d - %4d %s\n",7680+ stb__allocations[i].p , (int) stb__allocations[i].size,7681+ stb__allocations[i].line, stb__allocations[i].file);7682+}7683+#endif // STB_DEFINE7684+7685+7686+//////////////////////////////////////////////////////////////////////////////7687+//7688+// stb_pointer_set7689+//7690+//7691+// For data structures that support querying by key, data structure7692+// classes always hand-wave away the issue of what to do if two entries7693+// have the same key: basically, store a linked list of all the nodes7694+// which have the same key (a LISP-style list).7695+//7696+// The thing is, it's not that trivial. If you have an O(log n)7697+// lookup data structure, but then n/4 items have the same value,7698+// you don't want to spend O(n) time scanning that list when7699+// deleting an item if you already have a pointer to the item.7700+// (You have to spend O(n) time enumerating all the items with7701+// a given key, sure, and you can't accelerate deleting a particular7702+// item if you only have the key, not a pointer to the item.)7703+//7704+// I'm going to call this data structure, whatever it turns out to7705+// be, a "pointer set", because we don't store any associated data for7706+// items in this data structure, we just answer the question of7707+// whether an item is in it or not (it's effectively one bit per pointer).7708+// Technically they don't have to be pointers; you could cast ints7709+// to (void *) if you want, but you can't store 0 or 1 because of the7710+// hash table.7711+//7712+// Since the fastest data structure we might want to add support for7713+// identical-keys to is a hash table with O(1)-ish lookup time,7714+// that means that the conceptual "linked list of all items with7715+// the same indexed value" that we build needs to have the same7716+// performance; that way when we index a table we think is arbitrary7717+// ints, but in fact half of them are 0, we don't get screwed.7718+//7719+// Therefore, it needs to be a hash table, at least when it gets7720+// large. On the other hand, when the data has totally arbitrary ints7721+// or floats, there won't be many collisions, and we'll have tons of7722+// 1-item bitmaps. That will be grossly inefficient as hash tables;7723+// trade-off; the hash table is reasonably efficient per-item when7724+// it's large, but not when it's small. So we need to do something7725+// Judy-like and use different strategies depending on the size.7726+//7727+// Like Judy, we'll use the bottom bit to encode the strategy:7728+//7729+// bottom bits:7730+// 00 - direct pointer7731+// 01 - 4-item bucket (16 bytes, no length, NULLs)7732+// 10 - N-item array7733+// 11 - hash table7734+7735+typedef struct stb_ps stb_ps;7736+7737+STB_EXTERN int stb_ps_find (stb_ps *ps, void *value);7738+STB_EXTERN stb_ps * stb_ps_add (stb_ps *ps, void *value);7739+STB_EXTERN stb_ps * stb_ps_remove(stb_ps *ps, void *value);7740+STB_EXTERN stb_ps * stb_ps_remove_any(stb_ps *ps, void **value);7741+STB_EXTERN void stb_ps_delete(stb_ps *ps);7742+STB_EXTERN int stb_ps_count (stb_ps *ps);7743+7744+STB_EXTERN stb_ps * stb_ps_copy (stb_ps *ps);7745+STB_EXTERN int stb_ps_subset(stb_ps *bigger, stb_ps *smaller);7746+STB_EXTERN int stb_ps_eq (stb_ps *p0, stb_ps *p1);7747+7748+STB_EXTERN void ** stb_ps_getlist (stb_ps *ps, int *count);7749+STB_EXTERN int stb_ps_writelist(stb_ps *ps, void **list, int size );7750+7751+// enum and fastlist don't allocate storage, but you must consume the7752+// list before there's any chance the data structure gets screwed up;7753+STB_EXTERN int stb_ps_enum (stb_ps *ps, void *data,7754+ int (*func)(void *value, void*data) );7755+STB_EXTERN void ** stb_ps_fastlist(stb_ps *ps, int *count);7756+// result:7757+// returns a list, *count is the length of that list,7758+// but some entries of the list may be invalid;7759+// test with 'stb_ps_fastlist_valid(x)'7760+7761+#define stb_ps_fastlist_valid(x) ((stb_uinta) (x) > 1)7762+7763+#ifdef STB_DEFINE7764+7765+enum7766+{7767+ STB_ps_direct = 0,7768+ STB_ps_bucket = 1,7769+ STB_ps_array = 2,7770+ STB_ps_hash = 3,7771+};7772+7773+#define STB_BUCKET_SIZE 47774+7775+typedef struct7776+{7777+ void *p[STB_BUCKET_SIZE];7778+} stb_ps_bucket;7779+#define GetBucket(p) ((stb_ps_bucket *) ((char *) (p) - STB_ps_bucket))7780+#define EncodeBucket(p) ((stb_ps *) ((char *) (p) + STB_ps_bucket))7781+7782+static void stb_bucket_free(stb_ps_bucket *b)7783+{7784+ free(b);7785+}7786+7787+static stb_ps_bucket *stb_bucket_create2(void *v0, void *v1)7788+{7789+ stb_ps_bucket *b = (stb_ps_bucket*) malloc(sizeof(*b));7790+ b->p[0] = v0;7791+ b->p[1] = v1;7792+ b->p[2] = NULL;7793+ b->p[3] = NULL;7794+ return b;7795+}7796+7797+static stb_ps_bucket * stb_bucket_create3(void **v)7798+{7799+ stb_ps_bucket *b = (stb_ps_bucket*) malloc(sizeof(*b));7800+ b->p[0] = v[0];7801+ b->p[1] = v[1];7802+ b->p[2] = v[2];7803+ b->p[3] = NULL;7804+ return b;7805+}7806+7807+7808+// could use stb_arr, but this will save us memory7809+typedef struct7810+{7811+ int count;7812+ void *p[1];7813+} stb_ps_array;7814+#define GetArray(p) ((stb_ps_array *) ((char *) (p) - STB_ps_array))7815+#define EncodeArray(p) ((stb_ps *) ((char *) (p) + STB_ps_array))7816+7817+static int stb_ps_array_max = 13;7818+7819+typedef struct7820+{7821+ int size, mask;7822+ int count, count_deletes;7823+ int grow_threshhold;7824+ int shrink_threshhold;7825+ int rehash_threshhold;7826+ int any_offset;7827+ void *table[1];7828+} stb_ps_hash;7829+#define GetHash(p) ((stb_ps_hash *) ((char *) (p) - STB_ps_hash))7830+#define EncodeHash(p) ((stb_ps *) ((char *) (p) + STB_ps_hash))7831+7832+#define stb_ps_empty(v) (((stb_uint32) v) <= 1)7833+7834+static stb_ps_hash *stb_ps_makehash(int size, int old_size, void **old_data)7835+{7836+ int i;7837+ stb_ps_hash *h = (stb_ps_hash *) malloc(sizeof(*h) + (size-1) * sizeof(h->table[0]));7838+ assert(stb_is_pow2(size));7839+ h->size = size;7840+ h->mask = size-1;7841+ h->shrink_threshhold = (int) (0.3f * size);7842+ h-> grow_threshhold = (int) (0.8f * size);7843+ h->rehash_threshhold = (int) (0.9f * size);7844+ h->count = 0;7845+ h->count_deletes = 0;7846+ h->any_offset = 0;7847+ memset(h->table, 0, size * sizeof(h->table[0]));7848+ for (i=0; i < old_size; ++i)7849+ if (!stb_ps_empty((size_t)old_data[i]))7850+ stb_ps_add(EncodeHash(h), old_data[i]);7851+ return h;7852+}7853+7854+void stb_ps_delete(stb_ps *ps)7855+{7856+ switch (3 & (int)(size_t) ps) {7857+ case STB_ps_direct: break;7858+ case STB_ps_bucket: stb_bucket_free(GetBucket(ps)); break;7859+ case STB_ps_array : free(GetArray(ps)); break;7860+ case STB_ps_hash : free(GetHash(ps)); break;7861+ }7862+}7863+7864+stb_ps *stb_ps_copy(stb_ps *ps)7865+{7866+ int i;7867+ // not a switch: order based on expected performance/power-law distribution7868+ switch (3 & (int)(size_t) ps) {7869+ case STB_ps_direct: return ps;7870+ case STB_ps_bucket: {7871+ stb_ps_bucket *n = (stb_ps_bucket *) malloc(sizeof(*n));7872+ *n = *GetBucket(ps);7873+ return EncodeBucket(n);7874+ }7875+ case STB_ps_array: {7876+ stb_ps_array *a = GetArray(ps);7877+ stb_ps_array *n = (stb_ps_array *) malloc(sizeof(*n) + stb_ps_array_max * sizeof(n->p[0]));7878+ n->count = a->count;7879+ for (i=0; i < a->count; ++i)7880+ n->p[i] = a->p[i];7881+ return EncodeArray(n);7882+ }7883+ case STB_ps_hash: {7884+ stb_ps_hash *h = GetHash(ps);7885+ stb_ps_hash *n = stb_ps_makehash(h->size, h->size, h->table);7886+ return EncodeHash(n);7887+ }7888+ }7889+ assert(0); /* NOTREACHED */7890+ return NULL;7891+}7892+7893+int stb_ps_find(stb_ps *ps, void *value)7894+{7895+ int i, code = 3 & (int)(size_t) ps;7896+ assert((3 & (int)(size_t) value) == STB_ps_direct);7897+ assert(stb_ps_fastlist_valid(value));7898+ // not a switch: order based on expected performance/power-law distribution7899+ if (code == STB_ps_direct)7900+ return value == ps;7901+ if (code == STB_ps_bucket) {7902+ stb_ps_bucket *b = GetBucket(ps);7903+ assert(STB_BUCKET_SIZE == 4);7904+ if (b->p[0] == value || b->p[1] == value ||7905+ b->p[2] == value || b->p[3] == value)7906+ return STB_TRUE;7907+ return STB_FALSE;7908+ }7909+ if (code == STB_ps_array) {7910+ stb_ps_array *a = GetArray(ps);7911+ for (i=0; i < a->count; ++i)7912+ if (a->p[i] == value)7913+ return STB_TRUE;7914+ return STB_FALSE;7915+ } else {7916+ stb_ps_hash *h = GetHash(ps);7917+ stb_uint32 hash = stb_hashptr(value);7918+ stb_uint32 s, n = hash & h->mask;7919+ void **t = h->table;7920+ if (t[n] == value) return STB_TRUE;7921+ if (t[n] == NULL) return STB_FALSE;7922+ s = stb_rehash(hash) | 1;7923+ do {7924+ n = (n + s) & h->mask;7925+ if (t[n] == value) return STB_TRUE;7926+ } while (t[n] != NULL);7927+ return STB_FALSE;7928+ }7929+}7930+7931+stb_ps * stb_ps_add (stb_ps *ps, void *value)7932+{7933+ #ifdef STB_DEBUG7934+ assert(!stb_ps_find(ps,value));7935+ #endif7936+ if (value == NULL) return ps; // ignore NULL adds to avoid bad breakage7937+ assert((3 & (int)(size_t) value) == STB_ps_direct);7938+ assert(stb_ps_fastlist_valid(value));7939+ assert(value != STB_DEL); // STB_DEL is less likely7940+7941+ switch (3 & (int)(size_t) ps) {7942+ case STB_ps_direct:7943+ if (ps == NULL) return (stb_ps *) value;7944+ return EncodeBucket(stb_bucket_create2(ps,value));7945+7946+ case STB_ps_bucket: {7947+ stb_ps_bucket *b = GetBucket(ps);7948+ stb_ps_array *a;7949+ assert(STB_BUCKET_SIZE == 4);7950+ if (b->p[0] == NULL) { b->p[0] = value; return ps; }7951+ if (b->p[1] == NULL) { b->p[1] = value; return ps; }7952+ if (b->p[2] == NULL) { b->p[2] = value; return ps; }7953+ if (b->p[3] == NULL) { b->p[3] = value; return ps; }7954+ a = (stb_ps_array *) malloc(sizeof(*a) + 7 * sizeof(a->p[0])); // 8 slots, must be 2^k7955+ memcpy(a->p, b, sizeof(*b));7956+ a->p[4] = value;7957+ a->count = 5;7958+ stb_bucket_free(b);7959+ return EncodeArray(a);7960+ }7961+7962+ case STB_ps_array: {7963+ stb_ps_array *a = GetArray(ps);7964+ if (a->count == stb_ps_array_max) {7965+ // promote from array to hash7966+ stb_ps_hash *h = stb_ps_makehash(2 << stb_log2_ceil(a->count), a->count, a->p);7967+ free(a);7968+ return stb_ps_add(EncodeHash(h), value);7969+ }7970+ // do we need to resize the array? the array doubles in size when it7971+ // crosses a power-of-two7972+ if ((a->count & (a->count-1))==0) {7973+ int newsize = a->count*2;7974+ // clamp newsize to max if:7975+ // 1. it's larger than max7976+ // 2. newsize*1.5 is larger than max (to avoid extra resizing)7977+ if (newsize + a->count > stb_ps_array_max)7978+ newsize = stb_ps_array_max;7979+ a = (stb_ps_array *) realloc(a, sizeof(*a) + (newsize-1) * sizeof(a->p[0]));7980+ }7981+ a->p[a->count++] = value;7982+ return EncodeArray(a);7983+ }7984+ case STB_ps_hash: {7985+ stb_ps_hash *h = GetHash(ps);7986+ stb_uint32 hash = stb_hashptr(value);7987+ stb_uint32 n = hash & h->mask;7988+ void **t = h->table;7989+ // find first NULL or STB_DEL entry7990+ if (!stb_ps_empty((size_t)t[n])) {7991+ stb_uint32 s = stb_rehash(hash) | 1;7992+ do {7993+ n = (n + s) & h->mask;7994+ } while (!stb_ps_empty((size_t)t[n]));7995+ }7996+ if (t[n] == STB_DEL)7997+ -- h->count_deletes;7998+ t[n] = value;7999+ ++ h->count;8000+ if (h->count == h->grow_threshhold) {8001+ stb_ps_hash *h2 = stb_ps_makehash(h->size*2, h->size, t);8002+ free(h);8003+ return EncodeHash(h2);8004+ }8005+ if (h->count + h->count_deletes == h->rehash_threshhold) {8006+ stb_ps_hash *h2 = stb_ps_makehash(h->size, h->size, t);8007+ free(h);8008+ return EncodeHash(h2);8009+ }8010+ return ps;8011+ }8012+ }8013+ return NULL; /* NOTREACHED */8014+}8015+8016+stb_ps *stb_ps_remove(stb_ps *ps, void *value)8017+{8018+ #ifdef STB_DEBUG8019+ assert(stb_ps_find(ps, value));8020+ #endif8021+ assert((3 & (int)(size_t) value) == STB_ps_direct);8022+ if (value == NULL) return ps; // ignore NULL removes to avoid bad breakage8023+ switch (3 & (int)(size_t) ps) {8024+ case STB_ps_direct:8025+ return ps == value ? NULL : ps;8026+ case STB_ps_bucket: {8027+ stb_ps_bucket *b = GetBucket(ps);8028+ int count=0;8029+ assert(STB_BUCKET_SIZE == 4);8030+ if (b->p[0] == value) b->p[0] = NULL; else count += (b->p[0] != NULL);8031+ if (b->p[1] == value) b->p[1] = NULL; else count += (b->p[1] != NULL);8032+ if (b->p[2] == value) b->p[2] = NULL; else count += (b->p[2] != NULL);8033+ if (b->p[3] == value) b->p[3] = NULL; else count += (b->p[3] != NULL);8034+ if (count == 1) { // shrink bucket at size 18035+ value = b->p[0];8036+ if (value == NULL) value = b->p[1];8037+ if (value == NULL) value = b->p[2];8038+ if (value == NULL) value = b->p[3];8039+ assert(value != NULL);8040+ stb_bucket_free(b);8041+ return (stb_ps *) value; // return STB_ps_direct of value8042+ }8043+ return ps;8044+ }8045+ case STB_ps_array: {8046+ stb_ps_array *a = GetArray(ps);8047+ int i;8048+ for (i=0; i < a->count; ++i) {8049+ if (a->p[i] == value) {8050+ a->p[i] = a->p[--a->count];8051+ if (a->count == 3) { // shrink to bucket!8052+ stb_ps_bucket *b = stb_bucket_create3(a->p);8053+ free(a);8054+ return EncodeBucket(b);8055+ }8056+ return ps;8057+ }8058+ }8059+ return ps;8060+ }8061+ case STB_ps_hash: {8062+ stb_ps_hash *h = GetHash(ps);8063+ stb_uint32 hash = stb_hashptr(value);8064+ stb_uint32 s, n = hash & h->mask;8065+ void **t = h->table;8066+ if (t[n] != value) {8067+ s = stb_rehash(hash) | 1;8068+ do {8069+ n = (n + s) & h->mask;8070+ } while (t[n] != value);8071+ }8072+ t[n] = STB_DEL;8073+ -- h->count;8074+ ++ h->count_deletes;8075+ // should we shrink down to an array?8076+ if (h->count < stb_ps_array_max) {8077+ int n = 1 << stb_log2_floor(stb_ps_array_max);8078+ if (h->count < n) {8079+ stb_ps_array *a = (stb_ps_array *) malloc(sizeof(*a) + (n-1) * sizeof(a->p[0]));8080+ int i,j=0;8081+ for (i=0; i < h->size; ++i)8082+ if (!stb_ps_empty((size_t)t[i]))8083+ a->p[j++] = t[i];8084+ assert(j == h->count);8085+ a->count = j;8086+ free(h);8087+ return EncodeArray(a);8088+ }8089+ }8090+ if (h->count == h->shrink_threshhold) {8091+ stb_ps_hash *h2 = stb_ps_makehash(h->size >> 1, h->size, t);8092+ free(h);8093+ return EncodeHash(h2);8094+ }8095+ return ps;8096+ }8097+ }8098+ return ps; /* NOTREACHED */8099+}8100+8101+stb_ps *stb_ps_remove_any(stb_ps *ps, void **value)8102+{8103+ assert(ps != NULL);8104+ switch (3 & (int)(size_t) ps) {8105+ case STB_ps_direct:8106+ *value = ps;8107+ return NULL;8108+ case STB_ps_bucket: {8109+ stb_ps_bucket *b = GetBucket(ps);8110+ int count=0, slast=0, last=0;8111+ assert(STB_BUCKET_SIZE == 4);8112+ if (b->p[0]) { ++count; last = 0; }8113+ if (b->p[1]) { ++count; slast = last; last = 1; }8114+ if (b->p[2]) { ++count; slast = last; last = 2; }8115+ if (b->p[3]) { ++count; slast = last; last = 3; }8116+ *value = b->p[last];8117+ b->p[last] = 0;8118+ if (count == 2) {8119+ void *leftover = b->p[slast]; // second to last8120+ stb_bucket_free(b);8121+ return (stb_ps *) leftover;8122+ }8123+ return ps;8124+ }8125+ case STB_ps_array: {8126+ stb_ps_array *a = GetArray(ps);8127+ *value = a->p[a->count-1];8128+ if (a->count == 4)8129+ return stb_ps_remove(ps, *value);8130+ --a->count;8131+ return ps;8132+ }8133+ case STB_ps_hash: {8134+ stb_ps_hash *h = GetHash(ps);8135+ void **t = h->table;8136+ stb_uint32 n = h->any_offset;8137+ while (stb_ps_empty((size_t)t[n]))8138+ n = (n + 1) & h->mask;8139+ *value = t[n];8140+ h->any_offset = (n+1) & h->mask;8141+ // check if we need to skip down to the previous type8142+ if (h->count-1 < stb_ps_array_max || h->count-1 == h->shrink_threshhold)8143+ return stb_ps_remove(ps, *value);8144+ t[n] = STB_DEL;8145+ -- h->count;8146+ ++ h->count_deletes;8147+ return ps;8148+ }8149+ }8150+ return ps; /* NOTREACHED */8151+}8152+8153+8154+void ** stb_ps_getlist(stb_ps *ps, int *count)8155+{8156+ int i,n=0;8157+ void **p = NULL;8158+ switch (3 & (int)(size_t) ps) {8159+ case STB_ps_direct:8160+ if (ps == NULL) { *count = 0; return NULL; }8161+ p = (void **) malloc(sizeof(*p) * 1);8162+ p[0] = ps;8163+ *count = 1;8164+ return p;8165+ case STB_ps_bucket: {8166+ stb_ps_bucket *b = GetBucket(ps);8167+ p = (void **) malloc(sizeof(*p) * STB_BUCKET_SIZE);8168+ for (i=0; i < STB_BUCKET_SIZE; ++i)8169+ if (b->p[i] != NULL)8170+ p[n++] = b->p[i];8171+ break;8172+ }8173+ case STB_ps_array: {8174+ stb_ps_array *a = GetArray(ps);8175+ p = (void **) malloc(sizeof(*p) * a->count);8176+ memcpy(p, a->p, sizeof(*p) * a->count);8177+ *count = a->count;8178+ return p;8179+ }8180+ case STB_ps_hash: {8181+ stb_ps_hash *h = GetHash(ps);8182+ p = (void **) malloc(sizeof(*p) * h->count);8183+ for (i=0; i < h->size; ++i)8184+ if (!stb_ps_empty((size_t)h->table[i]))8185+ p[n++] = h->table[i];8186+ break;8187+ }8188+ }8189+ *count = n;8190+ return p;8191+}8192+8193+int stb_ps_writelist(stb_ps *ps, void **list, int size )8194+{8195+ int i,n=0;8196+ switch (3 & (int)(size_t) ps) {8197+ case STB_ps_direct:8198+ if (ps == NULL || size <= 0) return 0;8199+ list[0] = ps;8200+ return 1;8201+ case STB_ps_bucket: {8202+ stb_ps_bucket *b = GetBucket(ps);8203+ for (i=0; i < STB_BUCKET_SIZE; ++i)8204+ if (b->p[i] != NULL && n < size)8205+ list[n++] = b->p[i];8206+ return n;8207+ }8208+ case STB_ps_array: {8209+ stb_ps_array *a = GetArray(ps);8210+ n = stb_min(size, a->count);8211+ memcpy(list, a->p, sizeof(*list) * n);8212+ return n;8213+ }8214+ case STB_ps_hash: {8215+ stb_ps_hash *h = GetHash(ps);8216+ if (size <= 0) return 0;8217+ for (i=0; i < h->count; ++i) {8218+ if (!stb_ps_empty((size_t)h->table[i])) {8219+ list[n++] = h->table[i];8220+ if (n == size) break;8221+ }8222+ }8223+ return n;8224+ }8225+ }8226+ return 0; /* NOTREACHED */8227+}8228+8229+int stb_ps_enum(stb_ps *ps, void *data, int (*func)(void *value, void *data))8230+{8231+ int i;8232+ switch (3 & (int)(size_t) ps) {8233+ case STB_ps_direct:8234+ if (ps == NULL) return STB_TRUE;8235+ return func(ps, data);8236+ case STB_ps_bucket: {8237+ stb_ps_bucket *b = GetBucket(ps);8238+ for (i=0; i < STB_BUCKET_SIZE; ++i)8239+ if (b->p[i] != NULL)8240+ if (!func(b->p[i], data))8241+ return STB_FALSE;8242+ return STB_TRUE;8243+ }8244+ case STB_ps_array: {8245+ stb_ps_array *a = GetArray(ps);8246+ for (i=0; i < a->count; ++i)8247+ if (!func(a->p[i], data))8248+ return STB_FALSE;8249+ return STB_TRUE;8250+ }8251+ case STB_ps_hash: {8252+ stb_ps_hash *h = GetHash(ps);8253+ for (i=0; i < h->count; ++i)8254+ if (!stb_ps_empty((size_t)h->table[i]))8255+ if (!func(h->table[i], data))8256+ return STB_FALSE;8257+ return STB_TRUE;8258+ }8259+ }8260+ return STB_TRUE; /* NOTREACHED */8261+}8262+8263+int stb_ps_count (stb_ps *ps)8264+{8265+ switch (3 & (int)(size_t) ps) {8266+ case STB_ps_direct:8267+ return ps != NULL;8268+ case STB_ps_bucket: {8269+ stb_ps_bucket *b = GetBucket(ps);8270+ return (b->p[0] != NULL) + (b->p[1] != NULL) +8271+ (b->p[2] != NULL) + (b->p[3] != NULL);8272+ }8273+ case STB_ps_array: {8274+ stb_ps_array *a = GetArray(ps);8275+ return a->count;8276+ }8277+ case STB_ps_hash: {8278+ stb_ps_hash *h = GetHash(ps);8279+ return h->count;8280+ }8281+ }8282+ return 0;8283+}8284+8285+void ** stb_ps_fastlist(stb_ps *ps, int *count)8286+{8287+ static void *storage;8288+8289+ switch (3 & (int)(size_t) ps) {8290+ case STB_ps_direct:8291+ if (ps == NULL) { *count = 0; return NULL; }8292+ storage = ps;8293+ *count = 1;8294+ return &storage;8295+ case STB_ps_bucket: {8296+ stb_ps_bucket *b = GetBucket(ps);8297+ *count = STB_BUCKET_SIZE;8298+ return b->p;8299+ }8300+ case STB_ps_array: {8301+ stb_ps_array *a = GetArray(ps);8302+ *count = a->count;8303+ return a->p;8304+ }8305+ case STB_ps_hash: {8306+ stb_ps_hash *h = GetHash(ps);8307+ *count = h->size;8308+ return h->table;8309+ }8310+ }8311+ return NULL; /* NOTREACHED */8312+}8313+8314+int stb_ps_subset(stb_ps *bigger, stb_ps *smaller)8315+{8316+ int i, listlen;8317+ void **list = stb_ps_fastlist(smaller, &listlen);8318+ for(i=0; i < listlen; ++i)8319+ if (stb_ps_fastlist_valid(list[i]))8320+ if (!stb_ps_find(bigger, list[i]))8321+ return 0;8322+ return 1;8323+}8324+8325+int stb_ps_eq(stb_ps *p0, stb_ps *p1)8326+{8327+ if (stb_ps_count(p0) != stb_ps_count(p1))8328+ return 0;8329+ return stb_ps_subset(p0, p1);8330+}8331+8332+#undef GetBucket8333+#undef GetArray8334+#undef GetHash8335+8336+#undef EncodeBucket8337+#undef EncodeArray8338+#undef EncodeHash8339+8340+#endif8341+8342+8343+//////////////////////////////////////////////////////////////////////////////8344+//8345+// Random Numbers via Meresenne Twister or LCG8346+//8347+8348+STB_EXTERN unsigned int stb_srandLCG(unsigned int seed);8349+STB_EXTERN unsigned int stb_randLCG(void);8350+STB_EXTERN double stb_frandLCG(void);8351+8352+STB_EXTERN void stb_srand(unsigned int seed);8353+STB_EXTERN unsigned int stb_rand(void);8354+STB_EXTERN double stb_frand(void);8355+STB_EXTERN void stb_shuffle(void *p, size_t n, size_t sz,8356+ unsigned int seed);8357+STB_EXTERN void stb_reverse(void *p, size_t n, size_t sz);8358+8359+STB_EXTERN unsigned int stb_randLCG_explicit(unsigned int seed);8360+8361+#define stb_rand_define(x,y) \8362+ \8363+ unsigned int x(void) \8364+ { \8365+ static unsigned int stb__rand = y; \8366+ stb__rand = stb__rand * 2147001325 + 715136305; /* BCPL */ \8367+ return 0x31415926 ^ ((stb__rand >> 16) + (stb__rand << 16)); \8368+ }8369+8370+#ifdef STB_DEFINE8371+unsigned int stb_randLCG_explicit(unsigned int seed)8372+{8373+ return seed * 2147001325 + 715136305;8374+}8375+8376+static unsigned int stb__rand_seed=0;8377+8378+unsigned int stb_srandLCG(unsigned int seed)8379+{8380+ unsigned int previous = stb__rand_seed;8381+ stb__rand_seed = seed;8382+ return previous;8383+}8384+8385+unsigned int stb_randLCG(void)8386+{8387+ stb__rand_seed = stb__rand_seed * 2147001325 + 715136305; // BCPL generator8388+ // shuffle non-random bits to the middle, and xor to decorrelate with seed8389+ return 0x31415926 ^ ((stb__rand_seed >> 16) + (stb__rand_seed << 16));8390+}8391+8392+double stb_frandLCG(void)8393+{8394+ return stb_randLCG() / ((double) (1 << 16) * (1 << 16));8395+}8396+8397+void stb_shuffle(void *p, size_t n, size_t sz, unsigned int seed)8398+{8399+ char *a;8400+ unsigned int old_seed;8401+ int i;8402+ if (seed)8403+ old_seed = stb_srandLCG(seed);8404+ a = (char *) p + (n-1) * sz;8405+8406+ for (i=(int) n; i > 1; --i) {8407+ int j = stb_randLCG() % i;8408+ stb_swap(a, (char *) p + j * sz, sz);8409+ a -= sz;8410+ }8411+ if (seed)8412+ stb_srandLCG(old_seed);8413+}8414+8415+void stb_reverse(void *p, size_t n, size_t sz)8416+{8417+ size_t i,j = n-1;8418+ for (i=0; i < j; ++i,--j) {8419+ stb_swap((char *) p + i * sz, (char *) p + j * sz, sz);8420+ }8421+}8422+8423+// public domain Mersenne Twister by Michael Brundage8424+#define STB__MT_LEN 6248425+8426+int stb__mt_index = STB__MT_LEN*sizeof(int)+1;8427+unsigned int stb__mt_buffer[STB__MT_LEN];8428+8429+void stb_srand(unsigned int seed)8430+{8431+ int i;8432+ stb__mt_buffer[0]= seed & 0xffffffffUL;8433+ for (i=1 ; i < STB__MT_LEN; ++i)8434+ stb__mt_buffer[i] = (1812433253UL * (stb__mt_buffer[i-1] ^ (stb__mt_buffer[i-1] >> 30)) + i);8435+ stb__mt_index = STB__MT_LEN*sizeof(unsigned int);8436+}8437+8438+#define STB__MT_IA 3978439+#define STB__MT_IB (STB__MT_LEN - STB__MT_IA)8440+#define STB__UPPER_MASK 0x800000008441+#define STB__LOWER_MASK 0x7FFFFFFF8442+#define STB__MATRIX_A 0x9908B0DF8443+#define STB__TWIST(b,i,j) ((b)[i] & STB__UPPER_MASK) | ((b)[j] & STB__LOWER_MASK)8444+#define STB__MAGIC(s) (((s)&1)*STB__MATRIX_A)8445+8446+unsigned int stb_rand()8447+{8448+ unsigned int * b = stb__mt_buffer;8449+ int idx = stb__mt_index;8450+ unsigned int s,r;8451+ int i;8452+8453+ if (idx >= STB__MT_LEN*sizeof(unsigned int)) {8454+ if (idx > STB__MT_LEN*sizeof(unsigned int))8455+ stb_srand(0);8456+ idx = 0;8457+ i = 0;8458+ for (; i < STB__MT_IB; i++) {8459+ s = STB__TWIST(b, i, i+1);8460+ b[i] = b[i + STB__MT_IA] ^ (s >> 1) ^ STB__MAGIC(s);8461+ }8462+ for (; i < STB__MT_LEN-1; i++) {8463+ s = STB__TWIST(b, i, i+1);8464+ b[i] = b[i - STB__MT_IB] ^ (s >> 1) ^ STB__MAGIC(s);8465+ }8466+8467+ s = STB__TWIST(b, STB__MT_LEN-1, 0);8468+ b[STB__MT_LEN-1] = b[STB__MT_IA-1] ^ (s >> 1) ^ STB__MAGIC(s);8469+ }8470+ stb__mt_index = idx + sizeof(unsigned int);8471+8472+ r = *(unsigned int *)((unsigned char *)b + idx);8473+8474+ r ^= (r >> 11);8475+ r ^= (r << 7) & 0x9D2C5680;8476+ r ^= (r << 15) & 0xEFC60000;8477+ r ^= (r >> 18);8478+8479+ return r;8480+}8481+8482+double stb_frand(void)8483+{8484+ return stb_rand() / ((double) (1 << 16) * (1 << 16));8485+}8486+8487+#endif8488+8489+8490+//////////////////////////////////////////////////////////////////////////////8491+//8492+// stb_dupe8493+//8494+// stb_dupe is a duplicate-finding system for very, very large data8495+// structures--large enough that sorting is too slow, but not so large8496+// that we can't keep all the data in memory. using it works as follows:8497+//8498+// 1. create an stb_dupe:8499+// provide a hash function8500+// provide an equality function8501+// provide an estimate for the size8502+// optionally provide a comparison function8503+//8504+// 2. traverse your data, 'adding' pointers to the stb_dupe8505+//8506+// 3. finish and ask for duplicates8507+//8508+// the stb_dupe will discard its intermediate data and build8509+// a collection of sorted lists of duplicates, with non-duplicate8510+// entries omitted entirely8511+//8512+//8513+// Implementation strategy:8514+//8515+// while collecting the N items, we keep a hash table of approximate8516+// size sqrt(N). (if you tell use the N up front, the hash table is8517+// just that size exactly)8518+//8519+// each entry in the hash table is just an stb__arr of pointers (no need8520+// to use stb_ps, because we don't need to delete from these)8521+//8522+// for step 3, for each entry in the hash table, we apply stb_dupe to it8523+// recursively. once the size gets small enough (or doesn't decrease8524+// significantly), we switch to either using qsort() on the comparison8525+// function, or else we just do the icky N^2 gather8526+8527+8528+typedef struct stb_dupe stb_dupe;8529+8530+typedef int (*stb_compare_func)(void *a, void *b);8531+typedef int (*stb_hash_func)(void *a, unsigned int seed);8532+8533+STB_EXTERN void stb_dupe_free(stb_dupe *sd);8534+STB_EXTERN stb_dupe *stb_dupe_create(stb_hash_func hash,8535+ stb_compare_func eq, int size, stb_compare_func ineq);8536+STB_EXTERN void stb_dupe_add(stb_dupe *sd, void *item);8537+STB_EXTERN void stb_dupe_finish(stb_dupe *sd);8538+STB_EXTERN int stb_dupe_numsets(stb_dupe *sd);8539+STB_EXTERN void **stb_dupe_set(stb_dupe *sd, int num);8540+STB_EXTERN int stb_dupe_set_count(stb_dupe *sd, int num);8541+8542+struct stb_dupe8543+{8544+ void ***hash_table;8545+ int hash_size;8546+ int size_log2;8547+ int population;8548+8549+ int hash_shift;8550+ stb_hash_func hash;8551+8552+ stb_compare_func eq;8553+ stb_compare_func ineq;8554+8555+ void ***dupes;8556+};8557+8558+#ifdef STB_DEFINE8559+8560+int stb_dupe_numsets(stb_dupe *sd)8561+{8562+ assert(sd->hash_table == NULL);8563+ return stb_arr_len(sd->dupes);8564+}8565+8566+void **stb_dupe_set(stb_dupe *sd, int num)8567+{8568+ assert(sd->hash_table == NULL);8569+ return sd->dupes[num];8570+}8571+8572+int stb_dupe_set_count(stb_dupe *sd, int num)8573+{8574+ assert(sd->hash_table == NULL);8575+ return stb_arr_len(sd->dupes[num]);8576+}8577+8578+stb_dupe *stb_dupe_create(stb_hash_func hash, stb_compare_func eq, int size,8579+ stb_compare_func ineq)8580+{8581+ int i, hsize;8582+ stb_dupe *sd = (stb_dupe *) malloc(sizeof(*sd));8583+8584+ sd->size_log2 = 4;8585+ hsize = 1 << sd->size_log2;8586+ while (hsize * hsize < size) {8587+ ++sd->size_log2;8588+ hsize *= 2;8589+ }8590+8591+ sd->hash = hash;8592+ sd->eq = eq;8593+ sd->ineq = ineq;8594+ sd->hash_shift = 0;8595+8596+ sd->population = 0;8597+ sd->hash_size = hsize;8598+ sd->hash_table = (void ***) malloc(sizeof(*sd->hash_table) * hsize);8599+ for (i=0; i < hsize; ++i)8600+ sd->hash_table[i] = NULL;8601+8602+ sd->dupes = NULL;8603+8604+ return sd;8605+}8606+8607+void stb_dupe_add(stb_dupe *sd, void *item)8608+{8609+ stb_uint32 hash = sd->hash(item, sd->hash_shift);8610+ int z = hash & (sd->hash_size-1);8611+ stb_arr_push(sd->hash_table[z], item);8612+ ++sd->population;8613+}8614+8615+void stb_dupe_free(stb_dupe *sd)8616+{8617+ int i;8618+ for (i=0; i < stb_arr_len(sd->dupes); ++i)8619+ if (sd->dupes[i])8620+ stb_arr_free(sd->dupes[i]);8621+ stb_arr_free(sd->dupes);8622+ free(sd);8623+}8624+8625+static stb_compare_func stb__compare;8626+8627+static int stb__dupe_compare(const void *a, const void *b)8628+{8629+ void *p = *(void **) a;8630+ void *q = *(void **) b;8631+8632+ return stb__compare(p,q);8633+}8634+8635+void stb_dupe_finish(stb_dupe *sd)8636+{8637+ int i,j,k;8638+ assert(sd->dupes == NULL);8639+ for (i=0; i < sd->hash_size; ++i) {8640+ void ** list = sd->hash_table[i];8641+ if (list != NULL) {8642+ int n = stb_arr_len(list);8643+ // @TODO: measure to find good numbers instead of just making them up!8644+ int thresh = (sd->ineq ? 200 : 20);8645+ // if n is large enough to be worth it, and n is smaller than8646+ // before (so we can guarantee we'll use a smaller hash table);8647+ // and there are enough hash bits left, assuming full 32-bit hash8648+ if (n > thresh && n < (sd->population >> 3) && sd->hash_shift + sd->size_log2*2 < 32) {8649+8650+ // recursively process this row using stb_dupe, O(N log log N)8651+8652+ stb_dupe *d = stb_dupe_create(sd->hash, sd->eq, n, sd->ineq);8653+ d->hash_shift = stb_randLCG_explicit(sd->hash_shift);8654+ for (j=0; j < n; ++j)8655+ stb_dupe_add(d, list[j]);8656+ stb_arr_free(sd->hash_table[i]);8657+ stb_dupe_finish(d);8658+ for (j=0; j < stb_arr_len(d->dupes); ++j) {8659+ stb_arr_push(sd->dupes, d->dupes[j]);8660+ d->dupes[j] = NULL; // take over ownership8661+ }8662+ stb_dupe_free(d);8663+8664+ } else if (sd->ineq) {8665+8666+ // process this row using qsort(), O(N log N)8667+ stb__compare = sd->ineq;8668+ qsort(list, n, sizeof(list[0]), stb__dupe_compare);8669+8670+ // find equal subsequences of the list8671+ for (j=0; j < n-1; ) {8672+ // find a subsequence from j..k8673+ for (k=j; k < n; ++k)8674+ // only use ineq so eq can be left undefined8675+ if (sd->ineq(list[j], list[k]))8676+ break;8677+ // k is the first one not in the subsequence8678+ if (k-j > 1) {8679+ void **mylist = NULL;8680+ stb_arr_setlen(mylist, k-j);8681+ memcpy(mylist, list+j, sizeof(list[j]) * (k-j));8682+ stb_arr_push(sd->dupes, mylist);8683+ }8684+ j = k;8685+ }8686+ stb_arr_free(sd->hash_table[i]);8687+ } else {8688+8689+ // process this row using eq(), O(N^2)8690+ for (j=0; j < n; ++j) {8691+ if (list[j] != NULL) {8692+ void **output = NULL;8693+ for (k=j+1; k < n; ++k) {8694+ if (sd->eq(list[j], list[k])) {8695+ if (output == NULL)8696+ stb_arr_push(output, list[j]);8697+ stb_arr_push(output, list[k]);8698+ list[k] = NULL;8699+ }8700+ }8701+ list[j] = NULL;8702+ if (output)8703+ stb_arr_push(sd->dupes, output);8704+ }8705+ }8706+ stb_arr_free(sd->hash_table[i]);8707+ }8708+ }8709+ }8710+ free(sd->hash_table);8711+ sd->hash_table = NULL;8712+}8713+#endif8714+8715+//////////////////////////////////////////////////////////////////////////////8716+//8717+// templatized Sort routine8718+//8719+// This is an attempt to implement a templated sorting algorithm.8720+// To use it, you have to explicitly instantiate it as a _function_,8721+// then you call that function. This allows the comparison to be inlined,8722+// giving the sort similar performance to C++ sorts.8723+//8724+// It implements quicksort with three-way-median partitioning (generally8725+// well-behaved), with a final insertion sort pass.8726+//8727+// When you define the compare expression, you should assume you have8728+// elements of your array pointed to by 'a' and 'b', and perform the comparison8729+// on those. OR you can use one or more statements; first say '0;', then8730+// write whatever code you want, and compute the result into a variable 'c'.8731+8732+#define stb_declare_sort(FUNCNAME, TYPE) \8733+ void FUNCNAME(TYPE *p, int n)8734+#define stb_define_sort(FUNCNAME,TYPE,COMPARE) \8735+ stb__define_sort( void, FUNCNAME,TYPE,COMPARE)8736+#define stb_define_sort_static(FUNCNAME,TYPE,COMPARE) \8737+ stb__define_sort(static void, FUNCNAME,TYPE,COMPARE)8738+8739+#define stb__define_sort(MODE, FUNCNAME, TYPE, COMPARE) \8740+ \8741+static void STB_(FUNCNAME,_ins_sort)(TYPE *p, int n) \8742+{ \8743+ int i,j; \8744+ for (i=1; i < n; ++i) { \8745+ TYPE t = p[i], *a = &t; \8746+ j = i; \8747+ while (j > 0) { \8748+ TYPE *b = &p[j-1]; \8749+ int c = COMPARE; \8750+ if (!c) break; \8751+ p[j] = p[j-1]; \8752+ --j; \8753+ } \8754+ if (i != j) \8755+ p[j] = t; \8756+ } \8757+} \8758+ \8759+static void STB_(FUNCNAME,_quicksort)(TYPE *p, int n) \8760+{ \8761+ /* threshold for transitioning to insertion sort */ \8762+ while (n > 12) { \8763+ TYPE *a,*b,t; \8764+ int c01,c12,c,m,i,j; \8765+ \8766+ /* compute median of three */ \8767+ m = n >> 1; \8768+ a = &p[0]; \8769+ b = &p[m]; \8770+ c = COMPARE; \8771+ c01 = c; \8772+ a = &p[m]; \8773+ b = &p[n-1]; \8774+ c = COMPARE; \8775+ c12 = c; \8776+ /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ \8777+ if (c01 != c12) { \8778+ /* otherwise, we'll need to swap something else to middle */ \8779+ int z; \8780+ a = &p[0]; \8781+ b = &p[n-1]; \8782+ c = COMPARE; \8783+ /* 0>mid && mid<n: 0>n => n; 0<n => 0 */ \8784+ /* 0<mid && mid>n: 0>n => 0; 0<n => n */ \8785+ z = (c == c12) ? 0 : n-1; \8786+ t = p[z]; \8787+ p[z] = p[m]; \8788+ p[m] = t; \8789+ } \8790+ /* now p[m] is the median-of-three */ \8791+ /* swap it to the beginning so it won't move around */ \8792+ t = p[0]; \8793+ p[0] = p[m]; \8794+ p[m] = t; \8795+ \8796+ /* partition loop */ \8797+ i=1; \8798+ j=n-1; \8799+ for(;;) { \8800+ /* handling of equality is crucial here */ \8801+ /* for sentinels & efficiency with duplicates */ \8802+ b = &p[0]; \8803+ for (;;++i) { \8804+ a=&p[i]; \8805+ c = COMPARE; \8806+ if (!c) break; \8807+ } \8808+ a = &p[0]; \8809+ for (;;--j) { \8810+ b=&p[j]; \8811+ c = COMPARE; \8812+ if (!c) break; \8813+ } \8814+ /* make sure we haven't crossed */ \8815+ if (i >= j) break; \8816+ t = p[i]; \8817+ p[i] = p[j]; \8818+ p[j] = t; \8819+ \8820+ ++i; \8821+ --j; \8822+ } \8823+ /* recurse on smaller side, iterate on larger */ \8824+ if (j < (n-i)) { \8825+ STB_(FUNCNAME,_quicksort)(p,j); \8826+ p = p+i; \8827+ n = n-i; \8828+ } else { \8829+ STB_(FUNCNAME,_quicksort)(p+i, n-i); \8830+ n = j; \8831+ } \8832+ } \8833+} \8834+ \8835+MODE FUNCNAME(TYPE *p, int n) \8836+{ \8837+ STB_(FUNCNAME, _quicksort)(p, n); \8838+ STB_(FUNCNAME, _ins_sort)(p, n); \8839+} \8840+8841+8842+//////////////////////////////////////////////////////////////////////////////8843+//8844+// stb_bitset an array of booleans indexed by integers8845+//8846+8847+typedef stb_uint32 stb_bitset;8848+8849+STB_EXTERN stb_bitset *stb_bitset_new(int value, int len);8850+8851+#define stb_bitset_clearall(arr,len) (memset(arr, 0, 4 * (len)))8852+#define stb_bitset_setall(arr,len) (memset(arr, 255, 4 * (len)))8853+8854+#define stb_bitset_setbit(arr,n) ((arr)[(n) >> 5] |= (1 << (n & 31)))8855+#define stb_bitset_clearbit(arr,n) ((arr)[(n) >> 5] &= ~(1 << (n & 31)))8856+#define stb_bitset_testbit(arr,n) ((arr)[(n) >> 5] & (1 << (n & 31)))8857+8858+STB_EXTERN stb_bitset *stb_bitset_union(stb_bitset *p0, stb_bitset *p1, int len);8859+8860+STB_EXTERN int *stb_bitset_getlist(stb_bitset *out, int start, int end);8861+8862+STB_EXTERN int stb_bitset_eq(stb_bitset *p0, stb_bitset *p1, int len);8863+STB_EXTERN int stb_bitset_disjoint(stb_bitset *p0, stb_bitset *p1, int len);8864+STB_EXTERN int stb_bitset_disjoint_0(stb_bitset *p0, stb_bitset *p1, int len);8865+STB_EXTERN int stb_bitset_subset(stb_bitset *bigger, stb_bitset *smaller, int len);8866+STB_EXTERN int stb_bitset_unioneq_changed(stb_bitset *p0, stb_bitset *p1, int len);8867+8868+#ifdef STB_DEFINE8869+int stb_bitset_eq(stb_bitset *p0, stb_bitset *p1, int len)8870+{8871+ int i;8872+ for (i=0; i < len; ++i)8873+ if (p0[i] != p1[i]) return 0;8874+ return 1;8875+}8876+8877+int stb_bitset_disjoint(stb_bitset *p0, stb_bitset *p1, int len)8878+{8879+ int i;8880+ for (i=0; i < len; ++i)8881+ if (p0[i] & p1[i]) return 0;8882+ return 1;8883+}8884+8885+int stb_bitset_disjoint_0(stb_bitset *p0, stb_bitset *p1, int len)8886+{8887+ int i;8888+ for (i=0; i < len; ++i)8889+ if ((p0[i] | p1[i]) != 0xffffffff) return 0;8890+ return 1;8891+}8892+8893+int stb_bitset_subset(stb_bitset *bigger, stb_bitset *smaller, int len)8894+{8895+ int i;8896+ for (i=0; i < len; ++i)8897+ if ((bigger[i] & smaller[i]) != smaller[i]) return 0;8898+ return 1;8899+}8900+8901+stb_bitset *stb_bitset_union(stb_bitset *p0, stb_bitset *p1, int len)8902+{8903+ int i;8904+ stb_bitset *d = (stb_bitset *) malloc(sizeof(*d) * len);8905+ for (i=0; i < len; ++i) d[i] = p0[i] | p1[i];8906+ return d;8907+}8908+8909+int stb_bitset_unioneq_changed(stb_bitset *p0, stb_bitset *p1, int len)8910+{8911+ int i, changed=0;8912+ for (i=0; i < len; ++i) {8913+ stb_bitset d = p0[i] | p1[i];8914+ if (d != p0[i]) {8915+ p0[i] = d;8916+ changed = 1;8917+ }8918+ }8919+ return changed;8920+}8921+8922+stb_bitset *stb_bitset_new(int value, int len)8923+{8924+ int i;8925+ stb_bitset *d = (stb_bitset *) malloc(sizeof(*d) * len);8926+ if (value) value = 0xffffffff;8927+ for (i=0; i < len; ++i) d[i] = value;8928+ return d;8929+}8930+8931+int *stb_bitset_getlist(stb_bitset *out, int start, int end)8932+{8933+ int *list = NULL;8934+ int i;8935+ for (i=start; i < end; ++i)8936+ if (stb_bitset_testbit(out, i))8937+ stb_arr_push(list, i);8938+ return list;8939+}8940+#endif8941+8942+//////////////////////////////////////////////////////////////////////////////8943+//8944+// stb_wordwrap quality word-wrapping for fixed-width fonts8945+//8946+8947+STB_EXTERN int stb_wordwrap(int *pairs, int pair_max, int count, char *str);8948+STB_EXTERN int *stb_wordwrapalloc(int count, char *str);8949+8950+#ifdef STB_DEFINE8951+8952+int stb_wordwrap(int *pairs, int pair_max, int count, char *str)8953+{8954+ int n=0,i=0, start=0,nonwhite=0;8955+ if (pairs == NULL) pair_max = 0x7ffffff0;8956+ else pair_max *= 2;8957+ // parse8958+ for(;;) {8959+ int s=i; // first whitespace char; last nonwhite+18960+ int w; // word start8961+ // accept whitespace8962+ while (isspace(str[i])) {8963+ if (str[i] == '\n' || str[i] == '\r') {8964+ if (str[i] + str[i+1] == '\n' + '\r') ++i;8965+ if (n >= pair_max) return -1;8966+ if (pairs) pairs[n] = start, pairs[n+1] = s-start;8967+ n += 2;8968+ nonwhite=0;8969+ start = i+1;8970+ s = start;8971+ }8972+ ++i;8973+ }8974+ if (i >= start+count) {8975+ // we've gone off the end using whitespace8976+ if (nonwhite) {8977+ if (n >= pair_max) return -1;8978+ if (pairs) pairs[n] = start, pairs[n+1] = s-start;8979+ n += 2;8980+ start = s = i;8981+ nonwhite=0;8982+ } else {8983+ // output all the whitespace8984+ while (i >= start+count) {8985+ if (n >= pair_max) return -1;8986+ if (pairs) pairs[n] = start, pairs[n+1] = count;8987+ n += 2;8988+ start += count;8989+ }8990+ s = start;8991+ }8992+ }8993+8994+ if (str[i] == 0) break;8995+ // now scan out a word and see if it fits8996+ w = i;8997+ while (str[i] && !isspace(str[i])) {8998+ ++i;8999+ }9000+ // wrapped?9001+ if (i > start + count) {9002+ // huge?9003+ if (i-s <= count) {9004+ if (n >= pair_max) return -1;9005+ if (pairs) pairs[n] = start, pairs[n+1] = s-start;9006+ n += 2;9007+ start = w;9008+ } else {9009+ // This word is longer than one line. If we wrap it onto N lines9010+ // there are leftover chars. do those chars fit on the cur line?9011+ // But if we have leading whitespace, we force it to start here.9012+ if ((w-start) + ((i-w) % count) <= count || !nonwhite) {9013+ // output a full line9014+ if (n >= pair_max) return -1;9015+ if (pairs) pairs[n] = start, pairs[n+1] = count;9016+ n += 2;9017+ start += count;9018+ w = start;9019+ } else {9020+ // output a partial line, trimming trailing whitespace9021+ if (s != start) {9022+ if (n >= pair_max) return -1;9023+ if (pairs) pairs[n] = start, pairs[n+1] = s-start;9024+ n += 2;9025+ start = w;9026+ }9027+ }9028+ // now output full lines as needed9029+ while (start + count <= i) {9030+ if (n >= pair_max) return -1;9031+ if (pairs) pairs[n] = start, pairs[n+1] = count;9032+ n += 2;9033+ start += count;9034+ }9035+ }9036+ }9037+ nonwhite=1;9038+ }9039+ if (start < i) {9040+ if (n >= pair_max) return -1;9041+ if (pairs) pairs[n] = start, pairs[n+1] = i-start;9042+ n += 2;9043+ }9044+ return n>>1;9045+}9046+9047+int *stb_wordwrapalloc(int count, char *str)9048+{9049+ int n = stb_wordwrap(NULL,0,count,str);9050+ int *z = NULL;9051+ stb_arr_setlen(z, n*2);9052+ stb_wordwrap(z, n, count, str);9053+ return z;9054+}9055+#endif9056+9057+9058+//////////////////////////////////////////////////////////////////////////////9059+//9060+// stb_match: wildcards and regexping9061+//9062+9063+STB_EXTERN int stb_wildmatch (char *expr, char *candidate);9064+STB_EXTERN int stb_wildmatchi(char *expr, char *candidate);9065+STB_EXTERN int stb_wildfind (char *expr, char *candidate);9066+STB_EXTERN int stb_wildfindi (char *expr, char *candidate);9067+9068+STB_EXTERN int stb_regex(char *regex, char *candidate);9069+9070+typedef struct stb_matcher stb_matcher;9071+9072+STB_EXTERN stb_matcher *stb_regex_matcher(char *regex);9073+STB_EXTERN int stb_matcher_match(stb_matcher *m, char *str);9074+STB_EXTERN int stb_matcher_find(stb_matcher *m, char *str);9075+STB_EXTERN void stb_matcher_free(stb_matcher *f);9076+9077+STB_EXTERN stb_matcher *stb_lex_matcher(void);9078+STB_EXTERN int stb_lex_item(stb_matcher *m, const char *str, int result);9079+STB_EXTERN int stb_lex_item_wild(stb_matcher *matcher, const char *regex, int result);9080+STB_EXTERN int stb_lex(stb_matcher *m, char *str, int *len);9081+9082+9083+9084+#ifdef STB_DEFINE9085+9086+static int stb__match_qstring(char *candidate, char *qstring, int qlen, int insensitive)9087+{9088+ int i;9089+ if (insensitive) {9090+ for (i=0; i < qlen; ++i)9091+ if (qstring[i] == '?') {9092+ if (!candidate[i]) return 0;9093+ } else9094+ if (tolower(qstring[i]) != tolower(candidate[i]))9095+ return 0;9096+ } else {9097+ for (i=0; i < qlen; ++i)9098+ if (qstring[i] == '?') {9099+ if (!candidate[i]) return 0;9100+ } else9101+ if (qstring[i] != candidate[i])9102+ return 0;9103+ }9104+ return 1;9105+}9106+9107+static int stb__find_qstring(char *candidate, char *qstring, int qlen, int insensitive)9108+{9109+ char c;9110+9111+ int offset=0;9112+ while (*qstring == '?') {9113+ ++qstring;9114+ --qlen;9115+ ++candidate;9116+ if (qlen == 0) return 0;9117+ if (*candidate == 0) return -1;9118+ }9119+9120+ c = *qstring++;9121+ --qlen;9122+ if (insensitive) c = tolower(c);9123+9124+ while (candidate[offset]) {9125+ if (c == (insensitive ? tolower(candidate[offset]) : candidate[offset]))9126+ if (stb__match_qstring(candidate+offset+1, qstring, qlen, insensitive))9127+ return offset;9128+ ++offset;9129+ }9130+9131+ return -1;9132+}9133+9134+int stb__wildmatch_raw2(char *expr, char *candidate, int search, int insensitive)9135+{9136+ int where=0;9137+ int start = -1;9138+9139+ if (!search) {9140+ // parse to first '*'9141+ if (*expr != '*')9142+ start = 0;9143+ while (*expr != '*') {9144+ if (!*expr)9145+ return *candidate == 0 ? 0 : -1;9146+ if (*expr == '?') {9147+ if (!*candidate) return -1;9148+ } else {9149+ if (insensitive) {9150+ if (tolower(*candidate) != tolower(*expr))9151+ return -1;9152+ } else9153+ if (*candidate != *expr)9154+ return -1;9155+ }9156+ ++candidate, ++expr, ++where;9157+ }9158+ } else {9159+ // 0-length search string9160+ if (!*expr)9161+ return 0;9162+ }9163+9164+ assert(search || *expr == '*');9165+ if (!search)9166+ ++expr;9167+9168+ // implicit '*' at this point9169+9170+ while (*expr) {9171+ int o=0;9172+ // combine redundant * characters9173+ while (expr[0] == '*') ++expr;9174+9175+ // ok, at this point, expr[-1] == '*',9176+ // and expr[0] != '*'9177+9178+ if (!expr[0]) return start >= 0 ? start : 0;9179+9180+ // now find next '*'9181+ o = 0;9182+ while (expr[o] != '*') {9183+ if (expr[o] == 0)9184+ break;9185+ ++o;9186+ }9187+ // if no '*', scan to end, then match at end9188+ if (expr[o] == 0 && !search) {9189+ int z;9190+ for (z=0; z < o; ++z)9191+ if (candidate[z] == 0)9192+ return -1;9193+ while (candidate[z])9194+ ++z;9195+ // ok, now check if they match9196+ if (stb__match_qstring(candidate+z-o, expr, o, insensitive))9197+ return start >= 0 ? start : 0;9198+ return -1;9199+ } else {9200+ // if yes '*', then do stb__find_qmatch on the intervening chars9201+ int n = stb__find_qstring(candidate, expr, o, insensitive);9202+ if (n < 0)9203+ return -1;9204+ if (start < 0)9205+ start = where + n;9206+ expr += o;9207+ candidate += n+o;9208+ }9209+9210+ if (*expr == 0) {9211+ assert(search);9212+ return start;9213+ }9214+9215+ assert(*expr == '*');9216+ ++expr;9217+ }9218+9219+ return start >= 0 ? start : 0;9220+}9221+9222+int stb__wildmatch_raw(char *expr, char *candidate, int search, int insensitive)9223+{9224+ char buffer[256];9225+ // handle multiple search strings9226+ char *s = strchr(expr, ';');9227+ char *last = expr;9228+ while (s) {9229+ int z;9230+ // need to allow for non-writeable strings... assume they're small9231+ if (s - last < 256) {9232+ stb_strncpy(buffer, last, (int) (s-last+1));9233+ z = stb__wildmatch_raw2(buffer, candidate, search, insensitive);9234+ } else {9235+ *s = 0;9236+ z = stb__wildmatch_raw2(last, candidate, search, insensitive);9237+ *s = ';';9238+ }9239+ if (z >= 0) return z;9240+ last = s+1;9241+ s = strchr(last, ';');9242+ }9243+ return stb__wildmatch_raw2(last, candidate, search, insensitive);9244+}9245+9246+int stb_wildmatch(char *expr, char *candidate)9247+{9248+ return stb__wildmatch_raw(expr, candidate, 0,0) >= 0;9249+}9250+9251+int stb_wildmatchi(char *expr, char *candidate)9252+{9253+ return stb__wildmatch_raw(expr, candidate, 0,1) >= 0;9254+}9255+9256+int stb_wildfind(char *expr, char *candidate)9257+{9258+ return stb__wildmatch_raw(expr, candidate, 1,0);9259+}9260+9261+int stb_wildfindi(char *expr, char *candidate)9262+{9263+ return stb__wildmatch_raw(expr, candidate, 1,1);9264+}9265+9266+typedef struct9267+{9268+ stb_int16 transition[256];9269+} stb_dfa;9270+9271+// an NFA node represents a state you're in; it then has9272+// an arbitrary number of edges dangling off of it9273+// note this isn't utf8-y9274+typedef struct9275+{9276+ stb_int16 match; // character/set to match9277+ stb_uint16 node; // output node to go to9278+} stb_nfa_edge;9279+9280+typedef struct9281+{9282+ stb_int16 goal; // does reaching this win the prize?9283+ stb_uint8 active; // is this in the active list9284+ stb_nfa_edge *out;9285+ stb_uint16 *eps; // list of epsilon closures9286+} stb_nfa_node;9287+9288+#define STB__DFA_UNDEF -19289+#define STB__DFA_GOAL -29290+#define STB__DFA_END -39291+#define STB__DFA_MGOAL -49292+#define STB__DFA_VALID 09293+9294+#define STB__NFA_STOP_GOAL -19295+9296+// compiled regexp9297+struct stb_matcher9298+{9299+ stb_uint16 start_node;9300+ stb_int16 dfa_start;9301+ stb_uint32 *charset;9302+ int num_charset;9303+ int match_start;9304+ stb_nfa_node *nodes;9305+ int does_lex;9306+9307+ // dfa matcher9308+ stb_dfa * dfa;9309+ stb_uint32 * dfa_mapping;9310+ stb_int16 * dfa_result;9311+ int num_words_per_dfa;9312+};9313+9314+static int stb__add_node(stb_matcher *matcher)9315+{9316+ stb_nfa_node z;9317+ z.active = 0;9318+ z.eps = 0;9319+ z.goal = 0;9320+ z.out = 0;9321+ stb_arr_push(matcher->nodes, z);9322+ return stb_arr_len(matcher->nodes)-1;9323+}9324+9325+static void stb__add_epsilon(stb_matcher *matcher, int from, int to)9326+{9327+ assert(from != to);9328+ if (matcher->nodes[from].eps == NULL)9329+ stb_arr_malloc((void **) &matcher->nodes[from].eps, matcher);9330+ stb_arr_push(matcher->nodes[from].eps, to);9331+}9332+9333+static void stb__add_edge(stb_matcher *matcher, int from, int to, int type)9334+{9335+ stb_nfa_edge z = { (stb_int16)type, (stb_uint16)to };9336+ if (matcher->nodes[from].out == NULL)9337+ stb_arr_malloc((void **) &matcher->nodes[from].out, matcher);9338+ stb_arr_push(matcher->nodes[from].out, z);9339+}9340+9341+static char *stb__reg_parse_alt(stb_matcher *m, int s, char *r, stb_uint16 *e);9342+static char *stb__reg_parse(stb_matcher *matcher, int start, char *regex, stb_uint16 *end)9343+{9344+ int n;9345+ int last_start = -1;9346+ stb_uint16 last_end = start;9347+9348+ while (*regex) {9349+ switch (*regex) {9350+ case '(':9351+ last_start = last_end;9352+ regex = stb__reg_parse_alt(matcher, last_end, regex+1, &last_end);9353+ if (regex == NULL || *regex != ')')9354+ return NULL;9355+ ++regex;9356+ break;9357+9358+ case '|':9359+ case ')':9360+ *end = last_end;9361+ return regex;9362+9363+ case '?':9364+ if (last_start < 0) return NULL;9365+ stb__add_epsilon(matcher, last_start, last_end);9366+ ++regex;9367+ break;9368+9369+ case '*':9370+ if (last_start < 0) return NULL;9371+ stb__add_epsilon(matcher, last_start, last_end);9372+9373+ // fall through9374+9375+ case '+':9376+ if (last_start < 0) return NULL;9377+ stb__add_epsilon(matcher, last_end, last_start);9378+ // prevent links back to last_end from chaining to last_start9379+ n = stb__add_node(matcher);9380+ stb__add_epsilon(matcher, last_end, n);9381+ last_end = n;9382+ ++regex;9383+ break;9384+9385+ case '{': // not supported!9386+ // @TODO: given {n,m}, clone last_start to last_end m times,9387+ // and include epsilons from start to first m-n blocks9388+ return NULL;9389+9390+ case '\\':9391+ ++regex;9392+ if (!*regex) return NULL;9393+9394+ // fallthrough9395+ default: // match exactly this character9396+ n = stb__add_node(matcher);9397+ stb__add_edge(matcher, last_end, n, *regex);9398+ last_start = last_end;9399+ last_end = n;9400+ ++regex;9401+ break;9402+9403+ case '$':9404+ n = stb__add_node(matcher);9405+ stb__add_edge(matcher, last_end, n, '\n');9406+ last_start = last_end;9407+ last_end = n;9408+ ++regex;9409+ break;9410+9411+ case '.':9412+ n = stb__add_node(matcher);9413+ stb__add_edge(matcher, last_end, n, -1);9414+ last_start = last_end;9415+ last_end = n;9416+ ++regex;9417+ break;9418+9419+ case '[': {9420+ stb_uint8 flags[256];9421+ int invert = 0,z;9422+ ++regex;9423+ if (matcher->num_charset == 0) {9424+ matcher->charset = (stb_uint *) stb_malloc(matcher, sizeof(*matcher->charset) * 256);9425+ memset(matcher->charset, 0, sizeof(*matcher->charset) * 256);9426+ }9427+9428+ memset(flags,0,sizeof(flags));9429+9430+ // leading ^ is special9431+ if (*regex == '^')9432+ ++regex, invert = 1;9433+9434+ // leading ] is special9435+ if (*regex == ']') {9436+ flags[(int) ']'] = 1;9437+ ++regex;9438+ }9439+ while (*regex != ']') {9440+ stb_uint a;9441+ if (!*regex) return NULL;9442+ a = *regex++;9443+ if (regex[0] == '-' && regex[1] != ']') {9444+ stb_uint i,b = regex[1];9445+ regex += 2;9446+ if (b == 0) return NULL;9447+ if (a > b) return NULL;9448+ for (i=a; i <= b; ++i)9449+ flags[i] = 1;9450+ } else9451+ flags[a] = 1;9452+ }9453+ ++regex;9454+ if (invert) {9455+ int i;9456+ for (i=0; i < 256; ++i)9457+ flags[i] = 1-flags[i];9458+ }9459+9460+ // now check if any existing charset matches9461+ for (z=0; z < matcher->num_charset; ++z) {9462+ int i, k[2] = { 0, 1 << z};9463+ for (i=0; i < 256; ++i) {9464+ unsigned int f = k[flags[i]];9465+ if ((matcher->charset[i] & k[1]) != f)9466+ break;9467+ }9468+ if (i == 256) break;9469+ }9470+9471+ if (z == matcher->num_charset) {9472+ int i;9473+ ++matcher->num_charset;9474+ if (matcher->num_charset > 32) {9475+ assert(0); /* NOTREACHED */9476+ return NULL; // too many charsets, oops9477+ }9478+ for (i=0; i < 256; ++i)9479+ if (flags[i])9480+ matcher->charset[i] |= (1 << z);9481+ }9482+9483+ n = stb__add_node(matcher);9484+ stb__add_edge(matcher, last_end, n, -2 - z);9485+ last_start = last_end;9486+ last_end = n;9487+ break;9488+ }9489+ }9490+ }9491+ *end = last_end;9492+ return regex;9493+}9494+9495+static char *stb__reg_parse_alt(stb_matcher *matcher, int start, char *regex, stb_uint16 *end)9496+{9497+ stb_uint16 last_end = start;9498+ stb_uint16 main_end;9499+9500+ int head, tail;9501+9502+ head = stb__add_node(matcher);9503+ stb__add_epsilon(matcher, start, head);9504+9505+ regex = stb__reg_parse(matcher, head, regex, &last_end);9506+ if (regex == NULL) return NULL;9507+ if (*regex == 0 || *regex == ')') {9508+ *end = last_end;9509+ return regex;9510+ }9511+9512+ main_end = last_end;9513+ tail = stb__add_node(matcher);9514+9515+ stb__add_epsilon(matcher, last_end, tail);9516+9517+ // start alternatives from the same starting node; use epsilon9518+ // transitions to combine their endings9519+ while(*regex && *regex != ')') {9520+ assert(*regex == '|');9521+ head = stb__add_node(matcher);9522+ stb__add_epsilon(matcher, start, head);9523+ regex = stb__reg_parse(matcher, head, regex+1, &last_end);9524+ if (regex == NULL)9525+ return NULL;9526+ stb__add_epsilon(matcher, last_end, tail);9527+ }9528+9529+ *end = tail;9530+ return regex;9531+}9532+9533+static char *stb__wild_parse(stb_matcher *matcher, int start, char *str, stb_uint16 *end)9534+{9535+ int n;9536+ stb_uint16 last_end;9537+9538+ last_end = stb__add_node(matcher);9539+ stb__add_epsilon(matcher, start, last_end);9540+9541+ while (*str) {9542+ switch (*str) {9543+ // fallthrough9544+ default: // match exactly this character9545+ n = stb__add_node(matcher);9546+ if (toupper(*str) == tolower(*str)) {9547+ stb__add_edge(matcher, last_end, n, *str);9548+ } else {9549+ stb__add_edge(matcher, last_end, n, tolower(*str));9550+ stb__add_edge(matcher, last_end, n, toupper(*str));9551+ }9552+ last_end = n;9553+ ++str;9554+ break;9555+9556+ case '?':9557+ n = stb__add_node(matcher);9558+ stb__add_edge(matcher, last_end, n, -1);9559+ last_end = n;9560+ ++str;9561+ break;9562+9563+ case '*':9564+ n = stb__add_node(matcher);9565+ stb__add_edge(matcher, last_end, n, -1);9566+ stb__add_epsilon(matcher, last_end, n);9567+ stb__add_epsilon(matcher, n, last_end);9568+ last_end = n;9569+ ++str;9570+ break;9571+ }9572+ }9573+9574+ // now require end of string to match9575+ n = stb__add_node(matcher);9576+ stb__add_edge(matcher, last_end, n, 0);9577+ last_end = n;9578+9579+ *end = last_end;9580+ return str;9581+}9582+9583+static int stb__opt(stb_matcher *m, int n)9584+{9585+ for(;;) {9586+ stb_nfa_node *p = &m->nodes[n];9587+ if (p->goal) return n;9588+ if (stb_arr_len(p->out)) return n;9589+ if (stb_arr_len(p->eps) != 1) return n;9590+ n = p->eps[0];9591+ }9592+}9593+9594+static void stb__optimize(stb_matcher *m)9595+{9596+ // if the target of any edge is a node with exactly9597+ // one out-epsilon, shorten it9598+ int i,j;9599+ for (i=0; i < stb_arr_len(m->nodes); ++i) {9600+ stb_nfa_node *p = &m->nodes[i];9601+ for (j=0; j < stb_arr_len(p->out); ++j)9602+ p->out[j].node = stb__opt(m,p->out[j].node);9603+ for (j=0; j < stb_arr_len(p->eps); ++j)9604+ p->eps[j] = stb__opt(m,p->eps[j] );9605+ }9606+ m->start_node = stb__opt(m,m->start_node);9607+}9608+9609+void stb_matcher_free(stb_matcher *f)9610+{9611+ stb_free(f);9612+}9613+9614+static stb_matcher *stb__alloc_matcher(void)9615+{9616+ stb_matcher *matcher = (stb_matcher *) stb_malloc(0,sizeof(*matcher));9617+9618+ matcher->start_node = 0;9619+ stb_arr_malloc((void **) &matcher->nodes, matcher);9620+ matcher->num_charset = 0;9621+ matcher->match_start = 0;9622+ matcher->does_lex = 0;9623+9624+ matcher->dfa_start = STB__DFA_UNDEF;9625+ stb_arr_malloc((void **) &matcher->dfa, matcher);9626+ stb_arr_malloc((void **) &matcher->dfa_mapping, matcher);9627+ stb_arr_malloc((void **) &matcher->dfa_result, matcher);9628+9629+ stb__add_node(matcher);9630+9631+ return matcher;9632+}9633+9634+static void stb__lex_reset(stb_matcher *matcher)9635+{9636+ // flush cached dfa data9637+ stb_arr_setlen(matcher->dfa, 0);9638+ stb_arr_setlen(matcher->dfa_mapping, 0);9639+ stb_arr_setlen(matcher->dfa_result, 0);9640+ matcher->dfa_start = STB__DFA_UNDEF;9641+}9642+9643+stb_matcher *stb_regex_matcher(char *regex)9644+{9645+ char *z;9646+ stb_uint16 end;9647+ stb_matcher *matcher = stb__alloc_matcher();9648+ if (*regex == '^') {9649+ matcher->match_start = 1;9650+ ++regex;9651+ }9652+9653+ z = stb__reg_parse_alt(matcher, matcher->start_node, regex, &end);9654+9655+ if (!z || *z) {9656+ stb_free(matcher);9657+ return NULL;9658+ }9659+9660+ ((matcher->nodes)[(int) end]).goal = STB__NFA_STOP_GOAL;9661+9662+ return matcher;9663+}9664+9665+stb_matcher *stb_lex_matcher(void)9666+{9667+ stb_matcher *matcher = stb__alloc_matcher();9668+9669+ matcher->match_start = 1;9670+ matcher->does_lex = 1;9671+9672+ return matcher;9673+}9674+9675+int stb_lex_item(stb_matcher *matcher, const char *regex, int result)9676+{9677+ char *z;9678+ stb_uint16 end;9679+9680+ z = stb__reg_parse_alt(matcher, matcher->start_node, (char*) regex, &end);9681+9682+ if (z == NULL)9683+ return 0;9684+9685+ stb__lex_reset(matcher);9686+9687+ matcher->nodes[(int) end].goal = result;9688+ return 1;9689+}9690+9691+int stb_lex_item_wild(stb_matcher *matcher, const char *regex, int result)9692+{9693+ char *z;9694+ stb_uint16 end;9695+9696+ z = stb__wild_parse(matcher, matcher->start_node, (char*) regex, &end);9697+9698+ if (z == NULL)9699+ return 0;9700+9701+ stb__lex_reset(matcher);9702+9703+ matcher->nodes[(int) end].goal = result;9704+ return 1;9705+}9706+9707+static void stb__clear(stb_matcher *m, stb_uint16 *list)9708+{9709+ int i;9710+ for (i=0; i < stb_arr_len(list); ++i)9711+ m->nodes[(int) list[i]].active = 0;9712+}9713+9714+static int stb__clear_goalcheck(stb_matcher *m, stb_uint16 *list)9715+{9716+ int i, t=0;9717+ for (i=0; i < stb_arr_len(list); ++i) {9718+ t += m->nodes[(int) list[i]].goal;9719+ m->nodes[(int) list[i]].active = 0;9720+ }9721+ return t;9722+}9723+9724+static stb_uint16 * stb__add_if_inactive(stb_matcher *m, stb_uint16 *list, int n)9725+{9726+ if (!m->nodes[n].active) {9727+ stb_arr_push(list, n);9728+ m->nodes[n].active = 1;9729+ }9730+ return list;9731+}9732+9733+static stb_uint16 * stb__eps_closure(stb_matcher *m, stb_uint16 *list)9734+{9735+ int i,n = stb_arr_len(list);9736+9737+ for(i=0; i < n; ++i) {9738+ stb_uint16 *e = m->nodes[(int) list[i]].eps;9739+ if (e) {9740+ int j,k = stb_arr_len(e);9741+ for (j=0; j < k; ++j)9742+ list = stb__add_if_inactive(m, list, e[j]);9743+ n = stb_arr_len(list);9744+ }9745+ }9746+9747+ return list;9748+}9749+9750+int stb_matcher_match(stb_matcher *m, char *str)9751+{9752+ int result = 0;9753+ int i,j,y,z;9754+ stb_uint16 *previous = NULL;9755+ stb_uint16 *current = NULL;9756+ stb_uint16 *temp;9757+9758+ stb_arr_setsize(previous, 4);9759+ stb_arr_setsize(current, 4);9760+9761+ previous = stb__add_if_inactive(m, previous, m->start_node);9762+ previous = stb__eps_closure(m,previous);9763+ stb__clear(m, previous);9764+9765+ while (*str && stb_arr_len(previous)) {9766+ y = stb_arr_len(previous);9767+ for (i=0; i < y; ++i) {9768+ stb_nfa_node *n = &m->nodes[(int) previous[i]];9769+ z = stb_arr_len(n->out);9770+ for (j=0; j < z; ++j) {9771+ if (n->out[j].match >= 0) {9772+ if (n->out[j].match == *str)9773+ current = stb__add_if_inactive(m, current, n->out[j].node);9774+ } else if (n->out[j].match == -1) {9775+ if (*str != '\n')9776+ current = stb__add_if_inactive(m, current, n->out[j].node);9777+ } else if (n->out[j].match < -1) {9778+ int z = -n->out[j].match - 2;9779+ if (m->charset[(stb_uint8) *str] & (1 << z))9780+ current = stb__add_if_inactive(m, current, n->out[j].node);9781+ }9782+ }9783+ }9784+ stb_arr_setlen(previous, 0);9785+9786+ temp = previous;9787+ previous = current;9788+ current = temp;9789+9790+ previous = stb__eps_closure(m,previous);9791+ stb__clear(m, previous);9792+9793+ ++str;9794+ }9795+9796+ // transition to pick up a '$' at the end9797+ y = stb_arr_len(previous);9798+ for (i=0; i < y; ++i)9799+ m->nodes[(int) previous[i]].active = 1;9800+9801+ for (i=0; i < y; ++i) {9802+ stb_nfa_node *n = &m->nodes[(int) previous[i]];9803+ z = stb_arr_len(n->out);9804+ for (j=0; j < z; ++j) {9805+ if (n->out[j].match == '\n')9806+ current = stb__add_if_inactive(m, current, n->out[j].node);9807+ }9808+ }9809+9810+ previous = stb__eps_closure(m,previous);9811+ stb__clear(m, previous);9812+9813+ y = stb_arr_len(previous);9814+ for (i=0; i < y; ++i)9815+ if (m->nodes[(int) previous[i]].goal)9816+ result = 1;9817+9818+ stb_arr_free(previous);9819+ stb_arr_free(current);9820+9821+ return result && *str == 0;9822+}9823+9824+stb_int16 stb__get_dfa_node(stb_matcher *m, stb_uint16 *list)9825+{9826+ stb_uint16 node;9827+ stb_uint32 data[8], *state, *newstate;9828+ int i,j,n;9829+9830+ state = (stb_uint32 *) stb_temp(data, m->num_words_per_dfa * 4);9831+ memset(state, 0, m->num_words_per_dfa*4);9832+9833+ n = stb_arr_len(list);9834+ for (i=0; i < n; ++i) {9835+ int x = list[i];9836+ state[x >> 5] |= 1 << (x & 31);9837+ }9838+9839+ // @TODO use a hash table9840+ n = stb_arr_len(m->dfa_mapping);9841+ i=j=0;9842+ for(; j < n; ++i, j += m->num_words_per_dfa) {9843+ // @TODO special case for <= 329844+ if (!memcmp(state, m->dfa_mapping + j, m->num_words_per_dfa*4)) {9845+ node = i;9846+ goto done;9847+ }9848+ }9849+9850+ assert(stb_arr_len(m->dfa) == i);9851+ node = i;9852+9853+ newstate = stb_arr_addn(m->dfa_mapping, m->num_words_per_dfa);9854+ memcpy(newstate, state, m->num_words_per_dfa*4);9855+9856+ // set all transitions to 'unknown'9857+ stb_arr_add(m->dfa);9858+ memset(m->dfa[i].transition, -1, sizeof(m->dfa[i].transition));9859+9860+ if (m->does_lex) {9861+ int result = -1;9862+ n = stb_arr_len(list);9863+ for (i=0; i < n; ++i) {9864+ if (m->nodes[(int) list[i]].goal > result)9865+ result = m->nodes[(int) list[i]].goal;9866+ }9867+9868+ stb_arr_push(m->dfa_result, result);9869+ }9870+9871+done:9872+ stb_tempfree(data, state);9873+ return node;9874+}9875+9876+static int stb__matcher_dfa(stb_matcher *m, char *str_c, int *len)9877+{9878+ stb_uint8 *str = (stb_uint8 *) str_c;9879+ stb_int16 node,prevnode;9880+ stb_dfa *trans;9881+ int match_length = 0;9882+ stb_int16 match_result=0;9883+9884+ if (m->dfa_start == STB__DFA_UNDEF) {9885+ stb_uint16 *list;9886+9887+ m->num_words_per_dfa = (stb_arr_len(m->nodes)+31) >> 5;9888+ stb__optimize(m);9889+9890+ list = stb__add_if_inactive(m, NULL, m->start_node);9891+ list = stb__eps_closure(m,list);9892+ if (m->does_lex) {9893+ m->dfa_start = stb__get_dfa_node(m,list);9894+ stb__clear(m, list);9895+ // DON'T allow start state to be a goal state!9896+ // this allows people to specify regexes that can match 09897+ // characters without them actually matching (also we don't9898+ // check _before_ advancing anyway9899+ if (m->dfa_start <= STB__DFA_MGOAL)9900+ m->dfa_start = -(m->dfa_start - STB__DFA_MGOAL);9901+ } else {9902+ if (stb__clear_goalcheck(m, list))9903+ m->dfa_start = STB__DFA_GOAL;9904+ else9905+ m->dfa_start = stb__get_dfa_node(m,list);9906+ }9907+ stb_arr_free(list);9908+ }9909+9910+ prevnode = STB__DFA_UNDEF;9911+ node = m->dfa_start;9912+ trans = m->dfa;9913+9914+ if (m->dfa_start == STB__DFA_GOAL)9915+ return 1;9916+9917+ for(;;) {9918+ assert(node >= STB__DFA_VALID);9919+9920+ // fast inner DFA loop; especially if STB__DFA_VALID is 09921+9922+ do {9923+ prevnode = node;9924+ node = trans[node].transition[*str++];9925+ } while (node >= STB__DFA_VALID);9926+9927+ assert(node >= STB__DFA_MGOAL - stb_arr_len(m->dfa));9928+ assert(node < stb_arr_len(m->dfa));9929+9930+ // special case for lex: need _longest_ match, so notice goal9931+ // state without stopping9932+ if (node <= STB__DFA_MGOAL) {9933+ match_length = (int) (str - (stb_uint8 *) str_c);9934+ node = -(node - STB__DFA_MGOAL);9935+ match_result = node;9936+ continue;9937+ }9938+9939+ // slow NFA->DFA conversion9940+9941+ // or we hit the goal or the end of the string, but those9942+ // can only happen once per search...9943+9944+ if (node == STB__DFA_UNDEF) {9945+ // build a list -- @TODO special case <= 32 states9946+ // heck, use a more compact data structure for <= 16 and <= 8 ?!9947+9948+ // @TODO keep states/newstates around instead of reallocating them9949+ stb_uint16 *states = NULL;9950+ stb_uint16 *newstates = NULL;9951+ int i,j,y,z;9952+ stb_uint32 *flags = &m->dfa_mapping[prevnode * m->num_words_per_dfa];9953+ assert(prevnode != STB__DFA_UNDEF);9954+ stb_arr_setsize(states, 4);9955+ stb_arr_setsize(newstates,4);9956+ for (j=0; j < m->num_words_per_dfa; ++j) {9957+ for (i=0; i < 32; ++i) {9958+ if (*flags & (1 << i))9959+ stb_arr_push(states, j*32+i);9960+ }9961+ ++flags;9962+ }9963+ // states is now the states we were in in the previous node;9964+ // so now we can compute what node it transitions to on str[-1]9965+9966+ y = stb_arr_len(states);9967+ for (i=0; i < y; ++i) {9968+ stb_nfa_node *n = &m->nodes[(int) states[i]];9969+ z = stb_arr_len(n->out);9970+ for (j=0; j < z; ++j) {9971+ if (n->out[j].match >= 0) {9972+ if (n->out[j].match == str[-1] || (str[-1] == 0 && n->out[j].match == '\n'))9973+ newstates = stb__add_if_inactive(m, newstates, n->out[j].node);9974+ } else if (n->out[j].match == -1) {9975+ if (str[-1] != '\n' && str[-1])9976+ newstates = stb__add_if_inactive(m, newstates, n->out[j].node);9977+ } else if (n->out[j].match < -1) {9978+ int z = -n->out[j].match - 2;9979+ if (m->charset[str[-1]] & (1 << z))9980+ newstates = stb__add_if_inactive(m, newstates, n->out[j].node);9981+ }9982+ }9983+ }9984+ // AND add in the start state!9985+ if (!m->match_start || (str[-1] == '\n' && !m->does_lex))9986+ newstates = stb__add_if_inactive(m, newstates, m->start_node);9987+ // AND epsilon close it9988+ newstates = stb__eps_closure(m, newstates);9989+ // if it's a goal state, then that's all there is to it9990+ if (stb__clear_goalcheck(m, newstates)) {9991+ if (m->does_lex) {9992+ match_length = (int) (str - (stb_uint8 *) str_c);9993+ node = stb__get_dfa_node(m,newstates);9994+ match_result = node;9995+ node = -node + STB__DFA_MGOAL;9996+ trans = m->dfa; // could have gotten realloc()ed9997+ } else9998+ node = STB__DFA_GOAL;9999+ } else if (str[-1] == 0 || stb_arr_len(newstates) == 0) {10000+ node = STB__DFA_END;10001+ } else {10002+ node = stb__get_dfa_node(m,newstates);10003+ trans = m->dfa; // could have gotten realloc()ed10004+ }10005+ trans[prevnode].transition[str[-1]] = node;10006+ if (node <= STB__DFA_MGOAL)10007+ node = -(node - STB__DFA_MGOAL);10008+ stb_arr_free(newstates);10009+ stb_arr_free(states);10010+ }10011+10012+ if (node == STB__DFA_GOAL) {10013+ return 1;10014+ }10015+ if (node == STB__DFA_END) {10016+ if (m->does_lex) {10017+ if (match_result) {10018+ if (len) *len = match_length;10019+ return m->dfa_result[(int) match_result];10020+ }10021+ }10022+ return 0;10023+ }10024+10025+ assert(node != STB__DFA_UNDEF);10026+ }10027+}10028+10029+int stb_matcher_find(stb_matcher *m, char *str)10030+{10031+ assert(m->does_lex == 0);10032+ return stb__matcher_dfa(m, str, NULL);10033+}10034+10035+int stb_lex(stb_matcher *m, char *str, int *len)10036+{10037+ assert(m->does_lex);10038+ return stb__matcher_dfa(m, str, len);10039+}10040+10041+#ifdef STB_PERFECT_HASH10042+int stb_regex(char *regex, char *str)10043+{10044+ static stb_perfect p;10045+ static stb_matcher ** matchers;10046+ static char ** regexps;10047+ static char ** regexp_cache;10048+ static unsigned short *mapping;10049+ int z = stb_perfect_hash(&p, (int)(size_t) regex);10050+ if (z >= 0) {10051+ if (strcmp(regex, regexp_cache[(int) mapping[z]])) {10052+ int i = mapping[z];10053+ stb_matcher_free(matchers[i]);10054+ free(regexp_cache[i]);10055+ regexps[i] = regex;10056+ regexp_cache[i] = stb_p_strdup(regex);10057+ matchers[i] = stb_regex_matcher(regex);10058+ }10059+ } else {10060+ int i,n;10061+ if (regex == NULL) {10062+ for (i=0; i < stb_arr_len(matchers); ++i) {10063+ stb_matcher_free(matchers[i]);10064+ free(regexp_cache[i]);10065+ }10066+ stb_arr_free(matchers);10067+ stb_arr_free(regexps);10068+ stb_arr_free(regexp_cache);10069+ stb_perfect_destroy(&p);10070+ free(mapping); mapping = NULL;10071+ return -1;10072+ }10073+ stb_arr_push(regexps, regex);10074+ stb_arr_push(regexp_cache, stb_p_strdup(regex));10075+ stb_arr_push(matchers, stb_regex_matcher(regex));10076+ stb_perfect_destroy(&p);10077+ n = stb_perfect_create(&p, (unsigned int *) (char **) regexps, stb_arr_len(regexps));10078+ mapping = (unsigned short *) realloc(mapping, n * sizeof(*mapping));10079+ for (i=0; i < stb_arr_len(regexps); ++i)10080+ mapping[stb_perfect_hash(&p, (int)(size_t) regexps[i])] = i;10081+ z = stb_perfect_hash(&p, (int)(size_t) regex);10082+ }10083+ return stb_matcher_find(matchers[(int) mapping[z]], str);10084+}10085+#endif10086+#endif // STB_DEFINE10087+10088+10089+#if 010090+//////////////////////////////////////////////////////////////////////////////10091+//10092+// C source-code introspection10093+//10094+10095+// runtime structure10096+typedef struct10097+{10098+ char *name;10099+ char *type; // base type10100+ char *comment; // content of comment field10101+ int size; // size of base type10102+ int offset; // field offset10103+ int arrcount[8]; // array sizes; -1 = pointer indirection; 0 = end of list10104+} stb_info_field;10105+10106+typedef struct10107+{10108+ char *structname;10109+ int size;10110+ int num_fields;10111+ stb_info_field *fields;10112+} stb_info_struct;10113+10114+extern stb_info_struct stb_introspect_output[];10115+10116+//10117+10118+STB_EXTERN void stb_introspect_precompiled(stb_info_struct *compiled);10119+STB_EXTERN void stb__introspect(char *path, char *file);10120+10121+#define stb_introspect_ship() stb__introspect(NULL, NULL, stb__introspect_output)10122+10123+#ifdef STB_SHIP10124+#define stb_introspect() stb_introspect_ship()10125+#define stb_introspect_path(p) stb_introspect_ship()10126+#else10127+// bootstrapping: define stb_introspect() (or 'path') the first time10128+#define stb_introspect() stb__introspect(NULL, __FILE__, NULL)10129+#define stb_introspect_auto() stb__introspect(NULL, __FILE__, stb__introspect_output)10130+10131+#define stb_introspect_path(p) stb__introspect(p, __FILE__, NULL)10132+#define stb_introspect_path(p) stb__introspect(p, __FILE__, NULL)10133+#endif10134+10135+#ifdef STB_DEFINE10136+10137+#ifndef STB_INTROSPECT_CPP10138+ #ifdef __cplusplus10139+ #define STB_INTROSPECT_CPP 110140+ #else10141+ #define STB_INTROSPECT_CPP 010142+ #endif10143+#endif10144+10145+void stb_introspect_precompiled(stb_info_struct *compiled)10146+{10147+10148+}10149+10150+10151+static void stb__introspect_filename(char *buffer, char *path)10152+{10153+ #if STB_INTROSPECT_CPP10154+ stb_p_sprintf(buffer stb_p_size(9999), "%s/stb_introspect.cpp", path);10155+ #else10156+ stb_p_sprintf(buffer stb_p_size(9999), "%s/stb_introspect.c", path);10157+ #endif10158+}10159+10160+static void stb__introspect_compute(char *path, char *file)10161+{10162+ int i;10163+ char ** include_list = NULL;10164+ char ** introspect_list = NULL;10165+ FILE *f;10166+ f = stb_p_fopen(file, "w");10167+ if (!f) return;10168+10169+ fputs("// if you get compiler errors, change the following 0 to a 1:\n", f);10170+ fputs("#define STB_INTROSPECT_INVALID 0\n\n", f);10171+ fputs("// this will force the code to compile, and force the introspector\n", f);10172+ fputs("// to run and then exit, allowing you to recompile\n\n\n", f);10173+ fputs("#include \"stb.h\"\n\n",f );10174+ fputs("#if STB_INTROSPECT_INVALID\n", f);10175+ fputs(" stb_info_struct stb__introspect_output[] = { (void *) 1 }\n", f);10176+ fputs("#else\n\n", f);10177+ for (i=0; i < stb_arr_len(include_list); ++i)10178+ fprintf(f, " #include \"%s\"\n", include_list[i]);10179+10180+ fputs(" stb_info_struct stb__introspect_output[] =\n{\n", f);10181+ for (i=0; i < stb_arr_len(introspect_list); ++i)10182+ fprintf(f, " stb_introspect_%s,\n", introspect_list[i]);10183+ fputs(" };\n", f);10184+ fputs("#endif\n", f);10185+ fclose(f);10186+}10187+10188+static stb_info_struct *stb__introspect_info;10189+10190+#ifndef STB_SHIP10191+10192+#endif10193+10194+void stb__introspect(char *path, char *file, stb_info_struct *compiled)10195+{10196+ static int first=1;10197+ if (!first) return;10198+ first=0;10199+10200+ stb__introspect_info = compiled;10201+10202+ #ifndef STB_SHIP10203+ if (path || file) {10204+ int bail_flag = compiled && compiled[0].structname == (void *) 1;10205+ int needs_building = bail_flag;10206+ struct stb__stat st;10207+ char buffer[1024], buffer2[1024];10208+ if (!path) {10209+ stb_splitpath(buffer, file, STB_PATH);10210+ path = buffer;10211+ }10212+ // bail if the source path doesn't exist10213+ if (!stb_fexists(path)) return;10214+10215+ stb__introspect_filename(buffer2, path);10216+10217+ // get source/include files timestamps, compare to output-file timestamp;10218+ // if mismatched, regenerate10219+10220+ if (stb__stat(buffer2, &st))10221+ needs_building = STB_TRUE;10222+10223+ {10224+ // find any file that contains an introspection command and is newer10225+ // if needs_building is already true, we don't need to do this test,10226+ // but we still need these arrays, so go ahead and get them10227+ char **all[3];10228+ all[0] = stb_readdir_files_mask(path, "*.h");10229+ all[1] = stb_readdir_files_mask(path, "*.c");10230+ all[2] = stb_readdir_files_mask(path, "*.cpp");10231+ int i,j;10232+ if (needs_building) {10233+ for (j=0; j < 3; ++j) {10234+ for (i=0; i < stb_arr_len(all[j]); ++i) {10235+ struct stb__stat st2;10236+ if (!stb__stat(all[j][i], &st2)) {10237+ if (st.st_mtime < st2.st_mtime) {10238+ char *z = stb_filec(all[j][i], NULL);10239+ int found=STB_FALSE;10240+ while (y) {10241+ y = strstr(y, "//si");10242+ if (y && isspace(y[4])) {10243+ found = STB_TRUE;10244+ break;10245+ }10246+ }10247+ needs_building = STB_TRUE;10248+ goto done;10249+ }10250+ }10251+ }10252+ }10253+ done:;10254+ }10255+ char *z = stb_filec(all[i], NULL), *y = z;10256+ int found=STB_FALSE;10257+ while (y) {10258+ y = strstr(y, "//si");10259+ if (y && isspace(y[4])) {10260+ found = STB_TRUE;10261+ break;10262+ }10263+ }10264+ if (found)10265+ stb_arr_push(introspect_h, stb_p_strdup(all[i]));10266+ free(z);10267+ }10268+ }10269+ stb_readdir_free(all);10270+ if (!needs_building) {10271+ for (i=0; i < stb_arr_len(introspect_h); ++i) {10272+ struct stb__stat st2;10273+ if (!stb__stat(introspect_h[i], &st2))10274+ if (st.st_mtime < st2.st_mtime)10275+ needs_building = STB_TRUE;10276+ }10277+ }10278+10279+ if (needs_building) {10280+ stb__introspect_compute(path, buffer2);10281+ }10282+ }10283+ }10284+ #endif10285+}10286+#endif10287+#endif10288+10289+#ifdef STB_INTROSPECT10290+// compile-time code-generator10291+#define INTROSPECT(x) int main(int argc, char **argv) { stb__introspect(__FILE__); return 0; }10292+#define FILE(x)10293+10294+void stb__introspect(char *filename)10295+{10296+ char *file = stb_file(filename, NULL);10297+ char *s = file, *t, **p;10298+ char *out_name = "stb_introspect.c";10299+ char *out_path;10300+ STB_ARR(char) filelist = NULL;10301+ int i,n;10302+ if (!file) stb_fatal("Couldn't open %s", filename);10303+10304+ out_path = stb_splitpathdup(filename, STB_PATH);10305+10306+ // search for the macros10307+ while (*s) {10308+ char buffer[256];10309+ while (*s && !isupper(*s)) ++s;10310+ s = stb_strtok_invert(buffer, s, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");10311+ s = stb_skipwhite(s);10312+ if (*s == '(') {10313+ ++s;10314+ t = strchr(s, ')');10315+ if (t == NULL) stb_fatal("Error parsing %s", filename);10316+10317+ }10318+ }10319+}10320+10321+10322+10323+#endif10324+10325+10326+//////////////////////////////////////////////////////////////////////////////10327+//10328+// STB-C sliding-window dictionary compression10329+//10330+// This uses a DEFLATE-style sliding window, but no bitwise entropy.10331+// Everything is on byte boundaries, so you could then apply a byte-wise10332+// entropy code, though that's nowhere near as effective.10333+//10334+// An STB-C stream begins with a 16-byte header:10335+// 4 bytes: 0x57 0xBC 0x00 0x0010336+// 8 bytes: big-endian size of decompressed data, 64-bits10337+// 4 bytes: big-endian size of window (how far back decompressor may need)10338+//10339+// The following symbols appear in the stream (these were determined ad hoc,10340+// not by analysis):10341+//10342+// [dict] 00000100 yyyyyyyy yyyyyyyy yyyyyyyy xxxxxxxx xxxxxxxx10343+// [END] 00000101 11111010 cccccccc cccccccc cccccccc cccccccc10344+// [dict] 00000110 yyyyyyyy yyyyyyyy yyyyyyyy xxxxxxxx10345+// [literals] 00000111 zzzzzzzz zzzzzzzz10346+// [literals] 00001zzz zzzzzzzz10347+// [dict] 00010yyy yyyyyyyy yyyyyyyy xxxxxxxx xxxxxxxx10348+// [dict] 00011yyy yyyyyyyy yyyyyyyy xxxxxxxx10349+// [literals] 001zzzzz10350+// [dict] 01yyyyyy yyyyyyyy xxxxxxxx10351+// [dict] 1xxxxxxx yyyyyyyy10352+//10353+// xxxxxxxx: match length - 110354+// yyyyyyyy: backwards distance - 110355+// zzzzzzzz: num literals - 110356+// cccccccc: adler32 checksum of decompressed data10357+// (all big-endian)10358+10359+10360+STB_EXTERN stb_uint stb_decompress_length(stb_uchar *input);10361+STB_EXTERN stb_uint stb_decompress(stb_uchar *out,stb_uchar *in,stb_uint len);10362+STB_EXTERN stb_uint stb_compress (stb_uchar *out,stb_uchar *in,stb_uint len);10363+STB_EXTERN void stb_compress_window(int z);10364+STB_EXTERN void stb_compress_hashsize(unsigned int z);10365+10366+STB_EXTERN int stb_compress_tofile(char *filename, char *in, stb_uint len);10367+STB_EXTERN int stb_compress_intofile(FILE *f, char *input, stb_uint len);10368+STB_EXTERN char *stb_decompress_fromfile(char *filename, stb_uint *len);10369+10370+STB_EXTERN int stb_compress_stream_start(FILE *f);10371+STB_EXTERN void stb_compress_stream_end(int close);10372+STB_EXTERN void stb_write(char *data, int data_len);10373+10374+#ifdef STB_DEFINE10375+10376+stb_uint stb_decompress_length(stb_uchar *input)10377+{10378+ return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11];10379+}10380+10381+//////////////////// decompressor ///////////////////////10382+10383+// simple implementation that just writes whole thing into big block10384+10385+static unsigned char *stb__barrier;10386+static unsigned char *stb__barrier2;10387+static unsigned char *stb__barrier3;10388+static unsigned char *stb__barrier4;10389+10390+static stb_uchar *stb__dout;10391+static void stb__match(stb_uchar *data, stb_uint length)10392+{10393+ // INVERSE of memmove... write each byte before copying the next...10394+ assert (stb__dout + length <= stb__barrier);10395+ if (stb__dout + length > stb__barrier) { stb__dout += length; return; }10396+ if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; }10397+ while (length--) *stb__dout++ = *data++;10398+}10399+10400+static void stb__lit(stb_uchar *data, stb_uint length)10401+{10402+ assert (stb__dout + length <= stb__barrier);10403+ if (stb__dout + length > stb__barrier) { stb__dout += length; return; }10404+ if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }10405+ memcpy(stb__dout, data, length);10406+ stb__dout += length;10407+}10408+10409+#define stb__in2(x) ((i[x] << 8) + i[(x)+1])10410+#define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1))10411+#define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1))10412+10413+static stb_uchar *stb_decompress_token(stb_uchar *i)10414+{10415+ if (*i >= 0x20) { // use fewer if's for cases that expand small10416+ if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2;10417+ else if (*i >= 0x40) stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3;10418+ else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1);10419+ } else { // more ifs for cases that expand large, since overhead is amortized10420+ if (*i >= 0x18) stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4;10421+ else if (*i >= 0x10) stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5;10422+ else if (*i >= 0x08) stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1);10423+ else if (*i == 0x07) stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1);10424+ else if (*i == 0x06) stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5;10425+ else if (*i == 0x04) stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6;10426+ }10427+ return i;10428+}10429+10430+stb_uint stb_decompress(stb_uchar *output, stb_uchar *i, stb_uint length)10431+{10432+ stb_uint olen;10433+ if (stb__in4(0) != 0x57bC0000) return 0;10434+ if (stb__in4(4) != 0) return 0; // error! stream is > 4GB10435+ olen = stb_decompress_length(i);10436+ stb__barrier2 = i;10437+ stb__barrier3 = i+length;10438+ stb__barrier = output + olen;10439+ stb__barrier4 = output;10440+ i += 16;10441+10442+ stb__dout = output;10443+ while (1) {10444+ stb_uchar *old_i = i;10445+ i = stb_decompress_token(i);10446+ if (i == old_i) {10447+ if (*i == 0x05 && i[1] == 0xfa) {10448+ assert(stb__dout == output + olen);10449+ if (stb__dout != output + olen) return 0;10450+ if (stb_adler32(1, output, olen) != (stb_uint) stb__in4(2))10451+ return 0;10452+ return olen;10453+ } else {10454+ assert(0); /* NOTREACHED */10455+ return 0;10456+ }10457+ }10458+ assert(stb__dout <= output + olen);10459+ if (stb__dout > output + olen)10460+ return 0;10461+ }10462+}10463+10464+char *stb_decompress_fromfile(char *filename, unsigned int *len)10465+{10466+ unsigned int n;10467+ char *q;10468+ unsigned char *p;10469+ FILE *f = stb_p_fopen(filename, "rb"); if (f == NULL) return NULL;10470+ fseek(f, 0, SEEK_END);10471+ n = ftell(f);10472+ fseek(f, 0, SEEK_SET);10473+ p = (unsigned char * ) malloc(n); if (p == NULL) return NULL;10474+ fread(p, 1, n, f);10475+ fclose(f);10476+ if (p == NULL) return NULL;10477+ if (p[0] != 0x57 || p[1] != 0xBc || p[2] || p[3]) { free(p); return NULL; }10478+ q = (char *) malloc(stb_decompress_length(p)+1);10479+ if (!q) { free(p); return NULL; }10480+ *len = stb_decompress((unsigned char *) q, p, n);10481+ if (*len) q[*len] = 0;10482+ free(p);10483+ return q;10484+}10485+10486+#if 010487+// streaming decompressor10488+10489+static struct10490+{10491+ stb__uchar *in_buffer;10492+ stb__uchar *match;10493+10494+ stb__uint pending_literals;10495+ stb__uint pending_match;10496+} xx;10497+10498+10499+10500+static void stb__match(stb_uchar *data, stb_uint length)10501+{10502+ // INVERSE of memmove... write each byte before copying the next...10503+ assert (stb__dout + length <= stb__barrier);10504+ if (stb__dout + length > stb__barrier) { stb__dout += length; return; }10505+ if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }10506+ while (length--) *stb__dout++ = *data++;10507+}10508+10509+static void stb__lit(stb_uchar *data, stb_uint length)10510+{10511+ assert (stb__dout + length <= stb__barrier);10512+ if (stb__dout + length > stb__barrier) { stb__dout += length; return; }10513+ if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }10514+ memcpy(stb__dout, data, length);10515+ stb__dout += length;10516+}10517+10518+static void sx_match(stb_uchar *data, stb_uint length)10519+{10520+ xx.match = data;10521+ xx.pending_match = length;10522+}10523+10524+static void sx_lit(stb_uchar *data, stb_uint length)10525+{10526+ xx.pending_lit = length;10527+}10528+10529+static int stb_decompress_token_state(void)10530+{10531+ stb__uchar *i = xx.in_buffer;10532+10533+ if (*i >= 0x20) { // use fewer if's for cases that expand small10534+ if (*i >= 0x80) sx_match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2;10535+ else if (*i >= 0x40) sx_match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3;10536+ else /* *i >= 0x20 */ sx_lit(i+1, i[0] - 0x20 + 1), i += 1;10537+ } else { // more ifs for cases that expand large, since overhead is amortized10538+ if (*i >= 0x18) sx_match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4;10539+ else if (*i >= 0x10) sx_match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5;10540+ else if (*i >= 0x08) sx_lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2;10541+ else if (*i == 0x07) sx_lit(i+3, stb__in2(1) + 1), i += 3;10542+ else if (*i == 0x06) sx_match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5;10543+ else if (*i == 0x04) sx_match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6;10544+ else return 0;10545+ }10546+ xx.in_buffer = i;10547+ return 1;10548+}10549+#endif10550+10551+10552+10553+//////////////////// compressor ///////////////////////10554+10555+static unsigned int stb_matchlen(stb_uchar *m1, stb_uchar *m2, stb_uint maxlen)10556+{10557+ stb_uint i;10558+ for (i=0; i < maxlen; ++i)10559+ if (m1[i] != m2[i]) return i;10560+ return i;10561+}10562+10563+// simple implementation that just takes the source data in a big block10564+10565+static stb_uchar *stb__out;10566+static FILE *stb__outfile;10567+static stb_uint stb__outbytes;10568+10569+static void stb__write(unsigned char v)10570+{10571+ fputc(v, stb__outfile);10572+ ++stb__outbytes;10573+}10574+10575+#define stb_out(v) (stb__out ? (void)(*stb__out++ = (stb_uchar) (v)) : stb__write((stb_uchar) (v)))10576+10577+static void stb_out2(stb_uint v)10578+{10579+ stb_out(v >> 8);10580+ stb_out(v);10581+}10582+10583+static void stb_out3(stb_uint v) { stb_out(v >> 16); stb_out(v >> 8); stb_out(v); }10584+static void stb_out4(stb_uint v) { stb_out(v >> 24); stb_out(v >> 16);10585+ stb_out(v >> 8 ); stb_out(v); }10586+10587+static void outliterals(stb_uchar *in, ptrdiff_t numlit)10588+{10589+ while (numlit > 65536) {10590+ outliterals(in,65536);10591+ in += 65536;10592+ numlit -= 65536;10593+ }10594+10595+ if (numlit == 0) ;10596+ else if (numlit <= 32) stb_out (0x000020 + (stb_uint) numlit-1);10597+ else if (numlit <= 2048) stb_out2(0x000800 + (stb_uint) numlit-1);10598+ else /* numlit <= 65536) */ stb_out3(0x070000 + (stb_uint) numlit-1);10599+10600+ if (stb__out) {10601+ memcpy(stb__out,in,numlit);10602+ stb__out += numlit;10603+ } else10604+ fwrite(in, 1, numlit, stb__outfile);10605+}10606+10607+static int stb__window = 0x40000; // 256K10608+void stb_compress_window(int z)10609+{10610+ if (z >= 0x1000000) z = 0x1000000; // limit of implementation10611+ if (z < 0x100) z = 0x100; // insanely small10612+ stb__window = z;10613+}10614+10615+static int stb_not_crap(int best, int dist)10616+{10617+ return ((best > 2 && dist <= 0x00100)10618+ || (best > 5 && dist <= 0x04000)10619+ || (best > 7 && dist <= 0x80000));10620+}10621+10622+static stb_uint stb__hashsize = 32768;10623+void stb_compress_hashsize(unsigned int y)10624+{10625+ unsigned int z = 1024;10626+ while (z < y) z <<= 1;10627+ stb__hashsize = z >> 2; // pass in bytes, store #pointers10628+}10629+10630+// note that you can play with the hashing functions all you10631+// want without needing to change the decompressor10632+#define stb__hc(q,h,c) (((h) << 7) + ((h) >> 25) + q[c])10633+#define stb__hc2(q,h,c,d) (((h) << 14) + ((h) >> 18) + (q[c] << 7) + q[d])10634+#define stb__hc3(q,c,d,e) ((q[c] << 14) + (q[d] << 7) + q[e])10635+10636+static stb_uint32 stb__running_adler;10637+10638+static int stb_compress_chunk(stb_uchar *history,10639+ stb_uchar *start,10640+ stb_uchar *end,10641+ int length,10642+ int *pending_literals,10643+ stb_uchar **chash,10644+ stb_uint mask)10645+{10646+ int window = stb__window;10647+ stb_uint match_max;10648+ stb_uchar *lit_start = start - *pending_literals;10649+ stb_uchar *q = start;10650+10651+ #define STB__SCRAMBLE(h) (((h) + ((h) >> 16)) & mask)10652+10653+ // stop short of the end so we don't scan off the end doing10654+ // the hashing; this means we won't compress the last few bytes10655+ // unless they were part of something longer10656+ while (q < start+length && q+12 < end) {10657+ int m;10658+ stb_uint h1,h2,h3,h4, h;10659+ stb_uchar *t;10660+ int best = 2, dist=0;10661+10662+ if (q+65536 > end)10663+ match_max = (stb_uint) (end-q);10664+ else10665+ match_max = 65536u;10666+10667+ #define stb__nc(b,d) ((d) <= window && ((b) > 9 || stb_not_crap(b,d)))10668+10669+ #define STB__TRY(t,p) /* avoid retrying a match we already tried */ \10670+ if (p ? dist != (int) (q-t) : 1) \10671+ if ((m = (int) stb_matchlen(t, q, match_max)) > best)\10672+ if (stb__nc(m,(int) (q-(t)))) \10673+ best = m, dist = (int) (q - (t))10674+10675+ // rather than search for all matches, only try 4 candidate locations,10676+ // chosen based on 4 different hash functions of different lengths.10677+ // this strategy is inspired by LZO; hashing is unrolled here using the10678+ // 'hc' macro10679+ h = stb__hc3(q,0, 1, 2); h1 = STB__SCRAMBLE(h);10680+ t = chash[h1]; if (t) STB__TRY(t,0);10681+ h = stb__hc2(q,h, 3, 4); h2 = STB__SCRAMBLE(h);10682+ h = stb__hc2(q,h, 5, 6); t = chash[h2]; if (t) STB__TRY(t,1);10683+ h = stb__hc2(q,h, 7, 8); h3 = STB__SCRAMBLE(h);10684+ h = stb__hc2(q,h, 9,10); t = chash[h3]; if (t) STB__TRY(t,1);10685+ h = stb__hc2(q,h,11,12); h4 = STB__SCRAMBLE(h);10686+ t = chash[h4]; if (t) STB__TRY(t,1);10687+10688+ // because we use a shared hash table, can only update it10689+ // _after_ we've probed all of them10690+ chash[h1] = chash[h2] = chash[h3] = chash[h4] = q;10691+10692+ if (best > 2)10693+ assert(dist > 0);10694+10695+ // see if our best match qualifies10696+ if (best < 3) { // fast path literals10697+ ++q;10698+ } else if (best > 2 && best <= 0x80 && dist <= 0x100) {10699+ outliterals(lit_start, q-lit_start); lit_start = (q += best);10700+ stb_out(0x80 + best-1);10701+ stb_out(dist-1);10702+ } else if (best > 5 && best <= 0x100 && dist <= 0x4000) {10703+ outliterals(lit_start, q-lit_start); lit_start = (q += best);10704+ stb_out2(0x4000 + dist-1);10705+ stb_out(best-1);10706+ } else if (best > 7 && best <= 0x100 && dist <= 0x80000) {10707+ outliterals(lit_start, q-lit_start); lit_start = (q += best);10708+ stb_out3(0x180000 + dist-1);10709+ stb_out(best-1);10710+ } else if (best > 8 && best <= 0x10000 && dist <= 0x80000) {10711+ outliterals(lit_start, q-lit_start); lit_start = (q += best);10712+ stb_out3(0x100000 + dist-1);10713+ stb_out2(best-1);10714+ } else if (best > 9 && dist <= 0x1000000) {10715+ if (best > 65536) best = 65536;10716+ outliterals(lit_start, q-lit_start); lit_start = (q += best);10717+ if (best <= 0x100) {10718+ stb_out(0x06);10719+ stb_out3(dist-1);10720+ stb_out(best-1);10721+ } else {10722+ stb_out(0x04);10723+ stb_out3(dist-1);10724+ stb_out2(best-1);10725+ }10726+ } else { // fallback literals if no match was a balanced tradeoff10727+ ++q;10728+ }10729+ }10730+10731+ // if we didn't get all the way, add the rest to literals10732+ if (q-start < length)10733+ q = start+length;10734+10735+ // the literals are everything from lit_start to q10736+ *pending_literals = (int) (q - lit_start);10737+10738+ stb__running_adler = stb_adler32(stb__running_adler, start, (int) (q - start));10739+ return (int) (q - start);10740+}10741+10742+static int stb_compress_inner(stb_uchar *input, stb_uint length)10743+{10744+ int literals = 0;10745+ stb_uint len,i;10746+10747+ stb_uchar **chash;10748+ chash = (stb_uchar**) malloc(stb__hashsize * sizeof(stb_uchar*));10749+ if (chash == NULL) return 0; // failure10750+ for (i=0; i < stb__hashsize; ++i)10751+ chash[i] = NULL;10752+10753+ // stream signature10754+ stb_out(0x57); stb_out(0xbc);10755+ stb_out2(0);10756+10757+ stb_out4(0); // 64-bit length requires 32-bit leading 010758+ stb_out4(length);10759+ stb_out4(stb__window);10760+10761+ stb__running_adler = 1;10762+10763+ len = stb_compress_chunk(input, input, input+length, length, &literals, chash, stb__hashsize-1);10764+ assert(len == length);10765+10766+ outliterals(input+length - literals, literals);10767+10768+ free(chash);10769+10770+ stb_out2(0x05fa); // end opcode10771+10772+ stb_out4(stb__running_adler);10773+10774+ return 1; // success10775+}10776+10777+stb_uint stb_compress(stb_uchar *out, stb_uchar *input, stb_uint length)10778+{10779+ stb__out = out;10780+ stb__outfile = NULL;10781+10782+ stb_compress_inner(input, length);10783+10784+ return (stb_uint) (stb__out - out);10785+}10786+10787+int stb_compress_tofile(char *filename, char *input, unsigned int length)10788+{10789+ //int maxlen = length + 512 + (length >> 2); // total guess10790+ //char *buffer = (char *) malloc(maxlen);10791+ //int blen = stb_compress((stb_uchar*)buffer, (stb_uchar*)input, length);10792+10793+ stb__out = NULL;10794+ stb__outfile = stb_p_fopen(filename, "wb");10795+ if (!stb__outfile) return 0;10796+10797+ stb__outbytes = 0;10798+10799+ if (!stb_compress_inner((stb_uchar*)input, length))10800+ return 0;10801+10802+ fclose(stb__outfile);10803+10804+ return stb__outbytes;10805+}10806+10807+int stb_compress_intofile(FILE *f, char *input, unsigned int length)10808+{10809+ //int maxlen = length + 512 + (length >> 2); // total guess10810+ //char *buffer = (char*)malloc(maxlen);10811+ //int blen = stb_compress((stb_uchar*)buffer, (stb_uchar*)input, length);10812+10813+ stb__out = NULL;10814+ stb__outfile = f;10815+ if (!stb__outfile) return 0;10816+10817+ stb__outbytes = 0;10818+10819+ if (!stb_compress_inner((stb_uchar*)input, length))10820+ return 0;10821+10822+ return stb__outbytes;10823+}10824+10825+////////////////////// streaming I/O version /////////////////////10826+10827+10828+static size_t stb_out_backpatch_id(void)10829+{10830+ if (stb__out)10831+ return (size_t) stb__out;10832+ else10833+ return ftell(stb__outfile);10834+}10835+10836+static void stb_out_backpatch(size_t id, stb_uint value)10837+{10838+ stb_uchar data[4] = { (stb_uchar)(value >> 24), (stb_uchar)(value >> 16), (stb_uchar)(value >> 8), (stb_uchar)(value) };10839+ if (stb__out) {10840+ memcpy((void *) id, data, 4);10841+ } else {10842+ stb_uint where = ftell(stb__outfile);10843+ fseek(stb__outfile, (long) id, SEEK_SET);10844+ fwrite(data, 4, 1, stb__outfile);10845+ fseek(stb__outfile, where, SEEK_SET);10846+ }10847+}10848+10849+// ok, the wraparound buffer was a total failure. let's instead10850+// use a copying-in-place buffer, which lets us share the code.10851+// This is way less efficient but it'll do for now.10852+10853+static struct10854+{10855+ stb_uchar *buffer;10856+ int size; // physical size of buffer in bytes10857+10858+ int valid; // amount of valid data in bytes10859+ int start; // bytes of data already output10860+10861+ int window;10862+ int fsize;10863+10864+ int pending_literals; // bytes not-quite output but counted in start10865+ int length_id;10866+10867+ stb_uint total_bytes;10868+10869+ stb_uchar **chash;10870+ stb_uint hashmask;10871+} xtb;10872+10873+static int stb_compress_streaming_start(void)10874+{10875+ stb_uint i;10876+ xtb.size = stb__window * 3;10877+ xtb.buffer = (stb_uchar*)malloc(xtb.size);10878+ if (!xtb.buffer) return 0;10879+10880+ xtb.chash = (stb_uchar**)malloc(sizeof(*xtb.chash) * stb__hashsize);10881+ if (!xtb.chash) {10882+ free(xtb.buffer);10883+ return 0;10884+ }10885+10886+ for (i=0; i < stb__hashsize; ++i)10887+ xtb.chash[i] = NULL;10888+10889+ xtb.hashmask = stb__hashsize-1;10890+10891+ xtb.valid = 0;10892+ xtb.start = 0;10893+ xtb.window = stb__window;10894+ xtb.fsize = stb__window;10895+ xtb.pending_literals = 0;10896+ xtb.total_bytes = 0;10897+10898+ // stream signature10899+ stb_out(0x57); stb_out(0xbc); stb_out2(0);10900+10901+ stb_out4(0); // 64-bit length requires 32-bit leading 010902+10903+ xtb.length_id = (int) stb_out_backpatch_id();10904+ stb_out4(0); // we don't know the output length yet10905+10906+ stb_out4(stb__window);10907+10908+ stb__running_adler = 1;10909+10910+ return 1;10911+}10912+10913+static int stb_compress_streaming_end(void)10914+{10915+ // flush out any remaining data10916+ stb_compress_chunk(xtb.buffer, xtb.buffer+xtb.start, xtb.buffer+xtb.valid,10917+ xtb.valid-xtb.start, &xtb.pending_literals, xtb.chash, xtb.hashmask);10918+10919+ // write out pending literals10920+ outliterals(xtb.buffer + xtb.valid - xtb.pending_literals, xtb.pending_literals);10921+10922+ stb_out2(0x05fa); // end opcode10923+ stb_out4(stb__running_adler);10924+10925+ stb_out_backpatch(xtb.length_id, xtb.total_bytes);10926+10927+ free(xtb.buffer);10928+ free(xtb.chash);10929+ return 1;10930+}10931+10932+void stb_write(char *data, int data_len)10933+{10934+ stb_uint i;10935+10936+ // @TODO: fast path for filling the buffer and doing nothing else10937+ // if (xtb.valid + data_len < xtb.size)10938+10939+ xtb.total_bytes += data_len;10940+10941+ while (data_len) {10942+ // fill buffer10943+ if (xtb.valid < xtb.size) {10944+ int amt = xtb.size - xtb.valid;10945+ if (data_len < amt) amt = data_len;10946+ memcpy(xtb.buffer + xtb.valid, data, amt);10947+ data_len -= amt;10948+ data += amt;10949+ xtb.valid += amt;10950+ }10951+ if (xtb.valid < xtb.size)10952+ return;10953+10954+ // at this point, the buffer is full10955+10956+ // if we can process some data, go for it; make sure10957+ // we leave an 'fsize's worth of data, though10958+ if (xtb.start + xtb.fsize < xtb.valid) {10959+ int amount = (xtb.valid - xtb.fsize) - xtb.start;10960+ int n;10961+ assert(amount > 0);10962+ n = stb_compress_chunk(xtb.buffer, xtb.buffer + xtb.start, xtb.buffer + xtb.valid,10963+ amount, &xtb.pending_literals, xtb.chash, xtb.hashmask);10964+ xtb.start += n;10965+ }10966+10967+ assert(xtb.start + xtb.fsize >= xtb.valid);10968+ // at this point, our future size is too small, so we10969+ // need to flush some history. we, in fact, flush exactly10970+ // one window's worth of history10971+10972+ {10973+ int flush = xtb.window;10974+ assert(xtb.start >= flush);10975+ assert(xtb.valid >= flush);10976+10977+ // if 'pending literals' extends back into the shift region,10978+ // write them out10979+ if (xtb.start - xtb.pending_literals < flush) {10980+ outliterals(xtb.buffer + xtb.start - xtb.pending_literals, xtb.pending_literals);10981+ xtb.pending_literals = 0;10982+ }10983+10984+ // now shift the window10985+ memmove(xtb.buffer, xtb.buffer + flush, xtb.valid - flush);10986+ xtb.start -= flush;10987+ xtb.valid -= flush;10988+10989+ for (i=0; i <= xtb.hashmask; ++i)10990+ if (xtb.chash[i] < xtb.buffer + flush)10991+ xtb.chash[i] = NULL;10992+ else10993+ xtb.chash[i] -= flush;10994+ }10995+ // and now that we've made room for more data, go back to the top10996+ }10997+}10998+10999+int stb_compress_stream_start(FILE *f)11000+{11001+ stb__out = NULL;11002+ stb__outfile = f;11003+11004+ if (f == NULL)11005+ return 0;11006+11007+ if (!stb_compress_streaming_start())11008+ return 0;11009+11010+ return 1;11011+}11012+11013+void stb_compress_stream_end(int close)11014+{11015+ stb_compress_streaming_end();11016+ if (close && stb__outfile) {11017+ fclose(stb__outfile);11018+ }11019+}11020+11021+#endif // STB_DEFINE11022+11023+//////////////////////////////////////////////////////////////////////////////11024+//11025+// File abstraction... tired of not having this... we can write11026+// compressors to be layers over these that auto-close their children.11027+11028+11029+typedef struct stbfile11030+{11031+ int (*getbyte)(struct stbfile *); // -1 on EOF11032+ unsigned int (*getdata)(struct stbfile *, void *block, unsigned int len);11033+11034+ int (*putbyte)(struct stbfile *, int byte);11035+ unsigned int (*putdata)(struct stbfile *, void *block, unsigned int len);11036+11037+ unsigned int (*size)(struct stbfile *);11038+11039+ unsigned int (*tell)(struct stbfile *);11040+ void (*backpatch)(struct stbfile *, unsigned int tell, void *block, unsigned int len);11041+11042+ void (*close)(struct stbfile *);11043+11044+ FILE *f; // file to fread/fwrite11045+ unsigned char *buffer; // input/output buffer11046+ unsigned char *indata, *inend; // input buffer11047+ union {11048+ int various;11049+ void *ptr;11050+ };11051+} stbfile;11052+11053+STB_EXTERN unsigned int stb_getc(stbfile *f); // read11054+STB_EXTERN int stb_putc(stbfile *f, int ch); // write11055+STB_EXTERN unsigned int stb_getdata(stbfile *f, void *buffer, unsigned int len); // read11056+STB_EXTERN unsigned int stb_putdata(stbfile *f, void *buffer, unsigned int len); // write11057+STB_EXTERN unsigned int stb_tell(stbfile *f); // read11058+STB_EXTERN unsigned int stb_size(stbfile *f); // read/write11059+STB_EXTERN void stb_backpatch(stbfile *f, unsigned int tell, void *buffer, unsigned int len); // write11060+11061+#ifdef STB_DEFINE11062+11063+unsigned int stb_getc(stbfile *f) { return f->getbyte(f); }11064+int stb_putc(stbfile *f, int ch) { return f->putbyte(f, ch); }11065+11066+unsigned int stb_getdata(stbfile *f, void *buffer, unsigned int len)11067+{11068+ return f->getdata(f, buffer, len);11069+}11070+unsigned int stb_putdata(stbfile *f, void *buffer, unsigned int len)11071+{11072+ return f->putdata(f, buffer, len);11073+}11074+void stb_close(stbfile *f)11075+{11076+ f->close(f);11077+ free(f);11078+}11079+unsigned int stb_tell(stbfile *f) { return f->tell(f); }11080+unsigned int stb_size(stbfile *f) { return f->size(f); }11081+void stb_backpatch(stbfile *f, unsigned int tell, void *buffer, unsigned int len)11082+{11083+ f->backpatch(f,tell,buffer,len);11084+}11085+11086+// FILE * implementation11087+static int stb__fgetbyte(stbfile *f) { return fgetc(f->f); }11088+static int stb__fputbyte(stbfile *f, int ch) { return fputc(ch, f->f)==0; }11089+static unsigned int stb__fgetdata(stbfile *f, void *buffer, unsigned int len) { return (unsigned int) fread(buffer,1,len,f->f); }11090+static unsigned int stb__fputdata(stbfile *f, void *buffer, unsigned int len) { return (unsigned int) fwrite(buffer,1,len,f->f); }11091+static unsigned int stb__fsize(stbfile *f) { return (unsigned int) stb_filelen(f->f); }11092+static unsigned int stb__ftell(stbfile *f) { return (unsigned int) ftell(f->f); }11093+static void stb__fbackpatch(stbfile *f, unsigned int where, void *buffer, unsigned int len)11094+{11095+ fseek(f->f, where, SEEK_SET);11096+ fwrite(buffer, 1, len, f->f);11097+ fseek(f->f, 0, SEEK_END);11098+}11099+static void stb__fclose(stbfile *f) { fclose(f->f); }11100+11101+stbfile *stb_openf(FILE *f)11102+{11103+ stbfile m = { stb__fgetbyte, stb__fgetdata,11104+ stb__fputbyte, stb__fputdata,11105+ stb__fsize, stb__ftell, stb__fbackpatch, stb__fclose,11106+ 0,0,0, };11107+ stbfile *z = (stbfile *) malloc(sizeof(*z));11108+ if (z) {11109+ *z = m;11110+ z->f = f;11111+ }11112+ return z;11113+}11114+11115+static int stb__nogetbyte(stbfile *f) { assert(0); return -1; }11116+static unsigned int stb__nogetdata(stbfile *f, void *buffer, unsigned int len) { assert(0); return 0; }11117+static int stb__noputbyte(stbfile *f, int ch) { assert(0); return 0; }11118+static unsigned int stb__noputdata(stbfile *f, void *buffer, unsigned int len) { assert(0); return 0; }11119+static void stb__nobackpatch(stbfile *f, unsigned int where, void *buffer, unsigned int len) { assert(0); }11120+11121+static int stb__bgetbyte(stbfile *s)11122+{11123+ if (s->indata < s->inend)11124+ return *s->indata++;11125+ else11126+ return -1;11127+}11128+11129+static unsigned int stb__bgetdata(stbfile *s, void *buffer, unsigned int len)11130+{11131+ if (s->indata + len > s->inend)11132+ len = (unsigned int) (s->inend - s->indata);11133+ memcpy(buffer, s->indata, len);11134+ s->indata += len;11135+ return len;11136+}11137+static unsigned int stb__bsize(stbfile *s) { return (unsigned int) (s->inend - s->buffer); }11138+static unsigned int stb__btell(stbfile *s) { return (unsigned int) (s->indata - s->buffer); }11139+11140+static void stb__bclose(stbfile *s)11141+{11142+ if (s->various)11143+ free(s->buffer);11144+}11145+11146+stbfile *stb_open_inbuffer(void *buffer, unsigned int len)11147+{11148+ stbfile m = { stb__bgetbyte, stb__bgetdata,11149+ stb__noputbyte, stb__noputdata,11150+ stb__bsize, stb__btell, stb__nobackpatch, stb__bclose };11151+ stbfile *z = (stbfile *) malloc(sizeof(*z));11152+ if (z) {11153+ *z = m;11154+ z->buffer = (unsigned char *) buffer;11155+ z->indata = z->buffer;11156+ z->inend = z->indata + len;11157+ }11158+ return z;11159+}11160+11161+stbfile *stb_open_inbuffer_free(void *buffer, unsigned int len)11162+{11163+ stbfile *z = stb_open_inbuffer(buffer, len);11164+ if (z)11165+ z->various = 1; // free11166+ return z;11167+}11168+11169+#ifndef STB_VERSION11170+// if we've been cut-and-pasted elsewhere, you get a limited11171+// version of stb_open, without the 'k' flag and utf8 support11172+static void stb__fclose2(stbfile *f)11173+{11174+ fclose(f->f);11175+}11176+11177+stbfile *stb_open(char *filename, char *mode)11178+{11179+ FILE *f = stb_p_fopen(filename, mode);11180+ stbfile *s;11181+ if (f == NULL) return NULL;11182+ s = stb_openf(f);11183+ if (s)11184+ s->close = stb__fclose2;11185+ return s;11186+}11187+#else11188+// the full version depends on some code in stb.h; this11189+// also includes the memory buffer output format implemented with stb_arr11190+static void stb__fclose2(stbfile *f)11191+{11192+ stb_fclose(f->f, f->various);11193+}11194+11195+stbfile *stb_open(char *filename, char *mode)11196+{11197+ FILE *f = stb_fopen(filename, mode[0] == 'k' ? mode+1 : mode);11198+ stbfile *s;11199+ if (f == NULL) return NULL;11200+ s = stb_openf(f);11201+ if (s) {11202+ s->close = stb__fclose2;11203+ s->various = mode[0] == 'k' ? stb_keep_if_different : stb_keep_yes;11204+ }11205+ return s;11206+}11207+11208+static int stb__aputbyte(stbfile *f, int ch)11209+{11210+ stb_arr_push(f->buffer, ch);11211+ return 1;11212+}11213+static unsigned int stb__aputdata(stbfile *f, void *data, unsigned int len)11214+{11215+ memcpy(stb_arr_addn(f->buffer, (int) len), data, len);11216+ return len;11217+}11218+static unsigned int stb__asize(stbfile *f) { return stb_arr_len(f->buffer); }11219+static void stb__abackpatch(stbfile *f, unsigned int where, void *data, unsigned int len)11220+{11221+ memcpy(f->buffer+where, data, len);11222+}11223+static void stb__aclose(stbfile *f)11224+{11225+ *(unsigned char **) f->ptr = f->buffer;11226+}11227+11228+stbfile *stb_open_outbuffer(unsigned char **update_on_close)11229+{11230+ stbfile m = { stb__nogetbyte, stb__nogetdata,11231+ stb__aputbyte, stb__aputdata,11232+ stb__asize, stb__asize, stb__abackpatch, stb__aclose };11233+ stbfile *z = (stbfile *) malloc(sizeof(*z));11234+ if (z) {11235+ z->ptr = update_on_close;11236+ *z = m;11237+ }11238+ return z;11239+}11240+#endif11241+#endif11242+11243+11244+//////////////////////////////////////////////////////////////////////////////11245+//11246+// Arithmetic coder... based on cbloom's notes on the subject, should be11247+// less code than a huffman code.11248+11249+typedef struct11250+{11251+ unsigned int range_low;11252+ unsigned int range_high;11253+ unsigned int code, range; // decode11254+ int buffered_u8;11255+ int pending_ffs;11256+ stbfile *output;11257+} stb_arith;11258+11259+STB_EXTERN void stb_arith_init_encode(stb_arith *a, stbfile *out);11260+STB_EXTERN void stb_arith_init_decode(stb_arith *a, stbfile *in);11261+STB_EXTERN stbfile *stb_arith_encode_close(stb_arith *a);11262+STB_EXTERN stbfile *stb_arith_decode_close(stb_arith *a);11263+11264+STB_EXTERN void stb_arith_encode(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq);11265+STB_EXTERN void stb_arith_encode_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq);11266+STB_EXTERN unsigned int stb_arith_decode_value(stb_arith *a, unsigned int totalfreq);11267+STB_EXTERN void stb_arith_decode_advance(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq);11268+STB_EXTERN unsigned int stb_arith_decode_value_log2(stb_arith *a, unsigned int totalfreq2);11269+STB_EXTERN void stb_arith_decode_advance_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq);11270+11271+STB_EXTERN void stb_arith_encode_byte(stb_arith *a, int byte);11272+STB_EXTERN int stb_arith_decode_byte(stb_arith *a);11273+11274+// this is a memory-inefficient way of doing things, but it's11275+// fast(?) and simple11276+typedef struct11277+{11278+ unsigned short cumfreq;11279+ unsigned short samples;11280+} stb_arith_symstate_item;11281+11282+typedef struct11283+{11284+ int num_sym;11285+ unsigned int pow2;11286+ int countdown;11287+ stb_arith_symstate_item data[1];11288+} stb_arith_symstate;11289+11290+#ifdef STB_DEFINE11291+void stb_arith_init_encode(stb_arith *a, stbfile *out)11292+{11293+ a->range_low = 0;11294+ a->range_high = 0xffffffff;11295+ a->pending_ffs = -1; // means no buffered character currently, to speed up normal case11296+ a->output = out;11297+}11298+11299+static void stb__arith_carry(stb_arith *a)11300+{11301+ int i;11302+ assert(a->pending_ffs != -1); // can't carry with no data11303+ stb_putc(a->output, a->buffered_u8);11304+ for (i=0; i < a->pending_ffs; ++i)11305+ stb_putc(a->output, 0);11306+}11307+11308+static void stb__arith_putbyte(stb_arith *a, int byte)11309+{11310+ if (a->pending_ffs) {11311+ if (a->pending_ffs == -1) { // means no buffered data; encoded for fast path efficiency11312+ if (byte == 0xff)11313+ stb_putc(a->output, byte); // just write it immediately11314+ else {11315+ a->buffered_u8 = byte;11316+ a->pending_ffs = 0;11317+ }11318+ } else if (byte == 0xff) {11319+ ++a->pending_ffs;11320+ } else {11321+ int i;11322+ stb_putc(a->output, a->buffered_u8);11323+ for (i=0; i < a->pending_ffs; ++i)11324+ stb_putc(a->output, 0xff);11325+ }11326+ } else if (byte == 0xff) {11327+ ++a->pending_ffs;11328+ } else {11329+ // fast path11330+ stb_putc(a->output, a->buffered_u8);11331+ a->buffered_u8 = byte;11332+ }11333+}11334+11335+static void stb__arith_flush(stb_arith *a)11336+{11337+ if (a->pending_ffs >= 0) {11338+ int i;11339+ stb_putc(a->output, a->buffered_u8);11340+ for (i=0; i < a->pending_ffs; ++i)11341+ stb_putc(a->output, 0xff);11342+ }11343+}11344+11345+static void stb__renorm_encoder(stb_arith *a)11346+{11347+ stb__arith_putbyte(a, a->range_low >> 24);11348+ a->range_low <<= 8;11349+ a->range_high = (a->range_high << 8) | 0xff;11350+}11351+11352+static void stb__renorm_decoder(stb_arith *a)11353+{11354+ int c = stb_getc(a->output);11355+ a->code = (a->code << 8) + (c >= 0 ? c : 0); // if EOF, insert 011356+}11357+11358+void stb_arith_encode(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq)11359+{11360+ unsigned int range = a->range_high - a->range_low;11361+ unsigned int old = a->range_low;11362+ range /= totalfreq;11363+ a->range_low += range * cumfreq;11364+ a->range_high = a->range_low + range*freq;11365+ if (a->range_low < old)11366+ stb__arith_carry(a);11367+ while (a->range_high - a->range_low < 0x1000000)11368+ stb__renorm_encoder(a);11369+}11370+11371+void stb_arith_encode_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq)11372+{11373+ unsigned int range = a->range_high - a->range_low;11374+ unsigned int old = a->range_low;11375+ range >>= totalfreq2;11376+ a->range_low += range * cumfreq;11377+ a->range_high = a->range_low + range*freq;11378+ if (a->range_low < old)11379+ stb__arith_carry(a);11380+ while (a->range_high - a->range_low < 0x1000000)11381+ stb__renorm_encoder(a);11382+}11383+11384+unsigned int stb_arith_decode_value(stb_arith *a, unsigned int totalfreq)11385+{11386+ unsigned int freqsize = a->range / totalfreq;11387+ unsigned int z = a->code / freqsize;11388+ return z >= totalfreq ? totalfreq-1 : z;11389+}11390+11391+void stb_arith_decode_advance(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq)11392+{11393+ unsigned int freqsize = a->range / totalfreq; // @OPTIMIZE, share with above divide somehow?11394+ a->code -= freqsize * cumfreq;11395+ a->range = freqsize * freq;11396+ while (a->range < 0x1000000)11397+ stb__renorm_decoder(a);11398+}11399+11400+unsigned int stb_arith_decode_value_log2(stb_arith *a, unsigned int totalfreq2)11401+{11402+ unsigned int freqsize = a->range >> totalfreq2;11403+ unsigned int z = a->code / freqsize;11404+ return z >= (1U<<totalfreq2) ? (1U<<totalfreq2)-1 : z;11405+}11406+11407+void stb_arith_decode_advance_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq)11408+{11409+ unsigned int freqsize = a->range >> totalfreq2;11410+ a->code -= freqsize * cumfreq;11411+ a->range = freqsize * freq;11412+ while (a->range < 0x1000000)11413+ stb__renorm_decoder(a);11414+}11415+11416+stbfile *stb_arith_encode_close(stb_arith *a)11417+{11418+ // put exactly as many bytes as we'll read, so we can turn on/off arithmetic coding in a stream11419+ stb__arith_putbyte(a, a->range_low >> 24);11420+ stb__arith_putbyte(a, a->range_low >> 16);11421+ stb__arith_putbyte(a, a->range_low >> 8);11422+ stb__arith_putbyte(a, a->range_low >> 0);11423+ stb__arith_flush(a);11424+ return a->output;11425+}11426+11427+stbfile *stb_arith_decode_close(stb_arith *a)11428+{11429+ return a->output;11430+}11431+#endif11432+11433+//////////////////////////////////////////////////////////////////////////////11434+//11435+// Threads11436+//11437+11438+#ifndef _WIN3211439+#ifdef STB_THREADS11440+#error "threads not implemented except for Windows"11441+#endif11442+#endif11443+11444+// call this function to free any global variables for memory testing11445+STB_EXTERN void stb_thread_cleanup(void);11446+11447+typedef void * (*stb_thread_func)(void *);11448+11449+// do not rely on these types, this is an implementation detail.11450+// compare against STB_THREAD_NULL and ST_SEMAPHORE_NULL11451+typedef void *stb_thread;11452+typedef void *stb_semaphore;11453+typedef void *stb_mutex;11454+typedef struct stb__sync *stb_sync;11455+11456+#define STB_SEMAPHORE_NULL NULL11457+#define STB_THREAD_NULL NULL11458+#define STB_MUTEX_NULL NULL11459+#define STB_SYNC_NULL NULL11460+11461+// get the number of processors (limited to those in the affinity mask for this process).11462+STB_EXTERN int stb_processor_count(void);11463+// force to run on a single core -- needed for RDTSC to work, e.g. for iprof11464+STB_EXTERN void stb_force_uniprocessor(void);11465+11466+// stb_work functions: queue up work to be done by some worker threads11467+11468+// set number of threads to serve the queue; you can change this on the fly,11469+// but if you decrease it, it won't decrease until things currently on the11470+// queue are finished11471+STB_EXTERN void stb_work_numthreads(int n);11472+// set maximum number of units in the queue; you can only set this BEFORE running any work functions11473+STB_EXTERN int stb_work_maxunits(int n);11474+// enqueue some work to be done (can do this from any thread, or even from a piece of work);11475+// return value of f is stored in *return_code if non-NULL11476+STB_EXTERN int stb_work(stb_thread_func f, void *d, volatile void **return_code);11477+// as above, but stb_sync_reach is called on 'rel' after work is complete11478+STB_EXTERN int stb_work_reach(stb_thread_func f, void *d, volatile void **return_code, stb_sync rel);11479+11480+11481+// necessary to call this when using volatile to order writes/reads11482+STB_EXTERN void stb_barrier(void);11483+11484+// support for independent queues with their own threads11485+11486+typedef struct stb__workqueue stb_workqueue;11487+11488+STB_EXTERN stb_workqueue*stb_workq_new(int numthreads, int max_units);11489+STB_EXTERN stb_workqueue*stb_workq_new_flags(int numthreads, int max_units, int no_add_mutex, int no_remove_mutex);11490+STB_EXTERN void stb_workq_delete(stb_workqueue *q);11491+STB_EXTERN void stb_workq_numthreads(stb_workqueue *q, int n);11492+STB_EXTERN int stb_workq(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code);11493+STB_EXTERN int stb_workq_reach(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel);11494+STB_EXTERN int stb_workq_length(stb_workqueue *q);11495+11496+STB_EXTERN stb_thread stb_create_thread (stb_thread_func f, void *d);11497+STB_EXTERN stb_thread stb_create_thread2(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel);11498+STB_EXTERN void stb_destroy_thread(stb_thread t);11499+11500+STB_EXTERN stb_semaphore stb_sem_new(int max_val);11501+STB_EXTERN stb_semaphore stb_sem_new_extra(int max_val, int start_val);11502+STB_EXTERN void stb_sem_delete (stb_semaphore s);11503+STB_EXTERN void stb_sem_waitfor(stb_semaphore s);11504+STB_EXTERN void stb_sem_release(stb_semaphore s);11505+11506+STB_EXTERN stb_mutex stb_mutex_new(void);11507+STB_EXTERN void stb_mutex_delete(stb_mutex m);11508+STB_EXTERN void stb_mutex_begin(stb_mutex m);11509+STB_EXTERN void stb_mutex_end(stb_mutex m);11510+11511+STB_EXTERN stb_sync stb_sync_new(void);11512+STB_EXTERN void stb_sync_delete(stb_sync s);11513+STB_EXTERN int stb_sync_set_target(stb_sync s, int count);11514+STB_EXTERN void stb_sync_reach_and_wait(stb_sync s); // wait for 'target' reachers11515+STB_EXTERN int stb_sync_reach(stb_sync s);11516+11517+typedef struct stb__threadqueue stb_threadqueue;11518+#define STB_THREADQ_DYNAMIC 011519+STB_EXTERN stb_threadqueue *stb_threadq_new(int item_size, int num_items, int many_add, int many_remove);11520+STB_EXTERN void stb_threadq_delete(stb_threadqueue *tq);11521+STB_EXTERN int stb_threadq_get(stb_threadqueue *tq, void *output);11522+STB_EXTERN void stb_threadq_get_block(stb_threadqueue *tq, void *output);11523+STB_EXTERN int stb_threadq_add(stb_threadqueue *tq, void *input);11524+// can return FALSE if STB_THREADQ_DYNAMIC and attempt to grow fails11525+STB_EXTERN int stb_threadq_add_block(stb_threadqueue *tq, void *input);11526+11527+#ifdef STB_THREADS11528+#ifdef STB_DEFINE11529+11530+typedef struct11531+{11532+ stb_thread_func f;11533+ void *d;11534+ volatile void **return_val;11535+ stb_semaphore sem;11536+} stb__thread;11537+11538+// this is initialized along all possible paths to create threads, therefore11539+// it's always initialized before any other threads are create, therefore11540+// it's free of races AS LONG AS you only create threads through stb_*11541+static stb_mutex stb__threadmutex, stb__workmutex;11542+11543+static void stb__threadmutex_init(void)11544+{11545+ if (stb__threadmutex == STB_SEMAPHORE_NULL) {11546+ stb__threadmutex = stb_mutex_new();11547+ stb__workmutex = stb_mutex_new();11548+ }11549+}11550+11551+#ifdef STB_THREAD_TEST11552+volatile float stb__t1=1, stb__t2;11553+11554+static void stb__wait(int n)11555+{11556+ float z = 0;11557+ int i;11558+ for (i=0; i < n; ++i)11559+ z += 1 / (stb__t1+i);11560+ stb__t2 = z;11561+}11562+#else11563+#define stb__wait(x)11564+#endif11565+11566+#ifdef _WIN3211567+11568+// avoid including windows.h -- note that our definitions aren't11569+// exactly the same (we don't define the security descriptor struct)11570+// so if you want to include windows.h, make sure you do it first.11571+#include <process.h>11572+11573+#ifndef _WINDOWS_ // check windows.h guard11574+#define STB__IMPORT STB_EXTERN __declspec(dllimport)11575+#define STB__DW unsigned long11576+11577+STB__IMPORT int __stdcall TerminateThread(void *, STB__DW);11578+STB__IMPORT void * __stdcall CreateSemaphoreA(void *sec, long,long,char*);11579+STB__IMPORT int __stdcall CloseHandle(void *);11580+STB__IMPORT STB__DW __stdcall WaitForSingleObject(void *, STB__DW);11581+STB__IMPORT int __stdcall ReleaseSemaphore(void *, long, long *);11582+STB__IMPORT void __stdcall Sleep(STB__DW);11583+#endif11584+11585+// necessary to call this when using volatile to order writes/reads11586+void stb_barrier(void)11587+{11588+ #ifdef MemoryBarrier11589+ MemoryBarrier();11590+ #else11591+ long temp;11592+ __asm xchg temp,eax;11593+ #endif11594+}11595+11596+static void stb__thread_run(void *t)11597+{11598+ void *res;11599+ stb__thread info = * (stb__thread *) t;11600+ free(t);11601+ res = info.f(info.d);11602+ if (info.return_val)11603+ *info.return_val = res;11604+ if (info.sem != STB_SEMAPHORE_NULL)11605+ stb_sem_release(info.sem);11606+}11607+11608+static stb_thread stb_create_thread_raw(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel)11609+{11610+#ifdef _MT11611+#if defined(STB_FASTMALLOC) && !defined(STB_FASTMALLOC_ITS_OKAY_I_ONLY_MALLOC_IN_ONE_THREAD)11612+ stb_fatal("Error! Cannot use STB_FASTMALLOC with threads.\n");11613+ return STB_THREAD_NULL;11614+#else11615+ unsigned long id;11616+ stb__thread *data = (stb__thread *) malloc(sizeof(*data));11617+ if (!data) return NULL;11618+ stb__threadmutex_init();11619+ data->f = f;11620+ data->d = d;11621+ data->return_val = return_code;11622+ data->sem = rel;11623+ id = _beginthread(stb__thread_run, 0, data);11624+ if (id == -1) return NULL;11625+ return (void *) id;11626+#endif11627+#else11628+#ifdef STB_NO_STB_STRINGS11629+ stb_fatal("Invalid compilation");11630+#else11631+ stb_fatal("Must compile mult-threaded to use stb_thread/stb_work.");11632+#endif11633+ return NULL;11634+#endif11635+}11636+11637+// trivial win32 wrappers11638+void stb_destroy_thread(stb_thread t) { TerminateThread(t,0); }11639+stb_semaphore stb_sem_new(int maxv) {return CreateSemaphoreA(NULL,0,maxv,NULL); }11640+stb_semaphore stb_sem_new_extra(int maxv,int start){return CreateSemaphoreA(NULL,start,maxv,NULL); }11641+void stb_sem_delete(stb_semaphore s) { if (s != NULL) CloseHandle(s); }11642+void stb_sem_waitfor(stb_semaphore s) { WaitForSingleObject(s, 0xffffffff); } // INFINITE11643+void stb_sem_release(stb_semaphore s) { ReleaseSemaphore(s,1,NULL); }11644+static void stb__thread_sleep(int ms) { Sleep(ms); }11645+11646+#ifndef _WINDOWS_11647+STB__IMPORT int __stdcall GetProcessAffinityMask(void *, STB__DW *, STB__DW *);11648+STB__IMPORT void * __stdcall GetCurrentProcess(void);11649+STB__IMPORT int __stdcall SetProcessAffinityMask(void *, STB__DW);11650+#endif11651+11652+int stb_processor_count(void)11653+{11654+ unsigned long proc,sys;11655+ GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys);11656+ return stb_bitcount(proc);11657+}11658+11659+void stb_force_uniprocessor(void)11660+{11661+ unsigned long proc,sys;11662+ GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys);11663+ if (stb_bitcount(proc) > 1) {11664+ int z;11665+ for (z=0; z < 32; ++z)11666+ if (proc & (1 << z))11667+ break;11668+ if (z < 32) {11669+ proc = 1 << z;11670+ SetProcessAffinityMask(GetCurrentProcess(), proc);11671+ }11672+ }11673+}11674+11675+#ifdef _WINDOWS_11676+#define STB_MUTEX_NATIVE11677+void *stb_mutex_new(void)11678+{11679+ CRITICAL_SECTION *p = (CRITICAL_SECTION *) malloc(sizeof(*p));11680+ if (p)11681+#if _WIN32_WINNT >= 0x050011682+ InitializeCriticalSectionAndSpinCount(p, 500);11683+#else11684+ InitializeCriticalSection(p);11685+#endif11686+ return p;11687+}11688+11689+void stb_mutex_delete(void *p)11690+{11691+ if (p) {11692+ DeleteCriticalSection((CRITICAL_SECTION *) p);11693+ free(p);11694+ }11695+}11696+11697+void stb_mutex_begin(void *p)11698+{11699+ stb__wait(500);11700+ if (p)11701+ EnterCriticalSection((CRITICAL_SECTION *) p);11702+}11703+11704+void stb_mutex_end(void *p)11705+{11706+ if (p)11707+ LeaveCriticalSection((CRITICAL_SECTION *) p);11708+ stb__wait(500);11709+}11710+#endif // _WINDOWS_11711+11712+#if 011713+// for future reference,11714+// InterlockedCompareExchange for x86:11715+ int cas64_mp(void * dest, void * xcmp, void * xxchg) {11716+ __asm11717+ {11718+ mov esi, [xxchg] ; exchange11719+ mov ebx, [esi + 0]11720+ mov ecx, [esi + 4]11721+11722+ mov esi, [xcmp] ; comparand11723+ mov eax, [esi + 0]11724+ mov edx, [esi + 4]11725+11726+ mov edi, [dest] ; destination11727+ lock cmpxchg8b [edi]11728+ jz yyyy;11729+11730+ mov [esi + 0], eax;11731+ mov [esi + 4], edx;11732+11733+yyyy:11734+ xor eax, eax;11735+ setz al;11736+ };11737+11738+inline unsigned __int64 _InterlockedCompareExchange64(volatile unsigned __int64 *dest11739+ ,unsigned __int64 exchange11740+ ,unsigned __int64 comperand)11741+{11742+ //value returned in eax::edx11743+ __asm {11744+ lea esi,comperand;11745+ lea edi,exchange;11746+11747+ mov eax,[esi];11748+ mov edx,4[esi];11749+ mov ebx,[edi];11750+ mov ecx,4[edi];11751+ mov esi,dest;11752+ lock CMPXCHG8B [esi];11753+ }11754+#endif // #if 011755+11756+#endif // _WIN3211757+11758+stb_thread stb_create_thread2(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel)11759+{11760+ return stb_create_thread_raw(f,d,return_code,rel);11761+}11762+11763+stb_thread stb_create_thread(stb_thread_func f, void *d)11764+{11765+ return stb_create_thread2(f,d,NULL,STB_SEMAPHORE_NULL);11766+}11767+11768+// mutex implemented by wrapping semaphore11769+#ifndef STB_MUTEX_NATIVE11770+stb_mutex stb_mutex_new(void) { return stb_sem_new_extra(1,1); }11771+void stb_mutex_delete(stb_mutex m) { stb_sem_delete (m); }11772+void stb_mutex_begin(stb_mutex m) { stb__wait(500); if (m) stb_sem_waitfor(m); }11773+void stb_mutex_end(stb_mutex m) { if (m) stb_sem_release(m); stb__wait(500); }11774+#endif11775+11776+// thread merge operation11777+struct stb__sync11778+{11779+ int target; // target number of threads to hit it11780+ int sofar; // total threads that hit it11781+ int waiting; // total threads waiting11782+11783+ stb_mutex start; // mutex to prevent starting again before finishing previous11784+ stb_mutex mutex; // mutex while tweaking state11785+ stb_semaphore release; // semaphore wake up waiting threads11786+ // we have to wake them up one at a time, rather than using a single release11787+ // call, because win32 semaphores don't let you dynamically change the max count!11788+};11789+11790+stb_sync stb_sync_new(void)11791+{11792+ stb_sync s = (stb_sync) malloc(sizeof(*s));11793+ if (!s) return s;11794+11795+ s->target = s->sofar = s->waiting = 0;11796+ s->mutex = stb_mutex_new();11797+ s->start = stb_mutex_new();11798+ s->release = stb_sem_new(1);11799+ if (s->mutex == STB_MUTEX_NULL || s->release == STB_SEMAPHORE_NULL || s->start == STB_MUTEX_NULL) {11800+ stb_mutex_delete(s->mutex);11801+ stb_mutex_delete(s->mutex);11802+ stb_sem_delete(s->release);11803+ free(s);11804+ return NULL;11805+ }11806+ return s;11807+}11808+11809+void stb_sync_delete(stb_sync s)11810+{11811+ if (s->waiting) {11812+ // it's bad to delete while there are threads waiting!11813+ // shall we wait for them to reach, or just bail? just bail11814+ assert(0);11815+ }11816+ stb_mutex_delete(s->mutex);11817+ stb_mutex_delete(s->release);11818+ free(s);11819+}11820+11821+int stb_sync_set_target(stb_sync s, int count)11822+{11823+ // don't allow setting a target until the last one is fully released;11824+ // note that this can lead to inefficient pipelining, and maybe we'd11825+ // be better off ping-ponging between two internal syncs?11826+ // I tried seeing how often this happened using TryEnterCriticalSection11827+ // and could _never_ get it to happen in imv(stb), even with more threads11828+ // than processors. So who knows!11829+ stb_mutex_begin(s->start);11830+11831+ // this mutex is pointless, since it's not valid for threads11832+ // to call reach() before anyone calls set_target() anyway11833+ stb_mutex_begin(s->mutex);11834+11835+ assert(s->target == 0); // enforced by start mutex11836+ s->target = count;11837+ s->sofar = 0;11838+ s->waiting = 0;11839+ stb_mutex_end(s->mutex);11840+ return STB_TRUE;11841+}11842+11843+void stb__sync_release(stb_sync s)11844+{11845+ if (s->waiting)11846+ stb_sem_release(s->release);11847+ else {11848+ s->target = 0;11849+ stb_mutex_end(s->start);11850+ }11851+}11852+11853+int stb_sync_reach(stb_sync s)11854+{11855+ int n;11856+ stb_mutex_begin(s->mutex);11857+ assert(s->sofar < s->target);11858+ n = ++s->sofar; // record this value to avoid possible race if we did 'return s->sofar';11859+ if (s->sofar == s->target)11860+ stb__sync_release(s);11861+ stb_mutex_end(s->mutex);11862+ return n;11863+}11864+11865+void stb_sync_reach_and_wait(stb_sync s)11866+{11867+ stb_mutex_begin(s->mutex);11868+ assert(s->sofar < s->target);11869+ ++s->sofar;11870+ if (s->sofar == s->target) {11871+ stb__sync_release(s);11872+ stb_mutex_end(s->mutex);11873+ } else {11874+ ++s->waiting; // we're waiting, so one more waiter11875+ stb_mutex_end(s->mutex); // release the mutex to other threads11876+11877+ stb_sem_waitfor(s->release); // wait for merge completion11878+11879+ stb_mutex_begin(s->mutex); // on merge completion, grab the mutex11880+ --s->waiting; // we're done waiting11881+ stb__sync_release(s); // restart the next waiter11882+ stb_mutex_end(s->mutex); // and now we're done11883+ // this ends the same as the first case, but it's a lot11884+ // clearer to understand without sharing the code11885+ }11886+}11887+11888+struct stb__threadqueue11889+{11890+ stb_mutex add, remove;11891+ stb_semaphore nonempty, nonfull;11892+ int head_blockers; // number of threads blocking--used to know whether to release(avail)11893+ int tail_blockers;11894+ int head, tail, array_size, growable;11895+ int item_size;11896+ char *data;11897+};11898+11899+static int stb__tq_wrap(volatile stb_threadqueue *z, int p)11900+{11901+ if (p == z->array_size)11902+ return p - z->array_size;11903+ else11904+ return p;11905+}11906+11907+int stb__threadq_get_raw(stb_threadqueue *tq2, void *output, int block)11908+{11909+ volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;11910+ if (tq->head == tq->tail && !block) return 0;11911+11912+ stb_mutex_begin(tq->remove);11913+11914+ while (tq->head == tq->tail) {11915+ if (!block) {11916+ stb_mutex_end(tq->remove);11917+ return 0;11918+ }11919+ ++tq->head_blockers;11920+ stb_mutex_end(tq->remove);11921+11922+ stb_sem_waitfor(tq->nonempty);11923+11924+ stb_mutex_begin(tq->remove);11925+ --tq->head_blockers;11926+ }11927+11928+ memcpy(output, tq->data + tq->head*tq->item_size, tq->item_size);11929+ stb_barrier();11930+ tq->head = stb__tq_wrap(tq, tq->head+1);11931+11932+ stb_sem_release(tq->nonfull);11933+ if (tq->head_blockers) // can't check if actually non-empty due to race?11934+ stb_sem_release(tq->nonempty); // if there are other blockers, wake one11935+11936+ stb_mutex_end(tq->remove);11937+ return STB_TRUE;11938+}11939+11940+int stb__threadq_grow(volatile stb_threadqueue *tq)11941+{11942+ int n;11943+ char *p;11944+ assert(tq->remove != STB_MUTEX_NULL); // must have this to allow growth!11945+ stb_mutex_begin(tq->remove);11946+11947+ n = tq->array_size * 2;11948+ p = (char *) realloc(tq->data, n * tq->item_size);11949+ if (p == NULL) {11950+ stb_mutex_end(tq->remove);11951+ stb_mutex_end(tq->add);11952+ return STB_FALSE;11953+ }11954+ if (tq->tail < tq->head) {11955+ memcpy(p + tq->array_size * tq->item_size, p, tq->tail * tq->item_size);11956+ tq->tail += tq->array_size;11957+ }11958+ tq->data = p;11959+ tq->array_size = n;11960+11961+ stb_mutex_end(tq->remove);11962+ return STB_TRUE;11963+}11964+11965+int stb__threadq_add_raw(stb_threadqueue *tq2, void *input, int block)11966+{11967+ int tail,pos;11968+ volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;11969+ stb_mutex_begin(tq->add);11970+ for(;;) {11971+ pos = tq->tail;11972+ tail = stb__tq_wrap(tq, pos+1);11973+ if (tail != tq->head) break;11974+11975+ // full11976+ if (tq->growable) {11977+ if (!stb__threadq_grow(tq)) {11978+ stb_mutex_end(tq->add);11979+ return STB_FALSE; // out of memory11980+ }11981+ } else if (!block) {11982+ stb_mutex_end(tq->add);11983+ return STB_FALSE;11984+ } else {11985+ ++tq->tail_blockers;11986+ stb_mutex_end(tq->add);11987+11988+ stb_sem_waitfor(tq->nonfull);11989+11990+ stb_mutex_begin(tq->add);11991+ --tq->tail_blockers;11992+ }11993+ }11994+ memcpy(tq->data + tq->item_size * pos, input, tq->item_size);11995+ stb_barrier();11996+ tq->tail = tail;11997+ stb_sem_release(tq->nonempty);11998+ if (tq->tail_blockers) // can't check if actually non-full due to race?11999+ stb_sem_release(tq->nonfull);12000+ stb_mutex_end(tq->add);12001+ return STB_TRUE;12002+}12003+12004+int stb_threadq_length(stb_threadqueue *tq2)12005+{12006+ int a,b,n;12007+ volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;12008+ stb_mutex_begin(tq->add);12009+ a = tq->head;12010+ b = tq->tail;12011+ n = tq->array_size;12012+ stb_mutex_end(tq->add);12013+ if (a > b) b += n;12014+ return b-a;12015+}12016+12017+int stb_threadq_get(stb_threadqueue *tq, void *output)12018+{12019+ return stb__threadq_get_raw(tq, output, STB_FALSE);12020+}12021+12022+void stb_threadq_get_block(stb_threadqueue *tq, void *output)12023+{12024+ stb__threadq_get_raw(tq, output, STB_TRUE);12025+}12026+12027+int stb_threadq_add(stb_threadqueue *tq, void *input)12028+{12029+ return stb__threadq_add_raw(tq, input, STB_FALSE);12030+}12031+12032+int stb_threadq_add_block(stb_threadqueue *tq, void *input)12033+{12034+ return stb__threadq_add_raw(tq, input, STB_TRUE);12035+}12036+12037+void stb_threadq_delete(stb_threadqueue *tq)12038+{12039+ if (tq) {12040+ free(tq->data);12041+ stb_mutex_delete(tq->add);12042+ stb_mutex_delete(tq->remove);12043+ stb_sem_delete(tq->nonempty);12044+ stb_sem_delete(tq->nonfull);12045+ free(tq);12046+ }12047+}12048+12049+#define STB_THREADQUEUE_DYNAMIC 012050+stb_threadqueue *stb_threadq_new(int item_size, int num_items, int many_add, int many_remove)12051+{12052+ int error=0;12053+ stb_threadqueue *tq = (stb_threadqueue *) malloc(sizeof(*tq));12054+ if (tq == NULL) return NULL;12055+12056+ if (num_items == STB_THREADQUEUE_DYNAMIC) {12057+ tq->growable = STB_TRUE;12058+ num_items = 32;12059+ } else12060+ tq->growable = STB_FALSE;12061+12062+ tq->item_size = item_size;12063+ tq->array_size = num_items+1;12064+12065+ tq->add = tq->remove = STB_MUTEX_NULL;12066+ tq->nonempty = tq->nonfull = STB_SEMAPHORE_NULL;12067+ tq->data = NULL;12068+ if (many_add)12069+ { tq->add = stb_mutex_new(); if (tq->add == STB_MUTEX_NULL) goto error; }12070+ if (many_remove || tq->growable)12071+ { tq->remove = stb_mutex_new(); if (tq->remove == STB_MUTEX_NULL) goto error; }12072+ tq->nonempty = stb_sem_new(1); if (tq->nonempty == STB_SEMAPHORE_NULL) goto error;12073+ tq->nonfull = stb_sem_new(1); if (tq->nonfull == STB_SEMAPHORE_NULL) goto error;12074+ tq->data = (char *) malloc(tq->item_size * tq->array_size);12075+ if (tq->data == NULL) goto error;12076+12077+ tq->head = tq->tail = 0;12078+ tq->head_blockers = tq->tail_blockers = 0;12079+12080+ return tq;12081+12082+error:12083+ stb_threadq_delete(tq);12084+ return NULL;12085+}12086+12087+typedef struct12088+{12089+ stb_thread_func f;12090+ void *d;12091+ volatile void **retval;12092+ stb_sync sync;12093+} stb__workinfo;12094+12095+//static volatile stb__workinfo *stb__work;12096+12097+struct stb__workqueue12098+{12099+ int numthreads;12100+ stb_threadqueue *tq;12101+};12102+12103+static stb_workqueue *stb__work_global;12104+12105+static void *stb__thread_workloop(void *p)12106+{12107+ volatile stb_workqueue *q = (volatile stb_workqueue *) p;12108+ for(;;) {12109+ void *z;12110+ stb__workinfo w;12111+ stb_threadq_get_block(q->tq, &w);12112+ if (w.f == NULL) // null work is a signal to end the thread12113+ return NULL;12114+ z = w.f(w.d);12115+ if (w.retval) { stb_barrier(); *w.retval = z; }12116+ if (w.sync != STB_SYNC_NULL) stb_sync_reach(w.sync);12117+ }12118+}12119+12120+stb_workqueue *stb_workq_new(int num_threads, int max_units)12121+{12122+ return stb_workq_new_flags(num_threads, max_units, 0,0);12123+}12124+12125+stb_workqueue *stb_workq_new_flags(int numthreads, int max_units, int no_add_mutex, int no_remove_mutex)12126+{12127+ stb_workqueue *q = (stb_workqueue *) malloc(sizeof(*q));12128+ if (q == NULL) return NULL;12129+ q->tq = stb_threadq_new(sizeof(stb__workinfo), max_units, !no_add_mutex, !no_remove_mutex);12130+ if (q->tq == NULL) { free(q); return NULL; }12131+ q->numthreads = 0;12132+ stb_workq_numthreads(q, numthreads);12133+ return q;12134+}12135+12136+void stb_workq_delete(stb_workqueue *q)12137+{12138+ while (stb_workq_length(q) != 0)12139+ stb__thread_sleep(1);12140+ stb_threadq_delete(q->tq);12141+ free(q);12142+}12143+12144+static int stb__work_maxitems = STB_THREADQUEUE_DYNAMIC;12145+12146+static void stb_work_init(int num_threads)12147+{12148+ if (stb__work_global == NULL) {12149+ stb__threadmutex_init();12150+ stb_mutex_begin(stb__workmutex);12151+ stb_barrier();12152+ if (*(stb_workqueue * volatile *) &stb__work_global == NULL)12153+ stb__work_global = stb_workq_new(num_threads, stb__work_maxitems);12154+ stb_mutex_end(stb__workmutex);12155+ }12156+}12157+12158+static int stb__work_raw(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)12159+{12160+ stb__workinfo w;12161+ if (q == NULL) {12162+ stb_work_init(1);12163+ q = stb__work_global;12164+ }12165+ w.f = f;12166+ w.d = d;12167+ w.retval = return_code;12168+ w.sync = rel;12169+ return stb_threadq_add(q->tq, &w);12170+}12171+12172+int stb_workq_length(stb_workqueue *q)12173+{12174+ return stb_threadq_length(q->tq);12175+}12176+12177+int stb_workq(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code)12178+{12179+ if (f == NULL) return 0;12180+ return stb_workq_reach(q, f, d, return_code, NULL);12181+}12182+12183+int stb_workq_reach(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)12184+{12185+ if (f == NULL) return 0;12186+ return stb__work_raw(q, f, d, return_code, rel);12187+}12188+12189+static void stb__workq_numthreads(stb_workqueue *q, int n)12190+{12191+ while (q->numthreads < n) {12192+ stb_create_thread(stb__thread_workloop, q);12193+ ++q->numthreads;12194+ }12195+ while (q->numthreads > n) {12196+ stb__work_raw(q, NULL, NULL, NULL, NULL);12197+ --q->numthreads;12198+ }12199+}12200+12201+void stb_workq_numthreads(stb_workqueue *q, int n)12202+{12203+ stb_mutex_begin(stb__threadmutex);12204+ stb__workq_numthreads(q,n);12205+ stb_mutex_end(stb__threadmutex);12206+}12207+12208+int stb_work_maxunits(int n)12209+{12210+ if (stb__work_global == NULL) {12211+ stb__work_maxitems = n;12212+ stb_work_init(1);12213+ }12214+ return stb__work_maxitems;12215+}12216+12217+int stb_work(stb_thread_func f, void *d, volatile void **return_code)12218+{12219+ return stb_workq(stb__work_global, f,d,return_code);12220+}12221+12222+int stb_work_reach(stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)12223+{12224+ return stb_workq_reach(stb__work_global, f,d,return_code,rel);12225+}12226+12227+void stb_work_numthreads(int n)12228+{12229+ if (stb__work_global == NULL)12230+ stb_work_init(n);12231+ else12232+ stb_workq_numthreads(stb__work_global, n);12233+}12234+#endif // STB_DEFINE12235+12236+12237+//////////////////////////////////////////////////////////////////////////////12238+//12239+// Background disk I/O12240+//12241+//12242+12243+#define STB_BGIO_READ_ALL (-1)12244+STB_EXTERN int stb_bgio_read (char *filename, int offset, int len, stb_uchar **result, int *olen);12245+STB_EXTERN int stb_bgio_readf (FILE *f , int offset, int len, stb_uchar **result, int *olen);12246+STB_EXTERN int stb_bgio_read_to (char *filename, int offset, int len, stb_uchar *buffer, int *olen);12247+STB_EXTERN int stb_bgio_readf_to(FILE *f , int offset, int len, stb_uchar *buffer, int *olen);12248+12249+typedef struct12250+{12251+ int have_data;12252+ int is_valid;12253+ int is_dir;12254+ time_t filetime;12255+ stb_int64 filesize;12256+} stb_bgstat;12257+12258+STB_EXTERN int stb_bgio_stat (char *filename, stb_bgstat *result);12259+12260+#ifdef STB_DEFINE12261+12262+static stb_workqueue *stb__diskio;12263+static stb_mutex stb__diskio_mutex;12264+12265+void stb_thread_cleanup(void)12266+{12267+ if (stb__work_global) stb_workq_delete(stb__work_global); stb__work_global = NULL;12268+ if (stb__threadmutex) stb_mutex_delete(stb__threadmutex); stb__threadmutex = NULL;12269+ if (stb__workmutex) stb_mutex_delete(stb__workmutex); stb__workmutex = NULL;12270+ if (stb__diskio) stb_workq_delete(stb__diskio); stb__diskio = NULL;12271+ if (stb__diskio_mutex)stb_mutex_delete(stb__diskio_mutex);stb__diskio_mutex= NULL;12272+}12273+12274+12275+typedef struct12276+{12277+ char *filename;12278+ FILE *f;12279+ int offset;12280+ int len;12281+12282+ stb_bgstat *stat_out;12283+ stb_uchar *output;12284+ stb_uchar **result;12285+ int *len_output;12286+ int *flag;12287+} stb__disk_command;12288+12289+#define STB__MAX_DISK_COMMAND 10012290+static stb__disk_command stb__dc_queue[STB__MAX_DISK_COMMAND];12291+static int stb__dc_offset;12292+12293+void stb__io_init(void)12294+{12295+ if (!stb__diskio) {12296+ stb__threadmutex_init();12297+ stb_mutex_begin(stb__threadmutex);12298+ stb_barrier();12299+ if (*(stb_thread * volatile *) &stb__diskio == NULL) {12300+ stb__diskio_mutex = stb_mutex_new();12301+ // use many threads so OS can try to schedule seeks12302+ stb__diskio = stb_workq_new_flags(16,STB__MAX_DISK_COMMAND,STB_FALSE,STB_FALSE);12303+ }12304+ stb_mutex_end(stb__threadmutex);12305+ }12306+}12307+12308+static void * stb__io_error(stb__disk_command *dc)12309+{12310+ if (dc->len_output) *dc->len_output = 0;12311+ if (dc->result) *dc->result = NULL;12312+ if (dc->flag) *dc->flag = -1;12313+ return NULL;12314+}12315+12316+static void * stb__io_task(void *p)12317+{12318+ stb__disk_command *dc = (stb__disk_command *) p;12319+ int len;12320+ FILE *f;12321+ stb_uchar *buf;12322+12323+ if (dc->stat_out) {12324+ struct _stati64 s;12325+ if (!_stati64(dc->filename, &s)) {12326+ dc->stat_out->filesize = s.st_size;12327+ dc->stat_out->filetime = s.st_mtime;12328+ dc->stat_out->is_dir = s.st_mode & _S_IFDIR;12329+ dc->stat_out->is_valid = (s.st_mode & _S_IFREG) || dc->stat_out->is_dir;12330+ } else12331+ dc->stat_out->is_valid = 0;12332+ stb_barrier();12333+ dc->stat_out->have_data = 1;12334+ free(dc->filename);12335+ return 0;12336+ }12337+ if (dc->f) {12338+ #ifdef WIN3212339+ f = _fdopen(_dup(_fileno(dc->f)), "rb");12340+ #else12341+ f = fdopen(dup(fileno(dc->f)), "rb");12342+ #endif12343+ if (!f)12344+ return stb__io_error(dc);12345+ } else {12346+ f = fopen(dc->filename, "rb");12347+ free(dc->filename);12348+ if (!f)12349+ return stb__io_error(dc);12350+ }12351+12352+ len = dc->len;12353+ if (len < 0) {12354+ fseek(f, 0, SEEK_END);12355+ len = ftell(f) - dc->offset;12356+ }12357+12358+ if (fseek(f, dc->offset, SEEK_SET)) {12359+ fclose(f);12360+ return stb__io_error(dc);12361+ }12362+12363+ if (dc->output)12364+ buf = dc->output;12365+ else {12366+ buf = (stb_uchar *) malloc(len);12367+ if (buf == NULL) {12368+ fclose(f);12369+ return stb__io_error(dc);12370+ }12371+ }12372+12373+ len = fread(buf, 1, len, f);12374+ fclose(f);12375+ if (dc->len_output) *dc->len_output = len;12376+ if (dc->result) *dc->result = buf;12377+ if (dc->flag) *dc->flag = 1;12378+12379+ return NULL;12380+}12381+12382+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)12383+{12384+ int res;12385+ stb__io_init();12386+ // do memory allocation outside of mutex12387+ if (fname) fname = stb_p_strdup(fname);12388+ stb_mutex_begin(stb__diskio_mutex);12389+ {12390+ stb__disk_command *dc = &stb__dc_queue[stb__dc_offset];12391+ dc->filename = fname;12392+ dc->f = f;12393+ dc->offset = off;12394+ dc->len = len;12395+ dc->output = out;12396+ dc->result = result;12397+ dc->len_output = olen;12398+ dc->flag = flag;12399+ dc->stat_out = stat;12400+ res = stb_workq(stb__diskio, stb__io_task, dc, NULL);12401+ if (res)12402+ stb__dc_offset = (stb__dc_offset + 1 == STB__MAX_DISK_COMMAND ? 0 : stb__dc_offset+1);12403+ }12404+ stb_mutex_end(stb__diskio_mutex);12405+ return res;12406+}12407+12408+int stb_bgio_read(char *filename, int offset, int len, stb_uchar **result, int *olen)12409+{12410+ return stb__io_add(filename,NULL,offset,len,NULL,result,olen,NULL,NULL);12411+}12412+12413+int stb_bgio_readf(FILE *f, int offset, int len, stb_uchar **result, int *olen)12414+{12415+ return stb__io_add(NULL,f,offset,len,NULL,result,olen,NULL,NULL);12416+}12417+12418+int stb_bgio_read_to(char *filename, int offset, int len, stb_uchar *buffer, int *olen)12419+{12420+ return stb__io_add(filename,NULL,offset,len,buffer,NULL,olen,NULL,NULL);12421+}12422+12423+int stb_bgio_readf_to(FILE *f, int offset, int len, stb_uchar *buffer, int *olen)12424+{12425+ return stb__io_add(NULL,f,offset,len,buffer,NULL,olen,NULL,NULL);12426+}12427+12428+STB_EXTERN int stb_bgio_stat (char *filename, stb_bgstat *result)12429+{12430+ result->have_data = 0;12431+ return stb__io_add(filename,NULL,0,0,0,NULL,0,NULL, result);12432+}12433+#endif12434+#endif12435+12436+12437+12438+//////////////////////////////////////////////////////////////////////////////12439+//12440+// Fast malloc implementation12441+//12442+// This is a clone of TCMalloc, but without the thread support.12443+// 1. large objects are allocated directly, page-aligned12444+// 2. small objects are allocated in homogeonous heaps, 0 overhead12445+//12446+// We keep an allocation table for pages a la TCMalloc. This would12447+// require 4MB for the entire address space, but we only allocate12448+// the parts that are in use. The overhead from using homogenous heaps12449+// everywhere is 3MB. (That is, if you allocate 1 object of each size,12450+// you'll use 3MB.)12451+12452+#if defined(STB_DEFINE) && ((defined(_WIN32) && !defined(_M_AMD64)) || defined(STB_FASTMALLOC))12453+12454+#ifdef _WIN3212455+ #ifndef _WINDOWS_12456+ #ifndef STB__IMPORT12457+ #define STB__IMPORT STB_EXTERN __declspec(dllimport)12458+ #define STB__DW unsigned long12459+ #endif12460+ STB__IMPORT void * __stdcall VirtualAlloc(void *p, unsigned long size, unsigned long type, unsigned long protect);12461+ STB__IMPORT int __stdcall VirtualFree(void *p, unsigned long size, unsigned long freetype);12462+ #endif12463+ #define stb__alloc_pages_raw(x) (stb_uint32) VirtualAlloc(NULL, (x), 0x3000, 0x04)12464+ #define stb__dealloc_pages_raw(p) VirtualFree((void *) p, 0, 0x8000)12465+#else12466+ #error "Platform not currently supported"12467+#endif12468+12469+typedef struct stb__span12470+{12471+ int start, len;12472+ struct stb__span *next, *prev;12473+ void *first_free;12474+ unsigned short list; // 1..256 free; 257..511 sizeclass; 0=large block12475+ short allocations; // # outstanding allocations for sizeclass12476+} stb__span; // 2412477+12478+static stb__span **stb__span_for_page;12479+static int stb__firstpage, stb__lastpage;12480+static void stb__update_page_range(int first, int last)12481+{12482+ stb__span **sfp;12483+ int i, f,l;12484+ if (first >= stb__firstpage && last <= stb__lastpage) return;12485+ if (stb__span_for_page == NULL) {12486+ f = first;12487+ l = f+stb_max(last-f, 16384);12488+ l = stb_min(l, 1<<20);12489+ } else if (last > stb__lastpage) {12490+ f = stb__firstpage;12491+ l = f + (stb__lastpage - f) * 2;12492+ l = stb_clamp(last, l,1<<20);12493+ } else {12494+ l = stb__lastpage;12495+ f = l - (l - stb__firstpage) * 2;12496+ f = stb_clamp(f, 0,first);12497+ }12498+ sfp = (stb__span **) stb__alloc_pages_raw(sizeof(void *) * (l-f));12499+ for (i=f; i < stb__firstpage; ++i) sfp[i - f] = NULL;12500+ for ( ; i < stb__lastpage ; ++i) sfp[i - f] = stb__span_for_page[i - stb__firstpage];12501+ for ( ; i < l ; ++i) sfp[i - f] = NULL;12502+ if (stb__span_for_page) stb__dealloc_pages_raw(stb__span_for_page);12503+ stb__firstpage = f;12504+ stb__lastpage = l;12505+ stb__span_for_page = sfp;12506+}12507+12508+static stb__span *stb__span_free=NULL;12509+static stb__span *stb__span_first, *stb__span_end;12510+static stb__span *stb__span_alloc(void)12511+{12512+ stb__span *s = stb__span_free;12513+ if (s)12514+ stb__span_free = s->next;12515+ else {12516+ if (!stb__span_first) {12517+ stb__span_first = (stb__span *) stb__alloc_pages_raw(65536);12518+ if (stb__span_first == NULL) return NULL;12519+ stb__span_end = stb__span_first + (65536 / sizeof(stb__span));12520+ }12521+ s = stb__span_first++;12522+ if (stb__span_first == stb__span_end) stb__span_first = NULL;12523+ }12524+ return s;12525+}12526+12527+static stb__span *stb__spanlist[512];12528+12529+static void stb__spanlist_unlink(stb__span *s)12530+{12531+ if (s->prev)12532+ s->prev->next = s->next;12533+ else {12534+ int n = s->list;12535+ assert(stb__spanlist[n] == s);12536+ stb__spanlist[n] = s->next;12537+ }12538+ if (s->next)12539+ s->next->prev = s->prev;12540+ s->next = s->prev = NULL;12541+ s->list = 0;12542+}12543+12544+static void stb__spanlist_add(int n, stb__span *s)12545+{12546+ s->list = n;12547+ s->next = stb__spanlist[n];12548+ s->prev = NULL;12549+ stb__spanlist[n] = s;12550+ if (s->next) s->next->prev = s;12551+}12552+12553+#define stb__page_shift 1212554+#define stb__page_size (1 << stb__page_shift)12555+#define stb__page_number(x) ((x) >> stb__page_shift)12556+#define stb__page_address(x) ((x) << stb__page_shift)12557+12558+static void stb__set_span_for_page(stb__span *s)12559+{12560+ int i;12561+ for (i=0; i < s->len; ++i)12562+ stb__span_for_page[s->start + i - stb__firstpage] = s;12563+}12564+12565+static stb__span *stb__coalesce(stb__span *a, stb__span *b)12566+{12567+ assert(a->start + a->len == b->start);12568+ if (a->list) stb__spanlist_unlink(a);12569+ if (b->list) stb__spanlist_unlink(b);12570+ a->len += b->len;12571+ b->len = 0;12572+ b->next = stb__span_free;12573+ stb__span_free = b;12574+ stb__set_span_for_page(a);12575+ return a;12576+}12577+12578+static void stb__free_span(stb__span *s)12579+{12580+ stb__span *n = NULL;12581+ if (s->start > stb__firstpage) {12582+ n = stb__span_for_page[s->start-1 - stb__firstpage];12583+ if (n && n->allocations == -2 && n->start + n->len == s->start) s = stb__coalesce(n,s);12584+ }12585+ if (s->start + s->len < stb__lastpage) {12586+ n = stb__span_for_page[s->start + s->len - stb__firstpage];12587+ if (n && n->allocations == -2 && s->start + s->len == n->start) s = stb__coalesce(s,n);12588+ }12589+ s->allocations = -2;12590+ stb__spanlist_add(s->len > 256 ? 256 : s->len, s);12591+}12592+12593+static stb__span *stb__alloc_pages(int num)12594+{12595+ stb__span *s = stb__span_alloc();12596+ int p;12597+ if (!s) return NULL;12598+ p = stb__alloc_pages_raw(num << stb__page_shift);12599+ if (p == 0) { s->next = stb__span_free; stb__span_free = s; return 0; }12600+ assert(stb__page_address(stb__page_number(p)) == p);12601+ p = stb__page_number(p);12602+ stb__update_page_range(p, p+num);12603+ s->start = p;12604+ s->len = num;12605+ s->next = NULL;12606+ s->prev = NULL;12607+ stb__set_span_for_page(s);12608+ return s;12609+}12610+12611+static stb__span *stb__alloc_span(int pagecount)12612+{12613+ int i;12614+ stb__span *p = NULL;12615+ for(i=pagecount; i < 256; ++i)12616+ if (stb__spanlist[i]) {12617+ p = stb__spanlist[i];12618+ break;12619+ }12620+ if (!p) {12621+ p = stb__spanlist[256];12622+ while (p && p->len < pagecount)12623+ p = p->next;12624+ }12625+ if (!p) {12626+ p = stb__alloc_pages(pagecount < 16 ? 16 : pagecount);12627+ if (p == NULL) return 0;12628+ } else12629+ stb__spanlist_unlink(p);12630+12631+ if (p->len > pagecount) {12632+ stb__span *q = stb__span_alloc();12633+ if (q) {12634+ q->start = p->start + pagecount;12635+ q->len = p->len - pagecount;12636+ p->len = pagecount;12637+ for (i=0; i < q->len; ++i)12638+ stb__span_for_page[q->start+i - stb__firstpage] = q;12639+ stb__spanlist_add(q->len > 256 ? 256 : q->len, q);12640+ }12641+ }12642+ return p;12643+}12644+12645+#define STB__MAX_SMALL_SIZE 3276812646+#define STB__MAX_SIZE_CLASSES 25612647+12648+static unsigned char stb__class_base[32];12649+static unsigned char stb__class_shift[32];12650+static unsigned char stb__pages_for_class[STB__MAX_SIZE_CLASSES];12651+static int stb__size_for_class[STB__MAX_SIZE_CLASSES];12652+12653+stb__span *stb__get_nonempty_sizeclass(int c)12654+{12655+ int s = c + 256, i, size, tsize; // remap to span-list index12656+ char *z;12657+ void *q;12658+ stb__span *p = stb__spanlist[s];12659+ if (p) {12660+ if (p->first_free) return p; // fast path: it's in the first one in list12661+ for (p=p->next; p; p=p->next)12662+ if (p->first_free) {12663+ // move to front for future queries12664+ stb__spanlist_unlink(p);12665+ stb__spanlist_add(s, p);12666+ return p;12667+ }12668+ }12669+ // no non-empty ones, so allocate a new one12670+ p = stb__alloc_span(stb__pages_for_class[c]);12671+ if (!p) return NULL;12672+ // create the free list up front12673+ size = stb__size_for_class[c];12674+ tsize = stb__pages_for_class[c] << stb__page_shift;12675+ i = 0;12676+ z = (char *) stb__page_address(p->start);12677+ q = NULL;12678+ while (i + size <= tsize) {12679+ * (void **) z = q; q = z;12680+ z += size;12681+ i += size;12682+ }12683+ p->first_free = q;12684+ p->allocations = 0;12685+ stb__spanlist_add(s,p);12686+ return p;12687+}12688+12689+static int stb__sizeclass(size_t sz)12690+{12691+ int z = stb_log2_floor(sz); // -1 below to group e.g. 13,14,15,16 correctly12692+ return stb__class_base[z] + ((sz-1) >> stb__class_shift[z]);12693+}12694+12695+static void stb__init_sizeclass(void)12696+{12697+ int i, size, overhead;12698+ int align_shift = 2; // allow 4-byte and 12-byte blocks as well, vs. TCMalloc12699+ int next_class = 1;12700+ int last_log = 0;12701+12702+ for (i = 0; i < align_shift; i++) {12703+ stb__class_base [i] = next_class;12704+ stb__class_shift[i] = align_shift;12705+ }12706+12707+ for (size = 1 << align_shift; size <= STB__MAX_SMALL_SIZE; size += 1 << align_shift) {12708+ i = stb_log2_floor(size);12709+ if (i > last_log) {12710+ if (size == 16) ++align_shift; // switch from 4-byte to 8-byte alignment12711+ else if (size >= 128 && align_shift < 8) ++align_shift;12712+ stb__class_base[i] = next_class - ((size-1) >> align_shift);12713+ stb__class_shift[i] = align_shift;12714+ last_log = i;12715+ }12716+ stb__size_for_class[next_class++] = size;12717+ }12718+12719+ for (i=1; i <= STB__MAX_SMALL_SIZE; ++i)12720+ assert(i <= stb__size_for_class[stb__sizeclass(i)]);12721+12722+ overhead = 0;12723+ for (i = 1; i < next_class; i++) {12724+ int s = stb__size_for_class[i];12725+ size = stb__page_size;12726+ while (size % s > size >> 3)12727+ size += stb__page_size;12728+ stb__pages_for_class[i] = (unsigned char) (size >> stb__page_shift);12729+ overhead += size;12730+ }12731+ assert(overhead < (4 << 20)); // make sure it's under 4MB of overhead12732+}12733+12734+#ifdef STB_DEBUG12735+#define stb__smemset(a,b,c) memset((void *) a, b, c)12736+#elif defined(STB_FASTMALLOC_INIT)12737+#define stb__smemset(a,b,c) memset((void *) a, b, c)12738+#else12739+#define stb__smemset(a,b,c)12740+#endif12741+void *stb_smalloc(size_t sz)12742+{12743+ stb__span *s;12744+ if (sz == 0) return NULL;12745+ if (stb__size_for_class[1] == 0) stb__init_sizeclass();12746+ if (sz > STB__MAX_SMALL_SIZE) {12747+ s = stb__alloc_span((sz + stb__page_size - 1) >> stb__page_shift);12748+ if (s == NULL) return NULL;12749+ s->list = 0;12750+ s->next = s->prev = NULL;12751+ s->allocations = -32767;12752+ stb__smemset(stb__page_address(s->start), 0xcd, (sz+3)&~3);12753+ return (void *) stb__page_address(s->start);12754+ } else {12755+ void *p;12756+ int c = stb__sizeclass(sz);12757+ s = stb__spanlist[256+c];12758+ if (!s || !s->first_free)12759+ s = stb__get_nonempty_sizeclass(c);12760+ if (s == NULL) return NULL;12761+ p = s->first_free;12762+ s->first_free = * (void **) p;12763+ ++s->allocations;12764+ stb__smemset(p,0xcd, sz);12765+ return p;12766+ }12767+}12768+12769+int stb_ssize(void *p)12770+{12771+ stb__span *s;12772+ if (p == NULL) return 0;12773+ s = stb__span_for_page[stb__page_number((stb_uint) p) - stb__firstpage];12774+ if (s->list >= 256) {12775+ return stb__size_for_class[s->list - 256];12776+ } else {12777+ assert(s->list == 0);12778+ return s->len << stb__page_shift;12779+ }12780+}12781+12782+void stb_sfree(void *p)12783+{12784+ stb__span *s;12785+ if (p == NULL) return;12786+ s = stb__span_for_page[stb__page_number((stb_uint) p) - stb__firstpage];12787+ if (s->list >= 256) {12788+ stb__smemset(p, 0xfe, stb__size_for_class[s->list-256]);12789+ * (void **) p = s->first_free;12790+ s->first_free = p;12791+ if (--s->allocations == 0) {12792+ stb__spanlist_unlink(s);12793+ stb__free_span(s);12794+ }12795+ } else {12796+ assert(s->list == 0);12797+ stb__smemset(p, 0xfe, stb_ssize(p));12798+ stb__free_span(s);12799+ }12800+}12801+12802+void *stb_srealloc(void *p, size_t sz)12803+{12804+ size_t cur_size;12805+ if (p == NULL) return stb_smalloc(sz);12806+ if (sz == 0) { stb_sfree(p); return NULL; }12807+ cur_size = stb_ssize(p);12808+ if (sz > cur_size || sz <= (cur_size >> 1)) {12809+ void *q;12810+ if (sz > cur_size && sz < (cur_size << 1)) sz = cur_size << 1;12811+ q = stb_smalloc(sz); if (q == NULL) return NULL;12812+ memcpy(q, p, sz < cur_size ? sz : cur_size);12813+ stb_sfree(p);12814+ return q;12815+ }12816+ return p;12817+}12818+12819+void *stb_scalloc(size_t n, size_t sz)12820+{12821+ void *p;12822+ if (n == 0 || sz == 0) return NULL;12823+ if (stb_log2_ceil(n) + stb_log2_ceil(n) >= 32) return NULL;12824+ p = stb_smalloc(n*sz);12825+ if (p) memset(p, 0, n*sz);12826+ return p;12827+}12828+12829+char *stb_sstrdup(char *s)12830+{12831+ int n = strlen(s);12832+ char *p = (char *) stb_smalloc(n+1);12833+ if (p) stb_p_strcpy_s(p,n+1,s);12834+ return p;12835+}12836+#endif // STB_DEFINE12837+12838+12839+12840+//////////////////////////////////////////////////////////////////////////////12841+//12842+// Source code constants12843+//12844+// This is a trivial system to let you specify constants in source code,12845+// then while running you can change the constants.12846+//12847+// Note that you can't wrap the #defines, because we need to know their12848+// names. So we provide a pre-wrapped version without 'STB_' for convenience;12849+// to request it, #define STB_CONVENIENT_H, yielding:12850+// KI -- integer12851+// KU -- unsigned integer12852+// KF -- float12853+// KD -- double12854+// KS -- string constant12855+//12856+// Defaults to functioning in debug build, not in release builds.12857+// To force on, define STB_ALWAYS_H12858+12859+#ifdef STB_CONVENIENT_H12860+#define KI(x) STB_I(x)12861+#define KU(x) STB_UI(x)12862+#define KF(x) STB_F(x)12863+#define KD(x) STB_D(x)12864+#define KS(x) STB_S(x)12865+#endif12866+12867+STB_EXTERN void stb_source_path(char *str);12868+#ifdef STB_DEFINE12869+char *stb__source_path;12870+void stb_source_path(char *path)12871+{12872+ stb__source_path = path;12873+}12874+12875+char *stb__get_sourcefile_path(char *file)12876+{12877+ static char filebuf[512];12878+ if (stb__source_path) {12879+ stb_p_sprintf(filebuf stb_p_size(sizeof(filebuf)), "%s/%s", stb__source_path, file);12880+ if (stb_fexists(filebuf)) return filebuf;12881+ }12882+12883+ if (stb_fexists(file)) return file;12884+12885+ stb_p_sprintf(filebuf stb_p_size(sizeof(filebuf)), "../%s", file);12886+ if (!stb_fexists(filebuf)) return filebuf;12887+12888+ return file;12889+}12890+#endif12891+12892+#define STB_F(x) ((float) STB_H(x))12893+#define STB_UI(x) ((unsigned int) STB_I(x))12894+12895+#if !defined(STB_DEBUG) && !defined(STB_ALWAYS_H)12896+#define STB_D(x) ((double) (x))12897+#define STB_I(x) ((int) (x))12898+#define STB_S(x) ((char *) (x))12899+#else12900+#define STB_D(x) stb__double_constant(__FILE__, __LINE__-1, (x))12901+#define STB_I(x) stb__int_constant(__FILE__, __LINE__-1, (x))12902+#define STB_S(x) stb__string_constant(__FILE__, __LINE__-1, (x))12903+12904+STB_EXTERN double stb__double_constant(char *file, int line, double x);12905+STB_EXTERN int stb__int_constant(char *file, int line, int x);12906+STB_EXTERN char * stb__string_constant(char *file, int line, char *str);12907+12908+#ifdef STB_DEFINE12909+12910+enum12911+{12912+ STB__CTYPE_int,12913+ STB__CTYPE_uint,12914+ STB__CTYPE_float,12915+ STB__CTYPE_double,12916+ STB__CTYPE_string,12917+};12918+12919+typedef struct12920+{12921+ int line;12922+ int type;12923+ union {12924+ int ival;12925+ double dval;12926+ char *sval;12927+ };12928+} stb__Entry;12929+12930+typedef struct12931+{12932+ stb__Entry *entries;12933+ char *filename;12934+ time_t timestamp;12935+ char **file_data;12936+ int file_len;12937+ unsigned short *line_index;12938+} stb__FileEntry;12939+12940+static void stb__constant_parse(stb__FileEntry *f, int i)12941+{12942+ char *s;12943+ int n;12944+ if (!stb_arr_valid(f->entries, i)) return;12945+ n = f->entries[i].line;12946+ if (n >= f->file_len) return;12947+ s = f->file_data[n];12948+ switch (f->entries[i].type) {12949+ case STB__CTYPE_float:12950+ while (*s) {12951+ if (!strncmp(s, "STB_D(", 6)) { s+=6; goto matched_float; }12952+ if (!strncmp(s, "STB_F(", 6)) { s+=6; goto matched_float; }12953+ if (!strncmp(s, "KD(", 3)) { s+=3; goto matched_float; }12954+ if (!strncmp(s, "KF(", 3)) { s+=3; goto matched_float; }12955+ ++s;12956+ }12957+ break;12958+ matched_float:12959+ f->entries[i].dval = strtod(s, NULL);12960+ break;12961+ case STB__CTYPE_int:12962+ while (*s) {12963+ if (!strncmp(s, "STB_I(", 6)) { s+=6; goto matched_int; }12964+ if (!strncmp(s, "STB_UI(", 7)) { s+=7; goto matched_int; }12965+ if (!strncmp(s, "KI(", 3)) { s+=3; goto matched_int; }12966+ if (!strncmp(s, "KU(", 3)) { s+=3; goto matched_int; }12967+ ++s;12968+ }12969+ break;12970+ matched_int: {12971+ int neg=0;12972+ s = stb_skipwhite(s);12973+ while (*s == '-') { neg = !neg; s = stb_skipwhite(s+1); } // handle '- - 5', pointlessly12974+ if (s[0] == '0' && tolower(s[1]) == 'x')12975+ f->entries[i].ival = strtol(s, NULL, 16);12976+ else if (s[0] == '0')12977+ f->entries[i].ival = strtol(s, NULL, 8);12978+ else12979+ f->entries[i].ival = strtol(s, NULL, 10);12980+ if (neg) f->entries[i].ival = -f->entries[i].ival;12981+ break;12982+ }12983+ case STB__CTYPE_string:12984+ // @TODO12985+ break;12986+ }12987+}12988+12989+static stb_sdict *stb__constant_file_hash;12990+12991+stb__Entry *stb__constant_get_entry(char *filename, int line, int type)12992+{12993+ int i;12994+ stb__FileEntry *f;12995+ if (stb__constant_file_hash == NULL)12996+ stb__constant_file_hash = stb_sdict_new(STB_TRUE);12997+ f = (stb__FileEntry*) stb_sdict_get(stb__constant_file_hash, filename);12998+ if (f == NULL) {12999+ char *s = stb__get_sourcefile_path(filename);13000+ if (s == NULL || !stb_fexists(s)) return 0;13001+ f = (stb__FileEntry *) malloc(sizeof(*f));13002+ f->timestamp = stb_ftimestamp(s);13003+ f->file_data = stb_stringfile(s, &f->file_len);13004+ f->filename = stb_p_strdup(s); // cache the full path13005+ f->entries = NULL;13006+ f->line_index = 0;13007+ stb_arr_setlen(f->line_index, f->file_len);13008+ memset(f->line_index, 0xff, stb_arr_storage(f->line_index));13009+ } else {13010+ time_t t = stb_ftimestamp(f->filename);13011+ if (f->timestamp != t) {13012+ f->timestamp = t;13013+ free(f->file_data);13014+ f->file_data = stb_stringfile(f->filename, &f->file_len);13015+ stb_arr_setlen(f->line_index, f->file_len);13016+ for (i=0; i < stb_arr_len(f->entries); ++i)13017+ stb__constant_parse(f, i);13018+ }13019+ }13020+13021+ if (line >= f->file_len) return 0;13022+13023+ if (f->line_index[line] >= stb_arr_len(f->entries)) {13024+ // need a new entry13025+ int n = stb_arr_len(f->entries);13026+ stb__Entry e;13027+ e.line = line;13028+ if (line < f->file_len)13029+ f->line_index[line] = n;13030+ e.type = type;13031+ stb_arr_push(f->entries, e);13032+ stb__constant_parse(f, n);13033+ }13034+ return f->entries + f->line_index[line];13035+}13036+13037+double stb__double_constant(char *file, int line, double x)13038+{13039+ stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_float);13040+ if (!e) return x;13041+ return e->dval;13042+}13043+13044+int stb__int_constant(char *file, int line, int x)13045+{13046+ stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_int);13047+ if (!e) return x;13048+ return e->ival;13049+}13050+13051+char * stb__string_constant(char *file, int line, char *x)13052+{13053+ stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_string);13054+ if (!e) return x;13055+ return e->sval;13056+}13057+13058+#endif // STB_DEFINE13059+#endif // !STB_DEBUG && !STB_ALWAYS_H13060+13061+13062+#ifdef STB_STUA13063+#error "STUA is no longer supported"13064+//////////////////////////////////////////////////////////////////////////13065+//13066+// stua: little scripting language13067+//13068+// define STB_STUA to compile it13069+//13070+// see http://nothings.org/stb/stb_stua.html for documentation13071+//13072+// basic parsing model:13073+//13074+// lexical analysis13075+// use stb_lex() to parse tokens; keywords get their own tokens13076+//13077+// parsing:13078+// recursive descent parser. too much of a hassle to make an unambiguous13079+// LR(1) grammar, and one-pass generation is clumsier (recursive descent13080+// makes it easier to e.g. compile nested functions). on the other hand,13081+// dictionary syntax required hackery to get extra lookahead.13082+//13083+// codegen:13084+// output into an evaluation tree, using array indices as 'pointers'13085+//13086+// run:13087+// traverse the tree; support for 'break/continue/return' is tricky13088+//13089+// garbage collection:13090+// stu__mark and sweep; explicit stack with non-stu__compile_global_scope roots13091+13092+typedef stb_int32 stua_obj;13093+13094+typedef stb_idict stua_dict;13095+13096+STB_EXTERN void stua_run_script(char *s);13097+STB_EXTERN void stua_uninit(void);13098+13099+extern stua_obj stua_globals;13100+13101+STB_EXTERN double stua_number(stua_obj z);13102+13103+STB_EXTERN stua_obj stua_getnil(void);13104+STB_EXTERN stua_obj stua_getfalse(void);13105+STB_EXTERN stua_obj stua_gettrue(void);13106+STB_EXTERN stua_obj stua_string(char *z);13107+STB_EXTERN stua_obj stua_make_number(double d);13108+STB_EXTERN stua_obj stua_box(int type, void *data, int size);13109+13110+enum13111+{13112+ STUA_op_negate=129,13113+ STUA_op_shl, STUA_op_ge,13114+ STUA_op_shr, STUA_op_le,13115+ STUA_op_shru,13116+ STUA_op_last13117+};13118+13119+#define STUA_NO_VALUE 2 // equivalent to a tagged NULL13120+STB_EXTERN stua_obj (*stua_overload)(int op, stua_obj a, stua_obj b, stua_obj c);13121+13122+STB_EXTERN stua_obj stua_error(char *err, ...);13123+13124+STB_EXTERN stua_obj stua_pushroot(stua_obj o);13125+STB_EXTERN void stua_poproot ( void );13126+13127+13128+#ifdef STB_DEFINE13129+// INTERPRETER13130+13131+// 31-bit floating point implementation13132+// force the (1 << 30) bit (2nd highest bit) to be zero by re-biasing the exponent;13133+// then shift and set the bottom bit13134+13135+static stua_obj stu__floatp(float *f)13136+{13137+ unsigned int n = *(unsigned int *) f;13138+ unsigned int e = n & (0xff << 23);13139+13140+ assert(sizeof(int) == 4 && sizeof(float) == 4);13141+13142+ if (!e) // zero?13143+ n = n; // no change13144+ else if (e < (64 << 23)) // underflow of the packed encoding?13145+ n = (n & 0x80000000); // signed 013146+ else if (e > (190 << 23)) // overflow of the encoding? (or INF or NAN)13147+ n = (n & 0x80000000) + (127 << 23); // new INF encoding13148+ else13149+ n -= 0x20000000;13150+13151+ // now we need to shuffle the bits so that the spare bit is at the bottom13152+ assert((n & 0x40000000) == 0);13153+ return (n & 0x80000000) + (n << 1) + 1;13154+}13155+13156+static unsigned char stu__getfloat_addend[256];13157+static float stu__getfloat(stua_obj v)13158+{13159+ unsigned int n;13160+ unsigned int e = ((unsigned int) v) >> 24;13161+13162+ n = (int) v >> 1; // preserve high bit13163+ n += stu__getfloat_addend[e] << 24;13164+ return *(float *) &n;13165+}13166+13167+stua_obj stua_float(float f)13168+{13169+ return stu__floatp(&f);13170+}13171+13172+static void stu__float_init(void)13173+{13174+ int i;13175+ stu__getfloat_addend[0] = 0; // do nothing to biased exponent of 013176+ for (i=1; i < 127; ++i)13177+ stu__getfloat_addend[i] = 32; // undo the -0x2000000013178+ stu__getfloat_addend[127] = 64; // convert packed INF to INF (0x3f -> 0x7f)13179+13180+ for (i=0; i < 128; ++i) // for signed floats, remove the bit we just shifted down13181+ stu__getfloat_addend[128+i] = stu__getfloat_addend[i] - 64;13182+}13183+13184+// Tagged data type implementation13185+13186+ // TAGS:13187+#define stu__int_tag 0 // of 2 bits // 00 int13188+#define stu__float_tag 1 // of 1 bit // 01 float13189+#define stu__ptr_tag 2 // of 2 bits // 10 boxed13190+ // 11 float13191+13192+#define stu__tag(x) ((x) & 3)13193+#define stu__number(x) (stu__tag(x) != stu__ptr_tag)13194+#define stu__isint(x) (stu__tag(x) == stu__int_tag)13195+13196+#define stu__int(x) ((x) >> 2)13197+#define stu__float(x) (stu__getfloat(x))13198+13199+#define stu__makeint(v) ((v)*4+stu__int_tag)13200+13201+// boxed data, and tag support for boxed data13202+13203+enum13204+{13205+ STU___float = 1, STU___int = 2,13206+ STU___number = 3, STU___string = 4,13207+ STU___function = 5, STU___dict = 6,13208+ STU___boolean = 7, STU___error = 8,13209+};13210+13211+// boxed data13212+#define STU__BOX short type, stua_gc13213+typedef struct stu__box { STU__BOX; } stu__box;13214+13215+stu__box stu__nil = { 0, 1 };13216+stu__box stu__true = { STU___boolean, 1, };13217+stu__box stu__false = { STU___boolean, 1, };13218+13219+#define stu__makeptr(v) ((stua_obj) (v) + stu__ptr_tag)13220+13221+#define stua_nil stu__makeptr(&stu__nil)13222+#define stua_true stu__makeptr(&stu__true)13223+#define stua_false stu__makeptr(&stu__false)13224+13225+stua_obj stua_getnil(void) { return stua_nil; }13226+stua_obj stua_getfalse(void) { return stua_false; }13227+stua_obj stua_gettrue(void) { return stua_true; }13228+13229+#define stu__ptr(x) ((stu__box *) ((x) - stu__ptr_tag))13230+13231+#define stu__checkt(t,x) ((t) == STU___float ? ((x) & 1) == stu__float_tag : \13232+ (t) == STU___int ? stu__isint(x) : \13233+ (t) == STU___number ? stu__number(x) : \13234+ stu__tag(x) == stu__ptr_tag && stu__ptr(x)->type == (t))13235+13236+typedef struct13237+{13238+ STU__BOX;13239+ void *ptr;13240+} stu__wrapper;13241+13242+// implementation of a 'function' or function + closure13243+13244+typedef struct stu__func13245+{13246+ STU__BOX;13247+ stua_obj closure_source; // 0 - regular function; 4 - C function13248+ // if closure, pointer to source function13249+ union {13250+ stua_obj closure_data; // partial-application data13251+ void *store; // pointer to free that holds 'code'13252+ stua_obj (*func)(stua_dict *context);13253+ } f;13254+ // closure ends here13255+ short *code;13256+ int num_param;13257+ stua_obj *param; // list of parameter strings13258+} stu__func;13259+13260+// apply this to 'short *code' to get at data13261+#define stu__const(f) ((stua_obj *) (f))13262+13263+static void stu__free_func(stu__func *f)13264+{13265+ if (f->closure_source == 0) free(f->f.store);13266+ if ((stb_uint) f->closure_source <= 4) free(f->param);13267+ free(f);13268+}13269+13270+#define stu__pd(x) ((stua_dict *) stu__ptr(x))13271+#define stu__pw(x) ((stu__wrapper *) stu__ptr(x))13272+#define stu__pf(x) ((stu__func *) stu__ptr(x))13273+13274+13275+// garbage-collection13276+13277+13278+static stu__box ** stu__gc_ptrlist;13279+static stua_obj * stu__gc_root_stack;13280+13281+stua_obj stua_pushroot(stua_obj o) { stb_arr_push(stu__gc_root_stack, o); return o; }13282+void stua_poproot ( void ) { stb_arr_pop(stu__gc_root_stack); }13283+13284+static stb_sdict *stu__strings;13285+static void stu__mark(stua_obj z)13286+{13287+ int i;13288+ stu__box *p = stu__ptr(z);13289+ if (p->stua_gc == 1) return; // already marked13290+ assert(p->stua_gc == 0);13291+ p->stua_gc = 1;13292+ switch(p->type) {13293+ case STU___function: {13294+ stu__func *f = (stu__func *) p;13295+ if ((stb_uint) f->closure_source <= 4) {13296+ if (f->closure_source == 0) {13297+ for (i=1; i <= f->code[0]; ++i)13298+ if (!stu__number(((stua_obj *) f->code)[-i]))13299+ stu__mark(((stua_obj *) f->code)[-i]);13300+ }13301+ for (i=0; i < f->num_param; ++i)13302+ stu__mark(f->param[i]);13303+ } else {13304+ stu__mark(f->closure_source);13305+ stu__mark(f->f.closure_data);13306+ }13307+ break;13308+ }13309+ case STU___dict: {13310+ stua_dict *e = (stua_dict *) p;13311+ for (i=0; i < e->limit; ++i)13312+ if (e->table[i].k != STB_IEMPTY && e->table[i].k != STB_IDEL) {13313+ if (!stu__number(e->table[i].k)) stu__mark((int) e->table[i].k);13314+ if (!stu__number(e->table[i].v)) stu__mark((int) e->table[i].v);13315+ }13316+ break;13317+ }13318+ }13319+}13320+13321+static int stu__num_allocs, stu__size_allocs;13322+static stua_obj stu__flow_val = stua_nil; // used for break & return13323+13324+static void stua_gc(int force)13325+{13326+ int i;13327+ if (!force && stu__num_allocs == 0 && stu__size_allocs == 0) return;13328+ stu__num_allocs = stu__size_allocs = 0;13329+ //printf("[gc]\n");13330+13331+ // clear marks13332+ for (i=0; i < stb_arr_len(stu__gc_ptrlist); ++i)13333+ stu__gc_ptrlist[i]->stua_gc = 0;13334+13335+ // stu__mark everything reachable13336+ stu__nil.stua_gc = stu__true.stua_gc = stu__false.stua_gc = 1;13337+ stu__mark(stua_globals);13338+ if (!stu__number(stu__flow_val))13339+ stu__mark(stu__flow_val);13340+ for (i=0; i < stb_arr_len(stu__gc_root_stack); ++i)13341+ if (!stu__number(stu__gc_root_stack[i]))13342+ stu__mark(stu__gc_root_stack[i]);13343+13344+ // sweep unreachables13345+ for (i=0; i < stb_arr_len(stu__gc_ptrlist);) {13346+ stu__box *z = stu__gc_ptrlist[i];13347+ if (!z->stua_gc) {13348+ switch (z->type) {13349+ case STU___dict: stb_idict_destroy((stua_dict *) z); break;13350+ case STU___error: free(((stu__wrapper *) z)->ptr); break;13351+ case STU___string: stb_sdict_remove(stu__strings, (char*) ((stu__wrapper *) z)->ptr, NULL); free(z); break;13352+ case STU___function: stu__free_func((stu__func *) z); break;13353+ }13354+ // swap in the last item over this, and repeat13355+ z = stb_arr_pop(stu__gc_ptrlist);13356+ stu__gc_ptrlist[i] = z;13357+ } else13358+ ++i;13359+ }13360+}13361+13362+static void stu__consider_gc(stua_obj x)13363+{13364+ if (stu__size_allocs < 100000) return;13365+ if (stu__num_allocs < 10 && stu__size_allocs < 1000000) return;13366+ stb_arr_push(stu__gc_root_stack, x);13367+ stua_gc(0);13368+ stb_arr_pop(stu__gc_root_stack);13369+}13370+13371+static stua_obj stu__makeobj(int type, void *data, int size, int safe_to_gc)13372+{13373+ stua_obj x = stu__makeptr(data);13374+ ((stu__box *) data)->type = type;13375+ stb_arr_push(stu__gc_ptrlist, (stu__box *) data);13376+ stu__num_allocs += 1;13377+ stu__size_allocs += size;13378+ if (safe_to_gc) stu__consider_gc(x);13379+ return x;13380+}13381+13382+stua_obj stua_box(int type, void *data, int size)13383+{13384+ stu__wrapper *p = (stu__wrapper *) malloc(sizeof(*p));13385+ p->ptr = data;13386+ return stu__makeobj(type, p, size, 0);13387+}13388+13389+// a stu string can be directly compared for equality, because13390+// they go into a hash table13391+stua_obj stua_string(char *z)13392+{13393+ stu__wrapper *b = (stu__wrapper *) stb_sdict_get(stu__strings, z);13394+ if (b == NULL) {13395+ int o = stua_box(STU___string, NULL, strlen(z) + sizeof(*b));13396+ b = stu__pw(o);13397+ stb_sdict_add(stu__strings, z, b);13398+ stb_sdict_getkey(stu__strings, z, (char **) &b->ptr);13399+ }13400+ return stu__makeptr(b);13401+}13402+13403+// stb_obj dictionary is just an stb_idict13404+static void stu__set(stua_dict *d, stua_obj k, stua_obj v)13405+{ if (stb_idict_set(d, k, v)) stu__size_allocs += 8; }13406+13407+static stua_obj stu__get(stua_dict *d, stua_obj k, stua_obj res)13408+{13409+ stb_idict_get_flag(d, k, &res);13410+ return res;13411+}13412+13413+static stua_obj make_string(char *z, int len)13414+{13415+ stua_obj s;13416+ char temp[256], *q = (char *) stb_temp(temp, len+1), *p = q;13417+ while (len > 0) {13418+ if (*z == '\\') {13419+ if (z[1] == 'n') *p = '\n';13420+ else if (z[1] == 'r') *p = '\r';13421+ else if (z[1] == 't') *p = '\t';13422+ else *p = z[1];13423+ p += 1; z += 2; len -= 2;13424+ } else {13425+ *p++ = *z++; len -= 1;13426+ }13427+ }13428+ *p = 0;13429+ s = stua_string(q);13430+ stb_tempfree(temp, q);13431+ return s;13432+}13433+13434+enum token_names13435+{13436+ T__none=128,13437+ ST_shl = STUA_op_shl, ST_ge = STUA_op_ge,13438+ ST_shr = STUA_op_shr, ST_le = STUA_op_le,13439+ ST_shru = STUA_op_shru, STU__negate = STUA_op_negate,13440+ ST__reset_numbering = STUA_op_last,13441+ ST_white,13442+ ST_id, ST_float, ST_decimal, ST_hex, ST_char,ST_string, ST_number,13443+ // make sure the keywords come _AFTER_ ST_id, so stb_lex prefer them13444+ ST_if, ST_while, ST_for, ST_eq, ST_nil,13445+ ST_then, ST_do, ST_in, ST_ne, ST_true,13446+ ST_else, ST_break, ST_let, ST_and, ST_false,13447+ ST_elseif, ST_continue, ST_into, ST_or, ST_repeat,13448+ ST_end, ST_as, ST_return, ST_var, ST_func,13449+ ST_catch, ST__frame,13450+ ST__max_terminals,13451+13452+ STU__defaultparm, STU__seq,13453+};13454+13455+static stua_dict * stu__globaldict;13456+ stua_obj stua_globals;13457+13458+static enum13459+{13460+ FLOW_normal, FLOW_continue, FLOW_break, FLOW_return, FLOW_error,13461+} stu__flow;13462+13463+stua_obj stua_error(char *z, ...)13464+{13465+ stua_obj a;13466+ char temp[4096], *x;13467+ va_list v; va_start(v,z); vsprintf(temp, z, v); va_end(v);13468+ x = stb_p_strdup(temp);13469+ a = stua_box(STU___error, x, strlen(x));13470+ stu__flow = FLOW_error;13471+ stu__flow_val = a;13472+ return stua_nil;13473+}13474+13475+double stua_number(stua_obj z)13476+{13477+ return stu__tag(z) == stu__int_tag ? stu__int(z) : stu__float(z);13478+}13479+13480+stua_obj stua_make_number(double d)13481+{13482+ double e = floor(d);13483+ if (e == d && e < (1 << 29) && e >= -(1 << 29))13484+ return stu__makeint((int) e);13485+ else13486+ return stua_float((float) d);13487+}13488+13489+stua_obj (*stua_overload)(int op, stua_obj a, stua_obj b, stua_obj c) = NULL;13490+13491+static stua_obj stu__op(int op, stua_obj a, stua_obj b, stua_obj c)13492+{13493+ stua_obj r = STUA_NO_VALUE;13494+ if (op == '+') {13495+ if (stu__checkt(STU___string, a) && stu__checkt(STU___string, b)) {13496+ ;// @TODO: string concatenation13497+ } else if (stu__checkt(STU___function, a) && stu__checkt(STU___dict, b)) {13498+ stu__func *f = (stu__func *) malloc(12);13499+ assert(offsetof(stu__func, code)==12);13500+ f->closure_source = a;13501+ f->f.closure_data = b;13502+ return stu__makeobj(STU___function, f, 16, 1);13503+ }13504+ }13505+ if (stua_overload) r = stua_overload(op,a,b,c);13506+ if (stu__flow != FLOW_error && r == STUA_NO_VALUE)13507+ stua_error("Typecheck for operator %d", op), r=stua_nil;13508+ return r;13509+}13510+13511+#define STU__EVAL2(a,b) \13512+ a = stu__eval(stu__f[n+1]); if (stu__flow) break; stua_pushroot(a); \13513+ b = stu__eval(stu__f[n+2]); stua_poproot(); if (stu__flow) break;13514+13515+#define STU__FB(op) \13516+ STU__EVAL2(a,b) \13517+ if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag) \13518+ return ((a) op (b)); \13519+ if (stu__number(a) && stu__number(b)) \13520+ return stua_make_number(stua_number(a) op stua_number(b)); \13521+ return stu__op(stu__f[n], a,b, stua_nil)13522+13523+#define STU__F(op) \13524+ STU__EVAL2(a,b) \13525+ if (stu__number(a) && stu__number(b)) \13526+ return stua_make_number(stua_number(a) op stua_number(b)); \13527+ return stu__op(stu__f[n], a,b, stua_nil)13528+13529+#define STU__I(op) \13530+ STU__EVAL2(a,b) \13531+ if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag) \13532+ return stu__makeint(stu__int(a) op stu__int(b)); \13533+ return stu__op(stu__f[n], a,b, stua_nil)13534+13535+#define STU__C(op) \13536+ STU__EVAL2(a,b) \13537+ if (stu__number(a) && stu__number(b)) \13538+ return (stua_number(a) op stua_number(b)) ? stua_true : stua_false; \13539+ return stu__op(stu__f[n], a,b, stua_nil)13540+13541+#define STU__CE(op) \13542+ STU__EVAL2(a,b) \13543+ return (a op b) ? stua_true : stua_false13544+13545+static short *stu__f;13546+static stua_obj stu__f_obj;13547+static stua_dict *stu__c;13548+static stua_obj stu__funceval(stua_obj fo, stua_obj co);13549+13550+static int stu__cond(stua_obj x)13551+{13552+ if (stu__flow) return 0;13553+ if (!stu__checkt(STU___boolean, x))13554+ x = stu__op('!', x, stua_nil, stua_nil);13555+ if (x == stua_true ) return 1;13556+ if (x == stua_false) return 0;13557+ stu__flow = FLOW_error;13558+ return 0;13559+}13560+13561+// had to manually eliminate tailcall recursion for debugging complex stuff13562+#define TAILCALL(x) n = (x); goto top;13563+static stua_obj stu__eval(int n)13564+{13565+top:13566+ if (stu__flow >= FLOW_return) return stua_nil; // is this needed?13567+ if (n < 0) return stu__const(stu__f)[n];13568+ assert(n != 0 && n != 1);13569+ switch (stu__f[n]) {13570+ stua_obj a,b,c;13571+ case ST_catch: a = stu__eval(stu__f[n+1]);13572+ if (stu__flow == FLOW_error) { a=stu__flow_val; stu__flow = FLOW_normal; }13573+ return a;13574+ case ST_var: b = stu__eval(stu__f[n+2]); if (stu__flow) break;13575+ stu__set(stu__c, stu__const(stu__f)[stu__f[n+1]], b);13576+ return b;13577+ case STU__seq: stu__eval(stu__f[n+1]); if (stu__flow) break;13578+ TAILCALL(stu__f[n+2]);13579+ case ST_if: if (!stu__cond(stu__eval(stu__f[n+1]))) return stua_nil;13580+ TAILCALL(stu__f[n+2]);13581+ case ST_else: a = stu__cond(stu__eval(stu__f[n+1]));13582+ TAILCALL(stu__f[n + 2 + !a]);13583+ #define STU__HANDLE_BREAK \13584+ if (stu__flow >= FLOW_break) { \13585+ if (stu__flow == FLOW_break) { \13586+ a = stu__flow_val; \13587+ stu__flow = FLOW_normal; \13588+ stu__flow_val = stua_nil; \13589+ return a; \13590+ } \13591+ return stua_nil; \13592+ }13593+ case ST_as: stu__eval(stu__f[n+3]);13594+ STU__HANDLE_BREAK13595+ // fallthrough!13596+ case ST_while: a = stua_nil; stua_pushroot(a);13597+ while (stu__cond(stu__eval(stu__f[n+1]))) {13598+ stua_poproot();13599+ a = stu__eval(stu__f[n+2]);13600+ STU__HANDLE_BREAK13601+ stu__flow = FLOW_normal; // clear 'continue' flag13602+ stua_pushroot(a);13603+ if (stu__f[n+3]) stu__eval(stu__f[n+3]);13604+ STU__HANDLE_BREAK13605+ stu__flow = FLOW_normal; // clear 'continue' flag13606+ }13607+ stua_poproot();13608+ return a;13609+ case ST_break: stu__flow = FLOW_break; stu__flow_val = stu__eval(stu__f[n+1]); break;13610+ case ST_continue:stu__flow = FLOW_continue; break;13611+ case ST_return: stu__flow = FLOW_return; stu__flow_val = stu__eval(stu__f[n+1]); break;13612+ case ST__frame: return stu__f_obj;13613+ case '[': STU__EVAL2(a,b);13614+ if (stu__checkt(STU___dict, a))13615+ return stu__get(stu__pd(a), b, stua_nil);13616+ return stu__op(stu__f[n], a, b, stua_nil);13617+ case '=': a = stu__eval(stu__f[n+2]); if (stu__flow) break;13618+ n = stu__f[n+1];13619+ if (stu__f[n] == ST_id) {13620+ if (!stb_idict_update(stu__c, stu__const(stu__f)[stu__f[n+1]], a))13621+ if (!stb_idict_update(stu__globaldict, stu__const(stu__f)[stu__f[n+1]], a))13622+ return stua_error("Assignment to undefined variable");13623+ } else if (stu__f[n] == '[') {13624+ stua_pushroot(a);13625+ b = stu__eval(stu__f[n+1]); if (stu__flow) { stua_poproot(); break; }13626+ stua_pushroot(b);13627+ c = stu__eval(stu__f[n+2]); stua_poproot(); stua_poproot();13628+ if (stu__flow) break;13629+ if (!stu__checkt(STU___dict, b)) return stua_nil;13630+ stu__set(stu__pd(b), c, a);13631+ } else {13632+ return stu__op(stu__f[n], stu__eval(n), a, stua_nil);13633+ }13634+ return a;13635+ case STU__defaultparm:13636+ a = stu__eval(stu__f[n+2]);13637+ stu__flow = FLOW_normal;13638+ if (stb_idict_add(stu__c, stu__const(stu__f)[stu__f[n+1]], a))13639+ stu__size_allocs += 8;13640+ return stua_nil;13641+ case ST_id: a = stu__get(stu__c, stu__const(stu__f)[stu__f[n+1]], STUA_NO_VALUE); // try local variable13642+ return a != STUA_NO_VALUE // else try stu__compile_global_scope variable13643+ ? a : stu__get(stu__globaldict, stu__const(stu__f)[stu__f[n+1]], stua_nil);13644+ case STU__negate:a = stu__eval(stu__f[n+1]); if (stu__flow) break;13645+ return stu__isint(a) ? -a : stu__op(stu__f[n], a, stua_nil, stua_nil);13646+ case '~': a = stu__eval(stu__f[n+1]); if (stu__flow) break;13647+ return stu__isint(a) ? (~a)&~3 : stu__op(stu__f[n], a, stua_nil, stua_nil);13648+ case '!': a = stu__eval(stu__f[n+1]); if (stu__flow) break;13649+ a = stu__cond(a); if (stu__flow) break;13650+ return a ? stua_true : stua_false;13651+ case ST_eq: STU__CE(==); case ST_le: STU__C(<=); case '<': STU__C(<);13652+ case ST_ne: STU__CE(!=); case ST_ge: STU__C(>=); case '>': STU__C(>);13653+ case '+' : STU__FB(+); case '*': STU__F(*); case '&': STU__I(&); case ST_shl: STU__I(<<);13654+ case '-' : STU__FB(-); case '/': STU__F(/); case '|': STU__I(|); case ST_shr: STU__I(>>);13655+ case '%': STU__I(%); case '^': STU__I(^);13656+ case ST_shru: STU__EVAL2(a,b);13657+ if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag)13658+ return stu__makeint((unsigned) stu__int(a) >> stu__int(b));13659+ return stu__op(stu__f[n], a,b, stua_nil);13660+ case ST_and: a = stu__eval(stu__f[n+1]); b = stu__cond(a); if (stu__flow) break;13661+ return a ? stu__eval(stu__f[n+2]) : a;13662+ case ST_or : a = stu__eval(stu__f[n+1]); b = stu__cond(a); if (stu__flow) break;13663+ return a ? b : stu__eval(stu__f[n+2]);13664+ case'(':case':': STU__EVAL2(a,b);13665+ if (!stu__checkt(STU___function, a))13666+ return stu__op(stu__f[n], a,b, stua_nil);13667+ if (!stu__checkt(STU___dict, b))13668+ return stua_nil;13669+ if (stu__f[n] == ':')13670+ b = stu__makeobj(STU___dict, stb_idict_copy(stu__pd(b)), stb_idict_memory_usage(stu__pd(b)), 0);13671+ a = stu__funceval(a,b);13672+ return a;13673+ case '{' : {13674+ stua_dict *d;13675+ d = stb_idict_new_size(stu__f[n+1] > 40 ? 64 : 16);13676+ if (d == NULL)13677+ return stua_nil; // breakpoint fodder13678+ c = stu__makeobj(STU___dict, d, 32, 1);13679+ stua_pushroot(c);13680+ a = stu__f[n+1];13681+ for (b=0; b < a; ++b) {13682+ stua_obj x = stua_pushroot(stu__eval(stu__f[n+2 + b*2 + 0]));13683+ stua_obj y = stu__eval(stu__f[n+2 + b*2 + 1]);13684+ stua_poproot();13685+ if (stu__flow) { stua_poproot(); return stua_nil; }13686+ stu__set(d, x, y);13687+ }13688+ stua_poproot();13689+ return c;13690+ }13691+ default: if (stu__f[n] < 0) return stu__const(stu__f)[stu__f[n]];13692+ assert(0); /* NOTREACHED */ // internal error!13693+ }13694+ return stua_nil;13695+}13696+13697+int stb__stua_nesting;13698+static stua_obj stu__funceval(stua_obj fo, stua_obj co)13699+{13700+ stu__func *f = stu__pf(fo);13701+ stua_dict *context = stu__pd(co);13702+ int i,j;13703+ stua_obj p;13704+ short *tf = stu__f; // save previous function13705+ stua_dict *tc = stu__c;13706+13707+ if (stu__flow == FLOW_error) return stua_nil;13708+ assert(stu__flow == FLOW_normal);13709+13710+ stua_pushroot(fo);13711+ stua_pushroot(co);13712+ stu__consider_gc(stua_nil);13713+13714+ while ((stb_uint) f->closure_source > 4) {13715+ // add data from closure to context13716+ stua_dict *e = (stua_dict *) stu__pd(f->f.closure_data);13717+ for (i=0; i < e->limit; ++i)13718+ if (e->table[i].k != STB_IEMPTY && e->table[i].k != STB_IDEL)13719+ if (stb_idict_add(context, e->table[i].k, e->table[i].v))13720+ stu__size_allocs += 8;13721+ // use add so if it's already defined, we don't override it; that way13722+ // explicit parameters win over applied ones, and most recent applications13723+ // win over previous ones13724+ f = stu__pf(f->closure_source);13725+ }13726+13727+ for (j=0, i=0; i < f->num_param; ++i)13728+ // if it doesn't already exist, add it from the numbered parameters13729+ if (stb_idict_add(context, f->param[i], stu__get(context, stu__int(j), stua_nil)))13730+ ++j;13731+13732+ // @TODO: if (stu__get(context, stu__int(f->num_param+1)) != STUA_NO_VALUE) // error: too many parameters13733+ // @TODO: ditto too few parameters13734+13735+ if (f->closure_source == 4)13736+ p = f->f.func(context);13737+ else {13738+ stu__f = f->code, stu__c = context;13739+ stu__f_obj = co;13740+ ++stb__stua_nesting;13741+ if (stu__f[1])13742+ p = stu__eval(stu__f[1]);13743+ else13744+ p = stua_nil;13745+ --stb__stua_nesting;13746+ stu__f = tf, stu__c = tc; // restore previous function13747+ if (stu__flow == FLOW_return) {13748+ stu__flow = FLOW_normal;13749+ p = stu__flow_val;13750+ stu__flow_val = stua_nil;13751+ }13752+ }13753+13754+ stua_poproot();13755+ stua_poproot();13756+13757+ return p;13758+}13759+13760+// Parser13761+13762+static int stu__tok;13763+static stua_obj stu__tokval;13764+13765+static char *stu__curbuf, *stu__bufstart;13766+13767+static stb_matcher *stu__lex_matcher;13768+13769+static unsigned char stu__prec[ST__max_terminals], stu__end[ST__max_terminals];13770+13771+static void stu__nexttoken(void)13772+{13773+ int len;13774+13775+retry:13776+ stu__tok = stb_lex(stu__lex_matcher, stu__curbuf, &len);13777+ if (stu__tok == 0)13778+ return;13779+ switch(stu__tok) {13780+ case ST_white : stu__curbuf += len; goto retry;13781+ case T__none : stu__tok = *stu__curbuf; break;13782+ case ST_string: stu__tokval = make_string(stu__curbuf+1, len-2); break;13783+ case ST_id : stu__tokval = make_string(stu__curbuf, len); break;13784+ case ST_hex : stu__tokval = stu__makeint(strtol(stu__curbuf+2,NULL,16)); stu__tok = ST_number; break;13785+ case ST_decimal: stu__tokval = stu__makeint(strtol(stu__curbuf ,NULL,10)); stu__tok = ST_number; break;13786+ case ST_float : stu__tokval = stua_float((float) atof(stu__curbuf)) ; stu__tok = ST_number; break;13787+ case ST_char : stu__tokval = stu__curbuf[2] == '\\' ? stu__curbuf[3] : stu__curbuf[2];13788+ if (stu__curbuf[3] == 't') stu__tokval = '\t';13789+ if (stu__curbuf[3] == 'n') stu__tokval = '\n';13790+ if (stu__curbuf[3] == 'r') stu__tokval = '\r';13791+ stu__tokval = stu__makeint(stu__tokval);13792+ stu__tok = ST_number;13793+ break;13794+ }13795+ stu__curbuf += len;13796+}13797+13798+static struct { int stu__tok; char *regex; } stu__lexemes[] =13799+{13800+ ST_white , "([ \t\n\r]|/\\*(.|\n)*\\*/|//[^\r\n]*([\r\n]|$))+",13801+ ST_id , "[_a-zA-Z][_a-zA-Z0-9]*",13802+ ST_hex , "0x[0-9a-fA-F]+",13803+ ST_decimal, "[0-9]+[0-9]*",13804+ ST_float , "[0-9]+\\.?[0-9]*([eE][-+]?[0-9]+)?",13805+ ST_float , "\\.[0-9]+([eE][-+]?[0-9]+)?",13806+ ST_char , "c'(\\\\.|[^\\'])'",13807+ ST_string , "\"(\\\\.|[^\\\"\n\r])*\"",13808+ ST_string , "\'(\\\\.|[^\\\'\n\r])*\'",13809+13810+ #define stua_key4(a,b,c,d) ST_##a, #a, ST_##b, #b, ST_##c, #c, ST_##d, #d,13811+ stua_key4(if,then,else,elseif) stua_key4(while,do,for,in)13812+ stua_key4(func,var,let,break) stua_key4(nil,true,false,end)13813+ stua_key4(return,continue,as,repeat) stua_key4(_frame,catch,catch,catch)13814+13815+ ST_shl, "<<", ST_and, "&&", ST_eq, "==", ST_ge, ">=",13816+ ST_shr, ">>", ST_or , "||", ST_ne, "!=", ST_le, "<=",13817+ ST_shru,">>>", ST_into, "=>",13818+ T__none, ".",13819+};13820+13821+typedef struct13822+{13823+ stua_obj *data; // constants being compiled13824+ short *code; // code being compiled13825+ stua_dict *locals;13826+ short *non_local_refs;13827+} stu__comp_func;13828+13829+static stu__comp_func stu__pfunc;13830+static stu__comp_func *func_stack = NULL;13831+static void stu__push_func_comp(void)13832+{13833+ stb_arr_push(func_stack, stu__pfunc);13834+ stu__pfunc.data = NULL;13835+ stu__pfunc.code = NULL;13836+ stu__pfunc.locals = stb_idict_new_size(16);13837+ stu__pfunc.non_local_refs = NULL;13838+ stb_arr_push(stu__pfunc.code, 0); // number of data items13839+ stb_arr_push(stu__pfunc.code, 1); // starting execution address13840+}13841+13842+static void stu__pop_func_comp(void)13843+{13844+ stb_arr_free(stu__pfunc.code);13845+ stb_arr_free(stu__pfunc.data);13846+ stb_idict_destroy(stu__pfunc.locals);13847+ stb_arr_free(stu__pfunc.non_local_refs);13848+ stu__pfunc = stb_arr_pop(func_stack);13849+}13850+13851+// if an id is a reference to an outer lexical scope, this13852+// function returns the "name" of it, and updates the stack13853+// structures to make sure the names are propagated in.13854+static int stu__nonlocal_id(stua_obj var_obj)13855+{13856+ stua_obj dummy, var = var_obj;13857+ int i, n = stb_arr_len(func_stack), j,k;13858+ if (stb_idict_get_flag(stu__pfunc.locals, var, &dummy)) return 0;13859+ for (i=n-1; i > 1; --i) {13860+ if (stb_idict_get_flag(func_stack[i].locals, var, &dummy))13861+ break;13862+ }13863+ if (i <= 1) return 0; // stu__compile_global_scope13864+ j = i; // need to access variable from j'th frame13865+ for (i=0; i < stb_arr_len(stu__pfunc.non_local_refs); ++i)13866+ if (stu__pfunc.non_local_refs[i] == j) return j-n;13867+ stb_arr_push(stu__pfunc.non_local_refs, j-n);13868+ // now make sure all the parents propagate it down13869+ for (k=n-1; k > 1; --k) {13870+ if (j-k >= 0) return j-n; // comes direct from this parent13871+ for(i=0; i < stb_arr_len(func_stack[k].non_local_refs); ++i)13872+ if (func_stack[k].non_local_refs[i] == j-k)13873+ return j-n;13874+ stb_arr_push(func_stack[k].non_local_refs, j-k);13875+ }13876+ assert (k != 1);13877+13878+ return j-n;13879+}13880+13881+static int stu__off(void) { return stb_arr_len(stu__pfunc.code); }13882+static void stu__cc(int a)13883+{13884+ assert(a >= -2000 && a < 5000);13885+ stb_arr_push(stu__pfunc.code, a);13886+}13887+static int stu__cc1(int a) { stu__cc(a); return stu__off()-1; }13888+static int stu__cc2(int a, int b) { stu__cc(a); stu__cc(b); return stu__off()-2; }13889+static int stu__cc3(int a, int b, int c) {13890+ if (a == '=') assert(c != 0);13891+ stu__cc(a); stu__cc(b); stu__cc(c); return stu__off()-3; }13892+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; }13893+13894+static int stu__cdv(stua_obj p)13895+{13896+ int i;13897+ assert(p != STUA_NO_VALUE);13898+ for (i=0; i < stb_arr_len(stu__pfunc.data); ++i)13899+ if (stu__pfunc.data[i] == p)13900+ break;13901+ if (i == stb_arr_len(stu__pfunc.data))13902+ stb_arr_push(stu__pfunc.data, p);13903+ return ~i;13904+}13905+13906+static int stu__cdt(void)13907+{13908+ int z = stu__cdv(stu__tokval);13909+ stu__nexttoken();13910+ return z;13911+}13912+13913+static int stu__seq(int a, int b)13914+{13915+ return !a ? b : !b ? a : stu__cc3(STU__seq, a,b);13916+}13917+13918+static char stu__comp_err_str[1024];13919+static int stu__comp_err_line;13920+static int stu__err(char *str, ...)13921+{13922+ va_list v;13923+ char *s = stu__bufstart;13924+ stu__comp_err_line = 1;13925+ while (s < stu__curbuf) {13926+ if (s[0] == '\n' || s[0] == '\r') {13927+ if (s[0]+s[1] == '\n' + '\r') ++s;13928+ ++stu__comp_err_line;13929+ }13930+ ++s;13931+ }13932+ va_start(v, str);13933+ vsprintf(stu__comp_err_str, str, v);13934+ va_end(v);13935+ return 0;13936+}13937+13938+static int stu__accept(int p)13939+{13940+ if (stu__tok != p) return 0;13941+ stu__nexttoken();13942+ return 1;13943+}13944+13945+static int stu__demand(int p)13946+{13947+ if (stu__accept(p)) return 1;13948+ return stu__err("Didn't find expected stu__tok");13949+}13950+13951+static int stu__demandv(int p, stua_obj *val)13952+{13953+ if (stu__tok == p || p==0) {13954+ *val = stu__tokval;13955+ stu__nexttoken();13956+ return 1;13957+ } else13958+ return 0;13959+}13960+13961+static int stu__expr(int p);13962+int stu__nexpr(int p) { stu__nexttoken(); return stu__expr(p); }13963+static int stu__statements(int once, int as);13964+13965+static int stu__parse_if(void) // parse both ST_if and ST_elseif13966+{13967+ int b,c,a;13968+ a = stu__nexpr(1); if (!a) return 0;13969+ if (!stu__demand(ST_then)) return stu__err("expecting THEN");13970+ b = stu__statements(0,0); if (!b) return 0;13971+ if (b == 1) b = -1;13972+13973+ if (stu__tok == ST_elseif) {13974+ return stu__parse_if();13975+ } else if (stu__accept(ST_else)) {13976+ c = stu__statements(0,0); if (!c) return 0;13977+ if (!stu__demand(ST_end)) return stu__err("expecting END after else clause");13978+ return stu__cc4(ST_else, a, b, c);13979+ } else {13980+ if (!stu__demand(ST_end)) return stu__err("expecting END in if statement");13981+ return stu__cc3(ST_if, a, b);13982+ }13983+}13984+13985+int stu__varinit(int z, int in_globals)13986+{13987+ int a,b;13988+ stu__nexttoken();13989+ while (stu__demandv(ST_id, &b)) {13990+ if (!stb_idict_add(stu__pfunc.locals, b, 1))13991+ if (!in_globals) return stu__err("Redefined variable %s.", stu__pw(b)->ptr);13992+ if (stu__accept('=')) {13993+ a = stu__expr(1); if (!a) return 0;13994+ } else13995+ a = stu__cdv(stua_nil);13996+ z = stu__seq(z, stu__cc3(ST_var, stu__cdv(b), a));13997+ if (!stu__accept(',')) break;13998+ }13999+ return z;14000+}14001+14002+static int stu__compile_unary(int z, int outparm, int require_inparm)14003+{14004+ int op = stu__tok, a, b;14005+ stu__nexttoken();14006+ if (outparm) {14007+ if (require_inparm || (stu__tok && stu__tok != ST_end && stu__tok != ST_else && stu__tok != ST_elseif && stu__tok !=';')) {14008+ a = stu__expr(1); if (!a) return 0;14009+ } else14010+ a = stu__cdv(stua_nil);14011+ b = stu__cc2(op, a);14012+ } else14013+ b = stu__cc1(op);14014+ return stu__seq(z,b);14015+}14016+14017+static int stu__assign(void)14018+{14019+ int z;14020+ stu__accept(ST_let);14021+ z = stu__expr(1); if (!z) return 0;14022+ if (stu__accept('=')) {14023+ int y,p = (z >= 0 ? stu__pfunc.code[z] : 0);14024+ if (z < 0 || (p != ST_id && p != '[')) return stu__err("Invalid lvalue in assignment");14025+ y = stu__assign(); if (!y) return 0;14026+ z = stu__cc3('=', z, y);14027+ }14028+ return z;14029+}14030+14031+static int stu__statements(int once, int stop_while)14032+{14033+ int a,b, c, z=0;14034+ for(;;) {14035+ switch (stu__tok) {14036+ case ST_if : a = stu__parse_if(); if (!a) return 0;14037+ z = stu__seq(z, a);14038+ break;14039+ case ST_while : if (stop_while) return (z ? z:1);14040+ a = stu__nexpr(1); if (!a) return 0;14041+ if (stu__accept(ST_as)) c = stu__statements(0,0); else c = 0;14042+ if (!stu__demand(ST_do)) return stu__err("expecting DO");14043+ b = stu__statements(0,0); if (!b) return 0;14044+ if (!stu__demand(ST_end)) return stu__err("expecting END");14045+ if (b == 1) b = -1;14046+ z = stu__seq(z, stu__cc4(ST_while, a, b, c));14047+ break;14048+ case ST_repeat : stu__nexttoken();14049+ c = stu__statements(0,1); if (!c) return 0;14050+ if (!stu__demand(ST_while)) return stu__err("expecting WHILE");14051+ a = stu__expr(1); if (!a) return 0;14052+ if (!stu__demand(ST_do)) return stu__err("expecting DO");14053+ b = stu__statements(0,0); if (!b) return 0;14054+ if (!stu__demand(ST_end)) return stu__err("expecting END");14055+ if (b == 1) b = -1;14056+ z = stu__seq(z, stu__cc4(ST_as, a, b, c));14057+ break;14058+ case ST_catch : a = stu__nexpr(1); if (!a) return 0;14059+ z = stu__seq(z, stu__cc2(ST_catch, a));14060+ break;14061+ case ST_var : z = stu__varinit(z,0); break;14062+ case ST_return : z = stu__compile_unary(z,1,1); break;14063+ case ST_continue:z = stu__compile_unary(z,0,0); break;14064+ case ST_break : z = stu__compile_unary(z,1,0); break;14065+ case ST_into : if (z == 0 && !once) return stu__err("=> cannot be first statement in block");14066+ a = stu__nexpr(99);14067+ b = (a >= 0? stu__pfunc.code[a] : 0);14068+ if (a < 0 || (b != ST_id && b != '[')) return stu__err("Invalid lvalue on right side of =>");14069+ z = stu__cc3('=', a, z);14070+ break;14071+ default : if (stu__end[stu__tok]) return once ? 0 : (z ? z:1);14072+ a = stu__assign(); if (!a) return 0;14073+ stu__accept(';');14074+ if (stu__tok && !stu__end[stu__tok]) {14075+ if (a < 0)14076+ return stu__err("Constant has no effect");14077+ if (stu__pfunc.code[a] != '(' && stu__pfunc.code[a] != '=')14078+ return stu__err("Expression has no effect");14079+ }14080+ z = stu__seq(z, a);14081+ break;14082+ }14083+ if (!z) return 0;14084+ stu__accept(';');14085+ if (once && stu__tok != ST_into) return z;14086+ }14087+}14088+14089+static int stu__postexpr(int z, int p);14090+static int stu__dictdef(int end, int *count)14091+{14092+ int z,n=0,i,flags=0;14093+ short *dict=NULL;14094+ stu__nexttoken();14095+ while (stu__tok != end) {14096+ if (stu__tok == ST_id) {14097+ stua_obj id = stu__tokval;14098+ stu__nexttoken();14099+ if (stu__tok == '=') {14100+ flags |= 1;14101+ stb_arr_push(dict, stu__cdv(id));14102+ z = stu__nexpr(1); if (!z) return 0;14103+ } else {14104+ z = stu__cc2(ST_id, stu__cdv(id));14105+ z = stu__postexpr(z,1); if (!z) return 0;14106+ flags |= 2;14107+ stb_arr_push(dict, stu__cdv(stu__makeint(n++)));14108+ }14109+ } else {14110+ z = stu__expr(1); if (!z) return 0;14111+ flags |= 2;14112+ stb_arr_push(dict, stu__cdv(stu__makeint(n++)));14113+ }14114+ if (end != ')' && flags == 3) { z=stu__err("can't mix initialized and uninitialized defs"); goto done;}14115+ stb_arr_push(dict, z);14116+ if (!stu__accept(',')) break;14117+ }14118+ if (!stu__demand(end))14119+ return stu__err(end == ')' ? "Expecting ) at end of function call"14120+ : "Expecting } at end of dictionary definition");14121+ z = stu__cc2('{', stb_arr_len(dict)/2);14122+ for (i=0; i < stb_arr_len(dict); ++i)14123+ stu__cc(dict[i]);14124+ if (count) *count = n;14125+done:14126+ stb_arr_free(dict);14127+ return z;14128+}14129+14130+static int stu__comp_id(void)14131+{14132+ int z,d;14133+ d = stu__nonlocal_id(stu__tokval);14134+ if (d == 0)14135+ return z = stu__cc2(ST_id, stu__cdt());14136+ // access a non-local frame by naming it with the appropriate int14137+ assert(d < 0);14138+ z = stu__cdv(d); // relative frame # is the 'variable' in our local frame14139+ z = stu__cc2(ST_id, z); // now access that dictionary14140+ return stu__cc3('[', z, stu__cdt()); // now access the variable from that dir14141+}14142+14143+static stua_obj stu__funcdef(stua_obj *id, stua_obj *func);14144+static int stu__expr(int p)14145+{14146+ int z;14147+ // unary14148+ switch (stu__tok) {14149+ case ST_number: z = stu__cdt(); break;14150+ case ST_string: z = stu__cdt(); break; // @TODO - string concatenation like C14151+ case ST_id : z = stu__comp_id(); break;14152+ case ST__frame: z = stu__cc1(ST__frame); stu__nexttoken(); break;14153+ case ST_func : z = stu__funcdef(NULL,NULL); break;14154+ case ST_if : z = stu__parse_if(); break;14155+ case ST_nil : z = stu__cdv(stua_nil); stu__nexttoken(); break;14156+ case ST_true : z = stu__cdv(stua_true); stu__nexttoken(); break;14157+ case ST_false : z = stu__cdv(stua_false); stu__nexttoken(); break;14158+ case '-' : z = stu__nexpr(99); if (z) z=stu__cc2(STU__negate,z); else return z; break;14159+ case '!' : z = stu__nexpr(99); if (z) z=stu__cc2('!',z); else return z; break;14160+ case '~' : z = stu__nexpr(99); if (z) z=stu__cc2('~',z); else return z; break;14161+ case '{' : z = stu__dictdef('}', NULL); break;14162+ default : return stu__err("Unexpected token");14163+ case '(' : stu__nexttoken(); z = stu__statements(0,0); if (!stu__demand(')')) return stu__err("Expecting )");14164+ }14165+ return stu__postexpr(z,p);14166+}14167+14168+static int stu__postexpr(int z, int p)14169+{14170+ int q;14171+ // postfix14172+ while (stu__tok == '(' || stu__tok == '[' || stu__tok == '.') {14173+ if (stu__accept('.')) {14174+ // MUST be followed by a plain identifier! use [] for other stuff14175+ if (stu__tok != ST_id) return stu__err("Must follow . with plain name; try [] instead");14176+ z = stu__cc3('[', z, stu__cdv(stu__tokval));14177+ stu__nexttoken();14178+ } else if (stu__accept('[')) {14179+ while (stu__tok != ']') {14180+ int r = stu__expr(1); if (!r) return 0;14181+ z = stu__cc3('[', z, r);14182+ if (!stu__accept(',')) break;14183+ }14184+ if (!stu__demand(']')) return stu__err("Expecting ]");14185+ } else {14186+ int n, p = stu__dictdef(')', &n); if (!p) return 0;14187+ #if 0 // this is incorrect!14188+ if (z > 0 && stu__pfunc.code[z] == ST_id) {14189+ stua_obj q = stu__get(stu__globaldict, stu__pfunc.data[-stu__pfunc.code[z+1]-1], stua_nil);14190+ if (stu__checkt(STU___function, q))14191+ if ((stu__pf(q))->num_param != n)14192+ return stu__err("Incorrect number of parameters");14193+ }14194+ #endif14195+ z = stu__cc3('(', z, p);14196+ }14197+ }14198+ // binop - this implementation taken from lcc14199+ for (q=stu__prec[stu__tok]; q >= p; --q) {14200+ while (stu__prec[stu__tok] == q) {14201+ int o = stu__tok, y = stu__nexpr(p+1); if (!y) return 0;14202+ z = stu__cc3(o,z,y);14203+ }14204+ }14205+ return z;14206+}14207+14208+static stua_obj stu__finish_func(stua_obj *param, int start)14209+{14210+ int n, size;14211+ stu__func *f = (stu__func *) malloc(sizeof(*f));14212+ f->closure_source = 0;14213+ f->num_param = stb_arr_len(param);14214+ f->param = (int *) stb_copy(param, f->num_param * sizeof(*f->param));14215+ size = stb_arr_storage(stu__pfunc.code) + stb_arr_storage(stu__pfunc.data) + sizeof(*f) + 8;14216+ f->f.store = malloc(stb_arr_storage(stu__pfunc.code) + stb_arr_storage(stu__pfunc.data));14217+ f->code = (short *) ((char *) f->f.store + stb_arr_storage(stu__pfunc.data));14218+ memcpy(f->code, stu__pfunc.code, stb_arr_storage(stu__pfunc.code));14219+ f->code[1] = start;14220+ f->code[0] = stb_arr_len(stu__pfunc.data);14221+ for (n=0; n < f->code[0]; ++n)14222+ ((stua_obj *) f->code)[-1-n] = stu__pfunc.data[n];14223+ return stu__makeobj(STU___function, f, size, 0);14224+}14225+14226+static int stu__funcdef(stua_obj *id, stua_obj *result)14227+{14228+ int n,z=0,i,q;14229+ stua_obj *param = NULL;14230+ short *nonlocal;14231+ stua_obj v,f=stua_nil;14232+ assert(stu__tok == ST_func);14233+ stu__nexttoken();14234+ if (id) {14235+ if (!stu__demandv(ST_id, id)) return stu__err("Expecting function name");14236+ } else14237+ stu__accept(ST_id);14238+ if (!stu__demand('(')) return stu__err("Expecting ( for function parameter");14239+ stu__push_func_comp();14240+ while (stu__tok != ')') {14241+ if (!stu__demandv(ST_id, &v)) { z=stu__err("Expecting parameter name"); goto done; }14242+ stb_idict_add(stu__pfunc.locals, v, 1);14243+ if (stu__tok == '=') {14244+ n = stu__nexpr(1); if (!n) { z=0; goto done; }14245+ z = stu__seq(z, stu__cc3(STU__defaultparm, stu__cdv(v), n));14246+ } else14247+ stb_arr_push(param, v);14248+ if (!stu__accept(',')) break;14249+ }14250+ if (!stu__demand(')')) { z=stu__err("Expecting ) at end of parameter list"); goto done; }14251+ n = stu__statements(0,0); if (!n) { z=0; goto done; }14252+ if (!stu__demand(ST_end)) { z=stu__err("Expecting END at end of function"); goto done; }14253+ if (n == 1) n = 0;14254+ n = stu__seq(z,n);14255+ f = stu__finish_func(param, n);14256+ if (result) { *result = f; z=1; stu__pop_func_comp(); }14257+ else {14258+ nonlocal = stu__pfunc.non_local_refs;14259+ stu__pfunc.non_local_refs = NULL;14260+ stu__pop_func_comp();14261+ z = stu__cdv(f);14262+ if (nonlocal) { // build a closure with references to the needed frames14263+ short *initcode = NULL;14264+ for (i=0; i < stb_arr_len(nonlocal); ++i) {14265+ int k = nonlocal[i], p;14266+ stb_arr_push(initcode, stu__cdv(k));14267+ if (k == -1) p = stu__cc1(ST__frame);14268+ else { p = stu__cdv(stu__makeint(k+1)); p = stu__cc2(ST_id, p); }14269+ stb_arr_push(initcode, p);14270+ }14271+ q = stu__cc2('{', stb_arr_len(nonlocal));14272+ for (i=0; i < stb_arr_len(initcode); ++i)14273+ stu__cc(initcode[i]);14274+ z = stu__cc3('+', z, q);14275+ stb_arr_free(initcode);14276+ }14277+ stb_arr_free(nonlocal);14278+ }14279+done:14280+ stb_arr_free(param);14281+ if (!z) stu__pop_func_comp();14282+ return z;14283+}14284+14285+static int stu__compile_global_scope(void)14286+{14287+ stua_obj o;14288+ int z=0;14289+14290+ stu__push_func_comp();14291+ while (stu__tok != 0) {14292+ if (stu__tok == ST_func) {14293+ stua_obj id, f;14294+ if (!stu__funcdef(&id,&f))14295+ goto error;14296+ stu__set(stu__globaldict, id, f);14297+ } else if (stu__tok == ST_var) {14298+ z = stu__varinit(z,1); if (!z) goto error;14299+ } else {14300+ int y = stu__statements(1,0); if (!y) goto error;14301+ z = stu__seq(z,y);14302+ }14303+ stu__accept(';');14304+ }14305+ o = stu__finish_func(NULL, z);14306+ stu__pop_func_comp();14307+14308+ o = stu__funceval(o, stua_globals); // initialize stu__globaldict14309+ if (stu__flow == FLOW_error)14310+ printf("Error: %s\n", ((stu__wrapper *) stu__ptr(stu__flow_val))->ptr);14311+ return 1;14312+error:14313+ stu__pop_func_comp();14314+ return 0;14315+}14316+14317+stua_obj stu__myprint(stua_dict *context)14318+{14319+ stua_obj x = stu__get(context, stua_string("x"), stua_nil);14320+ if ((x & 1) == stu__float_tag) printf("%f", stu__getfloat(x));14321+ else if (stu__tag(x) == stu__int_tag) printf("%d", stu__int(x));14322+ else {14323+ stu__wrapper *s = stu__pw(x);14324+ if (s->type == STU___string || s->type == STU___error)14325+ printf("%s", s->ptr);14326+ else if (s->type == STU___dict) printf("{{dictionary}}");14327+ else if (s->type == STU___function) printf("[[function]]");14328+ else14329+ printf("[[ERROR:%s]]", s->ptr);14330+ }14331+ return x;14332+}14333+14334+void stua_init(void)14335+{14336+ if (!stu__globaldict) {14337+ int i;14338+ stua_obj s;14339+ stu__func *f;14340+14341+ stu__prec[ST_and] = stu__prec[ST_or] = 1;14342+ stu__prec[ST_eq ] = stu__prec[ST_ne] = stu__prec[ST_le] =14343+ stu__prec[ST_ge] = stu__prec['>' ] = stu__prec['<'] = 2;14344+ stu__prec[':'] = 3;14345+ stu__prec['&'] = stu__prec['|'] = stu__prec['^'] = 4;14346+ stu__prec['+'] = stu__prec['-'] = 5;14347+ stu__prec['*'] = stu__prec['/'] = stu__prec['%'] =14348+ stu__prec[ST_shl]= stu__prec[ST_shr]= stu__prec[ST_shru]= 6;14349+14350+ stu__end[')'] = stu__end[ST_end] = stu__end[ST_else] = 1;14351+ stu__end[ST_do] = stu__end[ST_elseif] = 1;14352+14353+ stu__float_init();14354+ stu__lex_matcher = stb_lex_matcher();14355+ for (i=0; i < sizeof(stu__lexemes)/sizeof(stu__lexemes[0]); ++i)14356+ stb_lex_item(stu__lex_matcher, stu__lexemes[i].regex, stu__lexemes[i].stu__tok);14357+14358+ stu__globaldict = stb_idict_new_size(64);14359+ stua_globals = stu__makeobj(STU___dict, stu__globaldict, 0,0);14360+ stu__strings = stb_sdict_new(0);14361+14362+ stu__curbuf = stu__bufstart = "func _print(x) end\n"14363+ "func print()\n var x=0 while _frame[x] != nil as x=x+1 do _print(_frame[x]) end end\n";14364+ stu__nexttoken();14365+ if (!stu__compile_global_scope())14366+ printf("Compile error in line %d: %s\n", stu__comp_err_line, stu__comp_err_str);14367+14368+ s = stu__get(stu__globaldict, stua_string("_print"), stua_nil);14369+ if (stu__tag(s) == stu__ptr_tag && stu__ptr(s)->type == STU___function) {14370+ f = stu__pf(s);14371+ free(f->f.store);14372+ f->closure_source = 4;14373+ f->f.func = stu__myprint;14374+ f->code = NULL;14375+ }14376+ }14377+}14378+14379+void stua_uninit(void)14380+{14381+ if (stu__globaldict) {14382+ stb_idict_remove_all(stu__globaldict);14383+ stb_arr_setlen(stu__gc_root_stack, 0);14384+ stua_gc(1);14385+ stb_idict_destroy(stu__globaldict);14386+ stb_sdict_delete(stu__strings);14387+ stb_matcher_free(stu__lex_matcher);14388+ stb_arr_free(stu__gc_ptrlist);14389+ stb_arr_free(func_stack);14390+ stb_arr_free(stu__gc_root_stack);14391+ stu__globaldict = NULL;14392+ }14393+}14394+14395+void stua_run_script(char *s)14396+{14397+ stua_init();14398+14399+ stu__curbuf = stu__bufstart = s;14400+ stu__nexttoken();14401+14402+ stu__flow = FLOW_normal;14403+14404+ if (!stu__compile_global_scope())14405+ printf("Compile error in line %d: %s\n", stu__comp_err_line, stu__comp_err_str);14406+ stua_gc(1);14407+}14408+#endif // STB_DEFINE14409+#endif // STB_STUA14410+14411+#undef STB_EXTERN14412+#endif // STB_INCLUDE_STB_H14413+14414+/*14415+------------------------------------------------------------------------------14416+This software is available under 2 licenses -- choose whichever you prefer.14417+------------------------------------------------------------------------------14418+ALTERNATIVE A - MIT License14419+Copyright (c) 2017 Sean Barrett14420+Permission is hereby granted, free of charge, to any person obtaining a copy of14421+this software and associated documentation files (the "Software"), to deal in14422+the Software without restriction, including without limitation the rights to14423+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies14424+of the Software, and to permit persons to whom the Software is furnished to do14425+so, subject to the following conditions:14426+The above copyright notice and this permission notice shall be included in all14427+copies or substantial portions of the Software.14428+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14429+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,14430+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE14431+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER14432+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,14433+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE14434+SOFTWARE.14435+------------------------------------------------------------------------------14436+ALTERNATIVE B - Public Domain (www.unlicense.org)14437+This is free and unencumbered software released into the public domain.14438+Anyone is free to copy, modify, publish, use, compile, sell, or distribute this14439+software, either in source code form or as a compiled binary, for any purpose,14440+commercial or non-commercial, and by any means.14441+In jurisdictions that recognize copyright laws, the author or authors of this14442+software dedicate any and all copyright interest in the software to the public14443+domain. We make this dedication for the benefit of the public at large and to14444+the detriment of our heirs and successors. We intend this dedication to be an14445+overt act of relinquishment in perpetuity of all present and future rights to14446+this software under copyright law.14447+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14448+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,14449+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE14450+AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN14451+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION14452+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.14453+------------------------------------------------------------------------------14454+*/modified:docs/why_public_domain.md+6 added-5 removed
70 unmodified lines71 causes worries for lawyers, even if their programmers72 aren't modifying it.73 74 Any license which requires crediting in documentation75-adds friction which can add up. Valve used to have76-a page with a list of all of these on their web site,77-and it was insane, and obviously nobody ever looked78-at it so why would you care whether your credit appeared79-there?75+adds friction which can add up. Valve has a huge list76+(http://nothings.org/remote/ThirdPartyLegalNotices_steam_2019.html)77+of all of these included in each game they ship,78+and it's insane, and obviously nobody ever looks79+at it so why would you care whether your credit80+appeared there?81 82 Permissive licenses like zlib and BSD license are83 perfectly reasonable, but they are very wordy and84 have only two benefits over public domain: legally-mandated33 unmodified linesmodified:tests/test_vorbis.cnot shown
Its text is not shown, modified.
modified:README.md+21 added-3 removed
18 unmodified lines19 <a name="stb_libs"></a>20 21 library | lastest version | category | LoC | description22 --------------------- | ---- | -------- | --- | --------------------------------23-**[stb_vorbis.c](stb_vorbis.c)** | 1.21 | audio | 5569 | decode ogg vorbis files from file/memory to float/16-bit signed output24-**[stb_image.h](stb_image.h)** | 2.26 | graphics | 7762 | image loading/decoding from file/memory: JPG, PNG, TGA, BMP, PSD, GIF, HDR, PIC23+**[stb_vorbis.c](stb_vorbis.c)** | 1.20 | audio | 5563 | decode ogg vorbis files from file/memory to float/16-bit signed output24+**[stb_image.h](stb_image.h)** | 2.26 | graphics | 7762 | image loading/decoding from file/memory: JPG, PNG, TGA, BMP, PSD, GIF, HDR, PIC, PNM25 **[stb_truetype.h](stb_truetype.h)** | 1.24 | graphics | 5011 | parse, decode, and rasterize characters from truetype fonts26-**[stb_image_write.h](stb_image_write.h)** | 1.15 | graphics | 1690 | image writing to disk: PNG, TGA, BMP26+**[stb_image_write.h](stb_image_write.h)** | 1.15 | graphics | 1690 | image writing to disk: PNG, TGA, BMP, JPG, HDR27 **[stb_image_resize.h](stb_image_resize.h)** | 0.96 | graphics | 2631 | resize images larger/smaller with good quality28 **[stb_rect_pack.h](stb_rect_pack.h)** | 1.00 | graphics | 628 | simple 2D rectangle packer with decent quality29 **[stb_ds.h](stb_ds.h)** | 0.66 | utility | 1893 | typesafe dynamic array and hash tables for C, will compile in C++30 **[stb_sprintf.h](stb_sprintf.h)** | 1.09 | utility | 1879 | fast sprintf, snprintf for C/C++17 unmodified lines48 49 FAQ50 ---51 52+#### How do I use these libraries?53+54+The idea behind single-header file libraries is that they're easy to distribute and deploy55+because all the code is contained in a single file. By default, the .h files in here act as56+their own header files, i.e. they declare the functions contained in the file but don't57+actually result in any code getting compiled.58+59+So in addition, you should select _exactly one_ C/C++ source file that actually instantiates60+the code, preferably a file you're not editing frequently. This file should define a61+specific macro (this is documented per-library) to actually enable the function definitions.62+For example, to use stb_image, you should have exactly one C/C++ file that doesn't63+include stb_image.h regularly, but instead does64+65+ #define STB_IMAGE_IMPLEMENTATION66+ #include "stb_image.h"67+68+The right macro to define is pointed out right at the top of each of these libraries.69+70 #### What's the license?71 72 These libraries are in the public domain. You can do anything you73 want with them. You have no legal obligation109 unmodified linesmodified:stb_dxt.h+149 added-184 removed
1-// stb_dxt.h - v1.10 - DXT1/DXT5 compressor - public domain1+// stb_dxt.h - v1.11 - DXT1/DXT5 compressor - public domain2 // original by fabian "ryg" giesen - ported to C by stb3 // use '#define STB_DXT_IMPLEMENTATION' before including to create the implementation4 //5 // USAGE:3 unmodified lines9 // must supply some constant alpha in the alpha channel).10 // You can turn on dithering and "high quality" using mode.11 //12 // version history:13+// v1.11 - (ryg) avoid racy global init, better single-color tables, remove dither14 // v1.10 - (i.c) various small quality improvements15 // v1.09 - (stb) update documentation re: surprising alpha channel requirement16 // v1.08 - (stb) fix bug in dxt-with-alpha block17 // v1.07 - (stb) bc4; allow not using libc; add STB_DXT_STATIC11 unmodified lines29 // Rich Geldreich (more accurate index selection)30 // Kevin Schmidt (#defines for "freestanding" compilation)31 // github:ppiastucki (BC4 support)32 // Ignacio Castano - improve DXT endpoint quantization33+// Alan Hickman - static table initialization34 //35 // LICENSE36 //37 // See end of file for license information.12 unmodified lines50 #endif51 52 // compression mode (bitflags)53 #define STB_DXT_NORMAL 052-#define STB_DXT_DITHER 1 // use dithering. dubious win. never use for normal maps and the like!54+#define STB_DXT_DITHER 1 // use dithering. was always dubious, now deprecated. does nothing!55 #define STB_DXT_HIGHQUAL 2 // high quality mode, does two refinement steps instead of 1. ~30-40% slower.56 57 STBDDEF void stb_compress_dxt_block(unsigned char *dest, const unsigned char *src_rgba_four_bytes_per_pixel, int alpha, int mode);58 STBDDEF void stb_compress_bc4_block(unsigned char *dest, const unsigned char *src_r_one_byte_per_pixel);23 unmodified lines82 // #define STB_DXT_USE_ROUNDING_BIAS83 84 #include <stdlib.h>85 84-#if !defined(STBD_ABS) || !defined(STBI_FABS)86+#if !defined(STBD_FABS)87 #include <math.h>88 #endif89 88-#ifndef STBD_ABS89-#define STBD_ABS(i) abs(i)90-#endif91-90 #ifndef STBD_FABS91 #define STBD_FABS(x) fabs(x)92 #endif93 96-#ifndef STBD_MEMSET97-#include <string.h>98-#define STBD_MEMSET memset99-#endif94+static const unsigned char stb__OMatch5[256][2] = {95+ { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 1, 1 }, { 1, 1 }, { 1, 1 },96+ { 1, 1 }, { 1, 1 }, { 1, 1 }, { 1, 1 }, { 1, 1 }, { 2, 2 }, { 2, 2 }, { 2, 2 },97+ { 2, 2 }, { 2, 2 }, { 2, 2 }, { 2, 2 }, { 2, 2 }, { 3, 3 }, { 3, 3 }, { 3, 3 },98+ { 3, 3 }, { 3, 3 }, { 3, 3 }, { 3, 3 }, { 3, 3 }, { 4, 4 }, { 4, 4 }, { 4, 4 },99+ { 4, 4 }, { 4, 4 }, { 4, 4 }, { 4, 4 }, { 4, 4 }, { 4, 4 }, { 5, 5 }, { 5, 5 },100+ { 5, 5 }, { 5, 5 }, { 5, 5 }, { 5, 5 }, { 5, 5 }, { 5, 5 }, { 6, 6 }, { 6, 6 },101+ { 6, 6 }, { 6, 6 }, { 6, 6 }, { 6, 6 }, { 6, 6 }, { 6, 6 }, { 7, 7 }, { 7, 7 },102+ { 7, 7 }, { 7, 7 }, { 7, 7 }, { 7, 7 }, { 7, 7 }, { 7, 7 }, { 8, 8 }, { 8, 8 },103+ { 8, 8 }, { 8, 8 }, { 8, 8 }, { 8, 8 }, { 8, 8 }, { 8, 8 }, { 8, 8 }, { 9, 9 },104+ { 9, 9 }, { 9, 9 }, { 9, 9 }, { 9, 9 }, { 9, 9 }, { 9, 9 }, { 9, 9 }, { 10, 10 },105+ { 10, 10 }, { 10, 10 }, { 10, 10 }, { 10, 10 }, { 10, 10 }, { 10, 10 }, { 10, 10 }, { 11, 11 },106+ { 11, 11 }, { 11, 11 }, { 11, 11 }, { 11, 11 }, { 11, 11 }, { 11, 11 }, { 11, 11 }, { 12, 12 },107+ { 12, 12 }, { 12, 12 }, { 12, 12 }, { 12, 12 }, { 12, 12 }, { 12, 12 }, { 12, 12 }, { 12, 12 },108+ { 13, 13 }, { 13, 13 }, { 13, 13 }, { 13, 13 }, { 13, 13 }, { 13, 13 }, { 13, 13 }, { 13, 13 },109+ { 14, 14 }, { 14, 14 }, { 14, 14 }, { 14, 14 }, { 14, 14 }, { 14, 14 }, { 14, 14 }, { 14, 14 },110+ { 15, 15 }, { 15, 15 }, { 15, 15 }, { 15, 15 }, { 15, 15 }, { 15, 15 }, { 15, 15 }, { 15, 15 },111+ { 16, 16 }, { 16, 16 }, { 16, 16 }, { 16, 16 }, { 16, 16 }, { 16, 16 }, { 16, 16 }, { 16, 16 },112+ { 16, 16 }, { 17, 17 }, { 17, 17 }, { 17, 17 }, { 17, 17 }, { 17, 17 }, { 17, 17 }, { 17, 17 },113+ { 17, 17 }, { 18, 18 }, { 18, 18 }, { 18, 18 }, { 18, 18 }, { 18, 18 }, { 18, 18 }, { 18, 18 },114+ { 18, 18 }, { 19, 19 }, { 19, 19 }, { 19, 19 }, { 19, 19 }, { 19, 19 }, { 19, 19 }, { 19, 19 },115+ { 19, 19 }, { 20, 20 }, { 20, 20 }, { 20, 20 }, { 20, 20 }, { 20, 20 }, { 20, 20 }, { 20, 20 },116+ { 20, 20 }, { 20, 20 }, { 21, 21 }, { 21, 21 }, { 21, 21 }, { 21, 21 }, { 21, 21 }, { 21, 21 },117+ { 21, 21 }, { 21, 21 }, { 22, 22 }, { 22, 22 }, { 22, 22 }, { 22, 22 }, { 22, 22 }, { 22, 22 },118+ { 22, 22 }, { 22, 22 }, { 23, 23 }, { 23, 23 }, { 23, 23 }, { 23, 23 }, { 23, 23 }, { 23, 23 },119+ { 23, 23 }, { 23, 23 }, { 24, 24 }, { 24, 24 }, { 24, 24 }, { 24, 24 }, { 24, 24 }, { 24, 24 },120+ { 24, 24 }, { 24, 24 }, { 24, 24 }, { 25, 25 }, { 25, 25 }, { 25, 25 }, { 25, 25 }, { 25, 25 },121+ { 25, 25 }, { 25, 25 }, { 25, 25 }, { 26, 26 }, { 26, 26 }, { 26, 26 }, { 26, 26 }, { 26, 26 },122+ { 26, 26 }, { 26, 26 }, { 26, 26 }, { 27, 27 }, { 27, 27 }, { 27, 27 }, { 27, 27 }, { 27, 27 },123+ { 27, 27 }, { 27, 27 }, { 27, 27 }, { 28, 28 }, { 28, 28 }, { 28, 28 }, { 28, 28 }, { 28, 28 },124+ { 28, 28 }, { 28, 28 }, { 28, 28 }, { 28, 28 }, { 29, 29 }, { 29, 29 }, { 29, 29 }, { 29, 29 },125+ { 29, 29 }, { 29, 29 }, { 29, 29 }, { 29, 29 }, { 30, 30 }, { 30, 30 }, { 30, 30 }, { 30, 30 },126+ { 30, 30 }, { 30, 30 }, { 30, 30 }, { 30, 30 }, { 31, 31 }, { 31, 31 }, { 31, 31 }, { 31, 31 },127+};128+static const unsigned char stb__OMatch6[256][2] = {129+ { 0, 0 }, { 0, 0 }, { 0, 0 }, { 1, 1 }, { 1, 1 }, { 1, 1 }, { 1, 1 }, { 2, 2 },130+ { 2, 2 }, { 2, 2 }, { 2, 2 }, { 3, 3 }, { 3, 3 }, { 3, 3 }, { 3, 3 }, { 4, 4 },131+ { 4, 4 }, { 4, 4 }, { 4, 4 }, { 5, 5 }, { 5, 5 }, { 5, 5 }, { 5, 5 }, { 6, 6 },132+ { 6, 6 }, { 6, 6 }, { 6, 6 }, { 7, 7 }, { 7, 7 }, { 7, 7 }, { 7, 7 }, { 8, 8 },133+ { 8, 8 }, { 8, 8 }, { 8, 8 }, { 9, 9 }, { 9, 9 }, { 9, 9 }, { 9, 9 }, { 10, 10 },134+ { 10, 10 }, { 10, 10 }, { 10, 10 }, { 11, 11 }, { 11, 11 }, { 11, 11 }, { 11, 11 }, { 12, 12 },135+ { 12, 12 }, { 12, 12 }, { 12, 12 }, { 13, 13 }, { 13, 13 }, { 13, 13 }, { 13, 13 }, { 14, 14 },136+ { 14, 14 }, { 14, 14 }, { 14, 14 }, { 15, 15 }, { 15, 15 }, { 15, 15 }, { 15, 15 }, { 16, 16 },137+ { 16, 16 }, { 16, 16 }, { 16, 16 }, { 16, 16 }, { 17, 17 }, { 17, 17 }, { 17, 17 }, { 17, 17 },138+ { 18, 18 }, { 18, 18 }, { 18, 18 }, { 18, 18 }, { 19, 19 }, { 19, 19 }, { 19, 19 }, { 19, 19 },139+ { 20, 20 }, { 20, 20 }, { 20, 20 }, { 20, 20 }, { 21, 21 }, { 21, 21 }, { 21, 21 }, { 21, 21 },140+ { 22, 22 }, { 22, 22 }, { 22, 22 }, { 22, 22 }, { 23, 23 }, { 23, 23 }, { 23, 23 }, { 23, 23 },141+ { 24, 24 }, { 24, 24 }, { 24, 24 }, { 24, 24 }, { 25, 25 }, { 25, 25 }, { 25, 25 }, { 25, 25 },142+ { 26, 26 }, { 26, 26 }, { 26, 26 }, { 26, 26 }, { 27, 27 }, { 27, 27 }, { 27, 27 }, { 27, 27 },143+ { 28, 28 }, { 28, 28 }, { 28, 28 }, { 28, 28 }, { 29, 29 }, { 29, 29 }, { 29, 29 }, { 29, 29 },144+ { 30, 30 }, { 30, 30 }, { 30, 30 }, { 30, 30 }, { 31, 31 }, { 31, 31 }, { 31, 31 }, { 31, 31 },145+ { 32, 32 }, { 32, 32 }, { 32, 32 }, { 32, 32 }, { 32, 32 }, { 33, 33 }, { 33, 33 }, { 33, 33 },146+ { 33, 33 }, { 34, 34 }, { 34, 34 }, { 34, 34 }, { 34, 34 }, { 35, 35 }, { 35, 35 }, { 35, 35 },147+ { 35, 35 }, { 36, 36 }, { 36, 36 }, { 36, 36 }, { 36, 36 }, { 37, 37 }, { 37, 37 }, { 37, 37 },148+ { 37, 37 }, { 38, 38 }, { 38, 38 }, { 38, 38 }, { 38, 38 }, { 39, 39 }, { 39, 39 }, { 39, 39 },149+ { 39, 39 }, { 40, 40 }, { 40, 40 }, { 40, 40 }, { 40, 40 }, { 41, 41 }, { 41, 41 }, { 41, 41 },150+ { 41, 41 }, { 42, 42 }, { 42, 42 }, { 42, 42 }, { 42, 42 }, { 43, 43 }, { 43, 43 }, { 43, 43 },151+ { 43, 43 }, { 44, 44 }, { 44, 44 }, { 44, 44 }, { 44, 44 }, { 45, 45 }, { 45, 45 }, { 45, 45 },152+ { 45, 45 }, { 46, 46 }, { 46, 46 }, { 46, 46 }, { 46, 46 }, { 47, 47 }, { 47, 47 }, { 47, 47 },153+ { 47, 47 }, { 48, 48 }, { 48, 48 }, { 48, 48 }, { 48, 48 }, { 48, 48 }, { 49, 49 }, { 49, 49 },154+ { 49, 49 }, { 49, 49 }, { 50, 50 }, { 50, 50 }, { 50, 50 }, { 50, 50 }, { 51, 51 }, { 51, 51 },155+ { 51, 51 }, { 51, 51 }, { 52, 52 }, { 52, 52 }, { 52, 52 }, { 52, 52 }, { 53, 53 }, { 53, 53 },156+ { 53, 53 }, { 53, 53 }, { 54, 54 }, { 54, 54 }, { 54, 54 }, { 54, 54 }, { 55, 55 }, { 55, 55 },157+ { 55, 55 }, { 55, 55 }, { 56, 56 }, { 56, 56 }, { 56, 56 }, { 56, 56 }, { 57, 57 }, { 57, 57 },158+ { 57, 57 }, { 57, 57 }, { 58, 58 }, { 58, 58 }, { 58, 58 }, { 58, 58 }, { 59, 59 }, { 59, 59 },159+ { 59, 59 }, { 59, 59 }, { 60, 60 }, { 60, 60 }, { 60, 60 }, { 60, 60 }, { 61, 61 }, { 61, 61 },160+ { 61, 61 }, { 61, 61 }, { 62, 62 }, { 62, 62 }, { 62, 62 }, { 62, 62 }, { 63, 63 }, { 63, 63 },161+};162 101-static unsigned char stb__Expand5[32];102-static unsigned char stb__Expand6[64];103-static unsigned char stb__OMatch5[256][2];104-static unsigned char stb__OMatch6[256][2];105-static unsigned char stb__QuantRBTab[256+16];106-static unsigned char stb__QuantGTab[256+16];107-163 static int stb__Mul8Bit(int a, int b)164 {165 int t = a*b + 128;166 return (t + (t >> 8)) >> 8;4 unmodified lines171 int rv = (v & 0xf800) >> 11;172 int gv = (v & 0x07e0) >> 5;173 int bv = (v & 0x001f) >> 0;174 120- out[0] = stb__Expand5[rv];121- out[1] = stb__Expand6[gv];122- out[2] = stb__Expand5[bv];175+ // expand to 8 bits via bit replication176+ out[0] = (rv * 33) >> 2;177+ out[1] = (gv * 65) >> 4;178+ out[2] = (bv * 33) >> 2;179 out[3] = 0;180 }181 182 static unsigned short stb__As16Bit(int r, int g, int b)23 unmodified lines206 }207 208 /****************************************************************************/209 154-// compute table to reproduce constant colors as accurately as possible155-static void stb__PrepareOptTable(unsigned char *Table,const unsigned char *expand,int size)156-{157- int i,mn,mx;158- for (i=0;i<256;i++) {159- int bestErr = 256;160- for (mn=0;mn<size;mn++) {161- for (mx=0;mx<size;mx++) {162- int mine = expand[mn];163- int maxe = expand[mx];164- int err = STBD_ABS(stb__Lerp13(maxe, mine) - i);165-166- // DX10 spec says that interpolation must be within 3% of "correct" result,167- // add this as error term. (normally we'd expect a random distribution of168- // +-1.5% error, but nowhere in the spec does it say that the error has to be169- // unbiased - better safe than sorry).170- err += STBD_ABS(maxe - mine) * 3 / 100;171-172- if(err < bestErr)173- {174- Table[i*2+0] = (unsigned char)mx;175- Table[i*2+1] = (unsigned char)mn;176- bestErr = err;177- }178- }179- }180- }181-}182-210 static void stb__EvalColors(unsigned char *color,unsigned short c0,unsigned short c1)211 {212 stb__From16Bit(color+ 0, c0);213 stb__From16Bit(color+ 4, c1);214 stb__Lerp13RGB(color+ 8, color+0, color+4);215 stb__Lerp13RGB(color+12, color+4, color+0);216 }217 191-// Block dithering function. Simply dithers a block to 565 RGB.192-// (Floyd-Steinberg)193-static void stb__DitherBlock(unsigned char *dest, unsigned char *block)194-{195- int err[8],*ep1 = err,*ep2 = err+4, *et;196- int ch,y;197-198- // process channels separately199- for (ch=0; ch<3; ++ch) {200- unsigned char *bp = block+ch, *dp = dest+ch;201- unsigned char *quant = (ch == 1) ? stb__QuantGTab+8 : stb__QuantRBTab+8;202- STBD_MEMSET(err, 0, sizeof(err));203- for(y=0; y<4; ++y) {204- dp[ 0] = quant[bp[ 0] + ((3*ep2[1] + 5*ep2[0]) >> 4)];205- ep1[0] = bp[ 0] - dp[ 0];206- dp[ 4] = quant[bp[ 4] + ((7*ep1[0] + 3*ep2[2] + 5*ep2[1] + ep2[0]) >> 4)];207- ep1[1] = bp[ 4] - dp[ 4];208- dp[ 8] = quant[bp[ 8] + ((7*ep1[1] + 3*ep2[3] + 5*ep2[2] + ep2[1]) >> 4)];209- ep1[2] = bp[ 8] - dp[ 8];210- dp[12] = quant[bp[12] + ((7*ep1[2] + 5*ep2[3] + ep2[2]) >> 4)];211- ep1[3] = bp[12] - dp[12];212- bp += 16;213- dp += 16;214- et = ep1, ep1 = ep2, ep2 = et; // swap215- }216- }217-}218-218 // The color matching function220-static unsigned int stb__MatchColorsBlock(unsigned char *block, unsigned char *color,int dither)219+static unsigned int stb__MatchColorsBlock(unsigned char *block, unsigned char *color)220 {221 unsigned int mask = 0;222 int dirr = color[0*4+0] - color[1*4+0];223 int dirg = color[0*4+1] - color[1*4+1];20 unmodified lines244 c0Point = (stops[1] + stops[3]);245 halfPoint = (stops[3] + stops[2]);246 c3Point = (stops[2] + stops[0]);247 249- if(!dither) {250- // the version without dithering is straightforward251- for (i=15;i>=0;i--) {252- int dot = dots[i]*2;253- mask <<= 2;248+ for (i=15;i>=0;i--) {249+ int dot = dots[i]*2;250+ mask <<= 2;251 255- if(dot < halfPoint)256- mask |= (dot < c0Point) ? 1 : 3;257- else258- mask |= (dot < c3Point) ? 2 : 0;259- }260- } else {261- // with floyd-steinberg dithering262- int err[8],*ep1 = err,*ep2 = err+4;263- int *dp = dots, y;264-265- c0Point <<= 3;266- halfPoint <<= 3;267- c3Point <<= 3;268- for(i=0;i<8;i++)269- err[i] = 0;270-271- for(y=0;y<4;y++)272- {273- int dot,lmask,step;274-275- dot = (dp[0] << 4) + (3*ep2[1] + 5*ep2[0]);276- if(dot < halfPoint)277- step = (dot < c0Point) ? 1 : 3;278- else279- step = (dot < c3Point) ? 2 : 0;280- ep1[0] = dp[0] - stops[step];281- lmask = step;282-283- dot = (dp[1] << 4) + (7*ep1[0] + 3*ep2[2] + 5*ep2[1] + ep2[0]);284- if(dot < halfPoint)285- step = (dot < c0Point) ? 1 : 3;286- else287- step = (dot < c3Point) ? 2 : 0;288- ep1[1] = dp[1] - stops[step];289- lmask |= step<<2;290-291- dot = (dp[2] << 4) + (7*ep1[1] + 3*ep2[3] + 5*ep2[2] + ep2[1]);292- if(dot < halfPoint)293- step = (dot < c0Point) ? 1 : 3;294- else295- step = (dot < c3Point) ? 2 : 0;296- ep1[2] = dp[2] - stops[step];297- lmask |= step<<4;298-299- dot = (dp[3] << 4) + (7*ep1[2] + 5*ep2[3] + ep2[2]);300- if(dot < halfPoint)301- step = (dot < c0Point) ? 1 : 3;302- else303- step = (dot < c3Point) ? 2 : 0;304- ep1[3] = dp[3] - stops[step];305- lmask |= step<<6;306-307- dp += 4;308- mask |= lmask << (y*8);309- { int *et = ep1; ep1 = ep2; ep2 = et; } // swap310- }252+ if(dot < halfPoint)253+ mask |= (dot < c0Point) ? 1 : 3;254+ else255+ mask |= (dot < c3Point) ? 2 : 0;256 }257 258 return mask;259 }260 261 // The color optimization function. (Clever code, part 1)262 static void stb__OptimizeColorsBlock(unsigned char *block, unsigned short *pmax16, unsigned short *pmin16)263 {319- int mind = 0x7fffffff,maxd = -0x7fffffff;264+ int mind,maxd;265 unsigned char *minp, *maxp;266 double magn;267 int v_r,v_g,v_b;268 static const int nIterPower = 4;73 unmodified lines342 v_g = (int) (vfg * magn);343 v_b = (int) (vfb * magn);344 }345 346+ minp = maxp = block;347+ mind = maxd = block[0]*v_r + block[1]*v_g + block[2]*v_b;348 // Pick colors at extreme points402- for(i=0;i<16;i++)349+ for(i=1;i<16;i++)350 {351 int dot = block[i*4+0]*v_r + block[i*4+1]*v_g + block[i*4+2]*v_b;352 353 if (dot < mind) {10 unmodified lines364 *pmax16 = stb__As16Bit(maxp[0],maxp[1],maxp[2]);365 *pmin16 = stb__As16Bit(minp[0],minp[1],minp[2]);366 }367 421-static const float midpoints5[32] = {368+static const float stb__midpoints5[32] = {369 0.015686f, 0.047059f, 0.078431f, 0.111765f, 0.145098f, 0.176471f, 0.207843f, 0.241176f, 0.274510f, 0.305882f, 0.337255f, 0.370588f, 0.403922f, 0.435294f, 0.466667f, 0.5f,370 0.533333f, 0.564706f, 0.596078f, 0.629412f, 0.662745f, 0.694118f, 0.725490f, 0.758824f, 0.792157f, 0.823529f, 0.854902f, 0.888235f, 0.921569f, 0.952941f, 0.984314f, 1.0f371 };372 426-static const float midpoints6[64] = {373+static const float stb__midpoints6[64] = {374 0.007843f, 0.023529f, 0.039216f, 0.054902f, 0.070588f, 0.086275f, 0.101961f, 0.117647f, 0.133333f, 0.149020f, 0.164706f, 0.180392f, 0.196078f, 0.211765f, 0.227451f, 0.245098f,375 0.262745f, 0.278431f, 0.294118f, 0.309804f, 0.325490f, 0.341176f, 0.356863f, 0.372549f, 0.388235f, 0.403922f, 0.419608f, 0.435294f, 0.450980f, 0.466667f, 0.482353f, 0.500000f,376 0.517647f, 0.533333f, 0.549020f, 0.564706f, 0.580392f, 0.596078f, 0.611765f, 0.627451f, 0.643137f, 0.658824f, 0.674510f, 0.690196f, 0.705882f, 0.721569f, 0.737255f, 0.754902f,377 0.772549f, 0.788235f, 0.803922f, 0.819608f, 0.835294f, 0.850980f, 0.866667f, 0.882353f, 0.898039f, 0.913725f, 0.929412f, 0.945098f, 0.960784f, 0.976471f, 0.992157f, 1.0f3 unmodified lines381 {382 unsigned short q;383 x = x < 0 ? 0 : x > 1 ? 1 : x; // saturate384 q = (unsigned short)(x * 31);438- q += (x > midpoints5[q]);385+ q += (x > stb__midpoints5[q]);386 return q;387 }388 389 static unsigned short stb__Quantize6(float x)390 {391 unsigned short q;392 x = x < 0 ? 0 : x > 1 ? 1 : x; // saturate393 q = (unsigned short)(x * 63);447- q += (x > midpoints6[q]);394+ q += (x > stb__midpoints6[q]);395 return q;396 }397 398 // The refinement function. (Clever code, part 2)79 unmodified lines478 static void stb__CompressColorBlock(unsigned char *dest, unsigned char *block, int mode)479 {480 unsigned int mask;481 int i;535- int dither;482 int refinecount;483 unsigned short max16, min16;538- unsigned char dblock[16*4],color[4*4];484+ unsigned char color[4*4];485 540- dither = mode & STB_DXT_DITHER;486 refinecount = (mode & STB_DXT_HIGHQUAL) ? 2 : 1;487 488 // check if block is constant489 for (i=1;i<16;i++)5 unmodified lines495 mask = 0xaaaaaaaa;496 max16 = (stb__OMatch5[r][0]<<11) | (stb__OMatch6[g][0]<<5) | stb__OMatch5[b][0];497 min16 = (stb__OMatch5[r][1]<<11) | (stb__OMatch6[g][1]<<5) | stb__OMatch5[b][1];498 } else {554- // first step: compute dithered version for PCA if desired555- if(dither)556- stb__DitherBlock(dblock,block);557-558- // second step: pca+map along principal axis559- stb__OptimizeColorsBlock(dither ? dblock : block,&max16,&min16);499+ // first step: PCA+map along principal axis500+ stb__OptimizeColorsBlock(block,&max16,&min16);501 if (max16 != min16) {502 stb__EvalColors(color,max16,min16);562- mask = stb__MatchColorsBlock(block,color,dither);503+ mask = stb__MatchColorsBlock(block,color);504 } else505 mask = 0;506 507 // third step: refine (multiple times if requested)508 for (i=0;i<refinecount;i++) {509 unsigned int lastmask = mask;510 570- if (stb__RefineBlock(dither ? dblock : block,&max16,&min16,mask)) {511+ if (stb__RefineBlock(block,&max16,&min16,mask)) {512 if (max16 != min16) {513 stb__EvalColors(color,max16,min16);573- mask = stb__MatchColorsBlock(block,color,dither);514+ mask = stb__MatchColorsBlock(block,color);515 } else {516 mask = 0;517 break;518 }75 unmodified lines594 }595 }596 }597 657-static void stb__InitDXT()658-{659- int i;660- for(i=0;i<32;i++)661- stb__Expand5[i] = (unsigned char)((i<<3)|(i>>2));662-663- for(i=0;i<64;i++)664- stb__Expand6[i] = (unsigned char)((i<<2)|(i>>4));665-666- for(i=0;i<256+16;i++)667- {668- int v = i-8 < 0 ? 0 : i-8 > 255 ? 255 : i-8;669- stb__QuantRBTab[i] = stb__Expand5[stb__Mul8Bit(v,31)];670- stb__QuantGTab[i] = stb__Expand6[stb__Mul8Bit(v,63)];671- }672-673- stb__PrepareOptTable(&stb__OMatch5[0][0],stb__Expand5,32);674- stb__PrepareOptTable(&stb__OMatch6[0][0],stb__Expand6,64);675-}676-598 void stb_compress_dxt_block(unsigned char *dest, const unsigned char *src, int alpha, int mode)599 {600 unsigned char data[16][4];680- static int init=1;681- if (init) {682- stb__InitDXT();683- init=0;684- }685-601 if (alpha) {602 int i;603 stb__CompressAlphaBlock(dest,(unsigned char*) src+3, 4);604 dest += 8;19 unmodified lines624 stb__CompressAlphaBlock(dest + 8,(unsigned char*) src+1,2);625 }626 #endif // STB_DXT_IMPLEMENTATION627 628+// Compile with STB_DXT_IMPLEMENTATION and STB_DXT_GENERATE_TABLES629+// defined to generate the tables above.630+#ifdef STB_DXT_GENERATE_TABLES631+#include <stdio.h>632+633+int main()634+{635+ int i, j;636+ const char *omatch_names[] = { "stb__OMatch5", "stb__OMatch6" };637+ int dequant_mults[2] = { 33*4, 65 }; // .4 fixed-point dequant multipliers638+639+ // optimal endpoint tables640+ for (i = 0; i < 2; ++i) {641+ int dequant = dequant_mults[i];642+ int size = i ? 64 : 32;643+ printf("static const unsigned char %s[256][2] = {\n", omatch_names[i]);644+ for (int j = 0; j < 256; ++j) {645+ int mn, mx;646+ int best_mn = 0, best_mx = 0;647+ int best_err = 256 * 100;648+ for (mn=0;mn<size;mn++) {649+ for (mx=0;mx<size;mx++) {650+ int mine = (mn * dequant) >> 4;651+ int maxe = (mx * dequant) >> 4;652+ int err = abs(stb__Lerp13(maxe, mine) - j);653+654+ // DX10 spec says that interpolation must be within 3% of "correct" result,655+ // add this as error term. Normally we'd expect a random distribution of656+ // +-1.5% error, but nowhere in the spec does it say that the error has to be657+ // unbiased - better safe than sorry.658+ err += abs(maxe - mine) * 3;659+660+ if(err < best_err) {661+ best_mn = mn;662+ best_mx = mx;663+ best_err = err;664+ }665+ }666+ }667+ if ((j % 8) == 0) printf(" "); // 2 spaces, third is done below668+ printf(" { %2d, %2d },", best_mx, best_mn);669+ if ((j % 8) == 7) printf("\n");670+ }671+ printf("};\n");672+ }673+674+ return 0;675+}676+#endif677+678 /*679 ------------------------------------------------------------------------------680 This software is available under 2 licenses -- choose whichever you prefer.681 ------------------------------------------------------------------------------37 unmodified linesmodified:stb_image_write.h+7 added-7 removed
283 unmodified lines284 {285 fwrite(data,1,size,(FILE*) context);286 }287 288-#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8)288+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)289 #ifdef __cplusplus290 #define STBIW_EXTERN extern "C"291 #else292 #define STBIW_EXTERN extern9 unmodified lines302 303 static FILE *stbiw__fopen(char const *filename, char const *mode)304 {305 FILE *f;306-#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8)306+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)307 wchar_t wMode[64];308 wchar_t wFilename[1024];309- if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)))309+ if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename)))310 return 0;311 312- if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)))312+ if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode)))313 return 0;314 315-#if _MSC_VER >= 1400315+#if defined(_MSC_VER) && _MSC_VER >= 1400316 if (0 != _wfopen_s(&f, wFilename, wMode))317 f = 0;318 #else319 f = _wfopen(wFilename, wMode);76 unmodified lines396 }397 398 static void stbiw__write1(stbi__write_context *s, unsigned char a)399 {400- if (s->buf_used + 1 > sizeof(s->buffer))400+ if ((size_t)s->buf_used + 1 > sizeof(s->buffer))401 stbiw__write_flush(s);402 s->buffer[s->buf_used++] = a;403 }404 405 static void stbiw__write3(stbi__write_context *s, unsigned char a, unsigned char b, unsigned char c)406 {407 int n;408- if (s->buf_used + 3 > sizeof(s->buffer))408+ if ((size_t)s->buf_used + 3 > sizeof(s->buffer))409 stbiw__write_flush(s);410 n = s->buf_used;411 s->buf_used = n+3;412 s->buffer[n+0] = a;1278 unmodified linesmodified:stb_image.h+121 added-47 removed
1-/* stb_image - v2.26 - public domain image loader - http://nothings.org/stb1+/* stb_image - v2.27 - public domain image loader - http://nothings.org/stb2 no warranty implied; use at your own risk3 4 Do this:5 #define STB_IMAGE_IMPLEMENTATION41 unmodified lines47 See end of file for license information.48 49 RECENT REVISION HISTORY:50 51+ 2.27 ( ) document stbi_info better, 16-bit PNM support, bug fixes52 2.26 (2020-07-13) many minor fixes53 2.25 (2020-02-02) fix warnings54 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically55 2.23 (2019-08-11) fix clang static analysis warning33 unmodified lines89 socks-the-fox (16-bit PNG)90 Jeremy Sawicki (handle all ImageNet JPGs)91 Optimizations & bugfixes Mikhail Morozov (1-bit BMP)92 Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query)92- Arseny Kapoulkine93+ Arseny Kapoulkine Simon Breuss (16-bit PNM)94 John-Mark Allen95 Carmelo J Fdez-Aguera96 97 Bug & warning fixes4 unmodified lines102 Luke Graham Johan Duparc Nick Verigakis the Horde3D community103 Thomas Ruf Ronny Chevalier github:rlyeh104 Janez Zemva John Bartholomew Michal Cichon github:romigrou105 Jonathan Blow Ken Hamada Tero Hanninen github:svdijk105- Laurent Gomila Cort Stratton github:snagar106+ Eugene Golushkov Laurent Gomila Cort Stratton github:snagar107 Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex108 Cass Everitt Ryamond Barbiero github:grim210109 Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw110 Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus4 unmodified lines115 Luca Sas Alexander Veselov Zack Middleton [reserved]116 Ryan C. Gordon [reserved] [reserved]117 DO NOT ADD YOUR NAME HERE118 119+ Jacko Dirks120+121 To add your name to the credits, pick a random blank space in the middle and fill it.122 80% of merge conflicts on stb PRs are due to people adding their name at the end123 of the credits.124 */53 unmodified lines178 // more user-friendly ones.179 //180 // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.181 //182+// To query the width, height and component count of an image without having to183+// decode the full file, you can use the stbi_info family of functions:184+//185+// int x,y,n,ok;186+// ok = stbi_info(filename, &x, &y, &n);187+// // returns ok=1 and sets x, y, n if image is a supported format,188+// // 0 otherwise.189+//190+// Note that stb_image pervasively uses ints in its public API for sizes,191+// including sizes of memory buffers. This is now part of the API and thus192+// hard to change without causing breakage. As a result, the various image193+// loaders all have certain limits on image size; these differ somewhat194+// by format but generally boil down to either just under 2GB or just under195+// 1GB. When the decoded image would be larger than this, stb_image decoding196+// will fail.197+//198+// Additionally, stb_image will reject image files that have any of their199+// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS,200+// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit,201+// the only way to have an image with such dimensions load correctly202+// is for it to have a rather extreme aspect ratio. Either way, the203+// assumption here is that such larger images are likely to be malformed204+// or malicious. If you do need to load an image with individual dimensions205+// larger than that, and it still fits in the overall size limit, you can206+// #define STBI_MAX_DIMENSIONS on your own to be something larger.207+//208 // ===========================================================================209 //210 // UNICODE:211 //450 unmodified lines662 663 #ifdef STBI_HAS_LROTL664 #define stbi_lrot(x,y) _lrotl(x,y)665 #else637- #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y))))666+ #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31)))667 #endif668 669 #if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED))670 // ok105 unmodified lines776 #endif777 778 #ifdef STBI_NEON779 #include <arm_neon.h>751-// assume GCC or Clang on ARM targets780+#ifdef _MSC_VER781+#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name782+#else783 #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))784 #endif785+#endif786 787 #ifndef STBI_SIMD_ALIGN788 #define STBI_SIMD_ALIGN(type, name) type name789 #endif165 unmodified lines955 #ifndef STBI_NO_PNM956 static int stbi__pnm_test(stbi__context *s);957 static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);958 static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp);959+static int stbi__pnm_is16(stbi__context *s);960 #endif961 962 static963 #ifdef STBI_THREAD_LOCAL155 unmodified lines1119 ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed1120 ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order1121 ri->num_channels = 0;1122 1090- #ifndef STBI_NO_JPEG1091- if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri);1092- #endif1123+ // test the formats with a very explicit header first (at least a FOURCC1124+ // or distinctive magic number first)1125 #ifndef STBI_NO_PNG1126 if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri);1127 #endif1128 #ifndef STBI_NO_BMP9 unmodified lines1138 #endif1139 #ifndef STBI_NO_PIC1140 if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri);1141 #endif1142+1143+ // then the formats that can end up attempting to load with just 1 or 21144+ // bytes matching expectations; these are prone to false positives, so1145+ // try them later1146+ #ifndef STBI_NO_JPEG1147+ if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri);1148+ #endif1149 #ifndef STBI_NO_PNM1150 if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri);1151 #endif1152 147 unmodified lines1300 #endif1301 1302 #ifndef STBI_NO_STDIO1303 1265-#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8)1304+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)1305 STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide);1306 STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default);1307 #endif1308 1270-#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8)1309+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)1310 STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input)1311 {1312 return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL);1313 }1 unmodified line1315 1316 static FILE *stbi__fopen(char const *filename, char const *mode)1317 {1318 FILE *f;1280-#if defined(_MSC_VER) && defined(STBI_WINDOWS_UTF8)1319+#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8)1320 wchar_t wMode[64];1321 wchar_t wFilename[1024];1283- if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)))1322+ if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename)))1323 return 0;1324 1286- if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)))1325+ if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode)))1326 return 0;1327 1289-#if _MSC_VER >= 14001328+#if defined(_MSC_VER) && _MSC_VER >= 14001329 if (0 != _wfopen_s(&f, wFilename, wMode))1330 f = 0;1331 #else1332 f = _wfopen(wFilename, wMode);367 unmodified lines1700 #ifndef STBI_NO_BMP1701 static stbi__uint32 stbi__get32le(stbi__context *s)1702 {1703 stbi__uint32 z = stbi__get16le(s);1665- return z + (stbi__get16le(s) << 16);1704+ z += (stbi__uint32)stbi__get16le(s) << 16;1705+ return z;1706 }1707 #endif1708 1709 #define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings419 unmodified lines2129 unsigned int k;2130 int sgn;2131 if (j->code_bits < n) stbi__grow_buffer_unsafe(j);2132 2093- sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB2133+ sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative)2134 k = stbi_lrot(j->code_buffer, n);2095- if (n < 0 || n >= (int) (sizeof(stbi__bmask)/sizeof(*stbi__bmask))) return 0;2135 j->code_buffer = k & ~stbi__bmask[n];2136 k &= stbi__bmask[n];2137 j->code_bits -= n;2099- return k + (stbi__jbias[n] & ~sgn);2138+ return k + (stbi__jbias[n] & (sgn - 1));2139 }2140 2141 // get some unsigned bits2142 stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n)41 unmodified lines2184 int t;2185 2186 if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);2187 t = stbi__jpeg_huff_decode(j, hdc);2149- if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG");2188+ if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG");2189 2190 // 0 all the ac values now so we can do it 32-bits at a time2191 memset(data,0,64*sizeof(data[0]));2192 48 unmodified lines2241 if (j->succ_high == 0) {2242 // first scan for DC coefficient, must be first2243 memset(data,0,64*sizeof(data[0])); // 0 all the ac values now2244 t = stbi__jpeg_huff_decode(j, hdc);2206- if (t == -1) return stbi__err("can't merge dc and ac", "Corrupt JPEG");2245+ if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG");2246 diff = t ? stbi__extend_receive(j, t) : 0;2247 2248 dc = j->img_comp[b].dc_pred + diff;2249 j->img_comp[b].dc_pred = dc;2211- data[0] = (short) (dc << j->succ_low);2250+ data[0] = (short) (dc * (1 << j->succ_low));2251 } else {2252 // refinement scan for DC coefficient2253 if (stbi__jpeg_get_bit(j))2254 data[0] += (short) (1 << j->succ_low);28 unmodified lines2283 s = r & 15; // combined length2284 j->code_buffer <<= s;2285 j->code_bits -= s;2286 zig = stbi__jpeg_dezigzag[k++];2248- data[zig] = (short) ((r >> 8) << shift);2287+ data[zig] = (short) ((r >> 8) * (1 << shift));2288 } else {2289 int rs = stbi__jpeg_huff_decode(j, hac);2290 if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");2291 s = rs & 15;9 unmodified lines2301 k += 16;2302 } else {2303 k += r;2304 zig = stbi__jpeg_dezigzag[k++];2266- data[zig] = (short) (stbi__extend_receive(j,s) << shift);2305+ data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift));2306 }2307 }2308 } while (k <= j->spec_end);2309 } else {1652 unmodified lines3962 static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)3963 {3964 unsigned char* result;3965 stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg));3966+ if (!j) return stbi__errpuc("outofmem", "Out of memory");3967 STBI_NOTUSED(ri);3968 j->s = s;3969 stbi__setup_jpeg(j);3970 result = load_jpeg_image(j, x,y,comp,req_comp);4 unmodified lines3975 static int stbi__jpeg_test(stbi__context *s)3976 {3977 int r;3978 stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg));3979+ if (!j) return stbi__err("outofmem", "Out of memory");3980 j->s = s;3981 stbi__setup_jpeg(j);3982 r = stbi__decode_jpeg_header(j, STBI__SCAN_type);3983 stbi__rewind(s);16 unmodified lines4000 static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp)4001 {4002 int result;4003 stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg)));4004+ if (!j) return stbi__err("outofmem", "Out of memory");4005 j->s = s;4006 result = stbi__jpeg_info_raw(j, x, y, comp);4007 STBI_FREE(j);4008 return result;11 unmodified lines4020 4021 // fast-way is faster to check than jpeg huffman, but slow way is slower4022 #define STBI__ZFAST_BITS 9 // accelerate all cases in default tables4023 #define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1)4024+#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet4025 4026 // zlib-style huffman encoding4027 // (jpegs packs from left, zlib from right, so can't share code)4028 typedef struct1 unmodified line4030 stbi__uint16 fast[1 << STBI__ZFAST_BITS];4031 stbi__uint16 firstcode[16];4032 int maxcode[17];4033 stbi__uint16 firstsymbol[16];3991- stbi_uc size[288];3992- stbi__uint16 value[288];4034+ stbi_uc size[STBI__ZNSYMS];4035+ stbi__uint16 value[STBI__ZNSYMS];4036 } stbi__zhuffman;4037 4038 stbi_inline static int stbi__bitreverse16(int n)4039 {122 unmodified lines4162 break;4163 if (s >= 16) return -1; // invalid code!4164 // code size is s, so:4165 b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];4123- if (b >= sizeof (z->size)) return -1; // some data was corrupt somewhere!4166+ if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere!4167 if (z->size[b] != s) return -1; // was originally an assert, but report failure instead.4168 a->code_buffer >>= s;4169 a->num_bits -= s;4170 return z->value[b];188 unmodified lines4359 // window = 1 << (8 + cinfo)... but who cares, we fully buffer output4360 return 1;4361 }4362 4320-static const stbi_uc stbi__zdefault_length[288] =4363+static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] =4364 {4365 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,4366 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,4367 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,37 unmodified lines4405 return 0;4406 } else {4407 if (type == 1) {4408 // use fixed code lengths4366- if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0;4409+ if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0;4410 if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0;4411 } else {4412 if (!stbi__compute_huffman_codes(a)) return 0;4413 }387 unmodified lines4801 return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color);4802 4803 // de-interlacing4804 final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0);4805+ if (!final) return stbi__err("outofmem", "Out of memory");4806 for (p=0; p < 7; ++p) {4807 int xorig[] = { 0,4,0,2,0,1,0 };4808 int yorig[] = { 0,0,4,0,2,0,1 };4809 int xspc[] = { 8,8,4,4,2,2,1 };627 unmodified lines5437 if (info.bpp < 16)5438 psize = (info.offset - info.extra_read - info.hsz) >> 2;5439 }5440 if (psize == 0) {5397- STBI_ASSERT(info.offset == s->callback_already_read + (int) (s->img_buffer - s->img_buffer_original));5398- if (info.offset != s->callback_already_read + (s->img_buffer - s->buffer_start)) {5441+ if (info.offset != s->callback_already_read + (s->img_buffer - s->img_buffer_original)) {5442 return stbi__errpuc("bad offset", "Corrupt BMP");5443 }5444 }5445 938 unmodified lines6384 stbi__get16be(s); //skip `pad'6385 6386 // intermediate buffer is RGBA6387 result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0);6388+ if (!result) return stbi__errpuc("outofmem", "Out of memory");6389 memset(result, 0xff, x*y*4);6390 6391 if (!stbi__pic_load_core(s,x,y,comp, result)) {6392 STBI_FREE(result);107 unmodified lines6500 6501 static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp)6502 {6503 stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif));6504+ if (!g) return stbi__err("outofmem", "Out of memory");6505 if (!stbi__gif_header(s, g, comp, 1)) {6506 STBI_FREE(g);6507 stbi__rewind( s );6508 return 0;301 unmodified lines6810 }6811 }6812 }6813 6814+static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays)6815+{6816+ STBI_FREE(g->out);6817+ STBI_FREE(g->history);6818+ STBI_FREE(g->background);6819+6820+ if (out) STBI_FREE(out);6821+ if (delays && *delays) STBI_FREE(*delays);6822+ return stbi__errpuc("outofmem", "Out of memory");6823+}6824+6825 static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp)6826 {6827 if (stbi__gif_test(s)) {6828 int layers = 0;3 unmodified lines6832 stbi__gif g;6833 int stride;6834 int out_size = 0;6835 int delays_size = 0;6836+6837+ STBI_NOTUSED(out_size);6838+ STBI_NOTUSED(delays_size);6839+6840 memset(&g, 0, sizeof(g));6841 if (delays) {6842 *delays = 0;6843 }9 unmodified lines6853 stride = g.w * g.h * 4;6854 6855 if (out) {6856 void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride );6797- if (NULL == tmp) {6798- STBI_FREE(g.out);6799- STBI_FREE(g.history);6800- STBI_FREE(g.background);6801- return stbi__errpuc("outofmem", "Out of memory");6802- }6857+ if (!tmp)6858+ return stbi__load_gif_main_outofmem(&g, out, delays);6859 else {6860 out = (stbi_uc*) tmp;6861 out_size = layers * stride;6862 }6863 6864 if (delays) {6865 *delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers );6866+ if (!*delays)6867+ return stbi__load_gif_main_outofmem(&g, out, delays);6868 delays_size = layers * sizeof(int);6869 }6870 } else {6871 out = (stbi_uc*)stbi__malloc( layers * stride );6872+ if (!out)6873+ return stbi__load_gif_main_outofmem(&g, out, delays);6874 out_size = layers * stride;6875 if (delays) {6876 *delays = (int*) stbi__malloc( layers * sizeof(int) );6877+ if (!*delays)6878+ return stbi__load_gif_main_outofmem(&g, out, delays);6879 delays_size = layers * sizeof(int);6880 }6881 }6882 memcpy( out + ((layers - 1) * stride), u, stride );384 unmodified lines7267 if (channelCount < 0 || channelCount > 16) {7268 stbi__rewind( s );7269 return 0;7270 }7209- (void) stbi__get32be(s);7210- (void) stbi__get32be(s);7271+ STBI_NOTUSED(stbi__get32be(s));7272+ STBI_NOTUSED(stbi__get32be(s));7273 depth = stbi__get16be(s);7274 if (depth != 16) {7275 stbi__rewind( s );7276 return 0;70 unmodified lines7347 //7348 // Known limitations:7349 // Does not support comments in the header section7350 // Does not support ASCII image data (formats P2 and P3)7289-// Does not support 16-bit-per-channel7351 7352 #ifndef STBI_NO_PNM7353 7354 static int stbi__pnm_test(stbi__context *s)12 unmodified lines7367 {7368 stbi_uc *out;7369 STBI_NOTUSED(ri);7370 7310- if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n))7371+ ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n);7372+ if (ri->bits_per_channel == 0)7373 return 0;7374 7375 if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");7376 if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)");1 unmodified line7378 *x = s->img_x;7379 *y = s->img_y;7380 if (comp) *comp = s->img_n;7381 7320- if (!stbi__mad3sizes_valid(s->img_n, s->img_x, s->img_y, 0))7382+ if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0))7383 return stbi__errpuc("too large", "PNM too large");7384 7323- out = (stbi_uc *) stbi__malloc_mad3(s->img_n, s->img_x, s->img_y, 0);7385+ out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0);7386 if (!out) return stbi__errpuc("outofmem", "Out of memory");7325- stbi__getn(s, out, s->img_n * s->img_x * s->img_y);7387+ stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8));7388 7389 if (req_comp && req_comp != s->img_n) {7390 out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y);7391 if (out == NULL) return out; // stbi__convert_format frees input on failure67 unmodified lines7459 *y = stbi__pnm_getinteger(s, &c); // read height7460 stbi__pnm_skip_whitespace(s, &c);7461 7462 maxv = stbi__pnm_getinteger(s, &c); // read max value7401-7402- if (maxv > 255)7403- return stbi__err("max value > 255", "PPM image not 8-bit");7463+ if (maxv > 65535)7464+ return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images");7465+ else if (maxv > 255)7466+ return 16;7467 else7405- return 1;7468+ return 8;7469 }7470+7471+static int stbi__pnm_is16(stbi__context *s)7472+{7473+ if (stbi__pnm_info(s, NULL, NULL, NULL) == 16)7474+ return 1;7475+ return 0;7476+}7477+7478 #endif7479 7480 static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp)7481 {46 unmodified lines7528 #ifndef STBI_NO_PSD7529 if (stbi__psd_is16(s)) return 1;7530 #endif7531 7532+ #ifndef STBI_NO_PNM7533+ if (stbi__pnm_is16(s)) return 1;7534+ #endif7535 return 0;7536 }7537 7538 #ifndef STBI_NO_STDIO298 unmodified linesmodified:stb_sprintf.h+16 added-7 removed
5 unmodified lines6 // lengths : hh h ll j z t I64 I32 I7 //8 // Contributors:9 // Fabian "ryg" Giesen (reformatting)10+// github:aganm (attribute format)11 //12 // Contributors (bugfixes):13 // github:d2643514 // github:trex78161 unmodified lines176 #define STBSP__PUBLICDEF STBSP__ASAN177 #endif178 #endif179 180+#if defined(__has_attribute)181+ #if __has_attribute(format)182+ #define STBSP__ATTRIBUTE_FORMAT(fmt,va) __attribute__((format(printf,fmt,va)))183+ #endif184+#endif185+186+#ifndef STBSP__ATTRIBUTE_FORMAT187+#define STBSP__ATTRIBUTE_FORMAT(fmt,va)188+#endif189+179-#include <stdarg.h> // for va_list()190+#include <stdarg.h> // for va_arg(), va_list()191 #include <stddef.h> // size_t, ptrdiff_t192 193 #ifndef STB_SPRINTF_MIN194 #define STB_SPRINTF_MIN 512 // how many characters per callback5 unmodified lines200 #endif201 202 STBSP__PUBLICDEF int STB_SPRINTF_DECORATE(vsprintf)(char *buf, char const *fmt, va_list va);203 STBSP__PUBLICDEF int STB_SPRINTF_DECORATE(vsnprintf)(char *buf, int count, char const *fmt, va_list va);193-STBSP__PUBLICDEF int STB_SPRINTF_DECORATE(sprintf)(char *buf, char const *fmt, ...);194-STBSP__PUBLICDEF int STB_SPRINTF_DECORATE(snprintf)(char *buf, int count, char const *fmt, ...);204+STBSP__PUBLICDEF int STB_SPRINTF_DECORATE(sprintf)(char *buf, char const *fmt, ...) STBSP__ATTRIBUTE_FORMAT(2,3);205+STBSP__PUBLICDEF int STB_SPRINTF_DECORATE(snprintf)(char *buf, int count, char const *fmt, ...) STBSP__ATTRIBUTE_FORMAT(3,4);206 207 STBSP__PUBLICDEF int STB_SPRINTF_DECORATE(vsprintfcb)(STBSP_SPRINTFCB *callback, void *user, char *buf, char const *fmt, va_list va);208 STBSP__PUBLICDEF void STB_SPRINTF_DECORATE(set_separators)(char comma, char period);209 210 #endif // STB_SPRINTF_H_INCLUDE211 212 #ifdef STB_SPRINTF_IMPLEMENTATION213 203-#include <stdlib.h> // for va_arg()204-214 #define stbsp__uint32 unsigned int215 #define stbsp__int32 signed int216 217 #ifdef _MSC_VER5 unmodified lines223 #endif224 #define stbsp__uint16 unsigned short225 226 #ifndef stbsp__uintptr218-#if defined(__ppc64__) || defined(__powerpc64__) || defined(__aarch64__) || defined(_M_X64) || defined(__x86_64__) || defined(__x86_64)227+#if defined(__ppc64__) || defined(__powerpc64__) || defined(__aarch64__) || defined(_M_X64) || defined(__x86_64__) || defined(__x86_64) || defined(__s390x__)228 #define stbsp__uintptr stbsp__uint64229 #else230 #define stbsp__uintptr stbsp__uint32231 #endif1364 unmodified lines1596 1597 #define stbsp__ddtoS64(ob, xh, xl) \1598 { \1599 double ahi = 0, alo, vh, t; \1591- ob = (stbsp__int64)ph; \1600+ ob = (stbsp__int64)xh; \1601 vh = (double)ob; \1602 ahi = (xh - vh); \1603 t = (ahi - xh); \1604 alo = (xh - (ahi - t)) - (vh + t); \284 unmodified linesmodified:stb_textedit.h+2 added-2 removed
85 unmodified lines86 // If you don't define these, they are set to permissive types and87 // moderate sizes. The undo system does no memory allocations, so88 // it grows STB_TexteditState by the worst-case storage which is (in bytes):89 //90-// [4 + 3 * sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATE_COUNT91-// + sizeof(STB_TEXTEDIT_CHARTYPE) * STB_TEXTEDIT_UNDOCHAR_COUNT90+// [4 + 3 * sizeof(STB_TEXTEDIT_POSITIONTYPE)] * STB_TEXTEDIT_UNDOSTATECOUNT91+// + sizeof(STB_TEXTEDIT_CHARTYPE) * STB_TEXTEDIT_UNDOCHARCOUNT92 //93 //94 // Implementation mode:95 //1309 unmodified linesmodified:stb_truetype.hnot shown
Its text is not shown, modified.
deleted:stb.h-14454 removed
1-/* stb.h - v2.37 - Sean's Tool Box -- public domain -- http://nothings.org/stb.h2- no warranty is offered or implied; use this code at your own risk3-4- This is a single header file with a bunch of useful utilities5- for getting stuff done in C/C++.6-7- Documentation: http://nothings.org/stb/stb_h.html8- Unit tests: http://nothings.org/stb/stb.c9-10- ============================================================================11- You MUST12-13- #define STB_DEFINE14-15- in EXACTLY _one_ C or C++ file that includes this header, BEFORE the16- include, like this:17-18- #define STB_DEFINE19- #include "stb.h"20-21- All other files should just #include "stb.h" without the #define.22- ============================================================================23-24-Version History25-26- 2.36 various fixes27- 2.35 fix clang-cl issues with swprintf28- 2.34 fix warnings29- 2.33 more fixes to random numbers30- 2.32 stb_intcmprev, stb_uidict, fix random numbers on Linux31- 2.31 stb_ucharcmp32- 2.30 MinGW fix33- 2.29 attempt to fix use of swprintf()34- 2.28 various new functionality35- 2.27 test _WIN32 not WIN32 in STB_THREADS36- 2.26 various warning & bugfixes37- 2.25 various warning & bugfixes38- 2.24 various warning & bugfixes39- 2.23 fix 2.2240- 2.22 64-bit fixes from '!='; fix stb_sdict_copy() to have preferred name41- 2.21 utf-8 decoder rejects "overlong" encodings; attempted 64-bit improvements42- 2.20 fix to hash "copy" function--reported by someone with handle "!="43- 2.19 ???44- 2.18 stb_readdir_subdirs_mask45- 2.17 stb_cfg_dir46- 2.16 fix stb_bgio_, add stb_bgio_stat(); begin a streaming wrapper47- 2.15 upgraded hash table template to allow:48- - aggregate keys (explicit comparison func for EMPTY and DEL keys)49- - "static" implementations (so they can be culled if unused)50- 2.14 stb_mprintf51- 2.13 reduce identifiable strings in STB_NO_STB_STRINGS52- 2.12 fix STB_ONLY -- lots of uint32s, TRUE/FALSE things had crept in53- 2.11 fix bug in stb_dirtree_get() which caused "c://path" sorts of stuff54- 2.10 STB_F(), STB_I() inline constants (also KI,KU,KF,KD)55- 2.09 stb_box_face_vertex_axis_side56- 2.08 bugfix stb_trimwhite()57- 2.07 colored printing in windows (why are we in 1985?)58- 2.06 comparison functions are now functions-that-return-functions and59- accept a struct-offset as a parameter (not thread-safe)60- 2.05 compile and pass tests under Linux (but no threads); thread cleanup61- 2.04 stb_cubic_bezier_1d, smoothstep, avoid dependency on registry62- 2.03 ?63- 2.02 remove integrated documentation64- 2.01 integrate various fixes; stb_force_uniprocessor65- 2.00 revised stb_dupe to use multiple hashes66- 1.99 stb_charcmp67- 1.98 stb_arr_deleten, stb_arr_insertn68- 1.97 fix stb_newell_normal()69- 1.96 stb_hash_number()70- 1.95 hack stb__rec_max; clean up recursion code to use new functions71- 1.94 stb_dirtree; rename stb_extra to stb_ptrmap72- 1.93 stb_sem_new() API cleanup (no blockflag-starts blocked; use 'extra')73- 1.92 stb_threadqueue--multi reader/writer queue, fixed size or resizeable74- 1.91 stb_bgio_* for reading disk asynchronously75- 1.90 stb_mutex uses CRITICAL_REGION; new stb_sync primitive for thread76- joining; workqueue supports stb_sync instead of stb_semaphore77- 1.89 support ';' in constant-string wildcards; stb_mutex wrapper (can78- implement with EnterCriticalRegion eventually)79- 1.88 portable threading API (only for win32 so far); worker thread queue80- 1.87 fix wildcard handling in stb_readdir_recursive81- 1.86 support ';' in wildcards82- 1.85 make stb_regex work with non-constant strings;83- beginnings of stb_introspect()84- 1.84 (forgot to make notes)85- 1.83 whoops, stb_keep_if_different wasn't deleting the temp file86- 1.82 bring back stb_compress from stb_file.h for cmirror87- 1.81 various bugfixes, STB_FASTMALLOC_INIT inits FASTMALLOC in release88- 1.80 stb_readdir returns utf8; write own utf8-utf16 because lib was wrong89- 1.79 stb_write90- 1.78 calloc() support for malloc wrapper, STB_FASTMALLOC91- 1.77 STB_FASTMALLOC92- 1.76 STB_STUA - Lua-like language; (stb_image, stb_csample, stb_bilinear)93- 1.75 alloc/free array of blocks; stb_hheap bug; a few stb_ps_ funcs;94- hash*getkey, hash*copy; stb_bitset; stb_strnicmp; bugfix stb_bst95- 1.74 stb_replaceinplace; use stdlib C function to convert utf8 to UTF-1696- 1.73 fix performance bug & leak in stb_ischar (C++ port lost a 'static')97- 1.72 remove stb_block, stb_block_manager, stb_decompress (to stb_file.h)98- 1.71 stb_trimwhite, stb_tokens_nested, etc.99- 1.70 back out 1.69 because it might problemize mixed builds; stb_filec()100- 1.69 (stb_file returns 'char *' in C++)101- 1.68 add a special 'tree root' data type for stb_bst; stb_arr_end102- 1.67 full C++ port. (stb_block_manager)103- 1.66 stb_newell_normal104- 1.65 stb_lex_item_wild -- allow wildcard items which MUST match entirely105- 1.64 stb_data106- 1.63 stb_log_name107- 1.62 stb_define_sort; C++ cleanup108- 1.61 stb_hash_fast -- Paul Hsieh's hash function (beats Bob Jenkins'?)109- 1.60 stb_delete_directory_recursive110- 1.59 stb_readdir_recursive111- 1.58 stb_bst variant with parent pointer for O(1) iteration, not O(log N)112- 1.57 replace LCG random with Mersenne Twister (found a public domain one)113- 1.56 stb_perfect_hash, stb_ischar, stb_regex114- 1.55 new stb_bst API allows multiple BSTs per node (e.g. secondary keys)115- 1.54 bugfix: stb_define_hash, stb_wildmatch, regexp116- 1.53 stb_define_hash; recoded stb_extra, stb_sdict use it117- 1.52 stb_rand_define, stb_bst, stb_reverse118- 1.51 fix 'stb_arr_setlen(NULL, 0)'119- 1.50 stb_wordwrap120- 1.49 minor improvements to enable the scripting language121- 1.48 better approach for stb_arr using stb_malloc; more invasive, clearer122- 1.47 stb_lex (lexes stb.h at 1.5ML/s on 3Ghz P4; 60/70% of optimal/flex)123- 1.46 stb_wrapper_*, STB_MALLOC_WRAPPER124- 1.45 lightly tested DFA acceleration of regexp searching125- 1.44 wildcard matching & searching; regexp matching & searching126- 1.43 stb_temp127- 1.42 allow stb_arr to use stb_malloc/realloc; note this is global128- 1.41 make it compile in C++; (disable stb_arr in C++)129- 1.40 stb_dupe tweak; stb_swap; stb_substr130- 1.39 stb_dupe; improve stb_file_max to be less stupid131- 1.38 stb_sha1_file: generate sha1 for file, even > 4GB132- 1.37 stb_file_max; partial support for utf8 filenames in Windows133- 1.36 remove STB__NO_PREFIX - poor interaction with IDE, not worth it134- streamline stb_arr to make it separately publishable135- 1.35 bugfixes for stb_sdict, stb_malloc(0), stristr136- 1.34 (streaming interfaces for stb_compress)137- 1.33 stb_alloc; bug in stb_getopt; remove stb_overflow138- 1.32 (stb_compress returns, smaller&faster; encode window & 64-bit len)139- 1.31 stb_prefix_count140- 1.30 (STB__NO_PREFIX - remove stb_ prefixes for personal projects)141- 1.29 stb_fput_varlen64, etc.142- 1.28 stb_sha1143- 1.27 ?144- 1.26 stb_extra145- 1.25 ?146- 1.24 stb_copyfile147- 1.23 stb_readdir148- 1.22 ?149- 1.21 ?150- 1.20 ?151- 1.19 ?152- 1.18 ?153- 1.17 ?154- 1.16 ?155- 1.15 stb_fixpath, stb_splitpath, stb_strchr2156- 1.14 stb_arr157- 1.13 ?stb, stb_log, stb_fatal158- 1.12 ?stb_hash2159- 1.11 miniML160- 1.10 stb_crc32, stb_adler32161- 1.09 stb_sdict162- 1.08 stb_bitreverse, stb_ispow2, stb_big32163- stb_fopen, stb_fput_varlen, stb_fput_ranged164- stb_fcmp, stb_feq165- 1.07 (stb_encompress)166- 1.06 stb_compress167- 1.05 stb_tokens, (stb_hheap)168- 1.04 stb_rand169- 1.03 ?(s-strings)170- 1.02 ?stb_filelen, stb_tokens171- 1.01 stb_tolower172- 1.00 stb_hash, stb_intcmp173- stb_file, stb_stringfile, stb_fgets174- stb_prefix, stb_strlower, stb_strtok175- stb_image176- (stb_array), (stb_arena)177-178-Parenthesized items have since been removed.179-180-LICENSE181-182- See end of file for license information.183-184-CREDITS185-186- Written by Sean Barrett.187-188- Fixes:189- Philipp Wiesemann190- Robert Nix191- r-lyeh192- blackpawn193- github:Mojofreem194- Ryan Whitworth195- Vincent Isambart196- Mike Sartain197- Eugene Opalev198- Tim Sjostrand199- github:infatum200- Dave Butler (Croepha)201- Ethan Lee (flibitijibibo)202- Brian Collins203- Kyle Langley204-*/205-206-#include <stdarg.h>207-208-#ifndef STB__INCLUDE_STB_H209-#define STB__INCLUDE_STB_H210-211-#define STB_VERSION 1212-213-#ifdef STB_INTROSPECT214- #define STB_DEFINE215-#endif216-217-#ifdef STB_DEFINE_THREADS218- #ifndef STB_DEFINE219- #define STB_DEFINE220- #endif221- #ifndef STB_THREADS222- #define STB_THREADS223- #endif224-#endif225-226-#if defined(_WIN32) && !defined(__MINGW32__)227- #ifndef _CRT_SECURE_NO_WARNINGS228- #define _CRT_SECURE_NO_WARNINGS229- #endif230- #ifndef _CRT_NONSTDC_NO_DEPRECATE231- #define _CRT_NONSTDC_NO_DEPRECATE232- #endif233- #ifndef _CRT_NON_CONFORMING_SWPRINTFS234- #define _CRT_NON_CONFORMING_SWPRINTFS235- #endif236- #if !defined(_MSC_VER) || _MSC_VER > 1700237- #include <intrin.h> // _BitScanReverse238- #endif239-#endif240-241-#include <stdlib.h> // stdlib could have min/max242-#include <stdio.h> // need FILE243-#include <string.h> // stb_define_hash needs memcpy/memset244-#include <time.h> // stb_dirtree245-#ifdef __MINGW32__246- #include <fcntl.h> // O_RDWR247-#endif248-249-#ifdef STB_PERSONAL250- typedef int Bool;251- #define False 0252- #define True 1253-#endif254-255-#ifdef STB_MALLOC_WRAPPER_PAGED256- #define STB_MALLOC_WRAPPER_DEBUG257-#endif258-#ifdef STB_MALLOC_WRAPPER_DEBUG259- #define STB_MALLOC_WRAPPER260-#endif261-#ifdef STB_MALLOC_WRAPPER_FASTMALLOC262- #define STB_FASTMALLOC263- #define STB_MALLOC_WRAPPER264-#endif265-266-#ifdef STB_FASTMALLOC267- #ifndef _WIN32268- #undef STB_FASTMALLOC269- #endif270-#endif271-272-#ifdef STB_DEFINE273- #include <assert.h>274- #include <stdarg.h>275- #include <stddef.h>276- #include <ctype.h>277- #include <math.h>278- #ifndef _WIN32279- #include <unistd.h>280- #else281- #include <io.h> // _mktemp282- #include <direct.h> // _rmdir283- #endif284- #include <sys/types.h> // stat()/_stat()285- #include <sys/stat.h> // stat()/_stat()286-#endif287-288-#define stb_min(a,b) ((a) < (b) ? (a) : (b))289-#define stb_max(a,b) ((a) > (b) ? (a) : (b))290-291-#ifndef STB_ONLY292- #if !defined(__cplusplus) && !defined(min) && !defined(max)293- #define min(x,y) stb_min(x,y)294- #define max(x,y) stb_max(x,y)295- #endif296-297- #ifndef M_PI298- #define M_PI 3.14159265358979323846f299- #endif300-301- #ifndef TRUE302- #define TRUE 1303- #define FALSE 0304- #endif305-306- #ifndef deg2rad307- #define deg2rad(a) ((a)*(M_PI/180))308- #endif309- #ifndef rad2deg310- #define rad2deg(a) ((a)*(180/M_PI))311- #endif312-313- #ifndef swap314- #ifndef __cplusplus315- #define swap(TYPE,a,b) \316- do { TYPE stb__t; stb__t = (a); (a) = (b); (b) = stb__t; } while (0)317- #endif318- #endif319-320- typedef unsigned char uint8 ;321- typedef signed char int8 ;322- typedef unsigned short uint16;323- typedef signed short int16;324- #if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32)325- typedef unsigned long uint32;326- typedef signed long int32;327- #else328- typedef unsigned int uint32;329- typedef signed int int32;330- #endif331-332- typedef unsigned char uchar ;333- typedef unsigned short ushort;334- typedef unsigned int uint ;335- typedef unsigned long ulong ;336-337- // produce compile errors if the sizes aren't right338- typedef char stb__testsize16[sizeof(int16)==2];339- typedef char stb__testsize32[sizeof(int32)==4];340-#endif341-342-#ifndef STB_TRUE343- #define STB_TRUE 1344- #define STB_FALSE 0345-#endif346-347-// if we're STB_ONLY, can't rely on uint32 or even uint, so all the348-// variables we'll use herein need typenames prefixed with 'stb':349-typedef unsigned char stb_uchar;350-typedef unsigned char stb_uint8;351-typedef unsigned int stb_uint;352-typedef unsigned short stb_uint16;353-typedef short stb_int16;354-typedef signed char stb_int8;355-#if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32)356- typedef unsigned long stb_uint32;357- typedef long stb_int32;358-#else359- typedef unsigned int stb_uint32;360- typedef int stb_int32;361-#endif362-typedef char stb__testsize2_16[sizeof(stb_uint16)==2 ? 1 : -1];363-typedef char stb__testsize2_32[sizeof(stb_uint32)==4 ? 1 : -1];364-365-#ifdef _MSC_VER366- typedef unsigned __int64 stb_uint64;367- typedef __int64 stb_int64;368- #define STB_IMM_UINT64(literalui64) (literalui64##ui64)369- #define STB_IMM_INT64(literali64) (literali64##i64)370-#else371- // ??372- typedef unsigned long long stb_uint64;373- typedef long long stb_int64;374- #define STB_IMM_UINT64(literalui64) (literalui64##ULL)375- #define STB_IMM_INT64(literali64) (literali64##LL)376-#endif377-typedef char stb__testsize2_64[sizeof(stb_uint64)==8 ? 1 : -1];378-379-// add platform-specific ways of checking for sizeof(char*) == 8,380-// and make those define STB_PTR64381-#if defined(_WIN64) || defined(__x86_64__) || defined(__ia64__) || defined(__LP64__)382- #define STB_PTR64383-#endif384-385-#ifdef STB_PTR64386-typedef char stb__testsize2_ptr[sizeof(char *) == 8];387-typedef stb_uint64 stb_uinta;388-typedef stb_int64 stb_inta;389-#else390-typedef char stb__testsize2_ptr[sizeof(char *) == 4];391-typedef stb_uint32 stb_uinta;392-typedef stb_int32 stb_inta;393-#endif394-typedef char stb__testsize2_uinta[sizeof(stb_uinta)==sizeof(char*) ? 1 : -1];395-396-// if so, we should define an int type that is the pointer size. until then,397-// we'll have to make do with this (which is not the same at all!)398-399-typedef union400-{401- unsigned int i;402- void * p;403-} stb_uintptr;404-405-406-#ifdef __cplusplus407- #define STB_EXTERN extern "C"408-#else409- #define STB_EXTERN extern410-#endif411-412-// check for well-known debug defines413-#if defined(DEBUG) || defined(_DEBUG) || defined(DBG)414- #ifndef NDEBUG415- #define STB_DEBUG416- #endif417-#endif418-419-#ifdef STB_DEBUG420- #include <assert.h>421-#endif422-423-//////////////////////////////////////////////////////////////////////////////424-//425-// C library function platform handling426-//427-428-#ifdef STB_DEFINE429-430-#if defined(_WIN32) && defined(__STDC_WANT_SECURE_LIB__)431-static FILE * stb_p_fopen(const char *filename, const char *mode)432-{433- FILE *f;434- if (0 == fopen_s(&f, filename, mode))435- return f;436- else437- return NULL;438-}439-static FILE * stb_p_wfopen(const wchar_t *filename, const wchar_t *mode)440-{441- FILE *f;442- if (0 == _wfopen_s(&f, filename, mode))443- return f;444- else445- return NULL;446-}447-static char *stb_p_strcpy_s(char *a, size_t size, const char *b)448-{449- strcpy_s(a,size,b);450- return a;451-}452-static char *stb_p_strncpy_s(char *a, size_t size, const char *b, size_t count)453-{454- strncpy_s(a,size,b,count);455- return a;456-}457-#define stb_p_mktemp(s) (_mktemp_s(s, strlen(s)+1) == 0)458-#define stb_p_sprintf sprintf_s459-#define stb_p_size(x) ,(x)460-#else461-#define stb_p_fopen fopen462-#define stb_p_wfopen _wfopen463-#define stb_p_strcpy_s(a,s,b) strcpy(a,b)464-#define stb_p_strncpy_s(a,s,b,c) strncpy(a,b,c)465-#define stb_p_mktemp(s) (mktemp(s) != NULL)466-467-#define stb_p_sprintf sprintf468-#define stb_p_size(x)469-#endif470-471-#if defined(_WIN32)472-#define stb_p_vsnprintf _vsnprintf473-#else474-#define stb_p_vsnprintf vsnprintf475-#endif476-#endif // STB_DEFINE477-478-#if defined(_WIN32) && (_MSC_VER >= 1300)479-#define stb_p_stricmp _stricmp480-#define stb_p_strnicmp _strnicmp481-#define stb_p_strdup _strdup482-#else483-#define stb_p_strdup strdup484-#define stb_p_stricmp stricmp485-#define stb_p_strnicmp strnicmp486-#endif487-488-STB_EXTERN void stb_wrapper_malloc(void *newp, size_t sz, char *file, int line);489-STB_EXTERN void stb_wrapper_free(void *oldp, char *file, int line);490-STB_EXTERN void stb_wrapper_realloc(void *oldp, void *newp, size_t sz, char *file, int line);491-STB_EXTERN void stb_wrapper_calloc(size_t num, size_t sz, char *file, int line);492-STB_EXTERN void stb_wrapper_listall(void (*func)(void *ptr, size_t sz, char *file, int line));493-STB_EXTERN void stb_wrapper_dump(char *filename);494-STB_EXTERN size_t stb_wrapper_allocsize(void *oldp);495-STB_EXTERN void stb_wrapper_check(void *oldp);496-497-#ifdef STB_DEFINE498-// this is a special function used inside malloc wrapper499-// to do allocations that aren't tracked (to avoid500-// reentrancy). Of course if someone _else_ wraps realloc,501-// this breaks, but if they're doing that AND the malloc502-// wrapper they need to explicitly check for reentrancy.503-//504-// only define realloc_raw() and we do realloc(NULL,sz)505-// for malloc() and realloc(p,0) for free().506-static void * stb__realloc_raw(void *p, int sz)507-{508- if (p == NULL) return malloc(sz);509- if (sz == 0) { free(p); return NULL; }510- return realloc(p,sz);511-}512-#endif513-514-#ifdef _WIN32515-STB_EXTERN void * stb_smalloc(size_t sz);516-STB_EXTERN void stb_sfree(void *p);517-STB_EXTERN void * stb_srealloc(void *p, size_t sz);518-STB_EXTERN void * stb_scalloc(size_t n, size_t sz);519-STB_EXTERN char * stb_sstrdup(char *s);520-#endif521-522-#ifdef STB_FASTMALLOC523-#define malloc stb_smalloc524-#define free stb_sfree525-#define realloc stb_srealloc526-#define strdup stb_sstrdup527-#define calloc stb_scalloc528-#endif529-530-#ifndef STB_MALLOC_ALLCHECK531- #define stb__check(p) 1532-#else533- #ifndef STB_MALLOC_WRAPPER534- #error STB_MALLOC_ALLCHECK requires STB_MALLOC_WRAPPER535- #else536- #define stb__check(p) stb_mcheck(p)537- #endif538-#endif539-540-#ifdef STB_MALLOC_WRAPPER541- STB_EXTERN void * stb__malloc(size_t, char *, int);542- STB_EXTERN void * stb__realloc(void *, size_t, char *, int);543- STB_EXTERN void * stb__calloc(size_t n, size_t s, char *, int);544- STB_EXTERN void stb__free(void *, char *file, int);545- STB_EXTERN char * stb__strdup(char *s, char *file, int);546- STB_EXTERN void stb_malloc_checkall(void);547- STB_EXTERN void stb_malloc_check_counter(int init_delay, int rep_delay);548- #ifndef STB_MALLOC_WRAPPER_DEBUG549- #define stb_mcheck(p) 1550- #else551- STB_EXTERN int stb_mcheck(void *);552- #endif553-554-555- #ifdef STB_DEFINE556-557- #ifdef STB_MALLOC_WRAPPER_DEBUG558- #define STB__PAD 32559- #define STB__BIAS 16560- #define STB__SIG 0x51b01234561- #define STB__FIXSIZE(sz) (((sz+3) & ~3) + STB__PAD)562- #define STB__ptr(x,y) ((char *) (x) + (y))563- #else564- #define STB__ptr(x,y) (x)565- #define STB__FIXSIZE(sz) (sz)566- #endif567-568- #ifdef STB_MALLOC_WRAPPER_DEBUG569- int stb_mcheck(void *p)570- {571- unsigned int sz;572- if (p == NULL) return 1;573- p = ((char *) p) - STB__BIAS;574- sz = * (unsigned int *) p;575- assert(* (unsigned int *) STB__ptr(p,4) == STB__SIG);576- assert(* (unsigned int *) STB__ptr(p,8) == STB__SIG);577- assert(* (unsigned int *) STB__ptr(p,12) == STB__SIG);578- assert(* (unsigned int *) STB__ptr(p,sz-4) == STB__SIG+1);579- assert(* (unsigned int *) STB__ptr(p,sz-8) == STB__SIG+1);580- assert(* (unsigned int *) STB__ptr(p,sz-12) == STB__SIG+1);581- assert(* (unsigned int *) STB__ptr(p,sz-16) == STB__SIG+1);582- stb_wrapper_check(STB__ptr(p, STB__BIAS));583- return 1;584- }585-586- static void stb__check2(void *p, size_t sz, char *file, int line)587- {588- stb_mcheck(p);589- }590-591- void stb_malloc_checkall(void)592- {593- stb_wrapper_listall(stb__check2);594- }595- #else596- void stb_malloc_checkall(void) { }597- #endif598-599- static int stb__malloc_wait=(1 << 30), stb__malloc_next_wait = (1 << 30), stb__malloc_iter;600- void stb_malloc_check_counter(int init_delay, int rep_delay)601- {602- stb__malloc_wait = init_delay;603- stb__malloc_next_wait = rep_delay;604- }605-606- void stb_mcheck_all(void)607- {608- #ifdef STB_MALLOC_WRAPPER_DEBUG609- ++stb__malloc_iter;610- if (--stb__malloc_wait <= 0) {611- stb_malloc_checkall();612- stb__malloc_wait = stb__malloc_next_wait;613- }614- #endif615- }616-617- #ifdef STB_MALLOC_WRAPPER_PAGED618- #define STB__WINDOWS_PAGE (1 << 12)619- #ifndef _WINDOWS_620- STB_EXTERN __declspec(dllimport) void * __stdcall VirtualAlloc(void *p, unsigned long size, unsigned long type, unsigned long protect);621- STB_EXTERN __declspec(dllimport) int __stdcall VirtualFree(void *p, unsigned long size, unsigned long freetype);622- #endif623- #endif624-625- static void *stb__malloc_final(size_t sz)626- {627- #ifdef STB_MALLOC_WRAPPER_PAGED628- size_t aligned = (sz + STB__WINDOWS_PAGE - 1) & ~(STB__WINDOWS_PAGE-1);629- char *p = VirtualAlloc(NULL, aligned + STB__WINDOWS_PAGE, 0x2000, 0x04); // RESERVE, READWRITE630- if (p == NULL) return p;631- VirtualAlloc(p, aligned, 0x1000, 0x04); // COMMIT, READWRITE632- return p;633- #else634- return malloc(sz);635- #endif636- }637-638- static void stb__free_final(void *p)639- {640- #ifdef STB_MALLOC_WRAPPER_PAGED641- VirtualFree(p, 0, 0x8000); // RELEASE642- #else643- free(p);644- #endif645- }646-647- int stb__malloc_failure;648- #ifdef STB_MALLOC_WRAPPER_PAGED649- static void *stb__realloc_final(void *p, size_t sz, size_t old_sz)650- {651- void *q = stb__malloc_final(sz);652- if (q == NULL)653- return ++stb__malloc_failure, q;654- // @TODO: deal with p being smaller!655- memcpy(q, p, sz < old_sz ? sz : old_sz);656- stb__free_final(p);657- return q;658- }659- #endif660-661- void stb__free(void *p, char *file, int line)662- {663- stb_mcheck_all();664- if (!p) return;665- #ifdef STB_MALLOC_WRAPPER_DEBUG666- stb_mcheck(p);667- #endif668- stb_wrapper_free(p,file,line);669- #ifdef STB_MALLOC_WRAPPER_DEBUG670- p = STB__ptr(p,-STB__BIAS);671- * (unsigned int *) STB__ptr(p,0) = 0xdeadbeef;672- * (unsigned int *) STB__ptr(p,4) = 0xdeadbeef;673- * (unsigned int *) STB__ptr(p,8) = 0xdeadbeef;674- * (unsigned int *) STB__ptr(p,12) = 0xdeadbeef;675- #endif676- stb__free_final(p);677- }678-679- void * stb__malloc(size_t sz, char *file, int line)680- {681- void *p;682- stb_mcheck_all();683- if (sz == 0) return NULL;684- p = stb__malloc_final(STB__FIXSIZE(sz));685- if (p == NULL) p = stb__malloc_final(STB__FIXSIZE(sz));686- if (p == NULL) p = stb__malloc_final(STB__FIXSIZE(sz));687- if (p == NULL) {688- ++stb__malloc_failure;689- #ifdef STB_MALLOC_WRAPPER_DEBUG690- stb_malloc_checkall();691- #endif692- return p;693- }694- #ifdef STB_MALLOC_WRAPPER_DEBUG695- * (int *) STB__ptr(p,0) = STB__FIXSIZE(sz);696- * (unsigned int *) STB__ptr(p,4) = STB__SIG;697- * (unsigned int *) STB__ptr(p,8) = STB__SIG;698- * (unsigned int *) STB__ptr(p,12) = STB__SIG;699- * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-4) = STB__SIG+1;700- * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-8) = STB__SIG+1;701- * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-12) = STB__SIG+1;702- * (unsigned int *) STB__ptr(p,STB__FIXSIZE(sz)-16) = STB__SIG+1;703- p = STB__ptr(p, STB__BIAS);704- #endif705- stb_wrapper_malloc(p,sz,file,line);706- return p;707- }708-709- void * stb__realloc(void *p, size_t sz, char *file, int line)710- {711- void *q;712-713- stb_mcheck_all();714- if (p == NULL) return stb__malloc(sz,file,line);715- if (sz == 0 ) { stb__free(p,file,line); return NULL; }716-717- #ifdef STB_MALLOC_WRAPPER_DEBUG718- stb_mcheck(p);719- p = STB__ptr(p,-STB__BIAS);720- #endif721- #ifdef STB_MALLOC_WRAPPER_PAGED722- {723- size_t n = stb_wrapper_allocsize(STB__ptr(p,STB__BIAS));724- if (!n)725- stb_wrapper_check(STB__ptr(p,STB__BIAS));726- q = stb__realloc_final(p, STB__FIXSIZE(sz), STB__FIXSIZE(n));727- }728- #else729- q = realloc(p, STB__FIXSIZE(sz));730- #endif731- if (q == NULL)732- return ++stb__malloc_failure, q;733- #ifdef STB_MALLOC_WRAPPER_DEBUG734- * (int *) STB__ptr(q,0) = STB__FIXSIZE(sz);735- * (unsigned int *) STB__ptr(q,4) = STB__SIG;736- * (unsigned int *) STB__ptr(q,8) = STB__SIG;737- * (unsigned int *) STB__ptr(q,12) = STB__SIG;738- * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-4) = STB__SIG+1;739- * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-8) = STB__SIG+1;740- * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-12) = STB__SIG+1;741- * (unsigned int *) STB__ptr(q,STB__FIXSIZE(sz)-16) = STB__SIG+1;742-743- q = STB__ptr(q, STB__BIAS);744- p = STB__ptr(p, STB__BIAS);745- #endif746- stb_wrapper_realloc(p,q,sz,file,line);747- return q;748- }749-750- STB_EXTERN int stb_log2_ceil(size_t);751- static void *stb__calloc(size_t n, size_t sz, char *file, int line)752- {753- void *q;754- stb_mcheck_all();755- if (n == 0 || sz == 0) return NULL;756- if (stb_log2_ceil(n) + stb_log2_ceil(sz) >= 32) return NULL;757- q = stb__malloc(n*sz, file, line);758- if (q) memset(q, 0, n*sz);759- return q;760- }761-762- char * stb__strdup(char *s, char *file, int line)763- {764- char *p;765- stb_mcheck_all();766- p = stb__malloc(strlen(s)+1, file, line);767- if (!p) return p;768- stb_p_strcpy_s(p, strlen(s)+1, s);769- return p;770- }771- #endif // STB_DEFINE772-773- #ifdef STB_FASTMALLOC774- #undef malloc775- #undef realloc776- #undef free777- #undef strdup778- #undef calloc779- #endif780-781- // include everything that might define these, BEFORE making macros782- #include <stdlib.h>783- #include <string.h>784- #include <malloc.h>785-786- #define malloc(s) stb__malloc ( s, __FILE__, __LINE__)787- #define realloc(p,s) stb__realloc(p,s, __FILE__, __LINE__)788- #define calloc(n,s) stb__calloc (n,s, __FILE__, __LINE__)789- #define free(p) stb__free (p, __FILE__, __LINE__)790- #define strdup(p) stb__strdup (p, __FILE__, __LINE__)791-#endif792-793-//////////////////////////////////////////////////////////////////////////////794-//795-// Windows pretty display796-//797-798-STB_EXTERN void stbprint(const char *fmt, ...);799-STB_EXTERN char *stb_sprintf(const char *fmt, ...);800-STB_EXTERN char *stb_mprintf(const char *fmt, ...);801-STB_EXTERN int stb_snprintf(char *s, size_t n, const char *fmt, ...);802-STB_EXTERN int stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v);803-804-#ifdef STB_DEFINE805-int stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v)806-{807- int res;808- #ifdef _WIN32809- #ifdef __STDC_WANT_SECURE_LIB__810- res = _vsnprintf_s(s, n, _TRUNCATE, fmt, v);811- #else812- res = stb_p_vsnprintf(s,n,fmt,v);813- #endif814- #else815- res = vsnprintf(s,n,fmt,v);816- #endif817- if (n) s[n-1] = 0;818- // Unix returns length output would require, Windows returns negative when truncated.819- return (res >= (int) n || res < 0) ? -1 : res;820-}821-822-int stb_snprintf(char *s, size_t n, const char *fmt, ...)823-{824- int res;825- va_list v;826- va_start(v,fmt);827- res = stb_vsnprintf(s, n, fmt, v);828- va_end(v);829- return res;830-}831-832-char *stb_sprintf(const char *fmt, ...)833-{834- static char buffer[1024];835- va_list v;836- va_start(v,fmt);837- stb_vsnprintf(buffer,1024,fmt,v);838- va_end(v);839- return buffer;840-}841-842-char *stb_mprintf(const char *fmt, ...)843-{844- static char buffer[1024];845- va_list v;846- va_start(v,fmt);847- stb_vsnprintf(buffer,1024,fmt,v);848- va_end(v);849- return stb_p_strdup(buffer);850-}851-852-#ifdef _WIN32853-854-#ifndef _WINDOWS_855-STB_EXTERN __declspec(dllimport) int __stdcall WriteConsoleA(void *, const void *, unsigned int, unsigned int *, void *);856-STB_EXTERN __declspec(dllimport) void * __stdcall GetStdHandle(unsigned int);857-STB_EXTERN __declspec(dllimport) int __stdcall SetConsoleTextAttribute(void *, unsigned short);858-#endif859-860-static void stb__print_one(void *handle, char *s, ptrdiff_t len)861-{862- if (len)863- if (0==WriteConsoleA(handle, s, (unsigned) len, NULL,NULL))864- // if it fails, maybe redirected, so output normally...865- // but it's supriously reporting failure now on Win7 and later866- {}//fwrite(s, 1, (unsigned) len, stdout);867-}868-869-static void stb__print(char *s)870-{871- void *handle = GetStdHandle((unsigned int) -11); // STD_OUTPUT_HANDLE872- int pad=0; // number of padding characters to add873-874- char *t = s;875- while (*s) {876- int lpad;877- while (*s && *s != '{') {878- if (pad) {879- if (*s == '\r' || *s == '\n')880- pad = 0;881- else if (s[0] == ' ' && s[1] == ' ') {882- stb__print_one(handle, t, s-t);883- t = s;884- while (pad) {885- stb__print_one(handle, t, 1);886- --pad;887- }888- }889- }890- ++s;891- }892- if (!*s) break;893- stb__print_one(handle, t, s-t);894- if (s[1] == '{') {895- ++s;896- continue;897- }898-899- if (s[1] == '#') {900- t = s+3;901- if (isxdigit(s[2]))902- if (isdigit(s[2]))903- SetConsoleTextAttribute(handle, s[2] - '0');904- else905- SetConsoleTextAttribute(handle, tolower(s[2]) - 'a' + 10);906- else {907- SetConsoleTextAttribute(handle, 0x0f);908- t=s+2;909- }910- } else if (s[1] == '!') {911- SetConsoleTextAttribute(handle, 0x0c);912- t = s+2;913- } else if (s[1] == '@') {914- SetConsoleTextAttribute(handle, 0x09);915- t = s+2;916- } else if (s[1] == '$') {917- SetConsoleTextAttribute(handle, 0x0a);918- t = s+2;919- } else {920- SetConsoleTextAttribute(handle, 0x08); // 0,7,8,15 => shades of grey921- t = s+1;922- }923-924- lpad = (int) (t-s);925- s = t;926- while (*s && *s != '}') ++s;927- if (!*s) break;928- stb__print_one(handle, t, s-t);929- if (s[1] == '}') {930- t = s+2;931- } else {932- pad += 1+lpad;933- t = s+1;934- }935- s=t;936- SetConsoleTextAttribute(handle, 0x07);937- }938- stb__print_one(handle, t, s-t);939- SetConsoleTextAttribute(handle, 0x07);940-}941-942-void stbprint(const char *fmt, ...)943-{944- int res;945- char buffer[1024];946- char *tbuf = buffer;947- va_list v;948-949- va_start(v,fmt);950- res = stb_vsnprintf(buffer, sizeof(buffer), fmt, v);951- va_end(v);952-953- if (res < 0) {954- tbuf = (char *) malloc(16384);955- va_start(v,fmt);956- res = stb_vsnprintf(tbuf,16384, fmt, v);957- va_end(v);958- tbuf[16383] = 0;959- }960-961- stb__print(tbuf);962-963- if (tbuf != buffer)964- free(tbuf);965-}966-967-#else // _WIN32968-void stbprint(const char *fmt, ...)969-{970- va_list v;971- va_start(v,fmt);972- vprintf(fmt,v);973- va_end(v);974-}975-#endif // _WIN32976-#endif // STB_DEFINE977-978-979-980-//////////////////////////////////////////////////////////////////////////////981-//982-// Windows UTF8 filename handling983-//984-// Windows stupidly treats 8-bit filenames as some dopey code page,985-// rather than utf-8. If we want to use utf8 filenames, we have to986-// convert them to WCHAR explicitly and call WCHAR versions of the987-// file functions. So, ok, we do.988-989-990-#ifdef _WIN32991- #define stb__fopen(x,y) stb_p_wfopen((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y))992- #define stb__windows(x,y) x993-#else994- #define stb__fopen(x,y) stb_p_fopen(x,y)995- #define stb__windows(x,y) y996-#endif997-998-999-typedef unsigned short stb__wchar;1000-1001-STB_EXTERN stb__wchar * stb_from_utf8(stb__wchar *buffer, const char *str, int n);1002-STB_EXTERN char * stb_to_utf8 (char *buffer, const stb__wchar *str, int n);1003-1004-STB_EXTERN stb__wchar *stb__from_utf8(const char *str);1005-STB_EXTERN stb__wchar *stb__from_utf8_alt(const char *str);1006-STB_EXTERN char *stb__to_utf8(const stb__wchar *str);1007-1008-1009-#ifdef STB_DEFINE1010-stb__wchar * stb_from_utf8(stb__wchar *buffer, const char *ostr, int n)1011-{1012- unsigned char *str = (unsigned char *) ostr;1013- stb_uint32 c;1014- int i=0;1015- --n;1016- while (*str) {1017- if (i >= n)1018- return NULL;1019- if (!(*str & 0x80))1020- buffer[i++] = *str++;1021- else if ((*str & 0xe0) == 0xc0) {1022- if (*str < 0xc2) return NULL;1023- c = (*str++ & 0x1f) << 6;1024- if ((*str & 0xc0) != 0x80) return NULL;1025- buffer[i++] = c + (*str++ & 0x3f);1026- } else if ((*str & 0xf0) == 0xe0) {1027- if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return NULL;1028- if (*str == 0xed && str[1] > 0x9f) return NULL; // str[1] < 0x80 is checked below1029- c = (*str++ & 0x0f) << 12;1030- if ((*str & 0xc0) != 0x80) return NULL;1031- c += (*str++ & 0x3f) << 6;1032- if ((*str & 0xc0) != 0x80) return NULL;1033- buffer[i++] = c + (*str++ & 0x3f);1034- } else if ((*str & 0xf8) == 0xf0) {1035- if (*str > 0xf4) return NULL;1036- if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return NULL;1037- if (*str == 0xf4 && str[1] > 0x8f) return NULL; // str[1] < 0x80 is checked below1038- c = (*str++ & 0x07) << 18;1039- if ((*str & 0xc0) != 0x80) return NULL;1040- c += (*str++ & 0x3f) << 12;1041- if ((*str & 0xc0) != 0x80) return NULL;1042- c += (*str++ & 0x3f) << 6;1043- if ((*str & 0xc0) != 0x80) return NULL;1044- c += (*str++ & 0x3f);1045- // utf-8 encodings of values used in surrogate pairs are invalid1046- if ((c & 0xFFFFF800) == 0xD800) return NULL;1047- if (c >= 0x10000) {1048- c -= 0x10000;1049- if (i + 2 > n) return NULL;1050- buffer[i++] = 0xD800 | (0x3ff & (c >> 10));1051- buffer[i++] = 0xDC00 | (0x3ff & (c ));1052- }1053- } else1054- return NULL;1055- }1056- buffer[i] = 0;1057- return buffer;1058-}1059-1060-char * stb_to_utf8(char *buffer, const stb__wchar *str, int n)1061-{1062- int i=0;1063- --n;1064- while (*str) {1065- if (*str < 0x80) {1066- if (i+1 > n) return NULL;1067- buffer[i++] = (char) *str++;1068- } else if (*str < 0x800) {1069- if (i+2 > n) return NULL;1070- buffer[i++] = 0xc0 + (*str >> 6);1071- buffer[i++] = 0x80 + (*str & 0x3f);1072- str += 1;1073- } else if (*str >= 0xd800 && *str < 0xdc00) {1074- stb_uint32 c;1075- if (i+4 > n) return NULL;1076- c = ((str[0] - 0xd800) << 10) + ((str[1]) - 0xdc00) + 0x10000;1077- buffer[i++] = 0xf0 + (c >> 18);1078- buffer[i++] = 0x80 + ((c >> 12) & 0x3f);1079- buffer[i++] = 0x80 + ((c >> 6) & 0x3f);1080- buffer[i++] = 0x80 + ((c ) & 0x3f);1081- str += 2;1082- } else if (*str >= 0xdc00 && *str < 0xe000) {1083- return NULL;1084- } else {1085- if (i+3 > n) return NULL;1086- buffer[i++] = 0xe0 + (*str >> 12);1087- buffer[i++] = 0x80 + ((*str >> 6) & 0x3f);1088- buffer[i++] = 0x80 + ((*str ) & 0x3f);1089- str += 1;1090- }1091- }1092- buffer[i] = 0;1093- return buffer;1094-}1095-1096-stb__wchar *stb__from_utf8(const char *str)1097-{1098- static stb__wchar buffer[4096];1099- return stb_from_utf8(buffer, str, 4096);1100-}1101-1102-stb__wchar *stb__from_utf8_alt(const char *str)1103-{1104- static stb__wchar buffer[4096];1105- return stb_from_utf8(buffer, str, 4096);1106-}1107-1108-char *stb__to_utf8(const stb__wchar *str)1109-{1110- static char buffer[4096];1111- return stb_to_utf8(buffer, str, 4096);1112-}1113-1114-#endif1115-1116-//////////////////////////////////////////////////////////////////////////////1117-//1118-// Miscellany1119-//1120-1121-STB_EXTERN void stb_fatal(const char *fmt, ...);1122-STB_EXTERN void stb_(char *fmt, ...);1123-STB_EXTERN void stb_append_to_file(char *file, char *fmt, ...);1124-STB_EXTERN void stb_log(int active);1125-STB_EXTERN void stb_log_fileline(int active);1126-STB_EXTERN void stb_log_name(char *filename);1127-1128-STB_EXTERN void stb_swap(void *p, void *q, size_t sz);1129-STB_EXTERN void *stb_copy(void *p, size_t sz);1130-STB_EXTERN void stb_pointer_array_free(void *p, int len);1131-STB_EXTERN void **stb_array_block_alloc(int count, int blocksize);1132-1133-#define stb_arrcount(x) (sizeof(x)/sizeof((x)[0]))1134-1135-1136-STB_EXTERN int stb__record_fileline(const char *f, int n);1137-1138-#ifdef STB_DEFINE1139-1140-static char *stb__file;1141-static int stb__line;1142-1143-int stb__record_fileline(const char *f, int n)1144-{1145- stb__file = (char*) f;1146- stb__line = n;1147- return 0;1148-}1149-1150-void stb_fatal(const char *s, ...)1151-{1152- va_list a;1153- if (stb__file)1154- fprintf(stderr, "[%s:%d] ", stb__file, stb__line);1155- va_start(a,s);1156- fputs("Fatal error: ", stderr);1157- vfprintf(stderr, s, a);1158- va_end(a);1159- fputs("\n", stderr);1160- #ifdef STB_DEBUG1161- #ifdef _MSC_VER1162- #ifndef STB_PTR641163- __asm int 3; // trap to debugger!1164- #else1165- __debugbreak();1166- #endif1167- #else1168- __builtin_trap();1169- #endif1170- #endif1171- exit(1);1172-}1173-1174-static int stb__log_active=1, stb__log_fileline=1;1175-1176-void stb_log(int active)1177-{1178- stb__log_active = active;1179-}1180-1181-void stb_log_fileline(int active)1182-{1183- stb__log_fileline = active;1184-}1185-1186-#ifdef STB_NO_STB_STRINGS1187-const char *stb__log_filename = "temp.log";1188-#else1189-const char *stb__log_filename = "stb.log";1190-#endif1191-1192-void stb_log_name(char *s)1193-{1194- stb__log_filename = s;1195-}1196-1197-void stb_(char *s, ...)1198-{1199- if (stb__log_active) {1200- FILE *f = stb_p_fopen(stb__log_filename, "a");1201- if (f) {1202- va_list a;1203- if (stb__log_fileline && stb__file)1204- fprintf(f, "[%s:%4d] ", stb__file, stb__line);1205- va_start(a,s);1206- vfprintf(f, s, a);1207- va_end(a);1208- fputs("\n", f);1209- fclose(f);1210- }1211- }1212-}1213-1214-void stb_append_to_file(char *filename, char *s, ...)1215-{1216- FILE *f = stb_p_fopen(filename, "a");1217- if (f) {1218- va_list a;1219- va_start(a,s);1220- vfprintf(f, s, a);1221- va_end(a);1222- fputs("\n", f);1223- fclose(f);1224- }1225-}1226-1227-1228-typedef struct { char d[4]; } stb__4;1229-typedef struct { char d[8]; } stb__8;1230-1231-// optimize the small cases, though you shouldn't be calling this for those!1232-void stb_swap(void *p, void *q, size_t sz)1233-{1234- char buffer[256];1235- if (p == q) return;1236- if (sz == 4) {1237- stb__4 temp = * ( stb__4 *) p;1238- * (stb__4 *) p = * ( stb__4 *) q;1239- * (stb__4 *) q = temp;1240- return;1241- } else if (sz == 8) {1242- stb__8 temp = * ( stb__8 *) p;1243- * (stb__8 *) p = * ( stb__8 *) q;1244- * (stb__8 *) q = temp;1245- return;1246- }1247-1248- while (sz > sizeof(buffer)) {1249- stb_swap(p, q, sizeof(buffer));1250- p = (char *) p + sizeof(buffer);1251- q = (char *) q + sizeof(buffer);1252- sz -= sizeof(buffer);1253- }1254-1255- memcpy(buffer, p , sz);1256- memcpy(p , q , sz);1257- memcpy(q , buffer, sz);1258-}1259-1260-void *stb_copy(void *p, size_t sz)1261-{1262- void *q = malloc(sz);1263- memcpy(q, p, sz);1264- return q;1265-}1266-1267-void stb_pointer_array_free(void *q, int len)1268-{1269- void **p = (void **) q;1270- int i;1271- for (i=0; i < len; ++i)1272- free(p[i]);1273-}1274-1275-void **stb_array_block_alloc(int count, int blocksize)1276-{1277- int i;1278- char *p = (char *) malloc(sizeof(void *) * count + count * blocksize);1279- void **q;1280- if (p == NULL) return NULL;1281- q = (void **) p;1282- p += sizeof(void *) * count;1283- for (i=0; i < count; ++i)1284- q[i] = p + i * blocksize;1285- return q;1286-}1287-#endif1288-1289-#ifdef STB_DEBUG1290- // tricky hack to allow recording FILE,LINE even in varargs functions1291- #define STB__RECORD_FILE(x) (stb__record_fileline(__FILE__, __LINE__),(x))1292- #define stb_log STB__RECORD_FILE(stb_log)1293- #define stb_ STB__RECORD_FILE(stb_)1294- #ifndef STB_FATAL_CLEAN1295- #define stb_fatal STB__RECORD_FILE(stb_fatal)1296- #endif1297- #define STB__DEBUG(x) x1298-#else1299- #define STB__DEBUG(x)1300-#endif1301-1302-//////////////////////////////////////////////////////////////////////////////1303-//1304-// stb_temp1305-//1306-1307-#define stb_temp(block, sz) stb__temp(block, sizeof(block), (sz))1308-1309-STB_EXTERN void * stb__temp(void *b, int b_sz, int want_sz);1310-STB_EXTERN void stb_tempfree(void *block, void *ptr);1311-1312-#ifdef STB_DEFINE1313-1314-void * stb__temp(void *b, int b_sz, int want_sz)1315-{1316- if (b_sz >= want_sz)1317- return b;1318- else1319- return malloc(want_sz);1320-}1321-1322-void stb_tempfree(void *b, void *p)1323-{1324- if (p != b)1325- free(p);1326-}1327-#endif1328-1329-1330-//////////////////////////////////////////////////////////////////////////////1331-//1332-// math/sampling operations1333-//1334-1335-1336-#define stb_lerp(t,a,b) ( (a) + (t) * (float) ((b)-(a)) )1337-#define stb_unlerp(t,a,b) ( ((t) - (a)) / (float) ((b) - (a)) )1338-1339-#define stb_clamp(x,xmin,xmax) ((x) < (xmin) ? (xmin) : (x) > (xmax) ? (xmax) : (x))1340-1341-STB_EXTERN void stb_newell_normal(float *normal, int num_vert, float **vert, int normalize);1342-STB_EXTERN int stb_box_face_vertex_axis_side(int face_number, int vertex_number, int axis);1343-STB_EXTERN void stb_linear_controller(float *curpos, float target_pos, float acc, float deacc, float dt);1344-1345-STB_EXTERN int stb_float_eq(float x, float y, float delta, int max_ulps);1346-STB_EXTERN int stb_is_prime(unsigned int m);1347-STB_EXTERN unsigned int stb_power_of_two_nearest_prime(int n);1348-1349-STB_EXTERN float stb_smoothstep(float t);1350-STB_EXTERN float stb_cubic_bezier_1d(float t, float p0, float p1, float p2, float p3);1351-1352-STB_EXTERN double stb_linear_remap(double x, double a, double b,1353- double c, double d);1354-1355-#ifdef STB_DEFINE1356-float stb_smoothstep(float t)1357-{1358- return (3 - 2*t)*(t*t);1359-}1360-1361-float stb_cubic_bezier_1d(float t, float p0, float p1, float p2, float p3)1362-{1363- float it = 1-t;1364- return it*it*it*p0 + 3*it*it*t*p1 + 3*it*t*t*p2 + t*t*t*p3;1365-}1366-1367-void stb_newell_normal(float *normal, int num_vert, float **vert, int normalize)1368-{1369- int i,j;1370- float p;1371- normal[0] = normal[1] = normal[2] = 0;1372- for (i=num_vert-1,j=0; j < num_vert; i=j++) {1373- float *u = vert[i];1374- float *v = vert[j];1375- normal[0] += (u[1] - v[1]) * (u[2] + v[2]);1376- normal[1] += (u[2] - v[2]) * (u[0] + v[0]);1377- normal[2] += (u[0] - v[0]) * (u[1] + v[1]);1378- }1379- if (normalize) {1380- p = normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2];1381- p = (float) (1.0 / sqrt(p));1382- normal[0] *= p;1383- normal[1] *= p;1384- normal[2] *= p;1385- }1386-}1387-1388-int stb_box_face_vertex_axis_side(int face_number, int vertex_number, int axis)1389-{1390- static int box_vertices[6][4][3] =1391- {1392- { { 1,1,1 }, { 1,0,1 }, { 1,0,0 }, { 1,1,0 } },1393- { { 0,0,0 }, { 0,0,1 }, { 0,1,1 }, { 0,1,0 } },1394- { { 0,0,0 }, { 0,1,0 }, { 1,1,0 }, { 1,0,0 } },1395- { { 0,0,0 }, { 1,0,0 }, { 1,0,1 }, { 0,0,1 } },1396- { { 1,1,1 }, { 0,1,1 }, { 0,0,1 }, { 1,0,1 } },1397- { { 1,1,1 }, { 1,1,0 }, { 0,1,0 }, { 0,1,1 } },1398- };1399- assert(face_number >= 0 && face_number < 6);1400- assert(vertex_number >= 0 && vertex_number < 4);1401- assert(axis >= 0 && axis < 3);1402- return box_vertices[face_number][vertex_number][axis];1403-}1404-1405-void stb_linear_controller(float *curpos, float target_pos, float acc, float deacc, float dt)1406-{1407- float sign = 1, p, cp = *curpos;1408- if (cp == target_pos) return;1409- if (target_pos < cp) {1410- target_pos = -target_pos;1411- cp = -cp;1412- sign = -1;1413- }1414- // first decelerate1415- if (cp < 0) {1416- p = cp + deacc * dt;1417- if (p > 0) {1418- p = 0;1419- dt = dt - cp / deacc;1420- if (dt < 0) dt = 0;1421- } else {1422- dt = 0;1423- }1424- cp = p;1425- }1426- // now accelerate1427- p = cp + acc*dt;1428- if (p > target_pos) p = target_pos;1429- *curpos = p * sign;1430- // @TODO: testing1431-}1432-1433-float stb_quadratic_controller(float target_pos, float curpos, float maxvel, float maxacc, float dt, float *curvel)1434-{1435- return 0; // @TODO1436-}1437-1438-int stb_float_eq(float x, float y, float delta, int max_ulps)1439-{1440- if (fabs(x-y) <= delta) return 1;1441- if (abs(*(int *)&x - *(int *)&y) <= max_ulps) return 1;1442- return 0;1443-}1444-1445-int stb_is_prime(unsigned int m)1446-{1447- unsigned int i,j;1448- if (m < 2) return 0;1449- if (m == 2) return 1;1450- if (!(m & 1)) return 0;1451- if (m % 3 == 0) return (m == 3);1452- for (i=5; (j=i*i), j <= m && j > i; i += 6) {1453- if (m % i == 0) return 0;1454- if (m % (i+2) == 0) return 0;1455- }1456- return 1;1457-}1458-1459-unsigned int stb_power_of_two_nearest_prime(int n)1460-{1461- static signed char tab[32] = { 0,0,0,0,1,0,-1,0,1,-1,-1,3,-1,0,-1,2,1,1462- 0,2,0,-1,-4,-1,5,-1,18,-2,15,2,-1,2,0 };1463- if (!tab[0]) {1464- int i;1465- for (i=0; i < 32; ++i)1466- tab[i] = (1 << i) + 2*tab[i] - 1;1467- tab[1] = 2;1468- tab[0] = 1;1469- }1470- if (n >= 32) return 0xfffffffb;1471- return tab[n];1472-}1473-1474-double stb_linear_remap(double x, double x_min, double x_max,1475- double out_min, double out_max)1476-{1477- return stb_lerp(stb_unlerp(x,x_min,x_max),out_min,out_max);1478-}1479-#endif1480-1481-// create a macro so it's faster, but you can get at the function pointer1482-#define stb_linear_remap(t,a,b,c,d) stb_lerp(stb_unlerp(t,a,b),c,d)1483-1484-1485-//////////////////////////////////////////////////////////////////////////////1486-//1487-// bit operations1488-//1489-1490-#define stb_big32(c) (((c)[0]<<24) + (c)[1]*65536 + (c)[2]*256 + (c)[3])1491-#define stb_little32(c) (((c)[3]<<24) + (c)[2]*65536 + (c)[1]*256 + (c)[0])1492-#define stb_big16(c) ((c)[0]*256 + (c)[1])1493-#define stb_little16(c) ((c)[1]*256 + (c)[0])1494-1495-STB_EXTERN int stb_bitcount(unsigned int a);1496-STB_EXTERN unsigned int stb_bitreverse8(unsigned char n);1497-STB_EXTERN unsigned int stb_bitreverse(unsigned int n);1498-1499-STB_EXTERN int stb_is_pow2(size_t);1500-STB_EXTERN int stb_log2_ceil(size_t);1501-STB_EXTERN int stb_log2_floor(size_t);1502-1503-STB_EXTERN int stb_lowbit8(unsigned int n);1504-STB_EXTERN int stb_highbit8(unsigned int n);1505-1506-#ifdef STB_DEFINE1507-int stb_bitcount(unsigned int a)1508-{1509- a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 21510- a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 41511- a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits1512- a = (a + (a >> 8)); // max 16 per 8 bits1513- a = (a + (a >> 16)); // max 32 per 8 bits1514- return a & 0xff;1515-}1516-1517-unsigned int stb_bitreverse8(unsigned char n)1518-{1519- n = ((n & 0xAA) >> 1) + ((n & 0x55) << 1);1520- n = ((n & 0xCC) >> 2) + ((n & 0x33) << 2);1521- return (unsigned char) ((n >> 4) + (n << 4));1522-}1523-1524-unsigned int stb_bitreverse(unsigned int n)1525-{1526- n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);1527- n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);1528- n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);1529- n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);1530- return (n >> 16) | (n << 16);1531-}1532-1533-int stb_is_pow2(size_t n)1534-{1535- return (n & (n-1)) == 0;1536-}1537-1538-// tricky use of 4-bit table to identify 5 bit positions (note the '-1')1539-// 3-bit table would require another tree level; 5-bit table wouldn't save one1540-#if defined(_WIN32) && !defined(__MINGW32__)1541-#pragma warning(push)1542-#pragma warning(disable: 4035) // disable warning about no return value1543-int stb_log2_floor(size_t n)1544-{1545- #if _MSC_VER > 17001546- unsigned long i;1547- #ifdef STB_PTR641548- _BitScanReverse64(&i, n);1549- #else1550- _BitScanReverse(&i, n);1551- #endif1552- return i != 0 ? i : -1;1553- #else1554- __asm {1555- bsr eax,n1556- jnz done1557- mov eax,-11558- }1559- done:;1560- #endif1561-}1562-#pragma warning(pop)1563-#else1564-int stb_log2_floor(size_t n)1565-{1566- static signed char log2_4[16] = { -1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3 };1567-1568-#ifdef STB_PTR641569- if (n >= ((size_t) 1u << 32))1570- return stb_log2_floor(n >> 32);1571-#endif1572-1573- // 2 compares if n < 16, 3 compares otherwise1574- if (n < (1U << 14))1575- if (n < (1U << 4)) return 0 + log2_4[n ];1576- else if (n < (1U << 9)) return 5 + log2_4[n >> 5];1577- else return 10 + log2_4[n >> 10];1578- else if (n < (1U << 24))1579- if (n < (1U << 19)) return 15 + log2_4[n >> 15];1580- else return 20 + log2_4[n >> 20];1581- else if (n < (1U << 29)) return 25 + log2_4[n >> 25];1582- else return 30 + log2_4[n >> 30];1583-}1584-#endif1585-1586-// define ceil from floor1587-int stb_log2_ceil(size_t n)1588-{1589- if (stb_is_pow2(n)) return stb_log2_floor(n);1590- else return 1 + stb_log2_floor(n);1591-}1592-1593-int stb_highbit8(unsigned int n)1594-{1595- return stb_log2_ceil(n&255);1596-}1597-1598-int stb_lowbit8(unsigned int n)1599-{1600- static signed char lowbit4[16] = { -1,0,1,0, 2,0,1,0, 3,0,1,0, 2,0,1,0 };1601- int k = lowbit4[n & 15];1602- if (k >= 0) return k;1603- k = lowbit4[(n >> 4) & 15];1604- if (k >= 0) return k+4;1605- return k;1606-}1607-#endif1608-1609-1610-1611-//////////////////////////////////////////////////////////////////////////////1612-//1613-// qsort Compare Routines1614-//1615-1616-#ifdef _WIN321617- #define stb_stricmp(a,b) stb_p_stricmp(a,b)1618- #define stb_strnicmp(a,b,n) stb_p_strnicmp(a,b,n)1619-#else1620- #define stb_stricmp(a,b) strcasecmp(a,b)1621- #define stb_strnicmp(a,b,n) strncasecmp(a,b,n)1622-#endif1623-1624-1625-STB_EXTERN int (*stb_intcmp(int offset))(const void *a, const void *b);1626-STB_EXTERN int (*stb_intcmprev(int offset))(const void *a, const void *b);1627-STB_EXTERN int (*stb_qsort_strcmp(int offset))(const void *a, const void *b);1628-STB_EXTERN int (*stb_qsort_stricmp(int offset))(const void *a, const void *b);1629-STB_EXTERN int (*stb_floatcmp(int offset))(const void *a, const void *b);1630-STB_EXTERN int (*stb_doublecmp(int offset))(const void *a, const void *b);1631-STB_EXTERN int (*stb_charcmp(int offset))(const void *a, const void *b);1632-1633-#ifdef STB_DEFINE1634-static int stb__intcmpoffset, stb__ucharcmpoffset, stb__strcmpoffset;1635-static int stb__floatcmpoffset, stb__doublecmpoffset;1636-static int stb__memcmpoffset, stb__memcmpsize;1637-1638-int stb__intcmp(const void *a, const void *b)1639-{1640- const int p = *(const int *) ((const char *) a + stb__intcmpoffset);1641- const int q = *(const int *) ((const char *) b + stb__intcmpoffset);1642- return p < q ? -1 : p > q;1643-}1644-1645-int stb__intcmprev(const void *a, const void *b)1646-{1647- const int p = *(const int *) ((const char *) a + stb__intcmpoffset);1648- const int q = *(const int *) ((const char *) b + stb__intcmpoffset);1649- return q < p ? -1 : q > p;1650-}1651-1652-int stb__ucharcmp(const void *a, const void *b)1653-{1654- const int p = *(const unsigned char *) ((const char *) a + stb__ucharcmpoffset);1655- const int q = *(const unsigned char *) ((const char *) b + stb__ucharcmpoffset);1656- return p < q ? -1 : p > q;1657-}1658-1659-int stb__floatcmp(const void *a, const void *b)1660-{1661- const float p = *(const float *) ((const char *) a + stb__floatcmpoffset);1662- const float q = *(const float *) ((const char *) b + stb__floatcmpoffset);1663- return p < q ? -1 : p > q;1664-}1665-1666-int stb__doublecmp(const void *a, const void *b)1667-{1668- const double p = *(const double *) ((const char *) a + stb__doublecmpoffset);1669- const double q = *(const double *) ((const char *) b + stb__doublecmpoffset);1670- return p < q ? -1 : p > q;1671-}1672-1673-int stb__qsort_strcmp(const void *a, const void *b)1674-{1675- const char *p = *(const char **) ((const char *) a + stb__strcmpoffset);1676- const char *q = *(const char **) ((const char *) b + stb__strcmpoffset);1677- return strcmp(p,q);1678-}1679-1680-int stb__qsort_stricmp(const void *a, const void *b)1681-{1682- const char *p = *(const char **) ((const char *) a + stb__strcmpoffset);1683- const char *q = *(const char **) ((const char *) b + stb__strcmpoffset);1684- return stb_stricmp(p,q);1685-}1686-1687-int stb__memcmp(const void *a, const void *b)1688-{1689- return memcmp((char *) a + stb__memcmpoffset, (char *) b + stb__memcmpoffset, stb__memcmpsize);1690-}1691-1692-int (*stb_intcmp(int offset))(const void *, const void *)1693-{1694- stb__intcmpoffset = offset;1695- return &stb__intcmp;1696-}1697-1698-int (*stb_intcmprev(int offset))(const void *, const void *)1699-{1700- stb__intcmpoffset = offset;1701- return &stb__intcmprev;1702-}1703-1704-int (*stb_ucharcmp(int offset))(const void *, const void *)1705-{1706- stb__ucharcmpoffset = offset;1707- return &stb__ucharcmp;1708-}1709-1710-int (*stb_qsort_strcmp(int offset))(const void *, const void *)1711-{1712- stb__strcmpoffset = offset;1713- return &stb__qsort_strcmp;1714-}1715-1716-int (*stb_qsort_stricmp(int offset))(const void *, const void *)1717-{1718- stb__strcmpoffset = offset;1719- return &stb__qsort_stricmp;1720-}1721-1722-int (*stb_floatcmp(int offset))(const void *, const void *)1723-{1724- stb__floatcmpoffset = offset;1725- return &stb__floatcmp;1726-}1727-1728-int (*stb_doublecmp(int offset))(const void *, const void *)1729-{1730- stb__doublecmpoffset = offset;1731- return &stb__doublecmp;1732-}1733-1734-int (*stb_memcmp(int offset, int size))(const void *, const void *)1735-{1736- stb__memcmpoffset = offset;1737- stb__memcmpsize = size;1738- return &stb__memcmp;1739-}1740-#endif1741-1742-//////////////////////////////////////////////////////////////////////////////1743-//1744-// Binary Search Toolkit1745-//1746-1747-typedef struct1748-{1749- int minval, maxval, guess;1750- int mode, step;1751-} stb_search;1752-1753-STB_EXTERN int stb_search_binary(stb_search *s, int minv, int maxv, int find_smallest);1754-STB_EXTERN int stb_search_open(stb_search *s, int minv, int find_smallest);1755-STB_EXTERN int stb_probe(stb_search *s, int compare, int *result); // return 0 when done1756-1757-#ifdef STB_DEFINE1758-enum1759-{1760- STB_probe_binary_smallest,1761- STB_probe_binary_largest,1762- STB_probe_open_smallest,1763- STB_probe_open_largest,1764-};1765-1766-static int stb_probe_guess(stb_search *s, int *result)1767-{1768- switch(s->mode) {1769- case STB_probe_binary_largest:1770- if (s->minval == s->maxval) {1771- *result = s->minval;1772- return 0;1773- }1774- assert(s->minval < s->maxval);1775- // if a < b, then a < p <= b1776- s->guess = s->minval + (((unsigned) s->maxval - s->minval + 1) >> 1);1777- break;1778-1779- case STB_probe_binary_smallest:1780- if (s->minval == s->maxval) {1781- *result = s->minval;1782- return 0;1783- }1784- assert(s->minval < s->maxval);1785- // if a < b, then a <= p < b1786- s->guess = s->minval + (((unsigned) s->maxval - s->minval) >> 1);1787- break;1788- case STB_probe_open_smallest:1789- case STB_probe_open_largest:1790- s->guess = s->maxval; // guess the current maxval1791- break;1792- }1793- *result = s->guess;1794- return 1;1795-}1796-1797-int stb_probe(stb_search *s, int compare, int *result)1798-{1799- switch(s->mode) {1800- case STB_probe_open_smallest:1801- case STB_probe_open_largest: {1802- if (compare <= 0) {1803- // then it lies within minval & maxval1804- if (s->mode == STB_probe_open_smallest)1805- s->mode = STB_probe_binary_smallest;1806- else1807- s->mode = STB_probe_binary_largest;1808- } else {1809- // otherwise, we need to probe larger1810- s->minval = s->maxval + 1;1811- s->maxval = s->minval + s->step;1812- s->step += s->step;1813- }1814- break;1815- }1816- case STB_probe_binary_smallest: {1817- // if compare < 0, then s->minval <= a < p1818- // if compare = 0, then s->minval <= a <= p1819- // if compare > 0, then p < a <= s->maxval1820- if (compare <= 0)1821- s->maxval = s->guess;1822- else1823- s->minval = s->guess+1;1824- break;1825- }1826- case STB_probe_binary_largest: {1827- // if compare < 0, then s->minval <= a < p1828- // if compare = 0, then p <= a <= s->maxval1829- // if compare > 0, then p < a <= s->maxval1830- if (compare < 0)1831- s->maxval = s->guess-1;1832- else1833- s->minval = s->guess;1834- break;1835- }1836- }1837- return stb_probe_guess(s, result);1838-}1839-1840-int stb_search_binary(stb_search *s, int minv, int maxv, int find_smallest)1841-{1842- int r;1843- if (maxv < minv) return minv-1;1844- s->minval = minv;1845- s->maxval = maxv;1846- s->mode = find_smallest ? STB_probe_binary_smallest : STB_probe_binary_largest;1847- stb_probe_guess(s, &r);1848- return r;1849-}1850-1851-int stb_search_open(stb_search *s, int minv, int find_smallest)1852-{1853- int r;1854- s->step = 4;1855- s->minval = minv;1856- s->maxval = minv+s->step;1857- s->mode = find_smallest ? STB_probe_open_smallest : STB_probe_open_largest;1858- stb_probe_guess(s, &r);1859- return r;1860-}1861-#endif1862-1863-//////////////////////////////////////////////////////////////////////////////1864-//1865-// String Processing1866-//1867-1868-#define stb_prefixi(s,t) (0==stb_strnicmp((s),(t),strlen(t)))1869-1870-enum stb_splitpath_flag1871-{1872- STB_PATH = 1,1873- STB_FILE = 2,1874- STB_EXT = 4,1875- STB_PATH_FILE = STB_PATH + STB_FILE,1876- STB_FILE_EXT = STB_FILE + STB_EXT,1877- STB_EXT_NO_PERIOD = 8,1878-};1879-1880-STB_EXTERN char * stb_skipwhite(char *s);1881-STB_EXTERN char * stb_trimwhite(char *s);1882-STB_EXTERN char * stb_skipnewline(char *s);1883-STB_EXTERN char * stb_strncpy(char *s, char *t, int n);1884-STB_EXTERN char * stb_substr(char *t, int n);1885-STB_EXTERN char * stb_duplower(char *s);1886-STB_EXTERN void stb_tolower (char *s);1887-STB_EXTERN char * stb_strchr2 (char *s, char p1, char p2);1888-STB_EXTERN char * stb_strrchr2(char *s, char p1, char p2);1889-STB_EXTERN char * stb_strtok(char *output, char *src, char *delimit);1890-STB_EXTERN char * stb_strtok_keep(char *output, char *src, char *delimit);1891-STB_EXTERN char * stb_strtok_invert(char *output, char *src, char *allowed);1892-STB_EXTERN char * stb_dupreplace(char *s, char *find, char *replace);1893-STB_EXTERN void stb_replaceinplace(char *s, char *find, char *replace);1894-STB_EXTERN char * stb_splitpath(char *output, char *src, int flag);1895-STB_EXTERN char * stb_splitpathdup(char *src, int flag);1896-STB_EXTERN char * stb_replacedir(char *output, char *src, char *dir);1897-STB_EXTERN char * stb_replaceext(char *output, char *src, char *ext);1898-STB_EXTERN void stb_fixpath(char *path);1899-STB_EXTERN char * stb_shorten_path_readable(char *path, int max_len);1900-STB_EXTERN int stb_suffix (char *s, char *t);1901-STB_EXTERN int stb_suffixi(char *s, char *t);1902-STB_EXTERN int stb_prefix (char *s, char *t);1903-STB_EXTERN char * stb_strichr(char *s, char t);1904-STB_EXTERN char * stb_stristr(char *s, char *t);1905-STB_EXTERN int stb_prefix_count(char *s, char *t);1906-STB_EXTERN const char * stb_plural(int n); // "s" or ""1907-STB_EXTERN size_t stb_strscpy(char *d, const char *s, size_t n);1908-1909-STB_EXTERN char **stb_tokens(char *src, char *delimit, int *count);1910-STB_EXTERN char **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out);1911-STB_EXTERN char **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out);1912-STB_EXTERN char **stb_tokens_allowempty(char *src, char *delimit, int *count);1913-STB_EXTERN char **stb_tokens_stripwhite(char *src, char *delimit, int *count);1914-STB_EXTERN char **stb_tokens_withdelim(char *src, char *delimit, int *count);1915-STB_EXTERN char **stb_tokens_quoted(char *src, char *delimit, int *count);1916-// with 'quoted', allow delimiters to appear inside quotation marks, and don't1917-// strip whitespace inside them (and we delete the quotation marks unless they1918-// appear back to back, in which case they're considered escaped)1919-1920-#ifdef STB_DEFINE1921-1922-size_t stb_strscpy(char *d, const char *s, size_t n)1923-{1924- size_t len = strlen(s);1925- if (len >= n) {1926- if (n) d[0] = 0;1927- return 0;1928- }1929- stb_p_strcpy_s(d,n,s);1930- return len;1931-}1932-1933-const char *stb_plural(int n)1934-{1935- return n == 1 ? "" : "s";1936-}1937-1938-int stb_prefix(char *s, char *t)1939-{1940- while (*t)1941- if (*s++ != *t++)1942- return STB_FALSE;1943- return STB_TRUE;1944-}1945-1946-int stb_prefix_count(char *s, char *t)1947-{1948- int c=0;1949- while (*t) {1950- if (*s++ != *t++)1951- break;1952- ++c;1953- }1954- return c;1955-}1956-1957-int stb_suffix(char *s, char *t)1958-{1959- size_t n = strlen(s);1960- size_t m = strlen(t);1961- if (m <= n)1962- return 0 == strcmp(s+n-m, t);1963- else1964- return 0;1965-}1966-1967-int stb_suffixi(char *s, char *t)1968-{1969- size_t n = strlen(s);1970- size_t m = strlen(t);1971- if (m <= n)1972- return 0 == stb_stricmp(s+n-m, t);1973- else1974- return 0;1975-}1976-1977-// originally I was using this table so that I could create known sentinel1978-// values--e.g. change whitetable[0] to be true if I was scanning for whitespace,1979-// and false if I was scanning for nonwhite. I don't appear to be using that1980-// functionality anymore (I do for tokentable, though), so just replace it1981-// with isspace()1982-char *stb_skipwhite(char *s)1983-{1984- while (isspace((unsigned char) *s)) ++s;1985- return s;1986-}1987-1988-char *stb_skipnewline(char *s)1989-{1990- if (s[0] == '\r' || s[0] == '\n') {1991- if (s[0]+s[1] == '\r' + '\n') ++s;1992- ++s;1993- }1994- return s;1995-}1996-1997-char *stb_trimwhite(char *s)1998-{1999- int i,n;2000- s = stb_skipwhite(s);2001- n = (int) strlen(s);2002- for (i=n-1; i >= 0; --i)2003- if (!isspace(s[i]))2004- break;2005- s[i+1] = 0;2006- return s;2007-}2008-2009-char *stb_strncpy(char *s, char *t, int n)2010-{2011- stb_p_strncpy_s(s,n+1,t,n);2012- s[n] = 0;2013- return s;2014-}2015-2016-char *stb_substr(char *t, int n)2017-{2018- char *a;2019- int z = (int) strlen(t);2020- if (z < n) n = z;2021- a = (char *) malloc(n+1);2022- stb_p_strncpy_s(a,n+1,t,n);2023- a[n] = 0;2024- return a;2025-}2026-2027-char *stb_duplower(char *s)2028-{2029- char *p = stb_p_strdup(s), *q = p;2030- while (*q) {2031- *q = tolower(*q);2032- ++q;2033- }2034- return p;2035-}2036-2037-void stb_tolower(char *s)2038-{2039- while (*s) {2040- *s = tolower(*s);2041- ++s;2042- }2043-}2044-2045-char *stb_strchr2(char *s, char x, char y)2046-{2047- for(; *s; ++s)2048- if (*s == x || *s == y)2049- return s;2050- return NULL;2051-}2052-2053-char *stb_strrchr2(char *s, char x, char y)2054-{2055- char *r = NULL;2056- for(; *s; ++s)2057- if (*s == x || *s == y)2058- r = s;2059- return r;2060-}2061-2062-char *stb_strichr(char *s, char t)2063-{2064- if (tolower(t) == toupper(t))2065- return strchr(s,t);2066- return stb_strchr2(s, (char) tolower(t), (char) toupper(t));2067-}2068-2069-char *stb_stristr(char *s, char *t)2070-{2071- size_t n = strlen(t);2072- char *z;2073- if (n==0) return s;2074- while ((z = stb_strichr(s, *t)) != NULL) {2075- if (0==stb_strnicmp(z, t, n))2076- return z;2077- s = z+1;2078- }2079- return NULL;2080-}2081-2082-static char *stb_strtok_raw(char *output, char *src, char *delimit, int keep, int invert)2083-{2084- if (invert) {2085- while (*src && strchr(delimit, *src) != NULL) {2086- *output++ = *src++;2087- }2088- } else {2089- while (*src && strchr(delimit, *src) == NULL) {2090- *output++ = *src++;2091- }2092- }2093- *output = 0;2094- if (keep)2095- return src;2096- else2097- return *src ? src+1 : src;2098-}2099-2100-char *stb_strtok(char *output, char *src, char *delimit)2101-{2102- return stb_strtok_raw(output, src, delimit, 0, 0);2103-}2104-2105-char *stb_strtok_keep(char *output, char *src, char *delimit)2106-{2107- return stb_strtok_raw(output, src, delimit, 1, 0);2108-}2109-2110-char *stb_strtok_invert(char *output, char *src, char *delimit)2111-{2112- return stb_strtok_raw(output, src, delimit, 1,1);2113-}2114-2115-static char **stb_tokens_raw(char *src_, char *delimit, int *count,2116- int stripwhite, int allow_empty, char *start, char *end)2117-{2118- int nested = 0;2119- unsigned char *src = (unsigned char *) src_;2120- static char stb_tokentable[256]; // rely on static initializion to 02121- static char stable[256],etable[256];2122- char *out;2123- char **result;2124- int num=0;2125- unsigned char *s;2126-2127- s = (unsigned char *) delimit; while (*s) stb_tokentable[*s++] = 1;2128- if (start) {2129- s = (unsigned char *) start; while (*s) stable[*s++] = 1;2130- s = (unsigned char *) end; if (s) while (*s) stable[*s++] = 1;2131- s = (unsigned char *) end; if (s) while (*s) etable[*s++] = 1;2132- }2133- stable[0] = 1;2134-2135- // two passes through: the first time, counting how many2136- s = (unsigned char *) src;2137- while (*s) {2138- // state: just found delimiter2139- // skip further delimiters2140- if (!allow_empty) {2141- stb_tokentable[0] = 0;2142- while (stb_tokentable[*s])2143- ++s;2144- if (!*s) break;2145- }2146- ++num;2147- // skip further non-delimiters2148- stb_tokentable[0] = 1;2149- if (stripwhite == 2) { // quoted strings2150- while (!stb_tokentable[*s]) {2151- if (*s != '"')2152- ++s;2153- else {2154- ++s;2155- if (*s == '"')2156- ++s; // "" -> ", not start a string2157- else {2158- // begin a string2159- while (*s) {2160- if (s[0] == '"') {2161- if (s[1] == '"') s += 2; // "" -> "2162- else { ++s; break; } // terminating "2163- } else2164- ++s;2165- }2166- }2167- }2168- }2169- } else2170- while (nested || !stb_tokentable[*s]) {2171- if (stable[*s]) {2172- if (!*s) break;2173- if (end ? etable[*s] : nested)2174- --nested;2175- else2176- ++nested;2177- }2178- ++s;2179- }2180- if (allow_empty) {2181- if (*s) ++s;2182- }2183- }2184- // now num has the actual count... malloc our output structure2185- // need space for all the strings: strings won't be any longer than2186- // original input, since for every '\0' there's at least one delimiter2187- result = (char **) malloc(sizeof(*result) * (num+1) + (s-src+1));2188- if (result == NULL) return result;2189- out = (char *) (result + (num+1));2190- // second pass: copy out the data2191- s = (unsigned char *) src;2192- num = 0;2193- nested = 0;2194- while (*s) {2195- char *last_nonwhite;2196- // state: just found delimiter2197- // skip further delimiters2198- if (!allow_empty) {2199- stb_tokentable[0] = 0;2200- if (stripwhite)2201- while (stb_tokentable[*s] || isspace(*s))2202- ++s;2203- else2204- while (stb_tokentable[*s])2205- ++s;2206- } else if (stripwhite) {2207- while (isspace(*s)) ++s;2208- }2209- if (!*s) break;2210- // we're past any leading delimiters and whitespace2211- result[num] = out;2212- ++num;2213- // copy non-delimiters2214- stb_tokentable[0] = 1;2215- last_nonwhite = out-1;2216- if (stripwhite == 2) {2217- while (!stb_tokentable[*s]) {2218- if (*s != '"') {2219- if (!isspace(*s)) last_nonwhite = out;2220- *out++ = *s++;2221- } else {2222- ++s;2223- if (*s == '"') {2224- if (!isspace(*s)) last_nonwhite = out;2225- *out++ = *s++; // "" -> ", not start string2226- } else {2227- // begin a quoted string2228- while (*s) {2229- if (s[0] == '"') {2230- if (s[1] == '"') { *out++ = *s; s += 2; }2231- else { ++s; break; } // terminating "2232- } else2233- *out++ = *s++;2234- }2235- last_nonwhite = out-1; // all in quotes counts as non-white2236- }2237- }2238- }2239- } else {2240- while (nested || !stb_tokentable[*s]) {2241- if (!isspace(*s)) last_nonwhite = out;2242- if (stable[*s]) {2243- if (!*s) break;2244- if (end ? etable[*s] : nested)2245- --nested;2246- else2247- ++nested;2248- }2249- *out++ = *s++;2250- }2251- }2252-2253- if (stripwhite) // rewind to last non-whitespace char2254- out = last_nonwhite+1;2255- *out++ = '\0';2256-2257- if (*s) ++s; // skip delimiter2258- }2259- s = (unsigned char *) delimit; while (*s) stb_tokentable[*s++] = 0;2260- if (start) {2261- s = (unsigned char *) start; while (*s) stable[*s++] = 1;2262- s = (unsigned char *) end; if (s) while (*s) stable[*s++] = 1;2263- s = (unsigned char *) end; if (s) while (*s) etable[*s++] = 1;2264- }2265- if (count != NULL) *count = num;2266- result[num] = 0;2267- return result;2268-}2269-2270-char **stb_tokens(char *src, char *delimit, int *count)2271-{2272- return stb_tokens_raw(src,delimit,count,0,0,0,0);2273-}2274-2275-char **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out)2276-{2277- return stb_tokens_raw(src,delimit,count,0,0,nest_in,nest_out);2278-}2279-2280-char **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out)2281-{2282- return stb_tokens_raw(src,delimit,count,0,1,nest_in,nest_out);2283-}2284-2285-char **stb_tokens_allowempty(char *src, char *delimit, int *count)2286-{2287- return stb_tokens_raw(src,delimit,count,0,1,0,0);2288-}2289-2290-char **stb_tokens_stripwhite(char *src, char *delimit, int *count)2291-{2292- return stb_tokens_raw(src,delimit,count,1,1,0,0);2293-}2294-2295-char **stb_tokens_quoted(char *src, char *delimit, int *count)2296-{2297- return stb_tokens_raw(src,delimit,count,2,1,0,0);2298-}2299-2300-char *stb_dupreplace(char *src, char *find, char *replace)2301-{2302- size_t len_find = strlen(find);2303- size_t len_replace = strlen(replace);2304- int count = 0;2305-2306- char *s,*p,*q;2307-2308- s = strstr(src, find);2309- if (s == NULL) return stb_p_strdup(src);2310- do {2311- ++count;2312- s = strstr(s + len_find, find);2313- } while (s != NULL);2314-2315- p = (char *) malloc(strlen(src) + count * (len_replace - len_find) + 1);2316- if (p == NULL) return p;2317- q = p;2318- s = src;2319- for (;;) {2320- char *t = strstr(s, find);2321- if (t == NULL) {2322- stb_p_strcpy_s(q,strlen(src)+count*(len_replace-len_find)+1,s);2323- assert(strlen(p) == strlen(src) + count*(len_replace-len_find));2324- return p;2325- }2326- memcpy(q, s, t-s);2327- q += t-s;2328- memcpy(q, replace, len_replace);2329- q += len_replace;2330- s = t + len_find;2331- }2332-}2333-2334-void stb_replaceinplace(char *src, char *find, char *replace)2335-{2336- size_t len_find = strlen(find);2337- size_t len_replace = strlen(replace);2338- int delta;2339-2340- char *s,*p,*q;2341-2342- delta = (int) (len_replace - len_find);2343- assert(delta <= 0);2344- if (delta > 0) return;2345-2346- p = strstr(src, find);2347- if (p == NULL) return;2348-2349- s = q = p;2350- while (*s) {2351- memcpy(q, replace, len_replace);2352- p += len_find;2353- q += len_replace;2354- s = strstr(p, find);2355- if (s == NULL) s = p + strlen(p);2356- memmove(q, p, s-p);2357- q += s-p;2358- p = s;2359- }2360- *q = 0;2361-}2362-2363-void stb_fixpath(char *path)2364-{2365- for(; *path; ++path)2366- if (*path == '\\')2367- *path = '/';2368-}2369-2370-void stb__add_section(char *buffer, char *data, ptrdiff_t curlen, ptrdiff_t newlen)2371-{2372- if (newlen < curlen) {2373- ptrdiff_t z1 = newlen >> 1, z2 = newlen-z1;2374- memcpy(buffer, data, z1-1);2375- buffer[z1-1] = '.';2376- buffer[z1-0] = '.';2377- memcpy(buffer+z1+1, data+curlen-z2+1, z2-1);2378- } else2379- memcpy(buffer, data, curlen);2380-}2381-2382-char * stb_shorten_path_readable(char *path, int len)2383-{2384- static char buffer[1024];2385- ptrdiff_t n = strlen(path),n1,n2,r1,r2;2386- char *s;2387- if (n <= len) return path;2388- if (len > 1024) return path;2389- s = stb_strrchr2(path, '/', '\\');2390- if (s) {2391- n1 = s - path + 1;2392- n2 = n - n1;2393- ++s;2394- } else {2395- n1 = 0;2396- n2 = n;2397- s = path;2398- }2399- // now we need to reduce r1 and r2 so that they fit in len2400- if (n1 < len>>1) {2401- r1 = n1;2402- r2 = len - r1;2403- } else if (n2 < len >> 1) {2404- r2 = n2;2405- r1 = len - r2;2406- } else {2407- r1 = n1 * len / n;2408- r2 = n2 * len / n;2409- if (r1 < len>>2) r1 = len>>2, r2 = len-r1;2410- if (r2 < len>>2) r2 = len>>2, r1 = len-r2;2411- }2412- assert(r1 <= n1 && r2 <= n2);2413- if (n1)2414- stb__add_section(buffer, path, n1, r1);2415- stb__add_section(buffer+r1, s, n2, r2);2416- buffer[len] = 0;2417- return buffer;2418-}2419-2420-static char *stb__splitpath_raw(char *buffer, char *path, int flag)2421-{2422- ptrdiff_t len=0,x,y, n = (int) strlen(path), f1,f2;2423- char *s = stb_strrchr2(path, '/', '\\');2424- char *t = strrchr(path, '.');2425- if (s && t && t < s) t = NULL;2426- if (s) ++s;2427-2428- if (flag == STB_EXT_NO_PERIOD)2429- flag |= STB_EXT;2430-2431- if (!(flag & (STB_PATH | STB_FILE | STB_EXT))) return NULL;2432-2433- f1 = s == NULL ? 0 : s-path; // start of filename2434- f2 = t == NULL ? n : t-path; // just past end of filename2435-2436- if (flag & STB_PATH) {2437- x = 0; if (f1 == 0 && flag == STB_PATH) len=2;2438- } else if (flag & STB_FILE) {2439- x = f1;2440- } else {2441- x = f2;2442- if (flag & STB_EXT_NO_PERIOD)2443- if (path[x] == '.')2444- ++x;2445- }2446-2447- if (flag & STB_EXT)2448- y = n;2449- else if (flag & STB_FILE)2450- y = f2;2451- else2452- y = f1;2453-2454- if (buffer == NULL) {2455- buffer = (char *) malloc(y-x + len + 1);2456- if (!buffer) return NULL;2457- }2458-2459- if (len) { stb_p_strcpy_s(buffer, 3, "./"); return buffer; }2460- stb_strncpy(buffer, path+(int)x, (int)(y-x));2461- return buffer;2462-}2463-2464-char *stb_splitpath(char *output, char *src, int flag)2465-{2466- return stb__splitpath_raw(output, src, flag);2467-}2468-2469-char *stb_splitpathdup(char *src, int flag)2470-{2471- return stb__splitpath_raw(NULL, src, flag);2472-}2473-2474-char *stb_replacedir(char *output, char *src, char *dir)2475-{2476- char buffer[4096];2477- stb_splitpath(buffer, src, STB_FILE | STB_EXT);2478- if (dir)2479- stb_p_sprintf(output stb_p_size(9999), "%s/%s", dir, buffer);2480- else2481- stb_p_strcpy_s(output, sizeof(buffer), buffer); // @UNSAFE2482- return output;2483-}2484-2485-char *stb_replaceext(char *output, char *src, char *ext)2486-{2487- char buffer[4096];2488- stb_splitpath(buffer, src, STB_PATH | STB_FILE);2489- if (ext)2490- stb_p_sprintf(output stb_p_size(9999), "%s.%s", buffer, ext[0] == '.' ? ext+1 : ext);2491- else2492- stb_p_strcpy_s(output, sizeof(buffer), buffer); // @UNSAFE2493- return output;2494-}2495-#endif2496-2497-//////////////////////////////////////////////////////////////////////////////2498-//2499-// stb_alloc - hierarchical allocator2500-//2501-// inspired by http://swapped.cc/halloc2502-//2503-//2504-// When you alloc a given block through stb_alloc, you have these choices:2505-//2506-// 1. does it have a parent?2507-// 2. can it have children?2508-// 3. can it be freed directly?2509-// 4. is it transferrable?2510-// 5. what is its alignment?2511-//2512-// Here are interesting combinations of those:2513-//2514-// children free transfer alignment2515-// arena Y Y N n/a2516-// no-overhead, chunked N N N normal2517-// string pool alloc N N N 12518-// parent-ptr, chunked Y N N normal2519-// low-overhead, unchunked N Y Y normal2520-// general purpose alloc Y Y Y normal2521-//2522-// Unchunked allocations will probably return 16-aligned pointers. If2523-// we 16-align the results, we have room for 4 pointers. For smaller2524-// allocations that allow finer alignment, we can reduce the pointers.2525-//2526-// The strategy is that given a pointer, assuming it has a header (only2527-// the no-overhead allocations have no header), we can determine the2528-// type of the header fields, and the number of them, by stepping backwards2529-// through memory and looking at the tags in the bottom bits.2530-//2531-// Implementation strategy:2532-// chunked allocations come from the middle of chunks, and can't2533-// be freed. thefore they do not need to be on a sibling chain.2534-// they may need child pointers if they have children.2535-//2536-// chunked, with-children2537-// void *parent;2538-//2539-// unchunked, no-children -- reduced storage2540-// void *next_sibling;2541-// void *prev_sibling_nextp;2542-//2543-// unchunked, general2544-// void *first_child;2545-// void *next_sibling;2546-// void *prev_sibling_nextp;2547-// void *chunks;2548-//2549-// so, if we code each of these fields with different bit patterns2550-// (actually same one for next/prev/child), then we can identify which2551-// each one is from the last field.2552-2553-STB_EXTERN void stb_free(void *p);2554-STB_EXTERN void *stb_malloc_global(size_t size);2555-STB_EXTERN void *stb_malloc(void *context, size_t size);2556-STB_EXTERN void *stb_malloc_nofree(void *context, size_t size);2557-STB_EXTERN void *stb_malloc_leaf(void *context, size_t size);2558-STB_EXTERN void *stb_malloc_raw(void *context, size_t size);2559-STB_EXTERN void *stb_realloc(void *ptr, size_t newsize);2560-2561-STB_EXTERN void stb_reassign(void *new_context, void *ptr);2562-STB_EXTERN void stb_malloc_validate(void *p, void *parent);2563-2564-extern int stb_alloc_chunk_size ;2565-extern int stb_alloc_count_free ;2566-extern int stb_alloc_count_alloc;2567-extern int stb_alloc_alignment ;2568-2569-#ifdef STB_DEFINE2570-2571-int stb_alloc_chunk_size = 65536;2572-int stb_alloc_count_free = 0;2573-int stb_alloc_count_alloc = 0;2574-int stb_alloc_alignment = -16;2575-2576-typedef struct stb__chunk2577-{2578- struct stb__chunk *next;2579- int data_left;2580- int alloc;2581-} stb__chunk;2582-2583-typedef struct2584-{2585- void * next;2586- void ** prevn;2587-} stb__nochildren;2588-2589-typedef struct2590-{2591- void ** prevn;2592- void * child;2593- void * next;2594- stb__chunk *chunks;2595-} stb__alloc;2596-2597-typedef struct2598-{2599- stb__alloc *parent;2600-} stb__chunked;2601-2602-#define STB__PARENT 12603-#define STB__CHUNKS 22604-2605-typedef enum2606-{2607- STB__nochildren = 0,2608- STB__chunked = STB__PARENT,2609- STB__alloc = STB__CHUNKS,2610-2611- STB__chunk_raw = 4,2612-} stb__alloc_type;2613-2614-// these functions set the bottom bits of a pointer efficiently2615-#define STB__DECODE(x,v) ((void *) ((char *) (x) - (v)))2616-#define STB__ENCODE(x,v) ((void *) ((char *) (x) + (v)))2617-2618-#define stb__parent(z) (stb__alloc *) STB__DECODE((z)->parent, STB__PARENT)2619-#define stb__chunks(z) (stb__chunk *) STB__DECODE((z)->chunks, STB__CHUNKS)2620-2621-#define stb__setparent(z,p) (z)->parent = (stb__alloc *) STB__ENCODE((p), STB__PARENT)2622-#define stb__setchunks(z,c) (z)->chunks = (stb__chunk *) STB__ENCODE((c), STB__CHUNKS)2623-2624-static stb__alloc stb__alloc_global =2625-{2626- NULL,2627- NULL,2628- NULL,2629- (stb__chunk *) STB__ENCODE(NULL, STB__CHUNKS)2630-};2631-2632-static stb__alloc_type stb__identify(void *p)2633-{2634- void **q = (void **) p;2635- return (stb__alloc_type) ((stb_uinta) q[-1] & 3);2636-}2637-2638-static void *** stb__prevn(void *p)2639-{2640- if (stb__identify(p) == STB__alloc) {2641- stb__alloc *s = (stb__alloc *) p - 1;2642- return &s->prevn;2643- } else {2644- stb__nochildren *s = (stb__nochildren *) p - 1;2645- return &s->prevn;2646- }2647-}2648-2649-void stb_free(void *p)2650-{2651- if (p == NULL) return;2652-2653- // count frees so that unit tests can see what's happening2654- ++stb_alloc_count_free;2655-2656- switch(stb__identify(p)) {2657- case STB__chunked:2658- // freeing a chunked-block with children does nothing;2659- // they only get freed when the parent does2660- // surely this is wrong, and it should free them immediately?2661- // otherwise how are they getting put on the right chain?2662- return;2663- case STB__nochildren: {2664- stb__nochildren *s = (stb__nochildren *) p - 1;2665- // unlink from sibling chain2666- *(s->prevn) = s->next;2667- if (s->next)2668- *stb__prevn(s->next) = s->prevn;2669- free(s);2670- return;2671- }2672- case STB__alloc: {2673- stb__alloc *s = (stb__alloc *) p - 1;2674- stb__chunk *c, *n;2675- void *q;2676-2677- // unlink from sibling chain, if any2678- *(s->prevn) = s->next;2679- if (s->next)2680- *stb__prevn(s->next) = s->prevn;2681-2682- // first free chunks2683- c = (stb__chunk *) stb__chunks(s);2684- while (c != NULL) {2685- n = c->next;2686- stb_alloc_count_free += c->alloc;2687- free(c);2688- c = n;2689- }2690-2691- // validating2692- stb__setchunks(s,NULL);2693- s->prevn = NULL;2694- s->next = NULL;2695-2696- // now free children2697- while ((q = s->child) != NULL) {2698- stb_free(q);2699- }2700-2701- // now free self2702- free(s);2703- return;2704- }2705- default:2706- assert(0); /* NOTREACHED */2707- }2708-}2709-2710-void stb_malloc_validate(void *p, void *parent)2711-{2712- if (p == NULL) return;2713-2714- switch(stb__identify(p)) {2715- case STB__chunked:2716- return;2717- case STB__nochildren: {2718- stb__nochildren *n = (stb__nochildren *) p - 1;2719- if (n->prevn)2720- assert(*n->prevn == p);2721- if (n->next) {2722- assert(*stb__prevn(n->next) == &n->next);2723- stb_malloc_validate(n, parent);2724- }2725- return;2726- }2727- case STB__alloc: {2728- stb__alloc *s = (stb__alloc *) p - 1;2729-2730- if (s->prevn)2731- assert(*s->prevn == p);2732-2733- if (s->child) {2734- assert(*stb__prevn(s->child) == &s->child);2735- stb_malloc_validate(s->child, p);2736- }2737-2738- if (s->next) {2739- assert(*stb__prevn(s->next) == &s->next);2740- stb_malloc_validate(s->next, parent);2741- }2742- return;2743- }2744- default:2745- assert(0); /* NOTREACHED */2746- }2747-}2748-2749-static void * stb__try_chunk(stb__chunk *c, int size, int align, int pre_align)2750-{2751- char *memblock = (char *) (c+1), *q;2752- stb_inta iq;2753- int start_offset;2754-2755- // we going to allocate at the end of the chunk, not the start. confusing,2756- // but it means we don't need both a 'limit' and a 'cur', just a 'cur'.2757- // the block ends at: p + c->data_left2758- // then we move back by size2759- start_offset = c->data_left - size;2760-2761- // now we need to check the alignment of that2762- q = memblock + start_offset;2763- iq = (stb_inta) q;2764- assert(sizeof(q) == sizeof(iq));2765-2766- // suppose align = 22767- // then we need to retreat iq far enough that (iq & (2-1)) == 02768- // to get (iq & (align-1)) = 0 requires subtracting (iq & (align-1))2769-2770- start_offset -= iq & (align-1);2771- assert(((stb_uinta) (memblock+start_offset) & (align-1)) == 0);2772-2773- // now, if that + pre_align works, go for it!2774- start_offset -= pre_align;2775-2776- if (start_offset >= 0) {2777- c->data_left = start_offset;2778- return memblock + start_offset;2779- }2780-2781- return NULL;2782-}2783-2784-static void stb__sort_chunks(stb__alloc *src)2785-{2786- // of the first two chunks, put the chunk with more data left in it first2787- stb__chunk *c = stb__chunks(src), *d;2788- if (c == NULL) return;2789- d = c->next;2790- if (d == NULL) return;2791- if (c->data_left > d->data_left) return;2792-2793- c->next = d->next;2794- d->next = c;2795- stb__setchunks(src, d);2796-}2797-2798-static void * stb__alloc_chunk(stb__alloc *src, int size, int align, int pre_align)2799-{2800- void *p;2801- stb__chunk *c = stb__chunks(src);2802-2803- if (c && size <= stb_alloc_chunk_size) {2804-2805- p = stb__try_chunk(c, size, align, pre_align);2806- if (p) { ++c->alloc; return p; }2807-2808- // try a second chunk to reduce wastage2809- if (c->next) {2810- p = stb__try_chunk(c->next, size, align, pre_align);2811- if (p) { ++c->alloc; return p; }2812-2813- // put the bigger chunk first, since the second will get buried2814- // the upshot of this is that, until it gets allocated from, chunk #22815- // is always the largest remaining chunk. (could formalize2816- // this with a heap!)2817- stb__sort_chunks(src);2818- c = stb__chunks(src);2819- }2820- }2821-2822- // allocate a new chunk2823- {2824- stb__chunk *n;2825-2826- int chunk_size = stb_alloc_chunk_size;2827- // we're going to allocate a new chunk to put this in2828- if (size > chunk_size)2829- chunk_size = size;2830-2831- assert(sizeof(*n) + pre_align <= 16);2832-2833- // loop trying to allocate a large enough chunk2834- // the loop is because the alignment may cause problems if it's big...2835- // and we don't know what our chunk alignment is going to be2836- while (1) {2837- n = (stb__chunk *) malloc(16 + chunk_size);2838- if (n == NULL) return NULL;2839-2840- n->data_left = chunk_size - sizeof(*n);2841-2842- p = stb__try_chunk(n, size, align, pre_align);2843- if (p != NULL) {2844- n->next = c;2845- stb__setchunks(src, n);2846-2847- // if we just used up the whole block immediately,2848- // move the following chunk up2849- n->alloc = 1;2850- if (size == chunk_size)2851- stb__sort_chunks(src);2852-2853- return p;2854- }2855-2856- free(n);2857- chunk_size += 16+align;2858- }2859- }2860-}2861-2862-static stb__alloc * stb__get_context(void *context)2863-{2864- if (context == NULL) {2865- return &stb__alloc_global;2866- } else {2867- int u = stb__identify(context);2868- // if context is chunked, grab parent2869- if (u == STB__chunked) {2870- stb__chunked *s = (stb__chunked *) context - 1;2871- return stb__parent(s);2872- } else {2873- return (stb__alloc *) context - 1;2874- }2875- }2876-}2877-2878-static void stb__insert_alloc(stb__alloc *src, stb__alloc *s)2879-{2880- s->prevn = &src->child;2881- s->next = src->child;2882- src->child = s+1;2883- if (s->next)2884- *stb__prevn(s->next) = &s->next;2885-}2886-2887-static void stb__insert_nochild(stb__alloc *src, stb__nochildren *s)2888-{2889- s->prevn = &src->child;2890- s->next = src->child;2891- src->child = s+1;2892- if (s->next)2893- *stb__prevn(s->next) = &s->next;2894-}2895-2896-static void * malloc_base(void *context, size_t size, stb__alloc_type t, int align)2897-{2898- void *p;2899-2900- stb__alloc *src = stb__get_context(context);2901-2902- if (align <= 0) {2903- // compute worst-case C packed alignment2904- // e.g. a 24-byte struct is 8-aligned2905- int align_proposed = 1 << stb_lowbit8((unsigned int) size);2906-2907- if (align_proposed < 0)2908- align_proposed = 4;2909-2910- if (align_proposed == 0) {2911- if (size == 0)2912- align_proposed = 1;2913- else2914- align_proposed = 256;2915- }2916-2917- // a negative alignment means 'don't align any larger2918- // than this'; so -16 means we align 1,2,4,8, or 162919-2920- if (align < 0) {2921- if (align_proposed > -align)2922- align_proposed = -align;2923- }2924-2925- align = align_proposed;2926- }2927-2928- assert(stb_is_pow2(align));2929-2930- // don't cause misalignment when allocating nochildren2931- if (t == STB__nochildren && align > 8)2932- t = STB__alloc;2933-2934- switch (t) {2935- case STB__alloc: {2936- stb__alloc *s = (stb__alloc *) malloc(size + sizeof(*s));2937- if (s == NULL) return NULL;2938- p = s+1;2939- s->child = NULL;2940- stb__insert_alloc(src, s);2941-2942- stb__setchunks(s,NULL);2943- break;2944- }2945-2946- case STB__nochildren: {2947- stb__nochildren *s = (stb__nochildren *) malloc(size + sizeof(*s));2948- if (s == NULL) return NULL;2949- p = s+1;2950- stb__insert_nochild(src, s);2951- break;2952- }2953-2954- case STB__chunk_raw: {2955- p = stb__alloc_chunk(src, (int) size, align, 0);2956- if (p == NULL) return NULL;2957- break;2958- }2959-2960- case STB__chunked: {2961- stb__chunked *s;2962- if (align < sizeof(stb_uintptr)) align = sizeof(stb_uintptr);2963- s = (stb__chunked *) stb__alloc_chunk(src, (int) size, align, sizeof(*s));2964- if (s == NULL) return NULL;2965- stb__setparent(s, src);2966- p = s+1;2967- break;2968- }2969-2970- default: p = NULL; assert(0); /* NOTREACHED */2971- }2972-2973- ++stb_alloc_count_alloc;2974- return p;2975-}2976-2977-void *stb_malloc_global(size_t size)2978-{2979- return malloc_base(NULL, size, STB__alloc, stb_alloc_alignment);2980-}2981-2982-void *stb_malloc(void *context, size_t size)2983-{2984- return malloc_base(context, size, STB__alloc, stb_alloc_alignment);2985-}2986-2987-void *stb_malloc_nofree(void *context, size_t size)2988-{2989- return malloc_base(context, size, STB__chunked, stb_alloc_alignment);2990-}2991-2992-void *stb_malloc_leaf(void *context, size_t size)2993-{2994- return malloc_base(context, size, STB__nochildren, stb_alloc_alignment);2995-}2996-2997-void *stb_malloc_raw(void *context, size_t size)2998-{2999- return malloc_base(context, size, STB__chunk_raw, stb_alloc_alignment);3000-}3001-3002-char *stb_malloc_string(void *context, size_t size)3003-{3004- return (char *) malloc_base(context, size, STB__chunk_raw, 1);3005-}3006-3007-void *stb_realloc(void *ptr, size_t newsize)3008-{3009- stb__alloc_type t;3010-3011- if (ptr == NULL) return stb_malloc(NULL, newsize);3012- if (newsize == 0) { stb_free(ptr); return NULL; }3013-3014- t = stb__identify(ptr);3015- assert(t == STB__alloc || t == STB__nochildren);3016-3017- if (t == STB__alloc) {3018- stb__alloc *s = (stb__alloc *) ptr - 1;3019-3020- s = (stb__alloc *) realloc(s, newsize + sizeof(*s));3021- if (s == NULL) return NULL;3022-3023- ptr = s+1;3024-3025- // update pointers3026- (*s->prevn) = ptr;3027- if (s->next)3028- *stb__prevn(s->next) = &s->next;3029-3030- if (s->child)3031- *stb__prevn(s->child) = &s->child;3032-3033- return ptr;3034- } else {3035- stb__nochildren *s = (stb__nochildren *) ptr - 1;3036-3037- s = (stb__nochildren *) realloc(ptr, newsize + sizeof(s));3038- if (s == NULL) return NULL;3039-3040- // update pointers3041- (*s->prevn) = s+1;3042- if (s->next)3043- *stb__prevn(s->next) = &s->next;3044-3045- return s+1;3046- }3047-}3048-3049-void *stb_realloc_c(void *context, void *ptr, size_t newsize)3050-{3051- if (ptr == NULL) return stb_malloc(context, newsize);3052- if (newsize == 0) { stb_free(ptr); return NULL; }3053- // @TODO: verify you haven't changed contexts3054- return stb_realloc(ptr, newsize);3055-}3056-3057-void stb_reassign(void *new_context, void *ptr)3058-{3059- stb__alloc *src = stb__get_context(new_context);3060-3061- stb__alloc_type t = stb__identify(ptr);3062- assert(t == STB__alloc || t == STB__nochildren);3063-3064- if (t == STB__alloc) {3065- stb__alloc *s = (stb__alloc *) ptr - 1;3066-3067- // unlink from old3068- *(s->prevn) = s->next;3069- if (s->next)3070- *stb__prevn(s->next) = s->prevn;3071-3072- stb__insert_alloc(src, s);3073- } else {3074- stb__nochildren *s = (stb__nochildren *) ptr - 1;3075-3076- // unlink from old3077- *(s->prevn) = s->next;3078- if (s->next)3079- *stb__prevn(s->next) = s->prevn;3080-3081- stb__insert_nochild(src, s);3082- }3083-}3084-3085-#endif3086-3087-3088-//////////////////////////////////////////////////////////////////////////////3089-//3090-// stb_arr3091-//3092-// An stb_arr is directly useable as a pointer (use the actual type in your3093-// definition), but when it resizes, it returns a new pointer and you can't3094-// use the old one, so you have to be careful to copy-in-out as necessary.3095-//3096-// Use a NULL pointer as a 0-length array.3097-//3098-// float *my_array = NULL, *temp;3099-//3100-// // add elements on the end one at a time3101-// stb_arr_push(my_array, 0.0f);3102-// stb_arr_push(my_array, 1.0f);3103-// stb_arr_push(my_array, 2.0f);3104-//3105-// assert(my_array[1] == 2.0f);3106-//3107-// // add an uninitialized element at the end, then assign it3108-// *stb_arr_add(my_array) = 3.0f;3109-//3110-// // add three uninitialized elements at the end3111-// temp = stb_arr_addn(my_array,3);3112-// temp[0] = 4.0f;3113-// temp[1] = 5.0f;3114-// temp[2] = 6.0f;3115-//3116-// assert(my_array[5] == 5.0f);3117-//3118-// // remove the last one3119-// stb_arr_pop(my_array);3120-//3121-// assert(stb_arr_len(my_array) == 6);3122-3123-3124-#ifdef STB_MALLOC_WRAPPER3125- #define STB__PARAMS , char *file, int line3126- #define STB__ARGS , file, line3127-#else3128- #define STB__PARAMS3129- #define STB__ARGS3130-#endif3131-3132-// calling this function allocates an empty stb_arr attached to p3133-// (whereas NULL isn't attached to anything)3134-STB_EXTERN void stb_arr_malloc(void **target, void *context);3135-3136-// call this function with a non-NULL value to have all successive3137-// stbs that are created be attached to the associated parent. Note3138-// that once a given stb_arr is non-empty, it stays attached to its3139-// current parent, even if you call this function again.3140-// it turns the previous value, so you can restore it3141-STB_EXTERN void* stb_arr_malloc_parent(void *p);3142-3143-// simple functions written on top of other functions3144-#define stb_arr_empty(a) ( stb_arr_len(a) == 0 )3145-#define stb_arr_add(a) ( stb_arr_addn((a),1) )3146-#define stb_arr_push(a,v) ( *stb_arr_add(a)=(v) )3147-3148-typedef struct3149-{3150- int len, limit;3151- int stb_malloc;3152- unsigned int signature;3153-} stb__arr;3154-3155-#define stb_arr_signature 0x51bada7b // ends with 0123 in decimal3156-3157-// access the header block stored before the data3158-#define stb_arrhead(a) /*lint --e(826)*/ (((stb__arr *) (a)) - 1)3159-#define stb_arrhead2(a) /*lint --e(826)*/ (((stb__arr *) (a)) - 1)3160-3161-#ifdef STB_DEBUG3162-#define stb_arr_check(a) assert(!a || stb_arrhead(a)->signature == stb_arr_signature)3163-#define stb_arr_check2(a) assert(!a || stb_arrhead2(a)->signature == stb_arr_signature)3164-#else3165-#define stb_arr_check(a) ((void) 0)3166-#define stb_arr_check2(a) ((void) 0)3167-#endif3168-3169-// ARRAY LENGTH3170-3171-// get the array length; special case if pointer is NULL3172-#define stb_arr_len(a) (a ? stb_arrhead(a)->len : 0)3173-#define stb_arr_len2(a) ((stb__arr *) (a) ? stb_arrhead2(a)->len : 0)3174-#define stb_arr_lastn(a) (stb_arr_len(a)-1)3175-3176-// check whether a given index is valid -- tests 0 <= i < stb_arr_len(a)3177-#define stb_arr_valid(a,i) (a ? (int) (i) < stb_arrhead(a)->len : 0)3178-3179-// change the array length so is is exactly N entries long, creating3180-// uninitialized entries as needed3181-#define stb_arr_setlen(a,n) \3182- (stb__arr_setlen((void **) &(a), sizeof(a[0]), (n)))3183-3184-// change the array length so that N is a valid index (that is, so3185-// it is at least N entries long), creating uninitialized entries as needed3186-#define stb_arr_makevalid(a,n) \3187- (stb_arr_len(a) < (n)+1 ? stb_arr_setlen(a,(n)+1),(a) : (a))3188-3189-// remove the last element of the array, returning it3190-#define stb_arr_pop(a) ((stb_arr_check(a), (a))[--stb_arrhead(a)->len])3191-3192-// access the last element in the array3193-#define stb_arr_last(a) ((stb_arr_check(a), (a))[stb_arr_len(a)-1])3194-3195-// is iterator at end of list?3196-#define stb_arr_end(a,i) ((i) >= &(a)[stb_arr_len(a)])3197-3198-// (internal) change the allocated length of the array3199-#define stb_arr__grow(a,n) (stb_arr_check(a), stb_arrhead(a)->len += (n))3200-3201-// add N new uninitialized elements to the end of the array3202-#define stb_arr__addn(a,n) /*lint --e(826)*/ \3203- ((stb_arr_len(a)+(n) > stb_arrcurmax(a)) \3204- ? (stb__arr_addlen((void **) &(a),sizeof(*a),(n)),0) \3205- : ((stb_arr__grow(a,n), 0)))3206-3207-// add N new uninitialized elements to the end of the array, and return3208-// a pointer to the first new one3209-#define stb_arr_addn(a,n) (stb_arr__addn((a),n),(a)+stb_arr_len(a)-(n))3210-3211-// add N new uninitialized elements starting at index 'i'3212-#define stb_arr_insertn(a,i,n) (stb__arr_insertn((void **) &(a), sizeof(*a), (i), (n)))3213-3214-// insert an element at i3215-#define stb_arr_insert(a,i,v) (stb__arr_insertn((void **) &(a), sizeof(*a), (i), (1)), ((a)[i] = v))3216-3217-// delete N elements from the middle starting at index 'i'3218-#define stb_arr_deleten(a,i,n) (stb__arr_deleten((void **) &(a), sizeof(*a), (i), (n)))3219-3220-// delete the i'th element3221-#define stb_arr_delete(a,i) stb_arr_deleten(a,i,1)3222-3223-// delete the i'th element, swapping down from the end3224-#define stb_arr_fastdelete(a,i) \3225- (stb_swap(&a[i], &a[stb_arrhead(a)->len-1], sizeof(*a)), stb_arr_pop(a))3226-3227-3228-// ARRAY STORAGE3229-3230-// get the array maximum storage; special case if NULL3231-#define stb_arrcurmax(a) (a ? stb_arrhead(a)->limit : 0)3232-#define stb_arrcurmax2(a) (a ? stb_arrhead2(a)->limit : 0)3233-3234-// set the maxlength of the array to n in anticipation of further growth3235-#define stb_arr_setsize(a,n) (stb_arr_check(a), stb__arr_setsize((void **) &(a),sizeof((a)[0]),n))3236-3237-// make sure maxlength is large enough for at least N new allocations3238-#define stb_arr_atleast(a,n) (stb_arr_len(a)+(n) > stb_arrcurmax(a) \3239- ? stb_arr_setsize((a), (n)) : 0)3240-3241-// make a copy of a given array (copies contents via 'memcpy'!)3242-#define stb_arr_copy(a) stb__arr_copy(a, sizeof((a)[0]))3243-3244-// compute the storage needed to store all the elements of the array3245-#define stb_arr_storage(a) (stb_arr_len(a) * sizeof((a)[0]))3246-3247-#define stb_arr_for(v,arr) for((v)=(arr); (v) < (arr)+stb_arr_len(arr); ++(v))3248-3249-// IMPLEMENTATION3250-3251-STB_EXTERN void stb_arr_free_(void **p);3252-STB_EXTERN void *stb__arr_copy_(void *p, int elem_size);3253-STB_EXTERN void stb__arr_setsize_(void **p, int size, int limit STB__PARAMS);3254-STB_EXTERN void stb__arr_setlen_(void **p, int size, int newlen STB__PARAMS);3255-STB_EXTERN void stb__arr_addlen_(void **p, int size, int addlen STB__PARAMS);3256-STB_EXTERN void stb__arr_deleten_(void **p, int size, int loc, int n STB__PARAMS);3257-STB_EXTERN void stb__arr_insertn_(void **p, int size, int loc, int n STB__PARAMS);3258-3259-#define stb_arr_free(p) stb_arr_free_((void **) &(p))3260-#define stb__arr_copy stb__arr_copy_3261-3262-#ifndef STB_MALLOC_WRAPPER3263- #define stb__arr_setsize stb__arr_setsize_3264- #define stb__arr_setlen stb__arr_setlen_3265- #define stb__arr_addlen stb__arr_addlen_3266- #define stb__arr_deleten stb__arr_deleten_3267- #define stb__arr_insertn stb__arr_insertn_3268-#else3269- #define stb__arr_addlen(p,s,n) stb__arr_addlen_(p,s,n,__FILE__,__LINE__)3270- #define stb__arr_setlen(p,s,n) stb__arr_setlen_(p,s,n,__FILE__,__LINE__)3271- #define stb__arr_setsize(p,s,n) stb__arr_setsize_(p,s,n,__FILE__,__LINE__)3272- #define stb__arr_deleten(p,s,i,n) stb__arr_deleten_(p,s,i,n,__FILE__,__LINE__)3273- #define stb__arr_insertn(p,s,i,n) stb__arr_insertn_(p,s,i,n,__FILE__,__LINE__)3274-#endif3275-3276-#ifdef STB_DEFINE3277-static void *stb__arr_context;3278-3279-void *stb_arr_malloc_parent(void *p)3280-{3281- void *q = stb__arr_context;3282- stb__arr_context = p;3283- return q;3284-}3285-3286-void stb_arr_malloc(void **target, void *context)3287-{3288- stb__arr *q = (stb__arr *) stb_malloc(context, sizeof(*q));3289- q->len = q->limit = 0;3290- q->stb_malloc = 1;3291- q->signature = stb_arr_signature;3292- *target = (void *) (q+1);3293-}3294-3295-static void * stb__arr_malloc(int size)3296-{3297- if (stb__arr_context)3298- return stb_malloc(stb__arr_context, size);3299- return malloc(size);3300-}3301-3302-void * stb__arr_copy_(void *p, int elem_size)3303-{3304- stb__arr *q;3305- if (p == NULL) return p;3306- q = (stb__arr *) stb__arr_malloc(sizeof(*q) + elem_size * stb_arrhead2(p)->limit);3307- stb_arr_check2(p);3308- memcpy(q, stb_arrhead2(p), sizeof(*q) + elem_size * stb_arrhead2(p)->len);3309- q->stb_malloc = !!stb__arr_context;3310- return q+1;3311-}3312-3313-void stb_arr_free_(void **pp)3314-{3315- void *p = *pp;3316- stb_arr_check2(p);3317- if (p) {3318- stb__arr *q = stb_arrhead2(p);3319- if (q->stb_malloc)3320- stb_free(q);3321- else3322- free(q);3323- }3324- *pp = NULL;3325-}3326-3327-static void stb__arrsize_(void **pp, int size, int limit, int len STB__PARAMS)3328-{3329- void *p = *pp;3330- stb__arr *a;3331- stb_arr_check2(p);3332- if (p == NULL) {3333- if (len == 0 && size == 0) return;3334- a = (stb__arr *) stb__arr_malloc(sizeof(*a) + size*limit);3335- a->limit = limit;3336- a->len = len;3337- a->stb_malloc = !!stb__arr_context;3338- a->signature = stb_arr_signature;3339- } else {3340- a = stb_arrhead2(p);3341- a->len = len;3342- if (a->limit < limit) {3343- void *p;3344- if (a->limit >= 4 && limit < a->limit * 2)3345- limit = a->limit * 2;3346- if (a->stb_malloc)3347- p = stb_realloc(a, sizeof(*a) + limit*size);3348- else3349- #ifdef STB_MALLOC_WRAPPER3350- p = stb__realloc(a, sizeof(*a) + limit*size, file, line);3351- #else3352- p = realloc(a, sizeof(*a) + limit*size);3353- #endif3354- if (p) {3355- a = (stb__arr *) p;3356- a->limit = limit;3357- } else {3358- // throw an error!3359- }3360- }3361- }3362- a->len = stb_min(a->len, a->limit);3363- *pp = a+1;3364-}3365-3366-void stb__arr_setsize_(void **pp, int size, int limit STB__PARAMS)3367-{3368- void *p = *pp;3369- stb_arr_check2(p);3370- stb__arrsize_(pp, size, limit, stb_arr_len2(p) STB__ARGS);3371-}3372-3373-void stb__arr_setlen_(void **pp, int size, int newlen STB__PARAMS)3374-{3375- void *p = *pp;3376- stb_arr_check2(p);3377- if (stb_arrcurmax2(p) < newlen || p == NULL) {3378- stb__arrsize_(pp, size, newlen, newlen STB__ARGS);3379- } else {3380- stb_arrhead2(p)->len = newlen;3381- }3382-}3383-3384-void stb__arr_addlen_(void **p, int size, int addlen STB__PARAMS)3385-{3386- stb__arr_setlen_(p, size, stb_arr_len2(*p) + addlen STB__ARGS);3387-}3388-3389-void stb__arr_insertn_(void **pp, int size, int i, int n STB__PARAMS)3390-{3391- void *p = *pp;3392- if (n) {3393- int z;3394-3395- if (p == NULL) {3396- stb__arr_addlen_(pp, size, n STB__ARGS);3397- return;3398- }3399-3400- z = stb_arr_len2(p);3401- stb__arr_addlen_(&p, size, n STB__ARGS);3402- memmove((char *) p + (i+n)*size, (char *) p + i*size, size * (z-i));3403- }3404- *pp = p;3405-}3406-3407-void stb__arr_deleten_(void **pp, int size, int i, int n STB__PARAMS)3408-{3409- void *p = *pp;3410- if (n) {3411- memmove((char *) p + i*size, (char *) p + (i+n)*size, size * (stb_arr_len2(p)-(i+n)));3412- stb_arrhead2(p)->len -= n;3413- }3414- *pp = p;3415-}3416-3417-#endif3418-3419-//////////////////////////////////////////////////////////////////////////////3420-//3421-// Hashing3422-//3423-// typical use for this is to make a power-of-two hash table.3424-//3425-// let N = size of table (2^n)3426-// let H = stb_hash(str)3427-// let S = stb_rehash(H) | 13428-//3429-// then hash probe sequence P(i) for i=0..N-13430-// P(i) = (H + S*i) & (N-1)3431-//3432-// the idea is that H has 32 bits of hash information, but the3433-// table has only, say, 2^20 entries so only uses 20 of the bits.3434-// then by rehashing the original H we get 2^12 different probe3435-// sequences for a given initial probe location. (So it's optimal3436-// for 64K tables and its optimality decreases past that.)3437-//3438-// ok, so I've added something that generates _two separate_3439-// 32-bit hashes simultaneously which should scale better to3440-// very large tables.3441-3442-3443-STB_EXTERN unsigned int stb_hash(char *str);3444-STB_EXTERN unsigned int stb_hashptr(void *p);3445-STB_EXTERN unsigned int stb_hashlen(char *str, int len);3446-STB_EXTERN unsigned int stb_rehash_improved(unsigned int v);3447-STB_EXTERN unsigned int stb_hash_fast(void *p, int len);3448-STB_EXTERN unsigned int stb_hash2(char *str, unsigned int *hash2_ptr);3449-STB_EXTERN unsigned int stb_hash_number(unsigned int hash);3450-3451-#define stb_rehash(x) ((x) + ((x) >> 6) + ((x) >> 19))3452-3453-#ifdef STB_DEFINE3454-unsigned int stb_hash(char *str)3455-{3456- unsigned int hash = 0;3457- while (*str)3458- hash = (hash << 7) + (hash >> 25) + *str++;3459- return hash + (hash >> 16);3460-}3461-3462-unsigned int stb_hashlen(char *str, int len)3463-{3464- unsigned int hash = 0;3465- while (len-- > 0 && *str)3466- hash = (hash << 7) + (hash >> 25) + *str++;3467- return hash + (hash >> 16);3468-}3469-3470-unsigned int stb_hashptr(void *p)3471-{3472- unsigned int x = (unsigned int)(size_t) p;3473-3474- // typically lacking in low bits and high bits3475- x = stb_rehash(x);3476- x += x << 16;3477-3478- // pearson's shuffle3479- x ^= x << 3;3480- x += x >> 5;3481- x ^= x << 2;3482- x += x >> 15;3483- x ^= x << 10;3484- return stb_rehash(x);3485-}3486-3487-unsigned int stb_rehash_improved(unsigned int v)3488-{3489- return stb_hashptr((void *)(size_t) v);3490-}3491-3492-unsigned int stb_hash2(char *str, unsigned int *hash2_ptr)3493-{3494- unsigned int hash1 = 0x3141592c;3495- unsigned int hash2 = 0x77f044ed;3496- while (*str) {3497- hash1 = (hash1 << 7) + (hash1 >> 25) + *str;3498- hash2 = (hash2 << 11) + (hash2 >> 21) + *str;3499- ++str;3500- }3501- *hash2_ptr = hash2 + (hash1 >> 16);3502- return hash1 + (hash2 >> 16);3503-}3504-3505-// Paul Hsieh hash3506-#define stb__get16(p) ((p)[0] | ((p)[1] << 8))3507-3508-unsigned int stb_hash_fast(void *p, int len)3509-{3510- unsigned char *q = (unsigned char *) p;3511- unsigned int hash = len;3512-3513- if (len <= 0 || q == NULL) return 0;3514-3515- /* Main loop */3516- for (;len > 3; len -= 4) {3517- unsigned int val;3518- hash += stb__get16(q);3519- val = (stb__get16(q+2) << 11);3520- hash = (hash << 16) ^ hash ^ val;3521- q += 4;3522- hash += hash >> 11;3523- }3524-3525- /* Handle end cases */3526- switch (len) {3527- case 3: hash += stb__get16(q);3528- hash ^= hash << 16;3529- hash ^= q[2] << 18;3530- hash += hash >> 11;3531- break;3532- case 2: hash += stb__get16(q);3533- hash ^= hash << 11;3534- hash += hash >> 17;3535- break;3536- case 1: hash += q[0];3537- hash ^= hash << 10;3538- hash += hash >> 1;3539- break;3540- case 0: break;3541- }3542-3543- /* Force "avalanching" of final 127 bits */3544- hash ^= hash << 3;3545- hash += hash >> 5;3546- hash ^= hash << 4;3547- hash += hash >> 17;3548- hash ^= hash << 25;3549- hash += hash >> 6;3550-3551- return hash;3552-}3553-3554-unsigned int stb_hash_number(unsigned int hash)3555-{3556- hash ^= hash << 3;3557- hash += hash >> 5;3558- hash ^= hash << 4;3559- hash += hash >> 17;3560- hash ^= hash << 25;3561- hash += hash >> 6;3562- return hash;3563-}3564-3565-#endif3566-3567-#ifdef STB_PERFECT_HASH3568-//////////////////////////////////////////////////////////////////////////////3569-//3570-// Perfect hashing for ints/pointers3571-//3572-// This is mainly useful for making faster pointer-indexed tables3573-// that don't change frequently. E.g. for stb_ischar().3574-//3575-3576-typedef struct3577-{3578- stb_uint32 addend;3579- stb_uint multiplicand;3580- stb_uint b_mask;3581- stb_uint8 small_bmap[16];3582- stb_uint16 *large_bmap;3583-3584- stb_uint table_mask;3585- stb_uint32 *table;3586-} stb_perfect;3587-3588-STB_EXTERN int stb_perfect_create(stb_perfect *,unsigned int*,int n);3589-STB_EXTERN void stb_perfect_destroy(stb_perfect *);3590-STB_EXTERN int stb_perfect_hash(stb_perfect *, unsigned int x);3591-extern int stb_perfect_hash_max_failures;3592-3593-#ifdef STB_DEFINE3594-3595-int stb_perfect_hash_max_failures;3596-3597-int stb_perfect_hash(stb_perfect *p, unsigned int x)3598-{3599- stb_uint m = x * p->multiplicand;3600- stb_uint y = x >> 16;3601- stb_uint bv = (m >> 24) + y;3602- stb_uint av = (m + y) >> 12;3603- if (p->table == NULL) return -1; // uninitialized table fails3604- bv &= p->b_mask;3605- av &= p->table_mask;3606- if (p->large_bmap)3607- av ^= p->large_bmap[bv];3608- else3609- av ^= p->small_bmap[bv];3610- return p->table[av] == x ? av : -1;3611-}3612-3613-static void stb__perfect_prehash(stb_perfect *p, stb_uint x, stb_uint16 *a, stb_uint16 *b)3614-{3615- stb_uint m = x * p->multiplicand;3616- stb_uint y = x >> 16;3617- stb_uint bv = (m >> 24) + y;3618- stb_uint av = (m + y) >> 12;3619- bv &= p->b_mask;3620- av &= p->table_mask;3621- *b = bv;3622- *a = av;3623-}3624-3625-static unsigned long stb__perfect_rand(void)3626-{3627- static unsigned long stb__rand;3628- stb__rand = stb__rand * 2147001325 + 715136305;3629- return 0x31415926 ^ ((stb__rand >> 16) + (stb__rand << 16));3630-}3631-3632-typedef struct {3633- unsigned short count;3634- unsigned short b;3635- unsigned short map;3636- unsigned short *entries;3637-} stb__slot;3638-3639-static int stb__slot_compare(const void *p, const void *q)3640-{3641- stb__slot *a = (stb__slot *) p;3642- stb__slot *b = (stb__slot *) q;3643- return a->count > b->count ? -1 : a->count < b->count; // sort large to small3644-}3645-3646-int stb_perfect_create(stb_perfect *p, unsigned int *v, int n)3647-{3648- unsigned int buffer1[64], buffer2[64], buffer3[64], buffer4[64], buffer5[32];3649- unsigned short *as = (unsigned short *) stb_temp(buffer1, sizeof(*v)*n);3650- unsigned short *bs = (unsigned short *) stb_temp(buffer2, sizeof(*v)*n);3651- unsigned short *entries = (unsigned short *) stb_temp(buffer4, sizeof(*entries) * n);3652- int size = 1 << stb_log2_ceil(n), bsize=8;3653- int failure = 0,i,j,k;3654-3655- assert(n <= 32768);3656- p->large_bmap = NULL;3657-3658- for(;;) {3659- stb__slot *bcount = (stb__slot *) stb_temp(buffer3, sizeof(*bcount) * bsize);3660- unsigned short *bloc = (unsigned short *) stb_temp(buffer5, sizeof(*bloc) * bsize);3661- unsigned short *e;3662- int bad=0;3663-3664- p->addend = stb__perfect_rand();3665- p->multiplicand = stb__perfect_rand() | 1;3666- p->table_mask = size-1;3667- p->b_mask = bsize-1;3668- p->table = (stb_uint32 *) malloc(size * sizeof(*p->table));3669-3670- for (i=0; i < bsize; ++i) {3671- bcount[i].b = i;3672- bcount[i].count = 0;3673- bcount[i].map = 0;3674- }3675- for (i=0; i < n; ++i) {3676- stb__perfect_prehash(p, v[i], as+i, bs+i);3677- ++bcount[bs[i]].count;3678- }3679- qsort(bcount, bsize, sizeof(*bcount), stb__slot_compare);3680- e = entries; // now setup up their entries index3681- for (i=0; i < bsize; ++i) {3682- bcount[i].entries = e;3683- e += bcount[i].count;3684- bcount[i].count = 0;3685- bloc[bcount[i].b] = i;3686- }3687- // now fill them out3688- for (i=0; i < n; ++i) {3689- int b = bs[i];3690- int w = bloc[b];3691- bcount[w].entries[bcount[w].count++] = i;3692- }3693- stb_tempfree(buffer5,bloc);3694- // verify3695- for (i=0; i < bsize; ++i)3696- for (j=0; j < bcount[i].count; ++j)3697- assert(bs[bcount[i].entries[j]] == bcount[i].b);3698- memset(p->table, 0, size*sizeof(*p->table));3699-3700- // check if any b has duplicate a3701- for (i=0; i < bsize; ++i) {3702- if (bcount[i].count > 1) {3703- for (j=0; j < bcount[i].count; ++j) {3704- if (p->table[as[bcount[i].entries[j]]])3705- bad = 1;3706- p->table[as[bcount[i].entries[j]]] = 1;3707- }3708- for (j=0; j < bcount[i].count; ++j) {3709- p->table[as[bcount[i].entries[j]]] = 0;3710- }3711- if (bad) break;3712- }3713- }3714-3715- if (!bad) {3716- // go through the bs and populate the table, first fit3717- for (i=0; i < bsize; ++i) {3718- if (bcount[i].count) {3719- // go through the candidate table[b] values3720- for (j=0; j < size; ++j) {3721- // go through the a values and see if they fit3722- for (k=0; k < bcount[i].count; ++k) {3723- int a = as[bcount[i].entries[k]];3724- if (p->table[(a^j)&p->table_mask]) {3725- break; // fails3726- }3727- }3728- // if succeeded, accept3729- if (k == bcount[i].count) {3730- bcount[i].map = j;3731- for (k=0; k < bcount[i].count; ++k) {3732- int a = as[bcount[i].entries[k]];3733- p->table[(a^j)&p->table_mask] = 1;3734- }3735- break;3736- }3737- }3738- if (j == size)3739- break; // no match for i'th entry, so break out in failure3740- }3741- }3742- if (i == bsize) {3743- // success... fill out map3744- if (bsize <= 16 && size <= 256) {3745- p->large_bmap = NULL;3746- for (i=0; i < bsize; ++i)3747- p->small_bmap[bcount[i].b] = (stb_uint8) bcount[i].map;3748- } else {3749- p->large_bmap = (unsigned short *) malloc(sizeof(*p->large_bmap) * bsize);3750- for (i=0; i < bsize; ++i)3751- p->large_bmap[bcount[i].b] = bcount[i].map;3752- }3753-3754- // initialize table to v[0], so empty slots will fail3755- for (i=0; i < size; ++i)3756- p->table[i] = v[0];3757-3758- for (i=0; i < n; ++i)3759- if (p->large_bmap)3760- p->table[as[i] ^ p->large_bmap[bs[i]]] = v[i];3761- else3762- p->table[as[i] ^ p->small_bmap[bs[i]]] = v[i];3763-3764- // and now validate that none of them collided3765- for (i=0; i < n; ++i)3766- assert(stb_perfect_hash(p, v[i]) >= 0);3767-3768- stb_tempfree(buffer3, bcount);3769- break;3770- }3771- }3772- free(p->table);3773- p->table = NULL;3774- stb_tempfree(buffer3, bcount);3775-3776- ++failure;3777- if (failure >= 4 && bsize < size) bsize *= 2;3778- if (failure >= 8 && (failure & 3) == 0 && size < 4*n) {3779- size *= 2;3780- bsize *= 2;3781- }3782- if (failure == 6) {3783- // make sure the input data is unique, so we don't infinite loop3784- unsigned int *data = (unsigned int *) stb_temp(buffer3, n * sizeof(*data));3785- memcpy(data, v, sizeof(*data) * n);3786- qsort(data, n, sizeof(*data), stb_intcmp(0));3787- for (i=1; i < n; ++i) {3788- if (data[i] == data[i-1])3789- size = 0; // size is return value, so 0 it3790- }3791- stb_tempfree(buffer3, data);3792- if (!size) break;3793- }3794- }3795-3796- if (failure > stb_perfect_hash_max_failures)3797- stb_perfect_hash_max_failures = failure;3798-3799- stb_tempfree(buffer1, as);3800- stb_tempfree(buffer2, bs);3801- stb_tempfree(buffer4, entries);3802-3803- return size;3804-}3805-3806-void stb_perfect_destroy(stb_perfect *p)3807-{3808- if (p->large_bmap) free(p->large_bmap);3809- if (p->table ) free(p->table);3810- p->large_bmap = NULL;3811- p->table = NULL;3812- p->b_mask = 0;3813- p->table_mask = 0;3814-}3815-#endif3816-3817-//////////////////////////////////////////////////////////////////////////////3818-//3819-// Perfect hash clients3820-3821-STB_EXTERN int stb_ischar(char s, char *set);3822-3823-#ifdef STB_DEFINE3824-3825-int stb_ischar(char c, char *set)3826-{3827- static unsigned char bit[8] = { 1,2,4,8,16,32,64,128 };3828- static stb_perfect p;3829- static unsigned char (*tables)[256];3830- static char ** sets = NULL;3831-3832- int z = stb_perfect_hash(&p, (int)(size_t) set);3833- if (z < 0) {3834- int i,k,n,j,f;3835- // special code that means free all existing data3836- if (set == NULL) {3837- stb_arr_free(sets);3838- free(tables);3839- tables = NULL;3840- stb_perfect_destroy(&p);3841- return 0;3842- }3843- stb_arr_push(sets, set);3844- stb_perfect_destroy(&p);3845- n = stb_perfect_create(&p, (unsigned int *) (char **) sets, stb_arr_len(sets));3846- assert(n != 0);3847- k = (n+7) >> 3;3848- tables = (unsigned char (*)[256]) realloc(tables, sizeof(*tables) * k);3849- memset(tables, 0, sizeof(*tables) * k);3850- for (i=0; i < stb_arr_len(sets); ++i) {3851- k = stb_perfect_hash(&p, (int)(size_t) sets[i]);3852- assert(k >= 0);3853- n = k >> 3;3854- f = bit[k&7];3855- for (j=0; !j || sets[i][j]; ++j) {3856- tables[n][(unsigned char) sets[i][j]] |= f;3857- }3858- }3859- z = stb_perfect_hash(&p, (int)(size_t) set);3860- }3861- return tables[z >> 3][(unsigned char) c] & bit[z & 7];3862-}3863-3864-#endif3865-#endif3866-3867-//////////////////////////////////////////////////////////////////////////////3868-//3869-// Instantiated data structures3870-//3871-// This is an attempt to implement a templated data structure.3872-//3873-// Hash table: call stb_define_hash(TYPE,N,KEY,K1,K2,HASH,VALUE)3874-// TYPE -- will define a structure type containing the hash table3875-// N -- the name, will prefix functions named:3876-// N create3877-// N destroy3878-// N get3879-// N set, N add, N update,3880-// N remove3881-// KEY -- the type of the key. 'x == y' must be valid3882-// K1,K2 -- keys never used by the app, used as flags in the hashtable3883-// HASH -- a piece of code ending with 'return' that hashes key 'k'3884-// VALUE -- the type of the value. 'x = y' must be valid3885-//3886-// Note that stb_define_hash_base can be used to define more sophisticated3887-// hash tables, e.g. those that make copies of the key or use special3888-// comparisons (e.g. strcmp).3889-3890-#define STB_(prefix,name) stb__##prefix##name3891-#define STB__(prefix,name) prefix##name3892-#define STB__use(x) x3893-#define STB__skip(x)3894-3895-#define stb_declare_hash(PREFIX,TYPE,N,KEY,VALUE) \3896- typedef struct stb__st_##TYPE TYPE;\3897- PREFIX int STB__(N, init)(TYPE *h, int count);\3898- PREFIX int STB__(N, memory_usage)(TYPE *h);\3899- PREFIX TYPE * STB__(N, create)(void);\3900- PREFIX TYPE * STB__(N, copy)(TYPE *h);\3901- PREFIX void STB__(N, destroy)(TYPE *h);\3902- PREFIX int STB__(N,get_flag)(TYPE *a, KEY k, VALUE *v);\3903- PREFIX VALUE STB__(N,get)(TYPE *a, KEY k);\3904- PREFIX int STB__(N, set)(TYPE *a, KEY k, VALUE v);\3905- PREFIX int STB__(N, add)(TYPE *a, KEY k, VALUE v);\3906- PREFIX int STB__(N, update)(TYPE*a,KEY k,VALUE v);\3907- PREFIX int STB__(N, remove)(TYPE *a, KEY k, VALUE *v);3908-3909-#define STB_nocopy(x) (x)3910-#define STB_nodelete(x) 03911-#define STB_nofields3912-#define STB_nonullvalue(x)3913-#define STB_nullvalue(x) x3914-#define STB_safecompare(x) x3915-#define STB_nosafe(x)3916-#define STB_noprefix3917-3918-#ifdef __GNUC__3919-#define STB__nogcc(x)3920-#else3921-#define STB__nogcc(x) x3922-#endif3923-3924-#define stb_define_hash_base(PREFIX,TYPE,FIELDS,N,NC,LOAD_FACTOR, \3925- KEY,EMPTY,DEL,COPY,DISPOSE,SAFE, \3926- VCOMPARE,CCOMPARE,HASH, \3927- VALUE,HASVNULL,VNULL) \3928- \3929-typedef struct \3930-{ \3931- KEY k; \3932- VALUE v; \3933-} STB_(N,_hashpair); \3934- \3935-STB__nogcc( typedef struct stb__st_##TYPE TYPE; ) \3936-struct stb__st_##TYPE { \3937- FIELDS \3938- STB_(N,_hashpair) *table; \3939- unsigned int mask; \3940- int count, limit; \3941- int deleted; \3942- \3943- int delete_threshhold; \3944- int grow_threshhold; \3945- int shrink_threshhold; \3946- unsigned char alloced, has_empty, has_del; \3947- VALUE ev; VALUE dv; \3948-}; \3949- \3950-static unsigned int STB_(N, hash)(KEY k) \3951-{ \3952- HASH \3953-} \3954- \3955-PREFIX int STB__(N, init)(TYPE *h, int count) \3956-{ \3957- int i; \3958- if (count < 4) count = 4; \3959- h->limit = count; \3960- h->count = 0; \3961- h->mask = count-1; \3962- h->deleted = 0; \3963- h->grow_threshhold = (int) (count * LOAD_FACTOR); \3964- h->has_empty = h->has_del = 0; \3965- h->alloced = 0; \3966- if (count <= 64) \3967- h->shrink_threshhold = 0; \3968- else \3969- h->shrink_threshhold = (int) (count * (LOAD_FACTOR/2.25)); \3970- h->delete_threshhold = (int) (count * (1-LOAD_FACTOR)/2); \3971- h->table = (STB_(N,_hashpair)*) malloc(sizeof(h->table[0]) * count); \3972- if (h->table == NULL) return 0; \3973- /* ideally this gets turned into a memset32 automatically */ \3974- for (i=0; i < count; ++i) \3975- h->table[i].k = EMPTY; \3976- return 1; \3977-} \3978- \3979-PREFIX int STB__(N, memory_usage)(TYPE *h) \3980-{ \3981- return sizeof(*h) + h->limit * sizeof(h->table[0]); \3982-} \3983- \3984-PREFIX TYPE * STB__(N, create)(void) \3985-{ \3986- TYPE *h = (TYPE *) malloc(sizeof(*h)); \3987- if (h) { \3988- if (STB__(N, init)(h, 16)) \3989- h->alloced = 1; \3990- else { free(h); h=NULL; } \3991- } \3992- return h; \3993-} \3994- \3995-PREFIX void STB__(N, destroy)(TYPE *a) \3996-{ \3997- int i; \3998- for (i=0; i < a->limit; ++i) \3999- if (!CCOMPARE(a->table[i].k,EMPTY) && !CCOMPARE(a->table[i].k, DEL)) \4000- DISPOSE(a->table[i].k); \4001- free(a->table); \4002- if (a->alloced) \4003- free(a); \4004-} \4005- \4006-static void STB_(N, rehash)(TYPE *a, int count); \4007- \4008-PREFIX int STB__(N,get_flag)(TYPE *a, KEY k, VALUE *v) \4009-{ \4010- unsigned int h = STB_(N, hash)(k); \4011- unsigned int n = h & a->mask, s; \4012- if (CCOMPARE(k,EMPTY)){ if (a->has_empty) *v = a->ev; return a->has_empty;}\4013- if (CCOMPARE(k,DEL)) { if (a->has_del ) *v = a->dv; return a->has_del; }\4014- if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \4015- SAFE(if (!CCOMPARE(a->table[n].k,DEL))) \4016- if (VCOMPARE(a->table[n].k,k)) { *v = a->table[n].v; return 1; } \4017- s = stb_rehash(h) | 1; \4018- for(;;) { \4019- n = (n + s) & a->mask; \4020- if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \4021- SAFE(if (CCOMPARE(a->table[n].k,DEL)) continue;) \4022- if (VCOMPARE(a->table[n].k,k)) \4023- { *v = a->table[n].v; return 1; } \4024- } \4025-} \4026- \4027-HASVNULL( \4028- PREFIX VALUE STB__(N,get)(TYPE *a, KEY k) \4029- { \4030- VALUE v; \4031- if (STB__(N,get_flag)(a,k,&v)) return v; \4032- else return VNULL; \4033- } \4034-) \4035- \4036-PREFIX int STB__(N,getkey)(TYPE *a, KEY k, KEY *kout) \4037-{ \4038- unsigned int h = STB_(N, hash)(k); \4039- unsigned int n = h & a->mask, s; \4040- if (CCOMPARE(k,EMPTY)||CCOMPARE(k,DEL)) return 0; \4041- if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \4042- SAFE(if (!CCOMPARE(a->table[n].k,DEL))) \4043- if (VCOMPARE(a->table[n].k,k)) { *kout = a->table[n].k; return 1; } \4044- s = stb_rehash(h) | 1; \4045- for(;;) { \4046- n = (n + s) & a->mask; \4047- if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \4048- SAFE(if (CCOMPARE(a->table[n].k,DEL)) continue;) \4049- if (VCOMPARE(a->table[n].k,k)) \4050- { *kout = a->table[n].k; return 1; } \4051- } \4052-} \4053- \4054-static int STB_(N,addset)(TYPE *a, KEY k, VALUE v, \4055- int allow_new, int allow_old, int copy) \4056-{ \4057- unsigned int h = STB_(N, hash)(k); \4058- unsigned int n = h & a->mask; \4059- int b = -1; \4060- if (CCOMPARE(k,EMPTY)) { \4061- if (a->has_empty ? allow_old : allow_new) { \4062- n=a->has_empty; a->ev = v; a->has_empty = 1; return !n; \4063- } else return 0; \4064- } \4065- if (CCOMPARE(k,DEL)) { \4066- if (a->has_del ? allow_old : allow_new) { \4067- n=a->has_del; a->dv = v; a->has_del = 1; return !n; \4068- } else return 0; \4069- } \4070- if (!CCOMPARE(a->table[n].k, EMPTY)) { \4071- unsigned int s; \4072- if (CCOMPARE(a->table[n].k, DEL)) \4073- b = n; \4074- else if (VCOMPARE(a->table[n].k,k)) { \4075- if (allow_old) \4076- a->table[n].v = v; \4077- return !allow_new; \4078- } \4079- s = stb_rehash(h) | 1; \4080- for(;;) { \4081- n = (n + s) & a->mask; \4082- if (CCOMPARE(a->table[n].k, EMPTY)) break; \4083- if (CCOMPARE(a->table[n].k, DEL)) { \4084- if (b < 0) b = n; \4085- } else if (VCOMPARE(a->table[n].k,k)) { \4086- if (allow_old) \4087- a->table[n].v = v; \4088- return !allow_new; \4089- } \4090- } \4091- } \4092- if (!allow_new) return 0; \4093- if (b < 0) b = n; else --a->deleted; \4094- a->table[b].k = copy ? COPY(k) : k; \4095- a->table[b].v = v; \4096- ++a->count; \4097- if (a->count > a->grow_threshhold) \4098- STB_(N,rehash)(a, a->limit*2); \4099- return 1; \4100-} \4101- \4102-PREFIX int STB__(N, set)(TYPE *a, KEY k, VALUE v){return STB_(N,addset)(a,k,v,1,1,1);}\4103-PREFIX int STB__(N, add)(TYPE *a, KEY k, VALUE v){return STB_(N,addset)(a,k,v,1,0,1);}\4104-PREFIX int STB__(N, update)(TYPE*a,KEY k,VALUE v){return STB_(N,addset)(a,k,v,0,1,1);}\4105- \4106-PREFIX int STB__(N, remove)(TYPE *a, KEY k, VALUE *v) \4107-{ \4108- unsigned int h = STB_(N, hash)(k); \4109- unsigned int n = h & a->mask, s; \4110- if (CCOMPARE(k,EMPTY)) { if (a->has_empty) { if(v)*v = a->ev; a->has_empty=0; return 1; } return 0; } \4111- if (CCOMPARE(k,DEL)) { if (a->has_del ) { if(v)*v = a->dv; a->has_del =0; return 1; } return 0; } \4112- if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \4113- if (SAFE(CCOMPARE(a->table[n].k,DEL) || ) !VCOMPARE(a->table[n].k,k)) { \4114- s = stb_rehash(h) | 1; \4115- for(;;) { \4116- n = (n + s) & a->mask; \4117- if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \4118- SAFE(if (CCOMPARE(a->table[n].k, DEL)) continue;) \4119- if (VCOMPARE(a->table[n].k,k)) break; \4120- } \4121- } \4122- DISPOSE(a->table[n].k); \4123- a->table[n].k = DEL; \4124- --a->count; \4125- ++a->deleted; \4126- if (v != NULL) \4127- *v = a->table[n].v; \4128- if (a->count < a->shrink_threshhold) \4129- STB_(N, rehash)(a, a->limit >> 1); \4130- else if (a->deleted > a->delete_threshhold) \4131- STB_(N, rehash)(a, a->limit); \4132- return 1; \4133-} \4134- \4135-PREFIX TYPE * STB__(NC, copy)(TYPE *a) \4136-{ \4137- int i; \4138- TYPE *h = (TYPE *) malloc(sizeof(*h)); \4139- if (!h) return NULL; \4140- if (!STB__(N, init)(h, a->limit)) { free(h); return NULL; } \4141- h->count = a->count; \4142- h->deleted = a->deleted; \4143- h->alloced = 1; \4144- h->ev = a->ev; h->dv = a->dv; \4145- h->has_empty = a->has_empty; h->has_del = a->has_del; \4146- memcpy(h->table, a->table, h->limit * sizeof(h->table[0])); \4147- for (i=0; i < a->limit; ++i) \4148- if (!CCOMPARE(h->table[i].k,EMPTY) && !CCOMPARE(h->table[i].k,DEL)) \4149- h->table[i].k = COPY(h->table[i].k); \4150- return h; \4151-} \4152- \4153-static void STB_(N, rehash)(TYPE *a, int count) \4154-{ \4155- int i; \4156- TYPE b; \4157- STB__(N, init)(&b, count); \4158- for (i=0; i < a->limit; ++i) \4159- if (!CCOMPARE(a->table[i].k,EMPTY) && !CCOMPARE(a->table[i].k,DEL)) \4160- STB_(N,addset)(&b, a->table[i].k, a->table[i].v,1,1,0); \4161- free(a->table); \4162- a->table = b.table; \4163- a->mask = b.mask; \4164- a->count = b.count; \4165- a->limit = b.limit; \4166- a->deleted = b.deleted; \4167- a->delete_threshhold = b.delete_threshhold; \4168- a->grow_threshhold = b.grow_threshhold; \4169- a->shrink_threshhold = b.shrink_threshhold; \4170-}4171-4172-#define STB_equal(a,b) ((a) == (b))4173-4174-#define stb_define_hash(TYPE,N,KEY,EMPTY,DEL,HASH,VALUE) \4175- stb_define_hash_base(STB_noprefix, TYPE,STB_nofields,N,NC,0.85f, \4176- KEY,EMPTY,DEL,STB_nocopy,STB_nodelete,STB_nosafe, \4177- STB_equal,STB_equal,HASH, \4178- VALUE,STB_nonullvalue,0)4179-4180-#define stb_define_hash_vnull(TYPE,N,KEY,EMPTY,DEL,HASH,VALUE,VNULL) \4181- stb_define_hash_base(STB_noprefix, TYPE,STB_nofields,N,NC,0.85f, \4182- KEY,EMPTY,DEL,STB_nocopy,STB_nodelete,STB_nosafe, \4183- STB_equal,STB_equal,HASH, \4184- VALUE,STB_nullvalue,VNULL)4185-4186-//////////////////////////////////////////////////////////////////////////////4187-//4188-// stb_ptrmap4189-//4190-// An stb_ptrmap data structure is an O(1) hash table between pointers. One4191-// application is to let you store "extra" data associated with pointers,4192-// which is why it was originally called stb_extra.4193-4194-stb_declare_hash(STB_EXTERN, stb_ptrmap, stb_ptrmap_, void *, void *)4195-stb_declare_hash(STB_EXTERN, stb_idict, stb_idict_, stb_int32, stb_int32)4196-stb_declare_hash(STB_EXTERN, stb_uidict, stbi_uidict_, stb_uint32, stb_uint32)4197-4198-STB_EXTERN void stb_ptrmap_delete(stb_ptrmap *e, void (*free_func)(void *));4199-STB_EXTERN stb_ptrmap *stb_ptrmap_new(void);4200-4201-STB_EXTERN stb_idict * stb_idict_new_size(int size);4202-STB_EXTERN void stb_idict_remove_all(stb_idict *e);4203-STB_EXTERN void stb_uidict_reset(stb_uidict *e);4204-4205-#ifdef STB_DEFINE4206-4207-#define STB_EMPTY ((void *) 2)4208-#define STB_EDEL ((void *) 6)4209-4210-stb_define_hash_base(STB_noprefix,stb_ptrmap, STB_nofields, stb_ptrmap_,stb_ptrmap_,0.85f,4211- void *,STB_EMPTY,STB_EDEL,STB_nocopy,STB_nodelete,STB_nosafe,4212- STB_equal,STB_equal,return stb_hashptr(k);,4213- void *,STB_nullvalue,NULL)4214-4215-stb_ptrmap *stb_ptrmap_new(void)4216-{4217- return stb_ptrmap_create();4218-}4219-4220-void stb_ptrmap_delete(stb_ptrmap *e, void (*free_func)(void *))4221-{4222- int i;4223- if (free_func)4224- for (i=0; i < e->limit; ++i)4225- if (e->table[i].k != STB_EMPTY && e->table[i].k != STB_EDEL) {4226- if (free_func == free)4227- free(e->table[i].v); // allow STB_MALLOC_WRAPPER to operate4228- else4229- free_func(e->table[i].v);4230- }4231- stb_ptrmap_destroy(e);4232-}4233-4234-// extra fields needed for stua_dict4235-#define STB_IEMPTY ((int) 1)4236-#define STB_IDEL ((int) 3)4237-stb_define_hash_base(STB_noprefix, stb_idict, short type; short gc; STB_nofields, stb_idict_,stb_idict_,0.95f,4238- stb_int32,STB_IEMPTY,STB_IDEL,STB_nocopy,STB_nodelete,STB_nosafe,4239- STB_equal,STB_equal,4240- return stb_rehash_improved(k);,stb_int32,STB_nonullvalue,0)4241-4242-stb_idict * stb_idict_new_size(int size)4243-{4244- stb_idict *e = (stb_idict *) malloc(sizeof(*e));4245- if (e) {4246- if (!stb_is_pow2(size))4247- size = 1 << stb_log2_ceil(size);4248- stb_idict_init(e, size);4249- e->alloced = 1;4250- }4251- return e;4252-}4253-4254-void stb_idict_remove_all(stb_idict *e)4255-{4256- int n;4257- for (n=0; n < e->limit; ++n)4258- e->table[n].k = STB_IEMPTY;4259- e->has_empty = e->has_del = 0;4260- e->count = 0;4261- e->deleted = 0;4262-}4263-4264-stb_define_hash_base(STB_noprefix, stb_uidict, STB_nofields, stb_uidict_,stb_uidict_,0.85f,4265- stb_int32,0xffffffff,0xfffffffe,STB_nocopy,STB_nodelete,STB_nosafe,4266- STB_equal,STB_equal,4267- return stb_rehash_improved(k);,stb_uint32,STB_nonullvalue,0)4268-4269-void stb_uidict_reset(stb_uidict *e)4270-{4271- int n;4272- for (n=0; n < e->limit; ++n)4273- e->table[n].k = 0xffffffff;4274- e->has_empty = e->has_del = 0;4275- e->count = 0;4276- e->deleted = 0;4277-}4278-#endif4279-4280-//////////////////////////////////////////////////////////////////////////////4281-//4282-// stb_sparse_ptr_matrix4283-//4284-// An stb_ptrmap data structure is an O(1) hash table storing an arbitrary4285-// block of data for a given pair of pointers.4286-//4287-// If create=0, returns4288-4289-typedef struct stb__st_stb_spmatrix stb_spmatrix;4290-4291-STB_EXTERN stb_spmatrix * stb_sparse_ptr_matrix_new(int val_size);4292-STB_EXTERN void stb_sparse_ptr_matrix_free(stb_spmatrix *z);4293-STB_EXTERN void * stb_sparse_ptr_matrix_get(stb_spmatrix *z, void *a, void *b, int create);4294-4295-#ifdef STB_DEFINE4296-typedef struct4297-{4298- void *a;4299- void *b;4300-} stb__ptrpair;4301-4302-static stb__ptrpair stb__ptrpair_empty = { (void *) 1, (void *) 1 };4303-static stb__ptrpair stb__ptrpair_del = { (void *) 2, (void *) 2 };4304-4305-#define STB__equal_ptrpair(x,y) ((x).a == (y).a && (x).b == (y).b)4306-4307-stb_define_hash_base(STB_noprefix, stb_spmatrix, int val_size; void *arena;, stb__spmatrix_,stb__spmatrix_, 0.85,4308- stb__ptrpair, stb__ptrpair_empty, stb__ptrpair_del,4309- STB_nocopy, STB_nodelete, STB_nosafe,4310- STB__equal_ptrpair, STB__equal_ptrpair, return stb_rehash(stb_hashptr(k.a))+stb_hashptr(k.b);,4311- void *, STB_nullvalue, 0)4312-4313-stb_spmatrix *stb_sparse_ptr_matrix_new(int val_size)4314-{4315- stb_spmatrix *m = stb__spmatrix_create();4316- if (m) m->val_size = val_size;4317- if (m) m->arena = stb_malloc_global(1);4318- return m;4319-}4320-4321-void stb_sparse_ptr_matrix_free(stb_spmatrix *z)4322-{4323- if (z->arena) stb_free(z->arena);4324- stb__spmatrix_destroy(z);4325-}4326-4327-void *stb_sparse_ptr_matrix_get(stb_spmatrix *z, void *a, void *b, int create)4328-{4329- stb__ptrpair t = { a,b };4330- void *data = stb__spmatrix_get(z, t);4331- if (!data && create) {4332- data = stb_malloc_raw(z->arena, z->val_size);4333- if (!data) return NULL;4334- memset(data, 0, z->val_size);4335- stb__spmatrix_add(z, t, data);4336- }4337- return data;4338-}4339-#endif4340-4341-4342-4343-//////////////////////////////////////////////////////////////////////////////4344-//4345-// SDICT: Hash Table for Strings (symbol table)4346-//4347-// if "use_arena=1", then strings will be copied4348-// into blocks and never freed until the sdict is freed;4349-// otherwise they're malloc()ed and free()d on the fly.4350-// (specify use_arena=1 if you never stb_sdict_remove)4351-4352-stb_declare_hash(STB_EXTERN, stb_sdict, stb_sdict_, char *, void *)4353-4354-STB_EXTERN stb_sdict * stb_sdict_new(int use_arena);4355-STB_EXTERN stb_sdict * stb_sdict_copy(stb_sdict*);4356-STB_EXTERN void stb_sdict_delete(stb_sdict *);4357-STB_EXTERN void * stb_sdict_change(stb_sdict *, char *str, void *p);4358-STB_EXTERN int stb_sdict_count(stb_sdict *d);4359-4360-STB_EXTERN int stb_sdict_internal_limit(stb_sdict *d);4361-STB_EXTERN char * stb_sdict_internal_key(stb_sdict *d, int n);4362-STB_EXTERN void * stb_sdict_internal_value(stb_sdict *d, int n);4363-4364-#define stb_sdict_for(d,i,q,z) \4365- for(i=0; i < stb_sdict_internal_limit(d) ? (q=stb_sdict_internal_key(d,i),z=stb_sdict_internal_value(d,i),1) : 0; ++i) \4366- if (q==NULL||q==(void *) 1);else // reversed makes macro friendly4367-4368-#ifdef STB_DEFINE4369-4370-// if in same translation unit, for speed, don't call accessors4371-#undef stb_sdict_for4372-#define stb_sdict_for(d,i,q,z) \4373- for(i=0; i < (d)->limit ? (q=(d)->table[i].k,z=(d)->table[i].v,1) : 0; ++i) \4374- if (q==NULL||q==(void *) 1);else // reversed makes macro friendly4375-4376-#define STB_DEL ((void *) 1)4377-#define STB_SDEL ((char *) 1)4378-4379-#define stb_sdict__copy(x) \4380- stb_p_strcpy_s(a->arena ? stb_malloc_string(a->arena, strlen(x)+1) \4381- : (char *) malloc(strlen(x)+1), strlen(x)+1, x)4382-4383-#define stb_sdict__dispose(x) if (!a->arena) free(x)4384-4385-stb_define_hash_base(STB_noprefix, stb_sdict, void*arena;, stb_sdict_,stb_sdictinternal_, 0.85f,4386- char *, NULL, STB_SDEL, stb_sdict__copy, stb_sdict__dispose,4387- STB_safecompare, !strcmp, STB_equal, return stb_hash(k);,4388- void *, STB_nullvalue, NULL)4389-4390-int stb_sdict_count(stb_sdict *a)4391-{4392- return a->count;4393-}4394-4395-int stb_sdict_internal_limit(stb_sdict *a)4396-{4397- return a->limit;4398-}4399-char* stb_sdict_internal_key(stb_sdict *a, int n)4400-{4401- return a->table[n].k;4402-}4403-void* stb_sdict_internal_value(stb_sdict *a, int n)4404-{4405- return a->table[n].v;4406-}4407-4408-stb_sdict * stb_sdict_new(int use_arena)4409-{4410- stb_sdict *d = stb_sdict_create();4411- if (d == NULL) return NULL;4412- d->arena = use_arena ? stb_malloc_global(1) : NULL;4413- return d;4414-}4415-4416-stb_sdict* stb_sdict_copy(stb_sdict *old)4417-{4418- stb_sdict *n;4419- void *old_arena = old->arena;4420- void *new_arena = old_arena ? stb_malloc_global(1) : NULL;4421- old->arena = new_arena;4422- n = stb_sdictinternal_copy(old);4423- old->arena = old_arena;4424- if (n)4425- n->arena = new_arena;4426- else if (new_arena)4427- stb_free(new_arena);4428- return n;4429-}4430-4431-4432-void stb_sdict_delete(stb_sdict *d)4433-{4434- if (d->arena)4435- stb_free(d->arena);4436- stb_sdict_destroy(d);4437-}4438-4439-void * stb_sdict_change(stb_sdict *d, char *str, void *p)4440-{4441- void *q = stb_sdict_get(d, str);4442- stb_sdict_set(d, str, p);4443- return q;4444-}4445-#endif4446-4447-//////////////////////////////////////////////////////////////////////////////4448-//4449-// Instantiated data structures4450-//4451-// This is an attempt to implement a templated data structure.4452-// What you do is define a struct foo, and then include several4453-// pointer fields to struct foo in your struct. Then you call4454-// the instantiator, which creates the functions that implement4455-// the data structure. This requires massive undebuggable #defines,4456-// so we limit the cases where we do this.4457-//4458-// AA tree is an encoding of a 2-3 tree whereas RB trees encode a 2-3-4 tree;4459-// much simpler code due to fewer cases.4460-4461-#define stb__bst_parent(x) x4462-#define stb__bst_noparent(x)4463-4464-#define stb_bst_fields(N) \4465- *STB_(N,left), *STB_(N,right); \4466- unsigned char STB_(N,level)4467-4468-#define stb_bst_fields_parent(N) \4469- *STB_(N,left), *STB_(N,right), *STB_(N,parent); \4470- unsigned char STB_(N,level)4471-4472-#define STB__level(N,x) ((x) ? (x)->STB_(N,level) : 0)4473-4474-#define stb_bst_base(TYPE, N, TREE, M, compare, PAR) \4475- \4476-static int STB_(N,_compare)(TYPE *p, TYPE *q) \4477-{ \4478- compare \4479-} \4480- \4481-static void STB_(N,setleft)(TYPE *q, TYPE *v) \4482-{ \4483- q->STB_(N,left) = v; \4484- PAR(if (v) v->STB_(N,parent) = q;) \4485-} \4486- \4487-static void STB_(N,setright)(TYPE *q, TYPE *v) \4488-{ \4489- q->STB_(N,right) = v; \4490- PAR(if (v) v->STB_(N,parent) = q;) \4491-} \4492- \4493-static TYPE *STB_(N,skew)(TYPE *q) \4494-{ \4495- if (q == NULL) return q; \4496- if (q->STB_(N,left) \4497- && q->STB_(N,left)->STB_(N,level) == q->STB_(N,level)) { \4498- TYPE *p = q->STB_(N,left); \4499- STB_(N,setleft)(q, p->STB_(N,right)); \4500- STB_(N,setright)(p, q); \4501- return p; \4502- } \4503- return q; \4504-} \4505- \4506-static TYPE *STB_(N,split)(TYPE *p) \4507-{ \4508- TYPE *q = p->STB_(N,right); \4509- if (q && q->STB_(N,right) \4510- && q->STB_(N,right)->STB_(N,level) == p->STB_(N,level)) { \4511- STB_(N,setright)(p, q->STB_(N,left)); \4512- STB_(N,setleft)(q,p); \4513- ++q->STB_(N,level); \4514- return q; \4515- } \4516- return p; \4517-} \4518- \4519-TYPE *STB__(N,insert)(TYPE *tree, TYPE *item) \4520-{ \4521- int c; \4522- if (tree == NULL) { \4523- item->STB_(N,left) = NULL; \4524- item->STB_(N,right) = NULL; \4525- item->STB_(N,level) = 1; \4526- PAR(item->STB_(N,parent) = NULL;) \4527- return item; \4528- } \4529- c = STB_(N,_compare)(item,tree); \4530- if (c == 0) { \4531- if (item != tree) { \4532- STB_(N,setleft)(item, tree->STB_(N,left)); \4533- STB_(N,setright)(item, tree->STB_(N,right)); \4534- item->STB_(N,level) = tree->STB_(N,level); \4535- PAR(item->STB_(N,parent) = NULL;) \4536- } \4537- return item; \4538- } \4539- if (c < 0) \4540- STB_(N,setleft )(tree, STB__(N,insert)(tree->STB_(N,left), item)); \4541- else \4542- STB_(N,setright)(tree, STB__(N,insert)(tree->STB_(N,right), item)); \4543- tree = STB_(N,skew)(tree); \4544- tree = STB_(N,split)(tree); \4545- PAR(tree->STB_(N,parent) = NULL;) \4546- return tree; \4547-} \4548- \4549-TYPE *STB__(N,remove)(TYPE *tree, TYPE *item) \4550-{ \4551- static TYPE *delnode, *leaf, *restore; \4552- if (tree == NULL) return NULL; \4553- leaf = tree; \4554- if (STB_(N,_compare)(item, tree) < 0) { \4555- STB_(N,setleft)(tree, STB__(N,remove)(tree->STB_(N,left), item)); \4556- } else { \4557- TYPE *r; \4558- delnode = tree; \4559- r = STB__(N,remove)(tree->STB_(N,right), item); \4560- /* maybe move 'leaf' up to this location */ \4561- if (restore == tree) { tree = leaf; leaf = restore = NULL; } \4562- STB_(N,setright)(tree,r); \4563- assert(tree->STB_(N,right) != tree); \4564- } \4565- if (tree == leaf) { \4566- if (delnode == item) { \4567- tree = tree->STB_(N,right); \4568- assert(leaf->STB_(N,left) == NULL); \4569- /* move leaf (the right sibling) up to delnode */ \4570- STB_(N,setleft )(leaf, item->STB_(N,left )); \4571- STB_(N,setright)(leaf, item->STB_(N,right)); \4572- leaf->STB_(N,level) = item->STB_(N,level); \4573- if (leaf != item) \4574- restore = delnode; \4575- } \4576- delnode = NULL; \4577- } else { \4578- if (STB__level(N,tree->STB_(N,left) ) < tree->STB_(N,level)-1 || \4579- STB__level(N,tree->STB_(N,right)) < tree->STB_(N,level)-1) { \4580- --tree->STB_(N,level); \4581- if (STB__level(N,tree->STB_(N,right)) > tree->STB_(N,level)) \4582- tree->STB_(N,right)->STB_(N,level) = tree->STB_(N,level); \4583- tree = STB_(N,skew)(tree); \4584- STB_(N,setright)(tree, STB_(N,skew)(tree->STB_(N,right))); \4585- if (tree->STB_(N,right)) \4586- STB_(N,setright)(tree->STB_(N,right), \4587- STB_(N,skew)(tree->STB_(N,right)->STB_(N,right))); \4588- tree = STB_(N,split)(tree); \4589- if (tree->STB_(N,right)) \4590- STB_(N,setright)(tree, STB_(N,split)(tree->STB_(N,right))); \4591- } \4592- } \4593- PAR(if (tree) tree->STB_(N,parent) = NULL;) \4594- return tree; \4595-} \4596- \4597-TYPE *STB__(N,last)(TYPE *tree) \4598-{ \4599- if (tree) \4600- while (tree->STB_(N,right)) tree = tree->STB_(N,right); \4601- return tree; \4602-} \4603- \4604-TYPE *STB__(N,first)(TYPE *tree) \4605-{ \4606- if (tree) \4607- while (tree->STB_(N,left)) tree = tree->STB_(N,left); \4608- return tree; \4609-} \4610- \4611-TYPE *STB__(N,next)(TYPE *tree, TYPE *item) \4612-{ \4613- TYPE *next = NULL; \4614- if (item->STB_(N,right)) \4615- return STB__(N,first)(item->STB_(N,right)); \4616- PAR( \4617- while(item->STB_(N,parent)) { \4618- TYPE *up = item->STB_(N,parent); \4619- if (up->STB_(N,left) == item) return up; \4620- item = up; \4621- } \4622- return NULL; \4623- ) \4624- while (tree != item) { \4625- if (STB_(N,_compare)(item, tree) < 0) { \4626- next = tree; \4627- tree = tree->STB_(N,left); \4628- } else { \4629- tree = tree->STB_(N,right); \4630- } \4631- } \4632- return next; \4633-} \4634- \4635-TYPE *STB__(N,prev)(TYPE *tree, TYPE *item) \4636-{ \4637- TYPE *next = NULL; \4638- if (item->STB_(N,left)) \4639- return STB__(N,last)(item->STB_(N,left)); \4640- PAR( \4641- while(item->STB_(N,parent)) { \4642- TYPE *up = item->STB_(N,parent); \4643- if (up->STB_(N,right) == item) return up; \4644- item = up; \4645- } \4646- return NULL; \4647- ) \4648- while (tree != item) { \4649- if (STB_(N,_compare)(item, tree) < 0) { \4650- tree = tree->STB_(N,left); \4651- } else { \4652- next = tree; \4653- tree = tree->STB_(N,right); \4654- } \4655- } \4656- return next; \4657-} \4658- \4659-STB__DEBUG( \4660- void STB__(N,_validate)(TYPE *tree, int root) \4661- { \4662- if (tree == NULL) return; \4663- PAR(if(root) assert(tree->STB_(N,parent) == NULL);) \4664- assert(STB__level(N,tree->STB_(N,left) ) == tree->STB_(N,level)-1); \4665- assert(STB__level(N,tree->STB_(N,right)) <= tree->STB_(N,level)); \4666- assert(STB__level(N,tree->STB_(N,right)) >= tree->STB_(N,level)-1); \4667- if (tree->STB_(N,right)) { \4668- assert(STB__level(N,tree->STB_(N,right)->STB_(N,right)) \4669- != tree->STB_(N,level)); \4670- PAR(assert(tree->STB_(N,right)->STB_(N,parent) == tree);) \4671- } \4672- PAR(if(tree->STB_(N,left)) assert(tree->STB_(N,left)->STB_(N,parent) == tree);) \4673- STB__(N,_validate)(tree->STB_(N,left) ,0); \4674- STB__(N,_validate)(tree->STB_(N,right),0); \4675- } \4676-) \4677- \4678-typedef struct \4679-{ \4680- TYPE *root; \4681-} TREE; \4682- \4683-void STB__(M,Insert)(TREE *tree, TYPE *item) \4684-{ tree->root = STB__(N,insert)(tree->root, item); } \4685-void STB__(M,Remove)(TREE *tree, TYPE *item) \4686-{ tree->root = STB__(N,remove)(tree->root, item); } \4687-TYPE *STB__(M,Next)(TREE *tree, TYPE *item) \4688-{ return STB__(N,next)(tree->root, item); } \4689-TYPE *STB__(M,Prev)(TREE *tree, TYPE *item) \4690-{ return STB__(N,prev)(tree->root, item); } \4691-TYPE *STB__(M,First)(TREE *tree) { return STB__(N,first)(tree->root); } \4692-TYPE *STB__(M,Last) (TREE *tree) { return STB__(N,last) (tree->root); } \4693-void STB__(M,Init)(TREE *tree) { tree->root = NULL; }4694-4695-4696-#define stb_bst_find(N,tree,fcompare) \4697-{ \4698- int c; \4699- while (tree != NULL) { \4700- fcompare \4701- if (c == 0) return tree; \4702- if (c < 0) tree = tree->STB_(N,left); \4703- else tree = tree->STB_(N,right); \4704- } \4705- return NULL; \4706-}4707-4708-#define stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,PAR) \4709- stb_bst_base(TYPE,N,TREE,M, \4710- VTYPE a = p->vfield; VTYPE b = q->vfield; return (compare);, PAR ) \4711- \4712-TYPE *STB__(N,find)(TYPE *tree, VTYPE a) \4713- stb_bst_find(N,tree,VTYPE b = tree->vfield; c = (compare);) \4714-TYPE *STB__(M,Find)(TREE *tree, VTYPE a) \4715-{ return STB__(N,find)(tree->root, a); }4716-4717-#define stb_bst(TYPE,N,TREE,M,vfield,VTYPE,compare) \4718- stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,stb__bst_noparent)4719-#define stb_bst_parent(TYPE,N,TREE,M,vfield,VTYPE,compare) \4720- stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,stb__bst_parent)4721-4722-4723-4724-//////////////////////////////////////////////////////////////////////////////4725-//4726-// Pointer Nulling4727-//4728-// This lets you automatically NULL dangling pointers to "registered"4729-// objects. Note that you have to make sure you call the appropriate4730-// functions when you free or realloc blocks of memory that contain4731-// pointers or pointer targets. stb.h can automatically do this for4732-// stb_arr, or for all frees/reallocs if it's wrapping them.4733-//4734-4735-#ifdef STB_NPTR4736-4737-STB_EXTERN void stb_nptr_set(void *address_of_pointer, void *value_to_write);4738-STB_EXTERN void stb_nptr_didset(void *address_of_pointer);4739-4740-STB_EXTERN void stb_nptr_didfree(void *address_being_freed, int len);4741-STB_EXTERN void stb_nptr_free(void *address_being_freed, int len);4742-4743-STB_EXTERN void stb_nptr_didrealloc(void *new_address, void *old_address, int len);4744-STB_EXTERN void stb_nptr_recache(void); // recache all known pointers4745- // do this after pointer sets outside your control, slow4746-4747-#ifdef STB_DEFINE4748-// for fast updating on free/realloc, we need to be able to find4749-// all the objects (pointers and targets) within a given block;4750-// this precludes hashing4751-4752-// we use a three-level hierarchy of memory to minimize storage:4753-// level 1: 65536 pointers to stb__memory_node (always uses 256 KB)4754-// level 2: each stb__memory_node represents a 64K block of memory4755-// with 256 stb__memory_leafs (worst case 64MB)4756-// level 3: each stb__memory_leaf represents 256 bytes of memory4757-// using a list of target locations and a list of pointers4758-// (which are hopefully fairly short normally!)4759-4760-// this approach won't work in 64-bit, which has a much larger address4761-// space. need to redesign4762-4763-#define STB__NPTR_ROOT_LOG2 164764-#define STB__NPTR_ROOT_NUM (1 << STB__NPTR_ROOT_LOG2)4765-#define STB__NPTR_ROOT_SHIFT (32 - STB__NPTR_ROOT_LOG2)4766-4767-#define STB__NPTR_NODE_LOG2 54768-#define STB__NPTR_NODE_NUM (1 << STB__NPTR_NODE_LOG2)4769-#define STB__NPTR_NODE_MASK (STB__NPTR_NODE_NUM-1)4770-#define STB__NPTR_NODE_SHIFT (STB__NPTR_ROOT_SHIFT - STB__NPTR_NODE_LOG2)4771-#define STB__NPTR_NODE_OFFSET(x) (((x) >> STB__NPTR_NODE_SHIFT) & STB__NPTR_NODE_MASK)4772-4773-typedef struct stb__st_nptr4774-{4775- void *ptr; // address of actual pointer4776- struct stb__st_nptr *next; // next pointer with same target4777- struct stb__st_nptr **prev; // prev pointer with same target, address of 'next' field (or first)4778- struct stb__st_nptr *next_in_block;4779-} stb__nptr;4780-4781-typedef struct stb__st_nptr_target4782-{4783- void *ptr; // address of target4784- stb__nptr *first; // address of first nptr pointing to this4785- struct stb__st_nptr_target *next_in_block;4786-} stb__nptr_target;4787-4788-typedef struct4789-{4790- stb__nptr *pointers;4791- stb__nptr_target *targets;4792-} stb__memory_leaf;4793-4794-typedef struct4795-{4796- stb__memory_leaf *children[STB__NPTR_NODE_NUM];4797-} stb__memory_node;4798-4799-stb__memory_node *stb__memtab_root[STB__NPTR_ROOT_NUM];4800-4801-static stb__memory_leaf *stb__nptr_find_leaf(void *mem)4802-{4803- stb_uint32 address = (stb_uint32) mem;4804- stb__memory_node *z = stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT];4805- if (z)4806- return z->children[STB__NPTR_NODE_OFFSET(address)];4807- else4808- return NULL;4809-}4810-4811-static void * stb__nptr_alloc(int size)4812-{4813- return stb__realloc_raw(0,size);4814-}4815-4816-static void stb__nptr_free(void *p)4817-{4818- stb__realloc_raw(p,0);4819-}4820-4821-static stb__memory_leaf *stb__nptr_make_leaf(void *mem)4822-{4823- stb_uint32 address = (stb_uint32) mem;4824- stb__memory_node *z = stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT];4825- stb__memory_leaf *f;4826- if (!z) {4827- int i;4828- z = (stb__memory_node *) stb__nptr_alloc(sizeof(*stb__memtab_root[0]));4829- stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT] = z;4830- for (i=0; i < 256; ++i)4831- z->children[i] = 0;4832- }4833- f = (stb__memory_leaf *) stb__nptr_alloc(sizeof(*f));4834- z->children[STB__NPTR_NODE_OFFSET(address)] = f;4835- f->pointers = NULL;4836- f->targets = NULL;4837- return f;4838-}4839-4840-static stb__nptr_target *stb__nptr_find_target(void *target, int force)4841-{4842- stb__memory_leaf *p = stb__nptr_find_leaf(target);4843- if (p) {4844- stb__nptr_target *t = p->targets;4845- while (t) {4846- if (t->ptr == target)4847- return t;4848- t = t->next_in_block;4849- }4850- }4851- if (force) {4852- stb__nptr_target *t = (stb__nptr_target*) stb__nptr_alloc(sizeof(*t));4853- if (!p) p = stb__nptr_make_leaf(target);4854- t->ptr = target;4855- t->first = NULL;4856- t->next_in_block = p->targets;4857- p->targets = t;4858- return t;4859- } else4860- return NULL;4861-}4862-4863-static stb__nptr *stb__nptr_find_pointer(void *ptr, int force)4864-{4865- stb__memory_leaf *p = stb__nptr_find_leaf(ptr);4866- if (p) {4867- stb__nptr *t = p->pointers;4868- while (t) {4869- if (t->ptr == ptr)4870- return t;4871- t = t->next_in_block;4872- }4873- }4874- if (force) {4875- stb__nptr *t = (stb__nptr *) stb__nptr_alloc(sizeof(*t));4876- if (!p) p = stb__nptr_make_leaf(ptr);4877- t->ptr = ptr;4878- t->next = NULL;4879- t->prev = NULL;4880- t->next_in_block = p->pointers;4881- p->pointers = t;4882- return t;4883- } else4884- return NULL;4885-}4886-4887-void stb_nptr_set(void *address_of_pointer, void *value_to_write)4888-{4889- if (*(void **)address_of_pointer != value_to_write) {4890- *(void **) address_of_pointer = value_to_write;4891- stb_nptr_didset(address_of_pointer);4892- }4893-}4894-4895-void stb_nptr_didset(void *address_of_pointer)4896-{4897- // first unlink from old chain4898- void *new_address;4899- stb__nptr *p = stb__nptr_find_pointer(address_of_pointer, 1); // force building if doesn't exist4900- if (p->prev) { // if p->prev is NULL, we just built it, or it was NULL4901- *(p->prev) = p->next;4902- if (p->next) p->next->prev = p->prev;4903- }4904- // now add to new chain4905- new_address = *(void **)address_of_pointer;4906- if (new_address != NULL) {4907- stb__nptr_target *t = stb__nptr_find_target(new_address, 1);4908- p->next = t->first;4909- if (p->next) p->next->prev = &p->next;4910- p->prev = &t->first;4911- t->first = p;4912- } else {4913- p->prev = NULL;4914- p->next = NULL;4915- }4916-}4917-4918-void stb__nptr_block(void *address, int len, void (*function)(stb__memory_leaf *f, int datum, void *start, void *end), int datum)4919-{4920- void *end_address = (void *) ((char *) address + len - 1);4921- stb__memory_node *n;4922- stb_uint32 start = (stb_uint32) address;4923- stb_uint32 end = start + len - 1;4924-4925- int b0 = start >> STB__NPTR_ROOT_SHIFT;4926- int b1 = end >> STB__NPTR_ROOT_SHIFT;4927- int b=b0,i,e0,e1;4928-4929- e0 = STB__NPTR_NODE_OFFSET(start);4930-4931- if (datum <= 0) {4932- // first block4933- n = stb__memtab_root[b0];4934- if (n) {4935- if (b0 != b1)4936- e1 = STB__NPTR_NODE_NUM-1;4937- else4938- e1 = STB__NPTR_NODE_OFFSET(end);4939- for (i=e0; i <= e1; ++i)4940- if (n->children[i])4941- function(n->children[i], datum, address, end_address);4942- }4943- if (b1 > b0) {4944- // blocks other than the first and last block4945- for (b=b0+1; b < b1; ++b) {4946- n = stb__memtab_root[b];4947- if (n)4948- for (i=0; i <= STB__NPTR_NODE_NUM-1; ++i)4949- if (n->children[i])4950- function(n->children[i], datum, address, end_address);4951- }4952- // last block4953- n = stb__memtab_root[b1];4954- if (n) {4955- e1 = STB__NPTR_NODE_OFFSET(end);4956- for (i=0; i <= e1; ++i)4957- if (n->children[i])4958- function(n->children[i], datum, address, end_address);4959- }4960- }4961- } else {4962- if (b1 > b0) {4963- // last block4964- n = stb__memtab_root[b1];4965- if (n) {4966- e1 = STB__NPTR_NODE_OFFSET(end);4967- for (i=e1; i >= 0; --i)4968- if (n->children[i])4969- function(n->children[i], datum, address, end_address);4970- }4971- // blocks other than the first and last block4972- for (b=b1-1; b > b0; --b) {4973- n = stb__memtab_root[b];4974- if (n)4975- for (i=STB__NPTR_NODE_NUM-1; i >= 0; --i)4976- if (n->children[i])4977- function(n->children[i], datum, address, end_address);4978- }4979- }4980- // first block4981- n = stb__memtab_root[b0];4982- if (n) {4983- if (b0 != b1)4984- e1 = STB__NPTR_NODE_NUM-1;4985- else4986- e1 = STB__NPTR_NODE_OFFSET(end);4987- for (i=e1; i >= e0; --i)4988- if (n->children[i])4989- function(n->children[i], datum, address, end_address);4990- }4991- }4992-}4993-4994-static void stb__nptr_delete_pointers(stb__memory_leaf *f, int offset, void *start, void *end)4995-{4996- stb__nptr **p = &f->pointers;4997- while (*p) {4998- stb__nptr *n = *p;4999- if (n->ptr >= start && n->ptr <= end) {5000- // unlink5001- if (n->prev) {5002- *(n->prev) = n->next;5003- if (n->next) n->next->prev = n->prev;5004- }5005- *p = n->next_in_block;5006- stb__nptr_free(n);5007- } else5008- p = &(n->next_in_block);5009- }5010-}5011-5012-static void stb__nptr_delete_targets(stb__memory_leaf *f, int offset, void *start, void *end)5013-{5014- stb__nptr_target **p = &f->targets;5015- while (*p) {5016- stb__nptr_target *n = *p;5017- if (n->ptr >= start && n->ptr <= end) {5018- // null pointers5019- stb__nptr *z = n->first;5020- while (z) {5021- stb__nptr *y = z->next;5022- z->prev = NULL;5023- z->next = NULL;5024- *(void **) z->ptr = NULL;5025- z = y;5026- }5027- // unlink this target5028- *p = n->next_in_block;5029- stb__nptr_free(n);5030- } else5031- p = &(n->next_in_block);5032- }5033-}5034-5035-void stb_nptr_didfree(void *address_being_freed, int len)5036-{5037- // step one: delete all pointers in this block5038- stb__nptr_block(address_being_freed, len, stb__nptr_delete_pointers, 0);5039- // step two: NULL all pointers to this block; do this second to avoid NULLing deleted pointers5040- stb__nptr_block(address_being_freed, len, stb__nptr_delete_targets, 0);5041-}5042-5043-void stb_nptr_free(void *address_being_freed, int len)5044-{5045- free(address_being_freed);5046- stb_nptr_didfree(address_being_freed, len);5047-}5048-5049-static void stb__nptr_move_targets(stb__memory_leaf *f, int offset, void *start, void *end)5050-{5051- stb__nptr_target **t = &f->targets;5052- while (*t) {5053- stb__nptr_target *n = *t;5054- if (n->ptr >= start && n->ptr <= end) {5055- stb__nptr *z;5056- stb__memory_leaf *f;5057- // unlink n5058- *t = n->next_in_block;5059- // update n to new address5060- n->ptr = (void *) ((char *) n->ptr + offset);5061- f = stb__nptr_find_leaf(n->ptr);5062- if (!f) f = stb__nptr_make_leaf(n->ptr);5063- n->next_in_block = f->targets;5064- f->targets = n;5065- // now go through all pointers and make them point here5066- z = n->first;5067- while (z) {5068- *(void**) z->ptr = n->ptr;5069- z = z->next;5070- }5071- } else5072- t = &(n->next_in_block);5073- }5074-}5075-5076-static void stb__nptr_move_pointers(stb__memory_leaf *f, int offset, void *start, void *end)5077-{5078- stb__nptr **p = &f->pointers;5079- while (*p) {5080- stb__nptr *n = *p;5081- if (n->ptr >= start && n->ptr <= end) {5082- // unlink5083- *p = n->next_in_block;5084- n->ptr = (void *) ((int) n->ptr + offset);5085- // move to new block5086- f = stb__nptr_find_leaf(n->ptr);5087- if (!f) f = stb__nptr_make_leaf(n->ptr);5088- n->next_in_block = f->pointers;5089- f->pointers = n;5090- } else5091- p = &(n->next_in_block);5092- }5093-}5094-5095-void stb_nptr_realloc(void *new_address, void *old_address, int len)5096-{5097- if (new_address == old_address) return;5098-5099- // have to move the pointers first, because moving the targets5100- // requires writing to the pointers-to-the-targets, and if some of those moved too,5101- // we need to make sure we don't write to the old memory5102-5103- // step one: move all pointers within the block5104- stb__nptr_block(old_address, len, stb__nptr_move_pointers, (char *) new_address - (char *) old_address);5105- // step two: move all targets within the block5106- stb__nptr_block(old_address, len, stb__nptr_move_targets, (char *) new_address - (char *) old_address);5107-}5108-5109-void stb_nptr_move(void *new_address, void *old_address)5110-{5111- stb_nptr_realloc(new_address, old_address, 1);5112-}5113-5114-void stb_nptr_recache(void)5115-{5116- int i,j;5117- for (i=0; i < STB__NPTR_ROOT_NUM; ++i)5118- if (stb__memtab_root[i])5119- for (j=0; j < STB__NPTR_NODE_NUM; ++j)5120- if (stb__memtab_root[i]->children[j]) {5121- stb__nptr *p = stb__memtab_root[i]->children[j]->pointers;5122- while (p) {5123- stb_nptr_didset(p->ptr);5124- p = p->next_in_block;5125- }5126- }5127-}5128-5129-#endif // STB_DEFINE5130-#endif // STB_NPTR5131-5132-5133-//////////////////////////////////////////////////////////////////////////////5134-//5135-// File Processing5136-//5137-5138-5139-#ifdef _WIN325140- #define stb_rename(x,y) _wrename((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y))5141-#else5142- #define stb_rename rename5143-#endif5144-5145-STB_EXTERN void stb_fput_varlen64(FILE *f, stb_uint64 v);5146-STB_EXTERN stb_uint64 stb_fget_varlen64(FILE *f);5147-STB_EXTERN int stb_size_varlen64(stb_uint64 v);5148-5149-5150-#define stb_filec (char *) stb_file5151-#define stb_fileu (unsigned char *) stb_file5152-STB_EXTERN void * stb_file(char *filename, size_t *length);5153-STB_EXTERN void * stb_file_max(char *filename, size_t *length);5154-STB_EXTERN size_t stb_filelen(FILE *f);5155-STB_EXTERN int stb_filewrite(char *filename, void *data, size_t length);5156-STB_EXTERN int stb_filewritestr(char *filename, char *data);5157-STB_EXTERN char ** stb_stringfile(char *filename, int *len);5158-STB_EXTERN char ** stb_stringfile_trimmed(char *name, int *len, char comm);5159-STB_EXTERN char * stb_fgets(char *buffer, int buflen, FILE *f);5160-STB_EXTERN char * stb_fgets_malloc(FILE *f);5161-STB_EXTERN int stb_fexists(char *filename);5162-STB_EXTERN int stb_fcmp(char *s1, char *s2);5163-STB_EXTERN int stb_feq(char *s1, char *s2);5164-STB_EXTERN time_t stb_ftimestamp(char *filename);5165-5166-STB_EXTERN int stb_fullpath(char *abs, int abs_size, char *rel);5167-STB_EXTERN FILE * stb_fopen(char *filename, const char *mode);5168-STB_EXTERN int stb_fclose(FILE *f, int keep);5169-5170-enum5171-{5172- stb_keep_no = 0,5173- stb_keep_yes = 1,5174- stb_keep_if_different = 2,5175-};5176-5177-STB_EXTERN int stb_copyfile(char *src, char *dest);5178-5179-STB_EXTERN void stb_fput_varlen64(FILE *f, stb_uint64 v);5180-STB_EXTERN stb_uint64 stb_fget_varlen64(FILE *f);5181-STB_EXTERN int stb_size_varlen64(stb_uint64 v);5182-5183-STB_EXTERN void stb_fwrite32(FILE *f, stb_uint32 datum);5184-STB_EXTERN void stb_fput_varlen (FILE *f, int v);5185-STB_EXTERN void stb_fput_varlenu(FILE *f, unsigned int v);5186-STB_EXTERN int stb_fget_varlen (FILE *f);5187-STB_EXTERN stb_uint stb_fget_varlenu(FILE *f);5188-STB_EXTERN void stb_fput_ranged (FILE *f, int v, int b, stb_uint n);5189-STB_EXTERN int stb_fget_ranged (FILE *f, int b, stb_uint n);5190-STB_EXTERN int stb_size_varlen (int v);5191-STB_EXTERN int stb_size_varlenu(unsigned int v);5192-STB_EXTERN int stb_size_ranged (int b, stb_uint n);5193-5194-STB_EXTERN int stb_fread(void *data, size_t len, size_t count, void *f);5195-STB_EXTERN int stb_fwrite(void *data, size_t len, size_t count, void *f);5196-5197-#if 05198-typedef struct5199-{5200- FILE *base_file;5201- char *buffer;5202- int buffer_size;5203- int buffer_off;5204- int buffer_left;5205-} STBF;5206-5207-STB_EXTERN STBF *stb_tfopen(char *filename, char *mode);5208-STB_EXTERN int stb_tfread(void *data, size_t len, size_t count, STBF *f);5209-STB_EXTERN int stb_tfwrite(void *data, size_t len, size_t count, STBF *f);5210-#endif5211-5212-#ifdef STB_DEFINE5213-5214-#if 05215-STBF *stb_tfopen(char *filename, char *mode)5216-{5217- STBF *z;5218- FILE *f = stb_p_fopen(filename, mode);5219- if (!f) return NULL;5220- z = (STBF *) malloc(sizeof(*z));5221- if (!z) { fclose(f); return NULL; }5222- z->base_file = f;5223- if (!strcmp(mode, "rb") || !strcmp(mode, "wb")) {5224- z->buffer_size = 4096;5225- z->buffer_off = z->buffer_size;5226- z->buffer_left = 0;5227- z->buffer = malloc(z->buffer_size);5228- if (!z->buffer) { free(z); fclose(f); return NULL; }5229- } else {5230- z->buffer = 0;5231- z->buffer_size = 0;5232- z->buffer_left = 0;5233- }5234- return z;5235-}5236-5237-int stb_tfread(void *data, size_t len, size_t count, STBF *f)5238-{5239- int total = len*count, done=0;5240- if (!total) return 0;5241- if (total <= z->buffer_left) {5242- memcpy(data, z->buffer + z->buffer_off, total);5243- z->buffer_off += total;5244- z->buffer_left -= total;5245- return count;5246- } else {5247- char *out = (char *) data;5248-5249- // consume all buffered data5250- memcpy(data, z->buffer + z->buffer_off, z->buffer_left);5251- done = z->buffer_left;5252- out += z->buffer_left;5253- z->buffer_left=0;5254-5255- if (total-done > (z->buffer_size >> 1)) {5256- done += fread(out5257- }5258- }5259-}5260-#endif5261-5262-void stb_fwrite32(FILE *f, stb_uint32 x)5263-{5264- fwrite(&x, 4, 1, f);5265-}5266-5267-#if defined(_WIN32)5268- #define stb__stat _stat5269-#else5270- #define stb__stat stat5271-#endif5272-5273-int stb_fexists(char *filename)5274-{5275- struct stb__stat buf;5276- return stb__windows(5277- _wstat((const wchar_t *)stb__from_utf8(filename), &buf),5278- stat(filename,&buf)5279- ) == 0;5280-}5281-5282-time_t stb_ftimestamp(char *filename)5283-{5284- struct stb__stat buf;5285- if (stb__windows(5286- _wstat((const wchar_t *)stb__from_utf8(filename), &buf),5287- stat(filename,&buf)5288- ) == 0)5289- {5290- return buf.st_mtime;5291- } else {5292- return 0;5293- }5294-}5295-5296-size_t stb_filelen(FILE *f)5297-{5298- long len, pos;5299- pos = ftell(f);5300- fseek(f, 0, SEEK_END);5301- len = ftell(f);5302- fseek(f, pos, SEEK_SET);5303- return (size_t) len;5304-}5305-5306-void *stb_file(char *filename, size_t *length)5307-{5308- FILE *f = stb__fopen(filename, "rb");5309- char *buffer;5310- size_t len, len2;5311- if (!f) return NULL;5312- len = stb_filelen(f);5313- buffer = (char *) malloc(len+2); // nul + extra5314- len2 = fread(buffer, 1, len, f);5315- if (len2 == len) {5316- if (length) *length = len;5317- buffer[len] = 0;5318- } else {5319- free(buffer);5320- buffer = NULL;5321- }5322- fclose(f);5323- return buffer;5324-}5325-5326-int stb_filewrite(char *filename, void *data, size_t length)5327-{5328- FILE *f = stb_fopen(filename, "wb");5329- if (f) {5330- unsigned char *data_ptr = (unsigned char *) data;5331- size_t remaining = length;5332- while (remaining > 0) {5333- size_t len2 = remaining > 65536 ? 65536 : remaining;5334- size_t len3 = fwrite(data_ptr, 1, len2, f);5335- if (len2 != len3) {5336- fprintf(stderr, "Failed while writing %s\n", filename);5337- break;5338- }5339- remaining -= len2;5340- data_ptr += len2;5341- }5342- stb_fclose(f, stb_keep_if_different);5343- }5344- return f != NULL;5345-}5346-5347-int stb_filewritestr(char *filename, char *data)5348-{5349- return stb_filewrite(filename, data, strlen(data));5350-}5351-5352-void * stb_file_max(char *filename, size_t *length)5353-{5354- FILE *f = stb__fopen(filename, "rb");5355- char *buffer;5356- size_t len, maxlen;5357- if (!f) return NULL;5358- maxlen = *length;5359- buffer = (char *) malloc(maxlen+1);5360- len = fread(buffer, 1, maxlen, f);5361- buffer[len] = 0;5362- fclose(f);5363- *length = len;5364- return buffer;5365-}5366-5367-char ** stb_stringfile(char *filename, int *plen)5368-{5369- FILE *f = stb__fopen(filename, "rb");5370- char *buffer, **list=NULL, *s;5371- size_t len, count, i;5372-5373- if (!f) return NULL;5374- len = stb_filelen(f);5375- buffer = (char *) malloc(len+1);5376- len = fread(buffer, 1, len, f);5377- buffer[len] = 0;5378- fclose(f);5379-5380- // two passes through: first time count lines, second time set them5381- for (i=0; i < 2; ++i) {5382- s = buffer;5383- if (i == 1)5384- list[0] = s;5385- count = 1;5386- while (*s) {5387- if (*s == '\n' || *s == '\r') {5388- // detect if both cr & lf are together5389- int crlf = (s[0] + s[1]) == ('\n' + '\r');5390- if (i == 1) *s = 0;5391- if (crlf) ++s;5392- if (s[1]) { // it's not over yet5393- if (i == 1) list[count] = s+1;5394- ++count;5395- }5396- }5397- ++s;5398- }5399- if (i == 0) {5400- list = (char **) malloc(sizeof(*list) * (count+1) + len+1);5401- if (!list) return NULL;5402- list[count] = 0;5403- // recopy the file so there's just a single allocation to free5404- memcpy(&list[count+1], buffer, len+1);5405- free(buffer);5406- buffer = (char *) &list[count+1];5407- if (plen) *plen = (int) count;5408- }5409- }5410- return list;5411-}5412-5413-char ** stb_stringfile_trimmed(char *name, int *len, char comment)5414-{5415- int i,n,o=0;5416- char **s = stb_stringfile(name, &n);5417- if (s == NULL) return NULL;5418- for (i=0; i < n; ++i) {5419- char *p = stb_skipwhite(s[i]);5420- if (*p && *p != comment)5421- s[o++] = p;5422- }5423- s[o] = NULL;5424- if (len) *len = o;5425- return s;5426-}5427-5428-char * stb_fgets(char *buffer, int buflen, FILE *f)5429-{5430- char *p;5431- buffer[0] = 0;5432- p = fgets(buffer, buflen, f);5433- if (p) {5434- int n = (int) (strlen(p)-1);5435- if (n >= 0)5436- if (p[n] == '\n')5437- p[n] = 0;5438- }5439- return p;5440-}5441-5442-char * stb_fgets_malloc(FILE *f)5443-{5444- // avoid reallocing for small strings5445- char quick_buffer[800];5446- quick_buffer[sizeof(quick_buffer)-2] = 0;5447- if (!fgets(quick_buffer, sizeof(quick_buffer), f))5448- return NULL;5449-5450- if (quick_buffer[sizeof(quick_buffer)-2] == 0) {5451- size_t n = strlen(quick_buffer);5452- if (n > 0 && quick_buffer[n-1] == '\n')5453- quick_buffer[n-1] = 0;5454- return stb_p_strdup(quick_buffer);5455- } else {5456- char *p;5457- char *a = stb_p_strdup(quick_buffer);5458- size_t len = sizeof(quick_buffer)-1;5459-5460- while (!feof(f)) {5461- if (a[len-1] == '\n') break;5462- a = (char *) realloc(a, len*2);5463- p = &a[len];5464- p[len-2] = 0;5465- if (!fgets(p, (int) len, f))5466- break;5467- if (p[len-2] == 0) {5468- len += strlen(p);5469- break;5470- }5471- len = len + (len-1);5472- }5473- if (a[len-1] == '\n')5474- a[len-1] = 0;5475- return a;5476- }5477-}5478-5479-int stb_fullpath(char *abs, int abs_size, char *rel)5480-{5481- #ifdef _WIN325482- return _fullpath(abs, rel, abs_size) != NULL;5483- #else5484- if (rel[0] == '/' || rel[0] == '~') {5485- if ((int) strlen(rel) >= abs_size)5486- return 0;5487- stb_p_strcpy_s(abs,65536,rel);5488- return STB_TRUE;5489- } else {5490- int n;5491- getcwd(abs, abs_size);5492- n = strlen(abs);5493- if (n+(int) strlen(rel)+2 <= abs_size) {5494- abs[n] = '/';5495- stb_p_strcpy_s(abs+n+1, 65536,rel);5496- return STB_TRUE;5497- } else {5498- return STB_FALSE;5499- }5500- }5501- #endif5502-}5503-5504-static int stb_fcmp_core(FILE *f, FILE *g)5505-{5506- char buf1[1024],buf2[1024];5507- int n1,n2, res=0;5508-5509- while (1) {5510- n1 = (int) fread(buf1, 1, sizeof(buf1), f);5511- n2 = (int) fread(buf2, 1, sizeof(buf2), g);5512- res = memcmp(buf1,buf2,stb_min(n1,n2));5513- if (res)5514- break;5515- if (n1 != n2) {5516- res = n1 < n2 ? -1 : 1;5517- break;5518- }5519- if (n1 == 0)5520- break;5521- }5522-5523- fclose(f);5524- fclose(g);5525- return res;5526-}5527-5528-int stb_fcmp(char *s1, char *s2)5529-{5530- FILE *f = stb__fopen(s1, "rb");5531- FILE *g = stb__fopen(s2, "rb");5532-5533- if (f == NULL || g == NULL) {5534- if (f) fclose(f);5535- if (g) {5536- fclose(g);5537- return STB_TRUE;5538- }5539- return f != NULL;5540- }5541-5542- return stb_fcmp_core(f,g);5543-}5544-5545-int stb_feq(char *s1, char *s2)5546-{5547- FILE *f = stb__fopen(s1, "rb");5548- FILE *g = stb__fopen(s2, "rb");5549-5550- if (f == NULL || g == NULL) {5551- if (f) fclose(f);5552- if (g) fclose(g);5553- return f == g;5554- }5555-5556- // feq is faster because it shortcuts if they're different length5557- if (stb_filelen(f) != stb_filelen(g)) {5558- fclose(f);5559- fclose(g);5560- return 0;5561- }5562-5563- return !stb_fcmp_core(f,g);5564-}5565-5566-static stb_ptrmap *stb__files;5567-5568-typedef struct5569-{5570- char *temp_name;5571- char *name;5572- int errors;5573-} stb__file_data;5574-5575-static FILE *stb__open_temp_file(char *temp_name, char *src_name, const char *mode)5576-{5577- size_t p;5578-#ifdef _MSC_VER5579- int j;5580-#endif5581- FILE *f;5582- // try to generate a temporary file in the same directory5583- p = strlen(src_name)-1;5584- while (p > 0 && src_name[p] != '/' && src_name[p] != '\\'5585- && src_name[p] != ':' && src_name[p] != '~')5586- --p;5587- ++p;5588-5589- memcpy(temp_name, src_name, p);5590-5591- #ifdef _MSC_VER5592- // try multiple times to make a temp file... just in5593- // case some other process makes the name first5594- for (j=0; j < 32; ++j) {5595- stb_p_strcpy_s(temp_name+p, 65536, "stmpXXXXXX");5596- if (!stb_p_mktemp(temp_name))5597- return 0;5598-5599- f = stb_p_fopen(temp_name, mode);5600- if (f != NULL)5601- break;5602- }5603- #else5604- {5605- stb_p_strcpy_s(temp_name+p, 65536, "stmpXXXXXX");5606- #ifdef __MINGW32__5607- int fd = open(stb_p_mktemp(temp_name), O_RDWR);5608- #else5609- int fd = mkstemp(temp_name);5610- #endif5611- if (fd == -1) return NULL;5612- f = fdopen(fd, mode);5613- if (f == NULL) {5614- unlink(temp_name);5615- close(fd);5616- return NULL;5617- }5618- }5619- #endif5620- return f;5621-}5622-5623-5624-FILE * stb_fopen(char *filename, const char *mode)5625-{5626- FILE *f;5627- char name_full[4096];5628- char temp_full[sizeof(name_full) + 12];5629-5630- // @TODO: if the file doesn't exist, we can also use the fastpath here5631- if (mode[0] != 'w' && !strchr(mode, '+'))5632- return stb__fopen(filename, mode);5633-5634- // save away the full path to the file so if the program5635- // changes the cwd everything still works right! unix has5636- // better ways to do this, but we have to work in windows5637- name_full[0] = '\0'; // stb_fullpath reads name_full[0]5638- if (stb_fullpath(name_full, sizeof(name_full), filename)==0)5639- return 0;5640-5641- f = stb__open_temp_file(temp_full, name_full, mode);5642- if (f != NULL) {5643- stb__file_data *d = (stb__file_data *) malloc(sizeof(*d));5644- if (!d) { assert(0); /* NOTREACHED */fclose(f); return NULL; }5645- if (stb__files == NULL) stb__files = stb_ptrmap_create();5646- d->temp_name = stb_p_strdup(temp_full);5647- d->name = stb_p_strdup(name_full);5648- d->errors = 0;5649- stb_ptrmap_add(stb__files, f, d);5650- return f;5651- }5652-5653- return NULL;5654-}5655-5656-int stb_fclose(FILE *f, int keep)5657-{5658- stb__file_data *d;5659-5660- int ok = STB_FALSE;5661- if (f == NULL) return 0;5662-5663- if (ferror(f))5664- keep = stb_keep_no;5665-5666- fclose(f);5667-5668- if (stb__files && stb_ptrmap_remove(stb__files, f, (void **) &d)) {5669- if (stb__files->count == 0) {5670- stb_ptrmap_destroy(stb__files);5671- stb__files = NULL;5672- }5673- } else5674- return STB_TRUE; // not special5675-5676- if (keep == stb_keep_if_different) {5677- // check if the files are identical5678- if (stb_feq(d->name, d->temp_name)) {5679- keep = stb_keep_no;5680- ok = STB_TRUE; // report success if no change5681- }5682- }5683-5684- if (keep == stb_keep_no) {5685- remove(d->temp_name);5686- } else {5687- if (!stb_fexists(d->name)) {5688- // old file doesn't exist, so just move the new file over it5689- stb_rename(d->temp_name, d->name);5690- } else {5691- // don't delete the old file yet in case there are troubles! First rename it!5692- char preserved_old_file[4096];5693-5694- // generate a temp filename in the same directory (also creates it, which we don't need)5695- FILE *dummy = stb__open_temp_file(preserved_old_file, d->name, "wb");5696- if (dummy != NULL) {5697- // we don't actually want the open file5698- fclose(dummy);5699-5700- // discard what we just created5701- remove(preserved_old_file); // if this fails, there's nothing we can do, and following logic handles it as best as possible anyway5702-5703- // move the existing file to the preserved name5704- if (0 != stb_rename(d->name, preserved_old_file)) { // 0 on success5705- // failed, state is:5706- // filename -> old file5707- // tempname -> new file5708- // keep tempname around so we don't lose data5709- } else {5710- // state is:5711- // preserved -> old file5712- // tempname -> new file5713- // move the new file to the old name5714- if (0 == stb_rename(d->temp_name, d->name)) {5715- // state is:5716- // preserved -> old file5717- // filename -> new file5718- ok = STB_TRUE;5719-5720- // 'filename -> new file' has always been the goal, so clean up5721- remove(preserved_old_file); // nothing to be done if it fails5722- } else {5723- // couldn't rename, so try renaming preserved file back5724-5725- // state is:5726- // preserved -> old file5727- // tempname -> new file5728- stb_rename(preserved_old_file, d->name);5729- // if the rename failed, there's nothing more we can do5730- }5731- }5732- } else {5733- // we couldn't get a temp filename. do this the naive way; the worst case failure here5734- // leaves the filename pointing to nothing and the new file as a tempfile5735- remove(d->name);5736- stb_rename(d->temp_name, d->name);5737- }5738- }5739- }5740-5741- free(d->temp_name);5742- free(d->name);5743- free(d);5744-5745- return ok;5746-}5747-5748-int stb_copyfile(char *src, char *dest)5749-{5750- char raw_buffer[1024];5751- char *buffer;5752- int buf_size = 65536;5753-5754- FILE *f, *g;5755-5756- // if file already exists at destination, do nothing5757- if (stb_feq(src, dest)) return STB_TRUE;5758-5759- // open file5760- f = stb__fopen(src, "rb");5761- if (f == NULL) return STB_FALSE;5762-5763- // open file for writing5764- g = stb__fopen(dest, "wb");5765- if (g == NULL) {5766- fclose(f);5767- return STB_FALSE;5768- }5769-5770- buffer = (char *) malloc(buf_size);5771- if (buffer == NULL) {5772- buffer = raw_buffer;5773- buf_size = sizeof(raw_buffer);5774- }5775-5776- while (!feof(f)) {5777- size_t n = fread(buffer, 1, buf_size, f);5778- if (n != 0)5779- fwrite(buffer, 1, n, g);5780- }5781-5782- fclose(f);5783- if (buffer != raw_buffer)5784- free(buffer);5785-5786- fclose(g);5787- return STB_TRUE;5788-}5789-5790-// varlen:5791-// v' = (v >> 31) + (v < 0 ? ~v : v)<<1; // small abs(v) => small v'5792-// output v as big endian v'+k for v' <= k:5793-// 1 byte : v' <= 0x00000080 ( -64 <= v < 64) 7 bits5794-// 2 bytes: v' <= 0x00004000 (-8192 <= v < 8192) 14 bits5795-// 3 bytes: v' <= 0x00200000 21 bits5796-// 4 bytes: v' <= 0x10000000 28 bits5797-// the number of most significant 1-bits in the first byte5798-// equals the number of bytes after the first5799-5800-#define stb__varlen_xform(v) (v<0 ? (~v << 1)+1 : (v << 1))5801-5802-int stb_size_varlen(int v) { return stb_size_varlenu(stb__varlen_xform(v)); }5803-int stb_size_varlenu(unsigned int v)5804-{5805- if (v < 0x00000080) return 1;5806- if (v < 0x00004000) return 2;5807- if (v < 0x00200000) return 3;5808- if (v < 0x10000000) return 4;5809- return 5;5810-}5811-5812-void stb_fput_varlen(FILE *f, int v) { stb_fput_varlenu(f, stb__varlen_xform(v)); }5813-5814-void stb_fput_varlenu(FILE *f, unsigned int z)5815-{5816- if (z >= 0x10000000) fputc(0xF0,f);5817- if (z >= 0x00200000) fputc((z < 0x10000000 ? 0xE0 : 0)+(z>>24),f);5818- if (z >= 0x00004000) fputc((z < 0x00200000 ? 0xC0 : 0)+(z>>16),f);5819- if (z >= 0x00000080) fputc((z < 0x00004000 ? 0x80 : 0)+(z>> 8),f);5820- fputc(z,f);5821-}5822-5823-#define stb_fgetc(f) ((unsigned char) fgetc(f))5824-5825-int stb_fget_varlen(FILE *f)5826-{5827- unsigned int z = stb_fget_varlenu(f);5828- return (z & 1) ? ~(z>>1) : (z>>1);5829-}5830-5831-unsigned int stb_fget_varlenu(FILE *f)5832-{5833- unsigned int z;5834- unsigned char d;5835- d = stb_fgetc(f);5836-5837- if (d >= 0x80) {5838- if (d >= 0xc0) {5839- if (d >= 0xe0) {5840- if (d == 0xf0) z = stb_fgetc(f) << 24;5841- else z = (d - 0xe0) << 24;5842- z += stb_fgetc(f) << 16;5843- }5844- else5845- z = (d - 0xc0) << 16;5846- z += stb_fgetc(f) << 8;5847- } else5848- z = (d - 0x80) << 8;5849- z += stb_fgetc(f);5850- } else5851- z = d;5852- return z;5853-}5854-5855-stb_uint64 stb_fget_varlen64(FILE *f)5856-{5857- stb_uint64 z;5858- unsigned char d;5859- d = stb_fgetc(f);5860-5861- if (d >= 0x80) {5862- if (d >= 0xc0) {5863- if (d >= 0xe0) {5864- if (d >= 0xf0) {5865- if (d >= 0xf8) {5866- if (d >= 0xfc) {5867- if (d >= 0xfe) {5868- if (d >= 0xff)5869- z = (stb_uint64) stb_fgetc(f) << 56;5870- else5871- z = (stb_uint64) (d - 0xfe) << 56;5872- z |= (stb_uint64) stb_fgetc(f) << 48;5873- } else z = (stb_uint64) (d - 0xfc) << 48;5874- z |= (stb_uint64) stb_fgetc(f) << 40;5875- } else z = (stb_uint64) (d - 0xf8) << 40;5876- z |= (stb_uint64) stb_fgetc(f) << 32;5877- } else z = (stb_uint64) (d - 0xf0) << 32;5878- z |= (stb_uint) stb_fgetc(f) << 24;5879- } else z = (stb_uint) (d - 0xe0) << 24;5880- z |= (stb_uint) stb_fgetc(f) << 16;5881- } else z = (stb_uint) (d - 0xc0) << 16;5882- z |= (stb_uint) stb_fgetc(f) << 8;5883- } else z = (stb_uint) (d - 0x80) << 8;5884- z |= stb_fgetc(f);5885- } else5886- z = d;5887-5888- return (z & 1) ? ~(z >> 1) : (z >> 1);5889-}5890-5891-int stb_size_varlen64(stb_uint64 v)5892-{5893- if (v < 0x00000080) return 1;5894- if (v < 0x00004000) return 2;5895- if (v < 0x00200000) return 3;5896- if (v < 0x10000000) return 4;5897- if (v < STB_IMM_UINT64(0x0000000800000000)) return 5;5898- if (v < STB_IMM_UINT64(0x0000040000000000)) return 6;5899- if (v < STB_IMM_UINT64(0x0002000000000000)) return 7;5900- if (v < STB_IMM_UINT64(0x0100000000000000)) return 8;5901- return 9;5902-}5903-5904-void stb_fput_varlen64(FILE *f, stb_uint64 v)5905-{5906- stb_uint64 z = stb__varlen_xform(v);5907- int first=1;5908- if (z >= STB_IMM_UINT64(0x100000000000000)) {5909- fputc(0xff,f);5910- first=0;5911- }5912- if (z >= STB_IMM_UINT64(0x02000000000000)) fputc((first ? 0xFE : 0)+(char)(z>>56),f), first=0;5913- if (z >= STB_IMM_UINT64(0x00040000000000)) fputc((first ? 0xFC : 0)+(char)(z>>48),f), first=0;5914- if (z >= STB_IMM_UINT64(0x00000800000000)) fputc((first ? 0xF8 : 0)+(char)(z>>40),f), first=0;5915- if (z >= STB_IMM_UINT64(0x00000010000000)) fputc((first ? 0xF0 : 0)+(char)(z>>32),f), first=0;5916- if (z >= STB_IMM_UINT64(0x00000000200000)) fputc((first ? 0xE0 : 0)+(char)(z>>24),f), first=0;5917- if (z >= STB_IMM_UINT64(0x00000000004000)) fputc((first ? 0xC0 : 0)+(char)(z>>16),f), first=0;5918- if (z >= STB_IMM_UINT64(0x00000000000080)) fputc((first ? 0x80 : 0)+(char)(z>> 8),f), first=0;5919- fputc((char)z,f);5920-}5921-5922-void stb_fput_ranged(FILE *f, int v, int b, stb_uint n)5923-{5924- v -= b;5925- if (n <= (1 << 31))5926- assert((stb_uint) v < n);5927- if (n > (1 << 24)) fputc(v >> 24, f);5928- if (n > (1 << 16)) fputc(v >> 16, f);5929- if (n > (1 << 8)) fputc(v >> 8, f);5930- fputc(v,f);5931-}5932-5933-int stb_fget_ranged(FILE *f, int b, stb_uint n)5934-{5935- unsigned int v=0;5936- if (n > (1 << 24)) v += stb_fgetc(f) << 24;5937- if (n > (1 << 16)) v += stb_fgetc(f) << 16;5938- if (n > (1 << 8)) v += stb_fgetc(f) << 8;5939- v += stb_fgetc(f);5940- return b+v;5941-}5942-5943-int stb_size_ranged(int b, stb_uint n)5944-{5945- if (n > (1 << 24)) return 4;5946- if (n > (1 << 16)) return 3;5947- if (n > (1 << 8)) return 2;5948- return 1;5949-}5950-5951-void stb_fput_string(FILE *f, char *s)5952-{5953- size_t len = strlen(s);5954- stb_fput_varlenu(f, (unsigned int) len);5955- fwrite(s, 1, len, f);5956-}5957-5958-// inverse of the above algorithm5959-char *stb_fget_string(FILE *f, void *p)5960-{5961- char *s;5962- int len = stb_fget_varlenu(f);5963- if (len > 4096) return NULL;5964- s = p ? stb_malloc_string(p, len+1) : (char *) malloc(len+1);5965- fread(s, 1, len, f);5966- s[len] = 0;5967- return s;5968-}5969-5970-char *stb_strdup(char *str, void *pool)5971-{5972- size_t len = strlen(str);5973- char *p = stb_malloc_string(pool, len+1);5974- stb_p_strcpy_s(p, len+1, str);5975- return p;5976-}5977-5978-// strip the trailing '/' or '\\' from a directory so we can refer to it5979-// as a file for _stat()5980-char *stb_strip_final_slash(char *t)5981-{5982- if (t[0]) {5983- char *z = t + strlen(t) - 1;5984- // *z is the last character5985- if (*z == '\\' || *z == '/')5986- if (z != t+2 || t[1] != ':') // but don't strip it if it's e.g. "c:/"5987- *z = 0;5988- if (*z == '\\')5989- *z = '/'; // canonicalize to make sure it matches db5990- }5991- return t;5992-}5993-5994-char *stb_strip_final_slash_regardless(char *t)5995-{5996- if (t[0]) {5997- char *z = t + strlen(t) - 1;5998- // *z is the last character5999- if (*z == '\\' || *z == '/')6000- *z = 0;6001- if (*z == '\\')6002- *z = '/'; // canonicalize to make sure it matches db6003- }6004- return t;6005-}6006-#endif6007-6008-//////////////////////////////////////////////////////////////////////////////6009-//6010-// Options parsing6011-//6012-6013-STB_EXTERN char **stb_getopt_param(int *argc, char **argv, char *param);6014-STB_EXTERN char **stb_getopt(int *argc, char **argv);6015-STB_EXTERN void stb_getopt_free(char **opts);6016-6017-#ifdef STB_DEFINE6018-6019-void stb_getopt_free(char **opts)6020-{6021- int i;6022- char ** o2 = opts;6023- for (i=0; i < stb_arr_len(o2); ++i)6024- free(o2[i]);6025- stb_arr_free(o2);6026-}6027-6028-char **stb_getopt(int *argc, char **argv)6029-{6030- return stb_getopt_param(argc, argv, (char*) "");6031-}6032-6033-char **stb_getopt_param(int *argc, char **argv, char *param)6034-{6035- char ** opts=NULL;6036- int i,j=1;6037- for (i=1; i < *argc; ++i) {6038- if (argv[i][0] != '-') {6039- argv[j++] = argv[i];6040- } else {6041- if (argv[i][1] == 0) { // plain - == don't parse further options6042- ++i;6043- while (i < *argc)6044- argv[j++] = argv[i++];6045- break;6046- } else if (argv[i][1] == '-') {6047- // copy argument through including initial '-' for clarity6048- stb_arr_push(opts, stb_p_strdup(argv[i]));6049- } else {6050- int k;6051- char *q = argv[i]; // traverse options list6052- for (k=1; q[k]; ++k) {6053- char *s;6054- if (strchr(param, q[k])) { // does it take a parameter?6055- char *t = &q[k+1], z = q[k];6056- size_t len=0;6057- if (*t == 0) {6058- if (i == *argc-1) { // takes a parameter, but none found6059- *argc = 0;6060- stb_getopt_free(opts);6061- return NULL;6062- }6063- t = argv[++i];6064- } else6065- k += (int) strlen(t);6066- len = strlen(t);6067- s = (char *) malloc(len+2);6068- if (!s) return NULL;6069- s[0] = z;6070- stb_p_strcpy_s(s+1, len+2, t);6071- } else {6072- // no parameter6073- s = (char *) malloc(2);6074- if (!s) return NULL;6075- s[0] = q[k];6076- s[1] = 0;6077- }6078- stb_arr_push(opts, s);6079- }6080- }6081- }6082- }6083- stb_arr_push(opts, NULL);6084- *argc = j;6085- return opts;6086-}6087-#endif6088-6089-6090-//////////////////////////////////////////////////////////////////////////////6091-//6092-// Portable directory reading6093-//6094-6095-STB_EXTERN char **stb_readdir_files (char *dir);6096-STB_EXTERN char **stb_readdir_files_mask(char *dir, char *wild);6097-STB_EXTERN char **stb_readdir_subdirs(char *dir);6098-STB_EXTERN char **stb_readdir_subdirs_mask(char *dir, char *wild);6099-STB_EXTERN void stb_readdir_free (char **files);6100-STB_EXTERN char **stb_readdir_recursive(char *dir, char *filespec);6101-STB_EXTERN void stb_delete_directory_recursive(char *dir);6102-6103-#ifdef STB_DEFINE6104-6105-#ifdef _MSC_VER6106-#include <io.h>6107-#else6108-#include <unistd.h>6109-#include <dirent.h>6110-#endif6111-6112-void stb_readdir_free(char **files)6113-{6114- char **f2 = files;6115- int i;6116- for (i=0; i < stb_arr_len(f2); ++i)6117- free(f2[i]);6118- stb_arr_free(f2);6119-}6120-6121-static int isdotdirname(char *name)6122-{6123- if (name[0] == '.')6124- return (name[1] == '.') ? !name[2] : !name[1];6125- return 0;6126-}6127-6128-STB_EXTERN int stb_wildmatchi(char *expr, char *candidate);6129-static char **readdir_raw(char *dir, int return_subdirs, char *mask)6130-{6131- char **results = NULL;6132- char buffer[4096], with_slash[4096];6133- size_t n;6134-6135- #ifdef _MSC_VER6136- stb__wchar *ws;6137- struct _wfinddata_t data;6138- #ifdef _WIN646139- const intptr_t none = -1;6140- intptr_t z;6141- #else6142- const long none = -1;6143- long z;6144- #endif6145- #else // !_MSC_VER6146- const DIR *none = NULL;6147- DIR *z;6148- #endif6149-6150- n = stb_strscpy(buffer,dir,sizeof(buffer));6151- if (!n || n >= sizeof(buffer))6152- return NULL;6153- stb_fixpath(buffer);6154-6155- if (n > 0 && (buffer[n-1] != '/')) {6156- buffer[n++] = '/';6157- }6158- buffer[n] = 0;6159- if (!stb_strscpy(with_slash,buffer,sizeof(with_slash)))6160- return NULL;6161-6162- #ifdef _MSC_VER6163- if (!stb_strscpy(buffer+n,"*.*",sizeof(buffer)-n))6164- return NULL;6165- ws = stb__from_utf8(buffer);6166- z = _wfindfirst((wchar_t *)ws, &data);6167- #else6168- z = opendir(dir);6169- #endif6170-6171- if (z != none) {6172- int nonempty = STB_TRUE;6173- #ifndef _MSC_VER6174- struct dirent *data = readdir(z);6175- nonempty = (data != NULL);6176- #endif6177-6178- if (nonempty) {6179-6180- do {6181- int is_subdir;6182- #ifdef _MSC_VER6183- char *name = stb__to_utf8((stb__wchar *)data.name);6184- if (name == NULL) {6185- fprintf(stderr, "%s to convert '%S' to %s!\n", "Unable", data.name, "utf8");6186- continue;6187- }6188- is_subdir = !!(data.attrib & _A_SUBDIR);6189- #else6190- char *name = data->d_name;6191- if (!stb_strscpy(buffer+n,name,sizeof(buffer)-n))6192- break;6193- // Could follow DT_LNK, but would need to check for recursive links.6194- is_subdir = !!(data->d_type & DT_DIR);6195- #endif6196-6197- if (is_subdir == return_subdirs) {6198- if (!is_subdir || !isdotdirname(name)) {6199- if (!mask || stb_wildmatchi(mask, name)) {6200- char buffer[4096],*p=buffer;6201- if ( stb_snprintf(buffer, sizeof(buffer), "%s%s", with_slash, name) < 0 )6202- break;6203- if (buffer[0] == '.' && buffer[1] == '/')6204- p = buffer+2;6205- stb_arr_push(results, stb_p_strdup(p));6206- }6207- }6208- }6209- }6210- #ifdef _MSC_VER6211- while (0 == _wfindnext(z, &data));6212- #else6213- while ((data = readdir(z)) != NULL);6214- #endif6215- }6216- #ifdef _MSC_VER6217- _findclose(z);6218- #else6219- closedir(z);6220- #endif6221- }6222- return results;6223-}6224-6225-char **stb_readdir_files (char *dir) { return readdir_raw(dir, 0, NULL); }6226-char **stb_readdir_subdirs(char *dir) { return readdir_raw(dir, 1, NULL); }6227-char **stb_readdir_files_mask(char *dir, char *wild) { return readdir_raw(dir, 0, wild); }6228-char **stb_readdir_subdirs_mask(char *dir, char *wild) { return readdir_raw(dir, 1, wild); }6229-6230-int stb__rec_max=0x7fffffff;6231-static char **stb_readdir_rec(char **sofar, char *dir, char *filespec)6232-{6233- char **files;6234- char ** dirs;6235- char **p;6236-6237- if (stb_arr_len(sofar) >= stb__rec_max) return sofar;6238-6239- files = stb_readdir_files_mask(dir, filespec);6240- stb_arr_for(p, files) {6241- stb_arr_push(sofar, stb_p_strdup(*p));6242- if (stb_arr_len(sofar) >= stb__rec_max) break;6243- }6244- stb_readdir_free(files);6245- if (stb_arr_len(sofar) >= stb__rec_max) return sofar;6246-6247- dirs = stb_readdir_subdirs(dir);6248- stb_arr_for(p, dirs)6249- sofar = stb_readdir_rec(sofar, *p, filespec);6250- stb_readdir_free(dirs);6251- return sofar;6252-}6253-6254-char **stb_readdir_recursive(char *dir, char *filespec)6255-{6256- return stb_readdir_rec(NULL, dir, filespec);6257-}6258-6259-void stb_delete_directory_recursive(char *dir)6260-{6261- char **list = stb_readdir_subdirs(dir);6262- int i;6263- for (i=0; i < stb_arr_len(list); ++i)6264- stb_delete_directory_recursive(list[i]);6265- stb_arr_free(list);6266- list = stb_readdir_files(dir);6267- for (i=0; i < stb_arr_len(list); ++i)6268- if (!remove(list[i])) {6269- // on windows, try again after making it writeable; don't ALWAYS6270- // do this first since that would be slow in the normal case6271- #ifdef _MSC_VER6272- _chmod(list[i], _S_IWRITE);6273- remove(list[i]);6274- #endif6275- }6276- stb_arr_free(list);6277- stb__windows(_rmdir,rmdir)(dir);6278-}6279-6280-#endif6281-6282-//////////////////////////////////////////////////////////////////////////////6283-//6284-// construct trees from filenames; useful for cmirror summaries6285-6286-typedef struct stb_dirtree2 stb_dirtree2;6287-6288-struct stb_dirtree26289-{6290- stb_dirtree2 **subdirs;6291-6292- // make convenient for stb_summarize_tree6293- int num_subdir;6294- float weight;6295-6296- // actual data6297- char *fullpath;6298- char *relpath;6299- char **files;6300-};6301-6302-STB_EXTERN stb_dirtree2 *stb_dirtree2_from_files_relative(char *src, char **filelist, int count);6303-STB_EXTERN stb_dirtree2 *stb_dirtree2_from_files(char **filelist, int count);6304-STB_EXTERN int stb_dir_is_prefix(char *dir, int dirlen, char *file);6305-6306-#ifdef STB_DEFINE6307-6308-int stb_dir_is_prefix(char *dir, int dirlen, char *file)6309-{6310- if (dirlen == 0) return STB_TRUE;6311- if (stb_strnicmp(dir, file, dirlen)) return STB_FALSE;6312- if (file[dirlen] == '/' || file[dirlen] == '\\') return STB_TRUE;6313- return STB_FALSE;6314-}6315-6316-stb_dirtree2 *stb_dirtree2_from_files_relative(char *src, char **filelist, int count)6317-{6318- char buffer1[1024];6319- int i;6320- int dlen = (int) strlen(src), elen;6321- stb_dirtree2 *d;6322- char ** descendents = NULL;6323- char ** files = NULL;6324- char *s;6325- if (!count) return NULL;6326- // first find all the ones that belong here... note this is will take O(NM) with N files and M subdirs6327- for (i=0; i < count; ++i) {6328- if (stb_dir_is_prefix(src, dlen, filelist[i])) {6329- stb_arr_push(descendents, filelist[i]);6330- }6331- }6332- if (descendents == NULL)6333- return NULL;6334- elen = dlen;6335- // skip a leading slash6336- if (elen == 0 && (descendents[0][0] == '/' || descendents[0][0] == '\\'))6337- ++elen;6338- else if (elen)6339- ++elen;6340- // now extract all the ones that have their root here6341- for (i=0; i < stb_arr_len(descendents);) {6342- if (!stb_strchr2(descendents[i]+elen, '/', '\\')) {6343- stb_arr_push(files, descendents[i]);6344- descendents[i] = descendents[stb_arr_len(descendents)-1];6345- stb_arr_pop(descendents);6346- } else6347- ++i;6348- }6349- // now create a record6350- d = (stb_dirtree2 *) malloc(sizeof(*d));6351- d->files = files;6352- d->subdirs = NULL;6353- d->fullpath = stb_p_strdup(src);6354- s = stb_strrchr2(d->fullpath, '/', '\\');6355- if (s)6356- ++s;6357- else6358- s = d->fullpath;6359- d->relpath = s;6360- // now create the children6361- qsort(descendents, stb_arr_len(descendents), sizeof(char *), stb_qsort_stricmp(0));6362- buffer1[0] = 0;6363- for (i=0; i < stb_arr_len(descendents); ++i) {6364- char buffer2[1024];6365- char *s = descendents[i] + elen, *t;6366- t = stb_strchr2(s, '/', '\\');6367- assert(t);6368- stb_strncpy(buffer2, descendents[i], (int) (t-descendents[i]+1));6369- if (stb_stricmp(buffer1, buffer2)) {6370- stb_dirtree2 *t = stb_dirtree2_from_files_relative(buffer2, descendents, stb_arr_len(descendents));6371- assert(t != NULL);6372- stb_p_strcpy_s(buffer1, sizeof(buffer1), buffer2);6373- stb_arr_push(d->subdirs, t);6374- }6375- }6376- d->num_subdir = stb_arr_len(d->subdirs);6377- d->weight = 0;6378- return d;6379-}6380-6381-stb_dirtree2 *stb_dirtree2_from_files(char **filelist, int count)6382-{6383- return stb_dirtree2_from_files_relative((char*) "", filelist, count);6384-}6385-#endif6386-6387-//////////////////////////////////////////////////////////////////////////////6388-//6389-// Checksums: CRC-32, ADLER32, SHA-16390-//6391-// CRC-32 and ADLER32 allow streaming blocks6392-// SHA-1 requires either a complete buffer, max size 2^32 - 736393-// or it can checksum directly from a file, max 2^616394-6395-#define STB_ADLER32_SEED 16396-#define STB_CRC32_SEED 0 // note that we logical NOT this in the code6397-6398-STB_EXTERN stb_uint6399- stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen);6400-STB_EXTERN stb_uint6401- stb_crc32_block(stb_uint crc32, stb_uchar *buffer, stb_uint len);6402-STB_EXTERN stb_uint stb_crc32(unsigned char *buffer, stb_uint len);6403-6404-STB_EXTERN void stb_sha1(6405- unsigned char output[20], unsigned char *buffer, unsigned int len);6406-STB_EXTERN int stb_sha1_file(unsigned char output[20], char *file);6407-6408-STB_EXTERN void stb_sha1_readable(char display[27], unsigned char sha[20]);6409-6410-#ifdef STB_DEFINE6411-stb_uint stb_crc32_block(stb_uint crc, unsigned char *buffer, stb_uint len)6412-{6413- static stb_uint crc_table[256];6414- stb_uint i,j,s;6415- crc = ~crc;6416-6417- if (crc_table[1] == 0)6418- for(i=0; i < 256; i++) {6419- for (s=i, j=0; j < 8; ++j)6420- s = (s >> 1) ^ (s & 1 ? 0xedb88320 : 0);6421- crc_table[i] = s;6422- }6423- for (i=0; i < len; ++i)6424- crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)];6425- return ~crc;6426-}6427-6428-stb_uint stb_crc32(unsigned char *buffer, stb_uint len)6429-{6430- return stb_crc32_block(0, buffer, len);6431-}6432-6433-stb_uint stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen)6434-{6435- const unsigned long ADLER_MOD = 65521;6436- unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16;6437- unsigned long blocklen, i;6438-6439- blocklen = buflen % 5552;6440- while (buflen) {6441- for (i=0; i + 7 < blocklen; i += 8) {6442- s1 += buffer[0], s2 += s1;6443- s1 += buffer[1], s2 += s1;6444- s1 += buffer[2], s2 += s1;6445- s1 += buffer[3], s2 += s1;6446- s1 += buffer[4], s2 += s1;6447- s1 += buffer[5], s2 += s1;6448- s1 += buffer[6], s2 += s1;6449- s1 += buffer[7], s2 += s1;6450-6451- buffer += 8;6452- }6453-6454- for (; i < blocklen; ++i)6455- s1 += *buffer++, s2 += s1;6456-6457- s1 %= ADLER_MOD, s2 %= ADLER_MOD;6458- buflen -= blocklen;6459- blocklen = 5552;6460- }6461- return (s2 << 16) + s1;6462-}6463-6464-static void stb__sha1(stb_uchar *chunk, stb_uint h[5])6465-{6466- int i;6467- stb_uint a,b,c,d,e;6468- stb_uint w[80];6469-6470- for (i=0; i < 16; ++i)6471- w[i] = stb_big32(&chunk[i*4]);6472- for (i=16; i < 80; ++i) {6473- stb_uint t;6474- t = w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16];6475- w[i] = (t + t) | (t >> 31);6476- }6477-6478- a = h[0];6479- b = h[1];6480- c = h[2];6481- d = h[3];6482- e = h[4];6483-6484- #define STB__SHA1(k,f) \6485- { \6486- stb_uint temp = (a << 5) + (a >> 27) + (f) + e + (k) + w[i]; \6487- e = d; \6488- d = c; \6489- c = (b << 30) + (b >> 2); \6490- b = a; \6491- a = temp; \6492- }6493-6494- i=0;6495- for (; i < 20; ++i) STB__SHA1(0x5a827999, d ^ (b & (c ^ d)) );6496- for (; i < 40; ++i) STB__SHA1(0x6ed9eba1, b ^ c ^ d );6497- for (; i < 60; ++i) STB__SHA1(0x8f1bbcdc, (b & c) + (d & (b ^ c)) );6498- for (; i < 80; ++i) STB__SHA1(0xca62c1d6, b ^ c ^ d );6499-6500- #undef STB__SHA16501-6502- h[0] += a;6503- h[1] += b;6504- h[2] += c;6505- h[3] += d;6506- h[4] += e;6507-}6508-6509-void stb_sha1(stb_uchar output[20], stb_uchar *buffer, stb_uint len)6510-{6511- unsigned char final_block[128];6512- stb_uint end_start, final_len, j;6513- int i;6514-6515- stb_uint h[5];6516-6517- h[0] = 0x67452301;6518- h[1] = 0xefcdab89;6519- h[2] = 0x98badcfe;6520- h[3] = 0x10325476;6521- h[4] = 0xc3d2e1f0;6522-6523- // we need to write padding to the last one or two6524- // blocks, so build those first into 'final_block'6525-6526- // we have to write one special byte, plus the 8-byte length6527-6528- // compute the block where the data runs out6529- end_start = len & ~63;6530-6531- // compute the earliest we can encode the length6532- if (((len+9) & ~63) == end_start) {6533- // it all fits in one block, so fill a second-to-last block6534- end_start -= 64;6535- }6536-6537- final_len = end_start + 128;6538-6539- // now we need to copy the data in6540- assert(end_start + 128 >= len+9);6541- assert(end_start < len || len < 64-9);6542-6543- j = 0;6544- if (end_start > len)6545- j = (stb_uint) - (int) end_start;6546-6547- for (; end_start + j < len; ++j)6548- final_block[j] = buffer[end_start + j];6549- final_block[j++] = 0x80;6550- while (j < 128-5) // 5 byte length, so write 4 extra padding bytes6551- final_block[j++] = 0;6552- // big-endian size6553- final_block[j++] = len >> 29;6554- final_block[j++] = len >> 21;6555- final_block[j++] = len >> 13;6556- final_block[j++] = len >> 5;6557- final_block[j++] = len << 3;6558- assert(j == 128 && end_start + j == final_len);6559-6560- for (j=0; j < final_len; j += 64) { // 512-bit chunks6561- if (j+64 >= end_start+64)6562- stb__sha1(&final_block[j - end_start], h);6563- else6564- stb__sha1(&buffer[j], h);6565- }6566-6567- for (i=0; i < 5; ++i) {6568- output[i*4 + 0] = h[i] >> 24;6569- output[i*4 + 1] = h[i] >> 16;6570- output[i*4 + 2] = h[i] >> 8;6571- output[i*4 + 3] = h[i] >> 0;6572- }6573-}6574-6575-#ifdef _MSC_VER6576-int stb_sha1_file(stb_uchar output[20], char *file)6577-{6578- int i;6579- stb_uint64 length=0;6580- unsigned char buffer[128];6581-6582- FILE *f = stb__fopen(file, "rb");6583- stb_uint h[5];6584-6585- if (f == NULL) return 0; // file not found6586-6587- h[0] = 0x67452301;6588- h[1] = 0xefcdab89;6589- h[2] = 0x98badcfe;6590- h[3] = 0x10325476;6591- h[4] = 0xc3d2e1f0;6592-6593- for(;;) {6594- size_t n = fread(buffer, 1, 64, f);6595- if (n == 64) {6596- stb__sha1(buffer, h);6597- length += n;6598- } else {6599- int block = 64;6600-6601- length += n;6602-6603- buffer[n++] = 0x80;6604-6605- // if there isn't enough room for the length, double the block6606- if (n + 8 > 64)6607- block = 128;6608-6609- // pad to end6610- memset(buffer+n, 0, block-8-n);6611-6612- i = block - 8;6613- buffer[i++] = (stb_uchar) (length >> 53);6614- buffer[i++] = (stb_uchar) (length >> 45);6615- buffer[i++] = (stb_uchar) (length >> 37);6616- buffer[i++] = (stb_uchar) (length >> 29);6617- buffer[i++] = (stb_uchar) (length >> 21);6618- buffer[i++] = (stb_uchar) (length >> 13);6619- buffer[i++] = (stb_uchar) (length >> 5);6620- buffer[i++] = (stb_uchar) (length << 3);6621- assert(i == block);6622- stb__sha1(buffer, h);6623- if (block == 128)6624- stb__sha1(buffer+64, h);6625- else6626- assert(block == 64);6627- break;6628- }6629- }6630- fclose(f);6631-6632- for (i=0; i < 5; ++i) {6633- output[i*4 + 0] = h[i] >> 24;6634- output[i*4 + 1] = h[i] >> 16;6635- output[i*4 + 2] = h[i] >> 8;6636- output[i*4 + 3] = h[i] >> 0;6637- }6638-6639- return 1;6640-}6641-#endif // _MSC_VER6642-6643-// client can truncate this wherever they like6644-void stb_sha1_readable(char display[27], unsigned char sha[20])6645-{6646- char encoding[65] = "0123456789abcdefghijklmnopqrstuv"6647- "wxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%$";6648- int num_bits = 0, acc=0;6649- int i=0,o=0;6650- while (o < 26) {6651- int v;6652- // expand the accumulator6653- if (num_bits < 6) {6654- assert(i != 20);6655- acc += sha[i++] << num_bits;6656- num_bits += 8;6657- }6658- v = acc & ((1 << 6) - 1);6659- display[o++] = encoding[v];6660- acc >>= 6;6661- num_bits -= 6;6662- }6663- assert(num_bits == 20*8 - 26*6);6664- display[o++] = encoding[acc];6665-}6666-6667-#endif // STB_DEFINE6668-6669-///////////////////////////////////////////////////////////6670-//6671-// simplified WINDOWS registry interface... hopefully6672-// we'll never actually use this?6673-6674-#if defined(_WIN32)6675-6676-STB_EXTERN void * stb_reg_open(const char *mode, const char *where); // mode: "rHKLM" or "rHKCU" or "w.."6677-STB_EXTERN void stb_reg_close(void *reg);6678-STB_EXTERN int stb_reg_read(void *zreg, const char *str, void *data, unsigned long len);6679-STB_EXTERN int stb_reg_read_string(void *zreg, const char *str, char *data, int len);6680-STB_EXTERN void stb_reg_write(void *zreg, const char *str, const void *data, unsigned long len);6681-STB_EXTERN void stb_reg_write_string(void *zreg, const char *str, const char *data);6682-6683-#if defined(STB_DEFINE) && !defined(STB_NO_REGISTRY)6684-6685-#define STB_HAS_REGISTRY6686-6687-#ifndef _WINDOWS_6688-6689-#define HKEY void *6690-6691-STB_EXTERN __declspec(dllimport) long __stdcall RegCloseKey ( HKEY hKey );6692-STB_EXTERN __declspec(dllimport) long __stdcall RegCreateKeyExA ( HKEY hKey, const char * lpSubKey,6693- int Reserved, char * lpClass, int dwOptions,6694- int samDesired, void *lpSecurityAttributes, HKEY * phkResult, int * lpdwDisposition );6695-STB_EXTERN __declspec(dllimport) long __stdcall RegDeleteKeyA ( HKEY hKey, const char * lpSubKey );6696-STB_EXTERN __declspec(dllimport) long __stdcall RegQueryValueExA ( HKEY hKey, const char * lpValueName,6697- int * lpReserved, unsigned long * lpType, unsigned char * lpData, unsigned long * lpcbData );6698-STB_EXTERN __declspec(dllimport) long __stdcall RegSetValueExA ( HKEY hKey, const char * lpValueName,6699- int Reserved, int dwType, const unsigned char* lpData, int cbData );6700-STB_EXTERN __declspec(dllimport) long __stdcall RegOpenKeyExA ( HKEY hKey, const char * lpSubKey,6701- int ulOptions, int samDesired, HKEY * phkResult );6702-6703-#endif // _WINDOWS_6704-6705-#define STB__REG_OPTION_NON_VOLATILE 06706-#define STB__REG_KEY_ALL_ACCESS 0x000f003f6707-#define STB__REG_KEY_READ 0x000200196708-6709-#ifdef _M_AMD646710-#define STB__HKEY_CURRENT_USER 0x80000001ull6711-#define STB__HKEY_LOCAL_MACHINE 0x80000002ull6712-#else6713-#define STB__HKEY_CURRENT_USER 0x800000016714-#define STB__HKEY_LOCAL_MACHINE 0x800000026715-#endif6716-6717-void *stb_reg_open(const char *mode, const char *where)6718-{6719- long res;6720- HKEY base;6721- HKEY zreg;6722- if (!stb_stricmp(mode+1, "cu") || !stb_stricmp(mode+1, "hkcu"))6723- base = (HKEY) STB__HKEY_CURRENT_USER;6724- else if (!stb_stricmp(mode+1, "lm") || !stb_stricmp(mode+1, "hklm"))6725- base = (HKEY) STB__HKEY_LOCAL_MACHINE;6726- else6727- return NULL;6728-6729- if (mode[0] == 'r')6730- res = RegOpenKeyExA(base, where, 0, STB__REG_KEY_READ, &zreg);6731- else if (mode[0] == 'w')6732- res = RegCreateKeyExA(base, where, 0, NULL, STB__REG_OPTION_NON_VOLATILE, STB__REG_KEY_ALL_ACCESS, NULL, &zreg, NULL);6733- else6734- return NULL;6735-6736- return res ? NULL : zreg;6737-}6738-6739-void stb_reg_close(void *reg)6740-{6741- RegCloseKey((HKEY) reg);6742-}6743-6744-#define STB__REG_SZ 16745-#define STB__REG_BINARY 36746-#define STB__REG_DWORD 46747-6748-int stb_reg_read(void *zreg, const char *str, void *data, unsigned long len)6749-{6750- unsigned long type;6751- unsigned long alen = len;6752- if (0 == RegQueryValueExA((HKEY) zreg, str, 0, &type, (unsigned char *) data, &len))6753- if (type == STB__REG_BINARY || type == STB__REG_SZ || type == STB__REG_DWORD) {6754- if (len < alen)6755- *((char *) data + len) = 0;6756- return 1;6757- }6758- return 0;6759-}6760-6761-void stb_reg_write(void *zreg, const char *str, const void *data, unsigned long len)6762-{6763- if (zreg)6764- RegSetValueExA((HKEY) zreg, str, 0, STB__REG_BINARY, (const unsigned char *) data, len);6765-}6766-6767-int stb_reg_read_string(void *zreg, const char *str, char *data, int len)6768-{6769- if (!stb_reg_read(zreg, str, data, len)) return 0;6770- data[len-1] = 0; // force a 0 at the end of the string no matter what6771- return 1;6772-}6773-6774-void stb_reg_write_string(void *zreg, const char *str, const char *data)6775-{6776- if (zreg)6777- RegSetValueExA((HKEY) zreg, str, 0, STB__REG_SZ, (const unsigned char *) data, (int) strlen(data)+1);6778-}6779-#endif // STB_DEFINE6780-#endif // _WIN326781-6782-6783-//////////////////////////////////////////////////////////////////////////////6784-//6785-// stb_cfg - This is like the registry, but the config info6786-// is all stored in plain old files where we can6787-// backup and restore them easily. The LOCATION of6788-// the config files is gotten from... the registry!6789-6790-#ifndef STB_NO_STB_STRINGS6791-typedef struct stb_cfg_st stb_cfg;6792-6793-STB_EXTERN stb_cfg * stb_cfg_open(char *config, const char *mode); // mode = "r", "w"6794-STB_EXTERN void stb_cfg_close(stb_cfg *cfg);6795-STB_EXTERN int stb_cfg_read(stb_cfg *cfg, char *key, void *value, int len);6796-STB_EXTERN void stb_cfg_write(stb_cfg *cfg, char *key, void *value, int len);6797-STB_EXTERN int stb_cfg_read_string(stb_cfg *cfg, char *key, char *value, int len);6798-STB_EXTERN void stb_cfg_write_string(stb_cfg *cfg, char *key, char *value);6799-STB_EXTERN int stb_cfg_delete(stb_cfg *cfg, char *key);6800-STB_EXTERN void stb_cfg_set_directory(char *dir);6801-6802-#ifdef STB_DEFINE6803-6804-typedef struct6805-{6806- char *key;6807- void *value;6808- int value_len;6809-} stb__cfg_item;6810-6811-struct stb_cfg_st6812-{6813- stb__cfg_item *data;6814- char *loaded_file; // this needs to be freed6815- FILE *f; // write the data to this file on close6816-};6817-6818-static const char *stb__cfg_sig = "sTbCoNfIg!\0\0";6819-static char stb__cfg_dir[512];6820-STB_EXTERN void stb_cfg_set_directory(char *dir)6821-{6822- stb_p_strcpy_s(stb__cfg_dir, sizeof(stb__cfg_dir), dir);6823-}6824-6825-STB_EXTERN stb_cfg * stb_cfg_open(char *config, const char *mode)6826-{6827- size_t len;6828- stb_cfg *z;6829- char file[512];6830- if (mode[0] != 'r' && mode[0] != 'w') return NULL;6831-6832- if (!stb__cfg_dir[0]) {6833- #ifdef _WIN326834- stb_p_strcpy_s(stb__cfg_dir, sizeof(stb__cfg_dir), "c:/stb");6835- #else6836- strcpy(stb__cfg_dir, "~/.stbconfig");6837- #endif6838-6839- #ifdef STB_HAS_REGISTRY6840- {6841- void *reg = stb_reg_open("rHKLM", "Software\\SilverSpaceship\\stb");6842- if (reg) {6843- stb_reg_read_string(reg, "config_dir", stb__cfg_dir, sizeof(stb__cfg_dir));6844- stb_reg_close(reg);6845- }6846- }6847- #endif6848- }6849-6850- stb_p_sprintf(file stb_p_size(sizeof(file)), "%s/%s.cfg", stb__cfg_dir, config);6851-6852- z = (stb_cfg *) stb_malloc(0, sizeof(*z));6853- z->data = NULL;6854-6855- z->loaded_file = stb_filec(file, &len);6856- if (z->loaded_file) {6857- char *s = z->loaded_file;6858- if (!memcmp(s, stb__cfg_sig, 12)) {6859- char *s = z->loaded_file + 12;6860- while (s < z->loaded_file + len) {6861- stb__cfg_item a;6862- int n = *(stb_int16 *) s;6863- a.key = s+2;6864- s = s+2 + n;6865- a.value_len = *(int *) s;6866- s += 4;6867- a.value = s;6868- s += a.value_len;6869- stb_arr_push(z->data, a);6870- }6871- assert(s == z->loaded_file + len);6872- }6873- }6874-6875- if (mode[0] == 'w')6876- z->f = stb_p_fopen(file, "wb");6877- else6878- z->f = NULL;6879-6880- return z;6881-}6882-6883-void stb_cfg_close(stb_cfg *z)6884-{6885- if (z->f) {6886- int i;6887- // write the file out6888- fwrite(stb__cfg_sig, 12, 1, z->f);6889- for (i=0; i < stb_arr_len(z->data); ++i) {6890- stb_int16 n = (stb_int16) strlen(z->data[i].key)+1;6891- fwrite(&n, 2, 1, z->f);6892- fwrite(z->data[i].key, n, 1, z->f);6893- fwrite(&z->data[i].value_len, 4, 1, z->f);6894- fwrite(z->data[i].value, z->data[i].value_len, 1, z->f);6895- }6896- fclose(z->f);6897- }6898- stb_arr_free(z->data);6899- stb_free(z);6900-}6901-6902-int stb_cfg_read(stb_cfg *z, char *key, void *value, int len)6903-{6904- int i;6905- for (i=0; i < stb_arr_len(z->data); ++i) {6906- if (!stb_stricmp(z->data[i].key, key)) {6907- int n = stb_min(len, z->data[i].value_len);6908- memcpy(value, z->data[i].value, n);6909- if (n < len)6910- *((char *) value + n) = 0;6911- return 1;6912- }6913- }6914- return 0;6915-}6916-6917-void stb_cfg_write(stb_cfg *z, char *key, void *value, int len)6918-{6919- int i;6920- for (i=0; i < stb_arr_len(z->data); ++i)6921- if (!stb_stricmp(z->data[i].key, key))6922- break;6923- if (i == stb_arr_len(z->data)) {6924- stb__cfg_item p;6925- p.key = stb_strdup(key, z);6926- p.value = NULL;6927- p.value_len = 0;6928- stb_arr_push(z->data, p);6929- }6930- z->data[i].value = stb_malloc(z, len);6931- z->data[i].value_len = len;6932- memcpy(z->data[i].value, value, len);6933-}6934-6935-int stb_cfg_delete(stb_cfg *z, char *key)6936-{6937- int i;6938- for (i=0; i < stb_arr_len(z->data); ++i)6939- if (!stb_stricmp(z->data[i].key, key)) {6940- stb_arr_fastdelete(z->data, i);6941- return 1;6942- }6943- return 0;6944-}6945-6946-int stb_cfg_read_string(stb_cfg *z, char *key, char *value, int len)6947-{6948- if (!stb_cfg_read(z, key, value, len)) return 0;6949- value[len-1] = 0;6950- return 1;6951-}6952-6953-void stb_cfg_write_string(stb_cfg *z, char *key, char *value)6954-{6955- stb_cfg_write(z, key, value, (int) strlen(value)+1);6956-}6957-#endif6958-6959-//////////////////////////////////////////////////////////////////////////////6960-//6961-// stb_dirtree - load a description of a directory tree6962-// uses a cache and stat()s the directories for changes6963-// MUCH faster on NTFS, _wrong_ on FAT32, so should6964-// ignore the db on FAT326965-6966-#ifdef _WIN326967-6968-typedef struct6969-{6970- char * path; // full path from passed-in root6971- time_t last_modified;6972- int num_files;6973- int flag;6974-} stb_dirtree_dir;6975-6976-typedef struct6977-{6978- char *name; // name relative to path6979- int dir; // index into dirs[] array6980- stb_int64 size; // size, max 4GB6981- time_t last_modified;6982- int flag;6983-} stb_dirtree_file;6984-6985-typedef struct6986-{6987- stb_dirtree_dir *dirs;6988- stb_dirtree_file *files;6989-6990- // internal use6991- void * string_pool; // used to free data en masse6992-} stb_dirtree;6993-6994-extern void stb_dirtree_free ( stb_dirtree *d );6995-extern stb_dirtree *stb_dirtree_get ( char *dir);6996-extern stb_dirtree *stb_dirtree_get_dir ( char *dir, char *cache_dir);6997-extern stb_dirtree *stb_dirtree_get_with_file ( char *dir, char *cache_file);6998-6999-// get a list of all the files recursively underneath 'dir'7000-//7001-// cache_file is used to store a copy of the directory tree to speed up7002-// later calls. It must be unique to 'dir' and the current working7003-// directory! Otherwise who knows what will happen (a good solution7004-// is to put it _in_ dir, but this API doesn't force that).7005-//7006-// Also, it might be possible to break this if you have two different processes7007-// do a call to stb_dirtree_get() with the same cache file at about the same7008-// time, but I _think_ it might just work.7009-7010-// i needed to build an identical data structure representing the state of7011-// a mirrored copy WITHOUT bothering to rescan it (i.e. we're mirroring to7012-// it WITHOUT scanning it, e.g. it's over the net), so this requires access7013-// to all of the innards.7014-extern void stb_dirtree_db_add_dir(stb_dirtree *active, char *path, time_t last);7015-extern void stb_dirtree_db_add_file(stb_dirtree *active, char *name, int dir, stb_int64 size, time_t last);7016-extern void stb_dirtree_db_read(stb_dirtree *target, char *filename, char *dir);7017-extern void stb_dirtree_db_write(stb_dirtree *target, char *filename, char *dir);7018-7019-#ifdef STB_DEFINE7020-static void stb__dirtree_add_dir(char *path, time_t last, stb_dirtree *active)7021-{7022- stb_dirtree_dir d;7023- d.last_modified = last;7024- d.num_files = 0;7025- d.path = stb_strdup(path, active->string_pool);7026- stb_arr_push(active->dirs, d);7027-}7028-7029-static void stb__dirtree_add_file(char *name, int dir, stb_int64 size, time_t last, stb_dirtree *active)7030-{7031- stb_dirtree_file f;7032- f.dir = dir;7033- f.size = size;7034- f.last_modified = last;7035- f.name = stb_strdup(name, active->string_pool);7036- ++active->dirs[dir].num_files;7037- stb_arr_push(active->files, f);7038-}7039-7040-// version 02 supports > 4GB files7041-static char stb__signature[12] = { 's', 'T', 'b', 'D', 'i', 'R', 't', 'R', 'e', 'E', '0', '2' };7042-7043-static void stb__dirtree_save_db(char *filename, stb_dirtree *data, char *root)7044-{7045- int i, num_dirs_final=0, num_files_final;7046- char *info = root ? root : (char*)"";7047- int *remap;7048- FILE *f = stb_p_fopen(filename, "wb");7049- if (!f) return;7050-7051- fwrite(stb__signature, sizeof(stb__signature), 1, f);7052- fwrite(info, strlen(info)+1, 1, f);7053- // need to be slightly tricky and not write out NULLed directories, nor the root7054-7055- // build remapping table of all dirs we'll be writing out7056- remap = (int *) malloc(sizeof(remap[0]) * stb_arr_len(data->dirs));7057- for (i=0; i < stb_arr_len(data->dirs); ++i) {7058- if (data->dirs[i].path == NULL || (root && 0==stb_stricmp(data->dirs[i].path, root))) {7059- remap[i] = -1;7060- } else {7061- remap[i] = num_dirs_final++;7062- }7063- }7064-7065- fwrite(&num_dirs_final, 4, 1, f);7066- for (i=0; i < stb_arr_len(data->dirs); ++i) {7067- if (remap[i] >= 0) {7068- fwrite(&data->dirs[i].last_modified, 4, 1, f);7069- stb_fput_string(f, data->dirs[i].path);7070- }7071- }7072-7073- num_files_final = 0;7074- for (i=0; i < stb_arr_len(data->files); ++i)7075- if (remap[data->files[i].dir] >= 0 && data->files[i].name)7076- ++num_files_final;7077-7078- fwrite(&num_files_final, 4, 1, f);7079- for (i=0; i < stb_arr_len(data->files); ++i) {7080- if (remap[data->files[i].dir] >= 0 && data->files[i].name) {7081- stb_fput_ranged(f, remap[data->files[i].dir], 0, num_dirs_final);7082- stb_fput_varlen64(f, data->files[i].size);7083- fwrite(&data->files[i].last_modified, 4, 1, f);7084- stb_fput_string(f, data->files[i].name);7085- }7086- }7087-7088- fclose(f);7089-}7090-7091-// note: stomps any existing data, rather than appending7092-static void stb__dirtree_load_db(char *filename, stb_dirtree *data, char *dir)7093-{7094- char sig[2048];7095- int i,n;7096- FILE *f = stb_p_fopen(filename, "rb");7097-7098- if (!f) return;7099-7100- data->string_pool = stb_malloc(0,1);7101-7102- fread(sig, sizeof(stb__signature), 1, f);7103- if (memcmp(stb__signature, sig, sizeof(stb__signature))) { fclose(f); return; }7104- if (!fread(sig, strlen(dir)+1, 1, f)) { fclose(f); return; }7105- if (stb_stricmp(sig,dir)) { fclose(f); return; }7106-7107- // we can just read them straight in, because they're guaranteed to be valid7108- fread(&n, 4, 1, f);7109- stb_arr_setlen(data->dirs, n);7110- for(i=0; i < stb_arr_len(data->dirs); ++i) {7111- fread(&data->dirs[i].last_modified, 4, 1, f);7112- data->dirs[i].path = stb_fget_string(f, data->string_pool);7113- if (data->dirs[i].path == NULL) goto bail;7114- }7115- fread(&n, 4, 1, f);7116- stb_arr_setlen(data->files, n);7117- for (i=0; i < stb_arr_len(data->files); ++i) {7118- data->files[i].dir = stb_fget_ranged(f, 0, stb_arr_len(data->dirs));7119- data->files[i].size = stb_fget_varlen64(f);7120- fread(&data->files[i].last_modified, 4, 1, f);7121- data->files[i].name = stb_fget_string(f, data->string_pool);7122- if (data->files[i].name == NULL) goto bail;7123- }7124-7125- if (0) {7126- bail:7127- stb_arr_free(data->dirs);7128- stb_arr_free(data->files);7129- }7130- fclose(f);7131-}7132-7133-FILE *hlog;7134-7135-static int stb__dircount, stb__dircount_mask, stb__showfile;7136-static void stb__dirtree_scandir(char *path, time_t last_time, stb_dirtree *active)7137-{7138- // this is dumb depth first; theoretically it might be faster7139- // to fully traverse each directory before visiting its children,7140- // but it's complicated and didn't seem like a gain in the test app7141-7142- int n;7143-7144- struct _wfinddatai64_t c_file;7145- long hFile;7146- stb__wchar full_path[1024];7147- int has_slash;7148- if (stb__showfile) printf("<");7149-7150- has_slash = (path[0] && path[strlen(path)-1] == '/');7151-7152- // @TODO: do this concatenation without using swprintf to avoid this mess:7153-#if (defined(_MSC_VER) && _MSC_VER < 1400) // || (defined(__clang__))7154- // confusingly, Windows Kits\10 needs to go down this path?!?7155- // except now it doesn't, I don't know what changed7156- if (has_slash)7157- swprintf(full_path, L"%s*", stb__from_utf8(path));7158- else7159- swprintf(full_path, L"%s/*", stb__from_utf8(path));7160-#else7161- if (has_slash)7162- swprintf((wchar_t *) full_path, (size_t) 1024, L"%s*", (wchar_t *) stb__from_utf8(path));7163- else7164- swprintf((wchar_t *) full_path, (size_t) 1024, L"%s/*", (wchar_t *) stb__from_utf8(path));7165-#endif7166-7167- // it's possible this directory is already present: that means it was in the7168- // cache, but its parent wasn't... in that case, we're done with it7169- if (stb__showfile) printf("C[%d]", stb_arr_len(active->dirs));7170- for (n=0; n < stb_arr_len(active->dirs); ++n)7171- if (0 == stb_stricmp(active->dirs[n].path, path)) {7172- if (stb__showfile) printf("D");7173- return;7174- }7175- if (stb__showfile) printf("E");7176-7177- // otherwise, we need to add it7178- stb__dirtree_add_dir(path, last_time, active);7179- n = stb_arr_lastn(active->dirs);7180-7181- if (stb__showfile) printf("[");7182- if( (hFile = (long) _wfindfirsti64( (wchar_t *) full_path, &c_file )) != -1L ) {7183- do {7184- if (stb__showfile) printf(")");7185- if (c_file.attrib & _A_SUBDIR) {7186- // ignore subdirectories starting with '.', e.g. "." and ".."7187- if (c_file.name[0] != '.') {7188- char *new_path = (char *) full_path;7189- char *temp = stb__to_utf8((stb__wchar *) c_file.name);7190-7191- if (has_slash)7192- stb_p_sprintf(new_path stb_p_size(sizeof(full_path)), "%s%s", path, temp);7193- else7194- stb_p_sprintf(new_path stb_p_size(sizeof(full_path)), "%s/%s", path, temp);7195-7196- if (stb__dircount_mask) {7197- ++stb__dircount;7198- if (!(stb__dircount & stb__dircount_mask)) {7199- char dummy_path[128], *pad;7200- stb_strncpy(dummy_path, new_path, sizeof(dummy_path)-1);7201- if (strlen(dummy_path) > 96) {7202- stb_p_strcpy_s(dummy_path+96/2-1,128, "...");7203- stb_p_strcpy_s(dummy_path+96/2+2,128, new_path + strlen(new_path)-96/2+2);7204- }7205- pad = dummy_path + strlen(dummy_path);7206- while (pad < dummy_path+98)7207- *pad++ = ' ';7208- *pad = 0;7209- printf("%s\r", dummy_path);7210- #if 07211- if (hlog == 0) {7212- hlog = stb_p_fopen("c:/x/temp.log", "w");7213- fprintf(hlog, "%s\n", dummy_path);7214- }7215- #endif7216- }7217- }7218-7219- stb__dirtree_scandir(new_path, c_file.time_write, active);7220- }7221- } else {7222- char *temp = stb__to_utf8((stb__wchar *) c_file.name);7223- stb__dirtree_add_file(temp, n, c_file.size, c_file.time_write, active);7224- }7225- if (stb__showfile) printf("(");7226- } while( _wfindnexti64( hFile, &c_file ) == 0 );7227- if (stb__showfile) printf("]");7228- _findclose( hFile );7229- }7230- if (stb__showfile) printf(">\n");7231-}7232-7233-// scan the database and see if it's all valid7234-static int stb__dirtree_update_db(stb_dirtree *db, stb_dirtree *active)7235-{7236- int changes_detected = STB_FALSE;7237- int i;7238- int *remap;7239- int *rescan=NULL;7240- remap = (int *) malloc(sizeof(remap[0]) * stb_arr_len(db->dirs));7241- memset(remap, 0, sizeof(remap[0]) * stb_arr_len(db->dirs));7242- rescan = NULL;7243-7244- for (i=0; i < stb_arr_len(db->dirs); ++i) {7245- struct _stat info;7246- if (stb__dircount_mask) {7247- ++stb__dircount;7248- if (!(stb__dircount & stb__dircount_mask)) {7249- printf(".");7250- }7251- }7252- if (0 == _stat(db->dirs[i].path, &info)) {7253- if (info.st_mode & _S_IFDIR) {7254- // it's still a directory, as expected7255- int n = abs((int) (info.st_mtime - db->dirs[i].last_modified));7256- 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 play7257- // it's changed! force a rescan7258- // we don't want to scan it until we've stat()d its7259- // subdirs, though, so we queue it7260- if (stb__showfile) printf("Changed: %s - %08x:%08x\n", db->dirs[i].path, (unsigned int) db->dirs[i].last_modified, (unsigned int) info.st_mtime);7261- stb_arr_push(rescan, i);7262- // update the last_mod time7263- db->dirs[i].last_modified = info.st_mtime;7264- // ignore existing files in this dir7265- remap[i] = -1;7266- changes_detected = STB_TRUE;7267- } else {7268- // it hasn't changed, just copy it through unchanged7269- stb__dirtree_add_dir(db->dirs[i].path, db->dirs[i].last_modified, active);7270- remap[i] = stb_arr_lastn(active->dirs);7271- }7272- } else {7273- // this path used to refer to a directory, but now it's a file!7274- // assume that the parent directory is going to be forced to rescan anyway7275- goto delete_entry;7276- }7277- } else {7278- delete_entry:7279- // directory no longer exists, so don't copy it7280- // we don't free it because it's in the string pool now7281- db->dirs[i].path = NULL;7282- remap[i] = -1;7283- changes_detected = STB_TRUE;7284- }7285- }7286-7287- // at this point, we have:7288- //7289- // <rescan> holds a list of directory indices that need to be scanned due to being out of date7290- // <remap> holds the directory index in <active> for each dir in <db>, if it exists; -1 if not7291- // directories in <rescan> are not in <active> yet7292-7293- // so we can go ahead and remap all the known files right now7294- for (i=0; i < stb_arr_len(db->files); ++i) {7295- int dir = db->files[i].dir;7296- if (remap[dir] >= 0) {7297- stb__dirtree_add_file(db->files[i].name, remap[dir], db->files[i].size, db->files[i].last_modified, active);7298- }7299- }7300-7301- // at this point we're done with db->files, and done with remap7302- free(remap);7303-7304- // now scan those directories using the standard scan7305- for (i=0; i < stb_arr_len(rescan); ++i) {7306- int z = rescan[i];7307- stb__dirtree_scandir(db->dirs[z].path, db->dirs[z].last_modified, active);7308- }7309- stb_arr_free(rescan);7310-7311- return changes_detected;7312-}7313-7314-static void stb__dirtree_free_raw(stb_dirtree *d)7315-{7316- stb_free(d->string_pool);7317- stb_arr_free(d->dirs);7318- stb_arr_free(d->files);7319-}7320-7321-stb_dirtree *stb_dirtree_get_with_file(char *dir, char *cache_file)7322-{7323- stb_dirtree *output = (stb_dirtree *) malloc(sizeof(*output));7324- stb_dirtree db,active;7325- int prev_dir_count, cache_mismatch;7326-7327- char *stripped_dir; // store the directory name without a trailing '/' or '\\'7328-7329- // load the database of last-known state on disk7330- db.string_pool = NULL;7331- db.files = NULL;7332- db.dirs = NULL;7333-7334- stripped_dir = stb_strip_final_slash(stb_p_strdup(dir));7335-7336- if (cache_file != NULL)7337- stb__dirtree_load_db(cache_file, &db, stripped_dir);7338- else if (stb__showfile)7339- printf("No cache file\n");7340-7341- active.files = NULL;7342- active.dirs = NULL;7343- active.string_pool = stb_malloc(0,1); // @TODO: share string pools between both?7344-7345- // check all the directories in the database; make note if7346- // anything we scanned had changed, and rescan those things7347- cache_mismatch = stb__dirtree_update_db(&db, &active);7348-7349- // check the root tree7350- prev_dir_count = stb_arr_len(active.dirs); // record how many directories we've seen7351-7352- stb__dirtree_scandir(stripped_dir, 0, &active); // no last_modified time available for root7353-7354- if (stb__dircount_mask)7355- printf(" \r");7356-7357- // done with the DB; write it back out if any changes, i.e. either7358- // 1. any inconsistency found between cached information and actual disk7359- // or 2. if scanning the root found any new directories--which we detect because7360- // more than one directory got added to the active db during that scan7361- if (cache_mismatch || stb_arr_len(active.dirs) > prev_dir_count+1)7362- stb__dirtree_save_db(cache_file, &active, stripped_dir);7363-7364- free(stripped_dir);7365-7366- stb__dirtree_free_raw(&db);7367-7368- *output = active;7369- return output;7370-}7371-7372-stb_dirtree *stb_dirtree_get_dir(char *dir, char *cache_dir)7373-{7374- int i;7375- stb_uint8 sha[20];7376- char dir_lower[1024];7377- char cache_file[1024],*s;7378- if (cache_dir == NULL)7379- return stb_dirtree_get_with_file(dir, NULL);7380- stb_p_strcpy_s(dir_lower, sizeof(dir_lower), dir);7381- stb_tolower(dir_lower);7382- stb_sha1(sha, (unsigned char *) dir_lower, (unsigned int) strlen(dir_lower));7383- stb_p_strcpy_s(cache_file, sizeof(cache_file), cache_dir);7384- s = cache_file + strlen(cache_file);7385- if (s[-1] != '/' && s[-1] != '\\') *s++ = '/';7386- stb_p_strcpy_s(s, sizeof(cache_file), "dirtree_");7387- s += strlen(s);7388- for (i=0; i < 8; ++i) {7389- char *hex = (char*)"0123456789abcdef";7390- stb_uint z = sha[i];7391- *s++ = hex[z >> 4];7392- *s++ = hex[z & 15];7393- }7394- stb_p_strcpy_s(s, sizeof(cache_file), ".bin");7395- return stb_dirtree_get_with_file(dir, cache_file);7396-}7397-7398-stb_dirtree *stb_dirtree_get(char *dir)7399-{7400- char cache_dir[256];7401- stb_p_strcpy_s(cache_dir, sizeof(cache_dir), "c:/bindata");7402- #ifdef STB_HAS_REGISTRY7403- {7404- void *reg = stb_reg_open("rHKLM", "Software\\SilverSpaceship\\stb");7405- if (reg) {7406- stb_reg_read(reg, "dirtree", cache_dir, sizeof(cache_dir));7407- stb_reg_close(reg);7408- }7409- }7410- #endif7411- return stb_dirtree_get_dir(dir, cache_dir);7412-}7413-7414-void stb_dirtree_free(stb_dirtree *d)7415-{7416- stb__dirtree_free_raw(d);7417- free(d);7418-}7419-7420-void stb_dirtree_db_add_dir(stb_dirtree *active, char *path, time_t last)7421-{7422- stb__dirtree_add_dir(path, last, active);7423-}7424-7425-void stb_dirtree_db_add_file(stb_dirtree *active, char *name, int dir, stb_int64 size, time_t last)7426-{7427- stb__dirtree_add_file(name, dir, size, last, active);7428-}7429-7430-void stb_dirtree_db_read(stb_dirtree *target, char *filename, char *dir)7431-{7432- char *s = stb_strip_final_slash(stb_p_strdup(dir));7433- target->dirs = 0;7434- target->files = 0;7435- target->string_pool = 0;7436- stb__dirtree_load_db(filename, target, s);7437- free(s);7438-}7439-7440-void stb_dirtree_db_write(stb_dirtree *target, char *filename, char *dir)7441-{7442- stb__dirtree_save_db(filename, target, 0); // don't strip out any directories7443-}7444-7445-#endif // STB_DEFINE7446-7447-#endif // _WIN327448-#endif // STB_NO_STB_STRINGS7449-7450-//////////////////////////////////////////////////////////////////////////////7451-//7452-// STB_MALLOC_WRAPPER7453-//7454-// you can use the wrapper functions with your own malloc wrapper,7455-// or define STB_MALLOC_WRAPPER project-wide to have7456-// malloc/free/realloc/strdup all get vectored to it7457-7458-// this has too many very specific error messages you could google for and find in stb.h,7459-// so don't use it if they don't want any stb.h-identifiable strings7460-#if defined(STB_DEFINE) && !defined(STB_NO_STB_STRINGS)7461-7462-typedef struct7463-{7464- void *p;7465- char *file;7466- int line;7467- size_t size;7468-} stb_malloc_record;7469-7470-#ifndef STB_MALLOC_HISTORY_COUNT7471-#define STB_MALLOC_HISTORY_COUNT 50 // 800 bytes7472-#endif7473-7474-stb_malloc_record *stb__allocations;7475-static int stb__alloc_size, stb__alloc_limit, stb__alloc_mask;7476-int stb__alloc_count;7477-7478-stb_malloc_record stb__alloc_history[STB_MALLOC_HISTORY_COUNT];7479-int stb__history_pos;7480-7481-static int stb__hashfind(void *p)7482-{7483- stb_uint32 h = stb_hashptr(p);7484- int s,n = h & stb__alloc_mask;7485- if (stb__allocations[n].p == p)7486- return n;7487- s = stb_rehash(h)|1;7488- for(;;) {7489- if (stb__allocations[n].p == NULL)7490- return -1;7491- n = (n+s) & stb__alloc_mask;7492- if (stb__allocations[n].p == p)7493- return n;7494- }7495-}7496-7497-size_t stb_wrapper_allocsize(void *p)7498-{7499- int n = stb__hashfind(p);7500- if (n < 0) return 0;7501- return stb__allocations[n].size;7502-}7503-7504-static int stb__historyfind(void *p)7505-{7506- int n = stb__history_pos;7507- int i;7508- for (i=0; i < STB_MALLOC_HISTORY_COUNT; ++i) {7509- if (--n < 0) n = STB_MALLOC_HISTORY_COUNT-1;7510- if (stb__alloc_history[n].p == p)7511- return n;7512- }7513- return -1;7514-}7515-7516-static void stb__add_alloc(void *p, size_t sz, char *file, int line);7517-static void stb__grow_alloc(void)7518-{7519- int i,old_num = stb__alloc_size;7520- stb_malloc_record *old = stb__allocations;7521- if (stb__alloc_size == 0)7522- stb__alloc_size = 64;7523- else7524- stb__alloc_size *= 2;7525-7526- stb__allocations = (stb_malloc_record *) stb__realloc_raw(NULL, stb__alloc_size * sizeof(stb__allocations[0]));7527- if (stb__allocations == NULL)7528- stb_fatal("Internal error: couldn't grow malloc wrapper table");7529- memset(stb__allocations, 0, stb__alloc_size * sizeof(stb__allocations[0]));7530- stb__alloc_limit = (stb__alloc_size*3)>>2;7531- stb__alloc_mask = stb__alloc_size-1;7532-7533- stb__alloc_count = 0;7534-7535- for (i=0; i < old_num; ++i)7536- if (old[i].p > STB_DEL) {7537- stb__add_alloc(old[i].p, old[i].size, old[i].file, old[i].line);7538- assert(stb__hashfind(old[i].p) >= 0);7539- }7540- for (i=0; i < old_num; ++i)7541- if (old[i].p > STB_DEL)7542- assert(stb__hashfind(old[i].p) >= 0);7543- stb__realloc_raw(old, 0);7544-}7545-7546-static void stb__add_alloc(void *p, size_t sz, char *file, int line)7547-{7548- stb_uint32 h;7549- int n;7550- if (stb__alloc_count >= stb__alloc_limit)7551- stb__grow_alloc();7552- h = stb_hashptr(p);7553- n = h & stb__alloc_mask;7554- if (stb__allocations[n].p > STB_DEL) {7555- int s = stb_rehash(h)|1;7556- do {7557- n = (n+s) & stb__alloc_mask;7558- } while (stb__allocations[n].p > STB_DEL);7559- }7560- assert(stb__allocations[n].p == NULL || stb__allocations[n].p == STB_DEL);7561- stb__allocations[n].p = p;7562- stb__allocations[n].size = sz;7563- stb__allocations[n].line = line;7564- stb__allocations[n].file = file;7565- ++stb__alloc_count;7566-}7567-7568-static void stb__remove_alloc(int n, char *file, int line)7569-{7570- stb__alloc_history[stb__history_pos] = stb__allocations[n];7571- stb__alloc_history[stb__history_pos].file = file;7572- stb__alloc_history[stb__history_pos].line = line;7573- if (++stb__history_pos == STB_MALLOC_HISTORY_COUNT)7574- stb__history_pos = 0;7575- stb__allocations[n].p = STB_DEL;7576- --stb__alloc_count;7577-}7578-7579-void stb_wrapper_malloc(void *p, size_t sz, char *file, int line)7580-{7581- if (!p) return;7582- stb__add_alloc(p,sz,file,line);7583-}7584-7585-void stb_wrapper_free(void *p, char *file, int line)7586-{7587- int n;7588-7589- if (p == NULL) return;7590-7591- n = stb__hashfind(p);7592-7593- if (n >= 0)7594- stb__remove_alloc(n, file, line);7595- else {7596- // tried to free something we hadn't allocated!7597- n = stb__historyfind(p);7598- assert(0); /* NOTREACHED */7599- if (n >= 0)7600- stb_fatal("Attempted to free %d-byte block %p at %s:%d previously freed/realloced at %s:%d",7601- stb__alloc_history[n].size, p,7602- file, line,7603- stb__alloc_history[n].file, stb__alloc_history[n].line);7604- else7605- stb_fatal("Attempted to free unknown block %p at %s:%d", p, file,line);7606- }7607-}7608-7609-void stb_wrapper_check(void *p)7610-{7611- int n;7612-7613- if (p == NULL) return;7614-7615- n = stb__hashfind(p);7616-7617- if (n >= 0) return;7618-7619- for (n=0; n < stb__alloc_size; ++n)7620- if (stb__allocations[n].p == p)7621- stb_fatal("Internal error: pointer %p was allocated, but hash search failed", p);7622-7623- // tried to free something that wasn't allocated!7624- n = stb__historyfind(p);7625- if (n >= 0)7626- stb_fatal("Checked %d-byte block %p previously freed/realloced at %s:%d",7627- stb__alloc_history[n].size, p,7628- stb__alloc_history[n].file, stb__alloc_history[n].line);7629- stb_fatal("Checked unknown block %p");7630-}7631-7632-void stb_wrapper_realloc(void *p, void *q, size_t sz, char *file, int line)7633-{7634- int n;7635- if (p == NULL) { stb_wrapper_malloc(q, sz, file, line); return; }7636- if (q == NULL) return; // nothing happened7637-7638- n = stb__hashfind(p);7639- if (n == -1) {7640- // tried to free something we hadn't allocated!7641- // this is weird, though, because we got past the realloc!7642- n = stb__historyfind(p);7643- assert(0); /* NOTREACHED */7644- if (n >= 0)7645- stb_fatal("Attempted to realloc %d-byte block %p at %s:%d previously freed/realloced at %s:%d",7646- stb__alloc_history[n].size, p,7647- file, line,7648- stb__alloc_history[n].file, stb__alloc_history[n].line);7649- else7650- stb_fatal("Attempted to realloc unknown block %p at %s:%d", p, file,line);7651- } else {7652- if (q == p) {7653- stb__allocations[n].size = sz;7654- stb__allocations[n].file = file;7655- stb__allocations[n].line = line;7656- } else {7657- stb__remove_alloc(n, file, line);7658- stb__add_alloc(q,sz,file,line);7659- }7660- }7661-}7662-7663-void stb_wrapper_listall(void (*func)(void *ptr, size_t sz, char *file, int line))7664-{7665- int i;7666- for (i=0; i < stb__alloc_size; ++i)7667- if (stb__allocations[i].p > STB_DEL)7668- func(stb__allocations[i].p , stb__allocations[i].size,7669- stb__allocations[i].file, stb__allocations[i].line);7670-}7671-7672-void stb_wrapper_dump(char *filename)7673-{7674- int i;7675- FILE *f = stb_p_fopen(filename, "w");7676- if (!f) return;7677- for (i=0; i < stb__alloc_size; ++i)7678- if (stb__allocations[i].p > STB_DEL)7679- fprintf(f, "%p %7d - %4d %s\n",7680- stb__allocations[i].p , (int) stb__allocations[i].size,7681- stb__allocations[i].line, stb__allocations[i].file);7682-}7683-#endif // STB_DEFINE7684-7685-7686-//////////////////////////////////////////////////////////////////////////////7687-//7688-// stb_pointer_set7689-//7690-//7691-// For data structures that support querying by key, data structure7692-// classes always hand-wave away the issue of what to do if two entries7693-// have the same key: basically, store a linked list of all the nodes7694-// which have the same key (a LISP-style list).7695-//7696-// The thing is, it's not that trivial. If you have an O(log n)7697-// lookup data structure, but then n/4 items have the same value,7698-// you don't want to spend O(n) time scanning that list when7699-// deleting an item if you already have a pointer to the item.7700-// (You have to spend O(n) time enumerating all the items with7701-// a given key, sure, and you can't accelerate deleting a particular7702-// item if you only have the key, not a pointer to the item.)7703-//7704-// I'm going to call this data structure, whatever it turns out to7705-// be, a "pointer set", because we don't store any associated data for7706-// items in this data structure, we just answer the question of7707-// whether an item is in it or not (it's effectively one bit per pointer).7708-// Technically they don't have to be pointers; you could cast ints7709-// to (void *) if you want, but you can't store 0 or 1 because of the7710-// hash table.7711-//7712-// Since the fastest data structure we might want to add support for7713-// identical-keys to is a hash table with O(1)-ish lookup time,7714-// that means that the conceptual "linked list of all items with7715-// the same indexed value" that we build needs to have the same7716-// performance; that way when we index a table we think is arbitrary7717-// ints, but in fact half of them are 0, we don't get screwed.7718-//7719-// Therefore, it needs to be a hash table, at least when it gets7720-// large. On the other hand, when the data has totally arbitrary ints7721-// or floats, there won't be many collisions, and we'll have tons of7722-// 1-item bitmaps. That will be grossly inefficient as hash tables;7723-// trade-off; the hash table is reasonably efficient per-item when7724-// it's large, but not when it's small. So we need to do something7725-// Judy-like and use different strategies depending on the size.7726-//7727-// Like Judy, we'll use the bottom bit to encode the strategy:7728-//7729-// bottom bits:7730-// 00 - direct pointer7731-// 01 - 4-item bucket (16 bytes, no length, NULLs)7732-// 10 - N-item array7733-// 11 - hash table7734-7735-typedef struct stb_ps stb_ps;7736-7737-STB_EXTERN int stb_ps_find (stb_ps *ps, void *value);7738-STB_EXTERN stb_ps * stb_ps_add (stb_ps *ps, void *value);7739-STB_EXTERN stb_ps * stb_ps_remove(stb_ps *ps, void *value);7740-STB_EXTERN stb_ps * stb_ps_remove_any(stb_ps *ps, void **value);7741-STB_EXTERN void stb_ps_delete(stb_ps *ps);7742-STB_EXTERN int stb_ps_count (stb_ps *ps);7743-7744-STB_EXTERN stb_ps * stb_ps_copy (stb_ps *ps);7745-STB_EXTERN int stb_ps_subset(stb_ps *bigger, stb_ps *smaller);7746-STB_EXTERN int stb_ps_eq (stb_ps *p0, stb_ps *p1);7747-7748-STB_EXTERN void ** stb_ps_getlist (stb_ps *ps, int *count);7749-STB_EXTERN int stb_ps_writelist(stb_ps *ps, void **list, int size );7750-7751-// enum and fastlist don't allocate storage, but you must consume the7752-// list before there's any chance the data structure gets screwed up;7753-STB_EXTERN int stb_ps_enum (stb_ps *ps, void *data,7754- int (*func)(void *value, void*data) );7755-STB_EXTERN void ** stb_ps_fastlist(stb_ps *ps, int *count);7756-// result:7757-// returns a list, *count is the length of that list,7758-// but some entries of the list may be invalid;7759-// test with 'stb_ps_fastlist_valid(x)'7760-7761-#define stb_ps_fastlist_valid(x) ((stb_uinta) (x) > 1)7762-7763-#ifdef STB_DEFINE7764-7765-enum7766-{7767- STB_ps_direct = 0,7768- STB_ps_bucket = 1,7769- STB_ps_array = 2,7770- STB_ps_hash = 3,7771-};7772-7773-#define STB_BUCKET_SIZE 47774-7775-typedef struct7776-{7777- void *p[STB_BUCKET_SIZE];7778-} stb_ps_bucket;7779-#define GetBucket(p) ((stb_ps_bucket *) ((char *) (p) - STB_ps_bucket))7780-#define EncodeBucket(p) ((stb_ps *) ((char *) (p) + STB_ps_bucket))7781-7782-static void stb_bucket_free(stb_ps_bucket *b)7783-{7784- free(b);7785-}7786-7787-static stb_ps_bucket *stb_bucket_create2(void *v0, void *v1)7788-{7789- stb_ps_bucket *b = (stb_ps_bucket*) malloc(sizeof(*b));7790- b->p[0] = v0;7791- b->p[1] = v1;7792- b->p[2] = NULL;7793- b->p[3] = NULL;7794- return b;7795-}7796-7797-static stb_ps_bucket * stb_bucket_create3(void **v)7798-{7799- stb_ps_bucket *b = (stb_ps_bucket*) malloc(sizeof(*b));7800- b->p[0] = v[0];7801- b->p[1] = v[1];7802- b->p[2] = v[2];7803- b->p[3] = NULL;7804- return b;7805-}7806-7807-7808-// could use stb_arr, but this will save us memory7809-typedef struct7810-{7811- int count;7812- void *p[1];7813-} stb_ps_array;7814-#define GetArray(p) ((stb_ps_array *) ((char *) (p) - STB_ps_array))7815-#define EncodeArray(p) ((stb_ps *) ((char *) (p) + STB_ps_array))7816-7817-static int stb_ps_array_max = 13;7818-7819-typedef struct7820-{7821- int size, mask;7822- int count, count_deletes;7823- int grow_threshhold;7824- int shrink_threshhold;7825- int rehash_threshhold;7826- int any_offset;7827- void *table[1];7828-} stb_ps_hash;7829-#define GetHash(p) ((stb_ps_hash *) ((char *) (p) - STB_ps_hash))7830-#define EncodeHash(p) ((stb_ps *) ((char *) (p) + STB_ps_hash))7831-7832-#define stb_ps_empty(v) (((stb_uint32) v) <= 1)7833-7834-static stb_ps_hash *stb_ps_makehash(int size, int old_size, void **old_data)7835-{7836- int i;7837- stb_ps_hash *h = (stb_ps_hash *) malloc(sizeof(*h) + (size-1) * sizeof(h->table[0]));7838- assert(stb_is_pow2(size));7839- h->size = size;7840- h->mask = size-1;7841- h->shrink_threshhold = (int) (0.3f * size);7842- h-> grow_threshhold = (int) (0.8f * size);7843- h->rehash_threshhold = (int) (0.9f * size);7844- h->count = 0;7845- h->count_deletes = 0;7846- h->any_offset = 0;7847- memset(h->table, 0, size * sizeof(h->table[0]));7848- for (i=0; i < old_size; ++i)7849- if (!stb_ps_empty((size_t)old_data[i]))7850- stb_ps_add(EncodeHash(h), old_data[i]);7851- return h;7852-}7853-7854-void stb_ps_delete(stb_ps *ps)7855-{7856- switch (3 & (int)(size_t) ps) {7857- case STB_ps_direct: break;7858- case STB_ps_bucket: stb_bucket_free(GetBucket(ps)); break;7859- case STB_ps_array : free(GetArray(ps)); break;7860- case STB_ps_hash : free(GetHash(ps)); break;7861- }7862-}7863-7864-stb_ps *stb_ps_copy(stb_ps *ps)7865-{7866- int i;7867- // not a switch: order based on expected performance/power-law distribution7868- switch (3 & (int)(size_t) ps) {7869- case STB_ps_direct: return ps;7870- case STB_ps_bucket: {7871- stb_ps_bucket *n = (stb_ps_bucket *) malloc(sizeof(*n));7872- *n = *GetBucket(ps);7873- return EncodeBucket(n);7874- }7875- case STB_ps_array: {7876- stb_ps_array *a = GetArray(ps);7877- stb_ps_array *n = (stb_ps_array *) malloc(sizeof(*n) + stb_ps_array_max * sizeof(n->p[0]));7878- n->count = a->count;7879- for (i=0; i < a->count; ++i)7880- n->p[i] = a->p[i];7881- return EncodeArray(n);7882- }7883- case STB_ps_hash: {7884- stb_ps_hash *h = GetHash(ps);7885- stb_ps_hash *n = stb_ps_makehash(h->size, h->size, h->table);7886- return EncodeHash(n);7887- }7888- }7889- assert(0); /* NOTREACHED */7890- return NULL;7891-}7892-7893-int stb_ps_find(stb_ps *ps, void *value)7894-{7895- int i, code = 3 & (int)(size_t) ps;7896- assert((3 & (int)(size_t) value) == STB_ps_direct);7897- assert(stb_ps_fastlist_valid(value));7898- // not a switch: order based on expected performance/power-law distribution7899- if (code == STB_ps_direct)7900- return value == ps;7901- if (code == STB_ps_bucket) {7902- stb_ps_bucket *b = GetBucket(ps);7903- assert(STB_BUCKET_SIZE == 4);7904- if (b->p[0] == value || b->p[1] == value ||7905- b->p[2] == value || b->p[3] == value)7906- return STB_TRUE;7907- return STB_FALSE;7908- }7909- if (code == STB_ps_array) {7910- stb_ps_array *a = GetArray(ps);7911- for (i=0; i < a->count; ++i)7912- if (a->p[i] == value)7913- return STB_TRUE;7914- return STB_FALSE;7915- } else {7916- stb_ps_hash *h = GetHash(ps);7917- stb_uint32 hash = stb_hashptr(value);7918- stb_uint32 s, n = hash & h->mask;7919- void **t = h->table;7920- if (t[n] == value) return STB_TRUE;7921- if (t[n] == NULL) return STB_FALSE;7922- s = stb_rehash(hash) | 1;7923- do {7924- n = (n + s) & h->mask;7925- if (t[n] == value) return STB_TRUE;7926- } while (t[n] != NULL);7927- return STB_FALSE;7928- }7929-}7930-7931-stb_ps * stb_ps_add (stb_ps *ps, void *value)7932-{7933- #ifdef STB_DEBUG7934- assert(!stb_ps_find(ps,value));7935- #endif7936- if (value == NULL) return ps; // ignore NULL adds to avoid bad breakage7937- assert((3 & (int)(size_t) value) == STB_ps_direct);7938- assert(stb_ps_fastlist_valid(value));7939- assert(value != STB_DEL); // STB_DEL is less likely7940-7941- switch (3 & (int)(size_t) ps) {7942- case STB_ps_direct:7943- if (ps == NULL) return (stb_ps *) value;7944- return EncodeBucket(stb_bucket_create2(ps,value));7945-7946- case STB_ps_bucket: {7947- stb_ps_bucket *b = GetBucket(ps);7948- stb_ps_array *a;7949- assert(STB_BUCKET_SIZE == 4);7950- if (b->p[0] == NULL) { b->p[0] = value; return ps; }7951- if (b->p[1] == NULL) { b->p[1] = value; return ps; }7952- if (b->p[2] == NULL) { b->p[2] = value; return ps; }7953- if (b->p[3] == NULL) { b->p[3] = value; return ps; }7954- a = (stb_ps_array *) malloc(sizeof(*a) + 7 * sizeof(a->p[0])); // 8 slots, must be 2^k7955- memcpy(a->p, b, sizeof(*b));7956- a->p[4] = value;7957- a->count = 5;7958- stb_bucket_free(b);7959- return EncodeArray(a);7960- }7961-7962- case STB_ps_array: {7963- stb_ps_array *a = GetArray(ps);7964- if (a->count == stb_ps_array_max) {7965- // promote from array to hash7966- stb_ps_hash *h = stb_ps_makehash(2 << stb_log2_ceil(a->count), a->count, a->p);7967- free(a);7968- return stb_ps_add(EncodeHash(h), value);7969- }7970- // do we need to resize the array? the array doubles in size when it7971- // crosses a power-of-two7972- if ((a->count & (a->count-1))==0) {7973- int newsize = a->count*2;7974- // clamp newsize to max if:7975- // 1. it's larger than max7976- // 2. newsize*1.5 is larger than max (to avoid extra resizing)7977- if (newsize + a->count > stb_ps_array_max)7978- newsize = stb_ps_array_max;7979- a = (stb_ps_array *) realloc(a, sizeof(*a) + (newsize-1) * sizeof(a->p[0]));7980- }7981- a->p[a->count++] = value;7982- return EncodeArray(a);7983- }7984- case STB_ps_hash: {7985- stb_ps_hash *h = GetHash(ps);7986- stb_uint32 hash = stb_hashptr(value);7987- stb_uint32 n = hash & h->mask;7988- void **t = h->table;7989- // find first NULL or STB_DEL entry7990- if (!stb_ps_empty((size_t)t[n])) {7991- stb_uint32 s = stb_rehash(hash) | 1;7992- do {7993- n = (n + s) & h->mask;7994- } while (!stb_ps_empty((size_t)t[n]));7995- }7996- if (t[n] == STB_DEL)7997- -- h->count_deletes;7998- t[n] = value;7999- ++ h->count;8000- if (h->count == h->grow_threshhold) {8001- stb_ps_hash *h2 = stb_ps_makehash(h->size*2, h->size, t);8002- free(h);8003- return EncodeHash(h2);8004- }8005- if (h->count + h->count_deletes == h->rehash_threshhold) {8006- stb_ps_hash *h2 = stb_ps_makehash(h->size, h->size, t);8007- free(h);8008- return EncodeHash(h2);8009- }8010- return ps;8011- }8012- }8013- return NULL; /* NOTREACHED */8014-}8015-8016-stb_ps *stb_ps_remove(stb_ps *ps, void *value)8017-{8018- #ifdef STB_DEBUG8019- assert(stb_ps_find(ps, value));8020- #endif8021- assert((3 & (int)(size_t) value) == STB_ps_direct);8022- if (value == NULL) return ps; // ignore NULL removes to avoid bad breakage8023- switch (3 & (int)(size_t) ps) {8024- case STB_ps_direct:8025- return ps == value ? NULL : ps;8026- case STB_ps_bucket: {8027- stb_ps_bucket *b = GetBucket(ps);8028- int count=0;8029- assert(STB_BUCKET_SIZE == 4);8030- if (b->p[0] == value) b->p[0] = NULL; else count += (b->p[0] != NULL);8031- if (b->p[1] == value) b->p[1] = NULL; else count += (b->p[1] != NULL);8032- if (b->p[2] == value) b->p[2] = NULL; else count += (b->p[2] != NULL);8033- if (b->p[3] == value) b->p[3] = NULL; else count += (b->p[3] != NULL);8034- if (count == 1) { // shrink bucket at size 18035- value = b->p[0];8036- if (value == NULL) value = b->p[1];8037- if (value == NULL) value = b->p[2];8038- if (value == NULL) value = b->p[3];8039- assert(value != NULL);8040- stb_bucket_free(b);8041- return (stb_ps *) value; // return STB_ps_direct of value8042- }8043- return ps;8044- }8045- case STB_ps_array: {8046- stb_ps_array *a = GetArray(ps);8047- int i;8048- for (i=0; i < a->count; ++i) {8049- if (a->p[i] == value) {8050- a->p[i] = a->p[--a->count];8051- if (a->count == 3) { // shrink to bucket!8052- stb_ps_bucket *b = stb_bucket_create3(a->p);8053- free(a);8054- return EncodeBucket(b);8055- }8056- return ps;8057- }8058- }8059- return ps;8060- }8061- case STB_ps_hash: {8062- stb_ps_hash *h = GetHash(ps);8063- stb_uint32 hash = stb_hashptr(value);8064- stb_uint32 s, n = hash & h->mask;8065- void **t = h->table;8066- if (t[n] != value) {8067- s = stb_rehash(hash) | 1;8068- do {8069- n = (n + s) & h->mask;8070- } while (t[n] != value);8071- }8072- t[n] = STB_DEL;8073- -- h->count;8074- ++ h->count_deletes;8075- // should we shrink down to an array?8076- if (h->count < stb_ps_array_max) {8077- int n = 1 << stb_log2_floor(stb_ps_array_max);8078- if (h->count < n) {8079- stb_ps_array *a = (stb_ps_array *) malloc(sizeof(*a) + (n-1) * sizeof(a->p[0]));8080- int i,j=0;8081- for (i=0; i < h->size; ++i)8082- if (!stb_ps_empty((size_t)t[i]))8083- a->p[j++] = t[i];8084- assert(j == h->count);8085- a->count = j;8086- free(h);8087- return EncodeArray(a);8088- }8089- }8090- if (h->count == h->shrink_threshhold) {8091- stb_ps_hash *h2 = stb_ps_makehash(h->size >> 1, h->size, t);8092- free(h);8093- return EncodeHash(h2);8094- }8095- return ps;8096- }8097- }8098- return ps; /* NOTREACHED */8099-}8100-8101-stb_ps *stb_ps_remove_any(stb_ps *ps, void **value)8102-{8103- assert(ps != NULL);8104- switch (3 & (int)(size_t) ps) {8105- case STB_ps_direct:8106- *value = ps;8107- return NULL;8108- case STB_ps_bucket: {8109- stb_ps_bucket *b = GetBucket(ps);8110- int count=0, slast=0, last=0;8111- assert(STB_BUCKET_SIZE == 4);8112- if (b->p[0]) { ++count; last = 0; }8113- if (b->p[1]) { ++count; slast = last; last = 1; }8114- if (b->p[2]) { ++count; slast = last; last = 2; }8115- if (b->p[3]) { ++count; slast = last; last = 3; }8116- *value = b->p[last];8117- b->p[last] = 0;8118- if (count == 2) {8119- void *leftover = b->p[slast]; // second to last8120- stb_bucket_free(b);8121- return (stb_ps *) leftover;8122- }8123- return ps;8124- }8125- case STB_ps_array: {8126- stb_ps_array *a = GetArray(ps);8127- *value = a->p[a->count-1];8128- if (a->count == 4)8129- return stb_ps_remove(ps, *value);8130- --a->count;8131- return ps;8132- }8133- case STB_ps_hash: {8134- stb_ps_hash *h = GetHash(ps);8135- void **t = h->table;8136- stb_uint32 n = h->any_offset;8137- while (stb_ps_empty((size_t)t[n]))8138- n = (n + 1) & h->mask;8139- *value = t[n];8140- h->any_offset = (n+1) & h->mask;8141- // check if we need to skip down to the previous type8142- if (h->count-1 < stb_ps_array_max || h->count-1 == h->shrink_threshhold)8143- return stb_ps_remove(ps, *value);8144- t[n] = STB_DEL;8145- -- h->count;8146- ++ h->count_deletes;8147- return ps;8148- }8149- }8150- return ps; /* NOTREACHED */8151-}8152-8153-8154-void ** stb_ps_getlist(stb_ps *ps, int *count)8155-{8156- int i,n=0;8157- void **p = NULL;8158- switch (3 & (int)(size_t) ps) {8159- case STB_ps_direct:8160- if (ps == NULL) { *count = 0; return NULL; }8161- p = (void **) malloc(sizeof(*p) * 1);8162- p[0] = ps;8163- *count = 1;8164- return p;8165- case STB_ps_bucket: {8166- stb_ps_bucket *b = GetBucket(ps);8167- p = (void **) malloc(sizeof(*p) * STB_BUCKET_SIZE);8168- for (i=0; i < STB_BUCKET_SIZE; ++i)8169- if (b->p[i] != NULL)8170- p[n++] = b->p[i];8171- break;8172- }8173- case STB_ps_array: {8174- stb_ps_array *a = GetArray(ps);8175- p = (void **) malloc(sizeof(*p) * a->count);8176- memcpy(p, a->p, sizeof(*p) * a->count);8177- *count = a->count;8178- return p;8179- }8180- case STB_ps_hash: {8181- stb_ps_hash *h = GetHash(ps);8182- p = (void **) malloc(sizeof(*p) * h->count);8183- for (i=0; i < h->size; ++i)8184- if (!stb_ps_empty((size_t)h->table[i]))8185- p[n++] = h->table[i];8186- break;8187- }8188- }8189- *count = n;8190- return p;8191-}8192-8193-int stb_ps_writelist(stb_ps *ps, void **list, int size )8194-{8195- int i,n=0;8196- switch (3 & (int)(size_t) ps) {8197- case STB_ps_direct:8198- if (ps == NULL || size <= 0) return 0;8199- list[0] = ps;8200- return 1;8201- case STB_ps_bucket: {8202- stb_ps_bucket *b = GetBucket(ps);8203- for (i=0; i < STB_BUCKET_SIZE; ++i)8204- if (b->p[i] != NULL && n < size)8205- list[n++] = b->p[i];8206- return n;8207- }8208- case STB_ps_array: {8209- stb_ps_array *a = GetArray(ps);8210- n = stb_min(size, a->count);8211- memcpy(list, a->p, sizeof(*list) * n);8212- return n;8213- }8214- case STB_ps_hash: {8215- stb_ps_hash *h = GetHash(ps);8216- if (size <= 0) return 0;8217- for (i=0; i < h->count; ++i) {8218- if (!stb_ps_empty((size_t)h->table[i])) {8219- list[n++] = h->table[i];8220- if (n == size) break;8221- }8222- }8223- return n;8224- }8225- }8226- return 0; /* NOTREACHED */8227-}8228-8229-int stb_ps_enum(stb_ps *ps, void *data, int (*func)(void *value, void *data))8230-{8231- int i;8232- switch (3 & (int)(size_t) ps) {8233- case STB_ps_direct:8234- if (ps == NULL) return STB_TRUE;8235- return func(ps, data);8236- case STB_ps_bucket: {8237- stb_ps_bucket *b = GetBucket(ps);8238- for (i=0; i < STB_BUCKET_SIZE; ++i)8239- if (b->p[i] != NULL)8240- if (!func(b->p[i], data))8241- return STB_FALSE;8242- return STB_TRUE;8243- }8244- case STB_ps_array: {8245- stb_ps_array *a = GetArray(ps);8246- for (i=0; i < a->count; ++i)8247- if (!func(a->p[i], data))8248- return STB_FALSE;8249- return STB_TRUE;8250- }8251- case STB_ps_hash: {8252- stb_ps_hash *h = GetHash(ps);8253- for (i=0; i < h->count; ++i)8254- if (!stb_ps_empty((size_t)h->table[i]))8255- if (!func(h->table[i], data))8256- return STB_FALSE;8257- return STB_TRUE;8258- }8259- }8260- return STB_TRUE; /* NOTREACHED */8261-}8262-8263-int stb_ps_count (stb_ps *ps)8264-{8265- switch (3 & (int)(size_t) ps) {8266- case STB_ps_direct:8267- return ps != NULL;8268- case STB_ps_bucket: {8269- stb_ps_bucket *b = GetBucket(ps);8270- return (b->p[0] != NULL) + (b->p[1] != NULL) +8271- (b->p[2] != NULL) + (b->p[3] != NULL);8272- }8273- case STB_ps_array: {8274- stb_ps_array *a = GetArray(ps);8275- return a->count;8276- }8277- case STB_ps_hash: {8278- stb_ps_hash *h = GetHash(ps);8279- return h->count;8280- }8281- }8282- return 0;8283-}8284-8285-void ** stb_ps_fastlist(stb_ps *ps, int *count)8286-{8287- static void *storage;8288-8289- switch (3 & (int)(size_t) ps) {8290- case STB_ps_direct:8291- if (ps == NULL) { *count = 0; return NULL; }8292- storage = ps;8293- *count = 1;8294- return &storage;8295- case STB_ps_bucket: {8296- stb_ps_bucket *b = GetBucket(ps);8297- *count = STB_BUCKET_SIZE;8298- return b->p;8299- }8300- case STB_ps_array: {8301- stb_ps_array *a = GetArray(ps);8302- *count = a->count;8303- return a->p;8304- }8305- case STB_ps_hash: {8306- stb_ps_hash *h = GetHash(ps);8307- *count = h->size;8308- return h->table;8309- }8310- }8311- return NULL; /* NOTREACHED */8312-}8313-8314-int stb_ps_subset(stb_ps *bigger, stb_ps *smaller)8315-{8316- int i, listlen;8317- void **list = stb_ps_fastlist(smaller, &listlen);8318- for(i=0; i < listlen; ++i)8319- if (stb_ps_fastlist_valid(list[i]))8320- if (!stb_ps_find(bigger, list[i]))8321- return 0;8322- return 1;8323-}8324-8325-int stb_ps_eq(stb_ps *p0, stb_ps *p1)8326-{8327- if (stb_ps_count(p0) != stb_ps_count(p1))8328- return 0;8329- return stb_ps_subset(p0, p1);8330-}8331-8332-#undef GetBucket8333-#undef GetArray8334-#undef GetHash8335-8336-#undef EncodeBucket8337-#undef EncodeArray8338-#undef EncodeHash8339-8340-#endif8341-8342-8343-//////////////////////////////////////////////////////////////////////////////8344-//8345-// Random Numbers via Meresenne Twister or LCG8346-//8347-8348-STB_EXTERN unsigned int stb_srandLCG(unsigned int seed);8349-STB_EXTERN unsigned int stb_randLCG(void);8350-STB_EXTERN double stb_frandLCG(void);8351-8352-STB_EXTERN void stb_srand(unsigned int seed);8353-STB_EXTERN unsigned int stb_rand(void);8354-STB_EXTERN double stb_frand(void);8355-STB_EXTERN void stb_shuffle(void *p, size_t n, size_t sz,8356- unsigned int seed);8357-STB_EXTERN void stb_reverse(void *p, size_t n, size_t sz);8358-8359-STB_EXTERN unsigned int stb_randLCG_explicit(unsigned int seed);8360-8361-#define stb_rand_define(x,y) \8362- \8363- unsigned int x(void) \8364- { \8365- static unsigned int stb__rand = y; \8366- stb__rand = stb__rand * 2147001325 + 715136305; /* BCPL */ \8367- return 0x31415926 ^ ((stb__rand >> 16) + (stb__rand << 16)); \8368- }8369-8370-#ifdef STB_DEFINE8371-unsigned int stb_randLCG_explicit(unsigned int seed)8372-{8373- return seed * 2147001325 + 715136305;8374-}8375-8376-static unsigned int stb__rand_seed=0;8377-8378-unsigned int stb_srandLCG(unsigned int seed)8379-{8380- unsigned int previous = stb__rand_seed;8381- stb__rand_seed = seed;8382- return previous;8383-}8384-8385-unsigned int stb_randLCG(void)8386-{8387- stb__rand_seed = stb__rand_seed * 2147001325 + 715136305; // BCPL generator8388- // shuffle non-random bits to the middle, and xor to decorrelate with seed8389- return 0x31415926 ^ ((stb__rand_seed >> 16) + (stb__rand_seed << 16));8390-}8391-8392-double stb_frandLCG(void)8393-{8394- return stb_randLCG() / ((double) (1 << 16) * (1 << 16));8395-}8396-8397-void stb_shuffle(void *p, size_t n, size_t sz, unsigned int seed)8398-{8399- char *a;8400- unsigned int old_seed;8401- int i;8402- if (seed)8403- old_seed = stb_srandLCG(seed);8404- a = (char *) p + (n-1) * sz;8405-8406- for (i=(int) n; i > 1; --i) {8407- int j = stb_randLCG() % i;8408- stb_swap(a, (char *) p + j * sz, sz);8409- a -= sz;8410- }8411- if (seed)8412- stb_srandLCG(old_seed);8413-}8414-8415-void stb_reverse(void *p, size_t n, size_t sz)8416-{8417- size_t i,j = n-1;8418- for (i=0; i < j; ++i,--j) {8419- stb_swap((char *) p + i * sz, (char *) p + j * sz, sz);8420- }8421-}8422-8423-// public domain Mersenne Twister by Michael Brundage8424-#define STB__MT_LEN 6248425-8426-int stb__mt_index = STB__MT_LEN*sizeof(int)+1;8427-unsigned int stb__mt_buffer[STB__MT_LEN];8428-8429-void stb_srand(unsigned int seed)8430-{8431- int i;8432- stb__mt_buffer[0]= seed & 0xffffffffUL;8433- for (i=1 ; i < STB__MT_LEN; ++i)8434- stb__mt_buffer[i] = (1812433253UL * (stb__mt_buffer[i-1] ^ (stb__mt_buffer[i-1] >> 30)) + i);8435- stb__mt_index = STB__MT_LEN*sizeof(unsigned int);8436-}8437-8438-#define STB__MT_IA 3978439-#define STB__MT_IB (STB__MT_LEN - STB__MT_IA)8440-#define STB__UPPER_MASK 0x800000008441-#define STB__LOWER_MASK 0x7FFFFFFF8442-#define STB__MATRIX_A 0x9908B0DF8443-#define STB__TWIST(b,i,j) ((b)[i] & STB__UPPER_MASK) | ((b)[j] & STB__LOWER_MASK)8444-#define STB__MAGIC(s) (((s)&1)*STB__MATRIX_A)8445-8446-unsigned int stb_rand()8447-{8448- unsigned int * b = stb__mt_buffer;8449- int idx = stb__mt_index;8450- unsigned int s,r;8451- int i;8452-8453- if (idx >= STB__MT_LEN*sizeof(unsigned int)) {8454- if (idx > STB__MT_LEN*sizeof(unsigned int))8455- stb_srand(0);8456- idx = 0;8457- i = 0;8458- for (; i < STB__MT_IB; i++) {8459- s = STB__TWIST(b, i, i+1);8460- b[i] = b[i + STB__MT_IA] ^ (s >> 1) ^ STB__MAGIC(s);8461- }8462- for (; i < STB__MT_LEN-1; i++) {8463- s = STB__TWIST(b, i, i+1);8464- b[i] = b[i - STB__MT_IB] ^ (s >> 1) ^ STB__MAGIC(s);8465- }8466-8467- s = STB__TWIST(b, STB__MT_LEN-1, 0);8468- b[STB__MT_LEN-1] = b[STB__MT_IA-1] ^ (s >> 1) ^ STB__MAGIC(s);8469- }8470- stb__mt_index = idx + sizeof(unsigned int);8471-8472- r = *(unsigned int *)((unsigned char *)b + idx);8473-8474- r ^= (r >> 11);8475- r ^= (r << 7) & 0x9D2C5680;8476- r ^= (r << 15) & 0xEFC60000;8477- r ^= (r >> 18);8478-8479- return r;8480-}8481-8482-double stb_frand(void)8483-{8484- return stb_rand() / ((double) (1 << 16) * (1 << 16));8485-}8486-8487-#endif8488-8489-8490-//////////////////////////////////////////////////////////////////////////////8491-//8492-// stb_dupe8493-//8494-// stb_dupe is a duplicate-finding system for very, very large data8495-// structures--large enough that sorting is too slow, but not so large8496-// that we can't keep all the data in memory. using it works as follows:8497-//8498-// 1. create an stb_dupe:8499-// provide a hash function8500-// provide an equality function8501-// provide an estimate for the size8502-// optionally provide a comparison function8503-//8504-// 2. traverse your data, 'adding' pointers to the stb_dupe8505-//8506-// 3. finish and ask for duplicates8507-//8508-// the stb_dupe will discard its intermediate data and build8509-// a collection of sorted lists of duplicates, with non-duplicate8510-// entries omitted entirely8511-//8512-//8513-// Implementation strategy:8514-//8515-// while collecting the N items, we keep a hash table of approximate8516-// size sqrt(N). (if you tell use the N up front, the hash table is8517-// just that size exactly)8518-//8519-// each entry in the hash table is just an stb__arr of pointers (no need8520-// to use stb_ps, because we don't need to delete from these)8521-//8522-// for step 3, for each entry in the hash table, we apply stb_dupe to it8523-// recursively. once the size gets small enough (or doesn't decrease8524-// significantly), we switch to either using qsort() on the comparison8525-// function, or else we just do the icky N^2 gather8526-8527-8528-typedef struct stb_dupe stb_dupe;8529-8530-typedef int (*stb_compare_func)(void *a, void *b);8531-typedef int (*stb_hash_func)(void *a, unsigned int seed);8532-8533-STB_EXTERN void stb_dupe_free(stb_dupe *sd);8534-STB_EXTERN stb_dupe *stb_dupe_create(stb_hash_func hash,8535- stb_compare_func eq, int size, stb_compare_func ineq);8536-STB_EXTERN void stb_dupe_add(stb_dupe *sd, void *item);8537-STB_EXTERN void stb_dupe_finish(stb_dupe *sd);8538-STB_EXTERN int stb_dupe_numsets(stb_dupe *sd);8539-STB_EXTERN void **stb_dupe_set(stb_dupe *sd, int num);8540-STB_EXTERN int stb_dupe_set_count(stb_dupe *sd, int num);8541-8542-struct stb_dupe8543-{8544- void ***hash_table;8545- int hash_size;8546- int size_log2;8547- int population;8548-8549- int hash_shift;8550- stb_hash_func hash;8551-8552- stb_compare_func eq;8553- stb_compare_func ineq;8554-8555- void ***dupes;8556-};8557-8558-#ifdef STB_DEFINE8559-8560-int stb_dupe_numsets(stb_dupe *sd)8561-{8562- assert(sd->hash_table == NULL);8563- return stb_arr_len(sd->dupes);8564-}8565-8566-void **stb_dupe_set(stb_dupe *sd, int num)8567-{8568- assert(sd->hash_table == NULL);8569- return sd->dupes[num];8570-}8571-8572-int stb_dupe_set_count(stb_dupe *sd, int num)8573-{8574- assert(sd->hash_table == NULL);8575- return stb_arr_len(sd->dupes[num]);8576-}8577-8578-stb_dupe *stb_dupe_create(stb_hash_func hash, stb_compare_func eq, int size,8579- stb_compare_func ineq)8580-{8581- int i, hsize;8582- stb_dupe *sd = (stb_dupe *) malloc(sizeof(*sd));8583-8584- sd->size_log2 = 4;8585- hsize = 1 << sd->size_log2;8586- while (hsize * hsize < size) {8587- ++sd->size_log2;8588- hsize *= 2;8589- }8590-8591- sd->hash = hash;8592- sd->eq = eq;8593- sd->ineq = ineq;8594- sd->hash_shift = 0;8595-8596- sd->population = 0;8597- sd->hash_size = hsize;8598- sd->hash_table = (void ***) malloc(sizeof(*sd->hash_table) * hsize);8599- for (i=0; i < hsize; ++i)8600- sd->hash_table[i] = NULL;8601-8602- sd->dupes = NULL;8603-8604- return sd;8605-}8606-8607-void stb_dupe_add(stb_dupe *sd, void *item)8608-{8609- stb_uint32 hash = sd->hash(item, sd->hash_shift);8610- int z = hash & (sd->hash_size-1);8611- stb_arr_push(sd->hash_table[z], item);8612- ++sd->population;8613-}8614-8615-void stb_dupe_free(stb_dupe *sd)8616-{8617- int i;8618- for (i=0; i < stb_arr_len(sd->dupes); ++i)8619- if (sd->dupes[i])8620- stb_arr_free(sd->dupes[i]);8621- stb_arr_free(sd->dupes);8622- free(sd);8623-}8624-8625-static stb_compare_func stb__compare;8626-8627-static int stb__dupe_compare(const void *a, const void *b)8628-{8629- void *p = *(void **) a;8630- void *q = *(void **) b;8631-8632- return stb__compare(p,q);8633-}8634-8635-void stb_dupe_finish(stb_dupe *sd)8636-{8637- int i,j,k;8638- assert(sd->dupes == NULL);8639- for (i=0; i < sd->hash_size; ++i) {8640- void ** list = sd->hash_table[i];8641- if (list != NULL) {8642- int n = stb_arr_len(list);8643- // @TODO: measure to find good numbers instead of just making them up!8644- int thresh = (sd->ineq ? 200 : 20);8645- // if n is large enough to be worth it, and n is smaller than8646- // before (so we can guarantee we'll use a smaller hash table);8647- // and there are enough hash bits left, assuming full 32-bit hash8648- if (n > thresh && n < (sd->population >> 3) && sd->hash_shift + sd->size_log2*2 < 32) {8649-8650- // recursively process this row using stb_dupe, O(N log log N)8651-8652- stb_dupe *d = stb_dupe_create(sd->hash, sd->eq, n, sd->ineq);8653- d->hash_shift = stb_randLCG_explicit(sd->hash_shift);8654- for (j=0; j < n; ++j)8655- stb_dupe_add(d, list[j]);8656- stb_arr_free(sd->hash_table[i]);8657- stb_dupe_finish(d);8658- for (j=0; j < stb_arr_len(d->dupes); ++j) {8659- stb_arr_push(sd->dupes, d->dupes[j]);8660- d->dupes[j] = NULL; // take over ownership8661- }8662- stb_dupe_free(d);8663-8664- } else if (sd->ineq) {8665-8666- // process this row using qsort(), O(N log N)8667- stb__compare = sd->ineq;8668- qsort(list, n, sizeof(list[0]), stb__dupe_compare);8669-8670- // find equal subsequences of the list8671- for (j=0; j < n-1; ) {8672- // find a subsequence from j..k8673- for (k=j; k < n; ++k)8674- // only use ineq so eq can be left undefined8675- if (sd->ineq(list[j], list[k]))8676- break;8677- // k is the first one not in the subsequence8678- if (k-j > 1) {8679- void **mylist = NULL;8680- stb_arr_setlen(mylist, k-j);8681- memcpy(mylist, list+j, sizeof(list[j]) * (k-j));8682- stb_arr_push(sd->dupes, mylist);8683- }8684- j = k;8685- }8686- stb_arr_free(sd->hash_table[i]);8687- } else {8688-8689- // process this row using eq(), O(N^2)8690- for (j=0; j < n; ++j) {8691- if (list[j] != NULL) {8692- void **output = NULL;8693- for (k=j+1; k < n; ++k) {8694- if (sd->eq(list[j], list[k])) {8695- if (output == NULL)8696- stb_arr_push(output, list[j]);8697- stb_arr_push(output, list[k]);8698- list[k] = NULL;8699- }8700- }8701- list[j] = NULL;8702- if (output)8703- stb_arr_push(sd->dupes, output);8704- }8705- }8706- stb_arr_free(sd->hash_table[i]);8707- }8708- }8709- }8710- free(sd->hash_table);8711- sd->hash_table = NULL;8712-}8713-#endif8714-8715-//////////////////////////////////////////////////////////////////////////////8716-//8717-// templatized Sort routine8718-//8719-// This is an attempt to implement a templated sorting algorithm.8720-// To use it, you have to explicitly instantiate it as a _function_,8721-// then you call that function. This allows the comparison to be inlined,8722-// giving the sort similar performance to C++ sorts.8723-//8724-// It implements quicksort with three-way-median partitioning (generally8725-// well-behaved), with a final insertion sort pass.8726-//8727-// When you define the compare expression, you should assume you have8728-// elements of your array pointed to by 'a' and 'b', and perform the comparison8729-// on those. OR you can use one or more statements; first say '0;', then8730-// write whatever code you want, and compute the result into a variable 'c'.8731-8732-#define stb_declare_sort(FUNCNAME, TYPE) \8733- void FUNCNAME(TYPE *p, int n)8734-#define stb_define_sort(FUNCNAME,TYPE,COMPARE) \8735- stb__define_sort( void, FUNCNAME,TYPE,COMPARE)8736-#define stb_define_sort_static(FUNCNAME,TYPE,COMPARE) \8737- stb__define_sort(static void, FUNCNAME,TYPE,COMPARE)8738-8739-#define stb__define_sort(MODE, FUNCNAME, TYPE, COMPARE) \8740- \8741-static void STB_(FUNCNAME,_ins_sort)(TYPE *p, int n) \8742-{ \8743- int i,j; \8744- for (i=1; i < n; ++i) { \8745- TYPE t = p[i], *a = &t; \8746- j = i; \8747- while (j > 0) { \8748- TYPE *b = &p[j-1]; \8749- int c = COMPARE; \8750- if (!c) break; \8751- p[j] = p[j-1]; \8752- --j; \8753- } \8754- if (i != j) \8755- p[j] = t; \8756- } \8757-} \8758- \8759-static void STB_(FUNCNAME,_quicksort)(TYPE *p, int n) \8760-{ \8761- /* threshold for transitioning to insertion sort */ \8762- while (n > 12) { \8763- TYPE *a,*b,t; \8764- int c01,c12,c,m,i,j; \8765- \8766- /* compute median of three */ \8767- m = n >> 1; \8768- a = &p[0]; \8769- b = &p[m]; \8770- c = COMPARE; \8771- c01 = c; \8772- a = &p[m]; \8773- b = &p[n-1]; \8774- c = COMPARE; \8775- c12 = c; \8776- /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ \8777- if (c01 != c12) { \8778- /* otherwise, we'll need to swap something else to middle */ \8779- int z; \8780- a = &p[0]; \8781- b = &p[n-1]; \8782- c = COMPARE; \8783- /* 0>mid && mid<n: 0>n => n; 0<n => 0 */ \8784- /* 0<mid && mid>n: 0>n => 0; 0<n => n */ \8785- z = (c == c12) ? 0 : n-1; \8786- t = p[z]; \8787- p[z] = p[m]; \8788- p[m] = t; \8789- } \8790- /* now p[m] is the median-of-three */ \8791- /* swap it to the beginning so it won't move around */ \8792- t = p[0]; \8793- p[0] = p[m]; \8794- p[m] = t; \8795- \8796- /* partition loop */ \8797- i=1; \8798- j=n-1; \8799- for(;;) { \8800- /* handling of equality is crucial here */ \8801- /* for sentinels & efficiency with duplicates */ \8802- b = &p[0]; \8803- for (;;++i) { \8804- a=&p[i]; \8805- c = COMPARE; \8806- if (!c) break; \8807- } \8808- a = &p[0]; \8809- for (;;--j) { \8810- b=&p[j]; \8811- c = COMPARE; \8812- if (!c) break; \8813- } \8814- /* make sure we haven't crossed */ \8815- if (i >= j) break; \8816- t = p[i]; \8817- p[i] = p[j]; \8818- p[j] = t; \8819- \8820- ++i; \8821- --j; \8822- } \8823- /* recurse on smaller side, iterate on larger */ \8824- if (j < (n-i)) { \8825- STB_(FUNCNAME,_quicksort)(p,j); \8826- p = p+i; \8827- n = n-i; \8828- } else { \8829- STB_(FUNCNAME,_quicksort)(p+i, n-i); \8830- n = j; \8831- } \8832- } \8833-} \8834- \8835-MODE FUNCNAME(TYPE *p, int n) \8836-{ \8837- STB_(FUNCNAME, _quicksort)(p, n); \8838- STB_(FUNCNAME, _ins_sort)(p, n); \8839-} \8840-8841-8842-//////////////////////////////////////////////////////////////////////////////8843-//8844-// stb_bitset an array of booleans indexed by integers8845-//8846-8847-typedef stb_uint32 stb_bitset;8848-8849-STB_EXTERN stb_bitset *stb_bitset_new(int value, int len);8850-8851-#define stb_bitset_clearall(arr,len) (memset(arr, 0, 4 * (len)))8852-#define stb_bitset_setall(arr,len) (memset(arr, 255, 4 * (len)))8853-8854-#define stb_bitset_setbit(arr,n) ((arr)[(n) >> 5] |= (1 << (n & 31)))8855-#define stb_bitset_clearbit(arr,n) ((arr)[(n) >> 5] &= ~(1 << (n & 31)))8856-#define stb_bitset_testbit(arr,n) ((arr)[(n) >> 5] & (1 << (n & 31)))8857-8858-STB_EXTERN stb_bitset *stb_bitset_union(stb_bitset *p0, stb_bitset *p1, int len);8859-8860-STB_EXTERN int *stb_bitset_getlist(stb_bitset *out, int start, int end);8861-8862-STB_EXTERN int stb_bitset_eq(stb_bitset *p0, stb_bitset *p1, int len);8863-STB_EXTERN int stb_bitset_disjoint(stb_bitset *p0, stb_bitset *p1, int len);8864-STB_EXTERN int stb_bitset_disjoint_0(stb_bitset *p0, stb_bitset *p1, int len);8865-STB_EXTERN int stb_bitset_subset(stb_bitset *bigger, stb_bitset *smaller, int len);8866-STB_EXTERN int stb_bitset_unioneq_changed(stb_bitset *p0, stb_bitset *p1, int len);8867-8868-#ifdef STB_DEFINE8869-int stb_bitset_eq(stb_bitset *p0, stb_bitset *p1, int len)8870-{8871- int i;8872- for (i=0; i < len; ++i)8873- if (p0[i] != p1[i]) return 0;8874- return 1;8875-}8876-8877-int stb_bitset_disjoint(stb_bitset *p0, stb_bitset *p1, int len)8878-{8879- int i;8880- for (i=0; i < len; ++i)8881- if (p0[i] & p1[i]) return 0;8882- return 1;8883-}8884-8885-int stb_bitset_disjoint_0(stb_bitset *p0, stb_bitset *p1, int len)8886-{8887- int i;8888- for (i=0; i < len; ++i)8889- if ((p0[i] | p1[i]) != 0xffffffff) return 0;8890- return 1;8891-}8892-8893-int stb_bitset_subset(stb_bitset *bigger, stb_bitset *smaller, int len)8894-{8895- int i;8896- for (i=0; i < len; ++i)8897- if ((bigger[i] & smaller[i]) != smaller[i]) return 0;8898- return 1;8899-}8900-8901-stb_bitset *stb_bitset_union(stb_bitset *p0, stb_bitset *p1, int len)8902-{8903- int i;8904- stb_bitset *d = (stb_bitset *) malloc(sizeof(*d) * len);8905- for (i=0; i < len; ++i) d[i] = p0[i] | p1[i];8906- return d;8907-}8908-8909-int stb_bitset_unioneq_changed(stb_bitset *p0, stb_bitset *p1, int len)8910-{8911- int i, changed=0;8912- for (i=0; i < len; ++i) {8913- stb_bitset d = p0[i] | p1[i];8914- if (d != p0[i]) {8915- p0[i] = d;8916- changed = 1;8917- }8918- }8919- return changed;8920-}8921-8922-stb_bitset *stb_bitset_new(int value, int len)8923-{8924- int i;8925- stb_bitset *d = (stb_bitset *) malloc(sizeof(*d) * len);8926- if (value) value = 0xffffffff;8927- for (i=0; i < len; ++i) d[i] = value;8928- return d;8929-}8930-8931-int *stb_bitset_getlist(stb_bitset *out, int start, int end)8932-{8933- int *list = NULL;8934- int i;8935- for (i=start; i < end; ++i)8936- if (stb_bitset_testbit(out, i))8937- stb_arr_push(list, i);8938- return list;8939-}8940-#endif8941-8942-//////////////////////////////////////////////////////////////////////////////8943-//8944-// stb_wordwrap quality word-wrapping for fixed-width fonts8945-//8946-8947-STB_EXTERN int stb_wordwrap(int *pairs, int pair_max, int count, char *str);8948-STB_EXTERN int *stb_wordwrapalloc(int count, char *str);8949-8950-#ifdef STB_DEFINE8951-8952-int stb_wordwrap(int *pairs, int pair_max, int count, char *str)8953-{8954- int n=0,i=0, start=0,nonwhite=0;8955- if (pairs == NULL) pair_max = 0x7ffffff0;8956- else pair_max *= 2;8957- // parse8958- for(;;) {8959- int s=i; // first whitespace char; last nonwhite+18960- int w; // word start8961- // accept whitespace8962- while (isspace(str[i])) {8963- if (str[i] == '\n' || str[i] == '\r') {8964- if (str[i] + str[i+1] == '\n' + '\r') ++i;8965- if (n >= pair_max) return -1;8966- if (pairs) pairs[n] = start, pairs[n+1] = s-start;8967- n += 2;8968- nonwhite=0;8969- start = i+1;8970- s = start;8971- }8972- ++i;8973- }8974- if (i >= start+count) {8975- // we've gone off the end using whitespace8976- if (nonwhite) {8977- if (n >= pair_max) return -1;8978- if (pairs) pairs[n] = start, pairs[n+1] = s-start;8979- n += 2;8980- start = s = i;8981- nonwhite=0;8982- } else {8983- // output all the whitespace8984- while (i >= start+count) {8985- if (n >= pair_max) return -1;8986- if (pairs) pairs[n] = start, pairs[n+1] = count;8987- n += 2;8988- start += count;8989- }8990- s = start;8991- }8992- }8993-8994- if (str[i] == 0) break;8995- // now scan out a word and see if it fits8996- w = i;8997- while (str[i] && !isspace(str[i])) {8998- ++i;8999- }9000- // wrapped?9001- if (i > start + count) {9002- // huge?9003- if (i-s <= count) {9004- if (n >= pair_max) return -1;9005- if (pairs) pairs[n] = start, pairs[n+1] = s-start;9006- n += 2;9007- start = w;9008- } else {9009- // This word is longer than one line. If we wrap it onto N lines9010- // there are leftover chars. do those chars fit on the cur line?9011- // But if we have leading whitespace, we force it to start here.9012- if ((w-start) + ((i-w) % count) <= count || !nonwhite) {9013- // output a full line9014- if (n >= pair_max) return -1;9015- if (pairs) pairs[n] = start, pairs[n+1] = count;9016- n += 2;9017- start += count;9018- w = start;9019- } else {9020- // output a partial line, trimming trailing whitespace9021- if (s != start) {9022- if (n >= pair_max) return -1;9023- if (pairs) pairs[n] = start, pairs[n+1] = s-start;9024- n += 2;9025- start = w;9026- }9027- }9028- // now output full lines as needed9029- while (start + count <= i) {9030- if (n >= pair_max) return -1;9031- if (pairs) pairs[n] = start, pairs[n+1] = count;9032- n += 2;9033- start += count;9034- }9035- }9036- }9037- nonwhite=1;9038- }9039- if (start < i) {9040- if (n >= pair_max) return -1;9041- if (pairs) pairs[n] = start, pairs[n+1] = i-start;9042- n += 2;9043- }9044- return n>>1;9045-}9046-9047-int *stb_wordwrapalloc(int count, char *str)9048-{9049- int n = stb_wordwrap(NULL,0,count,str);9050- int *z = NULL;9051- stb_arr_setlen(z, n*2);9052- stb_wordwrap(z, n, count, str);9053- return z;9054-}9055-#endif9056-9057-9058-//////////////////////////////////////////////////////////////////////////////9059-//9060-// stb_match: wildcards and regexping9061-//9062-9063-STB_EXTERN int stb_wildmatch (char *expr, char *candidate);9064-STB_EXTERN int stb_wildmatchi(char *expr, char *candidate);9065-STB_EXTERN int stb_wildfind (char *expr, char *candidate);9066-STB_EXTERN int stb_wildfindi (char *expr, char *candidate);9067-9068-STB_EXTERN int stb_regex(char *regex, char *candidate);9069-9070-typedef struct stb_matcher stb_matcher;9071-9072-STB_EXTERN stb_matcher *stb_regex_matcher(char *regex);9073-STB_EXTERN int stb_matcher_match(stb_matcher *m, char *str);9074-STB_EXTERN int stb_matcher_find(stb_matcher *m, char *str);9075-STB_EXTERN void stb_matcher_free(stb_matcher *f);9076-9077-STB_EXTERN stb_matcher *stb_lex_matcher(void);9078-STB_EXTERN int stb_lex_item(stb_matcher *m, const char *str, int result);9079-STB_EXTERN int stb_lex_item_wild(stb_matcher *matcher, const char *regex, int result);9080-STB_EXTERN int stb_lex(stb_matcher *m, char *str, int *len);9081-9082-9083-9084-#ifdef STB_DEFINE9085-9086-static int stb__match_qstring(char *candidate, char *qstring, int qlen, int insensitive)9087-{9088- int i;9089- if (insensitive) {9090- for (i=0; i < qlen; ++i)9091- if (qstring[i] == '?') {9092- if (!candidate[i]) return 0;9093- } else9094- if (tolower(qstring[i]) != tolower(candidate[i]))9095- return 0;9096- } else {9097- for (i=0; i < qlen; ++i)9098- if (qstring[i] == '?') {9099- if (!candidate[i]) return 0;9100- } else9101- if (qstring[i] != candidate[i])9102- return 0;9103- }9104- return 1;9105-}9106-9107-static int stb__find_qstring(char *candidate, char *qstring, int qlen, int insensitive)9108-{9109- char c;9110-9111- int offset=0;9112- while (*qstring == '?') {9113- ++qstring;9114- --qlen;9115- ++candidate;9116- if (qlen == 0) return 0;9117- if (*candidate == 0) return -1;9118- }9119-9120- c = *qstring++;9121- --qlen;9122- if (insensitive) c = tolower(c);9123-9124- while (candidate[offset]) {9125- if (c == (insensitive ? tolower(candidate[offset]) : candidate[offset]))9126- if (stb__match_qstring(candidate+offset+1, qstring, qlen, insensitive))9127- return offset;9128- ++offset;9129- }9130-9131- return -1;9132-}9133-9134-int stb__wildmatch_raw2(char *expr, char *candidate, int search, int insensitive)9135-{9136- int where=0;9137- int start = -1;9138-9139- if (!search) {9140- // parse to first '*'9141- if (*expr != '*')9142- start = 0;9143- while (*expr != '*') {9144- if (!*expr)9145- return *candidate == 0 ? 0 : -1;9146- if (*expr == '?') {9147- if (!*candidate) return -1;9148- } else {9149- if (insensitive) {9150- if (tolower(*candidate) != tolower(*expr))9151- return -1;9152- } else9153- if (*candidate != *expr)9154- return -1;9155- }9156- ++candidate, ++expr, ++where;9157- }9158- } else {9159- // 0-length search string9160- if (!*expr)9161- return 0;9162- }9163-9164- assert(search || *expr == '*');9165- if (!search)9166- ++expr;9167-9168- // implicit '*' at this point9169-9170- while (*expr) {9171- int o=0;9172- // combine redundant * characters9173- while (expr[0] == '*') ++expr;9174-9175- // ok, at this point, expr[-1] == '*',9176- // and expr[0] != '*'9177-9178- if (!expr[0]) return start >= 0 ? start : 0;9179-9180- // now find next '*'9181- o = 0;9182- while (expr[o] != '*') {9183- if (expr[o] == 0)9184- break;9185- ++o;9186- }9187- // if no '*', scan to end, then match at end9188- if (expr[o] == 0 && !search) {9189- int z;9190- for (z=0; z < o; ++z)9191- if (candidate[z] == 0)9192- return -1;9193- while (candidate[z])9194- ++z;9195- // ok, now check if they match9196- if (stb__match_qstring(candidate+z-o, expr, o, insensitive))9197- return start >= 0 ? start : 0;9198- return -1;9199- } else {9200- // if yes '*', then do stb__find_qmatch on the intervening chars9201- int n = stb__find_qstring(candidate, expr, o, insensitive);9202- if (n < 0)9203- return -1;9204- if (start < 0)9205- start = where + n;9206- expr += o;9207- candidate += n+o;9208- }9209-9210- if (*expr == 0) {9211- assert(search);9212- return start;9213- }9214-9215- assert(*expr == '*');9216- ++expr;9217- }9218-9219- return start >= 0 ? start : 0;9220-}9221-9222-int stb__wildmatch_raw(char *expr, char *candidate, int search, int insensitive)9223-{9224- char buffer[256];9225- // handle multiple search strings9226- char *s = strchr(expr, ';');9227- char *last = expr;9228- while (s) {9229- int z;9230- // need to allow for non-writeable strings... assume they're small9231- if (s - last < 256) {9232- stb_strncpy(buffer, last, (int) (s-last+1));9233- z = stb__wildmatch_raw2(buffer, candidate, search, insensitive);9234- } else {9235- *s = 0;9236- z = stb__wildmatch_raw2(last, candidate, search, insensitive);9237- *s = ';';9238- }9239- if (z >= 0) return z;9240- last = s+1;9241- s = strchr(last, ';');9242- }9243- return stb__wildmatch_raw2(last, candidate, search, insensitive);9244-}9245-9246-int stb_wildmatch(char *expr, char *candidate)9247-{9248- return stb__wildmatch_raw(expr, candidate, 0,0) >= 0;9249-}9250-9251-int stb_wildmatchi(char *expr, char *candidate)9252-{9253- return stb__wildmatch_raw(expr, candidate, 0,1) >= 0;9254-}9255-9256-int stb_wildfind(char *expr, char *candidate)9257-{9258- return stb__wildmatch_raw(expr, candidate, 1,0);9259-}9260-9261-int stb_wildfindi(char *expr, char *candidate)9262-{9263- return stb__wildmatch_raw(expr, candidate, 1,1);9264-}9265-9266-typedef struct9267-{9268- stb_int16 transition[256];9269-} stb_dfa;9270-9271-// an NFA node represents a state you're in; it then has9272-// an arbitrary number of edges dangling off of it9273-// note this isn't utf8-y9274-typedef struct9275-{9276- stb_int16 match; // character/set to match9277- stb_uint16 node; // output node to go to9278-} stb_nfa_edge;9279-9280-typedef struct9281-{9282- stb_int16 goal; // does reaching this win the prize?9283- stb_uint8 active; // is this in the active list9284- stb_nfa_edge *out;9285- stb_uint16 *eps; // list of epsilon closures9286-} stb_nfa_node;9287-9288-#define STB__DFA_UNDEF -19289-#define STB__DFA_GOAL -29290-#define STB__DFA_END -39291-#define STB__DFA_MGOAL -49292-#define STB__DFA_VALID 09293-9294-#define STB__NFA_STOP_GOAL -19295-9296-// compiled regexp9297-struct stb_matcher9298-{9299- stb_uint16 start_node;9300- stb_int16 dfa_start;9301- stb_uint32 *charset;9302- int num_charset;9303- int match_start;9304- stb_nfa_node *nodes;9305- int does_lex;9306-9307- // dfa matcher9308- stb_dfa * dfa;9309- stb_uint32 * dfa_mapping;9310- stb_int16 * dfa_result;9311- int num_words_per_dfa;9312-};9313-9314-static int stb__add_node(stb_matcher *matcher)9315-{9316- stb_nfa_node z;9317- z.active = 0;9318- z.eps = 0;9319- z.goal = 0;9320- z.out = 0;9321- stb_arr_push(matcher->nodes, z);9322- return stb_arr_len(matcher->nodes)-1;9323-}9324-9325-static void stb__add_epsilon(stb_matcher *matcher, int from, int to)9326-{9327- assert(from != to);9328- if (matcher->nodes[from].eps == NULL)9329- stb_arr_malloc((void **) &matcher->nodes[from].eps, matcher);9330- stb_arr_push(matcher->nodes[from].eps, to);9331-}9332-9333-static void stb__add_edge(stb_matcher *matcher, int from, int to, int type)9334-{9335- stb_nfa_edge z = { (stb_int16)type, (stb_uint16)to };9336- if (matcher->nodes[from].out == NULL)9337- stb_arr_malloc((void **) &matcher->nodes[from].out, matcher);9338- stb_arr_push(matcher->nodes[from].out, z);9339-}9340-9341-static char *stb__reg_parse_alt(stb_matcher *m, int s, char *r, stb_uint16 *e);9342-static char *stb__reg_parse(stb_matcher *matcher, int start, char *regex, stb_uint16 *end)9343-{9344- int n;9345- int last_start = -1;9346- stb_uint16 last_end = start;9347-9348- while (*regex) {9349- switch (*regex) {9350- case '(':9351- last_start = last_end;9352- regex = stb__reg_parse_alt(matcher, last_end, regex+1, &last_end);9353- if (regex == NULL || *regex != ')')9354- return NULL;9355- ++regex;9356- break;9357-9358- case '|':9359- case ')':9360- *end = last_end;9361- return regex;9362-9363- case '?':9364- if (last_start < 0) return NULL;9365- stb__add_epsilon(matcher, last_start, last_end);9366- ++regex;9367- break;9368-9369- case '*':9370- if (last_start < 0) return NULL;9371- stb__add_epsilon(matcher, last_start, last_end);9372-9373- // fall through9374-9375- case '+':9376- if (last_start < 0) return NULL;9377- stb__add_epsilon(matcher, last_end, last_start);9378- // prevent links back to last_end from chaining to last_start9379- n = stb__add_node(matcher);9380- stb__add_epsilon(matcher, last_end, n);9381- last_end = n;9382- ++regex;9383- break;9384-9385- case '{': // not supported!9386- // @TODO: given {n,m}, clone last_start to last_end m times,9387- // and include epsilons from start to first m-n blocks9388- return NULL;9389-9390- case '\\':9391- ++regex;9392- if (!*regex) return NULL;9393-9394- // fallthrough9395- default: // match exactly this character9396- n = stb__add_node(matcher);9397- stb__add_edge(matcher, last_end, n, *regex);9398- last_start = last_end;9399- last_end = n;9400- ++regex;9401- break;9402-9403- case '$':9404- n = stb__add_node(matcher);9405- stb__add_edge(matcher, last_end, n, '\n');9406- last_start = last_end;9407- last_end = n;9408- ++regex;9409- break;9410-9411- case '.':9412- n = stb__add_node(matcher);9413- stb__add_edge(matcher, last_end, n, -1);9414- last_start = last_end;9415- last_end = n;9416- ++regex;9417- break;9418-9419- case '[': {9420- stb_uint8 flags[256];9421- int invert = 0,z;9422- ++regex;9423- if (matcher->num_charset == 0) {9424- matcher->charset = (stb_uint *) stb_malloc(matcher, sizeof(*matcher->charset) * 256);9425- memset(matcher->charset, 0, sizeof(*matcher->charset) * 256);9426- }9427-9428- memset(flags,0,sizeof(flags));9429-9430- // leading ^ is special9431- if (*regex == '^')9432- ++regex, invert = 1;9433-9434- // leading ] is special9435- if (*regex == ']') {9436- flags[(int) ']'] = 1;9437- ++regex;9438- }9439- while (*regex != ']') {9440- stb_uint a;9441- if (!*regex) return NULL;9442- a = *regex++;9443- if (regex[0] == '-' && regex[1] != ']') {9444- stb_uint i,b = regex[1];9445- regex += 2;9446- if (b == 0) return NULL;9447- if (a > b) return NULL;9448- for (i=a; i <= b; ++i)9449- flags[i] = 1;9450- } else9451- flags[a] = 1;9452- }9453- ++regex;9454- if (invert) {9455- int i;9456- for (i=0; i < 256; ++i)9457- flags[i] = 1-flags[i];9458- }9459-9460- // now check if any existing charset matches9461- for (z=0; z < matcher->num_charset; ++z) {9462- int i, k[2] = { 0, 1 << z};9463- for (i=0; i < 256; ++i) {9464- unsigned int f = k[flags[i]];9465- if ((matcher->charset[i] & k[1]) != f)9466- break;9467- }9468- if (i == 256) break;9469- }9470-9471- if (z == matcher->num_charset) {9472- int i;9473- ++matcher->num_charset;9474- if (matcher->num_charset > 32) {9475- assert(0); /* NOTREACHED */9476- return NULL; // too many charsets, oops9477- }9478- for (i=0; i < 256; ++i)9479- if (flags[i])9480- matcher->charset[i] |= (1 << z);9481- }9482-9483- n = stb__add_node(matcher);9484- stb__add_edge(matcher, last_end, n, -2 - z);9485- last_start = last_end;9486- last_end = n;9487- break;9488- }9489- }9490- }9491- *end = last_end;9492- return regex;9493-}9494-9495-static char *stb__reg_parse_alt(stb_matcher *matcher, int start, char *regex, stb_uint16 *end)9496-{9497- stb_uint16 last_end = start;9498- stb_uint16 main_end;9499-9500- int head, tail;9501-9502- head = stb__add_node(matcher);9503- stb__add_epsilon(matcher, start, head);9504-9505- regex = stb__reg_parse(matcher, head, regex, &last_end);9506- if (regex == NULL) return NULL;9507- if (*regex == 0 || *regex == ')') {9508- *end = last_end;9509- return regex;9510- }9511-9512- main_end = last_end;9513- tail = stb__add_node(matcher);9514-9515- stb__add_epsilon(matcher, last_end, tail);9516-9517- // start alternatives from the same starting node; use epsilon9518- // transitions to combine their endings9519- while(*regex && *regex != ')') {9520- assert(*regex == '|');9521- head = stb__add_node(matcher);9522- stb__add_epsilon(matcher, start, head);9523- regex = stb__reg_parse(matcher, head, regex+1, &last_end);9524- if (regex == NULL)9525- return NULL;9526- stb__add_epsilon(matcher, last_end, tail);9527- }9528-9529- *end = tail;9530- return regex;9531-}9532-9533-static char *stb__wild_parse(stb_matcher *matcher, int start, char *str, stb_uint16 *end)9534-{9535- int n;9536- stb_uint16 last_end;9537-9538- last_end = stb__add_node(matcher);9539- stb__add_epsilon(matcher, start, last_end);9540-9541- while (*str) {9542- switch (*str) {9543- // fallthrough9544- default: // match exactly this character9545- n = stb__add_node(matcher);9546- if (toupper(*str) == tolower(*str)) {9547- stb__add_edge(matcher, last_end, n, *str);9548- } else {9549- stb__add_edge(matcher, last_end, n, tolower(*str));9550- stb__add_edge(matcher, last_end, n, toupper(*str));9551- }9552- last_end = n;9553- ++str;9554- break;9555-9556- case '?':9557- n = stb__add_node(matcher);9558- stb__add_edge(matcher, last_end, n, -1);9559- last_end = n;9560- ++str;9561- break;9562-9563- case '*':9564- n = stb__add_node(matcher);9565- stb__add_edge(matcher, last_end, n, -1);9566- stb__add_epsilon(matcher, last_end, n);9567- stb__add_epsilon(matcher, n, last_end);9568- last_end = n;9569- ++str;9570- break;9571- }9572- }9573-9574- // now require end of string to match9575- n = stb__add_node(matcher);9576- stb__add_edge(matcher, last_end, n, 0);9577- last_end = n;9578-9579- *end = last_end;9580- return str;9581-}9582-9583-static int stb__opt(stb_matcher *m, int n)9584-{9585- for(;;) {9586- stb_nfa_node *p = &m->nodes[n];9587- if (p->goal) return n;9588- if (stb_arr_len(p->out)) return n;9589- if (stb_arr_len(p->eps) != 1) return n;9590- n = p->eps[0];9591- }9592-}9593-9594-static void stb__optimize(stb_matcher *m)9595-{9596- // if the target of any edge is a node with exactly9597- // one out-epsilon, shorten it9598- int i,j;9599- for (i=0; i < stb_arr_len(m->nodes); ++i) {9600- stb_nfa_node *p = &m->nodes[i];9601- for (j=0; j < stb_arr_len(p->out); ++j)9602- p->out[j].node = stb__opt(m,p->out[j].node);9603- for (j=0; j < stb_arr_len(p->eps); ++j)9604- p->eps[j] = stb__opt(m,p->eps[j] );9605- }9606- m->start_node = stb__opt(m,m->start_node);9607-}9608-9609-void stb_matcher_free(stb_matcher *f)9610-{9611- stb_free(f);9612-}9613-9614-static stb_matcher *stb__alloc_matcher(void)9615-{9616- stb_matcher *matcher = (stb_matcher *) stb_malloc(0,sizeof(*matcher));9617-9618- matcher->start_node = 0;9619- stb_arr_malloc((void **) &matcher->nodes, matcher);9620- matcher->num_charset = 0;9621- matcher->match_start = 0;9622- matcher->does_lex = 0;9623-9624- matcher->dfa_start = STB__DFA_UNDEF;9625- stb_arr_malloc((void **) &matcher->dfa, matcher);9626- stb_arr_malloc((void **) &matcher->dfa_mapping, matcher);9627- stb_arr_malloc((void **) &matcher->dfa_result, matcher);9628-9629- stb__add_node(matcher);9630-9631- return matcher;9632-}9633-9634-static void stb__lex_reset(stb_matcher *matcher)9635-{9636- // flush cached dfa data9637- stb_arr_setlen(matcher->dfa, 0);9638- stb_arr_setlen(matcher->dfa_mapping, 0);9639- stb_arr_setlen(matcher->dfa_result, 0);9640- matcher->dfa_start = STB__DFA_UNDEF;9641-}9642-9643-stb_matcher *stb_regex_matcher(char *regex)9644-{9645- char *z;9646- stb_uint16 end;9647- stb_matcher *matcher = stb__alloc_matcher();9648- if (*regex == '^') {9649- matcher->match_start = 1;9650- ++regex;9651- }9652-9653- z = stb__reg_parse_alt(matcher, matcher->start_node, regex, &end);9654-9655- if (!z || *z) {9656- stb_free(matcher);9657- return NULL;9658- }9659-9660- ((matcher->nodes)[(int) end]).goal = STB__NFA_STOP_GOAL;9661-9662- return matcher;9663-}9664-9665-stb_matcher *stb_lex_matcher(void)9666-{9667- stb_matcher *matcher = stb__alloc_matcher();9668-9669- matcher->match_start = 1;9670- matcher->does_lex = 1;9671-9672- return matcher;9673-}9674-9675-int stb_lex_item(stb_matcher *matcher, const char *regex, int result)9676-{9677- char *z;9678- stb_uint16 end;9679-9680- z = stb__reg_parse_alt(matcher, matcher->start_node, (char*) regex, &end);9681-9682- if (z == NULL)9683- return 0;9684-9685- stb__lex_reset(matcher);9686-9687- matcher->nodes[(int) end].goal = result;9688- return 1;9689-}9690-9691-int stb_lex_item_wild(stb_matcher *matcher, const char *regex, int result)9692-{9693- char *z;9694- stb_uint16 end;9695-9696- z = stb__wild_parse(matcher, matcher->start_node, (char*) regex, &end);9697-9698- if (z == NULL)9699- return 0;9700-9701- stb__lex_reset(matcher);9702-9703- matcher->nodes[(int) end].goal = result;9704- return 1;9705-}9706-9707-static void stb__clear(stb_matcher *m, stb_uint16 *list)9708-{9709- int i;9710- for (i=0; i < stb_arr_len(list); ++i)9711- m->nodes[(int) list[i]].active = 0;9712-}9713-9714-static int stb__clear_goalcheck(stb_matcher *m, stb_uint16 *list)9715-{9716- int i, t=0;9717- for (i=0; i < stb_arr_len(list); ++i) {9718- t += m->nodes[(int) list[i]].goal;9719- m->nodes[(int) list[i]].active = 0;9720- }9721- return t;9722-}9723-9724-static stb_uint16 * stb__add_if_inactive(stb_matcher *m, stb_uint16 *list, int n)9725-{9726- if (!m->nodes[n].active) {9727- stb_arr_push(list, n);9728- m->nodes[n].active = 1;9729- }9730- return list;9731-}9732-9733-static stb_uint16 * stb__eps_closure(stb_matcher *m, stb_uint16 *list)9734-{9735- int i,n = stb_arr_len(list);9736-9737- for(i=0; i < n; ++i) {9738- stb_uint16 *e = m->nodes[(int) list[i]].eps;9739- if (e) {9740- int j,k = stb_arr_len(e);9741- for (j=0; j < k; ++j)9742- list = stb__add_if_inactive(m, list, e[j]);9743- n = stb_arr_len(list);9744- }9745- }9746-9747- return list;9748-}9749-9750-int stb_matcher_match(stb_matcher *m, char *str)9751-{9752- int result = 0;9753- int i,j,y,z;9754- stb_uint16 *previous = NULL;9755- stb_uint16 *current = NULL;9756- stb_uint16 *temp;9757-9758- stb_arr_setsize(previous, 4);9759- stb_arr_setsize(current, 4);9760-9761- previous = stb__add_if_inactive(m, previous, m->start_node);9762- previous = stb__eps_closure(m,previous);9763- stb__clear(m, previous);9764-9765- while (*str && stb_arr_len(previous)) {9766- y = stb_arr_len(previous);9767- for (i=0; i < y; ++i) {9768- stb_nfa_node *n = &m->nodes[(int) previous[i]];9769- z = stb_arr_len(n->out);9770- for (j=0; j < z; ++j) {9771- if (n->out[j].match >= 0) {9772- if (n->out[j].match == *str)9773- current = stb__add_if_inactive(m, current, n->out[j].node);9774- } else if (n->out[j].match == -1) {9775- if (*str != '\n')9776- current = stb__add_if_inactive(m, current, n->out[j].node);9777- } else if (n->out[j].match < -1) {9778- int z = -n->out[j].match - 2;9779- if (m->charset[(stb_uint8) *str] & (1 << z))9780- current = stb__add_if_inactive(m, current, n->out[j].node);9781- }9782- }9783- }9784- stb_arr_setlen(previous, 0);9785-9786- temp = previous;9787- previous = current;9788- current = temp;9789-9790- previous = stb__eps_closure(m,previous);9791- stb__clear(m, previous);9792-9793- ++str;9794- }9795-9796- // transition to pick up a '$' at the end9797- y = stb_arr_len(previous);9798- for (i=0; i < y; ++i)9799- m->nodes[(int) previous[i]].active = 1;9800-9801- for (i=0; i < y; ++i) {9802- stb_nfa_node *n = &m->nodes[(int) previous[i]];9803- z = stb_arr_len(n->out);9804- for (j=0; j < z; ++j) {9805- if (n->out[j].match == '\n')9806- current = stb__add_if_inactive(m, current, n->out[j].node);9807- }9808- }9809-9810- previous = stb__eps_closure(m,previous);9811- stb__clear(m, previous);9812-9813- y = stb_arr_len(previous);9814- for (i=0; i < y; ++i)9815- if (m->nodes[(int) previous[i]].goal)9816- result = 1;9817-9818- stb_arr_free(previous);9819- stb_arr_free(current);9820-9821- return result && *str == 0;9822-}9823-9824-stb_int16 stb__get_dfa_node(stb_matcher *m, stb_uint16 *list)9825-{9826- stb_uint16 node;9827- stb_uint32 data[8], *state, *newstate;9828- int i,j,n;9829-9830- state = (stb_uint32 *) stb_temp(data, m->num_words_per_dfa * 4);9831- memset(state, 0, m->num_words_per_dfa*4);9832-9833- n = stb_arr_len(list);9834- for (i=0; i < n; ++i) {9835- int x = list[i];9836- state[x >> 5] |= 1 << (x & 31);9837- }9838-9839- // @TODO use a hash table9840- n = stb_arr_len(m->dfa_mapping);9841- i=j=0;9842- for(; j < n; ++i, j += m->num_words_per_dfa) {9843- // @TODO special case for <= 329844- if (!memcmp(state, m->dfa_mapping + j, m->num_words_per_dfa*4)) {9845- node = i;9846- goto done;9847- }9848- }9849-9850- assert(stb_arr_len(m->dfa) == i);9851- node = i;9852-9853- newstate = stb_arr_addn(m->dfa_mapping, m->num_words_per_dfa);9854- memcpy(newstate, state, m->num_words_per_dfa*4);9855-9856- // set all transitions to 'unknown'9857- stb_arr_add(m->dfa);9858- memset(m->dfa[i].transition, -1, sizeof(m->dfa[i].transition));9859-9860- if (m->does_lex) {9861- int result = -1;9862- n = stb_arr_len(list);9863- for (i=0; i < n; ++i) {9864- if (m->nodes[(int) list[i]].goal > result)9865- result = m->nodes[(int) list[i]].goal;9866- }9867-9868- stb_arr_push(m->dfa_result, result);9869- }9870-9871-done:9872- stb_tempfree(data, state);9873- return node;9874-}9875-9876-static int stb__matcher_dfa(stb_matcher *m, char *str_c, int *len)9877-{9878- stb_uint8 *str = (stb_uint8 *) str_c;9879- stb_int16 node,prevnode;9880- stb_dfa *trans;9881- int match_length = 0;9882- stb_int16 match_result=0;9883-9884- if (m->dfa_start == STB__DFA_UNDEF) {9885- stb_uint16 *list;9886-9887- m->num_words_per_dfa = (stb_arr_len(m->nodes)+31) >> 5;9888- stb__optimize(m);9889-9890- list = stb__add_if_inactive(m, NULL, m->start_node);9891- list = stb__eps_closure(m,list);9892- if (m->does_lex) {9893- m->dfa_start = stb__get_dfa_node(m,list);9894- stb__clear(m, list);9895- // DON'T allow start state to be a goal state!9896- // this allows people to specify regexes that can match 09897- // characters without them actually matching (also we don't9898- // check _before_ advancing anyway9899- if (m->dfa_start <= STB__DFA_MGOAL)9900- m->dfa_start = -(m->dfa_start - STB__DFA_MGOAL);9901- } else {9902- if (stb__clear_goalcheck(m, list))9903- m->dfa_start = STB__DFA_GOAL;9904- else9905- m->dfa_start = stb__get_dfa_node(m,list);9906- }9907- stb_arr_free(list);9908- }9909-9910- prevnode = STB__DFA_UNDEF;9911- node = m->dfa_start;9912- trans = m->dfa;9913-9914- if (m->dfa_start == STB__DFA_GOAL)9915- return 1;9916-9917- for(;;) {9918- assert(node >= STB__DFA_VALID);9919-9920- // fast inner DFA loop; especially if STB__DFA_VALID is 09921-9922- do {9923- prevnode = node;9924- node = trans[node].transition[*str++];9925- } while (node >= STB__DFA_VALID);9926-9927- assert(node >= STB__DFA_MGOAL - stb_arr_len(m->dfa));9928- assert(node < stb_arr_len(m->dfa));9929-9930- // special case for lex: need _longest_ match, so notice goal9931- // state without stopping9932- if (node <= STB__DFA_MGOAL) {9933- match_length = (int) (str - (stb_uint8 *) str_c);9934- node = -(node - STB__DFA_MGOAL);9935- match_result = node;9936- continue;9937- }9938-9939- // slow NFA->DFA conversion9940-9941- // or we hit the goal or the end of the string, but those9942- // can only happen once per search...9943-9944- if (node == STB__DFA_UNDEF) {9945- // build a list -- @TODO special case <= 32 states9946- // heck, use a more compact data structure for <= 16 and <= 8 ?!9947-9948- // @TODO keep states/newstates around instead of reallocating them9949- stb_uint16 *states = NULL;9950- stb_uint16 *newstates = NULL;9951- int i,j,y,z;9952- stb_uint32 *flags = &m->dfa_mapping[prevnode * m->num_words_per_dfa];9953- assert(prevnode != STB__DFA_UNDEF);9954- stb_arr_setsize(states, 4);9955- stb_arr_setsize(newstates,4);9956- for (j=0; j < m->num_words_per_dfa; ++j) {9957- for (i=0; i < 32; ++i) {9958- if (*flags & (1 << i))9959- stb_arr_push(states, j*32+i);9960- }9961- ++flags;9962- }9963- // states is now the states we were in in the previous node;9964- // so now we can compute what node it transitions to on str[-1]9965-9966- y = stb_arr_len(states);9967- for (i=0; i < y; ++i) {9968- stb_nfa_node *n = &m->nodes[(int) states[i]];9969- z = stb_arr_len(n->out);9970- for (j=0; j < z; ++j) {9971- if (n->out[j].match >= 0) {9972- if (n->out[j].match == str[-1] || (str[-1] == 0 && n->out[j].match == '\n'))9973- newstates = stb__add_if_inactive(m, newstates, n->out[j].node);9974- } else if (n->out[j].match == -1) {9975- if (str[-1] != '\n' && str[-1])9976- newstates = stb__add_if_inactive(m, newstates, n->out[j].node);9977- } else if (n->out[j].match < -1) {9978- int z = -n->out[j].match - 2;9979- if (m->charset[str[-1]] & (1 << z))9980- newstates = stb__add_if_inactive(m, newstates, n->out[j].node);9981- }9982- }9983- }9984- // AND add in the start state!9985- if (!m->match_start || (str[-1] == '\n' && !m->does_lex))9986- newstates = stb__add_if_inactive(m, newstates, m->start_node);9987- // AND epsilon close it9988- newstates = stb__eps_closure(m, newstates);9989- // if it's a goal state, then that's all there is to it9990- if (stb__clear_goalcheck(m, newstates)) {9991- if (m->does_lex) {9992- match_length = (int) (str - (stb_uint8 *) str_c);9993- node = stb__get_dfa_node(m,newstates);9994- match_result = node;9995- node = -node + STB__DFA_MGOAL;9996- trans = m->dfa; // could have gotten realloc()ed9997- } else9998- node = STB__DFA_GOAL;9999- } else if (str[-1] == 0 || stb_arr_len(newstates) == 0) {10000- node = STB__DFA_END;10001- } else {10002- node = stb__get_dfa_node(m,newstates);10003- trans = m->dfa; // could have gotten realloc()ed10004- }10005- trans[prevnode].transition[str[-1]] = node;10006- if (node <= STB__DFA_MGOAL)10007- node = -(node - STB__DFA_MGOAL);10008- stb_arr_free(newstates);10009- stb_arr_free(states);10010- }10011-10012- if (node == STB__DFA_GOAL) {10013- return 1;10014- }10015- if (node == STB__DFA_END) {10016- if (m->does_lex) {10017- if (match_result) {10018- if (len) *len = match_length;10019- return m->dfa_result[(int) match_result];10020- }10021- }10022- return 0;10023- }10024-10025- assert(node != STB__DFA_UNDEF);10026- }10027-}10028-10029-int stb_matcher_find(stb_matcher *m, char *str)10030-{10031- assert(m->does_lex == 0);10032- return stb__matcher_dfa(m, str, NULL);10033-}10034-10035-int stb_lex(stb_matcher *m, char *str, int *len)10036-{10037- assert(m->does_lex);10038- return stb__matcher_dfa(m, str, len);10039-}10040-10041-#ifdef STB_PERFECT_HASH10042-int stb_regex(char *regex, char *str)10043-{10044- static stb_perfect p;10045- static stb_matcher ** matchers;10046- static char ** regexps;10047- static char ** regexp_cache;10048- static unsigned short *mapping;10049- int z = stb_perfect_hash(&p, (int)(size_t) regex);10050- if (z >= 0) {10051- if (strcmp(regex, regexp_cache[(int) mapping[z]])) {10052- int i = mapping[z];10053- stb_matcher_free(matchers[i]);10054- free(regexp_cache[i]);10055- regexps[i] = regex;10056- regexp_cache[i] = stb_p_strdup(regex);10057- matchers[i] = stb_regex_matcher(regex);10058- }10059- } else {10060- int i,n;10061- if (regex == NULL) {10062- for (i=0; i < stb_arr_len(matchers); ++i) {10063- stb_matcher_free(matchers[i]);10064- free(regexp_cache[i]);10065- }10066- stb_arr_free(matchers);10067- stb_arr_free(regexps);10068- stb_arr_free(regexp_cache);10069- stb_perfect_destroy(&p);10070- free(mapping); mapping = NULL;10071- return -1;10072- }10073- stb_arr_push(regexps, regex);10074- stb_arr_push(regexp_cache, stb_p_strdup(regex));10075- stb_arr_push(matchers, stb_regex_matcher(regex));10076- stb_perfect_destroy(&p);10077- n = stb_perfect_create(&p, (unsigned int *) (char **) regexps, stb_arr_len(regexps));10078- mapping = (unsigned short *) realloc(mapping, n * sizeof(*mapping));10079- for (i=0; i < stb_arr_len(regexps); ++i)10080- mapping[stb_perfect_hash(&p, (int)(size_t) regexps[i])] = i;10081- z = stb_perfect_hash(&p, (int)(size_t) regex);10082- }10083- return stb_matcher_find(matchers[(int) mapping[z]], str);10084-}10085-#endif10086-#endif // STB_DEFINE10087-10088-10089-#if 010090-//////////////////////////////////////////////////////////////////////////////10091-//10092-// C source-code introspection10093-//10094-10095-// runtime structure10096-typedef struct10097-{10098- char *name;10099- char *type; // base type10100- char *comment; // content of comment field10101- int size; // size of base type10102- int offset; // field offset10103- int arrcount[8]; // array sizes; -1 = pointer indirection; 0 = end of list10104-} stb_info_field;10105-10106-typedef struct10107-{10108- char *structname;10109- int size;10110- int num_fields;10111- stb_info_field *fields;10112-} stb_info_struct;10113-10114-extern stb_info_struct stb_introspect_output[];10115-10116-//10117-10118-STB_EXTERN void stb_introspect_precompiled(stb_info_struct *compiled);10119-STB_EXTERN void stb__introspect(char *path, char *file);10120-10121-#define stb_introspect_ship() stb__introspect(NULL, NULL, stb__introspect_output)10122-10123-#ifdef STB_SHIP10124-#define stb_introspect() stb_introspect_ship()10125-#define stb_introspect_path(p) stb_introspect_ship()10126-#else10127-// bootstrapping: define stb_introspect() (or 'path') the first time10128-#define stb_introspect() stb__introspect(NULL, __FILE__, NULL)10129-#define stb_introspect_auto() stb__introspect(NULL, __FILE__, stb__introspect_output)10130-10131-#define stb_introspect_path(p) stb__introspect(p, __FILE__, NULL)10132-#define stb_introspect_path(p) stb__introspect(p, __FILE__, NULL)10133-#endif10134-10135-#ifdef STB_DEFINE10136-10137-#ifndef STB_INTROSPECT_CPP10138- #ifdef __cplusplus10139- #define STB_INTROSPECT_CPP 110140- #else10141- #define STB_INTROSPECT_CPP 010142- #endif10143-#endif10144-10145-void stb_introspect_precompiled(stb_info_struct *compiled)10146-{10147-10148-}10149-10150-10151-static void stb__introspect_filename(char *buffer, char *path)10152-{10153- #if STB_INTROSPECT_CPP10154- stb_p_sprintf(buffer stb_p_size(9999), "%s/stb_introspect.cpp", path);10155- #else10156- stb_p_sprintf(buffer stb_p_size(9999), "%s/stb_introspect.c", path);10157- #endif10158-}10159-10160-static void stb__introspect_compute(char *path, char *file)10161-{10162- int i;10163- char ** include_list = NULL;10164- char ** introspect_list = NULL;10165- FILE *f;10166- f = stb_p_fopen(file, "w");10167- if (!f) return;10168-10169- fputs("// if you get compiler errors, change the following 0 to a 1:\n", f);10170- fputs("#define STB_INTROSPECT_INVALID 0\n\n", f);10171- fputs("// this will force the code to compile, and force the introspector\n", f);10172- fputs("// to run and then exit, allowing you to recompile\n\n\n", f);10173- fputs("#include \"stb.h\"\n\n",f );10174- fputs("#if STB_INTROSPECT_INVALID\n", f);10175- fputs(" stb_info_struct stb__introspect_output[] = { (void *) 1 }\n", f);10176- fputs("#else\n\n", f);10177- for (i=0; i < stb_arr_len(include_list); ++i)10178- fprintf(f, " #include \"%s\"\n", include_list[i]);10179-10180- fputs(" stb_info_struct stb__introspect_output[] =\n{\n", f);10181- for (i=0; i < stb_arr_len(introspect_list); ++i)10182- fprintf(f, " stb_introspect_%s,\n", introspect_list[i]);10183- fputs(" };\n", f);10184- fputs("#endif\n", f);10185- fclose(f);10186-}10187-10188-static stb_info_struct *stb__introspect_info;10189-10190-#ifndef STB_SHIP10191-10192-#endif10193-10194-void stb__introspect(char *path, char *file, stb_info_struct *compiled)10195-{10196- static int first=1;10197- if (!first) return;10198- first=0;10199-10200- stb__introspect_info = compiled;10201-10202- #ifndef STB_SHIP10203- if (path || file) {10204- int bail_flag = compiled && compiled[0].structname == (void *) 1;10205- int needs_building = bail_flag;10206- struct stb__stat st;10207- char buffer[1024], buffer2[1024];10208- if (!path) {10209- stb_splitpath(buffer, file, STB_PATH);10210- path = buffer;10211- }10212- // bail if the source path doesn't exist10213- if (!stb_fexists(path)) return;10214-10215- stb__introspect_filename(buffer2, path);10216-10217- // get source/include files timestamps, compare to output-file timestamp;10218- // if mismatched, regenerate10219-10220- if (stb__stat(buffer2, &st))10221- needs_building = STB_TRUE;10222-10223- {10224- // find any file that contains an introspection command and is newer10225- // if needs_building is already true, we don't need to do this test,10226- // but we still need these arrays, so go ahead and get them10227- char **all[3];10228- all[0] = stb_readdir_files_mask(path, "*.h");10229- all[1] = stb_readdir_files_mask(path, "*.c");10230- all[2] = stb_readdir_files_mask(path, "*.cpp");10231- int i,j;10232- if (needs_building) {10233- for (j=0; j < 3; ++j) {10234- for (i=0; i < stb_arr_len(all[j]); ++i) {10235- struct stb__stat st2;10236- if (!stb__stat(all[j][i], &st2)) {10237- if (st.st_mtime < st2.st_mtime) {10238- char *z = stb_filec(all[j][i], NULL);10239- int found=STB_FALSE;10240- while (y) {10241- y = strstr(y, "//si");10242- if (y && isspace(y[4])) {10243- found = STB_TRUE;10244- break;10245- }10246- }10247- needs_building = STB_TRUE;10248- goto done;10249- }10250- }10251- }10252- }10253- done:;10254- }10255- char *z = stb_filec(all[i], NULL), *y = z;10256- int found=STB_FALSE;10257- while (y) {10258- y = strstr(y, "//si");10259- if (y && isspace(y[4])) {10260- found = STB_TRUE;10261- break;10262- }10263- }10264- if (found)10265- stb_arr_push(introspect_h, stb_p_strdup(all[i]));10266- free(z);10267- }10268- }10269- stb_readdir_free(all);10270- if (!needs_building) {10271- for (i=0; i < stb_arr_len(introspect_h); ++i) {10272- struct stb__stat st2;10273- if (!stb__stat(introspect_h[i], &st2))10274- if (st.st_mtime < st2.st_mtime)10275- needs_building = STB_TRUE;10276- }10277- }10278-10279- if (needs_building) {10280- stb__introspect_compute(path, buffer2);10281- }10282- }10283- }10284- #endif10285-}10286-#endif10287-#endif10288-10289-#ifdef STB_INTROSPECT10290-// compile-time code-generator10291-#define INTROSPECT(x) int main(int argc, char **argv) { stb__introspect(__FILE__); return 0; }10292-#define FILE(x)10293-10294-void stb__introspect(char *filename)10295-{10296- char *file = stb_file(filename, NULL);10297- char *s = file, *t, **p;10298- char *out_name = "stb_introspect.c";10299- char *out_path;10300- STB_ARR(char) filelist = NULL;10301- int i,n;10302- if (!file) stb_fatal("Couldn't open %s", filename);10303-10304- out_path = stb_splitpathdup(filename, STB_PATH);10305-10306- // search for the macros10307- while (*s) {10308- char buffer[256];10309- while (*s && !isupper(*s)) ++s;10310- s = stb_strtok_invert(buffer, s, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");10311- s = stb_skipwhite(s);10312- if (*s == '(') {10313- ++s;10314- t = strchr(s, ')');10315- if (t == NULL) stb_fatal("Error parsing %s", filename);10316-10317- }10318- }10319-}10320-10321-10322-10323-#endif10324-10325-10326-//////////////////////////////////////////////////////////////////////////////10327-//10328-// STB-C sliding-window dictionary compression10329-//10330-// This uses a DEFLATE-style sliding window, but no bitwise entropy.10331-// Everything is on byte boundaries, so you could then apply a byte-wise10332-// entropy code, though that's nowhere near as effective.10333-//10334-// An STB-C stream begins with a 16-byte header:10335-// 4 bytes: 0x57 0xBC 0x00 0x0010336-// 8 bytes: big-endian size of decompressed data, 64-bits10337-// 4 bytes: big-endian size of window (how far back decompressor may need)10338-//10339-// The following symbols appear in the stream (these were determined ad hoc,10340-// not by analysis):10341-//10342-// [dict] 00000100 yyyyyyyy yyyyyyyy yyyyyyyy xxxxxxxx xxxxxxxx10343-// [END] 00000101 11111010 cccccccc cccccccc cccccccc cccccccc10344-// [dict] 00000110 yyyyyyyy yyyyyyyy yyyyyyyy xxxxxxxx10345-// [literals] 00000111 zzzzzzzz zzzzzzzz10346-// [literals] 00001zzz zzzzzzzz10347-// [dict] 00010yyy yyyyyyyy yyyyyyyy xxxxxxxx xxxxxxxx10348-// [dict] 00011yyy yyyyyyyy yyyyyyyy xxxxxxxx10349-// [literals] 001zzzzz10350-// [dict] 01yyyyyy yyyyyyyy xxxxxxxx10351-// [dict] 1xxxxxxx yyyyyyyy10352-//10353-// xxxxxxxx: match length - 110354-// yyyyyyyy: backwards distance - 110355-// zzzzzzzz: num literals - 110356-// cccccccc: adler32 checksum of decompressed data10357-// (all big-endian)10358-10359-10360-STB_EXTERN stb_uint stb_decompress_length(stb_uchar *input);10361-STB_EXTERN stb_uint stb_decompress(stb_uchar *out,stb_uchar *in,stb_uint len);10362-STB_EXTERN stb_uint stb_compress (stb_uchar *out,stb_uchar *in,stb_uint len);10363-STB_EXTERN void stb_compress_window(int z);10364-STB_EXTERN void stb_compress_hashsize(unsigned int z);10365-10366-STB_EXTERN int stb_compress_tofile(char *filename, char *in, stb_uint len);10367-STB_EXTERN int stb_compress_intofile(FILE *f, char *input, stb_uint len);10368-STB_EXTERN char *stb_decompress_fromfile(char *filename, stb_uint *len);10369-10370-STB_EXTERN int stb_compress_stream_start(FILE *f);10371-STB_EXTERN void stb_compress_stream_end(int close);10372-STB_EXTERN void stb_write(char *data, int data_len);10373-10374-#ifdef STB_DEFINE10375-10376-stb_uint stb_decompress_length(stb_uchar *input)10377-{10378- return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11];10379-}10380-10381-//////////////////// decompressor ///////////////////////10382-10383-// simple implementation that just writes whole thing into big block10384-10385-static unsigned char *stb__barrier;10386-static unsigned char *stb__barrier2;10387-static unsigned char *stb__barrier3;10388-static unsigned char *stb__barrier4;10389-10390-static stb_uchar *stb__dout;10391-static void stb__match(stb_uchar *data, stb_uint length)10392-{10393- // INVERSE of memmove... write each byte before copying the next...10394- assert (stb__dout + length <= stb__barrier);10395- if (stb__dout + length > stb__barrier) { stb__dout += length; return; }10396- if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; }10397- while (length--) *stb__dout++ = *data++;10398-}10399-10400-static void stb__lit(stb_uchar *data, stb_uint length)10401-{10402- assert (stb__dout + length <= stb__barrier);10403- if (stb__dout + length > stb__barrier) { stb__dout += length; return; }10404- if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }10405- memcpy(stb__dout, data, length);10406- stb__dout += length;10407-}10408-10409-#define stb__in2(x) ((i[x] << 8) + i[(x)+1])10410-#define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1))10411-#define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1))10412-10413-static stb_uchar *stb_decompress_token(stb_uchar *i)10414-{10415- if (*i >= 0x20) { // use fewer if's for cases that expand small10416- if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2;10417- else if (*i >= 0x40) stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3;10418- else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1);10419- } else { // more ifs for cases that expand large, since overhead is amortized10420- if (*i >= 0x18) stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4;10421- else if (*i >= 0x10) stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5;10422- else if (*i >= 0x08) stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1);10423- else if (*i == 0x07) stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1);10424- else if (*i == 0x06) stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5;10425- else if (*i == 0x04) stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6;10426- }10427- return i;10428-}10429-10430-stb_uint stb_decompress(stb_uchar *output, stb_uchar *i, stb_uint length)10431-{10432- stb_uint olen;10433- if (stb__in4(0) != 0x57bC0000) return 0;10434- if (stb__in4(4) != 0) return 0; // error! stream is > 4GB10435- olen = stb_decompress_length(i);10436- stb__barrier2 = i;10437- stb__barrier3 = i+length;10438- stb__barrier = output + olen;10439- stb__barrier4 = output;10440- i += 16;10441-10442- stb__dout = output;10443- while (1) {10444- stb_uchar *old_i = i;10445- i = stb_decompress_token(i);10446- if (i == old_i) {10447- if (*i == 0x05 && i[1] == 0xfa) {10448- assert(stb__dout == output + olen);10449- if (stb__dout != output + olen) return 0;10450- if (stb_adler32(1, output, olen) != (stb_uint) stb__in4(2))10451- return 0;10452- return olen;10453- } else {10454- assert(0); /* NOTREACHED */10455- return 0;10456- }10457- }10458- assert(stb__dout <= output + olen);10459- if (stb__dout > output + olen)10460- return 0;10461- }10462-}10463-10464-char *stb_decompress_fromfile(char *filename, unsigned int *len)10465-{10466- unsigned int n;10467- char *q;10468- unsigned char *p;10469- FILE *f = stb_p_fopen(filename, "rb"); if (f == NULL) return NULL;10470- fseek(f, 0, SEEK_END);10471- n = ftell(f);10472- fseek(f, 0, SEEK_SET);10473- p = (unsigned char * ) malloc(n); if (p == NULL) return NULL;10474- fread(p, 1, n, f);10475- fclose(f);10476- if (p == NULL) return NULL;10477- if (p[0] != 0x57 || p[1] != 0xBc || p[2] || p[3]) { free(p); return NULL; }10478- q = (char *) malloc(stb_decompress_length(p)+1);10479- if (!q) { free(p); return NULL; }10480- *len = stb_decompress((unsigned char *) q, p, n);10481- if (*len) q[*len] = 0;10482- free(p);10483- return q;10484-}10485-10486-#if 010487-// streaming decompressor10488-10489-static struct10490-{10491- stb__uchar *in_buffer;10492- stb__uchar *match;10493-10494- stb__uint pending_literals;10495- stb__uint pending_match;10496-} xx;10497-10498-10499-10500-static void stb__match(stb_uchar *data, stb_uint length)10501-{10502- // INVERSE of memmove... write each byte before copying the next...10503- assert (stb__dout + length <= stb__barrier);10504- if (stb__dout + length > stb__barrier) { stb__dout += length; return; }10505- if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }10506- while (length--) *stb__dout++ = *data++;10507-}10508-10509-static void stb__lit(stb_uchar *data, stb_uint length)10510-{10511- assert (stb__dout + length <= stb__barrier);10512- if (stb__dout + length > stb__barrier) { stb__dout += length; return; }10513- if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; }10514- memcpy(stb__dout, data, length);10515- stb__dout += length;10516-}10517-10518-static void sx_match(stb_uchar *data, stb_uint length)10519-{10520- xx.match = data;10521- xx.pending_match = length;10522-}10523-10524-static void sx_lit(stb_uchar *data, stb_uint length)10525-{10526- xx.pending_lit = length;10527-}10528-10529-static int stb_decompress_token_state(void)10530-{10531- stb__uchar *i = xx.in_buffer;10532-10533- if (*i >= 0x20) { // use fewer if's for cases that expand small10534- if (*i >= 0x80) sx_match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2;10535- else if (*i >= 0x40) sx_match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3;10536- else /* *i >= 0x20 */ sx_lit(i+1, i[0] - 0x20 + 1), i += 1;10537- } else { // more ifs for cases that expand large, since overhead is amortized10538- if (*i >= 0x18) sx_match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4;10539- else if (*i >= 0x10) sx_match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5;10540- else if (*i >= 0x08) sx_lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2;10541- else if (*i == 0x07) sx_lit(i+3, stb__in2(1) + 1), i += 3;10542- else if (*i == 0x06) sx_match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5;10543- else if (*i == 0x04) sx_match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6;10544- else return 0;10545- }10546- xx.in_buffer = i;10547- return 1;10548-}10549-#endif10550-10551-10552-10553-//////////////////// compressor ///////////////////////10554-10555-static unsigned int stb_matchlen(stb_uchar *m1, stb_uchar *m2, stb_uint maxlen)10556-{10557- stb_uint i;10558- for (i=0; i < maxlen; ++i)10559- if (m1[i] != m2[i]) return i;10560- return i;10561-}10562-10563-// simple implementation that just takes the source data in a big block10564-10565-static stb_uchar *stb__out;10566-static FILE *stb__outfile;10567-static stb_uint stb__outbytes;10568-10569-static void stb__write(unsigned char v)10570-{10571- fputc(v, stb__outfile);10572- ++stb__outbytes;10573-}10574-10575-#define stb_out(v) (stb__out ? (void)(*stb__out++ = (stb_uchar) (v)) : stb__write((stb_uchar) (v)))10576-10577-static void stb_out2(stb_uint v)10578-{10579- stb_out(v >> 8);10580- stb_out(v);10581-}10582-10583-static void stb_out3(stb_uint v) { stb_out(v >> 16); stb_out(v >> 8); stb_out(v); }10584-static void stb_out4(stb_uint v) { stb_out(v >> 24); stb_out(v >> 16);10585- stb_out(v >> 8 ); stb_out(v); }10586-10587-static void outliterals(stb_uchar *in, ptrdiff_t numlit)10588-{10589- while (numlit > 65536) {10590- outliterals(in,65536);10591- in += 65536;10592- numlit -= 65536;10593- }10594-10595- if (numlit == 0) ;10596- else if (numlit <= 32) stb_out (0x000020 + (stb_uint) numlit-1);10597- else if (numlit <= 2048) stb_out2(0x000800 + (stb_uint) numlit-1);10598- else /* numlit <= 65536) */ stb_out3(0x070000 + (stb_uint) numlit-1);10599-10600- if (stb__out) {10601- memcpy(stb__out,in,numlit);10602- stb__out += numlit;10603- } else10604- fwrite(in, 1, numlit, stb__outfile);10605-}10606-10607-static int stb__window = 0x40000; // 256K10608-void stb_compress_window(int z)10609-{10610- if (z >= 0x1000000) z = 0x1000000; // limit of implementation10611- if (z < 0x100) z = 0x100; // insanely small10612- stb__window = z;10613-}10614-10615-static int stb_not_crap(int best, int dist)10616-{10617- return ((best > 2 && dist <= 0x00100)10618- || (best > 5 && dist <= 0x04000)10619- || (best > 7 && dist <= 0x80000));10620-}10621-10622-static stb_uint stb__hashsize = 32768;10623-void stb_compress_hashsize(unsigned int y)10624-{10625- unsigned int z = 1024;10626- while (z < y) z <<= 1;10627- stb__hashsize = z >> 2; // pass in bytes, store #pointers10628-}10629-10630-// note that you can play with the hashing functions all you10631-// want without needing to change the decompressor10632-#define stb__hc(q,h,c) (((h) << 7) + ((h) >> 25) + q[c])10633-#define stb__hc2(q,h,c,d) (((h) << 14) + ((h) >> 18) + (q[c] << 7) + q[d])10634-#define stb__hc3(q,c,d,e) ((q[c] << 14) + (q[d] << 7) + q[e])10635-10636-static stb_uint32 stb__running_adler;10637-10638-static int stb_compress_chunk(stb_uchar *history,10639- stb_uchar *start,10640- stb_uchar *end,10641- int length,10642- int *pending_literals,10643- stb_uchar **chash,10644- stb_uint mask)10645-{10646- int window = stb__window;10647- stb_uint match_max;10648- stb_uchar *lit_start = start - *pending_literals;10649- stb_uchar *q = start;10650-10651- #define STB__SCRAMBLE(h) (((h) + ((h) >> 16)) & mask)10652-10653- // stop short of the end so we don't scan off the end doing10654- // the hashing; this means we won't compress the last few bytes10655- // unless they were part of something longer10656- while (q < start+length && q+12 < end) {10657- int m;10658- stb_uint h1,h2,h3,h4, h;10659- stb_uchar *t;10660- int best = 2, dist=0;10661-10662- if (q+65536 > end)10663- match_max = (stb_uint) (end-q);10664- else10665- match_max = 65536u;10666-10667- #define stb__nc(b,d) ((d) <= window && ((b) > 9 || stb_not_crap(b,d)))10668-10669- #define STB__TRY(t,p) /* avoid retrying a match we already tried */ \10670- if (p ? dist != (int) (q-t) : 1) \10671- if ((m = (int) stb_matchlen(t, q, match_max)) > best)\10672- if (stb__nc(m,(int) (q-(t)))) \10673- best = m, dist = (int) (q - (t))10674-10675- // rather than search for all matches, only try 4 candidate locations,10676- // chosen based on 4 different hash functions of different lengths.10677- // this strategy is inspired by LZO; hashing is unrolled here using the10678- // 'hc' macro10679- h = stb__hc3(q,0, 1, 2); h1 = STB__SCRAMBLE(h);10680- t = chash[h1]; if (t) STB__TRY(t,0);10681- h = stb__hc2(q,h, 3, 4); h2 = STB__SCRAMBLE(h);10682- h = stb__hc2(q,h, 5, 6); t = chash[h2]; if (t) STB__TRY(t,1);10683- h = stb__hc2(q,h, 7, 8); h3 = STB__SCRAMBLE(h);10684- h = stb__hc2(q,h, 9,10); t = chash[h3]; if (t) STB__TRY(t,1);10685- h = stb__hc2(q,h,11,12); h4 = STB__SCRAMBLE(h);10686- t = chash[h4]; if (t) STB__TRY(t,1);10687-10688- // because we use a shared hash table, can only update it10689- // _after_ we've probed all of them10690- chash[h1] = chash[h2] = chash[h3] = chash[h4] = q;10691-10692- if (best > 2)10693- assert(dist > 0);10694-10695- // see if our best match qualifies10696- if (best < 3) { // fast path literals10697- ++q;10698- } else if (best > 2 && best <= 0x80 && dist <= 0x100) {10699- outliterals(lit_start, q-lit_start); lit_start = (q += best);10700- stb_out(0x80 + best-1);10701- stb_out(dist-1);10702- } else if (best > 5 && best <= 0x100 && dist <= 0x4000) {10703- outliterals(lit_start, q-lit_start); lit_start = (q += best);10704- stb_out2(0x4000 + dist-1);10705- stb_out(best-1);10706- } else if (best > 7 && best <= 0x100 && dist <= 0x80000) {10707- outliterals(lit_start, q-lit_start); lit_start = (q += best);10708- stb_out3(0x180000 + dist-1);10709- stb_out(best-1);10710- } else if (best > 8 && best <= 0x10000 && dist <= 0x80000) {10711- outliterals(lit_start, q-lit_start); lit_start = (q += best);10712- stb_out3(0x100000 + dist-1);10713- stb_out2(best-1);10714- } else if (best > 9 && dist <= 0x1000000) {10715- if (best > 65536) best = 65536;10716- outliterals(lit_start, q-lit_start); lit_start = (q += best);10717- if (best <= 0x100) {10718- stb_out(0x06);10719- stb_out3(dist-1);10720- stb_out(best-1);10721- } else {10722- stb_out(0x04);10723- stb_out3(dist-1);10724- stb_out2(best-1);10725- }10726- } else { // fallback literals if no match was a balanced tradeoff10727- ++q;10728- }10729- }10730-10731- // if we didn't get all the way, add the rest to literals10732- if (q-start < length)10733- q = start+length;10734-10735- // the literals are everything from lit_start to q10736- *pending_literals = (int) (q - lit_start);10737-10738- stb__running_adler = stb_adler32(stb__running_adler, start, (int) (q - start));10739- return (int) (q - start);10740-}10741-10742-static int stb_compress_inner(stb_uchar *input, stb_uint length)10743-{10744- int literals = 0;10745- stb_uint len,i;10746-10747- stb_uchar **chash;10748- chash = (stb_uchar**) malloc(stb__hashsize * sizeof(stb_uchar*));10749- if (chash == NULL) return 0; // failure10750- for (i=0; i < stb__hashsize; ++i)10751- chash[i] = NULL;10752-10753- // stream signature10754- stb_out(0x57); stb_out(0xbc);10755- stb_out2(0);10756-10757- stb_out4(0); // 64-bit length requires 32-bit leading 010758- stb_out4(length);10759- stb_out4(stb__window);10760-10761- stb__running_adler = 1;10762-10763- len = stb_compress_chunk(input, input, input+length, length, &literals, chash, stb__hashsize-1);10764- assert(len == length);10765-10766- outliterals(input+length - literals, literals);10767-10768- free(chash);10769-10770- stb_out2(0x05fa); // end opcode10771-10772- stb_out4(stb__running_adler);10773-10774- return 1; // success10775-}10776-10777-stb_uint stb_compress(stb_uchar *out, stb_uchar *input, stb_uint length)10778-{10779- stb__out = out;10780- stb__outfile = NULL;10781-10782- stb_compress_inner(input, length);10783-10784- return (stb_uint) (stb__out - out);10785-}10786-10787-int stb_compress_tofile(char *filename, char *input, unsigned int length)10788-{10789- //int maxlen = length + 512 + (length >> 2); // total guess10790- //char *buffer = (char *) malloc(maxlen);10791- //int blen = stb_compress((stb_uchar*)buffer, (stb_uchar*)input, length);10792-10793- stb__out = NULL;10794- stb__outfile = stb_p_fopen(filename, "wb");10795- if (!stb__outfile) return 0;10796-10797- stb__outbytes = 0;10798-10799- if (!stb_compress_inner((stb_uchar*)input, length))10800- return 0;10801-10802- fclose(stb__outfile);10803-10804- return stb__outbytes;10805-}10806-10807-int stb_compress_intofile(FILE *f, char *input, unsigned int length)10808-{10809- //int maxlen = length + 512 + (length >> 2); // total guess10810- //char *buffer = (char*)malloc(maxlen);10811- //int blen = stb_compress((stb_uchar*)buffer, (stb_uchar*)input, length);10812-10813- stb__out = NULL;10814- stb__outfile = f;10815- if (!stb__outfile) return 0;10816-10817- stb__outbytes = 0;10818-10819- if (!stb_compress_inner((stb_uchar*)input, length))10820- return 0;10821-10822- return stb__outbytes;10823-}10824-10825-////////////////////// streaming I/O version /////////////////////10826-10827-10828-static size_t stb_out_backpatch_id(void)10829-{10830- if (stb__out)10831- return (size_t) stb__out;10832- else10833- return ftell(stb__outfile);10834-}10835-10836-static void stb_out_backpatch(size_t id, stb_uint value)10837-{10838- stb_uchar data[4] = { (stb_uchar)(value >> 24), (stb_uchar)(value >> 16), (stb_uchar)(value >> 8), (stb_uchar)(value) };10839- if (stb__out) {10840- memcpy((void *) id, data, 4);10841- } else {10842- stb_uint where = ftell(stb__outfile);10843- fseek(stb__outfile, (long) id, SEEK_SET);10844- fwrite(data, 4, 1, stb__outfile);10845- fseek(stb__outfile, where, SEEK_SET);10846- }10847-}10848-10849-// ok, the wraparound buffer was a total failure. let's instead10850-// use a copying-in-place buffer, which lets us share the code.10851-// This is way less efficient but it'll do for now.10852-10853-static struct10854-{10855- stb_uchar *buffer;10856- int size; // physical size of buffer in bytes10857-10858- int valid; // amount of valid data in bytes10859- int start; // bytes of data already output10860-10861- int window;10862- int fsize;10863-10864- int pending_literals; // bytes not-quite output but counted in start10865- int length_id;10866-10867- stb_uint total_bytes;10868-10869- stb_uchar **chash;10870- stb_uint hashmask;10871-} xtb;10872-10873-static int stb_compress_streaming_start(void)10874-{10875- stb_uint i;10876- xtb.size = stb__window * 3;10877- xtb.buffer = (stb_uchar*)malloc(xtb.size);10878- if (!xtb.buffer) return 0;10879-10880- xtb.chash = (stb_uchar**)malloc(sizeof(*xtb.chash) * stb__hashsize);10881- if (!xtb.chash) {10882- free(xtb.buffer);10883- return 0;10884- }10885-10886- for (i=0; i < stb__hashsize; ++i)10887- xtb.chash[i] = NULL;10888-10889- xtb.hashmask = stb__hashsize-1;10890-10891- xtb.valid = 0;10892- xtb.start = 0;10893- xtb.window = stb__window;10894- xtb.fsize = stb__window;10895- xtb.pending_literals = 0;10896- xtb.total_bytes = 0;10897-10898- // stream signature10899- stb_out(0x57); stb_out(0xbc); stb_out2(0);10900-10901- stb_out4(0); // 64-bit length requires 32-bit leading 010902-10903- xtb.length_id = (int) stb_out_backpatch_id();10904- stb_out4(0); // we don't know the output length yet10905-10906- stb_out4(stb__window);10907-10908- stb__running_adler = 1;10909-10910- return 1;10911-}10912-10913-static int stb_compress_streaming_end(void)10914-{10915- // flush out any remaining data10916- stb_compress_chunk(xtb.buffer, xtb.buffer+xtb.start, xtb.buffer+xtb.valid,10917- xtb.valid-xtb.start, &xtb.pending_literals, xtb.chash, xtb.hashmask);10918-10919- // write out pending literals10920- outliterals(xtb.buffer + xtb.valid - xtb.pending_literals, xtb.pending_literals);10921-10922- stb_out2(0x05fa); // end opcode10923- stb_out4(stb__running_adler);10924-10925- stb_out_backpatch(xtb.length_id, xtb.total_bytes);10926-10927- free(xtb.buffer);10928- free(xtb.chash);10929- return 1;10930-}10931-10932-void stb_write(char *data, int data_len)10933-{10934- stb_uint i;10935-10936- // @TODO: fast path for filling the buffer and doing nothing else10937- // if (xtb.valid + data_len < xtb.size)10938-10939- xtb.total_bytes += data_len;10940-10941- while (data_len) {10942- // fill buffer10943- if (xtb.valid < xtb.size) {10944- int amt = xtb.size - xtb.valid;10945- if (data_len < amt) amt = data_len;10946- memcpy(xtb.buffer + xtb.valid, data, amt);10947- data_len -= amt;10948- data += amt;10949- xtb.valid += amt;10950- }10951- if (xtb.valid < xtb.size)10952- return;10953-10954- // at this point, the buffer is full10955-10956- // if we can process some data, go for it; make sure10957- // we leave an 'fsize's worth of data, though10958- if (xtb.start + xtb.fsize < xtb.valid) {10959- int amount = (xtb.valid - xtb.fsize) - xtb.start;10960- int n;10961- assert(amount > 0);10962- n = stb_compress_chunk(xtb.buffer, xtb.buffer + xtb.start, xtb.buffer + xtb.valid,10963- amount, &xtb.pending_literals, xtb.chash, xtb.hashmask);10964- xtb.start += n;10965- }10966-10967- assert(xtb.start + xtb.fsize >= xtb.valid);10968- // at this point, our future size is too small, so we10969- // need to flush some history. we, in fact, flush exactly10970- // one window's worth of history10971-10972- {10973- int flush = xtb.window;10974- assert(xtb.start >= flush);10975- assert(xtb.valid >= flush);10976-10977- // if 'pending literals' extends back into the shift region,10978- // write them out10979- if (xtb.start - xtb.pending_literals < flush) {10980- outliterals(xtb.buffer + xtb.start - xtb.pending_literals, xtb.pending_literals);10981- xtb.pending_literals = 0;10982- }10983-10984- // now shift the window10985- memmove(xtb.buffer, xtb.buffer + flush, xtb.valid - flush);10986- xtb.start -= flush;10987- xtb.valid -= flush;10988-10989- for (i=0; i <= xtb.hashmask; ++i)10990- if (xtb.chash[i] < xtb.buffer + flush)10991- xtb.chash[i] = NULL;10992- else10993- xtb.chash[i] -= flush;10994- }10995- // and now that we've made room for more data, go back to the top10996- }10997-}10998-10999-int stb_compress_stream_start(FILE *f)11000-{11001- stb__out = NULL;11002- stb__outfile = f;11003-11004- if (f == NULL)11005- return 0;11006-11007- if (!stb_compress_streaming_start())11008- return 0;11009-11010- return 1;11011-}11012-11013-void stb_compress_stream_end(int close)11014-{11015- stb_compress_streaming_end();11016- if (close && stb__outfile) {11017- fclose(stb__outfile);11018- }11019-}11020-11021-#endif // STB_DEFINE11022-11023-//////////////////////////////////////////////////////////////////////////////11024-//11025-// File abstraction... tired of not having this... we can write11026-// compressors to be layers over these that auto-close their children.11027-11028-11029-typedef struct stbfile11030-{11031- int (*getbyte)(struct stbfile *); // -1 on EOF11032- unsigned int (*getdata)(struct stbfile *, void *block, unsigned int len);11033-11034- int (*putbyte)(struct stbfile *, int byte);11035- unsigned int (*putdata)(struct stbfile *, void *block, unsigned int len);11036-11037- unsigned int (*size)(struct stbfile *);11038-11039- unsigned int (*tell)(struct stbfile *);11040- void (*backpatch)(struct stbfile *, unsigned int tell, void *block, unsigned int len);11041-11042- void (*close)(struct stbfile *);11043-11044- FILE *f; // file to fread/fwrite11045- unsigned char *buffer; // input/output buffer11046- unsigned char *indata, *inend; // input buffer11047- union {11048- int various;11049- void *ptr;11050- };11051-} stbfile;11052-11053-STB_EXTERN unsigned int stb_getc(stbfile *f); // read11054-STB_EXTERN int stb_putc(stbfile *f, int ch); // write11055-STB_EXTERN unsigned int stb_getdata(stbfile *f, void *buffer, unsigned int len); // read11056-STB_EXTERN unsigned int stb_putdata(stbfile *f, void *buffer, unsigned int len); // write11057-STB_EXTERN unsigned int stb_tell(stbfile *f); // read11058-STB_EXTERN unsigned int stb_size(stbfile *f); // read/write11059-STB_EXTERN void stb_backpatch(stbfile *f, unsigned int tell, void *buffer, unsigned int len); // write11060-11061-#ifdef STB_DEFINE11062-11063-unsigned int stb_getc(stbfile *f) { return f->getbyte(f); }11064-int stb_putc(stbfile *f, int ch) { return f->putbyte(f, ch); }11065-11066-unsigned int stb_getdata(stbfile *f, void *buffer, unsigned int len)11067-{11068- return f->getdata(f, buffer, len);11069-}11070-unsigned int stb_putdata(stbfile *f, void *buffer, unsigned int len)11071-{11072- return f->putdata(f, buffer, len);11073-}11074-void stb_close(stbfile *f)11075-{11076- f->close(f);11077- free(f);11078-}11079-unsigned int stb_tell(stbfile *f) { return f->tell(f); }11080-unsigned int stb_size(stbfile *f) { return f->size(f); }11081-void stb_backpatch(stbfile *f, unsigned int tell, void *buffer, unsigned int len)11082-{11083- f->backpatch(f,tell,buffer,len);11084-}11085-11086-// FILE * implementation11087-static int stb__fgetbyte(stbfile *f) { return fgetc(f->f); }11088-static int stb__fputbyte(stbfile *f, int ch) { return fputc(ch, f->f)==0; }11089-static unsigned int stb__fgetdata(stbfile *f, void *buffer, unsigned int len) { return (unsigned int) fread(buffer,1,len,f->f); }11090-static unsigned int stb__fputdata(stbfile *f, void *buffer, unsigned int len) { return (unsigned int) fwrite(buffer,1,len,f->f); }11091-static unsigned int stb__fsize(stbfile *f) { return (unsigned int) stb_filelen(f->f); }11092-static unsigned int stb__ftell(stbfile *f) { return (unsigned int) ftell(f->f); }11093-static void stb__fbackpatch(stbfile *f, unsigned int where, void *buffer, unsigned int len)11094-{11095- fseek(f->f, where, SEEK_SET);11096- fwrite(buffer, 1, len, f->f);11097- fseek(f->f, 0, SEEK_END);11098-}11099-static void stb__fclose(stbfile *f) { fclose(f->f); }11100-11101-stbfile *stb_openf(FILE *f)11102-{11103- stbfile m = { stb__fgetbyte, stb__fgetdata,11104- stb__fputbyte, stb__fputdata,11105- stb__fsize, stb__ftell, stb__fbackpatch, stb__fclose,11106- 0,0,0, };11107- stbfile *z = (stbfile *) malloc(sizeof(*z));11108- if (z) {11109- *z = m;11110- z->f = f;11111- }11112- return z;11113-}11114-11115-static int stb__nogetbyte(stbfile *f) { assert(0); return -1; }11116-static unsigned int stb__nogetdata(stbfile *f, void *buffer, unsigned int len) { assert(0); return 0; }11117-static int stb__noputbyte(stbfile *f, int ch) { assert(0); return 0; }11118-static unsigned int stb__noputdata(stbfile *f, void *buffer, unsigned int len) { assert(0); return 0; }11119-static void stb__nobackpatch(stbfile *f, unsigned int where, void *buffer, unsigned int len) { assert(0); }11120-11121-static int stb__bgetbyte(stbfile *s)11122-{11123- if (s->indata < s->inend)11124- return *s->indata++;11125- else11126- return -1;11127-}11128-11129-static unsigned int stb__bgetdata(stbfile *s, void *buffer, unsigned int len)11130-{11131- if (s->indata + len > s->inend)11132- len = (unsigned int) (s->inend - s->indata);11133- memcpy(buffer, s->indata, len);11134- s->indata += len;11135- return len;11136-}11137-static unsigned int stb__bsize(stbfile *s) { return (unsigned int) (s->inend - s->buffer); }11138-static unsigned int stb__btell(stbfile *s) { return (unsigned int) (s->indata - s->buffer); }11139-11140-static void stb__bclose(stbfile *s)11141-{11142- if (s->various)11143- free(s->buffer);11144-}11145-11146-stbfile *stb_open_inbuffer(void *buffer, unsigned int len)11147-{11148- stbfile m = { stb__bgetbyte, stb__bgetdata,11149- stb__noputbyte, stb__noputdata,11150- stb__bsize, stb__btell, stb__nobackpatch, stb__bclose };11151- stbfile *z = (stbfile *) malloc(sizeof(*z));11152- if (z) {11153- *z = m;11154- z->buffer = (unsigned char *) buffer;11155- z->indata = z->buffer;11156- z->inend = z->indata + len;11157- }11158- return z;11159-}11160-11161-stbfile *stb_open_inbuffer_free(void *buffer, unsigned int len)11162-{11163- stbfile *z = stb_open_inbuffer(buffer, len);11164- if (z)11165- z->various = 1; // free11166- return z;11167-}11168-11169-#ifndef STB_VERSION11170-// if we've been cut-and-pasted elsewhere, you get a limited11171-// version of stb_open, without the 'k' flag and utf8 support11172-static void stb__fclose2(stbfile *f)11173-{11174- fclose(f->f);11175-}11176-11177-stbfile *stb_open(char *filename, char *mode)11178-{11179- FILE *f = stb_p_fopen(filename, mode);11180- stbfile *s;11181- if (f == NULL) return NULL;11182- s = stb_openf(f);11183- if (s)11184- s->close = stb__fclose2;11185- return s;11186-}11187-#else11188-// the full version depends on some code in stb.h; this11189-// also includes the memory buffer output format implemented with stb_arr11190-static void stb__fclose2(stbfile *f)11191-{11192- stb_fclose(f->f, f->various);11193-}11194-11195-stbfile *stb_open(char *filename, char *mode)11196-{11197- FILE *f = stb_fopen(filename, mode[0] == 'k' ? mode+1 : mode);11198- stbfile *s;11199- if (f == NULL) return NULL;11200- s = stb_openf(f);11201- if (s) {11202- s->close = stb__fclose2;11203- s->various = mode[0] == 'k' ? stb_keep_if_different : stb_keep_yes;11204- }11205- return s;11206-}11207-11208-static int stb__aputbyte(stbfile *f, int ch)11209-{11210- stb_arr_push(f->buffer, ch);11211- return 1;11212-}11213-static unsigned int stb__aputdata(stbfile *f, void *data, unsigned int len)11214-{11215- memcpy(stb_arr_addn(f->buffer, (int) len), data, len);11216- return len;11217-}11218-static unsigned int stb__asize(stbfile *f) { return stb_arr_len(f->buffer); }11219-static void stb__abackpatch(stbfile *f, unsigned int where, void *data, unsigned int len)11220-{11221- memcpy(f->buffer+where, data, len);11222-}11223-static void stb__aclose(stbfile *f)11224-{11225- *(unsigned char **) f->ptr = f->buffer;11226-}11227-11228-stbfile *stb_open_outbuffer(unsigned char **update_on_close)11229-{11230- stbfile m = { stb__nogetbyte, stb__nogetdata,11231- stb__aputbyte, stb__aputdata,11232- stb__asize, stb__asize, stb__abackpatch, stb__aclose };11233- stbfile *z = (stbfile *) malloc(sizeof(*z));11234- if (z) {11235- z->ptr = update_on_close;11236- *z = m;11237- }11238- return z;11239-}11240-#endif11241-#endif11242-11243-11244-//////////////////////////////////////////////////////////////////////////////11245-//11246-// Arithmetic coder... based on cbloom's notes on the subject, should be11247-// less code than a huffman code.11248-11249-typedef struct11250-{11251- unsigned int range_low;11252- unsigned int range_high;11253- unsigned int code, range; // decode11254- int buffered_u8;11255- int pending_ffs;11256- stbfile *output;11257-} stb_arith;11258-11259-STB_EXTERN void stb_arith_init_encode(stb_arith *a, stbfile *out);11260-STB_EXTERN void stb_arith_init_decode(stb_arith *a, stbfile *in);11261-STB_EXTERN stbfile *stb_arith_encode_close(stb_arith *a);11262-STB_EXTERN stbfile *stb_arith_decode_close(stb_arith *a);11263-11264-STB_EXTERN void stb_arith_encode(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq);11265-STB_EXTERN void stb_arith_encode_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq);11266-STB_EXTERN unsigned int stb_arith_decode_value(stb_arith *a, unsigned int totalfreq);11267-STB_EXTERN void stb_arith_decode_advance(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq);11268-STB_EXTERN unsigned int stb_arith_decode_value_log2(stb_arith *a, unsigned int totalfreq2);11269-STB_EXTERN void stb_arith_decode_advance_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq);11270-11271-STB_EXTERN void stb_arith_encode_byte(stb_arith *a, int byte);11272-STB_EXTERN int stb_arith_decode_byte(stb_arith *a);11273-11274-// this is a memory-inefficient way of doing things, but it's11275-// fast(?) and simple11276-typedef struct11277-{11278- unsigned short cumfreq;11279- unsigned short samples;11280-} stb_arith_symstate_item;11281-11282-typedef struct11283-{11284- int num_sym;11285- unsigned int pow2;11286- int countdown;11287- stb_arith_symstate_item data[1];11288-} stb_arith_symstate;11289-11290-#ifdef STB_DEFINE11291-void stb_arith_init_encode(stb_arith *a, stbfile *out)11292-{11293- a->range_low = 0;11294- a->range_high = 0xffffffff;11295- a->pending_ffs = -1; // means no buffered character currently, to speed up normal case11296- a->output = out;11297-}11298-11299-static void stb__arith_carry(stb_arith *a)11300-{11301- int i;11302- assert(a->pending_ffs != -1); // can't carry with no data11303- stb_putc(a->output, a->buffered_u8);11304- for (i=0; i < a->pending_ffs; ++i)11305- stb_putc(a->output, 0);11306-}11307-11308-static void stb__arith_putbyte(stb_arith *a, int byte)11309-{11310- if (a->pending_ffs) {11311- if (a->pending_ffs == -1) { // means no buffered data; encoded for fast path efficiency11312- if (byte == 0xff)11313- stb_putc(a->output, byte); // just write it immediately11314- else {11315- a->buffered_u8 = byte;11316- a->pending_ffs = 0;11317- }11318- } else if (byte == 0xff) {11319- ++a->pending_ffs;11320- } else {11321- int i;11322- stb_putc(a->output, a->buffered_u8);11323- for (i=0; i < a->pending_ffs; ++i)11324- stb_putc(a->output, 0xff);11325- }11326- } else if (byte == 0xff) {11327- ++a->pending_ffs;11328- } else {11329- // fast path11330- stb_putc(a->output, a->buffered_u8);11331- a->buffered_u8 = byte;11332- }11333-}11334-11335-static void stb__arith_flush(stb_arith *a)11336-{11337- if (a->pending_ffs >= 0) {11338- int i;11339- stb_putc(a->output, a->buffered_u8);11340- for (i=0; i < a->pending_ffs; ++i)11341- stb_putc(a->output, 0xff);11342- }11343-}11344-11345-static void stb__renorm_encoder(stb_arith *a)11346-{11347- stb__arith_putbyte(a, a->range_low >> 24);11348- a->range_low <<= 8;11349- a->range_high = (a->range_high << 8) | 0xff;11350-}11351-11352-static void stb__renorm_decoder(stb_arith *a)11353-{11354- int c = stb_getc(a->output);11355- a->code = (a->code << 8) + (c >= 0 ? c : 0); // if EOF, insert 011356-}11357-11358-void stb_arith_encode(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq)11359-{11360- unsigned int range = a->range_high - a->range_low;11361- unsigned int old = a->range_low;11362- range /= totalfreq;11363- a->range_low += range * cumfreq;11364- a->range_high = a->range_low + range*freq;11365- if (a->range_low < old)11366- stb__arith_carry(a);11367- while (a->range_high - a->range_low < 0x1000000)11368- stb__renorm_encoder(a);11369-}11370-11371-void stb_arith_encode_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq)11372-{11373- unsigned int range = a->range_high - a->range_low;11374- unsigned int old = a->range_low;11375- range >>= totalfreq2;11376- a->range_low += range * cumfreq;11377- a->range_high = a->range_low + range*freq;11378- if (a->range_low < old)11379- stb__arith_carry(a);11380- while (a->range_high - a->range_low < 0x1000000)11381- stb__renorm_encoder(a);11382-}11383-11384-unsigned int stb_arith_decode_value(stb_arith *a, unsigned int totalfreq)11385-{11386- unsigned int freqsize = a->range / totalfreq;11387- unsigned int z = a->code / freqsize;11388- return z >= totalfreq ? totalfreq-1 : z;11389-}11390-11391-void stb_arith_decode_advance(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq)11392-{11393- unsigned int freqsize = a->range / totalfreq; // @OPTIMIZE, share with above divide somehow?11394- a->code -= freqsize * cumfreq;11395- a->range = freqsize * freq;11396- while (a->range < 0x1000000)11397- stb__renorm_decoder(a);11398-}11399-11400-unsigned int stb_arith_decode_value_log2(stb_arith *a, unsigned int totalfreq2)11401-{11402- unsigned int freqsize = a->range >> totalfreq2;11403- unsigned int z = a->code / freqsize;11404- return z >= (1U<<totalfreq2) ? (1U<<totalfreq2)-1 : z;11405-}11406-11407-void stb_arith_decode_advance_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq)11408-{11409- unsigned int freqsize = a->range >> totalfreq2;11410- a->code -= freqsize * cumfreq;11411- a->range = freqsize * freq;11412- while (a->range < 0x1000000)11413- stb__renorm_decoder(a);11414-}11415-11416-stbfile *stb_arith_encode_close(stb_arith *a)11417-{11418- // put exactly as many bytes as we'll read, so we can turn on/off arithmetic coding in a stream11419- stb__arith_putbyte(a, a->range_low >> 24);11420- stb__arith_putbyte(a, a->range_low >> 16);11421- stb__arith_putbyte(a, a->range_low >> 8);11422- stb__arith_putbyte(a, a->range_low >> 0);11423- stb__arith_flush(a);11424- return a->output;11425-}11426-11427-stbfile *stb_arith_decode_close(stb_arith *a)11428-{11429- return a->output;11430-}11431-#endif11432-11433-//////////////////////////////////////////////////////////////////////////////11434-//11435-// Threads11436-//11437-11438-#ifndef _WIN3211439-#ifdef STB_THREADS11440-#error "threads not implemented except for Windows"11441-#endif11442-#endif11443-11444-// call this function to free any global variables for memory testing11445-STB_EXTERN void stb_thread_cleanup(void);11446-11447-typedef void * (*stb_thread_func)(void *);11448-11449-// do not rely on these types, this is an implementation detail.11450-// compare against STB_THREAD_NULL and ST_SEMAPHORE_NULL11451-typedef void *stb_thread;11452-typedef void *stb_semaphore;11453-typedef void *stb_mutex;11454-typedef struct stb__sync *stb_sync;11455-11456-#define STB_SEMAPHORE_NULL NULL11457-#define STB_THREAD_NULL NULL11458-#define STB_MUTEX_NULL NULL11459-#define STB_SYNC_NULL NULL11460-11461-// get the number of processors (limited to those in the affinity mask for this process).11462-STB_EXTERN int stb_processor_count(void);11463-// force to run on a single core -- needed for RDTSC to work, e.g. for iprof11464-STB_EXTERN void stb_force_uniprocessor(void);11465-11466-// stb_work functions: queue up work to be done by some worker threads11467-11468-// set number of threads to serve the queue; you can change this on the fly,11469-// but if you decrease it, it won't decrease until things currently on the11470-// queue are finished11471-STB_EXTERN void stb_work_numthreads(int n);11472-// set maximum number of units in the queue; you can only set this BEFORE running any work functions11473-STB_EXTERN int stb_work_maxunits(int n);11474-// enqueue some work to be done (can do this from any thread, or even from a piece of work);11475-// return value of f is stored in *return_code if non-NULL11476-STB_EXTERN int stb_work(stb_thread_func f, void *d, volatile void **return_code);11477-// as above, but stb_sync_reach is called on 'rel' after work is complete11478-STB_EXTERN int stb_work_reach(stb_thread_func f, void *d, volatile void **return_code, stb_sync rel);11479-11480-11481-// necessary to call this when using volatile to order writes/reads11482-STB_EXTERN void stb_barrier(void);11483-11484-// support for independent queues with their own threads11485-11486-typedef struct stb__workqueue stb_workqueue;11487-11488-STB_EXTERN stb_workqueue*stb_workq_new(int numthreads, int max_units);11489-STB_EXTERN stb_workqueue*stb_workq_new_flags(int numthreads, int max_units, int no_add_mutex, int no_remove_mutex);11490-STB_EXTERN void stb_workq_delete(stb_workqueue *q);11491-STB_EXTERN void stb_workq_numthreads(stb_workqueue *q, int n);11492-STB_EXTERN int stb_workq(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code);11493-STB_EXTERN int stb_workq_reach(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel);11494-STB_EXTERN int stb_workq_length(stb_workqueue *q);11495-11496-STB_EXTERN stb_thread stb_create_thread (stb_thread_func f, void *d);11497-STB_EXTERN stb_thread stb_create_thread2(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel);11498-STB_EXTERN void stb_destroy_thread(stb_thread t);11499-11500-STB_EXTERN stb_semaphore stb_sem_new(int max_val);11501-STB_EXTERN stb_semaphore stb_sem_new_extra(int max_val, int start_val);11502-STB_EXTERN void stb_sem_delete (stb_semaphore s);11503-STB_EXTERN void stb_sem_waitfor(stb_semaphore s);11504-STB_EXTERN void stb_sem_release(stb_semaphore s);11505-11506-STB_EXTERN stb_mutex stb_mutex_new(void);11507-STB_EXTERN void stb_mutex_delete(stb_mutex m);11508-STB_EXTERN void stb_mutex_begin(stb_mutex m);11509-STB_EXTERN void stb_mutex_end(stb_mutex m);11510-11511-STB_EXTERN stb_sync stb_sync_new(void);11512-STB_EXTERN void stb_sync_delete(stb_sync s);11513-STB_EXTERN int stb_sync_set_target(stb_sync s, int count);11514-STB_EXTERN void stb_sync_reach_and_wait(stb_sync s); // wait for 'target' reachers11515-STB_EXTERN int stb_sync_reach(stb_sync s);11516-11517-typedef struct stb__threadqueue stb_threadqueue;11518-#define STB_THREADQ_DYNAMIC 011519-STB_EXTERN stb_threadqueue *stb_threadq_new(int item_size, int num_items, int many_add, int many_remove);11520-STB_EXTERN void stb_threadq_delete(stb_threadqueue *tq);11521-STB_EXTERN int stb_threadq_get(stb_threadqueue *tq, void *output);11522-STB_EXTERN void stb_threadq_get_block(stb_threadqueue *tq, void *output);11523-STB_EXTERN int stb_threadq_add(stb_threadqueue *tq, void *input);11524-// can return FALSE if STB_THREADQ_DYNAMIC and attempt to grow fails11525-STB_EXTERN int stb_threadq_add_block(stb_threadqueue *tq, void *input);11526-11527-#ifdef STB_THREADS11528-#ifdef STB_DEFINE11529-11530-typedef struct11531-{11532- stb_thread_func f;11533- void *d;11534- volatile void **return_val;11535- stb_semaphore sem;11536-} stb__thread;11537-11538-// this is initialized along all possible paths to create threads, therefore11539-// it's always initialized before any other threads are create, therefore11540-// it's free of races AS LONG AS you only create threads through stb_*11541-static stb_mutex stb__threadmutex, stb__workmutex;11542-11543-static void stb__threadmutex_init(void)11544-{11545- if (stb__threadmutex == STB_SEMAPHORE_NULL) {11546- stb__threadmutex = stb_mutex_new();11547- stb__workmutex = stb_mutex_new();11548- }11549-}11550-11551-#ifdef STB_THREAD_TEST11552-volatile float stb__t1=1, stb__t2;11553-11554-static void stb__wait(int n)11555-{11556- float z = 0;11557- int i;11558- for (i=0; i < n; ++i)11559- z += 1 / (stb__t1+i);11560- stb__t2 = z;11561-}11562-#else11563-#define stb__wait(x)11564-#endif11565-11566-#ifdef _WIN3211567-11568-// avoid including windows.h -- note that our definitions aren't11569-// exactly the same (we don't define the security descriptor struct)11570-// so if you want to include windows.h, make sure you do it first.11571-#include <process.h>11572-11573-#ifndef _WINDOWS_ // check windows.h guard11574-#define STB__IMPORT STB_EXTERN __declspec(dllimport)11575-#define STB__DW unsigned long11576-11577-STB__IMPORT int __stdcall TerminateThread(void *, STB__DW);11578-STB__IMPORT void * __stdcall CreateSemaphoreA(void *sec, long,long,char*);11579-STB__IMPORT int __stdcall CloseHandle(void *);11580-STB__IMPORT STB__DW __stdcall WaitForSingleObject(void *, STB__DW);11581-STB__IMPORT int __stdcall ReleaseSemaphore(void *, long, long *);11582-STB__IMPORT void __stdcall Sleep(STB__DW);11583-#endif11584-11585-// necessary to call this when using volatile to order writes/reads11586-void stb_barrier(void)11587-{11588- #ifdef MemoryBarrier11589- MemoryBarrier();11590- #else11591- long temp;11592- __asm xchg temp,eax;11593- #endif11594-}11595-11596-static void stb__thread_run(void *t)11597-{11598- void *res;11599- stb__thread info = * (stb__thread *) t;11600- free(t);11601- res = info.f(info.d);11602- if (info.return_val)11603- *info.return_val = res;11604- if (info.sem != STB_SEMAPHORE_NULL)11605- stb_sem_release(info.sem);11606-}11607-11608-static stb_thread stb_create_thread_raw(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel)11609-{11610-#ifdef _MT11611-#if defined(STB_FASTMALLOC) && !defined(STB_FASTMALLOC_ITS_OKAY_I_ONLY_MALLOC_IN_ONE_THREAD)11612- stb_fatal("Error! Cannot use STB_FASTMALLOC with threads.\n");11613- return STB_THREAD_NULL;11614-#else11615- unsigned long id;11616- stb__thread *data = (stb__thread *) malloc(sizeof(*data));11617- if (!data) return NULL;11618- stb__threadmutex_init();11619- data->f = f;11620- data->d = d;11621- data->return_val = return_code;11622- data->sem = rel;11623- id = _beginthread(stb__thread_run, 0, data);11624- if (id == -1) return NULL;11625- return (void *) id;11626-#endif11627-#else11628-#ifdef STB_NO_STB_STRINGS11629- stb_fatal("Invalid compilation");11630-#else11631- stb_fatal("Must compile mult-threaded to use stb_thread/stb_work.");11632-#endif11633- return NULL;11634-#endif11635-}11636-11637-// trivial win32 wrappers11638-void stb_destroy_thread(stb_thread t) { TerminateThread(t,0); }11639-stb_semaphore stb_sem_new(int maxv) {return CreateSemaphoreA(NULL,0,maxv,NULL); }11640-stb_semaphore stb_sem_new_extra(int maxv,int start){return CreateSemaphoreA(NULL,start,maxv,NULL); }11641-void stb_sem_delete(stb_semaphore s) { if (s != NULL) CloseHandle(s); }11642-void stb_sem_waitfor(stb_semaphore s) { WaitForSingleObject(s, 0xffffffff); } // INFINITE11643-void stb_sem_release(stb_semaphore s) { ReleaseSemaphore(s,1,NULL); }11644-static void stb__thread_sleep(int ms) { Sleep(ms); }11645-11646-#ifndef _WINDOWS_11647-STB__IMPORT int __stdcall GetProcessAffinityMask(void *, STB__DW *, STB__DW *);11648-STB__IMPORT void * __stdcall GetCurrentProcess(void);11649-STB__IMPORT int __stdcall SetProcessAffinityMask(void *, STB__DW);11650-#endif11651-11652-int stb_processor_count(void)11653-{11654- unsigned long proc,sys;11655- GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys);11656- return stb_bitcount(proc);11657-}11658-11659-void stb_force_uniprocessor(void)11660-{11661- unsigned long proc,sys;11662- GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys);11663- if (stb_bitcount(proc) > 1) {11664- int z;11665- for (z=0; z < 32; ++z)11666- if (proc & (1 << z))11667- break;11668- if (z < 32) {11669- proc = 1 << z;11670- SetProcessAffinityMask(GetCurrentProcess(), proc);11671- }11672- }11673-}11674-11675-#ifdef _WINDOWS_11676-#define STB_MUTEX_NATIVE11677-void *stb_mutex_new(void)11678-{11679- CRITICAL_SECTION *p = (CRITICAL_SECTION *) malloc(sizeof(*p));11680- if (p)11681-#if _WIN32_WINNT >= 0x050011682- InitializeCriticalSectionAndSpinCount(p, 500);11683-#else11684- InitializeCriticalSection(p);11685-#endif11686- return p;11687-}11688-11689-void stb_mutex_delete(void *p)11690-{11691- if (p) {11692- DeleteCriticalSection((CRITICAL_SECTION *) p);11693- free(p);11694- }11695-}11696-11697-void stb_mutex_begin(void *p)11698-{11699- stb__wait(500);11700- if (p)11701- EnterCriticalSection((CRITICAL_SECTION *) p);11702-}11703-11704-void stb_mutex_end(void *p)11705-{11706- if (p)11707- LeaveCriticalSection((CRITICAL_SECTION *) p);11708- stb__wait(500);11709-}11710-#endif // _WINDOWS_11711-11712-#if 011713-// for future reference,11714-// InterlockedCompareExchange for x86:11715- int cas64_mp(void * dest, void * xcmp, void * xxchg) {11716- __asm11717- {11718- mov esi, [xxchg] ; exchange11719- mov ebx, [esi + 0]11720- mov ecx, [esi + 4]11721-11722- mov esi, [xcmp] ; comparand11723- mov eax, [esi + 0]11724- mov edx, [esi + 4]11725-11726- mov edi, [dest] ; destination11727- lock cmpxchg8b [edi]11728- jz yyyy;11729-11730- mov [esi + 0], eax;11731- mov [esi + 4], edx;11732-11733-yyyy:11734- xor eax, eax;11735- setz al;11736- };11737-11738-inline unsigned __int64 _InterlockedCompareExchange64(volatile unsigned __int64 *dest11739- ,unsigned __int64 exchange11740- ,unsigned __int64 comperand)11741-{11742- //value returned in eax::edx11743- __asm {11744- lea esi,comperand;11745- lea edi,exchange;11746-11747- mov eax,[esi];11748- mov edx,4[esi];11749- mov ebx,[edi];11750- mov ecx,4[edi];11751- mov esi,dest;11752- lock CMPXCHG8B [esi];11753- }11754-#endif // #if 011755-11756-#endif // _WIN3211757-11758-stb_thread stb_create_thread2(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel)11759-{11760- return stb_create_thread_raw(f,d,return_code,rel);11761-}11762-11763-stb_thread stb_create_thread(stb_thread_func f, void *d)11764-{11765- return stb_create_thread2(f,d,NULL,STB_SEMAPHORE_NULL);11766-}11767-11768-// mutex implemented by wrapping semaphore11769-#ifndef STB_MUTEX_NATIVE11770-stb_mutex stb_mutex_new(void) { return stb_sem_new_extra(1,1); }11771-void stb_mutex_delete(stb_mutex m) { stb_sem_delete (m); }11772-void stb_mutex_begin(stb_mutex m) { stb__wait(500); if (m) stb_sem_waitfor(m); }11773-void stb_mutex_end(stb_mutex m) { if (m) stb_sem_release(m); stb__wait(500); }11774-#endif11775-11776-// thread merge operation11777-struct stb__sync11778-{11779- int target; // target number of threads to hit it11780- int sofar; // total threads that hit it11781- int waiting; // total threads waiting11782-11783- stb_mutex start; // mutex to prevent starting again before finishing previous11784- stb_mutex mutex; // mutex while tweaking state11785- stb_semaphore release; // semaphore wake up waiting threads11786- // we have to wake them up one at a time, rather than using a single release11787- // call, because win32 semaphores don't let you dynamically change the max count!11788-};11789-11790-stb_sync stb_sync_new(void)11791-{11792- stb_sync s = (stb_sync) malloc(sizeof(*s));11793- if (!s) return s;11794-11795- s->target = s->sofar = s->waiting = 0;11796- s->mutex = stb_mutex_new();11797- s->start = stb_mutex_new();11798- s->release = stb_sem_new(1);11799- if (s->mutex == STB_MUTEX_NULL || s->release == STB_SEMAPHORE_NULL || s->start == STB_MUTEX_NULL) {11800- stb_mutex_delete(s->mutex);11801- stb_mutex_delete(s->mutex);11802- stb_sem_delete(s->release);11803- free(s);11804- return NULL;11805- }11806- return s;11807-}11808-11809-void stb_sync_delete(stb_sync s)11810-{11811- if (s->waiting) {11812- // it's bad to delete while there are threads waiting!11813- // shall we wait for them to reach, or just bail? just bail11814- assert(0);11815- }11816- stb_mutex_delete(s->mutex);11817- stb_mutex_delete(s->release);11818- free(s);11819-}11820-11821-int stb_sync_set_target(stb_sync s, int count)11822-{11823- // don't allow setting a target until the last one is fully released;11824- // note that this can lead to inefficient pipelining, and maybe we'd11825- // be better off ping-ponging between two internal syncs?11826- // I tried seeing how often this happened using TryEnterCriticalSection11827- // and could _never_ get it to happen in imv(stb), even with more threads11828- // than processors. So who knows!11829- stb_mutex_begin(s->start);11830-11831- // this mutex is pointless, since it's not valid for threads11832- // to call reach() before anyone calls set_target() anyway11833- stb_mutex_begin(s->mutex);11834-11835- assert(s->target == 0); // enforced by start mutex11836- s->target = count;11837- s->sofar = 0;11838- s->waiting = 0;11839- stb_mutex_end(s->mutex);11840- return STB_TRUE;11841-}11842-11843-void stb__sync_release(stb_sync s)11844-{11845- if (s->waiting)11846- stb_sem_release(s->release);11847- else {11848- s->target = 0;11849- stb_mutex_end(s->start);11850- }11851-}11852-11853-int stb_sync_reach(stb_sync s)11854-{11855- int n;11856- stb_mutex_begin(s->mutex);11857- assert(s->sofar < s->target);11858- n = ++s->sofar; // record this value to avoid possible race if we did 'return s->sofar';11859- if (s->sofar == s->target)11860- stb__sync_release(s);11861- stb_mutex_end(s->mutex);11862- return n;11863-}11864-11865-void stb_sync_reach_and_wait(stb_sync s)11866-{11867- stb_mutex_begin(s->mutex);11868- assert(s->sofar < s->target);11869- ++s->sofar;11870- if (s->sofar == s->target) {11871- stb__sync_release(s);11872- stb_mutex_end(s->mutex);11873- } else {11874- ++s->waiting; // we're waiting, so one more waiter11875- stb_mutex_end(s->mutex); // release the mutex to other threads11876-11877- stb_sem_waitfor(s->release); // wait for merge completion11878-11879- stb_mutex_begin(s->mutex); // on merge completion, grab the mutex11880- --s->waiting; // we're done waiting11881- stb__sync_release(s); // restart the next waiter11882- stb_mutex_end(s->mutex); // and now we're done11883- // this ends the same as the first case, but it's a lot11884- // clearer to understand without sharing the code11885- }11886-}11887-11888-struct stb__threadqueue11889-{11890- stb_mutex add, remove;11891- stb_semaphore nonempty, nonfull;11892- int head_blockers; // number of threads blocking--used to know whether to release(avail)11893- int tail_blockers;11894- int head, tail, array_size, growable;11895- int item_size;11896- char *data;11897-};11898-11899-static int stb__tq_wrap(volatile stb_threadqueue *z, int p)11900-{11901- if (p == z->array_size)11902- return p - z->array_size;11903- else11904- return p;11905-}11906-11907-int stb__threadq_get_raw(stb_threadqueue *tq2, void *output, int block)11908-{11909- volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;11910- if (tq->head == tq->tail && !block) return 0;11911-11912- stb_mutex_begin(tq->remove);11913-11914- while (tq->head == tq->tail) {11915- if (!block) {11916- stb_mutex_end(tq->remove);11917- return 0;11918- }11919- ++tq->head_blockers;11920- stb_mutex_end(tq->remove);11921-11922- stb_sem_waitfor(tq->nonempty);11923-11924- stb_mutex_begin(tq->remove);11925- --tq->head_blockers;11926- }11927-11928- memcpy(output, tq->data + tq->head*tq->item_size, tq->item_size);11929- stb_barrier();11930- tq->head = stb__tq_wrap(tq, tq->head+1);11931-11932- stb_sem_release(tq->nonfull);11933- if (tq->head_blockers) // can't check if actually non-empty due to race?11934- stb_sem_release(tq->nonempty); // if there are other blockers, wake one11935-11936- stb_mutex_end(tq->remove);11937- return STB_TRUE;11938-}11939-11940-int stb__threadq_grow(volatile stb_threadqueue *tq)11941-{11942- int n;11943- char *p;11944- assert(tq->remove != STB_MUTEX_NULL); // must have this to allow growth!11945- stb_mutex_begin(tq->remove);11946-11947- n = tq->array_size * 2;11948- p = (char *) realloc(tq->data, n * tq->item_size);11949- if (p == NULL) {11950- stb_mutex_end(tq->remove);11951- stb_mutex_end(tq->add);11952- return STB_FALSE;11953- }11954- if (tq->tail < tq->head) {11955- memcpy(p + tq->array_size * tq->item_size, p, tq->tail * tq->item_size);11956- tq->tail += tq->array_size;11957- }11958- tq->data = p;11959- tq->array_size = n;11960-11961- stb_mutex_end(tq->remove);11962- return STB_TRUE;11963-}11964-11965-int stb__threadq_add_raw(stb_threadqueue *tq2, void *input, int block)11966-{11967- int tail,pos;11968- volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;11969- stb_mutex_begin(tq->add);11970- for(;;) {11971- pos = tq->tail;11972- tail = stb__tq_wrap(tq, pos+1);11973- if (tail != tq->head) break;11974-11975- // full11976- if (tq->growable) {11977- if (!stb__threadq_grow(tq)) {11978- stb_mutex_end(tq->add);11979- return STB_FALSE; // out of memory11980- }11981- } else if (!block) {11982- stb_mutex_end(tq->add);11983- return STB_FALSE;11984- } else {11985- ++tq->tail_blockers;11986- stb_mutex_end(tq->add);11987-11988- stb_sem_waitfor(tq->nonfull);11989-11990- stb_mutex_begin(tq->add);11991- --tq->tail_blockers;11992- }11993- }11994- memcpy(tq->data + tq->item_size * pos, input, tq->item_size);11995- stb_barrier();11996- tq->tail = tail;11997- stb_sem_release(tq->nonempty);11998- if (tq->tail_blockers) // can't check if actually non-full due to race?11999- stb_sem_release(tq->nonfull);12000- stb_mutex_end(tq->add);12001- return STB_TRUE;12002-}12003-12004-int stb_threadq_length(stb_threadqueue *tq2)12005-{12006- int a,b,n;12007- volatile stb_threadqueue *tq = (volatile stb_threadqueue *) tq2;12008- stb_mutex_begin(tq->add);12009- a = tq->head;12010- b = tq->tail;12011- n = tq->array_size;12012- stb_mutex_end(tq->add);12013- if (a > b) b += n;12014- return b-a;12015-}12016-12017-int stb_threadq_get(stb_threadqueue *tq, void *output)12018-{12019- return stb__threadq_get_raw(tq, output, STB_FALSE);12020-}12021-12022-void stb_threadq_get_block(stb_threadqueue *tq, void *output)12023-{12024- stb__threadq_get_raw(tq, output, STB_TRUE);12025-}12026-12027-int stb_threadq_add(stb_threadqueue *tq, void *input)12028-{12029- return stb__threadq_add_raw(tq, input, STB_FALSE);12030-}12031-12032-int stb_threadq_add_block(stb_threadqueue *tq, void *input)12033-{12034- return stb__threadq_add_raw(tq, input, STB_TRUE);12035-}12036-12037-void stb_threadq_delete(stb_threadqueue *tq)12038-{12039- if (tq) {12040- free(tq->data);12041- stb_mutex_delete(tq->add);12042- stb_mutex_delete(tq->remove);12043- stb_sem_delete(tq->nonempty);12044- stb_sem_delete(tq->nonfull);12045- free(tq);12046- }12047-}12048-12049-#define STB_THREADQUEUE_DYNAMIC 012050-stb_threadqueue *stb_threadq_new(int item_size, int num_items, int many_add, int many_remove)12051-{12052- int error=0;12053- stb_threadqueue *tq = (stb_threadqueue *) malloc(sizeof(*tq));12054- if (tq == NULL) return NULL;12055-12056- if (num_items == STB_THREADQUEUE_DYNAMIC) {12057- tq->growable = STB_TRUE;12058- num_items = 32;12059- } else12060- tq->growable = STB_FALSE;12061-12062- tq->item_size = item_size;12063- tq->array_size = num_items+1;12064-12065- tq->add = tq->remove = STB_MUTEX_NULL;12066- tq->nonempty = tq->nonfull = STB_SEMAPHORE_NULL;12067- tq->data = NULL;12068- if (many_add)12069- { tq->add = stb_mutex_new(); if (tq->add == STB_MUTEX_NULL) goto error; }12070- if (many_remove || tq->growable)12071- { tq->remove = stb_mutex_new(); if (tq->remove == STB_MUTEX_NULL) goto error; }12072- tq->nonempty = stb_sem_new(1); if (tq->nonempty == STB_SEMAPHORE_NULL) goto error;12073- tq->nonfull = stb_sem_new(1); if (tq->nonfull == STB_SEMAPHORE_NULL) goto error;12074- tq->data = (char *) malloc(tq->item_size * tq->array_size);12075- if (tq->data == NULL) goto error;12076-12077- tq->head = tq->tail = 0;12078- tq->head_blockers = tq->tail_blockers = 0;12079-12080- return tq;12081-12082-error:12083- stb_threadq_delete(tq);12084- return NULL;12085-}12086-12087-typedef struct12088-{12089- stb_thread_func f;12090- void *d;12091- volatile void **retval;12092- stb_sync sync;12093-} stb__workinfo;12094-12095-//static volatile stb__workinfo *stb__work;12096-12097-struct stb__workqueue12098-{12099- int numthreads;12100- stb_threadqueue *tq;12101-};12102-12103-static stb_workqueue *stb__work_global;12104-12105-static void *stb__thread_workloop(void *p)12106-{12107- volatile stb_workqueue *q = (volatile stb_workqueue *) p;12108- for(;;) {12109- void *z;12110- stb__workinfo w;12111- stb_threadq_get_block(q->tq, &w);12112- if (w.f == NULL) // null work is a signal to end the thread12113- return NULL;12114- z = w.f(w.d);12115- if (w.retval) { stb_barrier(); *w.retval = z; }12116- if (w.sync != STB_SYNC_NULL) stb_sync_reach(w.sync);12117- }12118-}12119-12120-stb_workqueue *stb_workq_new(int num_threads, int max_units)12121-{12122- return stb_workq_new_flags(num_threads, max_units, 0,0);12123-}12124-12125-stb_workqueue *stb_workq_new_flags(int numthreads, int max_units, int no_add_mutex, int no_remove_mutex)12126-{12127- stb_workqueue *q = (stb_workqueue *) malloc(sizeof(*q));12128- if (q == NULL) return NULL;12129- q->tq = stb_threadq_new(sizeof(stb__workinfo), max_units, !no_add_mutex, !no_remove_mutex);12130- if (q->tq == NULL) { free(q); return NULL; }12131- q->numthreads = 0;12132- stb_workq_numthreads(q, numthreads);12133- return q;12134-}12135-12136-void stb_workq_delete(stb_workqueue *q)12137-{12138- while (stb_workq_length(q) != 0)12139- stb__thread_sleep(1);12140- stb_threadq_delete(q->tq);12141- free(q);12142-}12143-12144-static int stb__work_maxitems = STB_THREADQUEUE_DYNAMIC;12145-12146-static void stb_work_init(int num_threads)12147-{12148- if (stb__work_global == NULL) {12149- stb__threadmutex_init();12150- stb_mutex_begin(stb__workmutex);12151- stb_barrier();12152- if (*(stb_workqueue * volatile *) &stb__work_global == NULL)12153- stb__work_global = stb_workq_new(num_threads, stb__work_maxitems);12154- stb_mutex_end(stb__workmutex);12155- }12156-}12157-12158-static int stb__work_raw(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)12159-{12160- stb__workinfo w;12161- if (q == NULL) {12162- stb_work_init(1);12163- q = stb__work_global;12164- }12165- w.f = f;12166- w.d = d;12167- w.retval = return_code;12168- w.sync = rel;12169- return stb_threadq_add(q->tq, &w);12170-}12171-12172-int stb_workq_length(stb_workqueue *q)12173-{12174- return stb_threadq_length(q->tq);12175-}12176-12177-int stb_workq(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code)12178-{12179- if (f == NULL) return 0;12180- return stb_workq_reach(q, f, d, return_code, NULL);12181-}12182-12183-int stb_workq_reach(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)12184-{12185- if (f == NULL) return 0;12186- return stb__work_raw(q, f, d, return_code, rel);12187-}12188-12189-static void stb__workq_numthreads(stb_workqueue *q, int n)12190-{12191- while (q->numthreads < n) {12192- stb_create_thread(stb__thread_workloop, q);12193- ++q->numthreads;12194- }12195- while (q->numthreads > n) {12196- stb__work_raw(q, NULL, NULL, NULL, NULL);12197- --q->numthreads;12198- }12199-}12200-12201-void stb_workq_numthreads(stb_workqueue *q, int n)12202-{12203- stb_mutex_begin(stb__threadmutex);12204- stb__workq_numthreads(q,n);12205- stb_mutex_end(stb__threadmutex);12206-}12207-12208-int stb_work_maxunits(int n)12209-{12210- if (stb__work_global == NULL) {12211- stb__work_maxitems = n;12212- stb_work_init(1);12213- }12214- return stb__work_maxitems;12215-}12216-12217-int stb_work(stb_thread_func f, void *d, volatile void **return_code)12218-{12219- return stb_workq(stb__work_global, f,d,return_code);12220-}12221-12222-int stb_work_reach(stb_thread_func f, void *d, volatile void **return_code, stb_sync rel)12223-{12224- return stb_workq_reach(stb__work_global, f,d,return_code,rel);12225-}12226-12227-void stb_work_numthreads(int n)12228-{12229- if (stb__work_global == NULL)12230- stb_work_init(n);12231- else12232- stb_workq_numthreads(stb__work_global, n);12233-}12234-#endif // STB_DEFINE12235-12236-12237-//////////////////////////////////////////////////////////////////////////////12238-//12239-// Background disk I/O12240-//12241-//12242-12243-#define STB_BGIO_READ_ALL (-1)12244-STB_EXTERN int stb_bgio_read (char *filename, int offset, int len, stb_uchar **result, int *olen);12245-STB_EXTERN int stb_bgio_readf (FILE *f , int offset, int len, stb_uchar **result, int *olen);12246-STB_EXTERN int stb_bgio_read_to (char *filename, int offset, int len, stb_uchar *buffer, int *olen);12247-STB_EXTERN int stb_bgio_readf_to(FILE *f , int offset, int len, stb_uchar *buffer, int *olen);12248-12249-typedef struct12250-{12251- int have_data;12252- int is_valid;12253- int is_dir;12254- time_t filetime;12255- stb_int64 filesize;12256-} stb_bgstat;12257-12258-STB_EXTERN int stb_bgio_stat (char *filename, stb_bgstat *result);12259-12260-#ifdef STB_DEFINE12261-12262-static stb_workqueue *stb__diskio;12263-static stb_mutex stb__diskio_mutex;12264-12265-void stb_thread_cleanup(void)12266-{12267- if (stb__work_global) stb_workq_delete(stb__work_global); stb__work_global = NULL;12268- if (stb__threadmutex) stb_mutex_delete(stb__threadmutex); stb__threadmutex = NULL;12269- if (stb__workmutex) stb_mutex_delete(stb__workmutex); stb__workmutex = NULL;12270- if (stb__diskio) stb_workq_delete(stb__diskio); stb__diskio = NULL;12271- if (stb__diskio_mutex)stb_mutex_delete(stb__diskio_mutex);stb__diskio_mutex= NULL;12272-}12273-12274-12275-typedef struct12276-{12277- char *filename;12278- FILE *f;12279- int offset;12280- int len;12281-12282- stb_bgstat *stat_out;12283- stb_uchar *output;12284- stb_uchar **result;12285- int *len_output;12286- int *flag;12287-} stb__disk_command;12288-12289-#define STB__MAX_DISK_COMMAND 10012290-static stb__disk_command stb__dc_queue[STB__MAX_DISK_COMMAND];12291-static int stb__dc_offset;12292-12293-void stb__io_init(void)12294-{12295- if (!stb__diskio) {12296- stb__threadmutex_init();12297- stb_mutex_begin(stb__threadmutex);12298- stb_barrier();12299- if (*(stb_thread * volatile *) &stb__diskio == NULL) {12300- stb__diskio_mutex = stb_mutex_new();12301- // use many threads so OS can try to schedule seeks12302- stb__diskio = stb_workq_new_flags(16,STB__MAX_DISK_COMMAND,STB_FALSE,STB_FALSE);12303- }12304- stb_mutex_end(stb__threadmutex);12305- }12306-}12307-12308-static void * stb__io_error(stb__disk_command *dc)12309-{12310- if (dc->len_output) *dc->len_output = 0;12311- if (dc->result) *dc->result = NULL;12312- if (dc->flag) *dc->flag = -1;12313- return NULL;12314-}12315-12316-static void * stb__io_task(void *p)12317-{12318- stb__disk_command *dc = (stb__disk_command *) p;12319- int len;12320- FILE *f;12321- stb_uchar *buf;12322-12323- if (dc->stat_out) {12324- struct _stati64 s;12325- if (!_stati64(dc->filename, &s)) {12326- dc->stat_out->filesize = s.st_size;12327- dc->stat_out->filetime = s.st_mtime;12328- dc->stat_out->is_dir = s.st_mode & _S_IFDIR;12329- dc->stat_out->is_valid = (s.st_mode & _S_IFREG) || dc->stat_out->is_dir;12330- } else12331- dc->stat_out->is_valid = 0;12332- stb_barrier();12333- dc->stat_out->have_data = 1;12334- free(dc->filename);12335- return 0;12336- }12337- if (dc->f) {12338- #ifdef WIN3212339- f = _fdopen(_dup(_fileno(dc->f)), "rb");12340- #else12341- f = fdopen(dup(fileno(dc->f)), "rb");12342- #endif12343- if (!f)12344- return stb__io_error(dc);12345- } else {12346- f = fopen(dc->filename, "rb");12347- free(dc->filename);12348- if (!f)12349- return stb__io_error(dc);12350- }12351-12352- len = dc->len;12353- if (len < 0) {12354- fseek(f, 0, SEEK_END);12355- len = ftell(f) - dc->offset;12356- }12357-12358- if (fseek(f, dc->offset, SEEK_SET)) {12359- fclose(f);12360- return stb__io_error(dc);12361- }12362-12363- if (dc->output)12364- buf = dc->output;12365- else {12366- buf = (stb_uchar *) malloc(len);12367- if (buf == NULL) {12368- fclose(f);12369- return stb__io_error(dc);12370- }12371- }12372-12373- len = fread(buf, 1, len, f);12374- fclose(f);12375- if (dc->len_output) *dc->len_output = len;12376- if (dc->result) *dc->result = buf;12377- if (dc->flag) *dc->flag = 1;12378-12379- return NULL;12380-}12381-12382-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)12383-{12384- int res;12385- stb__io_init();12386- // do memory allocation outside of mutex12387- if (fname) fname = stb_p_strdup(fname);12388- stb_mutex_begin(stb__diskio_mutex);12389- {12390- stb__disk_command *dc = &stb__dc_queue[stb__dc_offset];12391- dc->filename = fname;12392- dc->f = f;12393- dc->offset = off;12394- dc->len = len;12395- dc->output = out;12396- dc->result = result;12397- dc->len_output = olen;12398- dc->flag = flag;12399- dc->stat_out = stat;12400- res = stb_workq(stb__diskio, stb__io_task, dc, NULL);12401- if (res)12402- stb__dc_offset = (stb__dc_offset + 1 == STB__MAX_DISK_COMMAND ? 0 : stb__dc_offset+1);12403- }12404- stb_mutex_end(stb__diskio_mutex);12405- return res;12406-}12407-12408-int stb_bgio_read(char *filename, int offset, int len, stb_uchar **result, int *olen)12409-{12410- return stb__io_add(filename,NULL,offset,len,NULL,result,olen,NULL,NULL);12411-}12412-12413-int stb_bgio_readf(FILE *f, int offset, int len, stb_uchar **result, int *olen)12414-{12415- return stb__io_add(NULL,f,offset,len,NULL,result,olen,NULL,NULL);12416-}12417-12418-int stb_bgio_read_to(char *filename, int offset, int len, stb_uchar *buffer, int *olen)12419-{12420- return stb__io_add(filename,NULL,offset,len,buffer,NULL,olen,NULL,NULL);12421-}12422-12423-int stb_bgio_readf_to(FILE *f, int offset, int len, stb_uchar *buffer, int *olen)12424-{12425- return stb__io_add(NULL,f,offset,len,buffer,NULL,olen,NULL,NULL);12426-}12427-12428-STB_EXTERN int stb_bgio_stat (char *filename, stb_bgstat *result)12429-{12430- result->have_data = 0;12431- return stb__io_add(filename,NULL,0,0,0,NULL,0,NULL, result);12432-}12433-#endif12434-#endif12435-12436-12437-12438-//////////////////////////////////////////////////////////////////////////////12439-//12440-// Fast malloc implementation12441-//12442-// This is a clone of TCMalloc, but without the thread support.12443-// 1. large objects are allocated directly, page-aligned12444-// 2. small objects are allocated in homogeonous heaps, 0 overhead12445-//12446-// We keep an allocation table for pages a la TCMalloc. This would12447-// require 4MB for the entire address space, but we only allocate12448-// the parts that are in use. The overhead from using homogenous heaps12449-// everywhere is 3MB. (That is, if you allocate 1 object of each size,12450-// you'll use 3MB.)12451-12452-#if defined(STB_DEFINE) && ((defined(_WIN32) && !defined(_M_AMD64)) || defined(STB_FASTMALLOC))12453-12454-#ifdef _WIN3212455- #ifndef _WINDOWS_12456- #ifndef STB__IMPORT12457- #define STB__IMPORT STB_EXTERN __declspec(dllimport)12458- #define STB__DW unsigned long12459- #endif12460- STB__IMPORT void * __stdcall VirtualAlloc(void *p, unsigned long size, unsigned long type, unsigned long protect);12461- STB__IMPORT int __stdcall VirtualFree(void *p, unsigned long size, unsigned long freetype);12462- #endif12463- #define stb__alloc_pages_raw(x) (stb_uint32) VirtualAlloc(NULL, (x), 0x3000, 0x04)12464- #define stb__dealloc_pages_raw(p) VirtualFree((void *) p, 0, 0x8000)12465-#else12466- #error "Platform not currently supported"12467-#endif12468-12469-typedef struct stb__span12470-{12471- int start, len;12472- struct stb__span *next, *prev;12473- void *first_free;12474- unsigned short list; // 1..256 free; 257..511 sizeclass; 0=large block12475- short allocations; // # outstanding allocations for sizeclass12476-} stb__span; // 2412477-12478-static stb__span **stb__span_for_page;12479-static int stb__firstpage, stb__lastpage;12480-static void stb__update_page_range(int first, int last)12481-{12482- stb__span **sfp;12483- int i, f,l;12484- if (first >= stb__firstpage && last <= stb__lastpage) return;12485- if (stb__span_for_page == NULL) {12486- f = first;12487- l = f+stb_max(last-f, 16384);12488- l = stb_min(l, 1<<20);12489- } else if (last > stb__lastpage) {12490- f = stb__firstpage;12491- l = f + (stb__lastpage - f) * 2;12492- l = stb_clamp(last, l,1<<20);12493- } else {12494- l = stb__lastpage;12495- f = l - (l - stb__firstpage) * 2;12496- f = stb_clamp(f, 0,first);12497- }12498- sfp = (stb__span **) stb__alloc_pages_raw(sizeof(void *) * (l-f));12499- for (i=f; i < stb__firstpage; ++i) sfp[i - f] = NULL;12500- for ( ; i < stb__lastpage ; ++i) sfp[i - f] = stb__span_for_page[i - stb__firstpage];12501- for ( ; i < l ; ++i) sfp[i - f] = NULL;12502- if (stb__span_for_page) stb__dealloc_pages_raw(stb__span_for_page);12503- stb__firstpage = f;12504- stb__lastpage = l;12505- stb__span_for_page = sfp;12506-}12507-12508-static stb__span *stb__span_free=NULL;12509-static stb__span *stb__span_first, *stb__span_end;12510-static stb__span *stb__span_alloc(void)12511-{12512- stb__span *s = stb__span_free;12513- if (s)12514- stb__span_free = s->next;12515- else {12516- if (!stb__span_first) {12517- stb__span_first = (stb__span *) stb__alloc_pages_raw(65536);12518- if (stb__span_first == NULL) return NULL;12519- stb__span_end = stb__span_first + (65536 / sizeof(stb__span));12520- }12521- s = stb__span_first++;12522- if (stb__span_first == stb__span_end) stb__span_first = NULL;12523- }12524- return s;12525-}12526-12527-static stb__span *stb__spanlist[512];12528-12529-static void stb__spanlist_unlink(stb__span *s)12530-{12531- if (s->prev)12532- s->prev->next = s->next;12533- else {12534- int n = s->list;12535- assert(stb__spanlist[n] == s);12536- stb__spanlist[n] = s->next;12537- }12538- if (s->next)12539- s->next->prev = s->prev;12540- s->next = s->prev = NULL;12541- s->list = 0;12542-}12543-12544-static void stb__spanlist_add(int n, stb__span *s)12545-{12546- s->list = n;12547- s->next = stb__spanlist[n];12548- s->prev = NULL;12549- stb__spanlist[n] = s;12550- if (s->next) s->next->prev = s;12551-}12552-12553-#define stb__page_shift 1212554-#define stb__page_size (1 << stb__page_shift)12555-#define stb__page_number(x) ((x) >> stb__page_shift)12556-#define stb__page_address(x) ((x) << stb__page_shift)12557-12558-static void stb__set_span_for_page(stb__span *s)12559-{12560- int i;12561- for (i=0; i < s->len; ++i)12562- stb__span_for_page[s->start + i - stb__firstpage] = s;12563-}12564-12565-static stb__span *stb__coalesce(stb__span *a, stb__span *b)12566-{12567- assert(a->start + a->len == b->start);12568- if (a->list) stb__spanlist_unlink(a);12569- if (b->list) stb__spanlist_unlink(b);12570- a->len += b->len;12571- b->len = 0;12572- b->next = stb__span_free;12573- stb__span_free = b;12574- stb__set_span_for_page(a);12575- return a;12576-}12577-12578-static void stb__free_span(stb__span *s)12579-{12580- stb__span *n = NULL;12581- if (s->start > stb__firstpage) {12582- n = stb__span_for_page[s->start-1 - stb__firstpage];12583- if (n && n->allocations == -2 && n->start + n->len == s->start) s = stb__coalesce(n,s);12584- }12585- if (s->start + s->len < stb__lastpage) {12586- n = stb__span_for_page[s->start + s->len - stb__firstpage];12587- if (n && n->allocations == -2 && s->start + s->len == n->start) s = stb__coalesce(s,n);12588- }12589- s->allocations = -2;12590- stb__spanlist_add(s->len > 256 ? 256 : s->len, s);12591-}12592-12593-static stb__span *stb__alloc_pages(int num)12594-{12595- stb__span *s = stb__span_alloc();12596- int p;12597- if (!s) return NULL;12598- p = stb__alloc_pages_raw(num << stb__page_shift);12599- if (p == 0) { s->next = stb__span_free; stb__span_free = s; return 0; }12600- assert(stb__page_address(stb__page_number(p)) == p);12601- p = stb__page_number(p);12602- stb__update_page_range(p, p+num);12603- s->start = p;12604- s->len = num;12605- s->next = NULL;12606- s->prev = NULL;12607- stb__set_span_for_page(s);12608- return s;12609-}12610-12611-static stb__span *stb__alloc_span(int pagecount)12612-{12613- int i;12614- stb__span *p = NULL;12615- for(i=pagecount; i < 256; ++i)12616- if (stb__spanlist[i]) {12617- p = stb__spanlist[i];12618- break;12619- }12620- if (!p) {12621- p = stb__spanlist[256];12622- while (p && p->len < pagecount)12623- p = p->next;12624- }12625- if (!p) {12626- p = stb__alloc_pages(pagecount < 16 ? 16 : pagecount);12627- if (p == NULL) return 0;12628- } else12629- stb__spanlist_unlink(p);12630-12631- if (p->len > pagecount) {12632- stb__span *q = stb__span_alloc();12633- if (q) {12634- q->start = p->start + pagecount;12635- q->len = p->len - pagecount;12636- p->len = pagecount;12637- for (i=0; i < q->len; ++i)12638- stb__span_for_page[q->start+i - stb__firstpage] = q;12639- stb__spanlist_add(q->len > 256 ? 256 : q->len, q);12640- }12641- }12642- return p;12643-}12644-12645-#define STB__MAX_SMALL_SIZE 3276812646-#define STB__MAX_SIZE_CLASSES 25612647-12648-static unsigned char stb__class_base[32];12649-static unsigned char stb__class_shift[32];12650-static unsigned char stb__pages_for_class[STB__MAX_SIZE_CLASSES];12651-static int stb__size_for_class[STB__MAX_SIZE_CLASSES];12652-12653-stb__span *stb__get_nonempty_sizeclass(int c)12654-{12655- int s = c + 256, i, size, tsize; // remap to span-list index12656- char *z;12657- void *q;12658- stb__span *p = stb__spanlist[s];12659- if (p) {12660- if (p->first_free) return p; // fast path: it's in the first one in list12661- for (p=p->next; p; p=p->next)12662- if (p->first_free) {12663- // move to front for future queries12664- stb__spanlist_unlink(p);12665- stb__spanlist_add(s, p);12666- return p;12667- }12668- }12669- // no non-empty ones, so allocate a new one12670- p = stb__alloc_span(stb__pages_for_class[c]);12671- if (!p) return NULL;12672- // create the free list up front12673- size = stb__size_for_class[c];12674- tsize = stb__pages_for_class[c] << stb__page_shift;12675- i = 0;12676- z = (char *) stb__page_address(p->start);12677- q = NULL;12678- while (i + size <= tsize) {12679- * (void **) z = q; q = z;12680- z += size;12681- i += size;12682- }12683- p->first_free = q;12684- p->allocations = 0;12685- stb__spanlist_add(s,p);12686- return p;12687-}12688-12689-static int stb__sizeclass(size_t sz)12690-{12691- int z = stb_log2_floor(sz); // -1 below to group e.g. 13,14,15,16 correctly12692- return stb__class_base[z] + ((sz-1) >> stb__class_shift[z]);12693-}12694-12695-static void stb__init_sizeclass(void)12696-{12697- int i, size, overhead;12698- int align_shift = 2; // allow 4-byte and 12-byte blocks as well, vs. TCMalloc12699- int next_class = 1;12700- int last_log = 0;12701-12702- for (i = 0; i < align_shift; i++) {12703- stb__class_base [i] = next_class;12704- stb__class_shift[i] = align_shift;12705- }12706-12707- for (size = 1 << align_shift; size <= STB__MAX_SMALL_SIZE; size += 1 << align_shift) {12708- i = stb_log2_floor(size);12709- if (i > last_log) {12710- if (size == 16) ++align_shift; // switch from 4-byte to 8-byte alignment12711- else if (size >= 128 && align_shift < 8) ++align_shift;12712- stb__class_base[i] = next_class - ((size-1) >> align_shift);12713- stb__class_shift[i] = align_shift;12714- last_log = i;12715- }12716- stb__size_for_class[next_class++] = size;12717- }12718-12719- for (i=1; i <= STB__MAX_SMALL_SIZE; ++i)12720- assert(i <= stb__size_for_class[stb__sizeclass(i)]);12721-12722- overhead = 0;12723- for (i = 1; i < next_class; i++) {12724- int s = stb__size_for_class[i];12725- size = stb__page_size;12726- while (size % s > size >> 3)12727- size += stb__page_size;12728- stb__pages_for_class[i] = (unsigned char) (size >> stb__page_shift);12729- overhead += size;12730- }12731- assert(overhead < (4 << 20)); // make sure it's under 4MB of overhead12732-}12733-12734-#ifdef STB_DEBUG12735-#define stb__smemset(a,b,c) memset((void *) a, b, c)12736-#elif defined(STB_FASTMALLOC_INIT)12737-#define stb__smemset(a,b,c) memset((void *) a, b, c)12738-#else12739-#define stb__smemset(a,b,c)12740-#endif12741-void *stb_smalloc(size_t sz)12742-{12743- stb__span *s;12744- if (sz == 0) return NULL;12745- if (stb__size_for_class[1] == 0) stb__init_sizeclass();12746- if (sz > STB__MAX_SMALL_SIZE) {12747- s = stb__alloc_span((sz + stb__page_size - 1) >> stb__page_shift);12748- if (s == NULL) return NULL;12749- s->list = 0;12750- s->next = s->prev = NULL;12751- s->allocations = -32767;12752- stb__smemset(stb__page_address(s->start), 0xcd, (sz+3)&~3);12753- return (void *) stb__page_address(s->start);12754- } else {12755- void *p;12756- int c = stb__sizeclass(sz);12757- s = stb__spanlist[256+c];12758- if (!s || !s->first_free)12759- s = stb__get_nonempty_sizeclass(c);12760- if (s == NULL) return NULL;12761- p = s->first_free;12762- s->first_free = * (void **) p;12763- ++s->allocations;12764- stb__smemset(p,0xcd, sz);12765- return p;12766- }12767-}12768-12769-int stb_ssize(void *p)12770-{12771- stb__span *s;12772- if (p == NULL) return 0;12773- s = stb__span_for_page[stb__page_number((stb_uint) p) - stb__firstpage];12774- if (s->list >= 256) {12775- return stb__size_for_class[s->list - 256];12776- } else {12777- assert(s->list == 0);12778- return s->len << stb__page_shift;12779- }12780-}12781-12782-void stb_sfree(void *p)12783-{12784- stb__span *s;12785- if (p == NULL) return;12786- s = stb__span_for_page[stb__page_number((stb_uint) p) - stb__firstpage];12787- if (s->list >= 256) {12788- stb__smemset(p, 0xfe, stb__size_for_class[s->list-256]);12789- * (void **) p = s->first_free;12790- s->first_free = p;12791- if (--s->allocations == 0) {12792- stb__spanlist_unlink(s);12793- stb__free_span(s);12794- }12795- } else {12796- assert(s->list == 0);12797- stb__smemset(p, 0xfe, stb_ssize(p));12798- stb__free_span(s);12799- }12800-}12801-12802-void *stb_srealloc(void *p, size_t sz)12803-{12804- size_t cur_size;12805- if (p == NULL) return stb_smalloc(sz);12806- if (sz == 0) { stb_sfree(p); return NULL; }12807- cur_size = stb_ssize(p);12808- if (sz > cur_size || sz <= (cur_size >> 1)) {12809- void *q;12810- if (sz > cur_size && sz < (cur_size << 1)) sz = cur_size << 1;12811- q = stb_smalloc(sz); if (q == NULL) return NULL;12812- memcpy(q, p, sz < cur_size ? sz : cur_size);12813- stb_sfree(p);12814- return q;12815- }12816- return p;12817-}12818-12819-void *stb_scalloc(size_t n, size_t sz)12820-{12821- void *p;12822- if (n == 0 || sz == 0) return NULL;12823- if (stb_log2_ceil(n) + stb_log2_ceil(n) >= 32) return NULL;12824- p = stb_smalloc(n*sz);12825- if (p) memset(p, 0, n*sz);12826- return p;12827-}12828-12829-char *stb_sstrdup(char *s)12830-{12831- int n = strlen(s);12832- char *p = (char *) stb_smalloc(n+1);12833- if (p) stb_p_strcpy_s(p,n+1,s);12834- return p;12835-}12836-#endif // STB_DEFINE12837-12838-12839-12840-//////////////////////////////////////////////////////////////////////////////12841-//12842-// Source code constants12843-//12844-// This is a trivial system to let you specify constants in source code,12845-// then while running you can change the constants.12846-//12847-// Note that you can't wrap the #defines, because we need to know their12848-// names. So we provide a pre-wrapped version without 'STB_' for convenience;12849-// to request it, #define STB_CONVENIENT_H, yielding:12850-// KI -- integer12851-// KU -- unsigned integer12852-// KF -- float12853-// KD -- double12854-// KS -- string constant12855-//12856-// Defaults to functioning in debug build, not in release builds.12857-// To force on, define STB_ALWAYS_H12858-12859-#ifdef STB_CONVENIENT_H12860-#define KI(x) STB_I(x)12861-#define KU(x) STB_UI(x)12862-#define KF(x) STB_F(x)12863-#define KD(x) STB_D(x)12864-#define KS(x) STB_S(x)12865-#endif12866-12867-STB_EXTERN void stb_source_path(char *str);12868-#ifdef STB_DEFINE12869-char *stb__source_path;12870-void stb_source_path(char *path)12871-{12872- stb__source_path = path;12873-}12874-12875-char *stb__get_sourcefile_path(char *file)12876-{12877- static char filebuf[512];12878- if (stb__source_path) {12879- stb_p_sprintf(filebuf stb_p_size(sizeof(filebuf)), "%s/%s", stb__source_path, file);12880- if (stb_fexists(filebuf)) return filebuf;12881- }12882-12883- if (stb_fexists(file)) return file;12884-12885- stb_p_sprintf(filebuf stb_p_size(sizeof(filebuf)), "../%s", file);12886- if (!stb_fexists(filebuf)) return filebuf;12887-12888- return file;12889-}12890-#endif12891-12892-#define STB_F(x) ((float) STB_H(x))12893-#define STB_UI(x) ((unsigned int) STB_I(x))12894-12895-#if !defined(STB_DEBUG) && !defined(STB_ALWAYS_H)12896-#define STB_D(x) ((double) (x))12897-#define STB_I(x) ((int) (x))12898-#define STB_S(x) ((char *) (x))12899-#else12900-#define STB_D(x) stb__double_constant(__FILE__, __LINE__-1, (x))12901-#define STB_I(x) stb__int_constant(__FILE__, __LINE__-1, (x))12902-#define STB_S(x) stb__string_constant(__FILE__, __LINE__-1, (x))12903-12904-STB_EXTERN double stb__double_constant(char *file, int line, double x);12905-STB_EXTERN int stb__int_constant(char *file, int line, int x);12906-STB_EXTERN char * stb__string_constant(char *file, int line, char *str);12907-12908-#ifdef STB_DEFINE12909-12910-enum12911-{12912- STB__CTYPE_int,12913- STB__CTYPE_uint,12914- STB__CTYPE_float,12915- STB__CTYPE_double,12916- STB__CTYPE_string,12917-};12918-12919-typedef struct12920-{12921- int line;12922- int type;12923- union {12924- int ival;12925- double dval;12926- char *sval;12927- };12928-} stb__Entry;12929-12930-typedef struct12931-{12932- stb__Entry *entries;12933- char *filename;12934- time_t timestamp;12935- char **file_data;12936- int file_len;12937- unsigned short *line_index;12938-} stb__FileEntry;12939-12940-static void stb__constant_parse(stb__FileEntry *f, int i)12941-{12942- char *s;12943- int n;12944- if (!stb_arr_valid(f->entries, i)) return;12945- n = f->entries[i].line;12946- if (n >= f->file_len) return;12947- s = f->file_data[n];12948- switch (f->entries[i].type) {12949- case STB__CTYPE_float:12950- while (*s) {12951- if (!strncmp(s, "STB_D(", 6)) { s+=6; goto matched_float; }12952- if (!strncmp(s, "STB_F(", 6)) { s+=6; goto matched_float; }12953- if (!strncmp(s, "KD(", 3)) { s+=3; goto matched_float; }12954- if (!strncmp(s, "KF(", 3)) { s+=3; goto matched_float; }12955- ++s;12956- }12957- break;12958- matched_float:12959- f->entries[i].dval = strtod(s, NULL);12960- break;12961- case STB__CTYPE_int:12962- while (*s) {12963- if (!strncmp(s, "STB_I(", 6)) { s+=6; goto matched_int; }12964- if (!strncmp(s, "STB_UI(", 7)) { s+=7; goto matched_int; }12965- if (!strncmp(s, "KI(", 3)) { s+=3; goto matched_int; }12966- if (!strncmp(s, "KU(", 3)) { s+=3; goto matched_int; }12967- ++s;12968- }12969- break;12970- matched_int: {12971- int neg=0;12972- s = stb_skipwhite(s);12973- while (*s == '-') { neg = !neg; s = stb_skipwhite(s+1); } // handle '- - 5', pointlessly12974- if (s[0] == '0' && tolower(s[1]) == 'x')12975- f->entries[i].ival = strtol(s, NULL, 16);12976- else if (s[0] == '0')12977- f->entries[i].ival = strtol(s, NULL, 8);12978- else12979- f->entries[i].ival = strtol(s, NULL, 10);12980- if (neg) f->entries[i].ival = -f->entries[i].ival;12981- break;12982- }12983- case STB__CTYPE_string:12984- // @TODO12985- break;12986- }12987-}12988-12989-static stb_sdict *stb__constant_file_hash;12990-12991-stb__Entry *stb__constant_get_entry(char *filename, int line, int type)12992-{12993- int i;12994- stb__FileEntry *f;12995- if (stb__constant_file_hash == NULL)12996- stb__constant_file_hash = stb_sdict_new(STB_TRUE);12997- f = (stb__FileEntry*) stb_sdict_get(stb__constant_file_hash, filename);12998- if (f == NULL) {12999- char *s = stb__get_sourcefile_path(filename);13000- if (s == NULL || !stb_fexists(s)) return 0;13001- f = (stb__FileEntry *) malloc(sizeof(*f));13002- f->timestamp = stb_ftimestamp(s);13003- f->file_data = stb_stringfile(s, &f->file_len);13004- f->filename = stb_p_strdup(s); // cache the full path13005- f->entries = NULL;13006- f->line_index = 0;13007- stb_arr_setlen(f->line_index, f->file_len);13008- memset(f->line_index, 0xff, stb_arr_storage(f->line_index));13009- } else {13010- time_t t = stb_ftimestamp(f->filename);13011- if (f->timestamp != t) {13012- f->timestamp = t;13013- free(f->file_data);13014- f->file_data = stb_stringfile(f->filename, &f->file_len);13015- stb_arr_setlen(f->line_index, f->file_len);13016- for (i=0; i < stb_arr_len(f->entries); ++i)13017- stb__constant_parse(f, i);13018- }13019- }13020-13021- if (line >= f->file_len) return 0;13022-13023- if (f->line_index[line] >= stb_arr_len(f->entries)) {13024- // need a new entry13025- int n = stb_arr_len(f->entries);13026- stb__Entry e;13027- e.line = line;13028- if (line < f->file_len)13029- f->line_index[line] = n;13030- e.type = type;13031- stb_arr_push(f->entries, e);13032- stb__constant_parse(f, n);13033- }13034- return f->entries + f->line_index[line];13035-}13036-13037-double stb__double_constant(char *file, int line, double x)13038-{13039- stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_float);13040- if (!e) return x;13041- return e->dval;13042-}13043-13044-int stb__int_constant(char *file, int line, int x)13045-{13046- stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_int);13047- if (!e) return x;13048- return e->ival;13049-}13050-13051-char * stb__string_constant(char *file, int line, char *x)13052-{13053- stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_string);13054- if (!e) return x;13055- return e->sval;13056-}13057-13058-#endif // STB_DEFINE13059-#endif // !STB_DEBUG && !STB_ALWAYS_H13060-13061-13062-#ifdef STB_STUA13063-#error "STUA is no longer supported"13064-//////////////////////////////////////////////////////////////////////////13065-//13066-// stua: little scripting language13067-//13068-// define STB_STUA to compile it13069-//13070-// see http://nothings.org/stb/stb_stua.html for documentation13071-//13072-// basic parsing model:13073-//13074-// lexical analysis13075-// use stb_lex() to parse tokens; keywords get their own tokens13076-//13077-// parsing:13078-// recursive descent parser. too much of a hassle to make an unambiguous13079-// LR(1) grammar, and one-pass generation is clumsier (recursive descent13080-// makes it easier to e.g. compile nested functions). on the other hand,13081-// dictionary syntax required hackery to get extra lookahead.13082-//13083-// codegen:13084-// output into an evaluation tree, using array indices as 'pointers'13085-//13086-// run:13087-// traverse the tree; support for 'break/continue/return' is tricky13088-//13089-// garbage collection:13090-// stu__mark and sweep; explicit stack with non-stu__compile_global_scope roots13091-13092-typedef stb_int32 stua_obj;13093-13094-typedef stb_idict stua_dict;13095-13096-STB_EXTERN void stua_run_script(char *s);13097-STB_EXTERN void stua_uninit(void);13098-13099-extern stua_obj stua_globals;13100-13101-STB_EXTERN double stua_number(stua_obj z);13102-13103-STB_EXTERN stua_obj stua_getnil(void);13104-STB_EXTERN stua_obj stua_getfalse(void);13105-STB_EXTERN stua_obj stua_gettrue(void);13106-STB_EXTERN stua_obj stua_string(char *z);13107-STB_EXTERN stua_obj stua_make_number(double d);13108-STB_EXTERN stua_obj stua_box(int type, void *data, int size);13109-13110-enum13111-{13112- STUA_op_negate=129,13113- STUA_op_shl, STUA_op_ge,13114- STUA_op_shr, STUA_op_le,13115- STUA_op_shru,13116- STUA_op_last13117-};13118-13119-#define STUA_NO_VALUE 2 // equivalent to a tagged NULL13120-STB_EXTERN stua_obj (*stua_overload)(int op, stua_obj a, stua_obj b, stua_obj c);13121-13122-STB_EXTERN stua_obj stua_error(char *err, ...);13123-13124-STB_EXTERN stua_obj stua_pushroot(stua_obj o);13125-STB_EXTERN void stua_poproot ( void );13126-13127-13128-#ifdef STB_DEFINE13129-// INTERPRETER13130-13131-// 31-bit floating point implementation13132-// force the (1 << 30) bit (2nd highest bit) to be zero by re-biasing the exponent;13133-// then shift and set the bottom bit13134-13135-static stua_obj stu__floatp(float *f)13136-{13137- unsigned int n = *(unsigned int *) f;13138- unsigned int e = n & (0xff << 23);13139-13140- assert(sizeof(int) == 4 && sizeof(float) == 4);13141-13142- if (!e) // zero?13143- n = n; // no change13144- else if (e < (64 << 23)) // underflow of the packed encoding?13145- n = (n & 0x80000000); // signed 013146- else if (e > (190 << 23)) // overflow of the encoding? (or INF or NAN)13147- n = (n & 0x80000000) + (127 << 23); // new INF encoding13148- else13149- n -= 0x20000000;13150-13151- // now we need to shuffle the bits so that the spare bit is at the bottom13152- assert((n & 0x40000000) == 0);13153- return (n & 0x80000000) + (n << 1) + 1;13154-}13155-13156-static unsigned char stu__getfloat_addend[256];13157-static float stu__getfloat(stua_obj v)13158-{13159- unsigned int n;13160- unsigned int e = ((unsigned int) v) >> 24;13161-13162- n = (int) v >> 1; // preserve high bit13163- n += stu__getfloat_addend[e] << 24;13164- return *(float *) &n;13165-}13166-13167-stua_obj stua_float(float f)13168-{13169- return stu__floatp(&f);13170-}13171-13172-static void stu__float_init(void)13173-{13174- int i;13175- stu__getfloat_addend[0] = 0; // do nothing to biased exponent of 013176- for (i=1; i < 127; ++i)13177- stu__getfloat_addend[i] = 32; // undo the -0x2000000013178- stu__getfloat_addend[127] = 64; // convert packed INF to INF (0x3f -> 0x7f)13179-13180- for (i=0; i < 128; ++i) // for signed floats, remove the bit we just shifted down13181- stu__getfloat_addend[128+i] = stu__getfloat_addend[i] - 64;13182-}13183-13184-// Tagged data type implementation13185-13186- // TAGS:13187-#define stu__int_tag 0 // of 2 bits // 00 int13188-#define stu__float_tag 1 // of 1 bit // 01 float13189-#define stu__ptr_tag 2 // of 2 bits // 10 boxed13190- // 11 float13191-13192-#define stu__tag(x) ((x) & 3)13193-#define stu__number(x) (stu__tag(x) != stu__ptr_tag)13194-#define stu__isint(x) (stu__tag(x) == stu__int_tag)13195-13196-#define stu__int(x) ((x) >> 2)13197-#define stu__float(x) (stu__getfloat(x))13198-13199-#define stu__makeint(v) ((v)*4+stu__int_tag)13200-13201-// boxed data, and tag support for boxed data13202-13203-enum13204-{13205- STU___float = 1, STU___int = 2,13206- STU___number = 3, STU___string = 4,13207- STU___function = 5, STU___dict = 6,13208- STU___boolean = 7, STU___error = 8,13209-};13210-13211-// boxed data13212-#define STU__BOX short type, stua_gc13213-typedef struct stu__box { STU__BOX; } stu__box;13214-13215-stu__box stu__nil = { 0, 1 };13216-stu__box stu__true = { STU___boolean, 1, };13217-stu__box stu__false = { STU___boolean, 1, };13218-13219-#define stu__makeptr(v) ((stua_obj) (v) + stu__ptr_tag)13220-13221-#define stua_nil stu__makeptr(&stu__nil)13222-#define stua_true stu__makeptr(&stu__true)13223-#define stua_false stu__makeptr(&stu__false)13224-13225-stua_obj stua_getnil(void) { return stua_nil; }13226-stua_obj stua_getfalse(void) { return stua_false; }13227-stua_obj stua_gettrue(void) { return stua_true; }13228-13229-#define stu__ptr(x) ((stu__box *) ((x) - stu__ptr_tag))13230-13231-#define stu__checkt(t,x) ((t) == STU___float ? ((x) & 1) == stu__float_tag : \13232- (t) == STU___int ? stu__isint(x) : \13233- (t) == STU___number ? stu__number(x) : \13234- stu__tag(x) == stu__ptr_tag && stu__ptr(x)->type == (t))13235-13236-typedef struct13237-{13238- STU__BOX;13239- void *ptr;13240-} stu__wrapper;13241-13242-// implementation of a 'function' or function + closure13243-13244-typedef struct stu__func13245-{13246- STU__BOX;13247- stua_obj closure_source; // 0 - regular function; 4 - C function13248- // if closure, pointer to source function13249- union {13250- stua_obj closure_data; // partial-application data13251- void *store; // pointer to free that holds 'code'13252- stua_obj (*func)(stua_dict *context);13253- } f;13254- // closure ends here13255- short *code;13256- int num_param;13257- stua_obj *param; // list of parameter strings13258-} stu__func;13259-13260-// apply this to 'short *code' to get at data13261-#define stu__const(f) ((stua_obj *) (f))13262-13263-static void stu__free_func(stu__func *f)13264-{13265- if (f->closure_source == 0) free(f->f.store);13266- if ((stb_uint) f->closure_source <= 4) free(f->param);13267- free(f);13268-}13269-13270-#define stu__pd(x) ((stua_dict *) stu__ptr(x))13271-#define stu__pw(x) ((stu__wrapper *) stu__ptr(x))13272-#define stu__pf(x) ((stu__func *) stu__ptr(x))13273-13274-13275-// garbage-collection13276-13277-13278-static stu__box ** stu__gc_ptrlist;13279-static stua_obj * stu__gc_root_stack;13280-13281-stua_obj stua_pushroot(stua_obj o) { stb_arr_push(stu__gc_root_stack, o); return o; }13282-void stua_poproot ( void ) { stb_arr_pop(stu__gc_root_stack); }13283-13284-static stb_sdict *stu__strings;13285-static void stu__mark(stua_obj z)13286-{13287- int i;13288- stu__box *p = stu__ptr(z);13289- if (p->stua_gc == 1) return; // already marked13290- assert(p->stua_gc == 0);13291- p->stua_gc = 1;13292- switch(p->type) {13293- case STU___function: {13294- stu__func *f = (stu__func *) p;13295- if ((stb_uint) f->closure_source <= 4) {13296- if (f->closure_source == 0) {13297- for (i=1; i <= f->code[0]; ++i)13298- if (!stu__number(((stua_obj *) f->code)[-i]))13299- stu__mark(((stua_obj *) f->code)[-i]);13300- }13301- for (i=0; i < f->num_param; ++i)13302- stu__mark(f->param[i]);13303- } else {13304- stu__mark(f->closure_source);13305- stu__mark(f->f.closure_data);13306- }13307- break;13308- }13309- case STU___dict: {13310- stua_dict *e = (stua_dict *) p;13311- for (i=0; i < e->limit; ++i)13312- if (e->table[i].k != STB_IEMPTY && e->table[i].k != STB_IDEL) {13313- if (!stu__number(e->table[i].k)) stu__mark((int) e->table[i].k);13314- if (!stu__number(e->table[i].v)) stu__mark((int) e->table[i].v);13315- }13316- break;13317- }13318- }13319-}13320-13321-static int stu__num_allocs, stu__size_allocs;13322-static stua_obj stu__flow_val = stua_nil; // used for break & return13323-13324-static void stua_gc(int force)13325-{13326- int i;13327- if (!force && stu__num_allocs == 0 && stu__size_allocs == 0) return;13328- stu__num_allocs = stu__size_allocs = 0;13329- //printf("[gc]\n");13330-13331- // clear marks13332- for (i=0; i < stb_arr_len(stu__gc_ptrlist); ++i)13333- stu__gc_ptrlist[i]->stua_gc = 0;13334-13335- // stu__mark everything reachable13336- stu__nil.stua_gc = stu__true.stua_gc = stu__false.stua_gc = 1;13337- stu__mark(stua_globals);13338- if (!stu__number(stu__flow_val))13339- stu__mark(stu__flow_val);13340- for (i=0; i < stb_arr_len(stu__gc_root_stack); ++i)13341- if (!stu__number(stu__gc_root_stack[i]))13342- stu__mark(stu__gc_root_stack[i]);13343-13344- // sweep unreachables13345- for (i=0; i < stb_arr_len(stu__gc_ptrlist);) {13346- stu__box *z = stu__gc_ptrlist[i];13347- if (!z->stua_gc) {13348- switch (z->type) {13349- case STU___dict: stb_idict_destroy((stua_dict *) z); break;13350- case STU___error: free(((stu__wrapper *) z)->ptr); break;13351- case STU___string: stb_sdict_remove(stu__strings, (char*) ((stu__wrapper *) z)->ptr, NULL); free(z); break;13352- case STU___function: stu__free_func((stu__func *) z); break;13353- }13354- // swap in the last item over this, and repeat13355- z = stb_arr_pop(stu__gc_ptrlist);13356- stu__gc_ptrlist[i] = z;13357- } else13358- ++i;13359- }13360-}13361-13362-static void stu__consider_gc(stua_obj x)13363-{13364- if (stu__size_allocs < 100000) return;13365- if (stu__num_allocs < 10 && stu__size_allocs < 1000000) return;13366- stb_arr_push(stu__gc_root_stack, x);13367- stua_gc(0);13368- stb_arr_pop(stu__gc_root_stack);13369-}13370-13371-static stua_obj stu__makeobj(int type, void *data, int size, int safe_to_gc)13372-{13373- stua_obj x = stu__makeptr(data);13374- ((stu__box *) data)->type = type;13375- stb_arr_push(stu__gc_ptrlist, (stu__box *) data);13376- stu__num_allocs += 1;13377- stu__size_allocs += size;13378- if (safe_to_gc) stu__consider_gc(x);13379- return x;13380-}13381-13382-stua_obj stua_box(int type, void *data, int size)13383-{13384- stu__wrapper *p = (stu__wrapper *) malloc(sizeof(*p));13385- p->ptr = data;13386- return stu__makeobj(type, p, size, 0);13387-}13388-13389-// a stu string can be directly compared for equality, because13390-// they go into a hash table13391-stua_obj stua_string(char *z)13392-{13393- stu__wrapper *b = (stu__wrapper *) stb_sdict_get(stu__strings, z);13394- if (b == NULL) {13395- int o = stua_box(STU___string, NULL, strlen(z) + sizeof(*b));13396- b = stu__pw(o);13397- stb_sdict_add(stu__strings, z, b);13398- stb_sdict_getkey(stu__strings, z, (char **) &b->ptr);13399- }13400- return stu__makeptr(b);13401-}13402-13403-// stb_obj dictionary is just an stb_idict13404-static void stu__set(stua_dict *d, stua_obj k, stua_obj v)13405-{ if (stb_idict_set(d, k, v)) stu__size_allocs += 8; }13406-13407-static stua_obj stu__get(stua_dict *d, stua_obj k, stua_obj res)13408-{13409- stb_idict_get_flag(d, k, &res);13410- return res;13411-}13412-13413-static stua_obj make_string(char *z, int len)13414-{13415- stua_obj s;13416- char temp[256], *q = (char *) stb_temp(temp, len+1), *p = q;13417- while (len > 0) {13418- if (*z == '\\') {13419- if (z[1] == 'n') *p = '\n';13420- else if (z[1] == 'r') *p = '\r';13421- else if (z[1] == 't') *p = '\t';13422- else *p = z[1];13423- p += 1; z += 2; len -= 2;13424- } else {13425- *p++ = *z++; len -= 1;13426- }13427- }13428- *p = 0;13429- s = stua_string(q);13430- stb_tempfree(temp, q);13431- return s;13432-}13433-13434-enum token_names13435-{13436- T__none=128,13437- ST_shl = STUA_op_shl, ST_ge = STUA_op_ge,13438- ST_shr = STUA_op_shr, ST_le = STUA_op_le,13439- ST_shru = STUA_op_shru, STU__negate = STUA_op_negate,13440- ST__reset_numbering = STUA_op_last,13441- ST_white,13442- ST_id, ST_float, ST_decimal, ST_hex, ST_char,ST_string, ST_number,13443- // make sure the keywords come _AFTER_ ST_id, so stb_lex prefer them13444- ST_if, ST_while, ST_for, ST_eq, ST_nil,13445- ST_then, ST_do, ST_in, ST_ne, ST_true,13446- ST_else, ST_break, ST_let, ST_and, ST_false,13447- ST_elseif, ST_continue, ST_into, ST_or, ST_repeat,13448- ST_end, ST_as, ST_return, ST_var, ST_func,13449- ST_catch, ST__frame,13450- ST__max_terminals,13451-13452- STU__defaultparm, STU__seq,13453-};13454-13455-static stua_dict * stu__globaldict;13456- stua_obj stua_globals;13457-13458-static enum13459-{13460- FLOW_normal, FLOW_continue, FLOW_break, FLOW_return, FLOW_error,13461-} stu__flow;13462-13463-stua_obj stua_error(char *z, ...)13464-{13465- stua_obj a;13466- char temp[4096], *x;13467- va_list v; va_start(v,z); vsprintf(temp, z, v); va_end(v);13468- x = stb_p_strdup(temp);13469- a = stua_box(STU___error, x, strlen(x));13470- stu__flow = FLOW_error;13471- stu__flow_val = a;13472- return stua_nil;13473-}13474-13475-double stua_number(stua_obj z)13476-{13477- return stu__tag(z) == stu__int_tag ? stu__int(z) : stu__float(z);13478-}13479-13480-stua_obj stua_make_number(double d)13481-{13482- double e = floor(d);13483- if (e == d && e < (1 << 29) && e >= -(1 << 29))13484- return stu__makeint((int) e);13485- else13486- return stua_float((float) d);13487-}13488-13489-stua_obj (*stua_overload)(int op, stua_obj a, stua_obj b, stua_obj c) = NULL;13490-13491-static stua_obj stu__op(int op, stua_obj a, stua_obj b, stua_obj c)13492-{13493- stua_obj r = STUA_NO_VALUE;13494- if (op == '+') {13495- if (stu__checkt(STU___string, a) && stu__checkt(STU___string, b)) {13496- ;// @TODO: string concatenation13497- } else if (stu__checkt(STU___function, a) && stu__checkt(STU___dict, b)) {13498- stu__func *f = (stu__func *) malloc(12);13499- assert(offsetof(stu__func, code)==12);13500- f->closure_source = a;13501- f->f.closure_data = b;13502- return stu__makeobj(STU___function, f, 16, 1);13503- }13504- }13505- if (stua_overload) r = stua_overload(op,a,b,c);13506- if (stu__flow != FLOW_error && r == STUA_NO_VALUE)13507- stua_error("Typecheck for operator %d", op), r=stua_nil;13508- return r;13509-}13510-13511-#define STU__EVAL2(a,b) \13512- a = stu__eval(stu__f[n+1]); if (stu__flow) break; stua_pushroot(a); \13513- b = stu__eval(stu__f[n+2]); stua_poproot(); if (stu__flow) break;13514-13515-#define STU__FB(op) \13516- STU__EVAL2(a,b) \13517- if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag) \13518- return ((a) op (b)); \13519- if (stu__number(a) && stu__number(b)) \13520- return stua_make_number(stua_number(a) op stua_number(b)); \13521- return stu__op(stu__f[n], a,b, stua_nil)13522-13523-#define STU__F(op) \13524- STU__EVAL2(a,b) \13525- if (stu__number(a) && stu__number(b)) \13526- return stua_make_number(stua_number(a) op stua_number(b)); \13527- return stu__op(stu__f[n], a,b, stua_nil)13528-13529-#define STU__I(op) \13530- STU__EVAL2(a,b) \13531- if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag) \13532- return stu__makeint(stu__int(a) op stu__int(b)); \13533- return stu__op(stu__f[n], a,b, stua_nil)13534-13535-#define STU__C(op) \13536- STU__EVAL2(a,b) \13537- if (stu__number(a) && stu__number(b)) \13538- return (stua_number(a) op stua_number(b)) ? stua_true : stua_false; \13539- return stu__op(stu__f[n], a,b, stua_nil)13540-13541-#define STU__CE(op) \13542- STU__EVAL2(a,b) \13543- return (a op b) ? stua_true : stua_false13544-13545-static short *stu__f;13546-static stua_obj stu__f_obj;13547-static stua_dict *stu__c;13548-static stua_obj stu__funceval(stua_obj fo, stua_obj co);13549-13550-static int stu__cond(stua_obj x)13551-{13552- if (stu__flow) return 0;13553- if (!stu__checkt(STU___boolean, x))13554- x = stu__op('!', x, stua_nil, stua_nil);13555- if (x == stua_true ) return 1;13556- if (x == stua_false) return 0;13557- stu__flow = FLOW_error;13558- return 0;13559-}13560-13561-// had to manually eliminate tailcall recursion for debugging complex stuff13562-#define TAILCALL(x) n = (x); goto top;13563-static stua_obj stu__eval(int n)13564-{13565-top:13566- if (stu__flow >= FLOW_return) return stua_nil; // is this needed?13567- if (n < 0) return stu__const(stu__f)[n];13568- assert(n != 0 && n != 1);13569- switch (stu__f[n]) {13570- stua_obj a,b,c;13571- case ST_catch: a = stu__eval(stu__f[n+1]);13572- if (stu__flow == FLOW_error) { a=stu__flow_val; stu__flow = FLOW_normal; }13573- return a;13574- case ST_var: b = stu__eval(stu__f[n+2]); if (stu__flow) break;13575- stu__set(stu__c, stu__const(stu__f)[stu__f[n+1]], b);13576- return b;13577- case STU__seq: stu__eval(stu__f[n+1]); if (stu__flow) break;13578- TAILCALL(stu__f[n+2]);13579- case ST_if: if (!stu__cond(stu__eval(stu__f[n+1]))) return stua_nil;13580- TAILCALL(stu__f[n+2]);13581- case ST_else: a = stu__cond(stu__eval(stu__f[n+1]));13582- TAILCALL(stu__f[n + 2 + !a]);13583- #define STU__HANDLE_BREAK \13584- if (stu__flow >= FLOW_break) { \13585- if (stu__flow == FLOW_break) { \13586- a = stu__flow_val; \13587- stu__flow = FLOW_normal; \13588- stu__flow_val = stua_nil; \13589- return a; \13590- } \13591- return stua_nil; \13592- }13593- case ST_as: stu__eval(stu__f[n+3]);13594- STU__HANDLE_BREAK13595- // fallthrough!13596- case ST_while: a = stua_nil; stua_pushroot(a);13597- while (stu__cond(stu__eval(stu__f[n+1]))) {13598- stua_poproot();13599- a = stu__eval(stu__f[n+2]);13600- STU__HANDLE_BREAK13601- stu__flow = FLOW_normal; // clear 'continue' flag13602- stua_pushroot(a);13603- if (stu__f[n+3]) stu__eval(stu__f[n+3]);13604- STU__HANDLE_BREAK13605- stu__flow = FLOW_normal; // clear 'continue' flag13606- }13607- stua_poproot();13608- return a;13609- case ST_break: stu__flow = FLOW_break; stu__flow_val = stu__eval(stu__f[n+1]); break;13610- case ST_continue:stu__flow = FLOW_continue; break;13611- case ST_return: stu__flow = FLOW_return; stu__flow_val = stu__eval(stu__f[n+1]); break;13612- case ST__frame: return stu__f_obj;13613- case '[': STU__EVAL2(a,b);13614- if (stu__checkt(STU___dict, a))13615- return stu__get(stu__pd(a), b, stua_nil);13616- return stu__op(stu__f[n], a, b, stua_nil);13617- case '=': a = stu__eval(stu__f[n+2]); if (stu__flow) break;13618- n = stu__f[n+1];13619- if (stu__f[n] == ST_id) {13620- if (!stb_idict_update(stu__c, stu__const(stu__f)[stu__f[n+1]], a))13621- if (!stb_idict_update(stu__globaldict, stu__const(stu__f)[stu__f[n+1]], a))13622- return stua_error("Assignment to undefined variable");13623- } else if (stu__f[n] == '[') {13624- stua_pushroot(a);13625- b = stu__eval(stu__f[n+1]); if (stu__flow) { stua_poproot(); break; }13626- stua_pushroot(b);13627- c = stu__eval(stu__f[n+2]); stua_poproot(); stua_poproot();13628- if (stu__flow) break;13629- if (!stu__checkt(STU___dict, b)) return stua_nil;13630- stu__set(stu__pd(b), c, a);13631- } else {13632- return stu__op(stu__f[n], stu__eval(n), a, stua_nil);13633- }13634- return a;13635- case STU__defaultparm:13636- a = stu__eval(stu__f[n+2]);13637- stu__flow = FLOW_normal;13638- if (stb_idict_add(stu__c, stu__const(stu__f)[stu__f[n+1]], a))13639- stu__size_allocs += 8;13640- return stua_nil;13641- case ST_id: a = stu__get(stu__c, stu__const(stu__f)[stu__f[n+1]], STUA_NO_VALUE); // try local variable13642- return a != STUA_NO_VALUE // else try stu__compile_global_scope variable13643- ? a : stu__get(stu__globaldict, stu__const(stu__f)[stu__f[n+1]], stua_nil);13644- case STU__negate:a = stu__eval(stu__f[n+1]); if (stu__flow) break;13645- return stu__isint(a) ? -a : stu__op(stu__f[n], a, stua_nil, stua_nil);13646- case '~': a = stu__eval(stu__f[n+1]); if (stu__flow) break;13647- return stu__isint(a) ? (~a)&~3 : stu__op(stu__f[n], a, stua_nil, stua_nil);13648- case '!': a = stu__eval(stu__f[n+1]); if (stu__flow) break;13649- a = stu__cond(a); if (stu__flow) break;13650- return a ? stua_true : stua_false;13651- case ST_eq: STU__CE(==); case ST_le: STU__C(<=); case '<': STU__C(<);13652- case ST_ne: STU__CE(!=); case ST_ge: STU__C(>=); case '>': STU__C(>);13653- case '+' : STU__FB(+); case '*': STU__F(*); case '&': STU__I(&); case ST_shl: STU__I(<<);13654- case '-' : STU__FB(-); case '/': STU__F(/); case '|': STU__I(|); case ST_shr: STU__I(>>);13655- case '%': STU__I(%); case '^': STU__I(^);13656- case ST_shru: STU__EVAL2(a,b);13657- if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag)13658- return stu__makeint((unsigned) stu__int(a) >> stu__int(b));13659- return stu__op(stu__f[n], a,b, stua_nil);13660- case ST_and: a = stu__eval(stu__f[n+1]); b = stu__cond(a); if (stu__flow) break;13661- return a ? stu__eval(stu__f[n+2]) : a;13662- case ST_or : a = stu__eval(stu__f[n+1]); b = stu__cond(a); if (stu__flow) break;13663- return a ? b : stu__eval(stu__f[n+2]);13664- case'(':case':': STU__EVAL2(a,b);13665- if (!stu__checkt(STU___function, a))13666- return stu__op(stu__f[n], a,b, stua_nil);13667- if (!stu__checkt(STU___dict, b))13668- return stua_nil;13669- if (stu__f[n] == ':')13670- b = stu__makeobj(STU___dict, stb_idict_copy(stu__pd(b)), stb_idict_memory_usage(stu__pd(b)), 0);13671- a = stu__funceval(a,b);13672- return a;13673- case '{' : {13674- stua_dict *d;13675- d = stb_idict_new_size(stu__f[n+1] > 40 ? 64 : 16);13676- if (d == NULL)13677- return stua_nil; // breakpoint fodder13678- c = stu__makeobj(STU___dict, d, 32, 1);13679- stua_pushroot(c);13680- a = stu__f[n+1];13681- for (b=0; b < a; ++b) {13682- stua_obj x = stua_pushroot(stu__eval(stu__f[n+2 + b*2 + 0]));13683- stua_obj y = stu__eval(stu__f[n+2 + b*2 + 1]);13684- stua_poproot();13685- if (stu__flow) { stua_poproot(); return stua_nil; }13686- stu__set(d, x, y);13687- }13688- stua_poproot();13689- return c;13690- }13691- default: if (stu__f[n] < 0) return stu__const(stu__f)[stu__f[n]];13692- assert(0); /* NOTREACHED */ // internal error!13693- }13694- return stua_nil;13695-}13696-13697-int stb__stua_nesting;13698-static stua_obj stu__funceval(stua_obj fo, stua_obj co)13699-{13700- stu__func *f = stu__pf(fo);13701- stua_dict *context = stu__pd(co);13702- int i,j;13703- stua_obj p;13704- short *tf = stu__f; // save previous function13705- stua_dict *tc = stu__c;13706-13707- if (stu__flow == FLOW_error) return stua_nil;13708- assert(stu__flow == FLOW_normal);13709-13710- stua_pushroot(fo);13711- stua_pushroot(co);13712- stu__consider_gc(stua_nil);13713-13714- while ((stb_uint) f->closure_source > 4) {13715- // add data from closure to context13716- stua_dict *e = (stua_dict *) stu__pd(f->f.closure_data);13717- for (i=0; i < e->limit; ++i)13718- if (e->table[i].k != STB_IEMPTY && e->table[i].k != STB_IDEL)13719- if (stb_idict_add(context, e->table[i].k, e->table[i].v))13720- stu__size_allocs += 8;13721- // use add so if it's already defined, we don't override it; that way13722- // explicit parameters win over applied ones, and most recent applications13723- // win over previous ones13724- f = stu__pf(f->closure_source);13725- }13726-13727- for (j=0, i=0; i < f->num_param; ++i)13728- // if it doesn't already exist, add it from the numbered parameters13729- if (stb_idict_add(context, f->param[i], stu__get(context, stu__int(j), stua_nil)))13730- ++j;13731-13732- // @TODO: if (stu__get(context, stu__int(f->num_param+1)) != STUA_NO_VALUE) // error: too many parameters13733- // @TODO: ditto too few parameters13734-13735- if (f->closure_source == 4)13736- p = f->f.func(context);13737- else {13738- stu__f = f->code, stu__c = context;13739- stu__f_obj = co;13740- ++stb__stua_nesting;13741- if (stu__f[1])13742- p = stu__eval(stu__f[1]);13743- else13744- p = stua_nil;13745- --stb__stua_nesting;13746- stu__f = tf, stu__c = tc; // restore previous function13747- if (stu__flow == FLOW_return) {13748- stu__flow = FLOW_normal;13749- p = stu__flow_val;13750- stu__flow_val = stua_nil;13751- }13752- }13753-13754- stua_poproot();13755- stua_poproot();13756-13757- return p;13758-}13759-13760-// Parser13761-13762-static int stu__tok;13763-static stua_obj stu__tokval;13764-13765-static char *stu__curbuf, *stu__bufstart;13766-13767-static stb_matcher *stu__lex_matcher;13768-13769-static unsigned char stu__prec[ST__max_terminals], stu__end[ST__max_terminals];13770-13771-static void stu__nexttoken(void)13772-{13773- int len;13774-13775-retry:13776- stu__tok = stb_lex(stu__lex_matcher, stu__curbuf, &len);13777- if (stu__tok == 0)13778- return;13779- switch(stu__tok) {13780- case ST_white : stu__curbuf += len; goto retry;13781- case T__none : stu__tok = *stu__curbuf; break;13782- case ST_string: stu__tokval = make_string(stu__curbuf+1, len-2); break;13783- case ST_id : stu__tokval = make_string(stu__curbuf, len); break;13784- case ST_hex : stu__tokval = stu__makeint(strtol(stu__curbuf+2,NULL,16)); stu__tok = ST_number; break;13785- case ST_decimal: stu__tokval = stu__makeint(strtol(stu__curbuf ,NULL,10)); stu__tok = ST_number; break;13786- case ST_float : stu__tokval = stua_float((float) atof(stu__curbuf)) ; stu__tok = ST_number; break;13787- case ST_char : stu__tokval = stu__curbuf[2] == '\\' ? stu__curbuf[3] : stu__curbuf[2];13788- if (stu__curbuf[3] == 't') stu__tokval = '\t';13789- if (stu__curbuf[3] == 'n') stu__tokval = '\n';13790- if (stu__curbuf[3] == 'r') stu__tokval = '\r';13791- stu__tokval = stu__makeint(stu__tokval);13792- stu__tok = ST_number;13793- break;13794- }13795- stu__curbuf += len;13796-}13797-13798-static struct { int stu__tok; char *regex; } stu__lexemes[] =13799-{13800- ST_white , "([ \t\n\r]|/\\*(.|\n)*\\*/|//[^\r\n]*([\r\n]|$))+",13801- ST_id , "[_a-zA-Z][_a-zA-Z0-9]*",13802- ST_hex , "0x[0-9a-fA-F]+",13803- ST_decimal, "[0-9]+[0-9]*",13804- ST_float , "[0-9]+\\.?[0-9]*([eE][-+]?[0-9]+)?",13805- ST_float , "\\.[0-9]+([eE][-+]?[0-9]+)?",13806- ST_char , "c'(\\\\.|[^\\'])'",13807- ST_string , "\"(\\\\.|[^\\\"\n\r])*\"",13808- ST_string , "\'(\\\\.|[^\\\'\n\r])*\'",13809-13810- #define stua_key4(a,b,c,d) ST_##a, #a, ST_##b, #b, ST_##c, #c, ST_##d, #d,13811- stua_key4(if,then,else,elseif) stua_key4(while,do,for,in)13812- stua_key4(func,var,let,break) stua_key4(nil,true,false,end)13813- stua_key4(return,continue,as,repeat) stua_key4(_frame,catch,catch,catch)13814-13815- ST_shl, "<<", ST_and, "&&", ST_eq, "==", ST_ge, ">=",13816- ST_shr, ">>", ST_or , "||", ST_ne, "!=", ST_le, "<=",13817- ST_shru,">>>", ST_into, "=>",13818- T__none, ".",13819-};13820-13821-typedef struct13822-{13823- stua_obj *data; // constants being compiled13824- short *code; // code being compiled13825- stua_dict *locals;13826- short *non_local_refs;13827-} stu__comp_func;13828-13829-static stu__comp_func stu__pfunc;13830-static stu__comp_func *func_stack = NULL;13831-static void stu__push_func_comp(void)13832-{13833- stb_arr_push(func_stack, stu__pfunc);13834- stu__pfunc.data = NULL;13835- stu__pfunc.code = NULL;13836- stu__pfunc.locals = stb_idict_new_size(16);13837- stu__pfunc.non_local_refs = NULL;13838- stb_arr_push(stu__pfunc.code, 0); // number of data items13839- stb_arr_push(stu__pfunc.code, 1); // starting execution address13840-}13841-13842-static void stu__pop_func_comp(void)13843-{13844- stb_arr_free(stu__pfunc.code);13845- stb_arr_free(stu__pfunc.data);13846- stb_idict_destroy(stu__pfunc.locals);13847- stb_arr_free(stu__pfunc.non_local_refs);13848- stu__pfunc = stb_arr_pop(func_stack);13849-}13850-13851-// if an id is a reference to an outer lexical scope, this13852-// function returns the "name" of it, and updates the stack13853-// structures to make sure the names are propagated in.13854-static int stu__nonlocal_id(stua_obj var_obj)13855-{13856- stua_obj dummy, var = var_obj;13857- int i, n = stb_arr_len(func_stack), j,k;13858- if (stb_idict_get_flag(stu__pfunc.locals, var, &dummy)) return 0;13859- for (i=n-1; i > 1; --i) {13860- if (stb_idict_get_flag(func_stack[i].locals, var, &dummy))13861- break;13862- }13863- if (i <= 1) return 0; // stu__compile_global_scope13864- j = i; // need to access variable from j'th frame13865- for (i=0; i < stb_arr_len(stu__pfunc.non_local_refs); ++i)13866- if (stu__pfunc.non_local_refs[i] == j) return j-n;13867- stb_arr_push(stu__pfunc.non_local_refs, j-n);13868- // now make sure all the parents propagate it down13869- for (k=n-1; k > 1; --k) {13870- if (j-k >= 0) return j-n; // comes direct from this parent13871- for(i=0; i < stb_arr_len(func_stack[k].non_local_refs); ++i)13872- if (func_stack[k].non_local_refs[i] == j-k)13873- return j-n;13874- stb_arr_push(func_stack[k].non_local_refs, j-k);13875- }13876- assert (k != 1);13877-13878- return j-n;13879-}13880-13881-static int stu__off(void) { return stb_arr_len(stu__pfunc.code); }13882-static void stu__cc(int a)13883-{13884- assert(a >= -2000 && a < 5000);13885- stb_arr_push(stu__pfunc.code, a);13886-}13887-static int stu__cc1(int a) { stu__cc(a); return stu__off()-1; }13888-static int stu__cc2(int a, int b) { stu__cc(a); stu__cc(b); return stu__off()-2; }13889-static int stu__cc3(int a, int b, int c) {13890- if (a == '=') assert(c != 0);13891- stu__cc(a); stu__cc(b); stu__cc(c); return stu__off()-3; }13892-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; }13893-13894-static int stu__cdv(stua_obj p)13895-{13896- int i;13897- assert(p != STUA_NO_VALUE);13898- for (i=0; i < stb_arr_len(stu__pfunc.data); ++i)13899- if (stu__pfunc.data[i] == p)13900- break;13901- if (i == stb_arr_len(stu__pfunc.data))13902- stb_arr_push(stu__pfunc.data, p);13903- return ~i;13904-}13905-13906-static int stu__cdt(void)13907-{13908- int z = stu__cdv(stu__tokval);13909- stu__nexttoken();13910- return z;13911-}13912-13913-static int stu__seq(int a, int b)13914-{13915- return !a ? b : !b ? a : stu__cc3(STU__seq, a,b);13916-}13917-13918-static char stu__comp_err_str[1024];13919-static int stu__comp_err_line;13920-static int stu__err(char *str, ...)13921-{13922- va_list v;13923- char *s = stu__bufstart;13924- stu__comp_err_line = 1;13925- while (s < stu__curbuf) {13926- if (s[0] == '\n' || s[0] == '\r') {13927- if (s[0]+s[1] == '\n' + '\r') ++s;13928- ++stu__comp_err_line;13929- }13930- ++s;13931- }13932- va_start(v, str);13933- vsprintf(stu__comp_err_str, str, v);13934- va_end(v);13935- return 0;13936-}13937-13938-static int stu__accept(int p)13939-{13940- if (stu__tok != p) return 0;13941- stu__nexttoken();13942- return 1;13943-}13944-13945-static int stu__demand(int p)13946-{13947- if (stu__accept(p)) return 1;13948- return stu__err("Didn't find expected stu__tok");13949-}13950-13951-static int stu__demandv(int p, stua_obj *val)13952-{13953- if (stu__tok == p || p==0) {13954- *val = stu__tokval;13955- stu__nexttoken();13956- return 1;13957- } else13958- return 0;13959-}13960-13961-static int stu__expr(int p);13962-int stu__nexpr(int p) { stu__nexttoken(); return stu__expr(p); }13963-static int stu__statements(int once, int as);13964-13965-static int stu__parse_if(void) // parse both ST_if and ST_elseif13966-{13967- int b,c,a;13968- a = stu__nexpr(1); if (!a) return 0;13969- if (!stu__demand(ST_then)) return stu__err("expecting THEN");13970- b = stu__statements(0,0); if (!b) return 0;13971- if (b == 1) b = -1;13972-13973- if (stu__tok == ST_elseif) {13974- return stu__parse_if();13975- } else if (stu__accept(ST_else)) {13976- c = stu__statements(0,0); if (!c) return 0;13977- if (!stu__demand(ST_end)) return stu__err("expecting END after else clause");13978- return stu__cc4(ST_else, a, b, c);13979- } else {13980- if (!stu__demand(ST_end)) return stu__err("expecting END in if statement");13981- return stu__cc3(ST_if, a, b);13982- }13983-}13984-13985-int stu__varinit(int z, int in_globals)13986-{13987- int a,b;13988- stu__nexttoken();13989- while (stu__demandv(ST_id, &b)) {13990- if (!stb_idict_add(stu__pfunc.locals, b, 1))13991- if (!in_globals) return stu__err("Redefined variable %s.", stu__pw(b)->ptr);13992- if (stu__accept('=')) {13993- a = stu__expr(1); if (!a) return 0;13994- } else13995- a = stu__cdv(stua_nil);13996- z = stu__seq(z, stu__cc3(ST_var, stu__cdv(b), a));13997- if (!stu__accept(',')) break;13998- }13999- return z;14000-}14001-14002-static int stu__compile_unary(int z, int outparm, int require_inparm)14003-{14004- int op = stu__tok, a, b;14005- stu__nexttoken();14006- if (outparm) {14007- if (require_inparm || (stu__tok && stu__tok != ST_end && stu__tok != ST_else && stu__tok != ST_elseif && stu__tok !=';')) {14008- a = stu__expr(1); if (!a) return 0;14009- } else14010- a = stu__cdv(stua_nil);14011- b = stu__cc2(op, a);14012- } else14013- b = stu__cc1(op);14014- return stu__seq(z,b);14015-}14016-14017-static int stu__assign(void)14018-{14019- int z;14020- stu__accept(ST_let);14021- z = stu__expr(1); if (!z) return 0;14022- if (stu__accept('=')) {14023- int y,p = (z >= 0 ? stu__pfunc.code[z] : 0);14024- if (z < 0 || (p != ST_id && p != '[')) return stu__err("Invalid lvalue in assignment");14025- y = stu__assign(); if (!y) return 0;14026- z = stu__cc3('=', z, y);14027- }14028- return z;14029-}14030-14031-static int stu__statements(int once, int stop_while)14032-{14033- int a,b, c, z=0;14034- for(;;) {14035- switch (stu__tok) {14036- case ST_if : a = stu__parse_if(); if (!a) return 0;14037- z = stu__seq(z, a);14038- break;14039- case ST_while : if (stop_while) return (z ? z:1);14040- a = stu__nexpr(1); if (!a) return 0;14041- if (stu__accept(ST_as)) c = stu__statements(0,0); else c = 0;14042- if (!stu__demand(ST_do)) return stu__err("expecting DO");14043- b = stu__statements(0,0); if (!b) return 0;14044- if (!stu__demand(ST_end)) return stu__err("expecting END");14045- if (b == 1) b = -1;14046- z = stu__seq(z, stu__cc4(ST_while, a, b, c));14047- break;14048- case ST_repeat : stu__nexttoken();14049- c = stu__statements(0,1); if (!c) return 0;14050- if (!stu__demand(ST_while)) return stu__err("expecting WHILE");14051- a = stu__expr(1); if (!a) return 0;14052- if (!stu__demand(ST_do)) return stu__err("expecting DO");14053- b = stu__statements(0,0); if (!b) return 0;14054- if (!stu__demand(ST_end)) return stu__err("expecting END");14055- if (b == 1) b = -1;14056- z = stu__seq(z, stu__cc4(ST_as, a, b, c));14057- break;14058- case ST_catch : a = stu__nexpr(1); if (!a) return 0;14059- z = stu__seq(z, stu__cc2(ST_catch, a));14060- break;14061- case ST_var : z = stu__varinit(z,0); break;14062- case ST_return : z = stu__compile_unary(z,1,1); break;14063- case ST_continue:z = stu__compile_unary(z,0,0); break;14064- case ST_break : z = stu__compile_unary(z,1,0); break;14065- case ST_into : if (z == 0 && !once) return stu__err("=> cannot be first statement in block");14066- a = stu__nexpr(99);14067- b = (a >= 0? stu__pfunc.code[a] : 0);14068- if (a < 0 || (b != ST_id && b != '[')) return stu__err("Invalid lvalue on right side of =>");14069- z = stu__cc3('=', a, z);14070- break;14071- default : if (stu__end[stu__tok]) return once ? 0 : (z ? z:1);14072- a = stu__assign(); if (!a) return 0;14073- stu__accept(';');14074- if (stu__tok && !stu__end[stu__tok]) {14075- if (a < 0)14076- return stu__err("Constant has no effect");14077- if (stu__pfunc.code[a] != '(' && stu__pfunc.code[a] != '=')14078- return stu__err("Expression has no effect");14079- }14080- z = stu__seq(z, a);14081- break;14082- }14083- if (!z) return 0;14084- stu__accept(';');14085- if (once && stu__tok != ST_into) return z;14086- }14087-}14088-14089-static int stu__postexpr(int z, int p);14090-static int stu__dictdef(int end, int *count)14091-{14092- int z,n=0,i,flags=0;14093- short *dict=NULL;14094- stu__nexttoken();14095- while (stu__tok != end) {14096- if (stu__tok == ST_id) {14097- stua_obj id = stu__tokval;14098- stu__nexttoken();14099- if (stu__tok == '=') {14100- flags |= 1;14101- stb_arr_push(dict, stu__cdv(id));14102- z = stu__nexpr(1); if (!z) return 0;14103- } else {14104- z = stu__cc2(ST_id, stu__cdv(id));14105- z = stu__postexpr(z,1); if (!z) return 0;14106- flags |= 2;14107- stb_arr_push(dict, stu__cdv(stu__makeint(n++)));14108- }14109- } else {14110- z = stu__expr(1); if (!z) return 0;14111- flags |= 2;14112- stb_arr_push(dict, stu__cdv(stu__makeint(n++)));14113- }14114- if (end != ')' && flags == 3) { z=stu__err("can't mix initialized and uninitialized defs"); goto done;}14115- stb_arr_push(dict, z);14116- if (!stu__accept(',')) break;14117- }14118- if (!stu__demand(end))14119- return stu__err(end == ')' ? "Expecting ) at end of function call"14120- : "Expecting } at end of dictionary definition");14121- z = stu__cc2('{', stb_arr_len(dict)/2);14122- for (i=0; i < stb_arr_len(dict); ++i)14123- stu__cc(dict[i]);14124- if (count) *count = n;14125-done:14126- stb_arr_free(dict);14127- return z;14128-}14129-14130-static int stu__comp_id(void)14131-{14132- int z,d;14133- d = stu__nonlocal_id(stu__tokval);14134- if (d == 0)14135- return z = stu__cc2(ST_id, stu__cdt());14136- // access a non-local frame by naming it with the appropriate int14137- assert(d < 0);14138- z = stu__cdv(d); // relative frame # is the 'variable' in our local frame14139- z = stu__cc2(ST_id, z); // now access that dictionary14140- return stu__cc3('[', z, stu__cdt()); // now access the variable from that dir14141-}14142-14143-static stua_obj stu__funcdef(stua_obj *id, stua_obj *func);14144-static int stu__expr(int p)14145-{14146- int z;14147- // unary14148- switch (stu__tok) {14149- case ST_number: z = stu__cdt(); break;14150- case ST_string: z = stu__cdt(); break; // @TODO - string concatenation like C14151- case ST_id : z = stu__comp_id(); break;14152- case ST__frame: z = stu__cc1(ST__frame); stu__nexttoken(); break;14153- case ST_func : z = stu__funcdef(NULL,NULL); break;14154- case ST_if : z = stu__parse_if(); break;14155- case ST_nil : z = stu__cdv(stua_nil); stu__nexttoken(); break;14156- case ST_true : z = stu__cdv(stua_true); stu__nexttoken(); break;14157- case ST_false : z = stu__cdv(stua_false); stu__nexttoken(); break;14158- case '-' : z = stu__nexpr(99); if (z) z=stu__cc2(STU__negate,z); else return z; break;14159- case '!' : z = stu__nexpr(99); if (z) z=stu__cc2('!',z); else return z; break;14160- case '~' : z = stu__nexpr(99); if (z) z=stu__cc2('~',z); else return z; break;14161- case '{' : z = stu__dictdef('}', NULL); break;14162- default : return stu__err("Unexpected token");14163- case '(' : stu__nexttoken(); z = stu__statements(0,0); if (!stu__demand(')')) return stu__err("Expecting )");14164- }14165- return stu__postexpr(z,p);14166-}14167-14168-static int stu__postexpr(int z, int p)14169-{14170- int q;14171- // postfix14172- while (stu__tok == '(' || stu__tok == '[' || stu__tok == '.') {14173- if (stu__accept('.')) {14174- // MUST be followed by a plain identifier! use [] for other stuff14175- if (stu__tok != ST_id) return stu__err("Must follow . with plain name; try [] instead");14176- z = stu__cc3('[', z, stu__cdv(stu__tokval));14177- stu__nexttoken();14178- } else if (stu__accept('[')) {14179- while (stu__tok != ']') {14180- int r = stu__expr(1); if (!r) return 0;14181- z = stu__cc3('[', z, r);14182- if (!stu__accept(',')) break;14183- }14184- if (!stu__demand(']')) return stu__err("Expecting ]");14185- } else {14186- int n, p = stu__dictdef(')', &n); if (!p) return 0;14187- #if 0 // this is incorrect!14188- if (z > 0 && stu__pfunc.code[z] == ST_id) {14189- stua_obj q = stu__get(stu__globaldict, stu__pfunc.data[-stu__pfunc.code[z+1]-1], stua_nil);14190- if (stu__checkt(STU___function, q))14191- if ((stu__pf(q))->num_param != n)14192- return stu__err("Incorrect number of parameters");14193- }14194- #endif14195- z = stu__cc3('(', z, p);14196- }14197- }14198- // binop - this implementation taken from lcc14199- for (q=stu__prec[stu__tok]; q >= p; --q) {14200- while (stu__prec[stu__tok] == q) {14201- int o = stu__tok, y = stu__nexpr(p+1); if (!y) return 0;14202- z = stu__cc3(o,z,y);14203- }14204- }14205- return z;14206-}14207-14208-static stua_obj stu__finish_func(stua_obj *param, int start)14209-{14210- int n, size;14211- stu__func *f = (stu__func *) malloc(sizeof(*f));14212- f->closure_source = 0;14213- f->num_param = stb_arr_len(param);14214- f->param = (int *) stb_copy(param, f->num_param * sizeof(*f->param));14215- size = stb_arr_storage(stu__pfunc.code) + stb_arr_storage(stu__pfunc.data) + sizeof(*f) + 8;14216- f->f.store = malloc(stb_arr_storage(stu__pfunc.code) + stb_arr_storage(stu__pfunc.data));14217- f->code = (short *) ((char *) f->f.store + stb_arr_storage(stu__pfunc.data));14218- memcpy(f->code, stu__pfunc.code, stb_arr_storage(stu__pfunc.code));14219- f->code[1] = start;14220- f->code[0] = stb_arr_len(stu__pfunc.data);14221- for (n=0; n < f->code[0]; ++n)14222- ((stua_obj *) f->code)[-1-n] = stu__pfunc.data[n];14223- return stu__makeobj(STU___function, f, size, 0);14224-}14225-14226-static int stu__funcdef(stua_obj *id, stua_obj *result)14227-{14228- int n,z=0,i,q;14229- stua_obj *param = NULL;14230- short *nonlocal;14231- stua_obj v,f=stua_nil;14232- assert(stu__tok == ST_func);14233- stu__nexttoken();14234- if (id) {14235- if (!stu__demandv(ST_id, id)) return stu__err("Expecting function name");14236- } else14237- stu__accept(ST_id);14238- if (!stu__demand('(')) return stu__err("Expecting ( for function parameter");14239- stu__push_func_comp();14240- while (stu__tok != ')') {14241- if (!stu__demandv(ST_id, &v)) { z=stu__err("Expecting parameter name"); goto done; }14242- stb_idict_add(stu__pfunc.locals, v, 1);14243- if (stu__tok == '=') {14244- n = stu__nexpr(1); if (!n) { z=0; goto done; }14245- z = stu__seq(z, stu__cc3(STU__defaultparm, stu__cdv(v), n));14246- } else14247- stb_arr_push(param, v);14248- if (!stu__accept(',')) break;14249- }14250- if (!stu__demand(')')) { z=stu__err("Expecting ) at end of parameter list"); goto done; }14251- n = stu__statements(0,0); if (!n) { z=0; goto done; }14252- if (!stu__demand(ST_end)) { z=stu__err("Expecting END at end of function"); goto done; }14253- if (n == 1) n = 0;14254- n = stu__seq(z,n);14255- f = stu__finish_func(param, n);14256- if (result) { *result = f; z=1; stu__pop_func_comp(); }14257- else {14258- nonlocal = stu__pfunc.non_local_refs;14259- stu__pfunc.non_local_refs = NULL;14260- stu__pop_func_comp();14261- z = stu__cdv(f);14262- if (nonlocal) { // build a closure with references to the needed frames14263- short *initcode = NULL;14264- for (i=0; i < stb_arr_len(nonlocal); ++i) {14265- int k = nonlocal[i], p;14266- stb_arr_push(initcode, stu__cdv(k));14267- if (k == -1) p = stu__cc1(ST__frame);14268- else { p = stu__cdv(stu__makeint(k+1)); p = stu__cc2(ST_id, p); }14269- stb_arr_push(initcode, p);14270- }14271- q = stu__cc2('{', stb_arr_len(nonlocal));14272- for (i=0; i < stb_arr_len(initcode); ++i)14273- stu__cc(initcode[i]);14274- z = stu__cc3('+', z, q);14275- stb_arr_free(initcode);14276- }14277- stb_arr_free(nonlocal);14278- }14279-done:14280- stb_arr_free(param);14281- if (!z) stu__pop_func_comp();14282- return z;14283-}14284-14285-static int stu__compile_global_scope(void)14286-{14287- stua_obj o;14288- int z=0;14289-14290- stu__push_func_comp();14291- while (stu__tok != 0) {14292- if (stu__tok == ST_func) {14293- stua_obj id, f;14294- if (!stu__funcdef(&id,&f))14295- goto error;14296- stu__set(stu__globaldict, id, f);14297- } else if (stu__tok == ST_var) {14298- z = stu__varinit(z,1); if (!z) goto error;14299- } else {14300- int y = stu__statements(1,0); if (!y) goto error;14301- z = stu__seq(z,y);14302- }14303- stu__accept(';');14304- }14305- o = stu__finish_func(NULL, z);14306- stu__pop_func_comp();14307-14308- o = stu__funceval(o, stua_globals); // initialize stu__globaldict14309- if (stu__flow == FLOW_error)14310- printf("Error: %s\n", ((stu__wrapper *) stu__ptr(stu__flow_val))->ptr);14311- return 1;14312-error:14313- stu__pop_func_comp();14314- return 0;14315-}14316-14317-stua_obj stu__myprint(stua_dict *context)14318-{14319- stua_obj x = stu__get(context, stua_string("x"), stua_nil);14320- if ((x & 1) == stu__float_tag) printf("%f", stu__getfloat(x));14321- else if (stu__tag(x) == stu__int_tag) printf("%d", stu__int(x));14322- else {14323- stu__wrapper *s = stu__pw(x);14324- if (s->type == STU___string || s->type == STU___error)14325- printf("%s", s->ptr);14326- else if (s->type == STU___dict) printf("{{dictionary}}");14327- else if (s->type == STU___function) printf("[[function]]");14328- else14329- printf("[[ERROR:%s]]", s->ptr);14330- }14331- return x;14332-}14333-14334-void stua_init(void)14335-{14336- if (!stu__globaldict) {14337- int i;14338- stua_obj s;14339- stu__func *f;14340-14341- stu__prec[ST_and] = stu__prec[ST_or] = 1;14342- stu__prec[ST_eq ] = stu__prec[ST_ne] = stu__prec[ST_le] =14343- stu__prec[ST_ge] = stu__prec['>' ] = stu__prec['<'] = 2;14344- stu__prec[':'] = 3;14345- stu__prec['&'] = stu__prec['|'] = stu__prec['^'] = 4;14346- stu__prec['+'] = stu__prec['-'] = 5;14347- stu__prec['*'] = stu__prec['/'] = stu__prec['%'] =14348- stu__prec[ST_shl]= stu__prec[ST_shr]= stu__prec[ST_shru]= 6;14349-14350- stu__end[')'] = stu__end[ST_end] = stu__end[ST_else] = 1;14351- stu__end[ST_do] = stu__end[ST_elseif] = 1;14352-14353- stu__float_init();14354- stu__lex_matcher = stb_lex_matcher();14355- for (i=0; i < sizeof(stu__lexemes)/sizeof(stu__lexemes[0]); ++i)14356- stb_lex_item(stu__lex_matcher, stu__lexemes[i].regex, stu__lexemes[i].stu__tok);14357-14358- stu__globaldict = stb_idict_new_size(64);14359- stua_globals = stu__makeobj(STU___dict, stu__globaldict, 0,0);14360- stu__strings = stb_sdict_new(0);14361-14362- stu__curbuf = stu__bufstart = "func _print(x) end\n"14363- "func print()\n var x=0 while _frame[x] != nil as x=x+1 do _print(_frame[x]) end end\n";14364- stu__nexttoken();14365- if (!stu__compile_global_scope())14366- printf("Compile error in line %d: %s\n", stu__comp_err_line, stu__comp_err_str);14367-14368- s = stu__get(stu__globaldict, stua_string("_print"), stua_nil);14369- if (stu__tag(s) == stu__ptr_tag && stu__ptr(s)->type == STU___function) {14370- f = stu__pf(s);14371- free(f->f.store);14372- f->closure_source = 4;14373- f->f.func = stu__myprint;14374- f->code = NULL;14375- }14376- }14377-}14378-14379-void stua_uninit(void)14380-{14381- if (stu__globaldict) {14382- stb_idict_remove_all(stu__globaldict);14383- stb_arr_setlen(stu__gc_root_stack, 0);14384- stua_gc(1);14385- stb_idict_destroy(stu__globaldict);14386- stb_sdict_delete(stu__strings);14387- stb_matcher_free(stu__lex_matcher);14388- stb_arr_free(stu__gc_ptrlist);14389- stb_arr_free(func_stack);14390- stb_arr_free(stu__gc_root_stack);14391- stu__globaldict = NULL;14392- }14393-}14394-14395-void stua_run_script(char *s)14396-{14397- stua_init();14398-14399- stu__curbuf = stu__bufstart = s;14400- stu__nexttoken();14401-14402- stu__flow = FLOW_normal;14403-14404- if (!stu__compile_global_scope())14405- printf("Compile error in line %d: %s\n", stu__comp_err_line, stu__comp_err_str);14406- stua_gc(1);14407-}14408-#endif // STB_DEFINE14409-#endif // STB_STUA14410-14411-#undef STB_EXTERN14412-#endif // STB_INCLUDE_STB_H14413-14414-/*14415-------------------------------------------------------------------------------14416-This software is available under 2 licenses -- choose whichever you prefer.14417-------------------------------------------------------------------------------14418-ALTERNATIVE A - MIT License14419-Copyright (c) 2017 Sean Barrett14420-Permission is hereby granted, free of charge, to any person obtaining a copy of14421-this software and associated documentation files (the "Software"), to deal in14422-the Software without restriction, including without limitation the rights to14423-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies14424-of the Software, and to permit persons to whom the Software is furnished to do14425-so, subject to the following conditions:14426-The above copyright notice and this permission notice shall be included in all14427-copies or substantial portions of the Software.14428-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14429-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,14430-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE14431-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER14432-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,14433-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE14434-SOFTWARE.14435-------------------------------------------------------------------------------14436-ALTERNATIVE B - Public Domain (www.unlicense.org)14437-This is free and unencumbered software released into the public domain.14438-Anyone is free to copy, modify, publish, use, compile, sell, or distribute this14439-software, either in source code form or as a compiled binary, for any purpose,14440-commercial or non-commercial, and by any means.14441-In jurisdictions that recognize copyright laws, the author or authors of this14442-software dedicate any and all copyright interest in the software to the public14443-domain. We make this dedication for the benefit of the public at large and to14444-the detriment of our heirs and successors. We intend this dedication to be an14445-overt act of relinquishment in perpetuity of all present and future rights to14446-this software under copyright law.14447-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR14448-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,14449-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE14450-AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN14451-ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION14452-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.14453-------------------------------------------------------------------------------14454-*/