Skip to content
Myr

Merge branch 'master' of https://github.com/nothings/stb into num-fonts

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Christopher Hansen · committed by Christopher Hansen · parents 75a8fd9, 3e7f2d6 · Browse files · 12 files+2775 added−278 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

12 files+2775 added−278 removed

  • tests:+27 added−4 removed
  • other:+2748 added−274 removed

12 files+2775 added−278 removed

added:deprecated/rrsprintf.h+1055 added
1#ifndef RR_SPRINTF_H_INCLUDE2#define RR_SPRINTF_H_INCLUDE34/*5Single file sprintf replacement.67Originally written by Jeff Roberts at RAD Game Tools - 2015/10/20. 8Hereby placed in public domain.910This is a full sprintf replacement that supports everything that11the C runtime sprintfs support, including float/double, 64-bit integers,12hex floats, field parameters (%*.*d stuff), length reads backs, etc.1314Why would you need this if sprintf already exists? Well, first off,15it's *much* faster (see below). It's also much smaller than the CRT16versions code-space-wise. We've also added some simple improvements 17that are super handy (commas in thousands, callbacks at buffer full,18for example). Finally, the format strings for MSVC and GCC differ 19for 64-bit integers (among other small things), so this lets you use 20the same format strings in cross platform code.2122It uses the standard single file trick of being both the header file23and the source itself. If you just include it normally, you just get 24the header file function definitions. To get the code, you include25it from a C or C++ file and define RR_SPRINTF_IMPLEMENTATION first.2627It only uses va_args macros from the C runtime to do it's work. It28does cast doubles to S64s and shifts and divides U64s, which does 29drag in CRT code on most platforms.3031It compiles to roughly 8K with float support, and 4K without.32As a comparison, when using MSVC static libs, calling sprintf drags33in 16K.3435API:36====37int rrsprintf( char * buf, char const * fmt, ... )38int rrsnprintf( char * buf, int count, char const * fmt, ... )39 Convert an arg list into a buffer. rrsnprintf always returns40 a zero-terminated string (unlike regular snprintf).4142int rrvsprintf( char * buf, char const * fmt, va_list va )43int rrvsnprintf( char * buf, int count, char const * fmt, va_list va )44 Convert a va_list arg list into a buffer. rrvsnprintf always returns45 a zero-terminated string (unlike regular snprintf).4647int rrvsprintfcb( RRSPRINTFCB * callback, void * user, char * buf, char const * fmt, va_list va )48 typedef char * RRSPRINTFCB( char const * buf, void * user, int len );49 Convert into a buffer, calling back every RR_SPRINTF_MIN chars.50 Your callback can then copy the chars out, print them or whatever.51 This function is actually the workhorse for everything else.52 The buffer you pass in must hold at least RR_SPRINTF_MIN characters.53 // you return the next buffer to use or 0 to stop converting5455void rrsetseparators( char comma, char period )56 Set the comma and period characters to use.5758FLOATS/DOUBLES:59===============60This code uses a internal float->ascii conversion method that uses61doubles with error correction (double-doubles, for ~105 bits of62precision). This conversion is round-trip perfect - that is, an atof63of the values output here will give you the bit-exact double back.6465One difference is that our insignificant digits will be different than 66with MSVC or GCC (but they don't match each other either). We also 67don't attempt to find the minimum length matching float (pre-MSVC15 68doesn't either).6970If you don't need float or doubles at all, define RR_SPRINTF_NOFLOAT71and you'll save 4K of code space.727364-BIT INTS:74============75This library also supports 64-bit integers and you can use MSVC style or76GCC style indicators (%I64d or %lld). It supports the C99 specifiers77for size_t and ptr_diff_t (%jd %zd) as well.7879EXTRAS:80=======81Like some GCCs, for integers and floats, you can use a ' (single quote)82specifier and commas will be inserted on the thousands: "%'d" on 12345 83would print 12,345.8485For integers and floats, you can use a "$" specifier and the number 86will be converted to float and then divided to get kilo, mega, giga or87tera and then printed, so "%$d" 1024 is "1.0 k", "%$.2d" 2536000 is 88"2.42 m", etc.8990In addition to octal and hexadecimal conversions, you can print 91integers in binary: "%b" for 256 would print 100.9293PERFORMANCE vs MSVC 2008 32-/64-bit (GCC is even slower than MSVC):94===================================================================95"%d" across all 32-bit ints (4.8x/4.0x faster than 32-/64-bit MSVC)96"%24d" across all 32-bit ints (4.5x/4.2x faster)97"%x" across all 32-bit ints (4.5x/3.8x faster)98"%08x" across all 32-bit ints (4.3x/3.8x faster)99"%f" across e-10 to e+10 floats (7.3x/6.0x faster)100"%e" across e-10 to e+10 floats (8.1x/6.0x faster)101"%g" across e-10 to e+10 floats (10.0x/7.1x faster)102"%f" for values near e-300 (7.9x/6.5x faster)103"%f" for values near e+300 (10.0x/9.1x faster)104"%e" for values near e-300 (10.1x/7.0x faster)105"%e" for values near e+300 (9.2x/6.0x faster)106"%.320f" for values near e-300 (12.6x/11.2x faster)107"%a" for random values (8.6x/4.3x faster)108"%I64d" for 64-bits with 32-bit values (4.8x/3.4x faster)109"%I64d" for 64-bits > 32-bit values (4.9x/5.5x faster)110"%s%s%s" for 64 char strings (7.1x/7.3x faster)111"...512 char string..." ( 35.0x/32.5x faster!)112*/113114#ifdef RR_SPRINTF_STATIC115#define RRPUBLIC_DEC static116#define RRPUBLIC_DEF static117#else118#ifdef __cplusplus119#define RRPUBLIC_DEC extern "C"120#define RRPUBLIC_DEF extern "C"121#else122#define RRPUBLIC_DEC extern 123#define RRPUBLIC_DEF124#endif125#endif126127#include <stdarg.h> // for va_list()128129#ifndef RR_SPRINTF_MIN130#define RR_SPRINTF_MIN 512 // how many characters per callback131#endif132typedef char * RRSPRINTFCB( char * buf, void * user, int len );133134#ifndef RR_SPRINTF_DECORATE135#define RR_SPRINTF_DECORATE(name) rr##name // define this before including if you want to change the names136#endif137138#ifndef RR_SPRINTF_IMPLEMENTATION139140RRPUBLIC_DEF int RR_SPRINTF_DECORATE( vsprintf )( char * buf, char const * fmt, va_list va );141RRPUBLIC_DEF int RR_SPRINTF_DECORATE( vsnprintf )( char * buf, int count, char const * fmt, va_list va );142RRPUBLIC_DEF int RR_SPRINTF_DECORATE( sprintf ) ( char * buf, char const * fmt, ... );143RRPUBLIC_DEF int RR_SPRINTF_DECORATE( snprintf )( char * buf, int count, char const * fmt, ... );144145RRPUBLIC_DEF int RR_SPRINTF_DECORATE( vsprintfcb )( RRSPRINTFCB * callback, void * user, char * buf, char const * fmt, va_list va );146RRPUBLIC_DEF void RR_SPRINTF_DECORATE( setseparators )( char comma, char period );147148#else149150#include <stdlib.h> // for va_arg()151152#define rU32 unsigned int153#define rS32 signed int154155#ifdef _MSC_VER156#define rU64 unsigned __int64157#define rS64 signed __int64158#else159#define rU64 unsigned long long160#define rS64 signed long long161#endif162#define rU16 unsigned short163164#ifndef rUINTa 165#if defined(__ppc64__) || defined(__aarch64__) || defined(_M_X64) || defined(__x86_64__) || defined(__x86_64)166#define rUINTa rU64167#else168#define rUINTa rU32169#endif170#endif171172#ifndef RR_SPRINTF_MSVC_MODE // used for MSVC2013 and earlier (MSVC2015 matches GCC)173#if defined(_MSC_VER) && (_MSC_VER<1900)174#define RR_SPRINTF_MSVC_MODE175#endif176#endif177178#ifdef RR_SPRINTF_NOUNALIGNED // define this before inclusion to force rrsprint to always use aligned accesses179#define RR_UNALIGNED(code)180#else181#define RR_UNALIGNED(code) code182#endif183184#ifndef RR_SPRINTF_NOFLOAT185// internal float utility functions186static rS32 rrreal_to_str( char const * * start, rU32 * len, char *out, rS32 * decimal_pos, double value, rU32 frac_digits );187static rS32 rrreal_to_parts( rS64 * bits, rS32 * expo, double value );188#define RRSPECIAL 0x7000189#endif190191static char RRperiod='.';192static char RRcomma=',';193static char rrdiglookup[201]="00010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899";194195RRPUBLIC_DEF void RR_SPRINTF_DECORATE( setseparators )( char pcomma, char pperiod )196{197 RRperiod=pperiod;198 RRcomma=pcomma;199}200201RRPUBLIC_DEF int RR_SPRINTF_DECORATE( vsprintfcb )( RRSPRINTFCB * callback, void * user, char * buf, char const * fmt, va_list va )202{203 static char hex[]="0123456789abcdefxp";204 static char hexu[]="0123456789ABCDEFXP";205 char * bf;206 char const * f;207 int tlen = 0;208209 bf = buf;210 f = fmt;211 for(;;)212 {213 rS32 fw,pr,tz; rU32 fl;214215 #define LJ 1216 #define LP 2217 #define LS 4218 #define LX 8219 #define LZ 16220 #define BI 32221 #define CS 64222 #define NG 128223 #define KI 256224 #define HW 512225 226 // macros for the callback buffer stuff227 #define chk_cb_bufL(bytes) { int len = (int)(bf-buf); if ((len+(bytes))>=RR_SPRINTF_MIN) { tlen+=len; if (0==(bf=buf=callback(buf,user,len))) goto done; } }228 #define chk_cb_buf(bytes) { if ( callback ) { chk_cb_bufL(bytes); } }229 #define flush_cb() { chk_cb_bufL(RR_SPRINTF_MIN-1); } //flush if there is even one byte in the buffer230 #define cb_buf_clamp(cl,v) cl = v; if ( callback ) { int lg = RR_SPRINTF_MIN-(int)(bf-buf); if (cl>lg) cl=lg; }231232 // fast copy everything up to the next % (or end of string)233 for(;;)234 { 235 while (((rUINTa)f)&3)236 {237 schk1: if (f[0]=='%') goto scandd;238 schk2: if (f[0]==0) goto endfmt;239 chk_cb_buf(1); *bf++=f[0]; ++f;240 } 241 for(;;)242 { 243 rU32 v,c;244 v=*(rU32*)f; c=(~v)&0x80808080;245 if ((v-0x26262626)&c) goto schk1; 246 if ((v-0x01010101)&c) goto schk2; 247 if (callback) if ((RR_SPRINTF_MIN-(int)(bf-buf))<4) goto schk1;248 *(rU32*)bf=v; bf+=4; f+=4;249 }250 } scandd:251252 ++f;253254 // ok, we have a percent, read the modifiers first255 fw = 0; pr = -1; fl = 0; tz = 0;256 257 // flags258 for(;;)259 {260 switch(f[0])261 {262 // if we have left just263 case '-': fl|=LJ; ++f; continue;264 // if we have leading plus265 case '+': fl|=LP; ++f; continue; 266 // if we have leading space267 case ' ': fl|=LS; ++f; continue; 268 // if we have leading 0x269 case '#': fl|=LX; ++f; continue; 270 // if we have thousand commas271 case '\'': fl|=CS; ++f; continue; 272 // if we have kilo marker273 case '$': fl|=KI; ++f; continue; 274 // if we have leading zero275 case '0': fl|=LZ; ++f; goto flags_done; 276 default: goto flags_done;277 }278 }279 flags_done:280 281 // get the field width282 if ( f[0] == '*' ) {fw = va_arg(va,rU32); ++f;} else { while (( f[0] >= '0' ) && ( f[0] <= '9' )) { fw = fw * 10 + f[0] - '0'; f++; } }283 // get the precision284 if ( f[0]=='.' ) { ++f; if ( f[0] == '*' ) {pr = va_arg(va,rU32); ++f;} else { pr = 0; while (( f[0] >= '0' ) && ( f[0] <= '9' )) { pr = pr * 10 + f[0] - '0'; f++; } } } 285 286 // handle integer size overrides287 switch(f[0])288 {289 // are we halfwidth?290 case 'h': fl|=HW; ++f; break;291 // are we 64-bit (unix style)292 case 'l': ++f; if ( f[0]=='l') { fl|=BI; ++f; } break;293 // are we 64-bit on intmax? (c99)294 case 'j': fl|=BI; ++f; break; 295 // are we 64-bit on size_t or ptrdiff_t? (c99)296 case 'z': case 't': fl|=((sizeof(char*)==8)?BI:0); ++f; break; 297 // are we 64-bit (msft style)298 case 'I': if ( ( f[1]=='6') && ( f[2]=='4') ) { fl|=BI; f+=3; } else if ( ( f[1]=='3') && ( f[2]=='2') ) { f+=3; } else { fl|=((sizeof(void*)==8)?BI:0); ++f; } break;299 default: break;300 }301302 // handle each replacement303 switch( f[0] )304 {305 #define NUMSZ 512 // big enough for e308 (with commas) or e-307 306 char num[NUMSZ]; 307 char lead[8]; 308 char tail[8]; 309 char *s;310 char const *h;311 rU32 l,n,cs;312 rU64 n64;313 #ifndef RR_SPRINTF_NOFLOAT 314 double fv; 315 #endif316 rS32 dp; char const * sn;317318 case 's':319 // get the string320 s = va_arg(va,char*); if (s==0) s = (char*)"null";321 // get the length322 sn = s;323 for(;;)324 { 325 if ((((rUINTa)sn)&3)==0) break;326 lchk:327 if (sn[0]==0) goto ld;328 ++sn;329 }330 n = 0xffffffff;331 if (pr>=0) { n=(rU32)(sn-s); if (n>=(rU32)pr) goto ld; n=((rU32)(pr-n))>>2; }332 while(n) 333 { 334 rU32 v=*(rU32*)sn;335 if ((v-0x01010101)&(~v)&0x80808080UL) goto lchk; 336 sn+=4; 337 --n;338 }339 goto lchk;340 ld:341342 l = (rU32) ( sn - s );343 // clamp to precision344 if ( l > (rU32)pr ) l = pr;345 lead[0]=0; tail[0]=0; pr = 0; dp = 0; cs = 0;346 // copy the string in347 goto scopy;348349 case 'c': // char350 // get the character351 s = num + NUMSZ -1; *s = (char)va_arg(va,int);352 l = 1;353 lead[0]=0; tail[0]=0; pr = 0; dp = 0; cs = 0;354 goto scopy;355356 case 'n': // weird write-bytes specifier357 { int * d = va_arg(va,int*);358 *d = tlen + (int)( bf - buf ); }359 break;360361#ifdef RR_SPRINTF_NOFLOAT362 case 'A': // float363 case 'a': // hex float364 case 'G': // float365 case 'g': // float366 case 'E': // float367 case 'e': // float368 case 'f': // float369 va_arg(va,double); // eat it370 s = (char*)"No float";371 l = 8;372 lead[0]=0; tail[0]=0; pr = 0; dp = 0; cs = 0;373 goto scopy;374#else375 case 'A': // float376 h=hexu; 377 goto hexfloat;378379 case 'a': // hex float380 h=hex;381 hexfloat: 382 fv = va_arg(va,double);383 if (pr==-1) pr=6; // default is 6384 // read the double into a string385 if ( rrreal_to_parts( (rS64*)&n64, &dp, fv ) )386 fl |= NG;387 388 s = num+64;389390 // sign391 lead[0]=0; if (fl&NG) { lead[0]=1; lead[1]='-'; } else if (fl&LS) { lead[0]=1; lead[1]=' '; } else if (fl&LP) { lead[0]=1; lead[1]='+'; };392393 if (dp==-1023) dp=(n64)?-1022:0; else n64|=(((rU64)1)<<52);394 n64<<=(64-56);395 if (pr<15) n64+=((((rU64)8)<<56)>>(pr*4));396 // add leading chars397 398 #ifdef RR_SPRINTF_MSVC_MODE399 *s++='0';*s++='x';400 #else401 lead[1+lead[0]]='0'; lead[2+lead[0]]='x'; lead[0]+=2;402 #endif403 *s++=h[(n64>>60)&15]; n64<<=4;404 if ( pr ) *s++=RRperiod;405 sn = s;406407 // print the bits408 n = pr; if (n>13) n = 13; if (pr>(rS32)n) tz=pr-n; pr = 0;409 while(n--) { *s++=h[(n64>>60)&15]; n64<<=4; }410411 // print the expo412 tail[1]=h[17];413 if (dp<0) { tail[2]='-'; dp=-dp;} else tail[2]='+';414 n = (dp>=1000)?6:((dp>=100)?5:((dp>=10)?4:3));415 tail[0]=(char)n;416 for(;;) { tail[n]='0'+dp%10; if (n<=3) break; --n; dp/=10; }417418 dp = (int)(s-sn);419 l = (int)(s-(num+64));420 s = num+64;421 cs = 1 + (3<<24);422 goto scopy;423424 case 'G': // float425 h=hexu;426 goto dosmallfloat;427428 case 'g': // float429 h=hex;430 dosmallfloat: 431 fv = va_arg(va,double);432 if (pr==-1) pr=6; else if (pr==0) pr = 1; // default is 6433 // read the double into a string434 if ( rrreal_to_str( &sn, &l, num, &dp, fv, (pr-1)|0x80000000 ) )435 fl |= NG;436437 // clamp the precision and delete extra zeros after clamp438 n = pr;439 if ( l > (rU32)pr ) l = pr; while ((l>1)&&(pr)&&(sn[l-1]=='0')) { --pr; --l; }440441 // should we use %e442 if ((dp<=-4)||(dp>(rS32)n))443 {444 if ( pr > (rS32)l ) pr = l-1; else if ( pr ) --pr; // when using %e, there is one digit before the decimal445 goto doexpfromg;446 }447 // this is the insane action to get the pr to match %g sematics for %f448 if(dp>0) { pr=(dp<(rS32)l)?l-dp:0; } else { pr = -dp+((pr>(rS32)l)?l:pr); }449 goto dofloatfromg;450451 case 'E': // float452 h=hexu; 453 goto doexp;454455 case 'e': // float456 h=hex;457 doexp: 458 fv = va_arg(va,double);459 if (pr==-1) pr=6; // default is 6460 // read the double into a string461 if ( rrreal_to_str( &sn, &l, num, &dp, fv, pr|0x80000000 ) )462 fl |= NG;463 doexpfromg: 464 tail[0]=0; 465 lead[0]=0; if (fl&NG) { lead[0]=1; lead[1]='-'; } else if (fl&LS) { lead[0]=1; lead[1]=' '; } else if (fl&LP) { lead[0]=1; lead[1]='+'; };466 if ( dp == RRSPECIAL ) { s=(char*)sn; cs=0; pr=0; goto scopy; }467 s=num+64; 468 // handle leading chars469 *s++=sn[0];470471 if (pr) *s++=RRperiod;472473 // handle after decimal474 if ((l-1)>(rU32)pr) l=pr+1;475 for(n=1;n<l;n++) *s++=sn[n];476 // trailing zeros477 tz = pr-(l-1); pr=0;478 // dump expo479 tail[1]=h[0xe];480 dp -= 1;481 if (dp<0) { tail[2]='-'; dp=-dp;} else tail[2]='+';482 #ifdef RR_SPRINTF_MSVC_MODE483 n = 5;484 #else485 n = (dp>=100)?5:4;486 #endif487 tail[0]=(char)n;488 for(;;) { tail[n]='0'+dp%10; if (n<=3) break; --n; dp/=10; }489 cs = 1 + (3<<24); // how many tens490 goto flt_lead; 491492 case 'f': // float493 fv = va_arg(va,double);494 doafloat: 495 // do kilos496 if (fl&KI) {while(fl<0x4000000) { if ((fv<1024.0) && (fv>-1024.0)) break; fv/=1024.0; fl+=0x1000000; }} 497 if (pr==-1) pr=6; // default is 6498 // read the double into a string499 if ( rrreal_to_str( &sn, &l, num, &dp, fv, pr ) )500 fl |= NG;501 dofloatfromg:502 tail[0]=0;503 // sign504 lead[0]=0; if (fl&NG) { lead[0]=1; lead[1]='-'; } else if (fl&LS) { lead[0]=1; lead[1]=' '; } else if (fl&LP) { lead[0]=1; lead[1]='+'; };505 if ( dp == RRSPECIAL ) { s=(char*)sn; cs=0; pr=0; goto scopy; }506 s=num+64; 507508 // handle the three decimal varieties509 if (dp<=0) 510 { 511 rS32 i;512 // handle 0.000*000xxxx513 *s++='0'; if (pr) *s++=RRperiod; 514 n=-dp; if((rS32)n>pr) n=pr; i=n; while(i) { if ((((rUINTa)s)&3)==0) break; *s++='0'; --i; } while(i>=4) { *(rU32*)s=0x30303030; s+=4; i-=4; } while(i) { *s++='0'; --i; }515 if ((rS32)(l+n)>pr) l=pr-n; i=l; while(i) { *s++=*sn++; --i; }516 tz = pr-(n+l);517 cs = 1 + (3<<24); // how many tens did we write (for commas below)518 }519 else520 {521 cs = (fl&CS)?((600-(rU32)dp)%3):0;522 if ((rU32)dp>=l)523 {524 // handle xxxx000*000.0525 n=0; for(;;) { if ((fl&CS) && (++cs==4)) { cs = 0; *s++=RRcomma; } else { *s++=sn[n]; ++n; if (n>=l) break; } }526 if (n<(rU32)dp)527 {528 n = dp - n;529 if ((fl&CS)==0) { while(n) { if ((((rUINTa)s)&3)==0) break; *s++='0'; --n; } while(n>=4) { *(rU32*)s=0x30303030; s+=4; n-=4; } }530 while(n) { if ((fl&CS) && (++cs==4)) { cs = 0; *s++=RRcomma; } else { *s++='0'; --n; } }531 }532 cs = (int)(s-(num+64)) + (3<<24); // cs is how many tens533 if (pr) { *s++=RRperiod; tz=pr;}534 }535 else536 {537 // handle xxxxx.xxxx000*000538 n=0; for(;;) { if ((fl&CS) && (++cs==4)) { cs = 0; *s++=RRcomma; } else { *s++=sn[n]; ++n; if (n>=(rU32)dp) break; } }539 cs = (int)(s-(num+64)) + (3<<24); // cs is how many tens540 if (pr) *s++=RRperiod;541 if ((l-dp)>(rU32)pr) l=pr+dp;542 while(n<l) { *s++=sn[n]; ++n; }543 tz = pr-(l-dp);544 }545 }546 pr = 0;547 548 // handle k,m,g,t549 if (fl&KI) { tail[0]=1; tail[1]=' '; { if (fl>>24) { tail[2]="_kmgt"[fl>>24]; tail[0]=2; } } };550551 flt_lead:552 // get the length that we copied553 l = (rU32) ( s-(num+64) );554 s=num+64; 555 goto scopy;556#endif557558 case 'B': // upper binary559 h = hexu;560 goto binary;561562 case 'b': // lower binary563 h = hex;564 binary:565 lead[0]=0;566 if (fl&LX) { lead[0]=2;lead[1]='0';lead[2]=h[0xb]; }567 l=(8<<4)|(1<<8);568 goto radixnum;569570 case 'o': // octal571 h = hexu;572 lead[0]=0;573 if (fl&LX) { lead[0]=1;lead[1]='0'; }574 l=(3<<4)|(3<<8);575 goto radixnum;576577 case 'p': // pointer578 fl |= (sizeof(void*)==8)?BI:0;579 pr = sizeof(void*)*2;580 fl &= ~LZ; // 'p' only prints the pointer with zeros581 // drop through to X582 583 case 'X': // upper binary584 h = hexu;585 goto dohexb;586587 case 'x': // lower binary588 h = hex; dohexb:589 l=(4<<4)|(4<<8);590 lead[0]=0;591 if (fl&LX) { lead[0]=2;lead[1]='0';lead[2]=h[16]; }592 radixnum: 593 // get the number594 if ( fl&BI )595 n64 = va_arg(va,rU64);596 else597 n64 = va_arg(va,rU32);598599 s = num + NUMSZ; dp = 0;600 // clear tail, and clear leading if value is zero601 tail[0]=0; if (n64==0) { lead[0]=0; if (pr==0) { l=0; cs = ( ((l>>4)&15)) << 24; goto scopy; } }602 // convert to string603 for(;;) { *--s = h[n64&((1<<(l>>8))-1)]; n64>>=(l>>8); if ( ! ( (n64) || ((rS32) ( (num+NUMSZ) - s ) < pr ) ) ) break; if ( fl&CS) { ++l; if ((l&15)==((l>>4)&15)) { l&=~15; *--s=RRcomma; } } };604 // get the tens and the comma pos605 cs = (rU32) ( (num+NUMSZ) - s ) + ( ( ((l>>4)&15)) << 24 );606 // get the length that we copied607 l = (rU32) ( (num+NUMSZ) - s );608 // copy it609 goto scopy;610611 case 'u': // unsigned612 case 'i':613 case 'd': // integer614 // get the integer and abs it615 if ( fl&BI )616 {617 rS64 i64 = va_arg(va,rS64); n64 = (rU64)i64; if ((f[0]!='u') && (i64<0)) { n64=(rU64)-i64; fl|=NG; }618 }619 else620 {621 rS32 i = va_arg(va,rS32); n64 = (rU32)i; if ((f[0]!='u') && (i<0)) { n64=(rU32)-i; fl|=NG; }622 }623624 #ifndef RR_SPRINTF_NOFLOAT625 if (fl&KI) { if (n64<1024) pr=0; else if (pr==-1) pr=1; fv=(double)(rS64)n64; goto doafloat; } 626 #endif627628 // convert to string629 s = num+NUMSZ; l=0; 630 631 for(;;)632 {633 // do in 32-bit chunks (avoid lots of 64-bit divides even with constant denominators)634 char * o=s-8;635 if (n64>=100000000) { n = (rU32)( n64 % 100000000); n64 /= 100000000; } else {n = (rU32)n64; n64 = 0; }636 if((fl&CS)==0) { while(n) { s-=2; *(rU16*)s=*(rU16*)&rrdiglookup[(n%100)*2]; n/=100; } }637 while (n) { if ( ( fl&CS) && (l++==3) ) { l=0; *--s=RRcomma; --o; } else { *--s=(char)(n%10)+'0'; n/=10; } }638 if (n64==0) { if ((s[0]=='0') && (s!=(num+NUMSZ))) ++s; break; }639 while (s!=o) if ( ( fl&CS) && (l++==3) ) { l=0; *--s=RRcomma; --o; } else { *--s='0'; }640 }641642 tail[0]=0;643 // sign644 lead[0]=0; if (fl&NG) { lead[0]=1; lead[1]='-'; } else if (fl&LS) { lead[0]=1; lead[1]=' '; } else if (fl&LP) { lead[0]=1; lead[1]='+'; };645646 // get the length that we copied647 l = (rU32) ( (num+NUMSZ) - s ); if ( l == 0 ) { *--s='0'; l = 1; }648 cs = l + (3<<24);649 if (pr<0) pr = 0;650651 scopy: 652 // get fw=leading/trailing space, pr=leading zeros653 if (pr<(rS32)l) pr = l;654 n = pr + lead[0] + tail[0] + tz;655 if (fw<(rS32)n) fw = n;656 fw -= n;657 pr -= l;658659 // handle right justify and leading zeros660 if ( (fl&LJ)==0 )661 {662 if (fl&LZ) // if leading zeros, everything is in pr663 { 664 pr = (fw>pr)?fw:pr;665 fw = 0;666 }667 else668 {669 fl &= ~CS; // if no leading zeros, then no commas670 }671 }672673 // copy the spaces and/or zeros674 if (fw+pr)675 {676 rS32 i; rU32 c; 677678 // copy leading spaces (or when doing %8.4d stuff)679 if ( (fl&LJ)==0 ) while(fw>0) { cb_buf_clamp(i,fw); fw -= i; while(i) { if ((((rUINTa)bf)&3)==0) break; *bf++=' '; --i; } while(i>=4) { *(rU32*)bf=0x20202020; bf+=4; i-=4; } while (i) {*bf++=' '; --i;} chk_cb_buf(1); }680 681 // copy leader682 sn=lead+1; while(lead[0]) { cb_buf_clamp(i,lead[0]); lead[0] -= (char)i; while (i) {*bf++=*sn++; --i;} chk_cb_buf(1); }683 684 // copy leading zeros685 c = cs >> 24; cs &= 0xffffff;686 cs = (fl&CS)?((rU32)(c-((pr+cs)%(c+1)))):0;687 while(pr>0) { cb_buf_clamp(i,pr); pr -= i; if((fl&CS)==0) { while(i) { if ((((rUINTa)bf)&3)==0) break; *bf++='0'; --i; } while(i>=4) { *(rU32*)bf=0x30303030; bf+=4; i-=4; } } while (i) { if((fl&CS) && (cs++==c)) { cs = 0; *bf++=RRcomma; } else *bf++='0'; --i; } chk_cb_buf(1); }688 }689690 // copy leader if there is still one691 sn=lead+1; while(lead[0]) { rS32 i; cb_buf_clamp(i,lead[0]); lead[0] -= (char)i; while (i) {*bf++=*sn++; --i;} chk_cb_buf(1); }692693 // copy the string694 n = l; while (n) { rS32 i; cb_buf_clamp(i,n); n-=i; RR_UNALIGNED( while(i>=4) { *(rU32*)bf=*(rU32*)s; bf+=4; s+=4; i-=4; } ) while (i) {*bf++=*s++; --i;} chk_cb_buf(1); }695696 // copy trailing zeros697 while(tz) { rS32 i; cb_buf_clamp(i,tz); tz -= i; while(i) { if ((((rUINTa)bf)&3)==0) break; *bf++='0'; --i; } while(i>=4) { *(rU32*)bf=0x30303030; bf+=4; i-=4; } while (i) {*bf++='0'; --i;} chk_cb_buf(1); }698699 // copy tail if there is one700 sn=tail+1; while(tail[0]) { rS32 i; cb_buf_clamp(i,tail[0]); tail[0] -= (char)i; while (i) {*bf++=*sn++; --i;} chk_cb_buf(1); }701702 // handle the left justify703 if (fl&LJ) if (fw>0) { while (fw) { rS32 i; cb_buf_clamp(i,fw); fw-=i; while(i) { if ((((rUINTa)bf)&3)==0) break; *bf++=' '; --i; } while(i>=4) { *(rU32*)bf=0x20202020; bf+=4; i-=4; } while (i--) *bf++=' '; chk_cb_buf(1); } }704 break;705706 default: // unknown, just copy code707 s = num + NUMSZ -1; *s = f[0];708 l = 1;709 fw=pr=fl=0;710 lead[0]=0; tail[0]=0; pr = 0; dp = 0; cs = 0;711 goto scopy;712 }713 ++f;714 }715 endfmt:716717 if (!callback) 718 *bf = 0;719 else720 flush_cb();721 722 done:723 return tlen + (int)(bf-buf);724}725726// cleanup727#undef LJ728#undef LP729#undef LS730#undef LX731#undef LZ732#undef BI733#undef CS734#undef NG735#undef KI736#undef NUMSZ737#undef chk_cb_bufL738#undef chk_cb_buf739#undef flush_cb740#undef cb_buf_clamp741742// ============================================================================743// wrapper functions744745RRPUBLIC_DEF int RR_SPRINTF_DECORATE( sprintf )( char * buf, char const * fmt, ... )746{747 va_list va;748 va_start( va, fmt );749 return RR_SPRINTF_DECORATE( vsprintfcb )( 0, 0, buf, fmt, va );750}751752typedef struct RRCCS753{754 char * buf;755 int count;756 char tmp[ RR_SPRINTF_MIN ];757} RRCCS;758759static char * rrclampcallback( char * buf, void * user, int len )760{761 RRCCS * c = (RRCCS*)user;762763 if ( len > c->count ) len = c->count;764765 if (len)766 {767 if ( buf != c->buf )768 {769 char * s, * d, * se;770 d = c->buf; s = buf; se = buf+len;771 do{ *d++ = *s++; } while (s<se);772 }773 c->buf += len;774 c->count -= len;775 }776 777 if ( c->count <= 0 ) return 0;778 return ( c->count >= RR_SPRINTF_MIN ) ? c->buf : c->tmp; // go direct into buffer if you can779}780781RRPUBLIC_DEF int RR_SPRINTF_DECORATE( vsnprintf )( char * buf, int count, char const * fmt, va_list va )782{783 RRCCS c;784 int l;785786 if ( count == 0 )787 return 0;788789 c.buf = buf;790 c.count = count;791792 RR_SPRINTF_DECORATE( vsprintfcb )( rrclampcallback, &c, rrclampcallback(0,&c,0), fmt, va );793 794 // zero-terminate795 l = (int)( c.buf - buf );796 if ( l >= count ) // should never be greater, only equal (or less) than count797 l = count - 1;798 buf[l] = 0;799800 return l;801}802803RRPUBLIC_DEF int RR_SPRINTF_DECORATE( snprintf )( char * buf, int count, char const * fmt, ... )804{805 va_list va;806 va_start( va, fmt );807808 return RR_SPRINTF_DECORATE( vsnprintf )( buf, count, fmt, va );809}810811RRPUBLIC_DEF int RR_SPRINTF_DECORATE( vsprintf )( char * buf, char const * fmt, va_list va )812{813 return RR_SPRINTF_DECORATE( vsprintfcb )( 0, 0, buf, fmt, va );814}815816// =======================================================================817// low level float utility functions818819#ifndef RR_SPRINTF_NOFLOAT820821 // copies d to bits w/ strict aliasing (this compiles to nothing on /Ox)822 #define RRCOPYFP(dest,src) { int cn; for(cn=0;cn<8;cn++) ((char*)&dest)[cn]=((char*)&src)[cn]; }823 824// get float info825static rS32 rrreal_to_parts( rS64 * bits, rS32 * expo, double value )826{827 double d;828 rS64 b = 0;829830 // load value and round at the frac_digits831 d = value;832833 RRCOPYFP( b, d );834835 *bits = b & ((((rU64)1)<<52)-1);836 *expo = ((b >> 52) & 2047)-1023;837 838 return (rS32)(b >> 63);839}840841static double const rrbot[23]={1e+000,1e+001,1e+002,1e+003,1e+004,1e+005,1e+006,1e+007,1e+008,1e+009,1e+010,1e+011,1e+012,1e+013,1e+014,1e+015,1e+016,1e+017,1e+018,1e+019,1e+020,1e+021,1e+022};842static double const rrnegbot[22]={1e-001,1e-002,1e-003,1e-004,1e-005,1e-006,1e-007,1e-008,1e-009,1e-010,1e-011,1e-012,1e-013,1e-014,1e-015,1e-016,1e-017,1e-018,1e-019,1e-020,1e-021,1e-022};843static double const rrnegboterr[22]={-5.551115123125783e-018,-2.0816681711721684e-019,-2.0816681711721686e-020,-4.7921736023859299e-021,-8.1803053914031305e-022,4.5251888174113741e-023,4.5251888174113739e-024,-2.0922560830128471e-025,-6.2281591457779853e-026,-3.6432197315497743e-027,6.0503030718060191e-028,2.0113352370744385e-029,-3.0373745563400371e-030,1.1806906454401013e-032,-7.7705399876661076e-032,2.0902213275965398e-033,-7.1542424054621921e-034,-7.1542424054621926e-035,2.4754073164739869e-036,5.4846728545790429e-037,9.2462547772103625e-038,-4.8596774326570872e-039};844static double const rrtop[13]={1e+023,1e+046,1e+069,1e+092,1e+115,1e+138,1e+161,1e+184,1e+207,1e+230,1e+253,1e+276,1e+299};845static double const rrnegtop[13]={1e-023,1e-046,1e-069,1e-092,1e-115,1e-138,1e-161,1e-184,1e-207,1e-230,1e-253,1e-276,1e-299};846static double const rrtoperr[13]={8388608,6.8601809640529717e+028,-7.253143638152921e+052,-4.3377296974619174e+075,-1.5559416129466825e+098,-3.2841562489204913e+121,-3.7745893248228135e+144,-1.7356668416969134e+167,-3.8893577551088374e+190,-9.9566444326005119e+213,6.3641293062232429e+236,-5.2069140800249813e+259,-5.2504760255204387e+282};847static double const rrnegtoperr[13]={3.9565301985100693e-040,-2.299904345391321e-063,3.6506201437945798e-086,1.1875228833981544e-109,-5.0644902316928607e-132,-6.7156837247865426e-155,-2.812077463003139e-178,-5.7778912386589953e-201,7.4997100559334532e-224,-4.6439668915134491e-247,-6.3691100762962136e-270,-9.436808465446358e-293,8.0970921678014997e-317};848849#if defined(_MSC_VER) && (_MSC_VER<=1200) 850static rU64 const rrpot[20]={1,10,100,1000, 10000,100000,1000000,10000000, 100000000,1000000000,10000000000,100000000000, 1000000000000,10000000000000,100000000000000,1000000000000000, 10000000000000000,100000000000000000,1000000000000000000,10000000000000000000U };851#define rrtento19th ((rU64)1000000000000000000)852#else853static rU64 const rrpot[20]={1,10,100,1000, 10000,100000,1000000,10000000, 100000000,1000000000,10000000000ULL,100000000000ULL, 1000000000000ULL,10000000000000ULL,100000000000000ULL,1000000000000000ULL, 10000000000000000ULL,100000000000000000ULL,1000000000000000000ULL,10000000000000000000ULL };854#define rrtento19th (1000000000000000000ULL)855#endif856857#define rrddmulthi(oh,ol,xh,yh) \858{ \859 double ahi=0,alo,bhi=0,blo; \860 rS64 bt; \861 oh = xh * yh; \862 RRCOPYFP(bt,xh); bt&=((~(rU64)0)<<27); RRCOPYFP(ahi,bt); alo = xh-ahi; \863 RRCOPYFP(bt,yh); bt&=((~(rU64)0)<<27); RRCOPYFP(bhi,bt); blo = yh-bhi; \864 ol = ((ahi*bhi-oh)+ahi*blo+alo*bhi)+alo*blo; \865}866867#define rrddtoS64(ob,xh,xl) \868{ \869 double ahi=0,alo,vh,t;\870 ob = (rS64)ph;\871 vh=(double)ob;\872 ahi = ( xh - vh );\873 t = ( ahi - xh );\874 alo = (xh-(ahi-t))-(vh+t);\875 ob += (rS64)(ahi+alo+xl);\876}877878879#define rrddrenorm(oh,ol) { double s; s=oh+ol; ol=ol-(s-oh); oh=s; }880881#define rrddmultlo(oh,ol,xh,xl,yh,yl) \882 ol = ol + ( xh*yl + xl*yh ); \883884#define rrddmultlos(oh,ol,xh,yl) \885 ol = ol + ( xh*yl ); \886887static void rrraise_to_power10( double *ohi, double *olo, double d, rS32 power ) // power can be -323 to +350888{889 double ph, pl;890 if ((power>=0) && (power<=22))891 {892 rrddmulthi(ph,pl,d,rrbot[power]);893 }894 else895 {896 rS32 e,et,eb;897 double p2h,p2l;898899 e=power; if (power<0) e=-e; 900 et = (e*0x2c9)>>14;/* %23 */ if (et>13) et=13; eb = e-(et*23);901902 ph = d; pl = 0.0;903 if (power<0)904 {905 if (eb) { --eb; rrddmulthi(ph,pl,d,rrnegbot[eb]); rrddmultlos(ph,pl,d,rrnegboterr[eb]); }906 if (et)907 { 908 rrddrenorm(ph,pl);909 --et; rrddmulthi(p2h,p2l,ph,rrnegtop[et]); rrddmultlo(p2h,p2l,ph,pl,rrnegtop[et],rrnegtoperr[et]); ph=p2h;pl=p2l;910 }911 }912 else913 {914 if (eb) 915 { 916 e = eb; if (eb>22) eb=22; e -= eb;917 rrddmulthi(ph,pl,d,rrbot[eb]); 918 if ( e ) { rrddrenorm(ph,pl); rrddmulthi(p2h,p2l,ph,rrbot[e]); rrddmultlos(p2h,p2l,rrbot[e],pl); ph=p2h;pl=p2l; }919 }920 if (et)921 {922 rrddrenorm(ph,pl);923 --et; rrddmulthi(p2h,p2l,ph,rrtop[et]); rrddmultlo(p2h,p2l,ph,pl,rrtop[et],rrtoperr[et]); ph=p2h;pl=p2l;924 }925 }926 }927 rrddrenorm(ph,pl);928 *ohi = ph; *olo = pl;929}930931// given a float value, returns the significant bits in bits, and the position of the932// decimal point in decimal_pos. +/-INF and NAN are specified by special values933// returned in the decimal_pos parameter.934// frac_digits is absolute normally, but if you want from first significant digits (got %g and %e), or in 0x80000000935static rS32 rrreal_to_str( char const * * start, rU32 * len, char *out, rS32 * decimal_pos, double value, rU32 frac_digits )936{937 double d;938 rS64 bits = 0;939 rS32 expo, e, ng, tens;940941 d = value;942 RRCOPYFP(bits,d);943 expo = (bits >> 52) & 2047;944 ng = (rS32)(bits >> 63);945 if (ng) d=-d;946947 if ( expo == 2047 ) // is nan or inf?948 {949 *start = (bits&((((rU64)1)<<52)-1)) ? "NaN" : "Inf";950 *decimal_pos = RRSPECIAL;951 *len = 3;952 return ng;953 } 954955 if ( expo == 0 ) // is zero or denormal956 {957 if ((bits<<1)==0) // do zero958 {959 *decimal_pos = 1; 960 *start = out;961 out[0] = '0'; *len = 1;962 return ng;963 }964 // find the right expo for denormals965 {966 rS64 v = ((rU64)1)<<51;967 while ((bits&v)==0) { --expo; v >>= 1; }968 }969 }970971 // find the decimal exponent as well as the decimal bits of the value972 {973 double ph,pl;974975 // log10 estimate - very specifically tweaked to hit or undershoot by no more than 1 of log10 of all expos 1..2046976 tens=expo-1023; tens = (tens<0)?((tens*617)/2048):(((tens*1233)/4096)+1);977978 // move the significant bits into position and stick them into an int 979 rrraise_to_power10( &ph, &pl, d, 18-tens );980981 // get full as much precision from double-double as possible982 rrddtoS64( bits, ph,pl );983984 // check if we undershot985 if ( ((rU64)bits) >= rrtento19th ) ++tens; 986 }987988 // now do the rounding in integer land989 frac_digits = ( frac_digits & 0x80000000 ) ? ( (frac_digits&0x7ffffff) + 1 ) : ( tens + frac_digits );990 if ( ( frac_digits < 24 ) )991 {992 rU32 dg = 1; if ((rU64)bits >= rrpot[9] ) dg=10; while( (rU64)bits >= rrpot[dg] ) { ++dg; if (dg==20) goto noround; }993 if ( frac_digits < dg )994 {995 rU64 r;996 // add 0.5 at the right position and round997 e = dg - frac_digits;998 if ( (rU32)e >= 24 ) goto noround;999 r = rrpot[e];1000 bits = bits + (r/2);1001 if ( (rU64)bits >= rrpot[dg] ) ++tens;1002 bits /= r;1003 } 1004 noround:;1005 }10061007 // kill long trailing runs of zeros1008 if ( bits )1009 {1010 rU32 n; for(;;) { if ( bits<=0xffffffff ) break; if (bits%1000) goto donez; bits/=1000; } n = (rU32)bits; while ((n%1000)==0) n/=1000; bits=n; donez:;1011 }10121013 // convert to string1014 out += 64;1015 e = 0; 1016 for(;;)1017 {1018 rU32 n;1019 char * o = out-8;1020 // do the conversion in chunks of U32s (avoid most 64-bit divides, worth it, constant denomiators be damned)1021 if (bits>=100000000) { n = (rU32)( bits % 100000000); bits /= 100000000; } else {n = (rU32)bits; bits = 0; }1022 while(n) { out-=2; *(rU16*)out=*(rU16*)&rrdiglookup[(n%100)*2]; n/=100; e+=2; }1023 if (bits==0) { if ((e) && (out[0]=='0')) { ++out; --e; } break; }1024 while( out!=o ) { *--out ='0'; ++e; }1025 }1026 1027 *decimal_pos = tens;1028 *start = out;1029 *len = e;1030 return ng;1031}10321033#undef rrddmulthi1034#undef rrddrenorm1035#undef rrddmultlo1036#undef rrddmultlos1037#undef RRSPECIAL 1038#undef RRCOPYFP1039 1040#endif10411042// clean up1043#undef rU161044#undef rU32 1045#undef rS32 1046#undef rU641047#undef rS641048#undef RRPUBLIC_DEC1049#undef RRPUBLIC_DEF1050#undef RR_SPRINTF_DECORATE1051#undef RR_UNALIGNED10521053#endif10541055#endif
modified:tests/grid_reachability.c+3 added
141 unmodified lines
142 tm = (end.QuadPart - start.QuadPart) / (double) freq.QuadPart;143 printf("%6.4lf ms: %s\n", tm * 1000, message);144}145146extern void quicktest(void);147148int loc[5000][2];149int main(int argc, char **argv)150{151 stbcc_grid *g;
1 unmodified line
153 int w,h, i,j,k=0, count=0, r;154 uint8 *map = stbi_load("data/map_03.png", &w, &h, 0, 1);155156 assert(map);157 quicktest();158159 for (j=0; j < h; ++j)160 for (i=0; i < w; ++i)161 map[j*w+i] = ~map[j*w+i];
202 unmodified lines
modified:tests/stb.dsp+4 added-4 removed
88 unmodified lines
89SOURCE=.\grid_reachability.c90# End Source File91# Begin Source File9293SOURCE=..\docs\other_libs.md94# End Source File95# Begin Source File9693SOURCE=.\stb.c94# End Source File95# Begin Source File96
56 unmodified lines
153SOURCE=..\stb_rect_pack.h154# End Source File155# Begin Source File156157SOURCE=..\stb_sprintf.h158# End Source File159# Begin Source File160161SOURCE=..\stb_textedit.h162# End Source File163# Begin Source File164
40 unmodified lines
modified:tests/test_c_compilation.c+12 added
1#include "stb_sprintf.h"2#define STB_SPRINTF_IMPLEMENTATION3#include "stb_sprintf.h"45#define STB_PERLIN_IMPLEMENTATION6#define STB_IMAGE_WRITE_IMPLEMENTATION7#define STB_DXT_IMPLEMENATION8#define STB_C_LEXER_IMPLEMENTATIOn
22 unmodified lines
31#define STBTE_DRAW_RECT(x0,y0,x1,y1,color) 032#define STBTE_DRAW_TILE(x,y,id,highlight,data) 033#define STB_TILEMAP_EDITOR_IMPLEMENTATION34#include "stb_tilemap_editor.h"353637int quicktest(void)38{39 char buffer[999];40 stbsp_sprintf(buffer, "test%%test");41 return 0;42}
modified:tests/test_cpp_compilation.cpp+4 added
1#include "stb_sprintf.h"2#define STB_SPRINTF_IMPLEMENTATION3#include "stb_sprintf.h"45#define STB_TRUETYPE_IMPLEMENTATION6#define STB_PERLIN_IMPLEMENTATION7#define STB_IMAGE_WRITE_IMPLEMENTATION8#define STB_DXT_IMPLEMENATION
138 unmodified lines
modified:tests/test_vorbis.c+4 added
1#define STB_IMAGE_STATIC2#define STB_IMAGE_IMPLEMENTATION3#include "stb_image.h"45#define STB_VORBIS_HEADER_ONLY6#include "stb_vorbis.c"7#include "stb.h"8
14 unmodified lines
modified:tools/README.header.md+4 added
modified:tools/README.list+1 added
2 unmodified lines
3stb_truetype.h | graphics | parse, decode, and rasterize characters from truetype fonts4stb_image_write.h | graphics | image writing to disk: PNG, TGA, BMP5stb_image_resize.h | graphics | resize images larger/smaller with good quality6stb_rect_pack.h | graphics | simple 2D rectangle packer with decent quality7stb_sprintf.h | utility | fast sprintf, snprintf for C/C++8stretchy_buffer.h | utility | typesafe dynamic array for C (i.e. approximation to vector<>), doesn't compile as C++9stb_textedit.h | user interface | guts of a text editor for games etc implementing them from scratch10stb_voxel_render.h | 3D graphics | Minecraft-esque voxel rendering "engine" with many more features11stb_dxt.h | 3D graphics | Fabian "ryg" Giesen's real-time DXT compressor
9 unmodified lines
modified:README.md+9 added-4 removed
modified:stb_image.h+614 added-270 removed
1/* stb_image - v2.12 - public domain image loader - http://nothings.org/stb_image.h1/* stb_image - v2.13 - public domain image loader - http://nothings.org/stb_image.h2 no warranty implied; use at your own risk34 Do this:5 #define STB_IMAGE_IMPLEMENTATION
139 unmodified lines
145 near-term back-compatibility use.146147148 Latest revision history:149 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes150 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes151 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64152 RGB-format JPEG; remove white matting in PSD;153 allocate large structures on the stack;
3 unmodified lines
157 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA158 2.07 (2015-09-13) partial animated GIF support159 limited 16-bit PSD support160 minor bugs, code cleanup, and compiler warnings160 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value161 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning162 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit163 2.03 (2015-04-12) additional corruption checking164 stbi_set_flip_vertically_on_load165 fix NEON support; fix mingw support166 2.02 (2015-01-19) fix incorrect assert, fix warning167 2.01 (2015-01-17) fix various warnings168 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG169 2.00 (2014-12-25) optimize JPEG, including x86 SSE2 & ARM NEON SIMD170 progressive JPEG171 PGM/PPM support172 STBI_MALLOC,STBI_REALLOC,STBI_FREE173 STBI_NO_*, STBI_ONLY_*174 GIF bugfix161162 See end of file for full revision history.163164
24 unmodified lines
189 Jonathan Blow Ken Hamada Tero Hanninen Baldur Karlsson190 Laurent Gomila Cort Stratton Sergio Gonzalez romigrou@github191 Aruelien Pocheville Thibault Reuille Cass Everitt Matthew Gregan192 Ryamond Barbiero Paul Du Bois Engin Manap snagar@github207 Michaelangel007@github Oriol Ferrer Mesia socks-the-fox208 Blazej Dariusz Roszkowski193 Michaelangel007@github Oriol Ferrer Mesia socks-the-fox Zelex@github194 Philipp Wiesemann Josh Tobin rlyeh@github grim210@github195 Blazej Dariusz Roszkowski 196197198LICENSE199
24 unmodified lines
224// // ... but 'n' will always be the number that it would have been if you said 0225// stbi_image_free(data)226//227// Standard parameters:241// int *x -- outputs image width in pixels242// int *y -- outputs image height in pixels243// int *comp -- outputs # of image components in image file244// int req_comp -- if non-zero, # of image components requested in result228// int *x -- outputs image width in pixels229// int *y -- outputs image height in pixels230// int *channels_in_file -- outputs # of image components in image file231// int desired_channels -- if non-zero, # of image components requested in result232//233// The return value from an image loader is an 'unsigned char *' which points234// to the pixel data, or NULL on an allocation failure or if the image is235// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels,
156 unmodified lines
392 STBI_rgb_alpha = 4393};394395typedef unsigned char stbi_uc;396typedef unsigned short stbi_us;397398#ifdef __cplusplus399extern "C" {400#endif
19 unmodified lines
420 void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative421 int (*eof) (void *user); // returns nonzero if we are at end of file/data422} stbi_io_callbacks;423436STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp);437STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *comp, int req_comp);438STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *comp, int req_comp);424////////////////////////////////////425//426// 8-bits-per-channel interface427//428429STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);430STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels);431STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels);432433#ifndef STBI_NO_STDIO441STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);434STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);435// for stbi_load_from_file, file pointer is left pointing immediately after image436#endif437438////////////////////////////////////439//440// 16-bits-per-channel interface441//442443STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);444#ifndef STBI_NO_STDIO445STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);446#endif447// @TODO the other variants448449////////////////////////////////////450//451// float-per-channel interface452//453#ifndef STBI_NO_LINEAR446 STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp);447 STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);448 STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);454 STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels);455 STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels);456 STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels);457458 #ifndef STBI_NO_STDIO451 STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);459 STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels);460 #endif461#endif462463#ifndef STBI_NO_HDR
109 unmodified lines
573#include <stdarg.h>574#include <stddef.h> // ptrdiff_t on osx575#include <stdlib.h>576#include <string.h>577#include <limits.h>578579#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR)580#include <math.h> // ldexp581#endif
253 unmodified lines
835 s->img_buffer = s->img_buffer_original;836 s->img_buffer_end = s->img_buffer_original_end;837}838839enum840{841 STBI_ORDER_RGB,842 STBI_ORDER_BGR843};844845typedef struct846{847 int bits_per_channel;848 int num_channels;849 int channel_order;850} stbi__result_info;851852#ifndef STBI_NO_JPEG853static int stbi__jpeg_test(stbi__context *s);832static stbi_uc *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);854static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);855static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp);856#endif857858#ifndef STBI_NO_PNG859static int stbi__png_test(stbi__context *s);838static stbi_uc *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);860static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);861static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp);862#endif863864#ifndef STBI_NO_BMP865static int stbi__bmp_test(stbi__context *s);844static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);866static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);867static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp);868#endif869870#ifndef STBI_NO_TGA871static int stbi__tga_test(stbi__context *s);850static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);872static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);873static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp);874#endif875876#ifndef STBI_NO_PSD877static int stbi__psd_test(stbi__context *s);856static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);878static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc);879static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp);880#endif881882#ifndef STBI_NO_HDR883static int stbi__hdr_test(stbi__context *s);862static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);884static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);885static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp);886#endif887888#ifndef STBI_NO_PIC889static int stbi__pic_test(stbi__context *s);868static stbi_uc *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);890static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);891static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp);892#endif893894#ifndef STBI_NO_GIF895static int stbi__gif_test(stbi__context *s);874static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);896static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);897static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp);898#endif899900#ifndef STBI_NO_PNM901static int stbi__pnm_test(stbi__context *s);880static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);902static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri);903static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp);904#endif905906// this is not threadsafe
14 unmodified lines
921{922 return STBI_MALLOC(size);923}924925// stb_image uses ints pervasively, including for offset calculations.926// therefore the largest decoded image size we can support with the927// current code, even on 64-bit targets, is INT_MAX. this is not a928// significant limitation for the intended use case.929//930// we do, however, need to make sure our size calculations don't931// overflow. hence a few helper functions for size calculations that932// multiply integers together, making sure that they're non-negative933// and no overflow occurs.934935// return 1 if the sum is valid, 0 on overflow.936// negative terms are considered invalid.937static int stbi__addsizes_valid(int a, int b)938{939 if (b < 0) return 0;940 // now 0 <= b <= INT_MAX, hence also941 // 0 <= INT_MAX - b <= INTMAX.942 // And "a + b <= INT_MAX" (which might overflow) is the943 // same as a <= INT_MAX - b (no overflow)944 return a <= INT_MAX - b;945}946947// returns 1 if the product is valid, 0 on overflow.948// negative factors are considered invalid.949static int stbi__mul2sizes_valid(int a, int b)950{951 if (a < 0 || b < 0) return 0;952 if (b == 0) return 1; // mul-by-0 is always safe953 // portable way to check for no overflows in a*b954 return a <= INT_MAX/b;955}956957// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow958static int stbi__mad2sizes_valid(int a, int b, int add)959{960 return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add);961}962963// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow964static int stbi__mad3sizes_valid(int a, int b, int c, int add)965{966 return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) &&967 stbi__addsizes_valid(a*b*c, add);968}969970// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow971static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add)972{973 return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) &&974 stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add);975}976977// mallocs with size overflow checking978static void *stbi__malloc_mad2(int a, int b, int add)979{980 if (!stbi__mad2sizes_valid(a, b, add)) return NULL;981 return stbi__malloc(a*b + add);982}983984static void *stbi__malloc_mad3(int a, int b, int c, int add)985{986 if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL;987 return stbi__malloc(a*b*c + add);988}989990static void *stbi__malloc_mad4(int a, int b, int c, int d, int add)991{992 if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL;993 return stbi__malloc(a*b*c*d + add);994}995996// stbi__err - error997// stbi__errpf - error returning pointer to float998// stbi__errpuc - error returning pointer to unsigned char999
27 unmodified lines
1027{1028 stbi__vertically_flip_on_load = flag_true_if_should_flip;1029}1030938static unsigned char *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)1031static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc)1032{1033 memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields1034 ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed1035 ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order1036 ri->num_channels = 0;10371038 #ifndef STBI_NO_JPEG941 if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp);1039 if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri);1040 #endif1041 #ifndef STBI_NO_PNG944 if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp);1042 if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri);1043 #endif1044 #ifndef STBI_NO_BMP947 if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp);1045 if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri);1046 #endif1047 #ifndef STBI_NO_GIF950 if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp);1048 if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri);1049 #endif1050 #ifndef STBI_NO_PSD953 if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp);1051 if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc);1052 #endif1053 #ifndef STBI_NO_PIC956 if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp);1054 if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri);1055 #endif1056 #ifndef STBI_NO_PNM959 if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp);1057 if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri);1058 #endif10591060 #ifndef STBI_NO_HDR1061 if (stbi__hdr_test(s)) {964 float *hdr = stbi__hdr_load(s, x,y,comp,req_comp);1062 float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri);1063 return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);1064 }1065 #endif10661067 #ifndef STBI_NO_TGA1068 // test tga last because it's a crappy test!1069 if (stbi__tga_test(s))972 return stbi__tga_load(s,x,y,comp,req_comp);1070 return stbi__tga_load(s,x,y,comp,req_comp, ri);1071 #endif10721073 return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt");1074}1075978static unsigned char *stbi__load_flip(stbi__context *s, int *x, int *y, int *comp, int req_comp)1076static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels)1077{980 unsigned char *result = stbi__load_main(s, x, y, comp, req_comp);1078 int i;1079 int img_len = w * h * channels;1080 stbi_uc *reduced;10811082 reduced = (stbi_uc *) stbi__malloc(img_len);1083 if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory");10841085 for (i = 0; i < img_len; ++i)1086 reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling10871088 STBI_FREE(orig);1089 return reduced;1090}10911092static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels)1093{1094 int i;1095 int img_len = w * h * channels;1096 stbi__uint16 *enlarged;10971098 enlarged = (stbi__uint16 *) stbi__malloc(img_len*2);1099 if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory");11001101 for (i = 0; i < img_len; ++i)1102 enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff11031104 STBI_FREE(orig);1105 return enlarged;1106}11071108static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp)1109{1110 stbi__result_info ri;1111 void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8);11121113 if (result == NULL)1114 return NULL;11151116 if (ri.bits_per_channel != 8) {1117 STBI_ASSERT(ri.bits_per_channel == 16);1118 result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp);1119 ri.bits_per_channel = 8;1120 }11211122 // @TODO: move stbi__convert_format to here1123982 if (stbi__vertically_flip_on_load && result != NULL) {1124 if (stbi__vertically_flip_on_load) {1125 int w = *x, h = *y;984 int depth = req_comp ? req_comp : *comp;1126 int channels = req_comp ? req_comp : *comp;1127 int row,col,z;986 stbi_uc temp;1128 stbi_uc *image = (stbi_uc *) result;11291130 // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once1131 for (row = 0; row < (h>>1); row++) {1132 for (col = 0; col < w; col++) {991 for (z = 0; z < depth; z++) {992 temp = result[(row * w + col) * depth + z];993 result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z];994 result[((h - row - 1) * w + col) * depth + z] = temp;1133 for (z = 0; z < channels; z++) {1134 stbi_uc temp = image[(row * w + col) * channels + z];1135 image[(row * w + col) * channels + z] = image[((h - row - 1) * w + col) * channels + z];1136 image[((h - row - 1) * w + col) * channels + z] = temp;1137 }1138 }1139 }1140 }11411000 return result;1142 return (unsigned char *) result;1143}11441145static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp)1146{1147 stbi__result_info ri;1148 void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16);11491150 if (result == NULL)1151 return NULL;11521153 if (ri.bits_per_channel != 16) {1154 STBI_ASSERT(ri.bits_per_channel == 8);1155 result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp);1156 ri.bits_per_channel = 16;1157 }11581159 // @TODO: move stbi__convert_format16 to here1160 // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision11611162 if (stbi__vertically_flip_on_load) {1163 int w = *x, h = *y;1164 int channels = req_comp ? req_comp : *comp;1165 int row,col,z;1166 stbi__uint16 *image = (stbi__uint16 *) result;11671168 // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once1169 for (row = 0; row < (h>>1); row++) {1170 for (col = 0; col < w; col++) {1171 for (z = 0; z < channels; z++) {1172 stbi__uint16 temp = image[(row * w + col) * channels + z];1173 image[(row * w + col) * channels + z] = image[((h - row - 1) * w + col) * channels + z];1174 image[((h - row - 1) * w + col) * channels + z] = temp;1175 }1176 }1177 }1178 }11791180 return (stbi__uint16 *) result;1181}11821183#ifndef STBI_NO_HDR1184static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp)1185{1186 if (stbi__vertically_flip_on_load && result != NULL) {
45 unmodified lines
1232{1233 unsigned char *result;1234 stbi__context s;1235 stbi__start_file(&s,f);1056 result = stbi__load_flip(&s,x,y,comp,req_comp);1236 result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);1237 if (result) {1238 // need to 'unget' all the characters in the IO buffer1239 fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);1240 }1241 return result;1242}12431244STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp)1245{1246 stbi__uint16 *result;1247 stbi__context s;1248 stbi__start_file(&s,f);1249 result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp);1250 if (result) {1251 // need to 'unget' all the characters in the IO buffer1252 fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);1253 }1254 return result;1255}12561257STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp)1258{1259 FILE *f = stbi__fopen(filename, "rb");1260 stbi__uint16 *result;1261 if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file");1262 result = stbi_load_from_file_16(f,x,y,comp,req_comp);1263 fclose(f);1264 return result;1265}126612671268#endif //!STBI_NO_STDIO12691270STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)1271{1272 stbi__context s;1273 stbi__start_mem(&s,buffer,len);1069 return stbi__load_flip(&s,x,y,comp,req_comp);1274 return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);1275}12761277STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)1278{1279 stbi__context s;1280 stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);1076 return stbi__load_flip(&s,x,y,comp,req_comp);1281 return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp);1282}12831284#ifndef STBI_NO_LINEAR1285static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)1286{1287 unsigned char *data;1288 #ifndef STBI_NO_HDR1289 if (stbi__hdr_test(s)) {1290 stbi__result_info ri;1085 float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp);1291 float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri);1292 if (hdr_data)1293 stbi__float_postprocess(hdr_data,x,y,comp,req_comp);1294 return hdr_data;1295 }1296 #endif1091 data = stbi__load_flip(s, x, y, comp, req_comp);1297 data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp);1298 if (data)1299 return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);1300 return stbi__errpf("unknown image type", "Image not of any known type, or corrupt");1301}
249 unmodified lines
15511552 if (req_comp == img_n) return data;1553 STBI_ASSERT(req_comp >= 1 && req_comp <= 4);15541349 good = (unsigned char *) stbi__malloc(req_comp * x * y);1555 good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0);1556 if (good == NULL) {1557 STBI_FREE(data);1558 return stbi__errpuc("outofmem", "Out of memory");1559 }
1 unmodified line
1561 for (j=0; j < (int) y; ++j) {1562 unsigned char *src = data + j * x * img_n ;1563 unsigned char *dest = good + j * x * req_comp;15641359 #define COMBO(a,b) ((a)*8+(b))1360 #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)1565 #define STBI__COMBO(a,b) ((a)*8+(b))1566 #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)1567 // convert source image with img_n components to one with req_comp components;1568 // avoid switch per pixel, so use switch per scanline and massive macros1363 switch (COMBO(img_n, req_comp)) {1364 CASE(1,2) dest[0]=src[0], dest[1]=255; break;1365 CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;1366 CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;1367 CASE(2,1) dest[0]=src[0]; break;1368 CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;1369 CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;1370 CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;1371 CASE(3,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break;1372 CASE(3,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = 255; break;1373 CASE(4,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break;1374 CASE(4,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;1375 CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;1569 switch (STBI__COMBO(img_n, req_comp)) {1570 STBI__CASE(1,2) { dest[0]=src[0], dest[1]=255; } break;1571 STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;1572 STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; } break;1573 STBI__CASE(2,1) { dest[0]=src[0]; } break;1574 STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;1575 STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; } break;1576 STBI__CASE(3,4) { dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; } break;1577 STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break;1578 STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = 255; } break;1579 STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break;1580 STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = src[3]; } break;1581 STBI__CASE(4,3) { dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; } break;1582 default: STBI_ASSERT(0);1583 }1378 #undef CASE1584 #undef STBI__CASE1585 }15861587 STBI_FREE(data);1588 return good;1589}15901591static stbi__uint16 stbi__compute_y_16(int r, int g, int b)1592{1593 return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8);1594}15951596static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y)1597{1598 int i,j;1599 stbi__uint16 *good;16001601 if (req_comp == img_n) return data;1602 STBI_ASSERT(req_comp >= 1 && req_comp <= 4);16031604 good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2);1605 if (good == NULL) {1606 STBI_FREE(data);1607 return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory");1608 }16091610 for (j=0; j < (int) y; ++j) {1611 stbi__uint16 *src = data + j * x * img_n ;1612 stbi__uint16 *dest = good + j * x * req_comp;16131614 #define STBI__COMBO(a,b) ((a)*8+(b))1615 #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)1616 // convert source image with img_n components to one with req_comp components;1617 // avoid switch per pixel, so use switch per scanline and massive macros1618 switch (STBI__COMBO(img_n, req_comp)) {1619 STBI__CASE(1,2) { dest[0]=src[0], dest[1]=0xffff; } break;1620 STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;1621 STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0], dest[3]=0xffff; } break;1622 STBI__CASE(2,1) { dest[0]=src[0]; } break;1623 STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break;1624 STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; } break;1625 STBI__CASE(3,4) { dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=0xffff; } break;1626 STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break;1627 STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]), dest[1] = 0xffff; } break;1628 STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break;1629 STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]), dest[1] = src[3]; } break;1630 STBI__CASE(4,3) { dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; } break;1631 default: STBI_ASSERT(0);1632 }1633 #undef STBI__CASE1634 }16351636 STBI_FREE(data);1637 return good;1638}16391640#ifndef STBI_NO_LINEAR1641static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp)1642{1643 int i,k,n;1389 float *output = (float *) stbi__malloc(x * y * comp * sizeof(float));1644 float *output;1645 if (!data) return NULL;1646 output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0);1647 if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); }1648 // compute number of non-alpha components1649 if (comp & 1) n = comp; else n = comp-1;1650 for (i=0; i < x*y; ++i) {
11 unmodified lines
1662#define stbi__float2int(x) ((int) (x))1663static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp)1664{1665 int i,k,n;1409 stbi_uc *output = (stbi_uc *) stbi__malloc(x * y * comp);1666 stbi_uc *output;1667 if (!data) return NULL;1668 output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0);1669 if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); }1670 // compute number of non-alpha components1671 if (comp & 1) n = comp; else n = comp-1;1672 for (i=0; i < x*y; ++i) {
1286 unmodified lines
29592960 return 1;2961}29622963static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why)2964{2965 int i;2966 for (i=0; i < ncomp; ++i) {2967 if (z->img_comp[i].raw_data) {2968 STBI_FREE(z->img_comp[i].raw_data);2969 z->img_comp[i].raw_data = NULL;2970 z->img_comp[i].data = NULL;2971 }2972 if (z->img_comp[i].raw_coeff) {2973 STBI_FREE(z->img_comp[i].raw_coeff);2974 z->img_comp[i].raw_coeff = 0;2975 z->img_comp[i].coeff = 0;2976 }2977 if (z->img_comp[i].linebuf) {2978 STBI_FREE(z->img_comp[i].linebuf);2979 z->img_comp[i].linebuf = NULL;2980 }2981 }2982 return why;2983}29842985static int stbi__process_frame_header(stbi__jpeg *z, int scan)2986{2987 stbi__context *s = z->s;2988 int Lf,p,i,q, h_max=1,v_max=1,c;
29 unmodified lines
3018 }30193020 if (scan != STBI__SCAN_load) return 1;30212741 if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode");3022 if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode");30233024 for (i=0; i < s->img_n; ++i) {3025 if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;3026 if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
3 unmodified lines
3030 z->img_h_max = h_max;3031 z->img_v_max = v_max;3032 z->img_mcu_w = h_max * 8;3033 z->img_mcu_h = v_max * 8;3034 // these sizes can't be more than 17 bits3035 z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;3036 z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;30373038 for (i=0; i < s->img_n; ++i) {
3 unmodified lines
3042 // to simplify generation, we'll allocate enough memory to decode3043 // the bogus oversized data from using interleaved MCUs and their3044 // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't3045 // discard the extra data until colorspace conversion3046 //3047 // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier)3048 // so these muls can't overflow with 32-bit ints (which we require)3049 z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;3050 z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;2766 z->img_comp[i].raw_data = stbi__malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);27672768 if (z->img_comp[i].raw_data == NULL) {2769 for(--i; i >= 0; --i) {2770 STBI_FREE(z->img_comp[i].raw_data);2771 z->img_comp[i].raw_data = NULL;2772 }2773 return stbi__err("outofmem", "Out of memory");2774 }3051 z->img_comp[i].coeff = 0;3052 z->img_comp[i].raw_coeff = 0;3053 z->img_comp[i].linebuf = NULL;3054 z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15);3055 if (z->img_comp[i].raw_data == NULL)3056 return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory"));3057 // align blocks for idct using mmx/sse3058 z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);2777 z->img_comp[i].linebuf = NULL;3059 if (z->progressive) {2779 z->img_comp[i].coeff_w = (z->img_comp[i].w2 + 7) >> 3;2780 z->img_comp[i].coeff_h = (z->img_comp[i].h2 + 7) >> 3;2781 z->img_comp[i].raw_coeff = STBI_MALLOC(z->img_comp[i].coeff_w * z->img_comp[i].coeff_h * 64 * sizeof(short) + 15);3060 // w2, h2 are multiples of 8 (see above)3061 z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8;3062 z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8;3063 z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15);3064 if (z->img_comp[i].raw_coeff == NULL)3065 return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory"));3066 z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15);2783 } else {2784 z->img_comp[i].coeff = 0;2785 z->img_comp[i].raw_coeff = 0;3067 }3068 }30693070 return 1;
497 unmodified lines
35683569// clean up the temporary component buffers3570static void stbi__cleanup_jpeg(stbi__jpeg *j)3571{3291 int i;3292 for (i=0; i < j->s->img_n; ++i) {3293 if (j->img_comp[i].raw_data) {3294 STBI_FREE(j->img_comp[i].raw_data);3295 j->img_comp[i].raw_data = NULL;3296 j->img_comp[i].data = NULL;3297 }3298 if (j->img_comp[i].raw_coeff) {3299 STBI_FREE(j->img_comp[i].raw_coeff);3300 j->img_comp[i].raw_coeff = 0;3301 j->img_comp[i].coeff = 0;3302 }3303 if (j->img_comp[i].linebuf) {3304 STBI_FREE(j->img_comp[i].linebuf);3305 j->img_comp[i].linebuf = NULL;3306 }3307 }3572 stbi__free_jpeg_components(j, j->s->img_n, 0);3573}35743575typedef struct3576{
55 unmodified lines
3632 else r->resample = stbi__resample_row_generic;3633 }36343635 // can't error after this so, this is safe3371 output = (stbi_uc *) stbi__malloc(n * z->s->img_x * z->s->img_y + 1);3636 output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1);3637 if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }36383639 // now go ahead and resample3640 for (j=0; j < z->s->img_y; ++j) {
47 unmodified lines
3688 return output;3689 }3690}36913427static unsigned char *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)3692static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)3693{3694 unsigned char* result;3695 stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg));3696 j->s = s;
288 unmodified lines
39853986 int hlit = stbi__zreceive(a,5) + 257;3987 int hdist = stbi__zreceive(a,5) + 1;3988 int hclen = stbi__zreceive(a,4) + 4;3989 int ntot = hlit + hdist;39903991 memset(codelength_sizes, 0, sizeof(codelength_sizes));3992 for (i=0; i < hclen; ++i) {3993 int s = stbi__zreceive(a,3);
1 unmodified line
3995 }3996 if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;39973998 n = 0;3733 while (n < hlit + hdist) {3999 while (n < ntot) {4000 int c = stbi__zhuffman_decode(a, &z_codelength);4001 if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG");4002 if (c < 16)4003 lencodes[n++] = (stbi_uc) c;3738 else if (c == 16) {3739 c = stbi__zreceive(a,2)+3;3740 memset(lencodes+n, lencodes[n-1], c);4004 else {4005 stbi_uc fill = 0;4006 if (c == 16) {4007 c = stbi__zreceive(a,2)+3;4008 if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG");4009 fill = lencodes[n-1];4010 } else if (c == 17)4011 c = stbi__zreceive(a,3)+3;4012 else {4013 STBI_ASSERT(c == 18);4014 c = stbi__zreceive(a,7)+11;4015 }4016 if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG");4017 memset(lencodes+n, fill, c);4018 n += c;3742 } else if (c == 17) {3743 c = stbi__zreceive(a,3)+3;3744 memset(lencodes+n, 0, c);3745 n += c;3746 } else {3747 STBI_ASSERT(c == 18);3748 c = stbi__zreceive(a,7)+11;3749 memset(lencodes+n, 0, c);3750 n += c;4019 }4020 }3753 if (n != hlit+hdist) return stbi__err("bad codelengths","Corrupt PNG");4021 if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG");4022 if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;4023 if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;4024 return 1;4025}
257 unmodified lines
4283 int filter_bytes = img_n*bytes;4284 int width = x;42854286 STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1);4019 a->out = (stbi_uc *) stbi__malloc(x * y * output_bytes); // extra bytes to write off the end into4287 a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into4288 if (!a->out) return stbi__err("outofmem", "Out of memory");42894290 img_width_bytes = (((img_n * x * depth) + 7) >> 3);4291 img_len = (img_width_bytes + 1) * y;
56 unmodified lines
43484349 // this is a little gross, so that we don't switch per-pixel or per-component4350 if (depth < 8 || img_n == out_n) {4351 int nk = (width - 1)*filter_bytes;4084 #define CASE(f) \4352 #define STBI__CASE(f) \4353 case f: \4354 for (k=0; k < nk; ++k)4355 switch (filter) {4356 // "none" filter turns into a memcpy here; make that explicit.4357 case STBI__F_none: memcpy(cur, raw, nk); break;4090 CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); break;4091 CASE(STBI__F_up) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break;4092 CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); break;4093 CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); break;4094 CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); break;4095 CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); break;4358 STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); } break;4359 STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break;4360 STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); } break;4361 STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); } break;4362 STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); } break;4363 STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); } break;4364 }4097 #undef CASE4365 #undef STBI__CASE4366 raw += nk;4367 } else {4368 STBI_ASSERT(img_n+1 == out_n);4101 #define CASE(f) \4369 #define STBI__CASE(f) \4370 case f: \4371 for (i=x-1; i >= 1; --i, cur[filter_bytes]=255,raw+=filter_bytes,cur+=output_bytes,prior+=output_bytes) \4372 for (k=0; k < filter_bytes; ++k)4373 switch (filter) {4106 CASE(STBI__F_none) cur[k] = raw[k]; break;4107 CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); break;4108 CASE(STBI__F_up) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break;4109 CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); break;4110 CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); break;4111 CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); break;4112 CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); break;4374 STBI__CASE(STBI__F_none) { cur[k] = raw[k]; } break;4375 STBI__CASE(STBI__F_sub) { cur[k] = STBI__BYTECAST(raw[k] + cur[k- output_bytes]); } break;4376 STBI__CASE(STBI__F_up) { cur[k] = STBI__BYTECAST(raw[k] + prior[k]); } break;4377 STBI__CASE(STBI__F_avg) { cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k- output_bytes])>>1)); } break;4378 STBI__CASE(STBI__F_paeth) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],prior[k],prior[k- output_bytes])); } break;4379 STBI__CASE(STBI__F_avg_first) { cur[k] = STBI__BYTECAST(raw[k] + (cur[k- output_bytes] >> 1)); } break;4380 STBI__CASE(STBI__F_paeth_first) { cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k- output_bytes],0,0)); } break;4381 }4114 #undef CASE4382 #undef STBI__CASE43834384 // the loop above sets the high byte of the pixels' alpha, but for4385 // 16 bit png files we also need the low byte set. we'll do that here.4386 if (depth == 16) {
94 unmodified lines
4481}44824483static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced)4484{4485 int bytes = (depth == 16 ? 2 : 1);4486 int out_bytes = out_n * bytes;4487 stbi_uc *final;4488 int p;4489 if (!interlaced)4490 return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color);44914492 // de-interlacing4223 final = (stbi_uc *) stbi__malloc(a->s->img_x * a->s->img_y * out_n);4493 final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0);4494 for (p=0; p < 7; ++p) {4495 int xorig[] = { 0,4,0,2,0,1,0 };4496 int yorig[] = { 0,0,4,0,2,0,1 };4497 int xspc[] = { 8,8,4,4,2,2,1 };
11 unmodified lines
4509 for (j=0; j < y; ++j) {4510 for (i=0; i < x; ++i) {4511 int out_y = j*yspc[p]+yorig[p];4512 int out_x = i*xspc[p]+xorig[p];4243 memcpy(final + out_y*a->s->img_x*out_n + out_x*out_n,4244 a->out + (j*x+i)*out_n, out_n);4513 memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes,4514 a->out + (j*x+i)*out_bytes, out_bytes);4515 }4516 }4517 STBI_FREE(a->out);4518 image_data += img_len;
59 unmodified lines
4578{4579 stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;4580 stbi_uc *p, *temp_out, *orig = a->out;45814312 p = (stbi_uc *) stbi__malloc(pixel_count * pal_img_n);4582 p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0);4583 if (p == NULL) return stbi__err("outofmem", "Out of memory");45844585 // between here and free(out) below, exitting would leak4586 temp_out = p;
23 unmodified lines
46104611 return 1;4612}46134344static int stbi__reduce_png(stbi__png *p)4345{4346 int i;4347 int img_len = p->s->img_x * p->s->img_y * p->s->img_out_n;4348 stbi_uc *reduced;4349 stbi__uint16 *orig = (stbi__uint16*)p->out;43504351 if (p->depth != 16) return 1; // don't need to do anything if not 16-bit data43524353 reduced = (stbi_uc *)stbi__malloc(img_len);4354 if (p == NULL) return stbi__err("outofmem", "Out of memory");43554356 for (i = 0; i < img_len; ++i) reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is a decent approx of 16->8 bit scaling43574358 p->out = reduced;4359 STBI_FREE(orig);43604361 return 1;4362}43634614static int stbi__unpremultiply_on_load = 0;4615static int stbi__de_iphone_flag = 0;46164617STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
131 unmodified lines
4749 if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG");4750 if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG");4751 has_trans = 1;4752 if (z->depth == 16) {4503 for (k = 0; k < s->img_n; ++k) tc16[k] = stbi__get16be(s); // copy the values as-is4753 for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is4754 } else {4755 for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger4756 }4757 }
78 unmodified lines
4836 stbi__get32be(s);4837 }4838}48394590static unsigned char *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp)4840static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri)4841{4592 unsigned char *result=NULL;4842 void *result=NULL;4843 if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");4844 if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) {4595 if (p->depth == 16) {4596 if (!stbi__reduce_png(p)) {4597 return result;4598 }4599 }4845 ri->bits_per_channel = p->depth;4846 result = p->out;4847 p->out = NULL;4848 if (req_comp && req_comp != p->s->img_out_n) {4849 if (ri->bits_per_channel == 8)4603 result = stbi__convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);4850 result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);4851 else4852 result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);4853 p->s->img_out_n = req_comp;4854 if (result == NULL) return result;4855 }4856 *x = p->s->img_x;
6 unmodified lines
48634864 return result;4865}48664618static unsigned char *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)4867static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)4868{4869 stbi__png p;4870 p.s = s;4622 return stbi__do_png(&p, x,y,comp,req_comp);4871 return stbi__do_png(&p, x,y,comp,req_comp, ri);4872}48734874static int stbi__png_test(stbi__context *s)4875{
179 unmodified lines
5055 return (void *) 1;5056}505750584810static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)5059static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)5060{5061 stbi_uc *out;5062 unsigned int mr=0,mg=0,mb=0,ma=0, all_a;5063 stbi_uc pal[256][4];5064 int psize=0,i,j,width;5065 int flip_vertically, pad, target;5066 stbi__bmp_data info;5067 STBI_NOTUSED(ri);50685069 info.all_a = 255; 5070 if (stbi__bmp_parse_header(s, &info) == NULL)5071 return NULL; // error code already set
20 unmodified lines
5092 target = req_comp;5093 else5094 target = s->img_n; // if they want monochrome, we'll post-convert50954846 out = (stbi_uc *) stbi__malloc(target * s->img_x * s->img_y);5096 // sanity-check size5097 if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0))5098 return stbi__errpuc("too large", "Corrupt BMP");50995100 out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0);5101 if (!out) return stbi__errpuc("outofmem", "Out of memory");5102 if (info.bpp < 16) {5103 int z=0;5104 if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); }
225 unmodified lines
5330 return res;5331}53325333// read 16bit value and convert to 24bit RGB5080void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out)5334static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out)5335{5082 stbi__uint16 px = stbi__get16le(s);5336 stbi__uint16 px = (stbi__uint16)stbi__get16le(s);5337 stbi__uint16 fiveBitMask = 31;5338 // we have 3 channels with 5bits each5339 int r = (px >> 10) & fiveBitMask;5340 int g = (px >> 5) & fiveBitMask;5341 int b = px & fiveBitMask;5342 // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later5089 out[0] = (r * 255)/31;5090 out[1] = (g * 255)/31;5091 out[2] = (b * 255)/31;5343 out[0] = (stbi_uc)((r * 255)/31);5344 out[1] = (stbi_uc)((g * 255)/31);5345 out[2] = (stbi_uc)((b * 255)/31);53465347 // some people claim that the most significant bit might be used for alpha5348 // (possibly if an alpha-bit is set in the "image descriptor byte")5349 // but that only made 16bit test images completely translucent..5350 // so let's treat all 15 and 16bit TGAs as RGB with no alpha.5351}53525099static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)5353static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)5354{5355 // read in the TGA header stuff5356 int tga_offset = stbi__get8(s);5357 int tga_indexed = stbi__get8(s);
17 unmodified lines
5375 unsigned char raw_data[4];5376 int RLE_count = 0;5377 int RLE_repeating = 0;5378 int read_next_pixel = 1;5379 STBI_NOTUSED(ri);53805381 // do a tiny bit of precessing5382 if ( tga_image_type >= 8 )5383 {
13 unmodified lines
5397 *x = tga_width;5398 *y = tga_height;5399 if (comp) *comp = tga_comp;54005146 tga_data = (unsigned char*)stbi__malloc( (size_t)tga_width * tga_height * tga_comp );5401 if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0))5402 return stbi__errpuc("too large", "Corrupt TGA");54035404 tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0);5405 if (!tga_data) return stbi__errpuc("outofmem", "Out of memory");54065407 // skip to the data's starting position (offset usually = 0)5408 stbi__skip(s, tga_offset );
10 unmodified lines
5419 {5420 // any data to skip? (offset usually = 0)5421 stbi__skip(s, tga_palette_start );5422 // load the palette5165 tga_palette = (unsigned char*)stbi__malloc( tga_palette_len * tga_comp );5423 tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0);5424 if (!tga_palette) {5425 STBI_FREE(tga_data);5426 return stbi__errpuc("outofmem", "Out of memory");5427 }
127 unmodified lines
5555 stbi__rewind(s);5556 return r;5557}55585301static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)5559static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount)5560{5561 int count, nleft, len;55625563 count = 0;5564 while ((nleft = pixelCount - count) > 0) {5565 len = stbi__get8(s);5566 if (len == 128) {5567 // No-op.5568 } else if (len < 128) {5569 // Copy next len+1 bytes literally.5570 len++;5571 if (len > nleft) return 0; // corrupt data5572 count += len;5573 while (len) {5574 *p = stbi__get8(s);5575 p += 4;5576 len--;5577 }5578 } else if (len > 128) {5579 stbi_uc val;5580 // Next -len+1 bytes in the dest are replicated from next source byte.5581 // (Interpret len as a negative 8-bit int.)5582 len = 257 - len;5583 if (len > nleft) return 0; // corrupt data5584 val = stbi__get8(s);5585 count += len;5586 while (len) {5587 *p = val;5588 p += 4;5589 len--;5590 }5591 }5592 }55935594 return 1;5595}55965597static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc)5598{5303 int pixelCount;5599 int pixelCount;5600 int channelCount, compression;5305 int channel, i, count, len;5601 int channel, i;5602 int bitdepth;5603 int w,h;5604 stbi_uc *out;5605 STBI_NOTUSED(ri);56065607 // Check identifier5608 if (stbi__get32be(s) != 0x38425053) // "8BPS"5609 return stbi__errpuc("not PSD", "Corrupt PSD image");
48 unmodified lines
5658 compression = stbi__get16be(s);5659 if (compression > 1)5660 return stbi__errpuc("bad compression", "PSD has an unknown compression format");56615662 // Check size5663 if (!stbi__mad3sizes_valid(4, w, h, 0))5664 return stbi__errpuc("too large", "Corrupt PSD");56655666 // Create the destination image.56675668 if (!compression && bitdepth == 16 && bpc == 16) {5669 out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0);5670 ri->bits_per_channel = 16;5671 } else5366 out = (stbi_uc *) stbi__malloc(4 * w*h);5672 out = (stbi_uc *) stbi__malloc(4 * w*h);56735674 if (!out) return stbi__errpuc("outofmem", "Out of memory");5675 pixelCount = w*h;56765677 // Initialize the data to zero.
23 unmodified lines
5701 for (i = 0; i < pixelCount; i++, p += 4)5702 *p = (channel == 3 ? 255 : 0);5703 } else {5704 // Read the RLE data.5398 count = 0;5399 while (count < pixelCount) {5400 len = stbi__get8(s);5401 if (len == 128) {5402 // No-op.5403 } else if (len < 128) {5404 // Copy next len+1 bytes literally.5405 len++;5406 count += len;5407 while (len) {5408 *p = stbi__get8(s);5409 p += 4;5410 len--;5411 }5412 } else if (len > 128) {5413 stbi_uc val;5414 // Next -len+1 bytes in the dest are replicated from next source byte.5415 // (Interpret len as a negative 8-bit int.)5416 len ^= 0x0FF;5417 len += 2;5418 val = stbi__get8(s);5419 count += len;5420 while (len) {5421 *p = val;5422 p += 4;5423 len--;5424 }5425 }5705 if (!stbi__psd_decode_rle(s, p, pixelCount)) {5706 STBI_FREE(out);5707 return stbi__errpuc("corrupt", "bad RLE data");5708 }5709 }5710 }57115712 } else {5713 // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)5432 // where each channel consists of an 8-bit value for each pixel in the image.5714 // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image.57155716 // Read the data by channel.5717 for (channel = 0; channel < 4; channel++) {5436 stbi_uc *p;54375438 p = out + channel;5718 if (channel >= channelCount) {5719 // Fill this channel with default data.5441 stbi_uc val = channel == 3 ? 255 : 0;5442 for (i = 0; i < pixelCount; i++, p += 4)5443 *p = val;5444 } else {5445 // Read the data.5446 if (bitdepth == 16) {5447 for (i = 0; i < pixelCount; i++, p += 4)5448 *p = (stbi_uc) (stbi__get16be(s) >> 8);5720 if (bitdepth == 16 && bpc == 16) {5721 stbi__uint16 *q = ((stbi__uint16 *) out) + channel;5722 stbi_uc val = channel == 3 ? 65535 : 0;5723 for (i = 0; i < pixelCount; i++, q += 4)5724 *q = val;5725 } else {5726 stbi_uc *p = out+channel;5727 stbi_uc val = channel == 3 ? 255 : 0;5728 for (i = 0; i < pixelCount; i++, p += 4)5451 *p = stbi__get8(s);5729 *p = val;5730 }5731 } else {5732 if (ri->bits_per_channel == 16) { // output bpc5733 stbi__uint16 *q = ((stbi__uint16 *) out) + channel;5734 for (i = 0; i < pixelCount; i++, q += 4)5735 *q = (stbi__uint16) stbi__get16be(s);5736 } else {5737 stbi_uc *p = out+channel;5738 if (bitdepth == 16) { // input bpc5739 for (i = 0; i < pixelCount; i++, p += 4)5740 *p = (stbi_uc) (stbi__get16be(s) >> 8);5741 } else {5742 for (i = 0; i < pixelCount; i++, p += 4)5743 *p = stbi__get8(s);5744 }5745 }5746 }5747 }5748 }57495750 // remove weird white matte from PSD5751 if (channelCount >= 4) {5458 for (i=0; i < w*h; ++i) {5459 unsigned char *pixel = out + 4*i;5460 if (pixel[3] != 0 && pixel[3] != 255) {5461 // remove weird white matte from PSD5462 float a = pixel[3] / 255.0f;5463 float ra = 1.0f / a;5464 float inv_a = 255.0f * (1 - ra);5465 pixel[0] = (unsigned char) (pixel[0]*ra + inv_a);5466 pixel[1] = (unsigned char) (pixel[1]*ra + inv_a);5467 pixel[2] = (unsigned char) (pixel[2]*ra + inv_a);5752 if (ri->bits_per_channel == 16) {5753 for (i=0; i < w*h; ++i) {5754 stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i;5755 if (pixel[3] != 0 && pixel[3] != 65535) {5756 float a = pixel[3] / 65535.0f;5757 float ra = 1.0f / a;5758 float inv_a = 65535.0f * (1 - ra);5759 pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a);5760 pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a);5761 pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a);5762 }5763 }5764 } else {5765 for (i=0; i < w*h; ++i) {5766 unsigned char *pixel = out + 4*i;5767 if (pixel[3] != 0 && pixel[3] != 255) {5768 float a = pixel[3] / 255.0f;5769 float ra = 1.0f / a;5770 float inv_a = 255.0f * (1 - ra);5771 pixel[0] = (unsigned char) (pixel[0]*ra + inv_a);5772 pixel[1] = (unsigned char) (pixel[1]*ra + inv_a);5773 pixel[2] = (unsigned char) (pixel[2]*ra + inv_a);5774 }5775 }5776 }5777 }57785779 // convert to desired output format5780 if (req_comp && req_comp != 4) {5781 if (ri->bits_per_channel == 16)5782 out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h);5783 else5473 out = stbi__convert_format(out, 4, req_comp, w, h);5784 out = stbi__convert_format(out, 4, req_comp, w, h);5785 if (out == NULL) return out; // stbi__convert_format frees input on failure5786 }57875788 if (comp) *comp = 4;
175 unmodified lines
59645965 return result;5966}59675657static stbi_uc *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp)5968static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri)5969{5970 stbi_uc *result;5971 int i, x,y;5972 STBI_NOTUSED(ri);59735974 for (i=0; i<92; ++i)5975 stbi__get8(s);59765977 x = stbi__get16be(s);5978 y = stbi__get16be(s);5979 if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)");5668 if ((1 << 28) / x < y) return stbi__errpuc("too large", "Image too large to decode");5980 if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode");59815982 stbi__get32be(s); //skip `ratio'5983 stbi__get16be(s); //skip `fields'5984 stbi__get16be(s); //skip `pad'59855986 // intermediate buffer is RGBA5675 result = (stbi_uc *) stbi__malloc(x*y*4);5987 result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0);5988 memset(result, 0xff, x*y*4);59895990 if (!stbi__pic_load_core(s,x,y,comp, result)) {5991 STBI_FREE(result);
250 unmodified lines
62426243 if (g->out == 0 && !stbi__gif_header(s, g, comp,0))6244 return 0; // stbi__g_failure_reason set by stbi__gif_header62456246 if (!stbi__mad3sizes_valid(g->w, g->h, 4, 0))6247 return stbi__errpuc("too large", "GIF too large");62486249 prev_out = g->out;5935 g->out = (stbi_uc *) stbi__malloc(4 * g->w * g->h);6250 g->out = (stbi_uc *) stbi__malloc_mad3(4, g->w, g->h, 0);6251 if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory");62526253 switch ((g->eflags & 0x1C) >> 2) {6254 case 0: // unspecified (also always used on 1st frame)
98 unmodified lines
63536354 STBI_NOTUSED(req_comp);6355}63566042static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)6357static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)6358{6359 stbi_uc *u = 0;6360 stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif));6361 memset(g, 0, sizeof(*g));6362 STBI_NOTUSED(ri);63636364 u = stbi__gif_load_next(s, g, comp, req_comp);6365 if (u == (stbi_uc *) s) u = 0; // end of animated gif marker6366 if (u) {
17 unmodified lines
6384// *************************************************************************************************6385// Radiance RGBE HDR loader6386// originally by Nicolas Schulz6387#ifndef STBI_NO_HDR6072static int stbi__hdr_test_core(stbi__context *s)6388static int stbi__hdr_test_core(stbi__context *s, const char *signature)6389{6074 const char *signature = "#?RADIANCE\n";6390 int i;6391 for (i=0; signature[i]; ++i)6392 if (stbi__get8(s) != signature[i])6078 return 0;6393 return 0;6394 stbi__rewind(s);6395 return 1;6396}63976398static int stbi__hdr_test(stbi__context* s)6399{6084 int r = stbi__hdr_test_core(s);6400 int r = stbi__hdr_test_core(s, "#?RADIANCE\n");6401 stbi__rewind(s);6402 if(!r) {6403 r = stbi__hdr_test_core(s, "#?RGBE\n");6404 stbi__rewind(s);6405 }6406 return r;6407}64086409#define STBI__HDR_BUFLEN 1024
45 unmodified lines
6455 }6456 }6457}64586139static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)6459static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)6460{6461 char buffer[STBI__HDR_BUFLEN];6462 char *token;6463 int valid = 0;
2 unmodified lines
6466 float *hdr_data;6467 int len;6468 unsigned char count, value;6469 int i, j, k, c1,c2, z;6470 const char *headerToken;6471 STBI_NOTUSED(ri);647261516473 // Check identifier6153 if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0)6474 headerToken = stbi__hdr_gettoken(s,buffer);6475 if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0)6476 return stbi__errpf("not HDR", "Corrupt HDR image");64776478 // Parse header6479 for(;;) {
20 unmodified lines
65006501 if (comp) *comp = 3;6502 if (req_comp == 0) req_comp = 3;65036504 if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0))6505 return stbi__errpf("too large", "HDR image is too large");65066507 // Read data6183 hdr_data = (float *) stbi__malloc(height * width * req_comp * sizeof(float));6508 hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0);6509 if (!hdr_data)6510 return stbi__errpf("outofmem", "Out of memory");65116512 // Load image data6513 // image data is stored as some number of sca6514 if ( width < 8 || width >= 32768) {
30 unmodified lines
6545 }6546 len <<= 8;6547 len |= stbi__get8(s);6548 if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); }6222 if (scanline == NULL) scanline = (stbi_uc *) stbi__malloc(width * 4);6549 if (scanline == NULL) {6550 scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0);6551 if (!scanline) {6552 STBI_FREE(hdr_data);6553 return stbi__errpf("outofmem", "Out of memory");6554 }6555 }65566557 for (k = 0; k < 4; ++k) {6558 int nleft;6559 i = 0;6226 while (i < width) {6560 while ((nleft = width - i) > 0) {6561 count = stbi__get8(s);6562 if (count > 128) {6563 // Run6564 value = stbi__get8(s);6565 count -= 128;6566 if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); }6567 for (z = 0; z < count; ++z)6568 scanline[i++ * 4 + k] = value;6569 } else {6570 // Dump6571 if (count > nleft) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); }6572 for (z = 0; z < count; ++z)6573 scanline[i++ * 4 + k] = stbi__get8(s);6574 }6575 }6576 }6577 for (i=0; i < width; ++i)6578 stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);6579 }6580 if (scanline)6244 STBI_FREE(scanline);6581 STBI_FREE(scanline);6582 }65836584 return hdr_data;6585}
169 unmodified lines
6755 }6756 return 1;6757}67586422static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)6759static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri)6760{6761 stbi_uc *out;6762 STBI_NOTUSED(ri);67636764 if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n))6765 return 0;67666767 *x = s->img_x;6768 *y = s->img_y;6769 *comp = s->img_n;67706431 out = (stbi_uc *) stbi__malloc(s->img_n * s->img_x * s->img_y);6771 if (!stbi__mad3sizes_valid(s->img_n, s->img_x, s->img_y, 0))6772 return stbi__errpuc("too large", "PNM too large");67736774 out = (stbi_uc *) stbi__malloc_mad3(s->img_n, s->img_x, s->img_y, 0);6775 if (!out) return stbi__errpuc("outofmem", "Out of memory");6776 stbi__getn(s, out, s->img_n * s->img_x * s->img_y);67776778 if (req_comp && req_comp != s->img_n) {
156 unmodified lines
6935#endif // STB_IMAGE_IMPLEMENTATION69366937/*6938 revision history:6939 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now6940 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes6941 2.11 (2016-04-02) allocate large structures on the stack6942 remove white matting for transparent PSD6943 fix reported channel count for PNG & BMP
156 unmodified lines
added:stb_sprintf.h+1064 added
1// stb_sprintf - v1.01 - public domain snprintf() implementation2// originally by Jeff Roberts / RAD Game Tools, 2015/10/203// http://github.com/nothings/stb4//5// allowed types: sc uidBboXx p AaGgEef n6// lengths : h ll j z t I64 I32 I78#ifndef STB_SPRINTF_H_INCLUDE9#define STB_SPRINTF_H_INCLUDE1011/*12Single file sprintf replacement.1314Originally written by Jeff Roberts at RAD Game Tools - 2015/10/20. 15Hereby placed in public domain.1617This is a full sprintf replacement that supports everything that18the C runtime sprintfs support, including float/double, 64-bit integers,19hex floats, field parameters (%*.*d stuff), length reads backs, etc.2021Why would you need this if sprintf already exists? Well, first off,22it's *much* faster (see below). It's also much smaller than the CRT23versions code-space-wise. We've also added some simple improvements 24that are super handy (commas in thousands, callbacks at buffer full,25for example). Finally, the format strings for MSVC and GCC differ 26for 64-bit integers (among other small things), so this lets you use 27the same format strings in cross platform code.2829It uses the standard single file trick of being both the header file30and the source itself. If you just include it normally, you just get 31the header file function definitions. To get the code, you include32it from a C or C++ file and define STB_SPRINTF_IMPLEMENTATION first.3334It only uses va_args macros from the C runtime to do it's work. It35does cast doubles to S64s and shifts and divides U64s, which does 36drag in CRT code on most platforms.3738It compiles to roughly 8K with float support, and 4K without.39As a comparison, when using MSVC static libs, calling sprintf drags40in 16K.4142API:43====44int stbsp_sprintf( char * buf, char const * fmt, ... )45int stbsp_snprintf( char * buf, int count, char const * fmt, ... )46 Convert an arg list into a buffer. stbsp_snprintf always returns47 a zero-terminated string (unlike regular snprintf).4849int stbsp_vsprintf( char * buf, char const * fmt, va_list va )50int stbsp_vsnprintf( char * buf, int count, char const * fmt, va_list va )51 Convert a va_list arg list into a buffer. stbsp_vsnprintf always returns52 a zero-terminated string (unlike regular snprintf).5354int stbsp_vsprintfcb( STBSP_SPRINTFCB * callback, void * user, char * buf, char const * fmt, va_list va )55 typedef char * STBSP_SPRINTFCB( char const * buf, void * user, int len );56 Convert into a buffer, calling back every STB_SPRINTF_MIN chars.57 Your callback can then copy the chars out, print them or whatever.58 This function is actually the workhorse for everything else.59 The buffer you pass in must hold at least STB_SPRINTF_MIN characters.60 // you return the next buffer to use or 0 to stop converting6162void stbsp_set_separators( char comma, char period )63 Set the comma and period characters to use.6465FLOATS/DOUBLES:66===============67This code uses a internal float->ascii conversion method that uses68doubles with error correction (double-doubles, for ~105 bits of69precision). This conversion is round-trip perfect - that is, an atof70of the values output here will give you the bit-exact double back.7172One difference is that our insignificant digits will be different than 73with MSVC or GCC (but they don't match each other either). We also 74don't attempt to find the minimum length matching float (pre-MSVC15 75doesn't either).7677If you don't need float or doubles at all, define STB_SPRINTF_NOFLOAT78and you'll save 4K of code space.798064-BIT INTS:81============82This library also supports 64-bit integers and you can use MSVC style or83GCC style indicators (%I64d or %lld). It supports the C99 specifiers84for size_t and ptr_diff_t (%jd %zd) as well.8586EXTRAS:87=======88Like some GCCs, for integers and floats, you can use a ' (single quote)89specifier and commas will be inserted on the thousands: "%'d" on 12345 90would print 12,345.9192For integers and floats, you can use a "$" specifier and the number 93will be converted to float and then divided to get kilo, mega, giga or94tera and then printed, so "%$d" 1024 is "1.0 k", "%$.2d" 2536000 is 95"2.42 m", etc.9697In addition to octal and hexadecimal conversions, you can print 98integers in binary: "%b" for 256 would print 100.99100PERFORMANCE vs MSVC 2008 32-/64-bit (GCC is even slower than MSVC):101===================================================================102"%d" across all 32-bit ints (4.8x/4.0x faster than 32-/64-bit MSVC)103"%24d" across all 32-bit ints (4.5x/4.2x faster)104"%x" across all 32-bit ints (4.5x/3.8x faster)105"%08x" across all 32-bit ints (4.3x/3.8x faster)106"%f" across e-10 to e+10 floats (7.3x/6.0x faster)107"%e" across e-10 to e+10 floats (8.1x/6.0x faster)108"%g" across e-10 to e+10 floats (10.0x/7.1x faster)109"%f" for values near e-300 (7.9x/6.5x faster)110"%f" for values near e+300 (10.0x/9.1x faster)111"%e" for values near e-300 (10.1x/7.0x faster)112"%e" for values near e+300 (9.2x/6.0x faster)113"%.320f" for values near e-300 (12.6x/11.2x faster)114"%a" for random values (8.6x/4.3x faster)115"%I64d" for 64-bits with 32-bit values (4.8x/3.4x faster)116"%I64d" for 64-bits > 32-bit values (4.9x/5.5x faster)117"%s%s%s" for 64 char strings (7.1x/7.3x faster)118"...512 char string..." ( 35.0x/32.5x faster!)119*/120121#ifdef STB_SPRINTF_STATIC122#define STBSP__PUBLICDEC static123#define STBSP__PUBLICDEF static124#else125#ifdef __cplusplus126#define STBSP__PUBLICDEC extern "C"127#define STBSP__PUBLICDEF extern "C"128#else129#define STBSP__PUBLICDEC extern 130#define STBSP__PUBLICDEF131#endif132#endif133134#include <stdarg.h> // for va_list()135136#ifndef STB_SPRINTF_MIN137#define STB_SPRINTF_MIN 512 // how many characters per callback138#endif139typedef char * STBSP_SPRINTFCB( char * buf, void * user, int len );140141#ifndef STB_SPRINTF_DECORATE142#define STB_SPRINTF_DECORATE(name) stbsp_##name // define this before including if you want to change the names143#endif144145STBSP__PUBLICDEF int STB_SPRINTF_DECORATE( vsprintf )( char * buf, char const * fmt, va_list va );146STBSP__PUBLICDEF int STB_SPRINTF_DECORATE( vsnprintf )( char * buf, int count, char const * fmt, va_list va );147STBSP__PUBLICDEF int STB_SPRINTF_DECORATE( sprintf ) ( char * buf, char const * fmt, ... );148STBSP__PUBLICDEF int STB_SPRINTF_DECORATE( snprintf )( char * buf, int count, char const * fmt, ... );149150STBSP__PUBLICDEF int STB_SPRINTF_DECORATE( vsprintfcb )( STBSP_SPRINTFCB * callback, void * user, char * buf, char const * fmt, va_list va );151STBSP__PUBLICDEF void STB_SPRINTF_DECORATE( set_separators )( char comma, char period );152153#endif // STB_SPRINTF_H_INCLUDE154155#ifdef STB_SPRINTF_IMPLEMENTATION156157#include <stdlib.h> // for va_arg()158159#define stbsp__uint32 unsigned int160#define stbsp__int32 signed int161162#ifdef _MSC_VER163#define stbsp__uint64 unsigned __int64164#define stbsp__int64 signed __int64165#else166#define stbsp__uint64 unsigned long long167#define stbsp__int64 signed long long168#endif169#define stbsp__uint16 unsigned short170171#ifndef stbsp__uintptr 172#if defined(__ppc64__) || defined(__aarch64__) || defined(_M_X64) || defined(__x86_64__) || defined(__x86_64)173#define stbsp__uintptr stbsp__uint64174#else175#define stbsp__uintptr stbsp__uint32176#endif177#endif178179#ifndef STB_SPRINTF_MSVC_MODE // used for MSVC2013 and earlier (MSVC2015 matches GCC)180#if defined(_MSC_VER) && (_MSC_VER<1900)181#define STB_SPRINTF_MSVC_MODE182#endif183#endif184185#ifdef STB_SPRINTF_NOUNALIGNED // define this before inclusion to force stbsp_sprintf to always use aligned accesses186#define STBSP__UNALIGNED(code)187#else188#define STBSP__UNALIGNED(code) code189#endif190191#ifndef STB_SPRINTF_NOFLOAT192// internal float utility functions193static stbsp__int32 stbsp__real_to_str( char const * * start, stbsp__uint32 * len, char *out, stbsp__int32 * decimal_pos, double value, stbsp__uint32 frac_digits );194static stbsp__int32 stbsp__real_to_parts( stbsp__int64 * bits, stbsp__int32 * expo, double value );195#define STBSP__SPECIAL 0x7000196#endif197198static char stbsp__period='.';199static char stbsp__comma=',';200static char stbsp__digitpair[201]="00010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899";201202STBSP__PUBLICDEF void STB_SPRINTF_DECORATE( set_separators )( char pcomma, char pperiod )203{204 stbsp__period=pperiod;205 stbsp__comma=pcomma;206}207208STBSP__PUBLICDEF int STB_SPRINTF_DECORATE( vsprintfcb )( STBSP_SPRINTFCB * callback, void * user, char * buf, char const * fmt, va_list va )209{210 static char hex[]="0123456789abcdefxp";211 static char hexu[]="0123456789ABCDEFXP";212 char * bf;213 char const * f;214 int tlen = 0;215216 bf = buf;217 f = fmt;218 for(;;)219 {220 stbsp__int32 fw,pr,tz; stbsp__uint32 fl;221222 #define STBSP__LEFTJUST 1223 #define STBSP__LEADINGPLUS 2224 #define STBSP__LEADINGSPACE 4225 #define STBSP__LEADING_0X 8226 #define STBSP__LEADINGZERO 16227 #define STBSP__INTMAX 32228 #define STBSP__TRIPLET_COMMA 64229 #define STBSP__NEGATIVE 128230 #define STBSP__METRIC_SUFFIX 256231 #define STBSP__HALFWIDTH 512232 233 // macros for the callback buffer stuff234 #define stbsp__chk_cb_bufL(bytes) { int len = (int)(bf-buf); if ((len+(bytes))>=STB_SPRINTF_MIN) { tlen+=len; if (0==(bf=buf=callback(buf,user,len))) goto done; } }235 #define stbsp__chk_cb_buf(bytes) { if ( callback ) { stbsp__chk_cb_bufL(bytes); } }236 #define stbsp__flush_cb() { stbsp__chk_cb_bufL(STB_SPRINTF_MIN-1); } //flush if there is even one byte in the buffer237 #define stbsp__cb_buf_clamp(cl,v) cl = v; if ( callback ) { int lg = STB_SPRINTF_MIN-(int)(bf-buf); if (cl>lg) cl=lg; }238239 // fast copy everything up to the next % (or end of string)240 for(;;)241 { 242 while (((stbsp__uintptr)f)&3)243 {244 schk1: if (f[0]=='%') goto scandd;245 schk2: if (f[0]==0) goto endfmt;246 stbsp__chk_cb_buf(1); *bf++=f[0]; ++f;247 } 248 for(;;)249 { 250 stbsp__uint32 v,c;251 v=*(stbsp__uint32*)f; c=(~v)&0x80808080;252 if ((v-0x26262626)&c) goto schk1; 253 if ((v-0x01010101)&c) goto schk2; 254 if (callback) if ((STB_SPRINTF_MIN-(int)(bf-buf))<4) goto schk1;255 *(stbsp__uint32*)bf=v; bf+=4; f+=4;256 }257 } scandd:258259 ++f;260261 // ok, we have a percent, read the modifiers first262 fw = 0; pr = -1; fl = 0; tz = 0;263 264 // flags265 for(;;)266 {267 switch(f[0])268 {269 // if we have left justify270 case '-': fl|=STBSP__LEFTJUST; ++f; continue;271 // if we have leading plus272 case '+': fl|=STBSP__LEADINGPLUS; ++f; continue; 273 // if we have leading space274 case ' ': fl|=STBSP__LEADINGSPACE; ++f; continue; 275 // if we have leading 0x276 case '#': fl|=STBSP__LEADING_0X; ++f; continue; 277 // if we have thousand commas278 case '\'': fl|=STBSP__TRIPLET_COMMA; ++f; continue; 279 // if we have kilo marker280 case '$': fl|=STBSP__METRIC_SUFFIX; ++f; continue; 281 // if we have leading zero282 case '0': fl|=STBSP__LEADINGZERO; ++f; goto flags_done; 283 default: goto flags_done;284 }285 }286 flags_done:287 288 // get the field width289 if ( f[0] == '*' ) {fw = va_arg(va,stbsp__uint32); ++f;} else { while (( f[0] >= '0' ) && ( f[0] <= '9' )) { fw = fw * 10 + f[0] - '0'; f++; } }290 // get the precision291 if ( f[0]=='.' ) { ++f; if ( f[0] == '*' ) {pr = va_arg(va,stbsp__uint32); ++f;} else { pr = 0; while (( f[0] >= '0' ) && ( f[0] <= '9' )) { pr = pr * 10 + f[0] - '0'; f++; } } } 292 293 // handle integer size overrides294 switch(f[0])295 {296 // are we halfwidth?297 case 'h': fl|=STBSP__HALFWIDTH; ++f; break;298 // are we 64-bit (unix style)299 case 'l': ++f; if ( f[0]=='l') { fl|=STBSP__INTMAX; ++f; } break;300 // are we 64-bit on intmax? (c99)301 case 'j': fl|=STBSP__INTMAX; ++f; break; 302 // are we 64-bit on size_t or ptrdiff_t? (c99)303 case 'z': case 't': fl|=((sizeof(char*)==8)?STBSP__INTMAX:0); ++f; break; 304 // are we 64-bit (msft style)305 case 'I': if ( ( f[1]=='6') && ( f[2]=='4') ) { fl|=STBSP__INTMAX; f+=3; }306 else if ( ( f[1]=='3') && ( f[2]=='2') ) { f+=3; }307 else { fl|=((sizeof(void*)==8)?STBSP__INTMAX:0); ++f; } break;308 default: break;309 }310311 // handle each replacement312 switch( f[0] )313 {314 #define STBSP__NUMSZ 512 // big enough for e308 (with commas) or e-307 315 char num[STBSP__NUMSZ]; 316 char lead[8]; 317 char tail[8]; 318 char *s;319 char const *h;320 stbsp__uint32 l,n,cs;321 stbsp__uint64 n64;322 #ifndef STB_SPRINTF_NOFLOAT 323 double fv; 324 #endif325 stbsp__int32 dp; char const * sn;326327 case 's':328 // get the string329 s = va_arg(va,char*); if (s==0) s = (char*)"null";330 // get the length331 sn = s;332 for(;;)333 { 334 if ((((stbsp__uintptr)sn)&3)==0) break;335 lchk:336 if (sn[0]==0) goto ld;337 ++sn;338 }339 n = 0xffffffff;340 if (pr>=0) { n=(stbsp__uint32)(sn-s); if (n>=(stbsp__uint32)pr) goto ld; n=((stbsp__uint32)(pr-n))>>2; }341 while(n) 342 { 343 stbsp__uint32 v=*(stbsp__uint32*)sn;344 if ((v-0x01010101)&(~v)&0x80808080UL) goto lchk; 345 sn+=4; 346 --n;347 }348 goto lchk;349 ld:350351 l = (stbsp__uint32) ( sn - s );352 // clamp to precision353 if ( l > (stbsp__uint32)pr ) l = pr;354 lead[0]=0; tail[0]=0; pr = 0; dp = 0; cs = 0;355 // copy the string in356 goto scopy;357358 case 'c': // char359 // get the character360 s = num + STBSP__NUMSZ -1; *s = (char)va_arg(va,int);361 l = 1;362 lead[0]=0; tail[0]=0; pr = 0; dp = 0; cs = 0;363 goto scopy;364365 case 'n': // weird write-bytes specifier366 { int * d = va_arg(va,int*);367 *d = tlen + (int)( bf - buf ); }368 break;369370#ifdef STB_SPRINTF_NOFLOAT371 case 'A': // float372 case 'a': // hex float373 case 'G': // float374 case 'g': // float375 case 'E': // float376 case 'e': // float377 case 'f': // float378 va_arg(va,double); // eat it379 s = (char*)"No float";380 l = 8;381 lead[0]=0; tail[0]=0; pr = 0; dp = 0; cs = 0;382 goto scopy;383#else384 case 'A': // float385 h=hexu; 386 goto hexfloat;387388 case 'a': // hex float389 h=hex;390 hexfloat: 391 fv = va_arg(va,double);392 if (pr==-1) pr=6; // default is 6393 // read the double into a string394 if ( stbsp__real_to_parts( (stbsp__int64*)&n64, &dp, fv ) )395 fl |= STBSP__NEGATIVE;396 397 s = num+64;398399 // sign400 lead[0]=0; if (fl&STBSP__NEGATIVE) { lead[0]=1; lead[1]='-'; } else if (fl&STBSP__LEADINGSPACE) { lead[0]=1; lead[1]=' '; } else if (fl&STBSP__LEADINGPLUS) { lead[0]=1; lead[1]='+'; };401402 if (dp==-1023) dp=(n64)?-1022:0; else n64|=(((stbsp__uint64)1)<<52);403 n64<<=(64-56);404 if (pr<15) n64+=((((stbsp__uint64)8)<<56)>>(pr*4));405 // add leading chars406 407 #ifdef STB_SPRINTF_MSVC_MODE408 *s++='0';*s++='x';409 #else410 lead[1+lead[0]]='0'; lead[2+lead[0]]='x'; lead[0]+=2;411 #endif412 *s++=h[(n64>>60)&15]; n64<<=4;413 if ( pr ) *s++=stbsp__period;414 sn = s;415416 // print the bits417 n = pr; if (n>13) n = 13; if (pr>(stbsp__int32)n) tz=pr-n; pr = 0;418 while(n--) { *s++=h[(n64>>60)&15]; n64<<=4; }419420 // print the expo421 tail[1]=h[17];422 if (dp<0) { tail[2]='-'; dp=-dp;} else tail[2]='+';423 n = (dp>=1000)?6:((dp>=100)?5:((dp>=10)?4:3));424 tail[0]=(char)n;425 for(;;) { tail[n]='0'+dp%10; if (n<=3) break; --n; dp/=10; }426427 dp = (int)(s-sn);428 l = (int)(s-(num+64));429 s = num+64;430 cs = 1 + (3<<24);431 goto scopy;432433 case 'G': // float434 h=hexu;435 goto dosmallfloat;436437 case 'g': // float438 h=hex;439 dosmallfloat: 440 fv = va_arg(va,double);441 if (pr==-1) pr=6; else if (pr==0) pr = 1; // default is 6442 // read the double into a string443 if ( stbsp__real_to_str( &sn, &l, num, &dp, fv, (pr-1)|0x80000000 ) )444 fl |= STBSP__NEGATIVE;445446 // clamp the precision and delete extra zeros after clamp447 n = pr;448 if ( l > (stbsp__uint32)pr ) l = pr; while ((l>1)&&(pr)&&(sn[l-1]=='0')) { --pr; --l; }449450 // should we use %e451 if ((dp<=-4)||(dp>(stbsp__int32)n))452 {453 if ( pr > (stbsp__int32)l ) pr = l-1; else if ( pr ) --pr; // when using %e, there is one digit before the decimal454 goto doexpfromg;455 }456 // this is the insane action to get the pr to match %g sematics for %f457 if(dp>0) { pr=(dp<(stbsp__int32)l)?l-dp:0; } else { pr = -dp+((pr>(stbsp__int32)l)?l:pr); }458 goto dofloatfromg;459460 case 'E': // float461 h=hexu; 462 goto doexp;463464 case 'e': // float465 h=hex;466 doexp: 467 fv = va_arg(va,double);468 if (pr==-1) pr=6; // default is 6469 // read the double into a string470 if ( stbsp__real_to_str( &sn, &l, num, &dp, fv, pr|0x80000000 ) )471 fl |= STBSP__NEGATIVE;472 doexpfromg: 473 tail[0]=0; 474 lead[0]=0; if (fl&STBSP__NEGATIVE) { lead[0]=1; lead[1]='-'; } else if (fl&STBSP__LEADINGSPACE) { lead[0]=1; lead[1]=' '; } else if (fl&STBSP__LEADINGPLUS) { lead[0]=1; lead[1]='+'; };475 if ( dp == STBSP__SPECIAL ) { s=(char*)sn; cs=0; pr=0; goto scopy; }476 s=num+64; 477 // handle leading chars478 *s++=sn[0];479480 if (pr) *s++=stbsp__period;481482 // handle after decimal483 if ((l-1)>(stbsp__uint32)pr) l=pr+1;484 for(n=1;n<l;n++) *s++=sn[n];485 // trailing zeros486 tz = pr-(l-1); pr=0;487 // dump expo488 tail[1]=h[0xe];489 dp -= 1;490 if (dp<0) { tail[2]='-'; dp=-dp;} else tail[2]='+';491 #ifdef STB_SPRINTF_MSVC_MODE492 n = 5;493 #else494 n = (dp>=100)?5:4;495 #endif496 tail[0]=(char)n;497 for(;;) { tail[n]='0'+dp%10; if (n<=3) break; --n; dp/=10; }498 cs = 1 + (3<<24); // how many tens499 goto flt_lead; 500501 case 'f': // float502 fv = va_arg(va,double);503 doafloat: 504 // do kilos505 if (fl&STBSP__METRIC_SUFFIX) {while(fl<0x4000000) { if ((fv<1024.0) && (fv>-1024.0)) break; fv/=1024.0; fl+=0x1000000; }} 506 if (pr==-1) pr=6; // default is 6507 // read the double into a string508 if ( stbsp__real_to_str( &sn, &l, num, &dp, fv, pr ) )509 fl |= STBSP__NEGATIVE;510 dofloatfromg:511 tail[0]=0;512 // sign513 lead[0]=0; if (fl&STBSP__NEGATIVE) { lead[0]=1; lead[1]='-'; } else if (fl&STBSP__LEADINGSPACE) { lead[0]=1; lead[1]=' '; } else if (fl&STBSP__LEADINGPLUS) { lead[0]=1; lead[1]='+'; };514 if ( dp == STBSP__SPECIAL ) { s=(char*)sn; cs=0; pr=0; goto scopy; }515 s=num+64; 516517 // handle the three decimal varieties518 if (dp<=0) 519 { 520 stbsp__int32 i;521 // handle 0.000*000xxxx522 *s++='0'; if (pr) *s++=stbsp__period; 523 n=-dp; if((stbsp__int32)n>pr) n=pr; i=n; while(i) { if ((((stbsp__uintptr)s)&3)==0) break; *s++='0'; --i; } while(i>=4) { *(stbsp__uint32*)s=0x30303030; s+=4; i-=4; } while(i) { *s++='0'; --i; }524 if ((stbsp__int32)(l+n)>pr) l=pr-n; i=l; while(i) { *s++=*sn++; --i; }525 tz = pr-(n+l);526 cs = 1 + (3<<24); // how many tens did we write (for commas below)527 }528 else529 {530 cs = (fl&STBSP__TRIPLET_COMMA)?((600-(stbsp__uint32)dp)%3):0;531 if ((stbsp__uint32)dp>=l)532 {533 // handle xxxx000*000.0534 n=0; for(;;) { if ((fl&STBSP__TRIPLET_COMMA) && (++cs==4)) { cs = 0; *s++=stbsp__comma; } else { *s++=sn[n]; ++n; if (n>=l) break; } }535 if (n<(stbsp__uint32)dp)536 {537 n = dp - n;538 if ((fl&STBSP__TRIPLET_COMMA)==0) { while(n) { if ((((stbsp__uintptr)s)&3)==0) break; *s++='0'; --n; } while(n>=4) { *(stbsp__uint32*)s=0x30303030; s+=4; n-=4; } }539 while(n) { if ((fl&STBSP__TRIPLET_COMMA) && (++cs==4)) { cs = 0; *s++=stbsp__comma; } else { *s++='0'; --n; } }540 }541 cs = (int)(s-(num+64)) + (3<<24); // cs is how many tens542 if (pr) { *s++=stbsp__period; tz=pr;}543 }544 else545 {546 // handle xxxxx.xxxx000*000547 n=0; for(;;) { if ((fl&STBSP__TRIPLET_COMMA) && (++cs==4)) { cs = 0; *s++=stbsp__comma; } else { *s++=sn[n]; ++n; if (n>=(stbsp__uint32)dp) break; } }548 cs = (int)(s-(num+64)) + (3<<24); // cs is how many tens549 if (pr) *s++=stbsp__period;550 if ((l-dp)>(stbsp__uint32)pr) l=pr+dp;551 while(n<l) { *s++=sn[n]; ++n; }552 tz = pr-(l-dp);553 }554 }555 pr = 0;556 557 // handle k,m,g,t558 if (fl&STBSP__METRIC_SUFFIX) { tail[0]=1; tail[1]=' '; { if (fl>>24) { tail[2]="_kmgt"[fl>>24]; tail[0]=2; } } };559560 flt_lead:561 // get the length that we copied562 l = (stbsp__uint32) ( s-(num+64) );563 s=num+64; 564 goto scopy;565#endif566567 case 'B': // upper binary568 h = hexu;569 goto binary;570571 case 'b': // lower binary572 h = hex;573 binary:574 lead[0]=0;575 if (fl&STBSP__LEADING_0X) { lead[0]=2;lead[1]='0';lead[2]=h[0xb]; }576 l=(8<<4)|(1<<8);577 goto radixnum;578579 case 'o': // octal580 h = hexu;581 lead[0]=0;582 if (fl&STBSP__LEADING_0X) { lead[0]=1;lead[1]='0'; }583 l=(3<<4)|(3<<8);584 goto radixnum;585586 case 'p': // pointer587 fl |= (sizeof(void*)==8)?STBSP__INTMAX:0;588 pr = sizeof(void*)*2;589 fl &= ~STBSP__LEADINGZERO; // 'p' only prints the pointer with zeros590 // drop through to X591 592 case 'X': // upper binary593 h = hexu;594 goto dohexb;595596 case 'x': // lower binary597 h = hex; dohexb:598 l=(4<<4)|(4<<8);599 lead[0]=0;600 if (fl&STBSP__LEADING_0X) { lead[0]=2;lead[1]='0';lead[2]=h[16]; }601 radixnum: 602 // get the number603 if ( fl&STBSP__INTMAX )604 n64 = va_arg(va,stbsp__uint64);605 else606 n64 = va_arg(va,stbsp__uint32);607608 s = num + STBSP__NUMSZ; dp = 0;609 // clear tail, and clear leading if value is zero610 tail[0]=0; if (n64==0) { lead[0]=0; if (pr==0) { l=0; cs = ( ((l>>4)&15)) << 24; goto scopy; } }611 // convert to string612 for(;;) { *--s = h[n64&((1<<(l>>8))-1)]; n64>>=(l>>8); if ( ! ( (n64) || ((stbsp__int32) ( (num+STBSP__NUMSZ) - s ) < pr ) ) ) break; if ( fl&STBSP__TRIPLET_COMMA) { ++l; if ((l&15)==((l>>4)&15)) { l&=~15; *--s=stbsp__comma; } } };613 // get the tens and the comma pos614 cs = (stbsp__uint32) ( (num+STBSP__NUMSZ) - s ) + ( ( ((l>>4)&15)) << 24 );615 // get the length that we copied616 l = (stbsp__uint32) ( (num+STBSP__NUMSZ) - s );617 // copy it618 goto scopy;619620 case 'u': // unsigned621 case 'i':622 case 'd': // integer623 // get the integer and abs it624 if ( fl&STBSP__INTMAX )625 {626 stbsp__int64 i64 = va_arg(va,stbsp__int64); n64 = (stbsp__uint64)i64; if ((f[0]!='u') && (i64<0)) { n64=(stbsp__uint64)-i64; fl|=STBSP__NEGATIVE; }627 }628 else629 {630 stbsp__int32 i = va_arg(va,stbsp__int32); n64 = (stbsp__uint32)i; if ((f[0]!='u') && (i<0)) { n64=(stbsp__uint32)-i; fl|=STBSP__NEGATIVE; }631 }632633 #ifndef STB_SPRINTF_NOFLOAT634 if (fl&STBSP__METRIC_SUFFIX) { if (n64<1024) pr=0; else if (pr==-1) pr=1; fv=(double)(stbsp__int64)n64; goto doafloat; } 635 #endif636637 // convert to string638 s = num+STBSP__NUMSZ; l=0; 639 640 for(;;)641 {642 // do in 32-bit chunks (avoid lots of 64-bit divides even with constant denominators)643 char * o=s-8;644 if (n64>=100000000) { n = (stbsp__uint32)( n64 % 100000000); n64 /= 100000000; } else {n = (stbsp__uint32)n64; n64 = 0; }645 if((fl&STBSP__TRIPLET_COMMA)==0) { while(n) { s-=2; *(stbsp__uint16*)s=*(stbsp__uint16*)&stbsp__digitpair[(n%100)*2]; n/=100; } }646 while (n) { if ( ( fl&STBSP__TRIPLET_COMMA) && (l++==3) ) { l=0; *--s=stbsp__comma; --o; } else { *--s=(char)(n%10)+'0'; n/=10; } }647 if (n64==0) { if ((s[0]=='0') && (s!=(num+STBSP__NUMSZ))) ++s; break; }648 while (s!=o) if ( ( fl&STBSP__TRIPLET_COMMA) && (l++==3) ) { l=0; *--s=stbsp__comma; --o; } else { *--s='0'; }649 }650651 tail[0]=0;652 // sign653 lead[0]=0; if (fl&STBSP__NEGATIVE) { lead[0]=1; lead[1]='-'; } else if (fl&STBSP__LEADINGSPACE) { lead[0]=1; lead[1]=' '; } else if (fl&STBSP__LEADINGPLUS) { lead[0]=1; lead[1]='+'; };654655 // get the length that we copied656 l = (stbsp__uint32) ( (num+STBSP__NUMSZ) - s ); if ( l == 0 ) { *--s='0'; l = 1; }657 cs = l + (3<<24);658 if (pr<0) pr = 0;659660 scopy: 661 // get fw=leading/trailing space, pr=leading zeros662 if (pr<(stbsp__int32)l) pr = l;663 n = pr + lead[0] + tail[0] + tz;664 if (fw<(stbsp__int32)n) fw = n;665 fw -= n;666 pr -= l;667668 // handle right justify and leading zeros669 if ( (fl&STBSP__LEFTJUST)==0 )670 {671 if (fl&STBSP__LEADINGZERO) // if leading zeros, everything is in pr672 { 673 pr = (fw>pr)?fw:pr;674 fw = 0;675 }676 else677 {678 fl &= ~STBSP__TRIPLET_COMMA; // if no leading zeros, then no commas679 }680 }681682 // copy the spaces and/or zeros683 if (fw+pr)684 {685 stbsp__int32 i; stbsp__uint32 c; 686687 // copy leading spaces (or when doing %8.4d stuff)688 if ( (fl&STBSP__LEFTJUST)==0 ) while(fw>0) { stbsp__cb_buf_clamp(i,fw); fw -= i; while(i) { if ((((stbsp__uintptr)bf)&3)==0) break; *bf++=' '; --i; } while(i>=4) { *(stbsp__uint32*)bf=0x20202020; bf+=4; i-=4; } while (i) {*bf++=' '; --i;} stbsp__chk_cb_buf(1); }689 690 // copy leader691 sn=lead+1; while(lead[0]) { stbsp__cb_buf_clamp(i,lead[0]); lead[0] -= (char)i; while (i) {*bf++=*sn++; --i;} stbsp__chk_cb_buf(1); }692 693 // copy leading zeros694 c = cs >> 24; cs &= 0xffffff;695 cs = (fl&STBSP__TRIPLET_COMMA)?((stbsp__uint32)(c-((pr+cs)%(c+1)))):0;696 while(pr>0) { stbsp__cb_buf_clamp(i,pr); pr -= i; if((fl&STBSP__TRIPLET_COMMA)==0) { while(i) { if ((((stbsp__uintptr)bf)&3)==0) break; *bf++='0'; --i; } while(i>=4) { *(stbsp__uint32*)bf=0x30303030; bf+=4; i-=4; } } while (i) { if((fl&STBSP__TRIPLET_COMMA) && (cs++==c)) { cs = 0; *bf++=stbsp__comma; } else *bf++='0'; --i; } stbsp__chk_cb_buf(1); }697 }698699 // copy leader if there is still one700 sn=lead+1; while(lead[0]) { stbsp__int32 i; stbsp__cb_buf_clamp(i,lead[0]); lead[0] -= (char)i; while (i) {*bf++=*sn++; --i;} stbsp__chk_cb_buf(1); }701702 // copy the string703 n = l; while (n) { stbsp__int32 i; stbsp__cb_buf_clamp(i,n); n-=i; STBSP__UNALIGNED( while(i>=4) { *(stbsp__uint32*)bf=*(stbsp__uint32*)s; bf+=4; s+=4; i-=4; } ) while (i) {*bf++=*s++; --i;} stbsp__chk_cb_buf(1); }704705 // copy trailing zeros706 while(tz) { stbsp__int32 i; stbsp__cb_buf_clamp(i,tz); tz -= i; while(i) { if ((((stbsp__uintptr)bf)&3)==0) break; *bf++='0'; --i; } while(i>=4) { *(stbsp__uint32*)bf=0x30303030; bf+=4; i-=4; } while (i) {*bf++='0'; --i;} stbsp__chk_cb_buf(1); }707708 // copy tail if there is one709 sn=tail+1; while(tail[0]) { stbsp__int32 i; stbsp__cb_buf_clamp(i,tail[0]); tail[0] -= (char)i; while (i) {*bf++=*sn++; --i;} stbsp__chk_cb_buf(1); }710711 // handle the left justify712 if (fl&STBSP__LEFTJUST) if (fw>0) { while (fw) { stbsp__int32 i; stbsp__cb_buf_clamp(i,fw); fw-=i; while(i) { if ((((stbsp__uintptr)bf)&3)==0) break; *bf++=' '; --i; } while(i>=4) { *(stbsp__uint32*)bf=0x20202020; bf+=4; i-=4; } while (i--) *bf++=' '; stbsp__chk_cb_buf(1); } }713 break;714715 default: // unknown, just copy code716 s = num + STBSP__NUMSZ -1; *s = f[0];717 l = 1;718 fw=pr=fl=0;719 lead[0]=0; tail[0]=0; pr = 0; dp = 0; cs = 0;720 goto scopy;721 }722 ++f;723 }724 endfmt:725726 if (!callback) 727 *bf = 0;728 else729 stbsp__flush_cb();730 731 done:732 return tlen + (int)(bf-buf);733}734735// cleanup736#undef STBSP__LEFTJUST737#undef STBSP__LEADINGPLUS738#undef STBSP__LEADINGSPACE739#undef STBSP__LEADING_0X740#undef STBSP__LEADINGZERO741#undef STBSP__INTMAX742#undef STBSP__TRIPLET_COMMA743#undef STBSP__NEGATIVE744#undef STBSP__METRIC_SUFFIX745#undef STBSP__NUMSZ746#undef stbsp__chk_cb_bufL747#undef stbsp__chk_cb_buf748#undef stbsp__flush_cb749#undef stbsp__cb_buf_clamp750751// ============================================================================752// wrapper functions753754STBSP__PUBLICDEF int STB_SPRINTF_DECORATE( sprintf )( char * buf, char const * fmt, ... )755{756 va_list va;757 va_start( va, fmt );758 return STB_SPRINTF_DECORATE( vsprintfcb )( 0, 0, buf, fmt, va );759}760761typedef struct stbsp__context762{763 char * buf;764 int count;765 char tmp[ STB_SPRINTF_MIN ];766} stbsp__context;767768static char * stbsp__clamp_callback( char * buf, void * user, int len )769{770 stbsp__context * c = (stbsp__context*)user;771772 if ( len > c->count ) len = c->count;773774 if (len)775 {776 if ( buf != c->buf )777 {778 char * s, * d, * se;779 d = c->buf; s = buf; se = buf+len;780 do{ *d++ = *s++; } while (s<se);781 }782 c->buf += len;783 c->count -= len;784 }785 786 if ( c->count <= 0 ) return 0;787 return ( c->count >= STB_SPRINTF_MIN ) ? c->buf : c->tmp; // go direct into buffer if you can788}789790STBSP__PUBLICDEF int STB_SPRINTF_DECORATE( vsnprintf )( char * buf, int count, char const * fmt, va_list va )791{792 stbsp__context c;793 int l;794795 if ( count == 0 )796 return 0;797798 c.buf = buf;799 c.count = count;800801 STB_SPRINTF_DECORATE( vsprintfcb )( stbsp__clamp_callback, &c, stbsp__clamp_callback(0,&c,0), fmt, va );802 803 // zero-terminate804 l = (int)( c.buf - buf );805 if ( l >= count ) // should never be greater, only equal (or less) than count806 l = count - 1;807 buf[l] = 0;808809 return l;810}811812STBSP__PUBLICDEF int STB_SPRINTF_DECORATE( snprintf )( char * buf, int count, char const * fmt, ... )813{814 va_list va;815 va_start( va, fmt );816817 return STB_SPRINTF_DECORATE( vsnprintf )( buf, count, fmt, va );818}819820STBSP__PUBLICDEF int STB_SPRINTF_DECORATE( vsprintf )( char * buf, char const * fmt, va_list va )821{822 return STB_SPRINTF_DECORATE( vsprintfcb )( 0, 0, buf, fmt, va );823}824825// =======================================================================826// low level float utility functions827828#ifndef STB_SPRINTF_NOFLOAT829830// copies d to bits w/ strict aliasing (this compiles to nothing on /Ox)831#define STBSP__COPYFP(dest,src) { int cn; for(cn=0;cn<8;cn++) ((char*)&dest)[cn]=((char*)&src)[cn]; }832 833// get float info834static stbsp__int32 stbsp__real_to_parts( stbsp__int64 * bits, stbsp__int32 * expo, double value )835{836 double d;837 stbsp__int64 b = 0;838839 // load value and round at the frac_digits840 d = value;841842 STBSP__COPYFP( b, d );843844 *bits = b & ((((stbsp__uint64)1)<<52)-1);845 *expo = (stbsp__int32) (((b >> 52) & 2047)-1023);846 847 return (stbsp__int32)(b >> 63);848}849850static double const stbsp__bot[23]={1e+000,1e+001,1e+002,1e+003,1e+004,1e+005,1e+006,1e+007,1e+008,1e+009,1e+010,1e+011,1e+012,1e+013,1e+014,1e+015,1e+016,1e+017,1e+018,1e+019,1e+020,1e+021,1e+022};851static double const stbsp__negbot[22]={1e-001,1e-002,1e-003,1e-004,1e-005,1e-006,1e-007,1e-008,1e-009,1e-010,1e-011,1e-012,1e-013,1e-014,1e-015,1e-016,1e-017,1e-018,1e-019,1e-020,1e-021,1e-022};852static double const stbsp__negboterr[22]={-5.551115123125783e-018,-2.0816681711721684e-019,-2.0816681711721686e-020,-4.7921736023859299e-021,-8.1803053914031305e-022,4.5251888174113741e-023,4.5251888174113739e-024,-2.0922560830128471e-025,-6.2281591457779853e-026,-3.6432197315497743e-027,6.0503030718060191e-028,2.0113352370744385e-029,-3.0373745563400371e-030,1.1806906454401013e-032,-7.7705399876661076e-032,2.0902213275965398e-033,-7.1542424054621921e-034,-7.1542424054621926e-035,2.4754073164739869e-036,5.4846728545790429e-037,9.2462547772103625e-038,-4.8596774326570872e-039};853static double const stbsp__top[13]={1e+023,1e+046,1e+069,1e+092,1e+115,1e+138,1e+161,1e+184,1e+207,1e+230,1e+253,1e+276,1e+299};854static double const stbsp__negtop[13]={1e-023,1e-046,1e-069,1e-092,1e-115,1e-138,1e-161,1e-184,1e-207,1e-230,1e-253,1e-276,1e-299};855static double const stbsp__toperr[13]={8388608,6.8601809640529717e+028,-7.253143638152921e+052,-4.3377296974619174e+075,-1.5559416129466825e+098,-3.2841562489204913e+121,-3.7745893248228135e+144,-1.7356668416969134e+167,-3.8893577551088374e+190,-9.9566444326005119e+213,6.3641293062232429e+236,-5.2069140800249813e+259,-5.2504760255204387e+282};856static double const stbsp__negtoperr[13]={3.9565301985100693e-040,-2.299904345391321e-063,3.6506201437945798e-086,1.1875228833981544e-109,-5.0644902316928607e-132,-6.7156837247865426e-155,-2.812077463003139e-178,-5.7778912386589953e-201,7.4997100559334532e-224,-4.6439668915134491e-247,-6.3691100762962136e-270,-9.436808465446358e-293,8.0970921678014997e-317};857858#if defined(_MSC_VER) && (_MSC_VER<=1200) 859static stbsp__uint64 const stbsp__powten[20]={1,10,100,1000, 10000,100000,1000000,10000000, 100000000,1000000000,10000000000,100000000000, 1000000000000,10000000000000,100000000000000,1000000000000000, 10000000000000000,100000000000000000,1000000000000000000,10000000000000000000U };860#define stbsp__tento19th ((stbsp__uint64)1000000000000000000)861#else862static stbsp__uint64 const stbsp__powten[20]={1,10,100,1000, 10000,100000,1000000,10000000, 100000000,1000000000,10000000000ULL,100000000000ULL, 1000000000000ULL,10000000000000ULL,100000000000000ULL,1000000000000000ULL, 10000000000000000ULL,100000000000000000ULL,1000000000000000000ULL,10000000000000000000ULL };863#define stbsp__tento19th (1000000000000000000ULL)864#endif865866#define stbsp__ddmulthi(oh,ol,xh,yh) \867{ \868 double ahi=0,alo,bhi=0,blo; \869 stbsp__int64 bt; \870 oh = xh * yh; \871 STBSP__COPYFP(bt,xh); bt&=((~(stbsp__uint64)0)<<27); STBSP__COPYFP(ahi,bt); alo = xh-ahi; \872 STBSP__COPYFP(bt,yh); bt&=((~(stbsp__uint64)0)<<27); STBSP__COPYFP(bhi,bt); blo = yh-bhi; \873 ol = ((ahi*bhi-oh)+ahi*blo+alo*bhi)+alo*blo; \874}875876#define stbsp__ddtoS64(ob,xh,xl) \877{ \878 double ahi=0,alo,vh,t;\879 ob = (stbsp__int64)ph;\880 vh=(double)ob;\881 ahi = ( xh - vh );\882 t = ( ahi - xh );\883 alo = (xh-(ahi-t))-(vh+t);\884 ob += (stbsp__int64)(ahi+alo+xl);\885}886887888#define stbsp__ddrenorm(oh,ol) { double s; s=oh+ol; ol=ol-(s-oh); oh=s; }889890#define stbsp__ddmultlo(oh,ol,xh,xl,yh,yl) \891 ol = ol + ( xh*yl + xl*yh ); \892893#define stbsp__ddmultlos(oh,ol,xh,yl) \894 ol = ol + ( xh*yl ); \895896static void stbsp__raise_to_power10( double *ohi, double *olo, double d, stbsp__int32 power ) // power can be -323 to +350897{898 double ph, pl;899 if ((power>=0) && (power<=22))900 {901 stbsp__ddmulthi(ph,pl,d,stbsp__bot[power]);902 }903 else904 {905 stbsp__int32 e,et,eb;906 double p2h,p2l;907908 e=power; if (power<0) e=-e; 909 et = (e*0x2c9)>>14;/* %23 */ if (et>13) et=13; eb = e-(et*23);910911 ph = d; pl = 0.0;912 if (power<0)913 {914 if (eb) { --eb; stbsp__ddmulthi(ph,pl,d,stbsp__negbot[eb]); stbsp__ddmultlos(ph,pl,d,stbsp__negboterr[eb]); }915 if (et)916 { 917 stbsp__ddrenorm(ph,pl);918 --et; stbsp__ddmulthi(p2h,p2l,ph,stbsp__negtop[et]); stbsp__ddmultlo(p2h,p2l,ph,pl,stbsp__negtop[et],stbsp__negtoperr[et]); ph=p2h;pl=p2l;919 }920 }921 else922 {923 if (eb) 924 { 925 e = eb; if (eb>22) eb=22; e -= eb;926 stbsp__ddmulthi(ph,pl,d,stbsp__bot[eb]); 927 if ( e ) { stbsp__ddrenorm(ph,pl); stbsp__ddmulthi(p2h,p2l,ph,stbsp__bot[e]); stbsp__ddmultlos(p2h,p2l,stbsp__bot[e],pl); ph=p2h;pl=p2l; }928 }929 if (et)930 {931 stbsp__ddrenorm(ph,pl);932 --et; stbsp__ddmulthi(p2h,p2l,ph,stbsp__top[et]); stbsp__ddmultlo(p2h,p2l,ph,pl,stbsp__top[et],stbsp__toperr[et]); ph=p2h;pl=p2l;933 }934 }935 }936 stbsp__ddrenorm(ph,pl);937 *ohi = ph; *olo = pl;938}939940// given a float value, returns the significant bits in bits, and the position of the941// decimal point in decimal_pos. +/-INF and NAN are specified by special values942// returned in the decimal_pos parameter.943// frac_digits is absolute normally, but if you want from first significant digits (got %g and %e), or in 0x80000000944static stbsp__int32 stbsp__real_to_str( char const * * start, stbsp__uint32 * len, char *out, stbsp__int32 * decimal_pos, double value, stbsp__uint32 frac_digits )945{946 double d;947 stbsp__int64 bits = 0;948 stbsp__int32 expo, e, ng, tens;949950 d = value;951 STBSP__COPYFP(bits,d);952 expo = (stbsp__int32) ((bits >> 52) & 2047);953 ng = (stbsp__int32)(bits >> 63);954 if (ng) d=-d;955956 if ( expo == 2047 ) // is nan or inf?957 {958 *start = (bits&((((stbsp__uint64)1)<<52)-1)) ? "NaN" : "Inf";959 *decimal_pos = STBSP__SPECIAL;960 *len = 3;961 return ng;962 } 963964 if ( expo == 0 ) // is zero or denormal965 {966 if ((bits<<1)==0) // do zero967 {968 *decimal_pos = 1; 969 *start = out;970 out[0] = '0'; *len = 1;971 return ng;972 }973 // find the right expo for denormals974 {975 stbsp__int64 v = ((stbsp__uint64)1)<<51;976 while ((bits&v)==0) { --expo; v >>= 1; }977 }978 }979980 // find the decimal exponent as well as the decimal bits of the value981 {982 double ph,pl;983984 // log10 estimate - very specifically tweaked to hit or undershoot by no more than 1 of log10 of all expos 1..2046985 tens=expo-1023; tens = (tens<0)?((tens*617)/2048):(((tens*1233)/4096)+1);986987 // move the significant bits into position and stick them into an int 988 stbsp__raise_to_power10( &ph, &pl, d, 18-tens );989990 // get full as much precision from double-double as possible991 stbsp__ddtoS64( bits, ph,pl );992993 // check if we undershot994 if ( ((stbsp__uint64)bits) >= stbsp__tento19th ) ++tens; 995 }996997 // now do the rounding in integer land998 frac_digits = ( frac_digits & 0x80000000 ) ? ( (frac_digits&0x7ffffff) + 1 ) : ( tens + frac_digits );999 if ( ( frac_digits < 24 ) )1000 {1001 stbsp__uint32 dg = 1; if ((stbsp__uint64)bits >= stbsp__powten[9] ) dg=10; while( (stbsp__uint64)bits >= stbsp__powten[dg] ) { ++dg; if (dg==20) goto noround; }1002 if ( frac_digits < dg )1003 {1004 stbsp__uint64 r;1005 // add 0.5 at the right position and round1006 e = dg - frac_digits;1007 if ( (stbsp__uint32)e >= 24 ) goto noround;1008 r = stbsp__powten[e];1009 bits = bits + (r/2);1010 if ( (stbsp__uint64)bits >= stbsp__powten[dg] ) ++tens;1011 bits /= r;1012 } 1013 noround:;1014 }10151016 // kill long trailing runs of zeros1017 if ( bits )1018 {1019 stbsp__uint32 n;1020 for(;;) { if ( bits<=0xffffffff ) break; if (bits%1000) goto donez; bits/=1000; }1021 n = (stbsp__uint32)bits;1022 while ((n%1000)==0) n/=1000;1023 bits=n;1024 donez:;1025 }10261027 // convert to string1028 out += 64;1029 e = 0; 1030 for(;;)1031 {1032 stbsp__uint32 n;1033 char * o = out-8;1034 // do the conversion in chunks of U32s (avoid most 64-bit divides, worth it, constant denomiators be damned)1035 if (bits>=100000000) { n = (stbsp__uint32)( bits % 100000000); bits /= 100000000; } else {n = (stbsp__uint32)bits; bits = 0; }1036 while(n) { out-=2; *(stbsp__uint16*)out=*(stbsp__uint16*)&stbsp__digitpair[(n%100)*2]; n/=100; e+=2; }1037 if (bits==0) { if ((e) && (out[0]=='0')) { ++out; --e; } break; }1038 while( out!=o ) { *--out ='0'; ++e; }1039 }1040 1041 *decimal_pos = tens;1042 *start = out;1043 *len = e;1044 return ng;1045}10461047#undef stbsp__ddmulthi1048#undef stbsp__ddrenorm1049#undef stbsp__ddmultlo1050#undef stbsp__ddmultlos1051#undef STBSP__SPECIAL 1052#undef STBSP__COPYFP1053 1054#endif // STB_SPRINTF_NOFLOAT10551056// clean up1057#undef stbsp__uint161058#undef stbsp__uint32 1059#undef stbsp__int32 1060#undef stbsp__uint641061#undef stbsp__int641062#undef STBSP__UNALIGNED10631064#endif // STB_SPRINTF_IMPLEMENTATION
modified:stb.h+1 added
728 unmodified lines
729STB_EXTERN int stb_snprintf(char *s, size_t n, const char *fmt, ...);730STB_EXTERN int stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v);731732#ifdef STB_DEFINE733734int stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v)735{736 int res;737 #ifdef _WIN32
13540 unmodified lines