miniz.h 227 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099
  1. /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing
  2. See "unlicense" statement at the end of this file.
  3. Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013
  4. Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt
  5. Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define
  6. MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros).
  7. * Change History
  8. 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!):
  9. - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug
  10. would only have occurred in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place()
  11. (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag).
  12. - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size
  13. - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries.
  14. Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice).
  15. - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes
  16. - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed
  17. - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6.
  18. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti
  19. - Merged MZ_FORCEINLINE fix from hdeanclark
  20. - Fix <time.h> include before config #ifdef, thanks emil.brink
  21. - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can
  22. set it to 1 for real-time compression).
  23. - Merged in some compiler fixes from paulharris's github repro.
  24. - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3.
  25. - Added example6.c, which dumps an image of the mandelbrot set to a PNG file.
  26. - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more.
  27. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled
  28. - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch
  29. 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect).
  30. 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit.
  31. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files.
  32. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64.
  33. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly
  34. "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning).
  35. - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64.
  36. - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test.
  37. - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives.
  38. - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.)
  39. - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself).
  40. 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's.
  41. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <bruced@valvesoftware.com> for the feedback/bug report.
  42. 5/28/11 v1.11 - Added statement from unlicense.org
  43. 5/27/11 v1.10 - Substantial compressor optimizations:
  44. - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a
  45. - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86).
  46. - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types.
  47. - Refactored the compression code for better readability and maintainability.
  48. - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large
  49. drop in throughput on some files).
  50. 5/15/11 v1.09 - Initial stable release.
  51. * Low-level Deflate/Inflate implementation notes:
  52. Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or
  53. greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses
  54. approximately as well as zlib.
  55. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function
  56. coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory
  57. block large enough to hold the entire file.
  58. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation.
  59. * zlib-style API notes:
  60. miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in
  61. zlib replacement in many apps:
  62. The z_stream struct, optional memory allocation callbacks
  63. deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound
  64. inflateInit/inflateInit2/inflate/inflateEnd
  65. compress, compress2, compressBound, uncompress
  66. CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines.
  67. Supports raw deflate streams or standard zlib streams with adler-32 checking.
  68. Limitations:
  69. The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries.
  70. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but
  71. there are no guarantees that miniz.c pulls this off perfectly.
  72. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by
  73. Alex Evans. Supports 1-4 bytes/pixel images.
  74. * ZIP archive API notes:
  75. The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to
  76. get the job done with minimal fuss. There are simple API's to retrieve file information, read files from
  77. existing archives, create new archives, append new files to existing archives, or clone archive data from
  78. one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h),
  79. or you can specify custom file read/write callbacks.
  80. - Archive reading: Just call this function to read a single file from a disk archive:
  81. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name,
  82. size_t *pSize, mz_uint zip_flags);
  83. For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central
  84. directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files.
  85. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file:
  86. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);
  87. The locate operation can optionally check file comments too, which (as one example) can be used to identify
  88. multiple versions of the same file in an archive. This function uses a simple linear search through the central
  89. directory, so it's not very fast.
  90. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and
  91. retrieve detailed info on each file by calling mz_zip_reader_file_stat().
  92. - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data
  93. to disk and builds an exact image of the central directory in memory. The central directory image is written
  94. all at once at the end of the archive file when the archive is finalized.
  95. The archive writer can optionally align each file's local header and file data to any power of 2 alignment,
  96. which can be useful when the archive will be read from optical media. Also, the writer supports placing
  97. arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still
  98. readable by any ZIP tool.
  99. - Archive appending: The simple way to add a single file to an archive is to call this function:
  100. mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name,
  101. const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
  102. The archive will be created if it doesn't already exist, otherwise it'll be appended to.
  103. Note the appending is done in-place and is not an atomic operation, so if something goes wrong
  104. during the operation it's possible the archive could be left without a central directory (although the local
  105. file headers and file data will be fine, so the archive will be recoverable).
  106. For more complex archive modification scenarios:
  107. 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to
  108. preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the
  109. compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and
  110. you're done. This is safe but requires a bunch of temporary disk space or heap memory.
  111. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(),
  112. append new files as needed, then finalize the archive which will write an updated central directory to the
  113. original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a
  114. possibility that the archive's central directory could be lost with this method if anything goes wrong, though.
  115. - ZIP archive support limitations:
  116. No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files.
  117. Requires streams capable of seeking.
  118. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the
  119. below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it.
  120. * Important: For best perf. be sure to customize the below macros for your target platform:
  121. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  122. #define MINIZ_LITTLE_ENDIAN 1
  123. #define MINIZ_HAS_64BIT_REGISTERS 1
  124. * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz
  125. uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files
  126. (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes).
  127. */
  128. #ifndef MINIZ_HEADER_INCLUDED
  129. #define MINIZ_HEADER_INCLUDED
  130. /*#include <stdlib.h>*/
  131. // Defines to completely disable specific portions of miniz.c:
  132. // If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl.
  133. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O.
  134. #define MINIZ_NO_STDIO
  135. // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or
  136. // get/set file times, and the C run-time funcs that get/set times won't be called.
  137. // The current downside is the times written to your archives will be from 1979.
  138. #define MINIZ_NO_TIME
  139. // Define MINIZ_NO_DEFLATE_APIS to disable all compression API's.
  140. //#define MINIZ_NO_DEFLATE_APIS
  141. // Define MINIZ_NO_INFLATE_APIS to disable all decompression API's.
  142. #define MINIZ_NO_INFLATE_APIS
  143. // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's.
  144. #define MINIZ_NO_ARCHIVE_APIS
  145. // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's.
  146. #define MINIZ_NO_ARCHIVE_WRITING_APIS
  147. // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's.
  148. #define MINIZ_NO_ZLIB_APIS
  149. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib.
  150. #define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  151. // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc.
  152. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc
  153. // callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user
  154. // functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work.
  155. //#define MINIZ_NO_MALLOC
  156. #define MINIZ_SDL_MALLOC
  157. #ifdef MINIZ_NO_INFLATE_APIS
  158. #define MINIZ_NO_ARCHIVE_APIS
  159. #endif
  160. #ifdef MINIZ_NO_DEFLATE_APIS
  161. #define MINIZ_NO_ARCHIVE_WRITING_APIS
  162. #endif
  163. // Define MINIZ_STATIC_FUNCTIONS to make all functions static. You probably
  164. // want this if you're using miniz in a library
  165. #define MINIZ_STATIC_FUNCTIONS
  166. #if defined(__TINYC__) && (defined(__linux) || defined(__linux__))
  167. // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux
  168. #define MINIZ_NO_TIME
  169. #endif
  170. #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
  171. #include <time.h>
  172. #endif
  173. #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__)
  174. // MINIZ_X86_OR_X64_CPU is only used to help set the below macros.
  175. #define MINIZ_X86_OR_X64_CPU 1
  176. #endif
  177. #ifndef MINIZ_LITTLE_ENDIAN /* if not defined by SDL */
  178. #if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
  179. // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian.
  180. #define MINIZ_LITTLE_ENDIAN 1
  181. #endif
  182. #endif // MINIZ_LITTLE_ENDIAN /* if not defined by SDL */
  183. #ifndef MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  184. #if MINIZ_X86_OR_X64_CPU
  185. // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses.
  186. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1
  187. #endif
  188. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  189. #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__)
  190. // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions).
  191. #define MINIZ_HAS_64BIT_REGISTERS 1
  192. #endif
  193. #ifdef MINIZ_STATIC_FUNCTIONS
  194. #define MINIZ_STATIC static
  195. #else
  196. #define MINIZ_STATIC
  197. #endif
  198. #ifdef __cplusplus
  199. extern "C" {
  200. #endif
  201. // ------------------- zlib-style API Definitions.
  202. // For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits!
  203. typedef unsigned long mz_ulong;
  204. // mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap.
  205. MINIZ_STATIC void mz_free(void *p);
  206. #define MZ_ADLER32_INIT (1)
  207. // mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL.
  208. MINIZ_STATIC mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len);
  209. #define MZ_CRC32_INIT (0)
  210. // mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL.
  211. MINIZ_STATIC mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len);
  212. // Compression strategies.
  213. enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 };
  214. // Method
  215. #define MZ_DEFLATED 8
  216. #ifndef MINIZ_NO_ZLIB_APIS
  217. // Heap allocation callbacks.
  218. // Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long.
  219. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size);
  220. typedef void (*mz_free_func)(void *opaque, void *address);
  221. typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size);
  222. #define MZ_VERSION "9.1.15"
  223. #define MZ_VERNUM 0x91F0
  224. #define MZ_VER_MAJOR 9
  225. #define MZ_VER_MINOR 1
  226. #define MZ_VER_REVISION 15
  227. #define MZ_VER_SUBREVISION 0
  228. // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs).
  229. enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 };
  230. // Return status codes. MZ_PARAM_ERROR is non-standard.
  231. enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 };
  232. // Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL.
  233. enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 };
  234. // Window bits
  235. #define MZ_DEFAULT_WINDOW_BITS 15
  236. struct mz_internal_state;
  237. // Compression/decompression stream struct.
  238. typedef struct mz_stream_s
  239. {
  240. const unsigned char *next_in; // pointer to next byte to read
  241. unsigned int avail_in; // number of bytes available at next_in
  242. mz_ulong total_in; // total number of bytes consumed so far
  243. unsigned char *next_out; // pointer to next byte to write
  244. unsigned int avail_out; // number of bytes that can be written to next_out
  245. mz_ulong total_out; // total number of bytes produced so far
  246. char *msg; // error msg (unused)
  247. struct mz_internal_state *state; // internal state, allocated by zalloc/zfree
  248. mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc)
  249. mz_free_func zfree; // optional heap free function (defaults to free)
  250. void *opaque; // heap alloc function user pointer
  251. int data_type; // data_type (unused)
  252. mz_ulong adler; // adler32 of the source or uncompressed data
  253. mz_ulong reserved; // not used
  254. } mz_stream;
  255. typedef mz_stream *mz_streamp;
  256. // Returns the version string of miniz.c.
  257. MINIZ_STATIC const char *mz_version(void);
  258. #ifndef MINIZ_NO_DEFLATE_APIS
  259. // mz_deflateInit() initializes a compressor with default options:
  260. // Parameters:
  261. // pStream must point to an initialized mz_stream struct.
  262. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION].
  263. // level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio.
  264. // (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.)
  265. // Return values:
  266. // MZ_OK on success.
  267. // MZ_STREAM_ERROR if the stream is bogus.
  268. // MZ_PARAM_ERROR if the input parameters are bogus.
  269. // MZ_MEM_ERROR on out of memory.
  270. MINIZ_STATIC int mz_deflateInit(mz_streamp pStream, int level);
  271. // mz_deflateInit2() is like mz_deflate(), except with more control:
  272. // Additional parameters:
  273. // method must be MZ_DEFLATED
  274. // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer)
  275. // mem_level must be between [1, 9] (it's checked but ignored by miniz.c)
  276. MINIZ_STATIC int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy);
  277. // Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2().
  278. MINIZ_STATIC int mz_deflateReset(mz_streamp pStream);
  279. // mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible.
  280. // Parameters:
  281. // pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members.
  282. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH.
  283. // Return values:
  284. // MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full).
  285. // MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore.
  286. // MZ_STREAM_ERROR if the stream is bogus.
  287. // MZ_PARAM_ERROR if one of the parameters is invalid.
  288. // MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.)
  289. MINIZ_STATIC int mz_deflate(mz_streamp pStream, int flush);
  290. // mz_deflateEnd() deinitializes a compressor:
  291. // Return values:
  292. // MZ_OK on success.
  293. // MZ_STREAM_ERROR if the stream is bogus.
  294. MINIZ_STATIC int mz_deflateEnd(mz_streamp pStream);
  295. // mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH.
  296. MINIZ_STATIC mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len);
  297. // Single-call compression functions mz_compress() and mz_compress2():
  298. // Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure.
  299. MINIZ_STATIC int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
  300. MINIZ_STATIC int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level);
  301. // mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress().
  302. MINIZ_STATIC mz_ulong mz_compressBound(mz_ulong source_len);
  303. #endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/
  304. #ifndef MINIZ_NO_INFLATE_APIS
  305. // Initializes a decompressor.
  306. MINIZ_STATIC int mz_inflateInit(mz_streamp pStream);
  307. // mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer:
  308. // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate).
  309. MINIZ_STATIC int mz_inflateInit2(mz_streamp pStream, int window_bits);
  310. // Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible.
  311. // Parameters:
  312. // pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members.
  313. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH.
  314. // On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster).
  315. // MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data.
  316. // Return values:
  317. // MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full.
  318. // MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified.
  319. // MZ_STREAM_ERROR if the stream is bogus.
  320. // MZ_DATA_ERROR if the deflate stream is invalid.
  321. // MZ_PARAM_ERROR if one of the parameters is invalid.
  322. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again
  323. // with more input data, or with more room in the output buffer (except when using single call decompression, described above).
  324. MINIZ_STATIC int mz_inflate(mz_streamp pStream, int flush);
  325. // Deinitializes a decompressor.
  326. MINIZ_STATIC int mz_inflateEnd(mz_streamp pStream);
  327. // Single-call decompression.
  328. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure.
  329. MINIZ_STATIC int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len);
  330. #endif /*#ifndef MINIZ_NO_INFLATE_APIS*/
  331. // Returns a string description of the specified error code, or NULL if the error code is invalid.
  332. MINIZ_STATIC const char *mz_error(int err);
  333. // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports.
  334. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project.
  335. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  336. typedef unsigned char Byte;
  337. typedef unsigned int uInt;
  338. typedef mz_ulong uLong;
  339. typedef Byte Bytef;
  340. typedef uInt uIntf;
  341. typedef char charf;
  342. typedef int intf;
  343. typedef void *voidpf;
  344. typedef uLong uLongf;
  345. typedef void *voidp;
  346. typedef void *const voidpc;
  347. #define Z_NULL 0
  348. #define Z_NO_FLUSH MZ_NO_FLUSH
  349. #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH
  350. #define Z_SYNC_FLUSH MZ_SYNC_FLUSH
  351. #define Z_FULL_FLUSH MZ_FULL_FLUSH
  352. #define Z_FINISH MZ_FINISH
  353. #define Z_BLOCK MZ_BLOCK
  354. #define Z_OK MZ_OK
  355. #define Z_STREAM_END MZ_STREAM_END
  356. #define Z_NEED_DICT MZ_NEED_DICT
  357. #define Z_ERRNO MZ_ERRNO
  358. #define Z_STREAM_ERROR MZ_STREAM_ERROR
  359. #define Z_DATA_ERROR MZ_DATA_ERROR
  360. #define Z_MEM_ERROR MZ_MEM_ERROR
  361. #define Z_BUF_ERROR MZ_BUF_ERROR
  362. #define Z_VERSION_ERROR MZ_VERSION_ERROR
  363. #define Z_PARAM_ERROR MZ_PARAM_ERROR
  364. #define Z_NO_COMPRESSION MZ_NO_COMPRESSION
  365. #define Z_BEST_SPEED MZ_BEST_SPEED
  366. #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION
  367. #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION
  368. #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY
  369. #define Z_FILTERED MZ_FILTERED
  370. #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY
  371. #define Z_RLE MZ_RLE
  372. #define Z_FIXED MZ_FIXED
  373. #define Z_DEFLATED MZ_DEFLATED
  374. #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS
  375. #define alloc_func mz_alloc_func
  376. #define free_func mz_free_func
  377. #define internal_state mz_internal_state
  378. #define z_stream mz_stream
  379. #ifndef MINIZ_NO_DEFLATE_APIS
  380. #define deflateInit mz_deflateInit
  381. #define deflateInit2 mz_deflateInit2
  382. #define deflateReset mz_deflateReset
  383. #define deflate mz_deflate
  384. #define deflateEnd mz_deflateEnd
  385. #define deflateBound mz_deflateBound
  386. #define compress mz_compress
  387. #define compress2 mz_compress2
  388. #define compressBound mz_compressBound
  389. #endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/
  390. #ifndef MINIZ_NO_INFLATE_APIS
  391. #define inflateInit mz_inflateInit
  392. #define inflateInit2 mz_inflateInit2
  393. #define inflate mz_inflate
  394. #define inflateEnd mz_inflateEnd
  395. #define uncompress mz_uncompress
  396. #endif /*#ifndef MINIZ_NO_INFLATE_APIS*/
  397. #define crc32 mz_crc32
  398. #define adler32 mz_adler32
  399. #define MAX_WBITS 15
  400. #define MAX_MEM_LEVEL 9
  401. #define zError mz_error
  402. #define ZLIB_VERSION MZ_VERSION
  403. #define ZLIB_VERNUM MZ_VERNUM
  404. #define ZLIB_VER_MAJOR MZ_VER_MAJOR
  405. #define ZLIB_VER_MINOR MZ_VER_MINOR
  406. #define ZLIB_VER_REVISION MZ_VER_REVISION
  407. #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION
  408. #define zlibVersion mz_version
  409. #define zlib_version mz_version()
  410. #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  411. #endif // MINIZ_NO_ZLIB_APIS
  412. // ------------------- Types and macros
  413. typedef unsigned char mz_uint8;
  414. typedef signed short mz_int16;
  415. typedef unsigned short mz_uint16;
  416. typedef unsigned int mz_uint32;
  417. typedef unsigned int mz_uint;
  418. typedef long long mz_int64;
  419. typedef unsigned long long mz_uint64;
  420. typedef int mz_bool;
  421. #define MZ_FALSE (0)
  422. #define MZ_TRUE (1)
  423. // An attempt to work around MSVC's spammy "warning C4127: conditional expression is constant" message.
  424. #ifdef _MSC_VER
  425. #define MZ_MACRO_END while (0, 0)
  426. #else
  427. #define MZ_MACRO_END while (0)
  428. #endif
  429. // ------------------- ZIP archive reading/writing
  430. #ifndef MINIZ_NO_ARCHIVE_APIS
  431. enum
  432. {
  433. MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024,
  434. MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260,
  435. MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256
  436. };
  437. typedef struct
  438. {
  439. mz_uint32 m_file_index;
  440. mz_uint32 m_central_dir_ofs;
  441. mz_uint16 m_version_made_by;
  442. mz_uint16 m_version_needed;
  443. mz_uint16 m_bit_flag;
  444. mz_uint16 m_method;
  445. #ifndef MINIZ_NO_TIME
  446. time_t m_time;
  447. #endif
  448. mz_uint32 m_crc32;
  449. mz_uint64 m_comp_size;
  450. mz_uint64 m_uncomp_size;
  451. mz_uint16 m_internal_attr;
  452. mz_uint32 m_external_attr;
  453. mz_uint64 m_local_header_ofs;
  454. mz_uint32 m_comment_size;
  455. char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE];
  456. char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE];
  457. } mz_zip_archive_file_stat;
  458. typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n);
  459. typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n);
  460. struct mz_zip_internal_state_tag;
  461. typedef struct mz_zip_internal_state_tag mz_zip_internal_state;
  462. typedef enum
  463. {
  464. MZ_ZIP_MODE_INVALID = 0,
  465. MZ_ZIP_MODE_READING = 1,
  466. MZ_ZIP_MODE_WRITING = 2,
  467. MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3
  468. } mz_zip_mode;
  469. typedef struct mz_zip_archive_tag
  470. {
  471. mz_uint64 m_archive_size;
  472. mz_uint64 m_central_directory_file_ofs;
  473. mz_uint m_total_files;
  474. mz_zip_mode m_zip_mode;
  475. mz_uint m_file_offset_alignment;
  476. mz_alloc_func m_pAlloc;
  477. mz_free_func m_pFree;
  478. mz_realloc_func m_pRealloc;
  479. void *m_pAlloc_opaque;
  480. mz_file_read_func m_pRead;
  481. mz_file_write_func m_pWrite;
  482. void *m_pIO_opaque;
  483. mz_zip_internal_state *m_pState;
  484. } mz_zip_archive;
  485. typedef enum
  486. {
  487. MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100,
  488. MZ_ZIP_FLAG_IGNORE_PATH = 0x0200,
  489. MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400,
  490. MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800
  491. } mz_zip_flags;
  492. // ZIP archive reading
  493. // Inits a ZIP archive reader.
  494. // These functions read and validate the archive's central directory.
  495. MINIZ_STATIC mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags);
  496. MINIZ_STATIC mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags);
  497. #ifndef MINIZ_NO_STDIO
  498. MINIZ_STATIC mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags);
  499. #endif
  500. // Returns the total number of files in the archive.
  501. MINIZ_STATIC mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip);
  502. // Returns detailed information about an archive file entry.
  503. MINIZ_STATIC mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat);
  504. // Determines if an archive file entry is a directory entry.
  505. MINIZ_STATIC mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index);
  506. MINIZ_STATIC mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index);
  507. // Retrieves the filename of an archive file entry.
  508. // Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename.
  509. MINIZ_STATIC mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size);
  510. // Attempts to locates a file in the archive's central directory.
  511. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH
  512. // Returns -1 if the file cannot be found.
  513. MINIZ_STATIC int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags);
  514. // Extracts a archive file to a memory buffer using no memory allocation.
  515. MINIZ_STATIC mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
  516. MINIZ_STATIC mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size);
  517. // Extracts a archive file to a memory buffer.
  518. MINIZ_STATIC mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags);
  519. MINIZ_STATIC mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags);
  520. // Extracts a archive file to a dynamically allocated heap buffer.
  521. MINIZ_STATIC void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags);
  522. MINIZ_STATIC void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags);
  523. // Extracts a archive file using a callback function to output the file's data.
  524. MINIZ_STATIC mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);
  525. MINIZ_STATIC mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags);
  526. #ifndef MINIZ_NO_STDIO
  527. // Extracts a archive file to a disk file and sets its last accessed and modified times.
  528. // This function only extracts files, not archive directory records.
  529. MINIZ_STATIC mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags);
  530. MINIZ_STATIC mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags);
  531. #endif
  532. // Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used.
  533. MINIZ_STATIC mz_bool mz_zip_reader_end(mz_zip_archive *pZip);
  534. // ZIP archive writing
  535. #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  536. // Inits a ZIP archive writer.
  537. MINIZ_STATIC mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size);
  538. MINIZ_STATIC mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size);
  539. #ifndef MINIZ_NO_STDIO
  540. MINIZ_STATIC mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning);
  541. #endif
  542. // Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive.
  543. // For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called.
  544. // For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it).
  545. // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL.
  546. // Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before
  547. // the archive is finalized the file's central directory will be hosed.
  548. MINIZ_STATIC mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename);
  549. // Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive.
  550. // To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer.
  551. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
  552. MINIZ_STATIC mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags);
  553. MINIZ_STATIC mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32);
  554. #ifndef MINIZ_NO_STDIO
  555. // Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive.
  556. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
  557. MINIZ_STATIC mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
  558. #endif
  559. // Adds a file to an archive by fully cloning the data from another archive.
  560. // This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields.
  561. MINIZ_STATIC mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index);
  562. // Finalizes the archive by writing the central directory records followed by the end of central directory record.
  563. // After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end().
  564. // An archive must be manually finalized by calling this function for it to be valid.
  565. MINIZ_STATIC mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip);
  566. MINIZ_STATIC mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize);
  567. // Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used.
  568. // Note for the archive to be valid, it must have been finalized before ending.
  569. MINIZ_STATIC mz_bool mz_zip_writer_end(mz_zip_archive *pZip);
  570. // Misc. high-level helper functions:
  571. // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive.
  572. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION.
  573. MINIZ_STATIC mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags);
  574. // Reads a single file from an archive into a heap block.
  575. // Returns NULL on failure.
  576. MINIZ_STATIC void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags);
  577. #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  578. #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
  579. // ------------------- Low-level Decompression API Definitions
  580. #ifndef MINIZ_NO_INFLATE_APIS
  581. // Decompression flags used by tinfl_decompress().
  582. // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream.
  583. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input.
  584. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB).
  585. // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes.
  586. enum
  587. {
  588. TINFL_FLAG_PARSE_ZLIB_HEADER = 1,
  589. TINFL_FLAG_HAS_MORE_INPUT = 2,
  590. TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4,
  591. TINFL_FLAG_COMPUTE_ADLER32 = 8
  592. };
  593. // High level decompression functions:
  594. // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc().
  595. // On entry:
  596. // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress.
  597. // On return:
  598. // Function returns a pointer to the decompressed data, or NULL on failure.
  599. // *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data.
  600. // The caller must call mz_free() on the returned block when it's no longer needed.
  601. MINIZ_STATIC void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
  602. // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory.
  603. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success.
  604. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1))
  605. MINIZ_STATIC size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
  606. // tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer.
  607. // Returns 1 on success or 0 on failure.
  608. typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
  609. MINIZ_STATIC int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
  610. struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor;
  611. // Max size of LZ dictionary.
  612. #define TINFL_LZ_DICT_SIZE 32768
  613. // Return status.
  614. typedef enum
  615. {
  616. TINFL_STATUS_BAD_PARAM = -3,
  617. TINFL_STATUS_ADLER32_MISMATCH = -2,
  618. TINFL_STATUS_FAILED = -1,
  619. TINFL_STATUS_DONE = 0,
  620. TINFL_STATUS_NEEDS_MORE_INPUT = 1,
  621. TINFL_STATUS_HAS_MORE_OUTPUT = 2
  622. } tinfl_status;
  623. // Initializes the decompressor to its initial state.
  624. #define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END
  625. #define tinfl_get_adler32(r) (r)->m_check_adler32
  626. // Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability.
  627. // This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output.
  628. MINIZ_STATIC tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags);
  629. // Internal/private bits follow.
  630. enum
  631. {
  632. TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19,
  633. TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS
  634. };
  635. typedef struct
  636. {
  637. mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0];
  638. mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2];
  639. } tinfl_huff_table;
  640. #if MINIZ_HAS_64BIT_REGISTERS
  641. #define TINFL_USE_64BIT_BITBUF 1
  642. #endif
  643. #if TINFL_USE_64BIT_BITBUF
  644. typedef mz_uint64 tinfl_bit_buf_t;
  645. #define TINFL_BITBUF_SIZE (64)
  646. #else
  647. typedef mz_uint32 tinfl_bit_buf_t;
  648. #define TINFL_BITBUF_SIZE (32)
  649. #endif
  650. struct tinfl_decompressor_tag
  651. {
  652. mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES];
  653. tinfl_bit_buf_t m_bit_buf;
  654. size_t m_dist_from_out_buf_start;
  655. tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES];
  656. mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137];
  657. };
  658. #endif /*#ifndef MINIZ_NO_INFLATE_APIS*/
  659. // ------------------- Low-level Compression API Definitions
  660. #ifndef MINIZ_NO_DEFLATE_APIS
  661. // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently).
  662. #define TDEFL_LESS_MEMORY 0
  663. // tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search):
  664. // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression).
  665. enum
  666. {
  667. TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF
  668. };
  669. // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data.
  670. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers).
  671. // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing.
  672. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory).
  673. // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1)
  674. // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled.
  675. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables.
  676. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks.
  677. // The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK).
  678. enum
  679. {
  680. TDEFL_WRITE_ZLIB_HEADER = 0x01000,
  681. TDEFL_COMPUTE_ADLER32 = 0x02000,
  682. TDEFL_GREEDY_PARSING_FLAG = 0x04000,
  683. TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000,
  684. TDEFL_RLE_MATCHES = 0x10000,
  685. TDEFL_FILTER_MATCHES = 0x20000,
  686. TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000,
  687. TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000
  688. };
  689. #ifndef MINIZ_SDL_NOUNUSED
  690. // High level compression functions:
  691. // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc().
  692. // On entry:
  693. // pSrc_buf, src_buf_len: Pointer and size of source block to compress.
  694. // flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression.
  695. // On return:
  696. // Function returns a pointer to the compressed data, or NULL on failure.
  697. // *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data.
  698. // The caller must free() the returned block when it's no longer needed.
  699. MINIZ_STATIC void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags);
  700. // tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory.
  701. // Returns 0 on failure.
  702. MINIZ_STATIC size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags);
  703. #endif /* MINIZ_SDL_NOUNUSED */
  704. // Compresses an image to a compressed PNG file in memory.
  705. // On entry:
  706. // pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4.
  707. // The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory.
  708. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL
  709. // If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps).
  710. // On return:
  711. // Function returns a pointer to the compressed data, or NULL on failure.
  712. // *pLen_out will be set to the size of the PNG image file.
  713. // The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed.
  714. MINIZ_STATIC void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, int bpl, size_t *pLen_out, mz_uint level, mz_bool flip, mz_uint8 *plte, int plte_size, mz_uint8 *trns, int trns_size);
  715. #ifndef MINIZ_SDL_NOUNUSED
  716. MINIZ_STATIC void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, int bpl, size_t *pLen_out);
  717. #endif
  718. // Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time.
  719. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser);
  720. #ifndef MINIZ_SDL_NOUNUSED
  721. // tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally.
  722. MINIZ_STATIC mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
  723. #endif
  724. //enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 };
  725. #define TDEFL_MAX_HUFF_TABLES 3
  726. #define TDEFL_MAX_HUFF_SYMBOLS_0 288
  727. #define TDEFL_MAX_HUFF_SYMBOLS_1 32
  728. #define TDEFL_MAX_HUFF_SYMBOLS_2 19
  729. #define TDEFL_LZ_DICT_SIZE 32768
  730. #define TDEFL_LZ_DICT_SIZE_MASK ( TDEFL_LZ_DICT_SIZE - 1 )
  731. #define TDEFL_MIN_MATCH_LEN 3
  732. #define TDEFL_MAX_MATCH_LEN 258
  733. // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes).
  734. #if TDEFL_LESS_MEMORY
  735. enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };
  736. #else
  737. enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS };
  738. #endif
  739. // The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions.
  740. typedef enum
  741. {
  742. TDEFL_STATUS_BAD_PARAM = -2,
  743. TDEFL_STATUS_PUT_BUF_FAILED = -1,
  744. TDEFL_STATUS_OKAY = 0,
  745. TDEFL_STATUS_DONE = 1,
  746. } tdefl_status;
  747. // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums
  748. typedef enum
  749. {
  750. TDEFL_NO_FLUSH = 0,
  751. TDEFL_SYNC_FLUSH = 2,
  752. TDEFL_FULL_FLUSH = 3,
  753. TDEFL_FINISH = 4
  754. } tdefl_flush;
  755. // tdefl's compression state structure.
  756. typedef struct
  757. {
  758. tdefl_put_buf_func_ptr m_pPut_buf_func;
  759. void *m_pPut_buf_user;
  760. mz_uint m_flags, m_max_probes[2];
  761. int m_greedy_parsing;
  762. mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size;
  763. mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end;
  764. mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer;
  765. mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish;
  766. tdefl_status m_prev_return_status;
  767. const void *m_pIn_buf;
  768. void *m_pOut_buf;
  769. size_t *m_pIn_buf_size, *m_pOut_buf_size;
  770. tdefl_flush m_flush;
  771. const mz_uint8 *m_pSrc;
  772. size_t m_src_buf_left, m_out_buf_ofs;
  773. mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1];
  774. mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  775. mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  776. mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS];
  777. mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE];
  778. mz_uint16 m_next[TDEFL_LZ_DICT_SIZE];
  779. mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE];
  780. mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE];
  781. } tdefl_compressor;
  782. // Initializes the compressor.
  783. // There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory.
  784. // pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression.
  785. // If pBut_buf_func is NULL the user should always call the tdefl_compress() API.
  786. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.)
  787. MINIZ_STATIC tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags);
  788. // Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible.
  789. MINIZ_STATIC tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush);
  790. // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr.
  791. // tdefl_compress_buffer() always consumes the entire input buffer.
  792. MINIZ_STATIC tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush);
  793. #ifndef MINIZ_SDL_NOUNUSED
  794. MINIZ_STATIC tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d);
  795. MINIZ_STATIC mz_uint32 tdefl_get_adler32(tdefl_compressor *d);
  796. #endif
  797. // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros.
  798. #ifndef MINIZ_NO_ZLIB_APIS
  799. // Create tdefl_compress() flags given zlib-style compression parameters.
  800. // level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files)
  801. // window_bits may be -15 (raw deflate) or 15 (zlib)
  802. // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED
  803. MINIZ_STATIC mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy);
  804. #endif // #ifndef MINIZ_NO_ZLIB_APIS
  805. #endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/
  806. #ifdef __cplusplus
  807. }
  808. #endif
  809. #endif // MINIZ_HEADER_INCLUDED
  810. // ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.)
  811. #ifndef MINIZ_HEADER_FILE_ONLY
  812. #ifdef _MSC_VER
  813. #pragma warning (push)
  814. #pragma warning (disable:4505) // unreferenced local function has been removed
  815. #endif
  816. typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1];
  817. typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1];
  818. typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1];
  819. /*#include <string.h>*/
  820. #ifndef MZ_ASSERT
  821. #include <assert.h>
  822. #define MZ_ASSERT(x) assert(x)
  823. #endif
  824. #ifdef MINIZ_NO_MALLOC
  825. #define MZ_MALLOC(x) NULL
  826. #define MZ_FREE(x) (void)x, ((void)0)
  827. #define MZ_REALLOC(p, x) NULL
  828. #elif defined(MINIZ_SDL_MALLOC)
  829. #define MZ_MALLOC(x) SDL_malloc(x)
  830. #define MZ_FREE(x) SDL_free(x)
  831. #define MZ_REALLOC(p, x) SDL_realloc(p, x)
  832. #else
  833. #define MZ_MALLOC(x) malloc(x)
  834. #define MZ_FREE(x) free(x)
  835. #define MZ_REALLOC(p, x) realloc(p, x)
  836. #endif
  837. #define MZ_MAX(a,b) (((a)>(b))?(a):(b))
  838. #define MZ_MIN(a,b) (((a)<(b))?(a):(b))
  839. #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj))
  840. #define MZ_CLEAR_ARR(obj) memset((obj), 0, sizeof(obj))
  841. #define MZ_CLEAR_PTR(obj) memset((obj), 0, sizeof(*obj))
  842. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  843. #define MZ_READ_LE16(p) *((const mz_uint16 *)(p))
  844. #define MZ_READ_LE32(p) *((const mz_uint32 *)(p))
  845. #else
  846. #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U))
  847. #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U))
  848. #endif
  849. #ifdef _MSC_VER
  850. #define MZ_FORCEINLINE __forceinline
  851. #elif defined(__GNUC__)
  852. #define MZ_FORCEINLINE inline __attribute__((__always_inline__))
  853. #else
  854. #define MZ_FORCEINLINE inline
  855. #endif
  856. #ifdef __cplusplus
  857. extern "C" {
  858. #endif
  859. // ------------------- zlib-style API's
  860. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len)
  861. {
  862. mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552;
  863. if (!ptr) return MZ_ADLER32_INIT;
  864. while (buf_len) {
  865. for (i = 0; i + 7 < block_len; i += 8, ptr += 8) {
  866. s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;
  867. s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;
  868. }
  869. for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;
  870. s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;
  871. }
  872. return (s2 << 16) + s1;
  873. }
  874. // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/
  875. mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len)
  876. {
  877. static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c,
  878. 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c };
  879. mz_uint32 crcu32 = (mz_uint32)crc;
  880. if (!ptr) return MZ_CRC32_INIT;
  881. crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; }
  882. return ~crcu32;
  883. }
  884. MINIZ_STATIC void mz_free(void *p)
  885. {
  886. MZ_FREE(p);
  887. }
  888. #ifndef MINIZ_NO_ZLIB_APIS
  889. static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); }
  890. static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); }
  891. static void *def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); }
  892. const char *mz_version(void)
  893. {
  894. return MZ_VERSION;
  895. }
  896. #ifndef MINIZ_NO_DEFLATE_APIS
  897. int mz_deflateInit(mz_streamp pStream, int level)
  898. {
  899. return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY);
  900. }
  901. int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy)
  902. {
  903. tdefl_compressor *pComp;
  904. mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy);
  905. if (!pStream) return MZ_STREAM_ERROR;
  906. if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR;
  907. pStream->data_type = 0;
  908. pStream->adler = MZ_ADLER32_INIT;
  909. pStream->msg = NULL;
  910. pStream->reserved = 0;
  911. pStream->total_in = 0;
  912. pStream->total_out = 0;
  913. if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
  914. if (!pStream->zfree) pStream->zfree = def_free_func;
  915. pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor));
  916. if (!pComp)
  917. return MZ_MEM_ERROR;
  918. pStream->state = (struct mz_internal_state *)pComp;
  919. if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY)
  920. {
  921. mz_deflateEnd(pStream);
  922. return MZ_PARAM_ERROR;
  923. }
  924. return MZ_OK;
  925. }
  926. int mz_deflateReset(mz_streamp pStream)
  927. {
  928. if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR;
  929. pStream->total_in = pStream->total_out = 0;
  930. tdefl_init((tdefl_compressor*)pStream->state, NULL, NULL, ((tdefl_compressor*)pStream->state)->m_flags);
  931. return MZ_OK;
  932. }
  933. int mz_deflate(mz_streamp pStream, int flush)
  934. {
  935. size_t in_bytes, out_bytes;
  936. mz_ulong orig_total_in, orig_total_out;
  937. int mz_status = MZ_OK;
  938. if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR;
  939. if (!pStream->avail_out) return MZ_BUF_ERROR;
  940. if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
  941. if (((tdefl_compressor*)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE)
  942. return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR;
  943. orig_total_in = pStream->total_in; orig_total_out = pStream->total_out;
  944. for ( ; ; )
  945. {
  946. tdefl_status defl_status;
  947. in_bytes = pStream->avail_in; out_bytes = pStream->avail_out;
  948. defl_status = tdefl_compress((tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush);
  949. pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes;
  950. pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor*)pStream->state);
  951. pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes;
  952. pStream->total_out += (mz_uint)out_bytes;
  953. if (defl_status < 0)
  954. {
  955. mz_status = MZ_STREAM_ERROR;
  956. break;
  957. }
  958. else if (defl_status == TDEFL_STATUS_DONE)
  959. {
  960. mz_status = MZ_STREAM_END;
  961. break;
  962. }
  963. else if (!pStream->avail_out)
  964. break;
  965. else if ((!pStream->avail_in) && (flush != MZ_FINISH))
  966. {
  967. if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out))
  968. break;
  969. return MZ_BUF_ERROR; // Can't make forward progress without some input.
  970. }
  971. }
  972. return mz_status;
  973. }
  974. int mz_deflateEnd(mz_streamp pStream)
  975. {
  976. if (!pStream) return MZ_STREAM_ERROR;
  977. if (pStream->state)
  978. {
  979. pStream->zfree(pStream->opaque, pStream->state);
  980. pStream->state = NULL;
  981. }
  982. return MZ_OK;
  983. }
  984. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len)
  985. {
  986. (void)pStream;
  987. // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.)
  988. return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5);
  989. }
  990. int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level)
  991. {
  992. int status;
  993. mz_stream stream;
  994. memset(&stream, 0, sizeof(stream));
  995. // In case mz_ulong is 64-bits (argh I hate longs).
  996. if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
  997. stream.next_in = pSource;
  998. stream.avail_in = (mz_uint32)source_len;
  999. stream.next_out = pDest;
  1000. stream.avail_out = (mz_uint32)*pDest_len;
  1001. status = mz_deflateInit(&stream, level);
  1002. if (status != MZ_OK) return status;
  1003. status = mz_deflate(&stream, MZ_FINISH);
  1004. if (status != MZ_STREAM_END)
  1005. {
  1006. mz_deflateEnd(&stream);
  1007. return (status == MZ_OK) ? MZ_BUF_ERROR : status;
  1008. }
  1009. *pDest_len = stream.total_out;
  1010. return mz_deflateEnd(&stream);
  1011. }
  1012. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)
  1013. {
  1014. return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION);
  1015. }
  1016. mz_ulong mz_compressBound(mz_ulong source_len)
  1017. {
  1018. return mz_deflateBound(NULL, source_len);
  1019. }
  1020. #endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/
  1021. #ifndef MINIZ_NO_INFLATE_APIS
  1022. typedef struct
  1023. {
  1024. tinfl_decompressor m_decomp;
  1025. mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits;
  1026. mz_uint8 m_dict[TINFL_LZ_DICT_SIZE];
  1027. tinfl_status m_last_status;
  1028. } inflate_state;
  1029. int mz_inflateInit2(mz_streamp pStream, int window_bits)
  1030. {
  1031. inflate_state *pDecomp;
  1032. if (!pStream) return MZ_STREAM_ERROR;
  1033. if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR;
  1034. pStream->data_type = 0;
  1035. pStream->adler = 0;
  1036. pStream->msg = NULL;
  1037. pStream->total_in = 0;
  1038. pStream->total_out = 0;
  1039. pStream->reserved = 0;
  1040. if (!pStream->zalloc) pStream->zalloc = def_alloc_func;
  1041. if (!pStream->zfree) pStream->zfree = def_free_func;
  1042. pDecomp = (inflate_state*)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state));
  1043. if (!pDecomp) return MZ_MEM_ERROR;
  1044. pStream->state = (struct mz_internal_state *)pDecomp;
  1045. tinfl_init(&pDecomp->m_decomp);
  1046. pDecomp->m_dict_ofs = 0;
  1047. pDecomp->m_dict_avail = 0;
  1048. pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT;
  1049. pDecomp->m_first_call = 1;
  1050. pDecomp->m_has_flushed = 0;
  1051. pDecomp->m_window_bits = window_bits;
  1052. return MZ_OK;
  1053. }
  1054. int mz_inflateInit(mz_streamp pStream)
  1055. {
  1056. return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS);
  1057. }
  1058. int mz_inflate(mz_streamp pStream, int flush)
  1059. {
  1060. inflate_state* pState;
  1061. mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32;
  1062. size_t in_bytes, out_bytes, orig_avail_in;
  1063. tinfl_status status;
  1064. if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR;
  1065. if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH;
  1066. if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR;
  1067. pState = (inflate_state*)pStream->state;
  1068. if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER;
  1069. orig_avail_in = pStream->avail_in;
  1070. first_call = pState->m_first_call; pState->m_first_call = 0;
  1071. if (pState->m_last_status < 0) return MZ_DATA_ERROR;
  1072. if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR;
  1073. pState->m_has_flushed |= (flush == MZ_FINISH);
  1074. if ((flush == MZ_FINISH) && (first_call))
  1075. {
  1076. // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file.
  1077. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF;
  1078. in_bytes = pStream->avail_in; out_bytes = pStream->avail_out;
  1079. status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags);
  1080. pState->m_last_status = status;
  1081. pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes;
  1082. pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  1083. pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes;
  1084. if (status < 0)
  1085. return MZ_DATA_ERROR;
  1086. else if (status != TINFL_STATUS_DONE)
  1087. {
  1088. pState->m_last_status = TINFL_STATUS_FAILED;
  1089. return MZ_BUF_ERROR;
  1090. }
  1091. return MZ_STREAM_END;
  1092. }
  1093. // flush != MZ_FINISH then we must assume there's more input.
  1094. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT;
  1095. if (pState->m_dict_avail)
  1096. {
  1097. n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  1098. memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  1099. pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n;
  1100. pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  1101. return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK;
  1102. }
  1103. for ( ; ; )
  1104. {
  1105. in_bytes = pStream->avail_in;
  1106. out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs;
  1107. status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags);
  1108. pState->m_last_status = status;
  1109. pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes;
  1110. pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp);
  1111. pState->m_dict_avail = (mz_uint)out_bytes;
  1112. n = MZ_MIN(pState->m_dict_avail, pStream->avail_out);
  1113. memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n);
  1114. pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n;
  1115. pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1);
  1116. if (status < 0)
  1117. return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well).
  1118. else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in))
  1119. return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH.
  1120. else if (flush == MZ_FINISH)
  1121. {
  1122. // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH.
  1123. if (status == TINFL_STATUS_DONE)
  1124. return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END;
  1125. // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong.
  1126. else if (!pStream->avail_out)
  1127. return MZ_BUF_ERROR;
  1128. }
  1129. else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail))
  1130. break;
  1131. }
  1132. return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK;
  1133. }
  1134. int mz_inflateEnd(mz_streamp pStream)
  1135. {
  1136. if (!pStream)
  1137. return MZ_STREAM_ERROR;
  1138. if (pStream->state)
  1139. {
  1140. pStream->zfree(pStream->opaque, pStream->state);
  1141. pStream->state = NULL;
  1142. }
  1143. return MZ_OK;
  1144. }
  1145. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len)
  1146. {
  1147. mz_stream stream;
  1148. int status;
  1149. memset(&stream, 0, sizeof(stream));
  1150. // In case mz_ulong is 64-bits (argh I hate longs).
  1151. if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR;
  1152. stream.next_in = pSource;
  1153. stream.avail_in = (mz_uint32)source_len;
  1154. stream.next_out = pDest;
  1155. stream.avail_out = (mz_uint32)*pDest_len;
  1156. status = mz_inflateInit(&stream);
  1157. if (status != MZ_OK)
  1158. return status;
  1159. status = mz_inflate(&stream, MZ_FINISH);
  1160. if (status != MZ_STREAM_END)
  1161. {
  1162. mz_inflateEnd(&stream);
  1163. return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status;
  1164. }
  1165. *pDest_len = stream.total_out;
  1166. return mz_inflateEnd(&stream);
  1167. }
  1168. #endif /*#ifndef MINIZ_NO_INFLATE_APIS*/
  1169. const char *mz_error(int err)
  1170. {
  1171. static struct { int m_err; const char *m_pDesc; } s_error_descs[] =
  1172. {
  1173. { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" },
  1174. { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" }
  1175. };
  1176. mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc;
  1177. return NULL;
  1178. }
  1179. #endif //MINIZ_NO_ZLIB_APIS
  1180. // ------------------- Low-level Decompression (completely independent from all compression API's)
  1181. #ifndef MINIZ_NO_INFLATE_APIS
  1182. #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l)
  1183. #define TINFL_MEMSET(p, c, l) memset(p, c, l)
  1184. #define TINFL_CR_BEGIN switch(r->m_state) { case 0:
  1185. #define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END
  1186. #define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END
  1187. #define TINFL_CR_FINISH }
  1188. // TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never
  1189. // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario.
  1190. #define TINFL_GET_BYTE(state_index, c) do { \
  1191. if (pIn_buf_cur >= pIn_buf_end) { \
  1192. for ( ; ; ) { \
  1193. if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \
  1194. TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \
  1195. if (pIn_buf_cur < pIn_buf_end) { \
  1196. c = *pIn_buf_cur++; \
  1197. break; \
  1198. } \
  1199. } else { \
  1200. c = 0; \
  1201. break; \
  1202. } \
  1203. } \
  1204. } else c = *pIn_buf_cur++; } MZ_MACRO_END
  1205. #define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n))
  1206. #define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
  1207. #define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END
  1208. // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2.
  1209. // It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a
  1210. // Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the
  1211. // bit buffer contains >=15 bits (deflate's max. Huffman code size).
  1212. #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \
  1213. do { \
  1214. temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \
  1215. if (temp >= 0) { \
  1216. code_len = temp >> 9; \
  1217. if ((code_len) && (num_bits >= code_len)) \
  1218. break; \
  1219. } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \
  1220. code_len = TINFL_FAST_LOOKUP_BITS; \
  1221. do { \
  1222. temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \
  1223. } while ((temp < 0) && (num_bits >= (code_len + 1))); \
  1224. if (temp >= 0) break; \
  1225. } \
  1226. TINFL_GET_BYTE(state_index, c); \
  1227. bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \
  1228. num_bits += 8; \
  1229. } while (num_bits < 15);
  1230. // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read
  1231. // beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully
  1232. // decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32.
  1233. // The slow path is only executed at the very end of the input buffer.
  1234. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \
  1235. int temp; mz_uint code_len, c; \
  1236. if (num_bits < 15) { \
  1237. if ((pIn_buf_end - pIn_buf_cur) < 2) { \
  1238. TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \
  1239. } else { \
  1240. bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \
  1241. } \
  1242. } \
  1243. if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \
  1244. code_len = temp >> 9, temp &= 511; \
  1245. else { \
  1246. code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \
  1247. } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END
  1248. tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags)
  1249. {
  1250. static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 };
  1251. static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };
  1252. static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
  1253. static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
  1254. static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
  1255. static const int s_min_table_sizes[3] = { 257, 1, 4 };
  1256. tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf;
  1257. const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size;
  1258. mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size;
  1259. size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start;
  1260. // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter).
  1261. if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; }
  1262. num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start;
  1263. TINFL_CR_BEGIN
  1264. bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1;
  1265. if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
  1266. {
  1267. TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1);
  1268. counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8));
  1269. if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4)))));
  1270. if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); }
  1271. }
  1272. do
  1273. {
  1274. TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1;
  1275. if (r->m_type == 0)
  1276. {
  1277. TINFL_SKIP_BITS(5, num_bits & 7);
  1278. for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); }
  1279. if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); }
  1280. while ((counter) && (num_bits))
  1281. {
  1282. TINFL_GET_BITS(51, dist, 8);
  1283. while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); }
  1284. *pOut_buf_cur++ = (mz_uint8)dist;
  1285. counter--;
  1286. }
  1287. while (counter)
  1288. {
  1289. size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); }
  1290. while (pIn_buf_cur >= pIn_buf_end)
  1291. {
  1292. if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT)
  1293. {
  1294. TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT);
  1295. }
  1296. else
  1297. {
  1298. TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED);
  1299. }
  1300. }
  1301. n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter);
  1302. TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n;
  1303. }
  1304. }
  1305. else if (r->m_type == 3)
  1306. {
  1307. TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED);
  1308. }
  1309. else
  1310. {
  1311. if (r->m_type == 1)
  1312. {
  1313. mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i;
  1314. r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32);
  1315. for ( i = 0; i <= 143; ++i) *p++ = 8;
  1316. for ( ; i <= 255; ++i) *p++ = 9;
  1317. for ( ; i <= 279; ++i) *p++ = 7;
  1318. for ( ; i <= 287; ++i) *p++ = 8;
  1319. }
  1320. else
  1321. {
  1322. for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; }
  1323. MZ_CLEAR_ARR(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; }
  1324. r->m_table_sizes[2] = 19;
  1325. }
  1326. for ( ; (int)r->m_type >= 0; r->m_type--)
  1327. {
  1328. int tree_next, tree_cur; tinfl_huff_table *pTable;
  1329. mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_ARR(total_syms); MZ_CLEAR_ARR(pTable->m_look_up); MZ_CLEAR_ARR(pTable->m_tree);
  1330. for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++;
  1331. used_syms = 0, total = 0; next_code[0] = next_code[1] = 0;
  1332. for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); }
  1333. if ((65536 != total) && (used_syms > 1))
  1334. {
  1335. TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED);
  1336. }
  1337. for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index)
  1338. {
  1339. mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue;
  1340. cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1);
  1341. if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; }
  1342. if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; }
  1343. rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1);
  1344. for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--)
  1345. {
  1346. tree_cur -= ((rev_code >>= 1) & 1);
  1347. if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1];
  1348. }
  1349. tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index;
  1350. }
  1351. if (r->m_type == 2)
  1352. {
  1353. for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); )
  1354. {
  1355. mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; }
  1356. if ((dist == 16) && (!counter))
  1357. {
  1358. TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED);
  1359. }
  1360. num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16];
  1361. TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s;
  1362. }
  1363. if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter)
  1364. {
  1365. TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED);
  1366. }
  1367. TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]);
  1368. }
  1369. }
  1370. for ( ; ; )
  1371. {
  1372. mz_uint8 *pSrc;
  1373. for ( ; ; )
  1374. {
  1375. if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2))
  1376. {
  1377. TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]);
  1378. if (counter >= 256)
  1379. break;
  1380. while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); }
  1381. *pOut_buf_cur++ = (mz_uint8)counter;
  1382. }
  1383. else
  1384. {
  1385. int sym2; mz_uint code_len;
  1386. #if TINFL_USE_64BIT_BITBUF
  1387. if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; }
  1388. #else
  1389. if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; }
  1390. #endif
  1391. if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
  1392. code_len = sym2 >> 9;
  1393. else
  1394. {
  1395. code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0);
  1396. }
  1397. counter = sym2; bit_buf >>= code_len; num_bits -= code_len;
  1398. if (counter & 256)
  1399. break;
  1400. #if !TINFL_USE_64BIT_BITBUF
  1401. if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; }
  1402. #endif
  1403. if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0)
  1404. code_len = sym2 >> 9;
  1405. else
  1406. {
  1407. code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0);
  1408. }
  1409. bit_buf >>= code_len; num_bits -= code_len;
  1410. pOut_buf_cur[0] = (mz_uint8)counter;
  1411. if (sym2 & 256)
  1412. {
  1413. pOut_buf_cur++;
  1414. counter = sym2;
  1415. break;
  1416. }
  1417. pOut_buf_cur[1] = (mz_uint8)sym2;
  1418. pOut_buf_cur += 2;
  1419. }
  1420. }
  1421. if ((counter &= 511) == 256) break;
  1422. num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257];
  1423. if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; }
  1424. TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]);
  1425. num_extra = s_dist_extra[dist]; dist = s_dist_base[dist];
  1426. if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; }
  1427. dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start;
  1428. if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))
  1429. {
  1430. TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED);
  1431. }
  1432. pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask);
  1433. if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end)
  1434. {
  1435. while (counter--)
  1436. {
  1437. while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); }
  1438. *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask];
  1439. }
  1440. continue;
  1441. }
  1442. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  1443. else if ((counter >= 9) && (counter <= dist))
  1444. {
  1445. const mz_uint8 *pSrc_end = pSrc + (counter & ~7);
  1446. do
  1447. {
  1448. ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0];
  1449. ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1];
  1450. pOut_buf_cur += 8;
  1451. } while ((pSrc += 8) < pSrc_end);
  1452. if ((counter &= 7) < 3)
  1453. {
  1454. if (counter)
  1455. {
  1456. pOut_buf_cur[0] = pSrc[0];
  1457. if (counter > 1)
  1458. pOut_buf_cur[1] = pSrc[1];
  1459. pOut_buf_cur += counter;
  1460. }
  1461. continue;
  1462. }
  1463. }
  1464. #endif
  1465. do
  1466. {
  1467. pOut_buf_cur[0] = pSrc[0];
  1468. pOut_buf_cur[1] = pSrc[1];
  1469. pOut_buf_cur[2] = pSrc[2];
  1470. pOut_buf_cur += 3; pSrc += 3;
  1471. } while ((int)(counter -= 3) > 2);
  1472. if ((int)counter > 0)
  1473. {
  1474. pOut_buf_cur[0] = pSrc[0];
  1475. if ((int)counter > 1)
  1476. pOut_buf_cur[1] = pSrc[1];
  1477. pOut_buf_cur += counter;
  1478. }
  1479. }
  1480. }
  1481. } while (!(r->m_final & 1));
  1482. if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER)
  1483. {
  1484. TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; }
  1485. }
  1486. TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE);
  1487. TINFL_CR_FINISH
  1488. common_exit:
  1489. r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start;
  1490. *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next;
  1491. if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0))
  1492. {
  1493. const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size;
  1494. mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552;
  1495. while (buf_len)
  1496. {
  1497. for (i = 0; i + 7 < block_len; i += 8, ptr += 8)
  1498. {
  1499. s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1;
  1500. s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1;
  1501. }
  1502. for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1;
  1503. s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552;
  1504. }
  1505. r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH;
  1506. }
  1507. return status;
  1508. }
  1509. // Higher level helper functions.
  1510. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)
  1511. {
  1512. tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0;
  1513. *pOut_len = 0;
  1514. tinfl_init(&decomp);
  1515. for ( ; ; )
  1516. {
  1517. size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity;
  1518. tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size,
  1519. (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  1520. if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT))
  1521. {
  1522. MZ_FREE(pBuf); *pOut_len = 0; return NULL;
  1523. }
  1524. src_buf_ofs += src_buf_size;
  1525. *pOut_len += dst_buf_size;
  1526. if (status == TINFL_STATUS_DONE) break;
  1527. new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128;
  1528. pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity);
  1529. if (!pNew_buf)
  1530. {
  1531. MZ_FREE(pBuf); *pOut_len = 0; return NULL;
  1532. }
  1533. pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity;
  1534. }
  1535. return pBuf;
  1536. }
  1537. size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)
  1538. {
  1539. tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp);
  1540. status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF);
  1541. return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len;
  1542. }
  1543. int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
  1544. {
  1545. int result = 0;
  1546. tinfl_decompressor decomp;
  1547. mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0;
  1548. if (!pDict)
  1549. return TINFL_STATUS_FAILED;
  1550. memset(pDict,0,TINFL_LZ_DICT_SIZE);
  1551. tinfl_init(&decomp);
  1552. for ( ; ; )
  1553. {
  1554. size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs;
  1555. tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size,
  1556. (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)));
  1557. in_buf_ofs += in_buf_size;
  1558. if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user)))
  1559. break;
  1560. if (status != TINFL_STATUS_HAS_MORE_OUTPUT)
  1561. {
  1562. result = (status == TINFL_STATUS_DONE);
  1563. break;
  1564. }
  1565. dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1);
  1566. }
  1567. MZ_FREE(pDict);
  1568. *pIn_buf_size = in_buf_ofs;
  1569. return result;
  1570. }
  1571. #endif /*#ifndef MINIZ_NO_INFLATE_APIS*/
  1572. // ------------------- Low-level Compression (independent from all decompression API's)
  1573. #ifndef MINIZ_NO_DEFLATE_APIS
  1574. // Purposely making these tables static for faster init and thread safety.
  1575. static const mz_uint16 s_tdefl_len_sym[256] = {
  1576. 257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272,
  1577. 273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276,
  1578. 277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,
  1579. 279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,
  1580. 281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,
  1581. 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,
  1582. 283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,
  1583. 284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 };
  1584. static const mz_uint8 s_tdefl_len_extra[256] = {
  1585. 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
  1586. 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
  1587. 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
  1588. 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 };
  1589. static const mz_uint8 s_tdefl_small_dist_sym[512] = {
  1590. 0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  1591. 11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,
  1592. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,
  1593. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  1594. 14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  1595. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16,
  1596. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  1597. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  1598. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  1599. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  1600. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  1601. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 };
  1602. static const mz_uint8 s_tdefl_small_dist_extra[512] = {
  1603. 0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,
  1604. 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
  1605. 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
  1606. 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  1607. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  1608. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  1609. 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
  1610. 7,7,7,7,7,7,7,7 };
  1611. static const mz_uint8 s_tdefl_large_dist_sym[128] = {
  1612. 0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,
  1613. 26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,
  1614. 28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 };
  1615. static const mz_uint8 s_tdefl_large_dist_extra[128] = {
  1616. 0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  1617. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  1618. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 };
  1619. // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values.
  1620. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq;
  1621. static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1)
  1622. {
  1623. mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_ARR(hist);
  1624. for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; }
  1625. while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--;
  1626. for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8)
  1627. {
  1628. const mz_uint32* pHist = &hist[pass << 8];
  1629. mz_uint offsets[256], cur_ofs = 0;
  1630. for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; }
  1631. for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i];
  1632. { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; }
  1633. }
  1634. return pCur_syms;
  1635. }
  1636. // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.
  1637. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n)
  1638. {
  1639. int root, leaf, next, avbl, used, dpth;
  1640. if (n==0) return; else if (n==1) { A[0].m_key = 1; return; }
  1641. A[0].m_key += A[1].m_key; root = 0; leaf = 2;
  1642. for (next=1; next < n-1; next++)
  1643. {
  1644. if (leaf>=n || A[root].m_key<A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key;
  1645. if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
  1646. }
  1647. A[n-2].m_key = 0; for (next=n-3; next>=0; next--) A[next].m_key = A[A[next].m_key].m_key+1;
  1648. avbl = 1; used = dpth = 0; root = n-2; next = n-1;
  1649. while (avbl>0)
  1650. {
  1651. while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; }
  1652. while (avbl>used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; }
  1653. avbl = 2*used; dpth++; used = 0;
  1654. }
  1655. }
  1656. // Limits canonical Huffman code table's max code size.
  1657. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 };
  1658. static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size)
  1659. {
  1660. int i; mz_uint32 total = 0; if (code_list_len <= 1) return;
  1661. for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i];
  1662. for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i));
  1663. while (total != (1UL << max_code_size))
  1664. {
  1665. pNum_codes[max_code_size]--;
  1666. for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; }
  1667. total--;
  1668. }
  1669. }
  1670. static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table)
  1671. {
  1672. int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_ARR(num_codes);
  1673. if (static_table)
  1674. {
  1675. for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++;
  1676. }
  1677. else
  1678. {
  1679. tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms;
  1680. int num_used_syms = 0;
  1681. const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0];
  1682. for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; }
  1683. pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms);
  1684. for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++;
  1685. tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit);
  1686. MZ_CLEAR_ARR(d->m_huff_code_sizes[table_num]); MZ_CLEAR_ARR(d->m_huff_codes[table_num]);
  1687. for (i = 1, j = num_used_syms; i <= code_size_limit; i++)
  1688. for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i);
  1689. }
  1690. next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1);
  1691. for (i = 0; i < table_len; i++)
  1692. {
  1693. mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue;
  1694. code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1);
  1695. d->m_huff_codes[table_num][i] = (mz_uint16)rev_code;
  1696. }
  1697. }
  1698. #define TDEFL_PUT_BITS(b, l) do { \
  1699. mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \
  1700. d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \
  1701. while (d->m_bits_in >= 8) { \
  1702. if (d->m_pOutput_buf < d->m_pOutput_buf_end) \
  1703. *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \
  1704. d->m_bit_buffer >>= 8; \
  1705. d->m_bits_in -= 8; \
  1706. } \
  1707. } MZ_MACRO_END
  1708. #define TDEFL_RLE_PREV_CODE_SIZE() do { \
  1709. if (rle_repeat_count) { \
  1710. if (rle_repeat_count < 3) { \
  1711. d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \
  1712. while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \
  1713. } else { \
  1714. d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \
  1715. } rle_repeat_count = 0; } \
  1716. } MZ_MACRO_END
  1717. #define TDEFL_RLE_ZERO_CODE_SIZE() do { \
  1718. if (rle_z_count) { \
  1719. if (rle_z_count < 3) { \
  1720. d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \
  1721. } else if (rle_z_count <= 10) { \
  1722. d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \
  1723. } else { \
  1724. d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \
  1725. } rle_z_count = 0; } \
  1726. } MZ_MACRO_END
  1727. static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
  1728. static void tdefl_start_dynamic_block(tdefl_compressor *d)
  1729. {
  1730. int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index;
  1731. mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF;
  1732. d->m_huff_count[0][256] = 1;
  1733. tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE);
  1734. tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE);
  1735. for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break;
  1736. for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break;
  1737. memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes);
  1738. memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes);
  1739. total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0;
  1740. memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2);
  1741. for (i = 0; i < total_code_sizes_to_pack; i++)
  1742. {
  1743. mz_uint8 code_size = code_sizes_to_pack[i];
  1744. if (!code_size)
  1745. {
  1746. TDEFL_RLE_PREV_CODE_SIZE();
  1747. if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); }
  1748. }
  1749. else
  1750. {
  1751. TDEFL_RLE_ZERO_CODE_SIZE();
  1752. if (code_size != prev_code_size)
  1753. {
  1754. TDEFL_RLE_PREV_CODE_SIZE();
  1755. d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size;
  1756. }
  1757. else if (++rle_repeat_count == 6)
  1758. {
  1759. TDEFL_RLE_PREV_CODE_SIZE();
  1760. }
  1761. }
  1762. prev_code_size = code_size;
  1763. }
  1764. if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); }
  1765. tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE);
  1766. TDEFL_PUT_BITS(2, 2);
  1767. TDEFL_PUT_BITS(num_lit_codes - 257, 5);
  1768. TDEFL_PUT_BITS(num_dist_codes - 1, 5);
  1769. for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break;
  1770. num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4);
  1771. for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3);
  1772. for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; )
  1773. {
  1774. mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2);
  1775. TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]);
  1776. if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]);
  1777. }
  1778. }
  1779. static void tdefl_start_static_block(tdefl_compressor *d)
  1780. {
  1781. mz_uint i;
  1782. mz_uint8 *p = &d->m_huff_code_sizes[0][0];
  1783. for (i = 0; i <= 143; ++i) *p++ = 8;
  1784. for ( ; i <= 255; ++i) *p++ = 9;
  1785. for ( ; i <= 279; ++i) *p++ = 7;
  1786. for ( ; i <= 287; ++i) *p++ = 8;
  1787. memset(d->m_huff_code_sizes[1], 5, 32);
  1788. tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE);
  1789. tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE);
  1790. TDEFL_PUT_BITS(1, 2);
  1791. }
  1792. static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF };
  1793. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS
  1794. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d)
  1795. {
  1796. mz_uint flags;
  1797. mz_uint8 *pLZ_codes;
  1798. mz_uint8 *pOutput_buf = d->m_pOutput_buf;
  1799. mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf;
  1800. mz_uint64 bit_buffer = d->m_bit_buffer;
  1801. mz_uint bits_in = d->m_bits_in;
  1802. #define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); }
  1803. flags = 1;
  1804. for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1)
  1805. {
  1806. if (flags == 1)
  1807. flags = *pLZ_codes++ | 0x100;
  1808. if (flags & 1)
  1809. {
  1810. mz_uint s0, s1, n0, n1, sym, num_extra_bits;
  1811. mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3;
  1812. MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  1813. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  1814. TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]);
  1815. // This sequence coaxes MSVC into using cmov's vs. jmp's.
  1816. s0 = s_tdefl_small_dist_sym[match_dist & 511];
  1817. n0 = s_tdefl_small_dist_extra[match_dist & 511];
  1818. s1 = s_tdefl_large_dist_sym[match_dist >> 8];
  1819. n1 = s_tdefl_large_dist_extra[match_dist >> 8];
  1820. sym = (match_dist < 512) ? s0 : s1;
  1821. num_extra_bits = (match_dist < 512) ? n0 : n1;
  1822. MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  1823. TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
  1824. TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
  1825. }
  1826. else
  1827. {
  1828. mz_uint lit = *pLZ_codes++;
  1829. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  1830. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  1831. if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end))
  1832. {
  1833. flags >>= 1;
  1834. lit = *pLZ_codes++;
  1835. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  1836. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  1837. if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end))
  1838. {
  1839. flags >>= 1;
  1840. lit = *pLZ_codes++;
  1841. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  1842. TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  1843. }
  1844. }
  1845. }
  1846. if (pOutput_buf >= d->m_pOutput_buf_end)
  1847. return MZ_FALSE;
  1848. *(mz_uint64*)pOutput_buf = bit_buffer;
  1849. pOutput_buf += (bits_in >> 3);
  1850. bit_buffer >>= (bits_in & ~7);
  1851. bits_in &= 7;
  1852. }
  1853. #undef TDEFL_PUT_BITS_FAST
  1854. d->m_pOutput_buf = pOutput_buf;
  1855. d->m_bits_in = 0;
  1856. d->m_bit_buffer = 0;
  1857. while (bits_in)
  1858. {
  1859. mz_uint32 n = MZ_MIN(bits_in, 16);
  1860. TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n);
  1861. bit_buffer >>= n;
  1862. bits_in -= n;
  1863. }
  1864. TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  1865. return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  1866. }
  1867. #else
  1868. static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d)
  1869. {
  1870. mz_uint flags;
  1871. mz_uint8 *pLZ_codes;
  1872. flags = 1;
  1873. for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1)
  1874. {
  1875. if (flags == 1)
  1876. flags = *pLZ_codes++ | 0x100;
  1877. if (flags & 1)
  1878. {
  1879. mz_uint sym, num_extra_bits;
  1880. mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3;
  1881. MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  1882. TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]);
  1883. TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]);
  1884. if (match_dist < 512)
  1885. {
  1886. sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist];
  1887. }
  1888. else
  1889. {
  1890. sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8];
  1891. }
  1892. MZ_ASSERT(d->m_huff_code_sizes[1][sym]);
  1893. TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]);
  1894. TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits);
  1895. }
  1896. else
  1897. {
  1898. mz_uint lit = *pLZ_codes++;
  1899. MZ_ASSERT(d->m_huff_code_sizes[0][lit]);
  1900. TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]);
  1901. }
  1902. }
  1903. TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]);
  1904. return (d->m_pOutput_buf < d->m_pOutput_buf_end);
  1905. }
  1906. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS
  1907. static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block)
  1908. {
  1909. if (static_block)
  1910. tdefl_start_static_block(d);
  1911. else
  1912. tdefl_start_dynamic_block(d);
  1913. return tdefl_compress_lz_codes(d);
  1914. }
  1915. static int tdefl_flush_block(tdefl_compressor *d, int flush)
  1916. {
  1917. mz_uint saved_bit_buf, saved_bits_in;
  1918. mz_uint8 *pSaved_output_buf;
  1919. mz_bool comp_block_succeeded = MZ_FALSE;
  1920. int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size;
  1921. mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf;
  1922. d->m_pOutput_buf = pOutput_buf_start;
  1923. d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16;
  1924. MZ_ASSERT(!d->m_output_flush_remaining);
  1925. d->m_output_flush_ofs = 0;
  1926. d->m_output_flush_remaining = 0;
  1927. *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left);
  1928. d->m_pLZ_code_buf -= (d->m_num_flags_left == 8);
  1929. if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index))
  1930. {
  1931. TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8);
  1932. }
  1933. TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1);
  1934. pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in;
  1935. if (!use_raw_block)
  1936. comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48));
  1937. // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead.
  1938. if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) &&
  1939. ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) )
  1940. {
  1941. mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  1942. TDEFL_PUT_BITS(0, 2);
  1943. if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); }
  1944. for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF)
  1945. {
  1946. TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16);
  1947. }
  1948. for (i = 0; i < d->m_total_lz_bytes; ++i)
  1949. {
  1950. TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8);
  1951. }
  1952. }
  1953. // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes.
  1954. else if (!comp_block_succeeded)
  1955. {
  1956. d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in;
  1957. tdefl_compress_block(d, MZ_TRUE);
  1958. }
  1959. if (flush)
  1960. {
  1961. if (flush == TDEFL_FINISH)
  1962. {
  1963. if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); }
  1964. if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } }
  1965. }
  1966. else
  1967. {
  1968. mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); }
  1969. }
  1970. }
  1971. MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end);
  1972. memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  1973. memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  1974. d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++;
  1975. if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0)
  1976. {
  1977. if (d->m_pPut_buf_func)
  1978. {
  1979. *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  1980. if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user))
  1981. return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED);
  1982. }
  1983. else if (pOutput_buf_start == d->m_output_buf)
  1984. {
  1985. int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs));
  1986. memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy);
  1987. d->m_out_buf_ofs += bytes_to_copy;
  1988. if ((n -= bytes_to_copy) != 0)
  1989. {
  1990. d->m_output_flush_ofs = bytes_to_copy;
  1991. d->m_output_flush_remaining = n;
  1992. }
  1993. }
  1994. else
  1995. {
  1996. d->m_out_buf_ofs += n;
  1997. }
  1998. }
  1999. return d->m_output_flush_remaining;
  2000. }
  2001. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  2002. #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p)
  2003. static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len)
  2004. {
  2005. mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;
  2006. mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  2007. const mz_uint16 *s = (const mz_uint16*)(d->m_dict + pos), *p, *q;
  2008. mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s);
  2009. MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return;
  2010. for ( ; ; )
  2011. {
  2012. for ( ; ; )
  2013. {
  2014. if (--num_probes_left == 0) return;
  2015. #define TDEFL_PROBE \
  2016. next_probe_pos = d->m_next[probe_pos]; \
  2017. if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \
  2018. probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  2019. if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break;
  2020. TDEFL_PROBE
  2021. TDEFL_PROBE
  2022. TDEFL_PROBE
  2023. }
  2024. if (!dist) break;
  2025. q = (const mz_uint16*)(d->m_dict + probe_pos);
  2026. if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue;
  2027. p = s; probe_len = 32;
  2028. do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  2029. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) );
  2030. if (!probe_len)
  2031. {
  2032. *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break;
  2033. }
  2034. else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8*)p == *(const mz_uint8*)q)) > match_len)
  2035. {
  2036. *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break;
  2037. c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]);
  2038. }
  2039. }
  2040. }
  2041. #else
  2042. static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len)
  2043. {
  2044. mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len;
  2045. mz_uint num_probes_left = d->m_max_probes[match_len >= 32];
  2046. const mz_uint8 *s = d->m_dict + pos, *p, *q;
  2047. mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1];
  2048. MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return;
  2049. for ( ; ; )
  2050. {
  2051. for ( ; ; )
  2052. {
  2053. if (--num_probes_left == 0) return;
  2054. #define TDEFL_PROBE \
  2055. next_probe_pos = d->m_next[probe_pos]; \
  2056. if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \
  2057. probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \
  2058. if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break;
  2059. TDEFL_PROBE
  2060. TDEFL_PROBE
  2061. TDEFL_PROBE
  2062. }
  2063. if (!dist) break;
  2064. p = s; q = d->m_dict + probe_pos;
  2065. for (probe_len = 0; probe_len < max_match_len; probe_len++) {
  2066. if (*p++ != *q++) break;
  2067. }
  2068. if (probe_len > match_len)
  2069. {
  2070. *pMatch_dist = dist;
  2071. if ((*pMatch_len = match_len = probe_len) == max_match_len) return;
  2072. c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1];
  2073. }
  2074. }
  2075. }
  2076. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES
  2077. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  2078. static mz_bool tdefl_compress_fast(tdefl_compressor *d)
  2079. {
  2080. // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio.
  2081. mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left;
  2082. mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags;
  2083. mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  2084. while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size)))
  2085. {
  2086. const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096;
  2087. mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
  2088. mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size);
  2089. d->m_src_buf_left -= num_bytes_to_process;
  2090. lookahead_size += num_bytes_to_process;
  2091. while (num_bytes_to_process)
  2092. {
  2093. mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process);
  2094. memcpy(d->m_dict + dst_pos, d->m_pSrc, n);
  2095. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  2096. memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos));
  2097. d->m_pSrc += n;
  2098. dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK;
  2099. num_bytes_to_process -= n;
  2100. }
  2101. dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size);
  2102. if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break;
  2103. while (lookahead_size >= 4)
  2104. {
  2105. mz_uint cur_match_dist, cur_match_len = 1;
  2106. mz_uint8 *pCur_dict = d->m_dict + cur_pos;
  2107. mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF;
  2108. mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK;
  2109. mz_uint probe_pos = d->m_hash[hash];
  2110. d->m_hash[hash] = (mz_uint16)lookahead_pos;
  2111. if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram))
  2112. {
  2113. const mz_uint16 *p = (const mz_uint16 *)pCur_dict;
  2114. const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos);
  2115. mz_uint32 probe_len = 32;
  2116. do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) &&
  2117. (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) );
  2118. cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q);
  2119. if (!probe_len)
  2120. cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0;
  2121. if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)))
  2122. {
  2123. cur_match_len = 1;
  2124. *pLZ_code_buf++ = (mz_uint8)first_trigram;
  2125. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  2126. d->m_huff_count[0][(mz_uint8)first_trigram]++;
  2127. }
  2128. else
  2129. {
  2130. mz_uint32 s0, s1;
  2131. cur_match_len = MZ_MIN(cur_match_len, lookahead_size);
  2132. MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE));
  2133. cur_match_dist--;
  2134. pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN);
  2135. *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist;
  2136. pLZ_code_buf += 3;
  2137. *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80);
  2138. s0 = s_tdefl_small_dist_sym[cur_match_dist & 511];
  2139. s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8];
  2140. d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++;
  2141. d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++;
  2142. }
  2143. }
  2144. else
  2145. {
  2146. *pLZ_code_buf++ = (mz_uint8)first_trigram;
  2147. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  2148. d->m_huff_count[0][(mz_uint8)first_trigram]++;
  2149. }
  2150. if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; }
  2151. total_lz_bytes += cur_match_len;
  2152. lookahead_pos += cur_match_len;
  2153. dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE);
  2154. cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK;
  2155. MZ_ASSERT(lookahead_size >= cur_match_len);
  2156. lookahead_size -= cur_match_len;
  2157. if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8])
  2158. {
  2159. int n;
  2160. d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
  2161. d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
  2162. if ((n = tdefl_flush_block(d, 0)) != 0)
  2163. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  2164. total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left;
  2165. }
  2166. }
  2167. while (lookahead_size)
  2168. {
  2169. mz_uint8 lit = d->m_dict[cur_pos];
  2170. total_lz_bytes++;
  2171. *pLZ_code_buf++ = lit;
  2172. *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1);
  2173. if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; }
  2174. d->m_huff_count[0][lit]++;
  2175. lookahead_pos++;
  2176. dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE);
  2177. cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK;
  2178. lookahead_size--;
  2179. if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8])
  2180. {
  2181. int n;
  2182. d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
  2183. d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
  2184. if ((n = tdefl_flush_block(d, 0)) != 0)
  2185. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  2186. total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left;
  2187. }
  2188. }
  2189. }
  2190. d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size;
  2191. d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left;
  2192. return MZ_TRUE;
  2193. }
  2194. #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  2195. static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit)
  2196. {
  2197. d->m_total_lz_bytes++;
  2198. *d->m_pLZ_code_buf++ = lit;
  2199. *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; }
  2200. d->m_huff_count[0][lit]++;
  2201. }
  2202. static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist)
  2203. {
  2204. mz_uint32 s0, s1;
  2205. MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE));
  2206. d->m_total_lz_bytes += match_len;
  2207. d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN);
  2208. match_dist -= 1;
  2209. d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF);
  2210. d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3;
  2211. *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; }
  2212. s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127];
  2213. d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++;
  2214. if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++;
  2215. }
  2216. static mz_bool tdefl_compress_normal(tdefl_compressor *d)
  2217. {
  2218. const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left;
  2219. tdefl_flush flush = d->m_flush;
  2220. while ((src_buf_left) || ((flush) && (d->m_lookahead_size)))
  2221. {
  2222. mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos;
  2223. // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN.
  2224. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1))
  2225. {
  2226. mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2;
  2227. mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK];
  2228. mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size);
  2229. const mz_uint8 *pSrc_end = pSrc ? pSrc + num_bytes_to_process : NULL;
  2230. src_buf_left -= num_bytes_to_process;
  2231. d->m_lookahead_size += num_bytes_to_process;
  2232. while (pSrc != pSrc_end)
  2233. {
  2234. mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  2235. hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
  2236. d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos);
  2237. dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++;
  2238. }
  2239. }
  2240. else
  2241. {
  2242. while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
  2243. {
  2244. mz_uint8 c = *pSrc++;
  2245. mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK;
  2246. src_buf_left--;
  2247. d->m_dict[dst_pos] = c;
  2248. if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1))
  2249. d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c;
  2250. if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN)
  2251. {
  2252. mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2;
  2253. mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1);
  2254. d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos);
  2255. }
  2256. }
  2257. }
  2258. d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size);
  2259. if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN))
  2260. break;
  2261. // Simple lazy/greedy parsing state machine.
  2262. len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK;
  2263. if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS))
  2264. {
  2265. if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))
  2266. {
  2267. mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK];
  2268. cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; }
  2269. if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1;
  2270. }
  2271. }
  2272. else
  2273. {
  2274. tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len);
  2275. }
  2276. if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5)))
  2277. {
  2278. cur_match_dist = cur_match_len = 0;
  2279. }
  2280. if (d->m_saved_match_len)
  2281. {
  2282. if (cur_match_len > d->m_saved_match_len)
  2283. {
  2284. tdefl_record_literal(d, (mz_uint8)d->m_saved_lit);
  2285. if (cur_match_len >= 128)
  2286. {
  2287. tdefl_record_match(d, cur_match_len, cur_match_dist);
  2288. d->m_saved_match_len = 0; len_to_move = cur_match_len;
  2289. }
  2290. else
  2291. {
  2292. d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len;
  2293. }
  2294. }
  2295. else
  2296. {
  2297. tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist);
  2298. len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0;
  2299. }
  2300. }
  2301. else if (!cur_match_dist)
  2302. tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]);
  2303. else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128))
  2304. {
  2305. tdefl_record_match(d, cur_match_len, cur_match_dist);
  2306. len_to_move = cur_match_len;
  2307. }
  2308. else
  2309. {
  2310. d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len;
  2311. }
  2312. // Move the lookahead forward by len_to_move bytes.
  2313. d->m_lookahead_pos += len_to_move;
  2314. MZ_ASSERT(d->m_lookahead_size >= len_to_move);
  2315. d->m_lookahead_size -= len_to_move;
  2316. d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE);
  2317. // Check if it's time to flush the current LZ codes to the internal output buffer.
  2318. if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) ||
  2319. ( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) )
  2320. {
  2321. int n;
  2322. d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left;
  2323. if ((n = tdefl_flush_block(d, 0)) != 0)
  2324. return (n < 0) ? MZ_FALSE : MZ_TRUE;
  2325. }
  2326. }
  2327. d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left;
  2328. return MZ_TRUE;
  2329. }
  2330. static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d)
  2331. {
  2332. if (d->m_pIn_buf_size)
  2333. {
  2334. *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf;
  2335. }
  2336. if (d->m_pOut_buf_size)
  2337. {
  2338. size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining);
  2339. memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n);
  2340. d->m_output_flush_ofs += (mz_uint)n;
  2341. d->m_output_flush_remaining -= (mz_uint)n;
  2342. d->m_out_buf_ofs += n;
  2343. *d->m_pOut_buf_size = d->m_out_buf_ofs;
  2344. }
  2345. return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY;
  2346. }
  2347. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush)
  2348. {
  2349. if (!d)
  2350. {
  2351. if (pIn_buf_size) *pIn_buf_size = 0;
  2352. if (pOut_buf_size) *pOut_buf_size = 0;
  2353. return TDEFL_STATUS_BAD_PARAM;
  2354. }
  2355. d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size;
  2356. d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size;
  2357. d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0;
  2358. d->m_out_buf_ofs = 0;
  2359. d->m_flush = flush;
  2360. if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) ||
  2361. (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) )
  2362. {
  2363. if (pIn_buf_size) *pIn_buf_size = 0;
  2364. if (pOut_buf_size) *pOut_buf_size = 0;
  2365. return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM);
  2366. }
  2367. d->m_wants_to_finish |= (flush == TDEFL_FINISH);
  2368. if ((d->m_output_flush_remaining) || (d->m_finished))
  2369. return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  2370. #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  2371. if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) &&
  2372. ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) &&
  2373. ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0))
  2374. {
  2375. if (!tdefl_compress_fast(d))
  2376. return d->m_prev_return_status;
  2377. }
  2378. else
  2379. #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN
  2380. {
  2381. if (!tdefl_compress_normal(d))
  2382. return d->m_prev_return_status;
  2383. }
  2384. if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf))
  2385. d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf);
  2386. if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining))
  2387. {
  2388. if (tdefl_flush_block(d, flush) < 0)
  2389. return d->m_prev_return_status;
  2390. d->m_finished = (flush == TDEFL_FINISH);
  2391. if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_ARR(d->m_hash); MZ_CLEAR_ARR(d->m_next); d->m_dict_size = 0; }
  2392. }
  2393. return (d->m_prev_return_status = tdefl_flush_output_buffer(d));
  2394. }
  2395. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush)
  2396. {
  2397. MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush);
  2398. }
  2399. tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
  2400. {
  2401. d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user;
  2402. d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0;
  2403. d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3;
  2404. if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_ARR(d->m_hash);
  2405. d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0;
  2406. d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0;
  2407. d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8;
  2408. d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY;
  2409. d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1;
  2410. d->m_pIn_buf = NULL; d->m_pOut_buf = NULL;
  2411. d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL;
  2412. d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0;
  2413. memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0);
  2414. memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1);
  2415. return TDEFL_STATUS_OKAY;
  2416. }
  2417. #ifndef MINIZ_SDL_NOUNUSED
  2418. tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d)
  2419. {
  2420. return d->m_prev_return_status;
  2421. }
  2422. mz_uint32 tdefl_get_adler32(tdefl_compressor *d)
  2423. {
  2424. return d->m_adler32;
  2425. }
  2426. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags)
  2427. {
  2428. tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE;
  2429. pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE;
  2430. succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY);
  2431. succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE);
  2432. MZ_FREE(pComp); return succeeded;
  2433. }
  2434. #endif /* MINIZ_SDL_NOUNUSED */
  2435. typedef struct
  2436. {
  2437. size_t m_size, m_capacity;
  2438. mz_uint8 *m_pBuf;
  2439. mz_bool m_expandable;
  2440. } tdefl_output_buffer;
  2441. static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser)
  2442. {
  2443. tdefl_output_buffer *p = (tdefl_output_buffer *)pUser;
  2444. size_t new_size = p->m_size + len;
  2445. if (new_size > p->m_capacity)
  2446. {
  2447. size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE;
  2448. do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity);
  2449. pNew_buf = (mz_uint8*)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE;
  2450. p->m_pBuf = pNew_buf; p->m_capacity = new_capacity;
  2451. }
  2452. memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size;
  2453. return MZ_TRUE;
  2454. }
  2455. #ifndef MINIZ_SDL_NOUNUSED
  2456. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags)
  2457. {
  2458. tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf);
  2459. if (!pOut_len) return MZ_FALSE; else *pOut_len = 0;
  2460. out_buf.m_expandable = MZ_TRUE;
  2461. if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL;
  2462. *pOut_len = out_buf.m_size; return out_buf.m_pBuf;
  2463. }
  2464. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags)
  2465. {
  2466. tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf);
  2467. if (!pOut_buf) return 0;
  2468. out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len;
  2469. if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0;
  2470. return out_buf.m_size;
  2471. }
  2472. #endif /* MINIZ_SDL_NOUNUSED */
  2473. #ifndef MINIZ_NO_ZLIB_APIS
  2474. static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 };
  2475. // level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files).
  2476. mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy)
  2477. {
  2478. mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0);
  2479. if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER;
  2480. if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS;
  2481. else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES;
  2482. else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK;
  2483. else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS;
  2484. else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES;
  2485. return comp_flags;
  2486. }
  2487. #endif //MINIZ_NO_ZLIB_APIS
  2488. #ifdef _MSC_VER
  2489. #pragma warning (push)
  2490. #pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal)
  2491. #endif
  2492. // Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at
  2493. // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/.
  2494. // This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck.
  2495. MINIZ_STATIC void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, int bpl, size_t *pLen_out, mz_uint level, mz_bool flip, mz_uint8 *plte, int plte_size, mz_uint8 *trns, int trns_size)
  2496. {
  2497. // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined.
  2498. static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 };
  2499. tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, y, z = 0; mz_uint32 c; *pLen_out = 0; size_t data_start, data_size;
  2500. if (!pComp) return NULL;
  2501. MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE;
  2502. out_buf.m_capacity = 57+MZ_MAX(64, (1+w*num_chans)*h);
  2503. if (plte_size > 0)
  2504. out_buf.m_capacity += 12+plte_size;
  2505. if (trns_size > 0)
  2506. out_buf.m_capacity += 12+trns_size;
  2507. if (NULL == (out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; }
  2508. // write header
  2509. {
  2510. static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06};
  2511. mz_uint8 pnghdr[33]={ 0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,
  2512. 0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52,
  2513. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  2514. 0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
  2515. pnghdr[18] = (mz_uint8)(w>>8);
  2516. pnghdr[19] = (mz_uint8)(w>>0);
  2517. pnghdr[22] = (mz_uint8)(h>>8);
  2518. pnghdr[23] = (mz_uint8)(h>>0);
  2519. if (num_chans == 1 && plte_size > 0)
  2520. pnghdr[25] = 3;
  2521. else
  2522. pnghdr[25] = (chans[num_chans]);
  2523. c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,pnghdr+12,17);
  2524. for (i=0; i<4; ++i, c<<=8) ((mz_uint8*)(pnghdr+29))[i] = (mz_uint8)(c>>24);
  2525. if (!tdefl_output_buffer_putter(pnghdr, sizeof(pnghdr), &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2526. }
  2527. // write PLTE chunk
  2528. if (plte_size > 0)
  2529. {
  2530. mz_uint8 hdr[8]={0x00,0x00,0x00,0x00,0x50,0x4c,0x54,0x45};
  2531. hdr[0] = (mz_uint8)(plte_size>>24);
  2532. hdr[1] = (mz_uint8)(plte_size>>16);
  2533. hdr[2] = (mz_uint8)(plte_size>> 8);
  2534. hdr[3] = (mz_uint8)(plte_size>> 0);
  2535. if (!tdefl_output_buffer_putter(hdr, sizeof(hdr), &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2536. data_start = out_buf.m_size;
  2537. if (!tdefl_output_buffer_putter(plte, plte_size, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2538. if (!tdefl_output_buffer_putter("\0\0\0\0", 4, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2539. c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,out_buf.m_pBuf+data_start-4, plte_size+4);
  2540. for (i=0; i<4; ++i, c<<=8) (out_buf.m_pBuf+out_buf.m_size-4)[i] = (mz_uint8)(c >> 24);
  2541. }
  2542. // write tRNS chunk
  2543. if (trns_size > 0)
  2544. {
  2545. mz_uint8 hdr[8]={0x00,0x00,0x00,0x00,0x74,0x52,0x4E,0x53};
  2546. hdr[0] = (mz_uint8)(trns_size>>24);
  2547. hdr[1] = (mz_uint8)(trns_size>>16);
  2548. hdr[2] = (mz_uint8)(trns_size>> 8);
  2549. hdr[3] = (mz_uint8)(trns_size>> 0);
  2550. if (!tdefl_output_buffer_putter(hdr, sizeof(hdr), &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2551. data_start = out_buf.m_size;
  2552. if (!tdefl_output_buffer_putter(trns, trns_size, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2553. if (!tdefl_output_buffer_putter("\0\0\0\0", 4, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2554. c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,out_buf.m_pBuf+data_start-4, trns_size+4);
  2555. for (i=0; i<4; ++i, c<<=8) (out_buf.m_pBuf+out_buf.m_size-4)[i] = (mz_uint8)(c >> 24);
  2556. }
  2557. // write IDAT chunk
  2558. if (!tdefl_output_buffer_putter("\0\0\0\0\x49\x44\x41\x54", 8, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2559. data_start = out_buf.m_size;
  2560. // compress image data
  2561. tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER);
  2562. for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8*)pImage + (flip ? (h - 1 - y) : y) * bpl, w * num_chans, TDEFL_NO_FLUSH); }
  2563. if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2564. // write IDAT size
  2565. data_size = out_buf.m_size-data_start;
  2566. (out_buf.m_pBuf+data_start-8)[0] = (mz_uint8)(data_size>>24);
  2567. (out_buf.m_pBuf+data_start-8)[1] = (mz_uint8)(data_size>>16);
  2568. (out_buf.m_pBuf+data_start-8)[2] = (mz_uint8)(data_size>> 8);
  2569. (out_buf.m_pBuf+data_start-8)[3] = (mz_uint8)(data_size>> 0);
  2570. // write footer (IDAT CRC-32, followed by IEND chunk)
  2571. if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; }
  2572. c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,out_buf.m_pBuf+data_start-4, data_size+4);
  2573. for (i=0; i<4; ++i, c<<=8) (out_buf.m_pBuf+out_buf.m_size-16)[i] = (mz_uint8)(c >> 24);
  2574. // compute final size of file, grab compressed data buffer and return
  2575. *pLen_out = out_buf.m_size;
  2576. MZ_FREE(pComp);
  2577. return out_buf.m_pBuf;
  2578. }
  2579. #ifndef MINIZ_SDL_NOUNUSED
  2580. MINIZ_STATIC void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, int bpl, size_t *pLen_out)
  2581. {
  2582. // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out)
  2583. return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, bpl, pLen_out, 6, MZ_FALSE, NULL, 0, NULL, 0);
  2584. }
  2585. #endif
  2586. #ifdef _MSC_VER
  2587. #pragma warning (pop)
  2588. #endif
  2589. #endif /*#ifndef MINIZ_NO_DEFLATE_APIS*/
  2590. // ------------------- .ZIP archive reading
  2591. #ifndef MINIZ_NO_ARCHIVE_APIS
  2592. #ifdef MINIZ_NO_STDIO
  2593. #define MZ_FILE void *
  2594. #else
  2595. #include <stdio.h>
  2596. #include <sys/stat.h>
  2597. #if defined(_MSC_VER) || defined(__MINGW64__)
  2598. static FILE *mz_fopen(const char *pFilename, const char *pMode)
  2599. {
  2600. FILE* pFile = NULL;
  2601. fopen_s(&pFile, pFilename, pMode);
  2602. return pFile;
  2603. }
  2604. static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream)
  2605. {
  2606. FILE* pFile = NULL;
  2607. if (freopen_s(&pFile, pPath, pMode, pStream))
  2608. return NULL;
  2609. return pFile;
  2610. }
  2611. #ifndef MINIZ_NO_TIME
  2612. #include <sys/utime.h>
  2613. #endif
  2614. #define MZ_FILE FILE
  2615. #define MZ_FOPEN mz_fopen
  2616. #define MZ_FCLOSE fclose
  2617. #define MZ_FREAD fread
  2618. #define MZ_FWRITE fwrite
  2619. #define MZ_FTELL64 _ftelli64
  2620. #define MZ_FSEEK64 _fseeki64
  2621. #define MZ_FILE_STAT_STRUCT _stat
  2622. #define MZ_FILE_STAT _stat
  2623. #define MZ_FFLUSH fflush
  2624. #define MZ_FREOPEN mz_freopen
  2625. #define MZ_DELETE_FILE remove
  2626. #elif defined(__MINGW32__)
  2627. #ifndef MINIZ_NO_TIME
  2628. #include <sys/utime.h>
  2629. #endif
  2630. #define MZ_FILE FILE
  2631. #define MZ_FOPEN(f, m) fopen(f, m)
  2632. #define MZ_FCLOSE fclose
  2633. #define MZ_FREAD fread
  2634. #define MZ_FWRITE fwrite
  2635. #define MZ_FTELL64 ftello64
  2636. #define MZ_FSEEK64 fseeko64
  2637. #define MZ_FILE_STAT_STRUCT _stat
  2638. #define MZ_FILE_STAT _stat
  2639. #define MZ_FFLUSH fflush
  2640. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  2641. #define MZ_DELETE_FILE remove
  2642. #elif defined(__TINYC__)
  2643. #ifndef MINIZ_NO_TIME
  2644. #include <sys/utime.h>
  2645. #endif
  2646. #define MZ_FILE FILE
  2647. #define MZ_FOPEN(f, m) fopen(f, m)
  2648. #define MZ_FCLOSE fclose
  2649. #define MZ_FREAD fread
  2650. #define MZ_FWRITE fwrite
  2651. #define MZ_FTELL64 ftell
  2652. #define MZ_FSEEK64 fseek
  2653. #define MZ_FILE_STAT_STRUCT stat
  2654. #define MZ_FILE_STAT stat
  2655. #define MZ_FFLUSH fflush
  2656. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  2657. #define MZ_DELETE_FILE remove
  2658. #elif defined(__GNUC__) && _LARGEFILE64_SOURCE
  2659. #ifndef MINIZ_NO_TIME
  2660. #include <utime.h>
  2661. #endif
  2662. #define MZ_FILE FILE
  2663. #define MZ_FOPEN(f, m) fopen64(f, m)
  2664. #define MZ_FCLOSE fclose
  2665. #define MZ_FREAD fread
  2666. #define MZ_FWRITE fwrite
  2667. #define MZ_FTELL64 ftello64
  2668. #define MZ_FSEEK64 fseeko64
  2669. #define MZ_FILE_STAT_STRUCT stat64
  2670. #define MZ_FILE_STAT stat64
  2671. #define MZ_FFLUSH fflush
  2672. #define MZ_FREOPEN(p, m, s) freopen64(p, m, s)
  2673. #define MZ_DELETE_FILE remove
  2674. #else
  2675. #ifndef MINIZ_NO_TIME
  2676. #include <utime.h>
  2677. #endif
  2678. #define MZ_FILE FILE
  2679. #define MZ_FOPEN(f, m) fopen(f, m)
  2680. #define MZ_FCLOSE fclose
  2681. #define MZ_FREAD fread
  2682. #define MZ_FWRITE fwrite
  2683. #define MZ_FTELL64 ftello
  2684. #define MZ_FSEEK64 fseeko
  2685. #define MZ_FILE_STAT_STRUCT stat
  2686. #define MZ_FILE_STAT stat
  2687. #define MZ_FFLUSH fflush
  2688. #define MZ_FREOPEN(f, m, s) freopen(f, m, s)
  2689. #define MZ_DELETE_FILE remove
  2690. #endif // #ifdef _MSC_VER
  2691. #endif // #ifdef MINIZ_NO_STDIO
  2692. #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c))
  2693. // Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff.
  2694. enum
  2695. {
  2696. // ZIP archive identifiers and record sizes
  2697. MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50,
  2698. MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22,
  2699. // Central directory header record offsets
  2700. MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8,
  2701. MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16,
  2702. MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30,
  2703. MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42,
  2704. // Local directory header offsets
  2705. MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10,
  2706. MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22,
  2707. MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28,
  2708. // End of central directory offsets
  2709. MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8,
  2710. MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20,
  2711. };
  2712. typedef struct
  2713. {
  2714. void *m_p;
  2715. size_t m_size, m_capacity;
  2716. mz_uint m_element_size;
  2717. } mz_zip_array;
  2718. struct mz_zip_internal_state_tag
  2719. {
  2720. mz_zip_array m_central_dir;
  2721. mz_zip_array m_central_dir_offsets;
  2722. mz_zip_array m_sorted_central_dir_offsets;
  2723. MZ_FILE *m_pFile;
  2724. void *m_pMem;
  2725. size_t m_mem_size;
  2726. size_t m_mem_capacity;
  2727. };
  2728. #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size
  2729. #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index]
  2730. static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray)
  2731. {
  2732. pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p);
  2733. memset(pArray, 0, sizeof(mz_zip_array));
  2734. }
  2735. static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing)
  2736. {
  2737. void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE;
  2738. if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; }
  2739. if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE;
  2740. pArray->m_p = pNew_p; pArray->m_capacity = new_capacity;
  2741. return MZ_TRUE;
  2742. }
  2743. static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing)
  2744. {
  2745. if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; }
  2746. return MZ_TRUE;
  2747. }
  2748. static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing)
  2749. {
  2750. if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; }
  2751. pArray->m_size = new_size;
  2752. return MZ_TRUE;
  2753. }
  2754. static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n)
  2755. {
  2756. return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE);
  2757. }
  2758. static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n)
  2759. {
  2760. size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE;
  2761. memcpy((mz_uint8*)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size);
  2762. return MZ_TRUE;
  2763. }
  2764. #ifndef MINIZ_NO_TIME
  2765. static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date)
  2766. {
  2767. struct tm tm;
  2768. memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1;
  2769. tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31;
  2770. tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62;
  2771. return mktime(&tm);
  2772. }
  2773. static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date)
  2774. {
  2775. #ifdef _MSC_VER
  2776. struct tm tm_struct;
  2777. struct tm *tm = &tm_struct;
  2778. errno_t err = localtime_s(tm, &time);
  2779. if (err)
  2780. {
  2781. *pDOS_date = 0; *pDOS_time = 0;
  2782. return;
  2783. }
  2784. #else
  2785. struct tm *tm = localtime(&time);
  2786. #endif
  2787. *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1));
  2788. *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday);
  2789. }
  2790. #endif
  2791. #ifndef MINIZ_NO_STDIO
  2792. static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date)
  2793. {
  2794. #ifdef MINIZ_NO_TIME
  2795. (void)pFilename; *pDOS_date = *pDOS_time = 0;
  2796. #else
  2797. struct MZ_FILE_STAT_STRUCT file_stat;
  2798. // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh.
  2799. if (MZ_FILE_STAT(pFilename, &file_stat) != 0)
  2800. return MZ_FALSE;
  2801. mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date);
  2802. #endif // #ifdef MINIZ_NO_TIME
  2803. return MZ_TRUE;
  2804. }
  2805. #ifndef MINIZ_NO_TIME
  2806. static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time)
  2807. {
  2808. struct utimbuf t; t.actime = access_time; t.modtime = modified_time;
  2809. return !utime(pFilename, &t);
  2810. }
  2811. #endif // #ifndef MINIZ_NO_TIME
  2812. #endif // #ifndef MINIZ_NO_STDIO
  2813. static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags)
  2814. {
  2815. (void)flags;
  2816. if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
  2817. return MZ_FALSE;
  2818. if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;
  2819. if (!pZip->m_pFree) pZip->m_pFree = def_free_func;
  2820. if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;
  2821. pZip->m_zip_mode = MZ_ZIP_MODE_READING;
  2822. pZip->m_archive_size = 0;
  2823. pZip->m_central_directory_file_ofs = 0;
  2824. pZip->m_total_files = 0;
  2825. if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
  2826. return MZ_FALSE;
  2827. memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
  2828. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8));
  2829. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32));
  2830. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32));
  2831. return MZ_TRUE;
  2832. }
  2833. static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index)
  2834. {
  2835. const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE;
  2836. const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index));
  2837. mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  2838. mz_uint8 l = 0, r = 0;
  2839. pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  2840. pE = pL + MZ_MIN(l_len, r_len);
  2841. while (pL < pE)
  2842. {
  2843. if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))
  2844. break;
  2845. pL++; pR++;
  2846. }
  2847. return (pL == pE) ? (l_len < r_len) : (l < r);
  2848. }
  2849. #define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END
  2850. // Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.)
  2851. static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip)
  2852. {
  2853. mz_zip_internal_state *pState = pZip->m_pState;
  2854. const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
  2855. const mz_zip_array *pCentral_dir = &pState->m_central_dir;
  2856. mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0);
  2857. const int size = pZip->m_total_files;
  2858. int start = (size - 2) >> 1, end;
  2859. while (start >= 0)
  2860. {
  2861. int child, root = start;
  2862. for ( ; ; )
  2863. {
  2864. if ((child = (root << 1) + 1) >= size)
  2865. break;
  2866. child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])));
  2867. if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child]))
  2868. break;
  2869. MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child;
  2870. }
  2871. start--;
  2872. }
  2873. end = size - 1;
  2874. while (end > 0)
  2875. {
  2876. int child, root = 0;
  2877. MZ_SWAP_UINT32(pIndices[end], pIndices[0]);
  2878. for ( ; ; )
  2879. {
  2880. if ((child = (root << 1) + 1) >= end)
  2881. break;
  2882. child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]));
  2883. if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child]))
  2884. break;
  2885. MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child;
  2886. }
  2887. end--;
  2888. }
  2889. }
  2890. static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags)
  2891. {
  2892. mz_uint cdir_size, num_this_disk, cdir_disk_index;
  2893. mz_uint64 cdir_ofs;
  2894. mz_int64 cur_file_ofs;
  2895. const mz_uint8 *p;
  2896. mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32;
  2897. mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0);
  2898. // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there.
  2899. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
  2900. return MZ_FALSE;
  2901. // Find the end of central directory record by scanning the file from the end towards the beginning.
  2902. cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0);
  2903. for ( ; ; )
  2904. {
  2905. int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs);
  2906. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n)
  2907. return MZ_FALSE;
  2908. for (i = n - 4; i >= 0; --i)
  2909. if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG)
  2910. break;
  2911. if (i >= 0)
  2912. {
  2913. cur_file_ofs += i;
  2914. break;
  2915. }
  2916. if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)))
  2917. return MZ_FALSE;
  2918. cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0);
  2919. }
  2920. // Read and verify the end of central directory record.
  2921. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE)
  2922. return MZ_FALSE;
  2923. if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) ||
  2924. ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS)))
  2925. return MZ_FALSE;
  2926. num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS);
  2927. cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS);
  2928. if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1)))
  2929. return MZ_FALSE;
  2930. if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)
  2931. return MZ_FALSE;
  2932. cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS);
  2933. if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size)
  2934. return MZ_FALSE;
  2935. pZip->m_central_directory_file_ofs = cdir_ofs;
  2936. if (pZip->m_total_files)
  2937. {
  2938. mz_uint i, n;
  2939. // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices.
  2940. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) ||
  2941. (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE)))
  2942. return MZ_FALSE;
  2943. if (sort_central_dir)
  2944. {
  2945. if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE))
  2946. return MZ_FALSE;
  2947. }
  2948. if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size)
  2949. return MZ_FALSE;
  2950. // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported).
  2951. p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p;
  2952. for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i)
  2953. {
  2954. mz_uint total_header_size, comp_size, decomp_size, disk_index;
  2955. if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG))
  2956. return MZ_FALSE;
  2957. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p);
  2958. if (sort_central_dir)
  2959. MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i;
  2960. comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  2961. decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  2962. if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF))
  2963. return MZ_FALSE;
  2964. disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS);
  2965. if ((disk_index != num_this_disk) && (disk_index != 1))
  2966. return MZ_FALSE;
  2967. if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size)
  2968. return MZ_FALSE;
  2969. if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n)
  2970. return MZ_FALSE;
  2971. n -= total_header_size; p += total_header_size;
  2972. }
  2973. }
  2974. if (sort_central_dir)
  2975. mz_zip_reader_sort_central_dir_offsets_by_filename(pZip);
  2976. return MZ_TRUE;
  2977. }
  2978. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags)
  2979. {
  2980. if ((!pZip) || (!pZip->m_pRead))
  2981. return MZ_FALSE;
  2982. if (!mz_zip_reader_init_internal(pZip, flags))
  2983. return MZ_FALSE;
  2984. pZip->m_archive_size = size;
  2985. if (!mz_zip_reader_read_central_dir(pZip, flags))
  2986. {
  2987. mz_zip_reader_end(pZip);
  2988. return MZ_FALSE;
  2989. }
  2990. return MZ_TRUE;
  2991. }
  2992. static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n)
  2993. {
  2994. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  2995. size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n);
  2996. memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s);
  2997. return s;
  2998. }
  2999. mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags)
  3000. {
  3001. if (!mz_zip_reader_init_internal(pZip, flags))
  3002. return MZ_FALSE;
  3003. pZip->m_archive_size = size;
  3004. pZip->m_pRead = mz_zip_mem_read_func;
  3005. pZip->m_pIO_opaque = pZip;
  3006. #ifdef __cplusplus
  3007. pZip->m_pState->m_pMem = const_cast<void *>(pMem);
  3008. #else
  3009. pZip->m_pState->m_pMem = (void *)pMem;
  3010. #endif
  3011. pZip->m_pState->m_mem_size = size;
  3012. if (!mz_zip_reader_read_central_dir(pZip, flags))
  3013. {
  3014. mz_zip_reader_end(pZip);
  3015. return MZ_FALSE;
  3016. }
  3017. return MZ_TRUE;
  3018. }
  3019. #ifndef MINIZ_NO_STDIO
  3020. static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n)
  3021. {
  3022. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  3023. mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
  3024. if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
  3025. return 0;
  3026. return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile);
  3027. }
  3028. mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags)
  3029. {
  3030. mz_uint64 file_size;
  3031. MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb");
  3032. if (!pFile)
  3033. return MZ_FALSE;
  3034. if (MZ_FSEEK64(pFile, 0, SEEK_END))
  3035. {
  3036. MZ_FCLOSE(pFile);
  3037. return MZ_FALSE;
  3038. }
  3039. file_size = MZ_FTELL64(pFile);
  3040. if (!mz_zip_reader_init_internal(pZip, flags))
  3041. {
  3042. MZ_FCLOSE(pFile);
  3043. return MZ_FALSE;
  3044. }
  3045. pZip->m_pRead = mz_zip_file_read_func;
  3046. pZip->m_pIO_opaque = pZip;
  3047. pZip->m_pState->m_pFile = pFile;
  3048. pZip->m_archive_size = file_size;
  3049. if (!mz_zip_reader_read_central_dir(pZip, flags))
  3050. {
  3051. mz_zip_reader_end(pZip);
  3052. return MZ_FALSE;
  3053. }
  3054. return MZ_TRUE;
  3055. }
  3056. #endif // #ifndef MINIZ_NO_STDIO
  3057. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip)
  3058. {
  3059. return pZip ? pZip->m_total_files : 0;
  3060. }
  3061. static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index)
  3062. {
  3063. if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  3064. return NULL;
  3065. return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index));
  3066. }
  3067. mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index)
  3068. {
  3069. mz_uint m_bit_flag;
  3070. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  3071. if (!p)
  3072. return MZ_FALSE;
  3073. m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
  3074. return (m_bit_flag & 1);
  3075. }
  3076. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index)
  3077. {
  3078. mz_uint filename_len, external_attr;
  3079. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  3080. if (!p)
  3081. return MZ_FALSE;
  3082. // First see if the filename ends with a '/' character.
  3083. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  3084. if (filename_len)
  3085. {
  3086. if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/')
  3087. return MZ_TRUE;
  3088. }
  3089. // Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct.
  3090. // Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field.
  3091. // FIXME: Remove this check? Is it necessary - we already check the filename.
  3092. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
  3093. if ((external_attr & 0x10) != 0)
  3094. return MZ_TRUE;
  3095. return MZ_FALSE;
  3096. }
  3097. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat)
  3098. {
  3099. mz_uint n;
  3100. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  3101. if ((!p) || (!pStat))
  3102. return MZ_FALSE;
  3103. // Unpack the central directory record.
  3104. pStat->m_file_index = file_index;
  3105. pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index);
  3106. pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS);
  3107. pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS);
  3108. pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS);
  3109. pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS);
  3110. #ifndef MINIZ_NO_TIME
  3111. pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS));
  3112. #endif
  3113. pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS);
  3114. pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  3115. pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  3116. pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS);
  3117. pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS);
  3118. pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
  3119. // Copy as much of the filename and comment as possible.
  3120. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1);
  3121. memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0';
  3122. n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1);
  3123. pStat->m_comment_size = n;
  3124. memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0';
  3125. return MZ_TRUE;
  3126. }
  3127. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size)
  3128. {
  3129. mz_uint n;
  3130. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  3131. if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; }
  3132. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  3133. if (filename_buf_size)
  3134. {
  3135. n = MZ_MIN(n, filename_buf_size - 1);
  3136. memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n);
  3137. pFilename[n] = '\0';
  3138. }
  3139. return n + 1;
  3140. }
  3141. static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags)
  3142. {
  3143. mz_uint i;
  3144. if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE)
  3145. return 0 == memcmp(pA, pB, len);
  3146. for (i = 0; i < len; ++i)
  3147. if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i]))
  3148. return MZ_FALSE;
  3149. return MZ_TRUE;
  3150. }
  3151. static MZ_FORCEINLINE int mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len)
  3152. {
  3153. const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE;
  3154. mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  3155. mz_uint8 l = 0, r = 0;
  3156. pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  3157. pE = pL + MZ_MIN(l_len, r_len);
  3158. while (pL < pE)
  3159. {
  3160. if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR)))
  3161. break;
  3162. pL++; pR++;
  3163. }
  3164. return (pL == pE) ? (int)(l_len - r_len) : (l - r);
  3165. }
  3166. static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename)
  3167. {
  3168. mz_zip_internal_state *pState = pZip->m_pState;
  3169. const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets;
  3170. const mz_zip_array *pCentral_dir = &pState->m_central_dir;
  3171. mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0);
  3172. const int size = pZip->m_total_files;
  3173. const mz_uint filename_len = (mz_uint)strlen(pFilename);
  3174. int l = 0, h = size - 1;
  3175. while (l <= h)
  3176. {
  3177. int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len);
  3178. if (!comp)
  3179. return file_index;
  3180. else if (comp < 0)
  3181. l = m + 1;
  3182. else
  3183. h = m - 1;
  3184. }
  3185. return -1;
  3186. }
  3187. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags)
  3188. {
  3189. mz_uint file_index; size_t name_len, comment_len;
  3190. if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  3191. return -1;
  3192. if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size))
  3193. return mz_zip_reader_locate_file_binary_search(pZip, pName);
  3194. name_len = strlen(pName); if (name_len > 0xFFFF) return -1;
  3195. comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1;
  3196. for (file_index = 0; file_index < pZip->m_total_files; file_index++)
  3197. {
  3198. const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index));
  3199. mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS);
  3200. const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE;
  3201. if (filename_len < name_len)
  3202. continue;
  3203. if (comment_len)
  3204. {
  3205. mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  3206. const char *pFile_comment = pFilename + filename_len + file_extra_len;
  3207. if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags)))
  3208. continue;
  3209. }
  3210. if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len))
  3211. {
  3212. int ofs = filename_len - 1;
  3213. do
  3214. {
  3215. if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':'))
  3216. break;
  3217. } while (--ofs >= 0);
  3218. ofs++;
  3219. pFilename += ofs; filename_len -= ofs;
  3220. }
  3221. if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags)))
  3222. return file_index;
  3223. }
  3224. return -1;
  3225. }
  3226. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size)
  3227. {
  3228. int status = TINFL_STATUS_DONE;
  3229. mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail;
  3230. mz_zip_archive_file_stat file_stat;
  3231. void *pRead_buf;
  3232. mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  3233. tinfl_decompressor inflator;
  3234. if ((buf_size) && (!pBuf))
  3235. return MZ_FALSE;
  3236. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
  3237. return MZ_FALSE;
  3238. // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes)
  3239. if (!file_stat.m_comp_size)
  3240. return MZ_TRUE;
  3241. // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers).
  3242. // I'm torn how to handle this case - should it fail instead?
  3243. if (mz_zip_reader_is_file_a_directory(pZip, file_index))
  3244. return MZ_TRUE;
  3245. // Encryption and patch files are not supported.
  3246. if (file_stat.m_bit_flag & (1 | 32))
  3247. return MZ_FALSE;
  3248. // This function only supports stored and deflate.
  3249. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED))
  3250. return MZ_FALSE;
  3251. // Ensure supplied output buffer is large enough.
  3252. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size;
  3253. if (buf_size < needed_size)
  3254. return MZ_FALSE;
  3255. // Read and parse the local directory entry.
  3256. cur_file_ofs = file_stat.m_local_header_ofs;
  3257. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  3258. return MZ_FALSE;
  3259. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  3260. return MZ_FALSE;
  3261. cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  3262. if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
  3263. return MZ_FALSE;
  3264. if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method))
  3265. {
  3266. // The file is stored or the caller has requested the compressed data.
  3267. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size)
  3268. return MZ_FALSE;
  3269. return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32);
  3270. }
  3271. // Decompress the file either directly from memory or from a file input buffer.
  3272. tinfl_init(&inflator);
  3273. if (pZip->m_pState->m_pMem)
  3274. {
  3275. // Read directly from the archive in memory.
  3276. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
  3277. read_buf_size = read_buf_avail = file_stat.m_comp_size;
  3278. comp_remaining = 0;
  3279. }
  3280. else if (pUser_read_buf)
  3281. {
  3282. // Use a user provided read buffer.
  3283. if (!user_read_buf_size)
  3284. return MZ_FALSE;
  3285. pRead_buf = (mz_uint8 *)pUser_read_buf;
  3286. read_buf_size = user_read_buf_size;
  3287. read_buf_avail = 0;
  3288. comp_remaining = file_stat.m_comp_size;
  3289. }
  3290. else
  3291. {
  3292. // Temporarily allocate a read buffer.
  3293. read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE);
  3294. #ifdef _MSC_VER
  3295. if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))
  3296. #else
  3297. if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF))
  3298. #endif
  3299. return MZ_FALSE;
  3300. if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size)))
  3301. return MZ_FALSE;
  3302. read_buf_avail = 0;
  3303. comp_remaining = file_stat.m_comp_size;
  3304. }
  3305. do
  3306. {
  3307. size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs);
  3308. if ((!read_buf_avail) && (!pZip->m_pState->m_pMem))
  3309. {
  3310. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  3311. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)
  3312. {
  3313. status = TINFL_STATUS_FAILED;
  3314. break;
  3315. }
  3316. cur_file_ofs += read_buf_avail;
  3317. comp_remaining -= read_buf_avail;
  3318. read_buf_ofs = 0;
  3319. }
  3320. in_buf_size = (size_t)read_buf_avail;
  3321. status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0));
  3322. read_buf_avail -= in_buf_size;
  3323. read_buf_ofs += in_buf_size;
  3324. out_buf_ofs += out_buf_size;
  3325. } while (status == TINFL_STATUS_NEEDS_MORE_INPUT);
  3326. if (status == TINFL_STATUS_DONE)
  3327. {
  3328. // Make sure the entire file was decompressed, and check its CRC.
  3329. if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32))
  3330. status = TINFL_STATUS_FAILED;
  3331. }
  3332. if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf))
  3333. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  3334. return status == TINFL_STATUS_DONE;
  3335. }
  3336. mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size)
  3337. {
  3338. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  3339. if (file_index < 0)
  3340. return MZ_FALSE;
  3341. return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size);
  3342. }
  3343. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags)
  3344. {
  3345. return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0);
  3346. }
  3347. mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags)
  3348. {
  3349. return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0);
  3350. }
  3351. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags)
  3352. {
  3353. mz_uint64 comp_size, uncomp_size, alloc_size;
  3354. const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index);
  3355. void *pBuf;
  3356. if (pSize)
  3357. *pSize = 0;
  3358. if (!p)
  3359. return NULL;
  3360. comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  3361. uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS);
  3362. alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size;
  3363. #ifdef _MSC_VER
  3364. if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
  3365. #else
  3366. if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF))
  3367. #endif
  3368. return NULL;
  3369. if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size)))
  3370. return NULL;
  3371. if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags))
  3372. {
  3373. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  3374. return NULL;
  3375. }
  3376. if (pSize) *pSize = (size_t)alloc_size;
  3377. return pBuf;
  3378. }
  3379. void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags)
  3380. {
  3381. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  3382. if (file_index < 0)
  3383. {
  3384. if (pSize) *pSize = 0;
  3385. return MZ_FALSE;
  3386. }
  3387. return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags);
  3388. }
  3389. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags)
  3390. {
  3391. int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT;
  3392. mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs;
  3393. mz_zip_archive_file_stat file_stat;
  3394. void *pRead_buf = NULL; void *pWrite_buf = NULL;
  3395. mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  3396. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
  3397. return MZ_FALSE;
  3398. // Empty file, or a directory (but not always a directory - I've seen odd zips with directories that have compressed data which inflates to 0 bytes)
  3399. if (!file_stat.m_comp_size)
  3400. return MZ_TRUE;
  3401. // Entry is a subdirectory (I've seen old zips with dir entries which have compressed deflate data which inflates to 0 bytes, but these entries claim to uncompress to 512 bytes in the headers).
  3402. // I'm torn how to handle this case - should it fail instead?
  3403. if (mz_zip_reader_is_file_a_directory(pZip, file_index))
  3404. return MZ_TRUE;
  3405. // Encryption and patch files are not supported.
  3406. if (file_stat.m_bit_flag & (1 | 32))
  3407. return MZ_FALSE;
  3408. // This function only supports stored and deflate.
  3409. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED))
  3410. return MZ_FALSE;
  3411. // Read and parse the local directory entry.
  3412. cur_file_ofs = file_stat.m_local_header_ofs;
  3413. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  3414. return MZ_FALSE;
  3415. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  3416. return MZ_FALSE;
  3417. cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  3418. if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size)
  3419. return MZ_FALSE;
  3420. // Decompress the file either directly from memory or from a file input buffer.
  3421. if (pZip->m_pState->m_pMem)
  3422. {
  3423. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs;
  3424. read_buf_size = read_buf_avail = file_stat.m_comp_size;
  3425. comp_remaining = 0;
  3426. }
  3427. else
  3428. {
  3429. read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE);
  3430. if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size)))
  3431. return MZ_FALSE;
  3432. read_buf_avail = 0;
  3433. comp_remaining = file_stat.m_comp_size;
  3434. }
  3435. if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method))
  3436. {
  3437. // The file is stored or the caller has requested the compressed data.
  3438. if (pZip->m_pState->m_pMem)
  3439. {
  3440. #ifdef _MSC_VER
  3441. if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF))
  3442. #else
  3443. if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF))
  3444. #endif
  3445. return MZ_FALSE;
  3446. if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size)
  3447. status = TINFL_STATUS_FAILED;
  3448. else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  3449. file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size);
  3450. cur_file_ofs += file_stat.m_comp_size;
  3451. out_buf_ofs += file_stat.m_comp_size;
  3452. comp_remaining = 0;
  3453. }
  3454. else
  3455. {
  3456. while (comp_remaining)
  3457. {
  3458. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  3459. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)
  3460. {
  3461. status = TINFL_STATUS_FAILED;
  3462. break;
  3463. }
  3464. if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  3465. file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail);
  3466. if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)
  3467. {
  3468. status = TINFL_STATUS_FAILED;
  3469. break;
  3470. }
  3471. cur_file_ofs += read_buf_avail;
  3472. out_buf_ofs += read_buf_avail;
  3473. comp_remaining -= read_buf_avail;
  3474. }
  3475. }
  3476. }
  3477. else
  3478. {
  3479. tinfl_decompressor inflator;
  3480. tinfl_init(&inflator);
  3481. if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE)))
  3482. status = TINFL_STATUS_FAILED;
  3483. else
  3484. {
  3485. do
  3486. {
  3487. mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
  3488. size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1));
  3489. if ((!read_buf_avail) && (!pZip->m_pState->m_pMem))
  3490. {
  3491. read_buf_avail = MZ_MIN(read_buf_size, comp_remaining);
  3492. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail)
  3493. {
  3494. status = TINFL_STATUS_FAILED;
  3495. break;
  3496. }
  3497. cur_file_ofs += read_buf_avail;
  3498. comp_remaining -= read_buf_avail;
  3499. read_buf_ofs = 0;
  3500. }
  3501. in_buf_size = (size_t)read_buf_avail;
  3502. status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0);
  3503. read_buf_avail -= in_buf_size;
  3504. read_buf_ofs += in_buf_size;
  3505. if (out_buf_size)
  3506. {
  3507. if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size)
  3508. {
  3509. status = TINFL_STATUS_FAILED;
  3510. break;
  3511. }
  3512. file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size);
  3513. if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size)
  3514. {
  3515. status = TINFL_STATUS_FAILED;
  3516. break;
  3517. }
  3518. }
  3519. } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT));
  3520. }
  3521. }
  3522. if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)))
  3523. {
  3524. // Make sure the entire file was decompressed, and check its CRC.
  3525. if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32))
  3526. status = TINFL_STATUS_FAILED;
  3527. }
  3528. if (!pZip->m_pState->m_pMem)
  3529. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  3530. if (pWrite_buf)
  3531. pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf);
  3532. return status == TINFL_STATUS_DONE;
  3533. }
  3534. mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags)
  3535. {
  3536. int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags);
  3537. if (file_index < 0)
  3538. return MZ_FALSE;
  3539. return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags);
  3540. }
  3541. #ifndef MINIZ_NO_STDIO
  3542. static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n)
  3543. {
  3544. (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE*)pOpaque);
  3545. }
  3546. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags)
  3547. {
  3548. mz_bool status;
  3549. mz_zip_archive_file_stat file_stat;
  3550. MZ_FILE *pFile;
  3551. if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat))
  3552. return MZ_FALSE;
  3553. pFile = MZ_FOPEN(pDst_filename, "wb");
  3554. if (!pFile)
  3555. return MZ_FALSE;
  3556. status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags);
  3557. if (MZ_FCLOSE(pFile) == EOF)
  3558. return MZ_FALSE;
  3559. #ifndef MINIZ_NO_TIME
  3560. if (status)
  3561. mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time);
  3562. #endif
  3563. return status;
  3564. }
  3565. #endif // #ifndef MINIZ_NO_STDIO
  3566. mz_bool mz_zip_reader_end(mz_zip_archive *pZip)
  3567. {
  3568. if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  3569. return MZ_FALSE;
  3570. if (pZip->m_pState)
  3571. {
  3572. mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL;
  3573. mz_zip_array_clear(pZip, &pState->m_central_dir);
  3574. mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
  3575. mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
  3576. #ifndef MINIZ_NO_STDIO
  3577. if (pState->m_pFile)
  3578. {
  3579. MZ_FCLOSE(pState->m_pFile);
  3580. pState->m_pFile = NULL;
  3581. }
  3582. #endif // #ifndef MINIZ_NO_STDIO
  3583. pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
  3584. }
  3585. pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
  3586. return MZ_TRUE;
  3587. }
  3588. #ifndef MINIZ_NO_STDIO
  3589. mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags)
  3590. {
  3591. int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags);
  3592. if (file_index < 0)
  3593. return MZ_FALSE;
  3594. return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags);
  3595. }
  3596. #endif
  3597. // ------------------- .ZIP archive writing
  3598. #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  3599. static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); }
  3600. static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); }
  3601. #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v))
  3602. #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v))
  3603. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size)
  3604. {
  3605. if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID))
  3606. return MZ_FALSE;
  3607. if (pZip->m_file_offset_alignment)
  3608. {
  3609. // Ensure user specified file offset alignment is a power of 2.
  3610. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1))
  3611. return MZ_FALSE;
  3612. }
  3613. if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func;
  3614. if (!pZip->m_pFree) pZip->m_pFree = def_free_func;
  3615. if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func;
  3616. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
  3617. pZip->m_archive_size = existing_size;
  3618. pZip->m_central_directory_file_ofs = 0;
  3619. pZip->m_total_files = 0;
  3620. if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state))))
  3621. return MZ_FALSE;
  3622. memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state));
  3623. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8));
  3624. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32));
  3625. MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32));
  3626. return MZ_TRUE;
  3627. }
  3628. static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n)
  3629. {
  3630. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  3631. mz_zip_internal_state *pState = pZip->m_pState;
  3632. mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size);
  3633. #ifdef _MSC_VER
  3634. if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
  3635. #else
  3636. if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)))
  3637. #endif
  3638. return 0;
  3639. if (new_size > pState->m_mem_capacity)
  3640. {
  3641. void *pNew_block;
  3642. size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2;
  3643. if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity)))
  3644. return 0;
  3645. pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity;
  3646. }
  3647. memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n);
  3648. pState->m_mem_size = (size_t)new_size;
  3649. return n;
  3650. }
  3651. mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size)
  3652. {
  3653. pZip->m_pWrite = mz_zip_heap_write_func;
  3654. pZip->m_pIO_opaque = pZip;
  3655. if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning))
  3656. return MZ_FALSE;
  3657. if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning)))
  3658. {
  3659. if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size)))
  3660. {
  3661. mz_zip_writer_end(pZip);
  3662. return MZ_FALSE;
  3663. }
  3664. pZip->m_pState->m_mem_capacity = initial_allocation_size;
  3665. }
  3666. return MZ_TRUE;
  3667. }
  3668. #ifndef MINIZ_NO_STDIO
  3669. static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n)
  3670. {
  3671. mz_zip_archive *pZip = (mz_zip_archive *)pOpaque;
  3672. mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile);
  3673. if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET))))
  3674. return 0;
  3675. return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile);
  3676. }
  3677. mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning)
  3678. {
  3679. MZ_FILE *pFile;
  3680. pZip->m_pWrite = mz_zip_file_write_func;
  3681. pZip->m_pIO_opaque = pZip;
  3682. if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning))
  3683. return MZ_FALSE;
  3684. if (NULL == (pFile = MZ_FOPEN(pFilename, "wb")))
  3685. {
  3686. mz_zip_writer_end(pZip);
  3687. return MZ_FALSE;
  3688. }
  3689. pZip->m_pState->m_pFile = pFile;
  3690. if (size_to_reserve_at_beginning)
  3691. {
  3692. mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_ARR(buf);
  3693. do
  3694. {
  3695. size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning);
  3696. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n)
  3697. {
  3698. mz_zip_writer_end(pZip);
  3699. return MZ_FALSE;
  3700. }
  3701. cur_ofs += n; size_to_reserve_at_beginning -= n;
  3702. } while (size_to_reserve_at_beginning);
  3703. }
  3704. return MZ_TRUE;
  3705. }
  3706. #endif // #ifndef MINIZ_NO_STDIO
  3707. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename)
  3708. {
  3709. mz_zip_internal_state *pState;
  3710. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING))
  3711. return MZ_FALSE;
  3712. // No sense in trying to write to an archive that's already at the support max size
  3713. if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  3714. return MZ_FALSE;
  3715. pState = pZip->m_pState;
  3716. if (pState->m_pFile)
  3717. {
  3718. #ifdef MINIZ_NO_STDIO
  3719. pFilename; return MZ_FALSE;
  3720. #else
  3721. // Archive is being read from stdio - try to reopen as writable.
  3722. if (pZip->m_pIO_opaque != pZip)
  3723. return MZ_FALSE;
  3724. if (!pFilename)
  3725. return MZ_FALSE;
  3726. pZip->m_pWrite = mz_zip_file_write_func;
  3727. if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile)))
  3728. {
  3729. // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it.
  3730. mz_zip_reader_end(pZip);
  3731. return MZ_FALSE;
  3732. }
  3733. #endif // #ifdef MINIZ_NO_STDIO
  3734. }
  3735. else if (pState->m_pMem)
  3736. {
  3737. // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback.
  3738. if (pZip->m_pIO_opaque != pZip)
  3739. return MZ_FALSE;
  3740. pState->m_mem_capacity = pState->m_mem_size;
  3741. pZip->m_pWrite = mz_zip_heap_write_func;
  3742. }
  3743. // Archive is being read via a user provided read function - make sure the user has specified a write function too.
  3744. else if (!pZip->m_pWrite)
  3745. return MZ_FALSE;
  3746. // Start writing new files at the archive's current central directory location.
  3747. pZip->m_archive_size = pZip->m_central_directory_file_ofs;
  3748. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING;
  3749. pZip->m_central_directory_file_ofs = 0;
  3750. return MZ_TRUE;
  3751. }
  3752. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags)
  3753. {
  3754. return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0);
  3755. }
  3756. typedef struct
  3757. {
  3758. mz_zip_archive *m_pZip;
  3759. mz_uint64 m_cur_archive_file_ofs;
  3760. mz_uint64 m_comp_size;
  3761. } mz_zip_writer_add_state;
  3762. static mz_bool mz_zip_writer_add_put_buf_callback(const void* pBuf, int len, void *pUser)
  3763. {
  3764. mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser;
  3765. if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len)
  3766. return MZ_FALSE;
  3767. pState->m_cur_archive_file_ofs += len;
  3768. pState->m_comp_size += len;
  3769. return MZ_TRUE;
  3770. }
  3771. static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date)
  3772. {
  3773. (void)pZip;
  3774. memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE);
  3775. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG);
  3776. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0);
  3777. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags);
  3778. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method);
  3779. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time);
  3780. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date);
  3781. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32);
  3782. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size);
  3783. MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
  3784. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size);
  3785. MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size);
  3786. return MZ_TRUE;
  3787. }
  3788. static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes)
  3789. {
  3790. (void)pZip;
  3791. memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
  3792. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG);
  3793. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0);
  3794. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags);
  3795. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method);
  3796. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time);
  3797. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date);
  3798. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32);
  3799. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size);
  3800. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size);
  3801. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size);
  3802. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size);
  3803. MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size);
  3804. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes);
  3805. MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs);
  3806. return MZ_TRUE;
  3807. }
  3808. static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes)
  3809. {
  3810. mz_zip_internal_state *pState = pZip->m_pState;
  3811. mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size;
  3812. size_t orig_central_dir_size = pState->m_central_dir.m_size;
  3813. mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
  3814. // No zip64 support yet
  3815. if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF))
  3816. return MZ_FALSE;
  3817. if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes))
  3818. return MZ_FALSE;
  3819. if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) ||
  3820. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) ||
  3821. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) ||
  3822. (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) ||
  3823. (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1)))
  3824. {
  3825. // Try to push the central directory array back into its original state.
  3826. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);
  3827. return MZ_FALSE;
  3828. }
  3829. return MZ_TRUE;
  3830. }
  3831. static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name)
  3832. {
  3833. // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes.
  3834. if (*pArchive_name == '/')
  3835. return MZ_FALSE;
  3836. while (*pArchive_name)
  3837. {
  3838. if ((*pArchive_name == '\\') || (*pArchive_name == ':'))
  3839. return MZ_FALSE;
  3840. pArchive_name++;
  3841. }
  3842. return MZ_TRUE;
  3843. }
  3844. static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip)
  3845. {
  3846. mz_uint32 n;
  3847. if (!pZip->m_file_offset_alignment)
  3848. return 0;
  3849. n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1));
  3850. return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1);
  3851. }
  3852. static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n)
  3853. {
  3854. char buf[4096];
  3855. memset(buf, 0, MZ_MIN(sizeof(buf), n));
  3856. while (n)
  3857. {
  3858. mz_uint32 s = MZ_MIN(sizeof(buf), n);
  3859. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s)
  3860. return MZ_FALSE;
  3861. cur_file_ofs += s; n -= s;
  3862. }
  3863. return MZ_TRUE;
  3864. }
  3865. mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32)
  3866. {
  3867. mz_uint16 method = 0, dos_time = 0, dos_date = 0;
  3868. mz_uint level, ext_attributes = 0, num_alignment_padding_bytes;
  3869. mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0;
  3870. size_t archive_name_size;
  3871. mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
  3872. tdefl_compressor *pComp = NULL;
  3873. mz_bool store_data_uncompressed;
  3874. mz_zip_internal_state *pState;
  3875. if ((int)level_and_flags < 0)
  3876. level_and_flags = MZ_DEFAULT_LEVEL;
  3877. level = level_and_flags & 0xF;
  3878. store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA));
  3879. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION))
  3880. return MZ_FALSE;
  3881. pState = pZip->m_pState;
  3882. if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size))
  3883. return MZ_FALSE;
  3884. // No zip64 support yet
  3885. if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF))
  3886. return MZ_FALSE;
  3887. if (!mz_zip_writer_validate_archive_name(pArchive_name))
  3888. return MZ_FALSE;
  3889. #ifndef MINIZ_NO_TIME
  3890. {
  3891. time_t cur_time; time(&cur_time);
  3892. mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date);
  3893. }
  3894. #endif // #ifndef MINIZ_NO_TIME
  3895. archive_name_size = strlen(pArchive_name);
  3896. if (archive_name_size > 0xFFFF)
  3897. return MZ_FALSE;
  3898. num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  3899. // no zip64 support yet
  3900. if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF))
  3901. return MZ_FALSE;
  3902. if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/'))
  3903. {
  3904. // Set DOS Subdirectory attribute bit.
  3905. ext_attributes |= 0x10;
  3906. // Subdirectories cannot contain data.
  3907. if ((buf_size) || (uncomp_size))
  3908. return MZ_FALSE;
  3909. }
  3910. // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.)
  3911. if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1)))
  3912. return MZ_FALSE;
  3913. if ((!store_data_uncompressed) && (buf_size))
  3914. {
  3915. if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor))))
  3916. return MZ_FALSE;
  3917. }
  3918. if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header)))
  3919. {
  3920. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  3921. return MZ_FALSE;
  3922. }
  3923. local_dir_header_ofs += num_alignment_padding_bytes;
  3924. if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); }
  3925. cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header);
  3926. MZ_CLEAR_ARR(local_dir_header);
  3927. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size)
  3928. {
  3929. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  3930. return MZ_FALSE;
  3931. }
  3932. cur_archive_file_ofs += archive_name_size;
  3933. if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))
  3934. {
  3935. uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, buf_size);
  3936. uncomp_size = buf_size;
  3937. if (uncomp_size <= 3)
  3938. {
  3939. level = 0;
  3940. store_data_uncompressed = MZ_TRUE;
  3941. }
  3942. }
  3943. if (store_data_uncompressed)
  3944. {
  3945. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size)
  3946. {
  3947. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  3948. return MZ_FALSE;
  3949. }
  3950. cur_archive_file_ofs += buf_size;
  3951. comp_size = buf_size;
  3952. if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)
  3953. method = MZ_DEFLATED;
  3954. }
  3955. else if (buf_size)
  3956. {
  3957. mz_zip_writer_add_state state;
  3958. state.m_pZip = pZip;
  3959. state.m_cur_archive_file_ofs = cur_archive_file_ofs;
  3960. state.m_comp_size = 0;
  3961. if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) ||
  3962. (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE))
  3963. {
  3964. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  3965. return MZ_FALSE;
  3966. }
  3967. comp_size = state.m_comp_size;
  3968. cur_archive_file_ofs = state.m_cur_archive_file_ofs;
  3969. method = MZ_DEFLATED;
  3970. }
  3971. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  3972. pComp = NULL;
  3973. // no zip64 support yet
  3974. if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
  3975. return MZ_FALSE;
  3976. if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
  3977. return MZ_FALSE;
  3978. if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header))
  3979. return MZ_FALSE;
  3980. if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes))
  3981. return MZ_FALSE;
  3982. pZip->m_total_files++;
  3983. pZip->m_archive_size = cur_archive_file_ofs;
  3984. return MZ_TRUE;
  3985. }
  3986. #ifndef MINIZ_NO_STDIO
  3987. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags)
  3988. {
  3989. mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes;
  3990. mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0;
  3991. mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0;
  3992. size_t archive_name_size;
  3993. mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE];
  3994. MZ_FILE *pSrc_file = NULL;
  3995. if ((int)level_and_flags < 0)
  3996. level_and_flags = MZ_DEFAULT_LEVEL;
  3997. level = level_and_flags & 0xF;
  3998. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION))
  3999. return MZ_FALSE;
  4000. if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)
  4001. return MZ_FALSE;
  4002. if (!mz_zip_writer_validate_archive_name(pArchive_name))
  4003. return MZ_FALSE;
  4004. archive_name_size = strlen(pArchive_name);
  4005. if (archive_name_size > 0xFFFF)
  4006. return MZ_FALSE;
  4007. num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  4008. // no zip64 support yet
  4009. if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF))
  4010. return MZ_FALSE;
  4011. if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date))
  4012. return MZ_FALSE;
  4013. pSrc_file = MZ_FOPEN(pSrc_filename, "rb");
  4014. if (!pSrc_file)
  4015. return MZ_FALSE;
  4016. MZ_FSEEK64(pSrc_file, 0, SEEK_END);
  4017. uncomp_size = MZ_FTELL64(pSrc_file);
  4018. MZ_FSEEK64(pSrc_file, 0, SEEK_SET);
  4019. if (uncomp_size > 0xFFFFFFFF)
  4020. {
  4021. // No zip64 support yet
  4022. MZ_FCLOSE(pSrc_file);
  4023. return MZ_FALSE;
  4024. }
  4025. if (uncomp_size <= 3)
  4026. level = 0;
  4027. if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header)))
  4028. {
  4029. MZ_FCLOSE(pSrc_file);
  4030. return MZ_FALSE;
  4031. }
  4032. local_dir_header_ofs += num_alignment_padding_bytes;
  4033. if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); }
  4034. cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header);
  4035. MZ_CLEAR_ARR(local_dir_header);
  4036. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size)
  4037. {
  4038. MZ_FCLOSE(pSrc_file);
  4039. return MZ_FALSE;
  4040. }
  4041. cur_archive_file_ofs += archive_name_size;
  4042. if (uncomp_size)
  4043. {
  4044. mz_uint64 uncomp_remaining = uncomp_size;
  4045. void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE);
  4046. if (!pRead_buf)
  4047. {
  4048. MZ_FCLOSE(pSrc_file);
  4049. return MZ_FALSE;
  4050. }
  4051. if (!level)
  4052. {
  4053. while (uncomp_remaining)
  4054. {
  4055. mz_uint n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining);
  4056. if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n))
  4057. {
  4058. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  4059. MZ_FCLOSE(pSrc_file);
  4060. return MZ_FALSE;
  4061. }
  4062. uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n);
  4063. uncomp_remaining -= n;
  4064. cur_archive_file_ofs += n;
  4065. }
  4066. comp_size = uncomp_size;
  4067. }
  4068. else
  4069. {
  4070. mz_bool result = MZ_FALSE;
  4071. mz_zip_writer_add_state state;
  4072. tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor));
  4073. if (!pComp)
  4074. {
  4075. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  4076. MZ_FCLOSE(pSrc_file);
  4077. return MZ_FALSE;
  4078. }
  4079. state.m_pZip = pZip;
  4080. state.m_cur_archive_file_ofs = cur_archive_file_ofs;
  4081. state.m_comp_size = 0;
  4082. if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY)
  4083. {
  4084. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  4085. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  4086. MZ_FCLOSE(pSrc_file);
  4087. return MZ_FALSE;
  4088. }
  4089. for ( ; ; )
  4090. {
  4091. size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, MZ_ZIP_MAX_IO_BUF_SIZE);
  4092. tdefl_status status;
  4093. if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size)
  4094. break;
  4095. uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size);
  4096. uncomp_remaining -= in_buf_size;
  4097. status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH);
  4098. if (status == TDEFL_STATUS_DONE)
  4099. {
  4100. result = MZ_TRUE;
  4101. break;
  4102. }
  4103. else if (status != TDEFL_STATUS_OKAY)
  4104. break;
  4105. }
  4106. pZip->m_pFree(pZip->m_pAlloc_opaque, pComp);
  4107. if (!result)
  4108. {
  4109. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  4110. MZ_FCLOSE(pSrc_file);
  4111. return MZ_FALSE;
  4112. }
  4113. comp_size = state.m_comp_size;
  4114. cur_archive_file_ofs = state.m_cur_archive_file_ofs;
  4115. method = MZ_DEFLATED;
  4116. }
  4117. pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf);
  4118. }
  4119. MZ_FCLOSE(pSrc_file); pSrc_file = NULL;
  4120. // no zip64 support yet
  4121. if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF))
  4122. return MZ_FALSE;
  4123. if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date))
  4124. return MZ_FALSE;
  4125. if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header))
  4126. return MZ_FALSE;
  4127. if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes))
  4128. return MZ_FALSE;
  4129. pZip->m_total_files++;
  4130. pZip->m_archive_size = cur_archive_file_ofs;
  4131. return MZ_TRUE;
  4132. }
  4133. #endif // #ifndef MINIZ_NO_STDIO
  4134. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index)
  4135. {
  4136. mz_uint n, bit_flags, num_alignment_padding_bytes;
  4137. mz_uint64 comp_bytes_remaining, local_dir_header_ofs;
  4138. mz_uint64 cur_src_file_ofs, cur_dst_file_ofs;
  4139. mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32;
  4140. mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE];
  4141. size_t orig_central_dir_size;
  4142. mz_zip_internal_state *pState;
  4143. void *pBuf; const mz_uint8 *pSrc_central_header;
  4144. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
  4145. return MZ_FALSE;
  4146. if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index)))
  4147. return MZ_FALSE;
  4148. pState = pZip->m_pState;
  4149. num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip);
  4150. // no zip64 support yet
  4151. if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  4152. return MZ_FALSE;
  4153. cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS);
  4154. cur_dst_file_ofs = pZip->m_archive_size;
  4155. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  4156. return MZ_FALSE;
  4157. if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG)
  4158. return MZ_FALSE;
  4159. cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
  4160. if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes))
  4161. return MZ_FALSE;
  4162. cur_dst_file_ofs += num_alignment_padding_bytes;
  4163. local_dir_header_ofs = cur_dst_file_ofs;
  4164. if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); }
  4165. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE)
  4166. return MZ_FALSE;
  4167. cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE;
  4168. n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS);
  4169. comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS);
  4170. if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining)))))
  4171. return MZ_FALSE;
  4172. while (comp_bytes_remaining)
  4173. {
  4174. n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining);
  4175. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n)
  4176. {
  4177. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4178. return MZ_FALSE;
  4179. }
  4180. cur_src_file_ofs += n;
  4181. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n)
  4182. {
  4183. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4184. return MZ_FALSE;
  4185. }
  4186. cur_dst_file_ofs += n;
  4187. comp_bytes_remaining -= n;
  4188. }
  4189. bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS);
  4190. if (bit_flags & 8)
  4191. {
  4192. // Copy data descriptor
  4193. if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4)
  4194. {
  4195. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4196. return MZ_FALSE;
  4197. }
  4198. n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3);
  4199. if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n)
  4200. {
  4201. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4202. return MZ_FALSE;
  4203. }
  4204. cur_src_file_ofs += n;
  4205. cur_dst_file_ofs += n;
  4206. }
  4207. pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf);
  4208. // no zip64 support yet
  4209. if (cur_dst_file_ofs > 0xFFFFFFFF)
  4210. return MZ_FALSE;
  4211. orig_central_dir_size = pState->m_central_dir.m_size;
  4212. memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE);
  4213. MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs);
  4214. if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE))
  4215. return MZ_FALSE;
  4216. n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS);
  4217. if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n))
  4218. {
  4219. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);
  4220. return MZ_FALSE;
  4221. }
  4222. if (pState->m_central_dir.m_size > 0xFFFFFFFF)
  4223. return MZ_FALSE;
  4224. n = (mz_uint32)orig_central_dir_size;
  4225. if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1))
  4226. {
  4227. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE);
  4228. return MZ_FALSE;
  4229. }
  4230. pZip->m_total_files++;
  4231. pZip->m_archive_size = cur_dst_file_ofs;
  4232. return MZ_TRUE;
  4233. }
  4234. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip)
  4235. {
  4236. mz_zip_internal_state *pState;
  4237. mz_uint64 central_dir_ofs, central_dir_size;
  4238. mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE];
  4239. if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING))
  4240. return MZ_FALSE;
  4241. pState = pZip->m_pState;
  4242. // no zip64 support yet
  4243. if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF))
  4244. return MZ_FALSE;
  4245. central_dir_ofs = 0;
  4246. central_dir_size = 0;
  4247. if (pZip->m_total_files)
  4248. {
  4249. // Write central directory
  4250. central_dir_ofs = pZip->m_archive_size;
  4251. central_dir_size = pState->m_central_dir.m_size;
  4252. pZip->m_central_directory_file_ofs = central_dir_ofs;
  4253. if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size)
  4254. return MZ_FALSE;
  4255. pZip->m_archive_size += central_dir_size;
  4256. }
  4257. // Write end of central directory record
  4258. MZ_CLEAR_ARR(hdr);
  4259. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG);
  4260. MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files);
  4261. MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files);
  4262. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size);
  4263. MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs);
  4264. if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr))
  4265. return MZ_FALSE;
  4266. #ifndef MINIZ_NO_STDIO
  4267. if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF))
  4268. return MZ_FALSE;
  4269. #endif // #ifndef MINIZ_NO_STDIO
  4270. pZip->m_archive_size += sizeof(hdr);
  4271. pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED;
  4272. return MZ_TRUE;
  4273. }
  4274. mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize)
  4275. {
  4276. if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize))
  4277. return MZ_FALSE;
  4278. if (pZip->m_pWrite != mz_zip_heap_write_func)
  4279. return MZ_FALSE;
  4280. if (!mz_zip_writer_finalize_archive(pZip))
  4281. return MZ_FALSE;
  4282. *pBuf = pZip->m_pState->m_pMem;
  4283. *pSize = pZip->m_pState->m_mem_size;
  4284. pZip->m_pState->m_pMem = NULL;
  4285. pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0;
  4286. return MZ_TRUE;
  4287. }
  4288. mz_bool mz_zip_writer_end(mz_zip_archive *pZip)
  4289. {
  4290. mz_zip_internal_state *pState;
  4291. mz_bool status = MZ_TRUE;
  4292. if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)))
  4293. return MZ_FALSE;
  4294. pState = pZip->m_pState;
  4295. pZip->m_pState = NULL;
  4296. mz_zip_array_clear(pZip, &pState->m_central_dir);
  4297. mz_zip_array_clear(pZip, &pState->m_central_dir_offsets);
  4298. mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets);
  4299. #ifndef MINIZ_NO_STDIO
  4300. if (pState->m_pFile)
  4301. {
  4302. MZ_FCLOSE(pState->m_pFile);
  4303. pState->m_pFile = NULL;
  4304. }
  4305. #endif // #ifndef MINIZ_NO_STDIO
  4306. if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem))
  4307. {
  4308. pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem);
  4309. pState->m_pMem = NULL;
  4310. }
  4311. pZip->m_pFree(pZip->m_pAlloc_opaque, pState);
  4312. pZip->m_zip_mode = MZ_ZIP_MODE_INVALID;
  4313. return status;
  4314. }
  4315. #ifndef MINIZ_NO_STDIO
  4316. mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags)
  4317. {
  4318. mz_bool status, created_new_archive = MZ_FALSE;
  4319. mz_zip_archive zip_archive;
  4320. struct MZ_FILE_STAT_STRUCT file_stat;
  4321. MZ_CLEAR_OBJ(zip_archive);
  4322. if ((int)level_and_flags < 0)
  4323. level_and_flags = MZ_DEFAULT_LEVEL;
  4324. if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION))
  4325. return MZ_FALSE;
  4326. if (!mz_zip_writer_validate_archive_name(pArchive_name))
  4327. return MZ_FALSE;
  4328. if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0)
  4329. {
  4330. // Create a new archive.
  4331. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0))
  4332. return MZ_FALSE;
  4333. created_new_archive = MZ_TRUE;
  4334. }
  4335. else
  4336. {
  4337. // Append to an existing archive.
  4338. if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
  4339. return MZ_FALSE;
  4340. if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename))
  4341. {
  4342. mz_zip_reader_end(&zip_archive);
  4343. return MZ_FALSE;
  4344. }
  4345. }
  4346. status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0);
  4347. // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.)
  4348. if (!mz_zip_writer_finalize_archive(&zip_archive))
  4349. status = MZ_FALSE;
  4350. if (!mz_zip_writer_end(&zip_archive))
  4351. status = MZ_FALSE;
  4352. if ((!status) && (created_new_archive))
  4353. {
  4354. // It's a new archive and something went wrong, so just delete it.
  4355. int ignoredStatus = MZ_DELETE_FILE(pZip_filename);
  4356. (void)ignoredStatus;
  4357. }
  4358. return status;
  4359. }
  4360. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags)
  4361. {
  4362. int file_index;
  4363. mz_zip_archive zip_archive;
  4364. void *p = NULL;
  4365. if (pSize)
  4366. *pSize = 0;
  4367. if ((!pZip_filename) || (!pArchive_name))
  4368. return NULL;
  4369. MZ_CLEAR_OBJ(zip_archive);
  4370. if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY))
  4371. return NULL;
  4372. if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0)
  4373. p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags);
  4374. mz_zip_reader_end(&zip_archive);
  4375. return p;
  4376. }
  4377. #endif // #ifndef MINIZ_NO_STDIO
  4378. #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS
  4379. #endif // #ifndef MINIZ_NO_ARCHIVE_APIS
  4380. #ifdef __cplusplus
  4381. }
  4382. #endif
  4383. #ifdef _MSC_VER
  4384. #pragma warning (pop)
  4385. #endif
  4386. #endif // MINIZ_HEADER_FILE_ONLY
  4387. /*
  4388. This is free and unencumbered software released into the public domain.
  4389. Anyone is free to copy, modify, publish, use, compile, sell, or
  4390. distribute this software, either in source code form or as a compiled
  4391. binary, for any purpose, commercial or non-commercial, and by any
  4392. means.
  4393. In jurisdictions that recognize copyright laws, the author or authors
  4394. of this software dedicate any and all copyright interest in the
  4395. software to the public domain. We make this dedication for the benefit
  4396. of the public at large and to the detriment of our heirs and
  4397. successors. We intend this dedication to be an overt act of
  4398. relinquishment in perpetuity of all present and future rights to this
  4399. software under copyright law.
  4400. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  4401. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4402. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  4403. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  4404. OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  4405. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  4406. OTHER DEALINGS IN THE SOFTWARE.
  4407. For more information, please refer to <http://unlicense.org/>
  4408. */