zstd_v07.c 180 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502
  1. /*
  2. * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. /*- Dependencies -*/
  11. #include <stddef.h> /* size_t, ptrdiff_t */
  12. #include <string.h> /* memcpy */
  13. #include <stdlib.h> /* malloc, free, qsort */
  14. #ifndef XXH_STATIC_LINKING_ONLY
  15. # define XXH_STATIC_LINKING_ONLY /* XXH64_state_t */
  16. #endif
  17. #include "xxhash.h" /* XXH64_* */
  18. #include "zstd_v07.h"
  19. #define FSEv07_STATIC_LINKING_ONLY /* FSEv07_MIN_TABLELOG */
  20. #define HUFv07_STATIC_LINKING_ONLY /* HUFv07_TABLELOG_ABSOLUTEMAX */
  21. #define ZSTDv07_STATIC_LINKING_ONLY
  22. #include "error_private.h"
  23. #ifdef ZSTDv07_STATIC_LINKING_ONLY
  24. /* ====================================================================================
  25. * The definitions in this section are considered experimental.
  26. * They should never be used with a dynamic library, as they may change in the future.
  27. * They are provided for advanced usages.
  28. * Use them only in association with static linking.
  29. * ==================================================================================== */
  30. /*--- Constants ---*/
  31. #define ZSTDv07_MAGIC_SKIPPABLE_START 0x184D2A50U
  32. #define ZSTDv07_WINDOWLOG_MAX_32 25
  33. #define ZSTDv07_WINDOWLOG_MAX_64 27
  34. #define ZSTDv07_WINDOWLOG_MAX ((U32)(MEM_32bits() ? ZSTDv07_WINDOWLOG_MAX_32 : ZSTDv07_WINDOWLOG_MAX_64))
  35. #define ZSTDv07_WINDOWLOG_MIN 18
  36. #define ZSTDv07_CHAINLOG_MAX (ZSTDv07_WINDOWLOG_MAX+1)
  37. #define ZSTDv07_CHAINLOG_MIN 4
  38. #define ZSTDv07_HASHLOG_MAX ZSTDv07_WINDOWLOG_MAX
  39. #define ZSTDv07_HASHLOG_MIN 12
  40. #define ZSTDv07_HASHLOG3_MAX 17
  41. #define ZSTDv07_SEARCHLOG_MAX (ZSTDv07_WINDOWLOG_MAX-1)
  42. #define ZSTDv07_SEARCHLOG_MIN 1
  43. #define ZSTDv07_SEARCHLENGTH_MAX 7
  44. #define ZSTDv07_SEARCHLENGTH_MIN 3
  45. #define ZSTDv07_TARGETLENGTH_MIN 4
  46. #define ZSTDv07_TARGETLENGTH_MAX 999
  47. #define ZSTDv07_FRAMEHEADERSIZE_MAX 18 /* for static allocation */
  48. static const size_t ZSTDv07_frameHeaderSize_min = 5;
  49. static const size_t ZSTDv07_frameHeaderSize_max = ZSTDv07_FRAMEHEADERSIZE_MAX;
  50. static const size_t ZSTDv07_skippableHeaderSize = 8; /* magic number + skippable frame length */
  51. /* custom memory allocation functions */
  52. typedef void* (*ZSTDv07_allocFunction) (void* opaque, size_t size);
  53. typedef void (*ZSTDv07_freeFunction) (void* opaque, void* address);
  54. typedef struct { ZSTDv07_allocFunction customAlloc; ZSTDv07_freeFunction customFree; void* opaque; } ZSTDv07_customMem;
  55. /*--- Advanced Decompression functions ---*/
  56. /*! ZSTDv07_estimateDCtxSize() :
  57. * Gives the potential amount of memory allocated to create a ZSTDv07_DCtx */
  58. ZSTDLIBv07_API size_t ZSTDv07_estimateDCtxSize(void);
  59. /*! ZSTDv07_createDCtx_advanced() :
  60. * Create a ZSTD decompression context using external alloc and free functions */
  61. ZSTDLIBv07_API ZSTDv07_DCtx* ZSTDv07_createDCtx_advanced(ZSTDv07_customMem customMem);
  62. /*! ZSTDv07_sizeofDCtx() :
  63. * Gives the amount of memory used by a given ZSTDv07_DCtx */
  64. ZSTDLIBv07_API size_t ZSTDv07_sizeofDCtx(const ZSTDv07_DCtx* dctx);
  65. /* ******************************************************************
  66. * Buffer-less streaming functions (synchronous mode)
  67. ********************************************************************/
  68. ZSTDLIBv07_API size_t ZSTDv07_decompressBegin(ZSTDv07_DCtx* dctx);
  69. ZSTDLIBv07_API size_t ZSTDv07_decompressBegin_usingDict(ZSTDv07_DCtx* dctx, const void* dict, size_t dictSize);
  70. ZSTDLIBv07_API void ZSTDv07_copyDCtx(ZSTDv07_DCtx* dctx, const ZSTDv07_DCtx* preparedDCtx);
  71. ZSTDLIBv07_API size_t ZSTDv07_nextSrcSizeToDecompress(ZSTDv07_DCtx* dctx);
  72. ZSTDLIBv07_API size_t ZSTDv07_decompressContinue(ZSTDv07_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
  73. /*
  74. Buffer-less streaming decompression (synchronous mode)
  75. A ZSTDv07_DCtx object is required to track streaming operations.
  76. Use ZSTDv07_createDCtx() / ZSTDv07_freeDCtx() to manage it.
  77. A ZSTDv07_DCtx object can be re-used multiple times.
  78. First optional operation is to retrieve frame parameters, using ZSTDv07_getFrameParams(), which doesn't consume the input.
  79. It can provide the minimum size of rolling buffer required to properly decompress data (`windowSize`),
  80. and optionally the final size of uncompressed content.
  81. (Note : content size is an optional info that may not be present. 0 means : content size unknown)
  82. Frame parameters are extracted from the beginning of compressed frame.
  83. The amount of data to read is variable, from ZSTDv07_frameHeaderSize_min to ZSTDv07_frameHeaderSize_max (so if `srcSize` >= ZSTDv07_frameHeaderSize_max, it will always work)
  84. If `srcSize` is too small for operation to succeed, function will return the minimum size it requires to produce a result.
  85. Result : 0 when successful, it means the ZSTDv07_frameParams structure has been filled.
  86. >0 : means there is not enough data into `src`. Provides the expected size to successfully decode header.
  87. errorCode, which can be tested using ZSTDv07_isError()
  88. Start decompression, with ZSTDv07_decompressBegin() or ZSTDv07_decompressBegin_usingDict().
  89. Alternatively, you can copy a prepared context, using ZSTDv07_copyDCtx().
  90. Then use ZSTDv07_nextSrcSizeToDecompress() and ZSTDv07_decompressContinue() alternatively.
  91. ZSTDv07_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTDv07_decompressContinue().
  92. ZSTDv07_decompressContinue() requires this exact amount of bytes, or it will fail.
  93. @result of ZSTDv07_decompressContinue() is the number of bytes regenerated within 'dst' (necessarily <= dstCapacity).
  94. It can be zero, which is not an error; it just means ZSTDv07_decompressContinue() has decoded some header.
  95. ZSTDv07_decompressContinue() needs previous data blocks during decompression, up to `windowSize`.
  96. They should preferably be located contiguously, prior to current block.
  97. Alternatively, a round buffer of sufficient size is also possible. Sufficient size is determined by frame parameters.
  98. ZSTDv07_decompressContinue() is very sensitive to contiguity,
  99. if 2 blocks don't follow each other, make sure that either the compressor breaks contiguity at the same place,
  100. or that previous contiguous segment is large enough to properly handle maximum back-reference.
  101. A frame is fully decoded when ZSTDv07_nextSrcSizeToDecompress() returns zero.
  102. Context can then be reset to start a new decompression.
  103. == Special case : skippable frames ==
  104. Skippable frames allow the integration of user-defined data into a flow of concatenated frames.
  105. Skippable frames will be ignored (skipped) by a decompressor. The format of skippable frame is following:
  106. a) Skippable frame ID - 4 Bytes, Little endian format, any value from 0x184D2A50 to 0x184D2A5F
  107. b) Frame Size - 4 Bytes, Little endian format, unsigned 32-bits
  108. c) Frame Content - any content (User Data) of length equal to Frame Size
  109. For skippable frames ZSTDv07_decompressContinue() always returns 0.
  110. For skippable frames ZSTDv07_getFrameParams() returns fparamsPtr->windowLog==0 what means that a frame is skippable.
  111. It also returns Frame Size as fparamsPtr->frameContentSize.
  112. */
  113. /* **************************************
  114. * Block functions
  115. ****************************************/
  116. /*! Block functions produce and decode raw zstd blocks, without frame metadata.
  117. Frame metadata cost is typically ~18 bytes, which can be non-negligible for very small blocks (< 100 bytes).
  118. User will have to take in charge required information to regenerate data, such as compressed and content sizes.
  119. A few rules to respect :
  120. - Compressing and decompressing require a context structure
  121. + Use ZSTDv07_createCCtx() and ZSTDv07_createDCtx()
  122. - It is necessary to init context before starting
  123. + compression : ZSTDv07_compressBegin()
  124. + decompression : ZSTDv07_decompressBegin()
  125. + variants _usingDict() are also allowed
  126. + copyCCtx() and copyDCtx() work too
  127. - Block size is limited, it must be <= ZSTDv07_getBlockSizeMax()
  128. + If you need to compress more, cut data into multiple blocks
  129. + Consider using the regular ZSTDv07_compress() instead, as frame metadata costs become negligible when source size is large.
  130. - When a block is considered not compressible enough, ZSTDv07_compressBlock() result will be zero.
  131. In which case, nothing is produced into `dst`.
  132. + User must test for such outcome and deal directly with uncompressed data
  133. + ZSTDv07_decompressBlock() doesn't accept uncompressed data as input !!!
  134. + In case of multiple successive blocks, decoder must be informed of uncompressed block existence to follow proper history.
  135. Use ZSTDv07_insertBlock() in such a case.
  136. */
  137. #define ZSTDv07_BLOCKSIZE_ABSOLUTEMAX (128 * 1024) /* define, for static allocation */
  138. ZSTDLIBv07_API size_t ZSTDv07_decompressBlock(ZSTDv07_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize);
  139. ZSTDLIBv07_API size_t ZSTDv07_insertBlock(ZSTDv07_DCtx* dctx, const void* blockStart, size_t blockSize); /**< insert block into `dctx` history. Useful for uncompressed blocks */
  140. #endif /* ZSTDv07_STATIC_LINKING_ONLY */
  141. /* ******************************************************************
  142. mem.h
  143. low-level memory access routines
  144. Copyright (C) 2013-2015, Yann Collet.
  145. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  146. Redistribution and use in source and binary forms, with or without
  147. modification, are permitted provided that the following conditions are
  148. met:
  149. * Redistributions of source code must retain the above copyright
  150. notice, this list of conditions and the following disclaimer.
  151. * Redistributions in binary form must reproduce the above
  152. copyright notice, this list of conditions and the following disclaimer
  153. in the documentation and/or other materials provided with the
  154. distribution.
  155. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  156. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  157. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  158. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  159. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  160. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  161. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  162. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  163. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  164. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  165. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  166. You can contact the author at :
  167. - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
  168. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  169. ****************************************************************** */
  170. #ifndef MEM_H_MODULE
  171. #define MEM_H_MODULE
  172. #if defined (__cplusplus)
  173. extern "C" {
  174. #endif
  175. /*-****************************************
  176. * Compiler specifics
  177. ******************************************/
  178. #if defined(_MSC_VER) /* Visual Studio */
  179. # include <stdlib.h> /* _byteswap_ulong */
  180. # include <intrin.h> /* _byteswap_* */
  181. #endif
  182. #if defined(__GNUC__)
  183. # define MEM_STATIC static __attribute__((unused))
  184. #elif defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  185. # define MEM_STATIC static inline
  186. #elif defined(_MSC_VER)
  187. # define MEM_STATIC static __inline
  188. #else
  189. # define MEM_STATIC static /* this version may generate warnings for unused static functions; disable the relevant warning */
  190. #endif
  191. /*-**************************************************************
  192. * Basic Types
  193. *****************************************************************/
  194. #if !defined (__VMS) && (defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */) )
  195. # include <stdint.h>
  196. typedef uint8_t BYTE;
  197. typedef uint16_t U16;
  198. typedef int16_t S16;
  199. typedef uint32_t U32;
  200. typedef int32_t S32;
  201. typedef uint64_t U64;
  202. typedef int64_t S64;
  203. #else
  204. typedef unsigned char BYTE;
  205. typedef unsigned short U16;
  206. typedef signed short S16;
  207. typedef unsigned int U32;
  208. typedef signed int S32;
  209. typedef unsigned long long U64;
  210. typedef signed long long S64;
  211. #endif
  212. /*-**************************************************************
  213. * Memory I/O
  214. *****************************************************************/
  215. /* MEM_FORCE_MEMORY_ACCESS :
  216. * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
  217. * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
  218. * The below switch allow to select different access method for improved performance.
  219. * Method 0 (default) : use `memcpy()`. Safe and portable.
  220. * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).
  221. * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
  222. * Method 2 : direct access. This method is portable but violate C standard.
  223. * It can generate buggy code on targets depending on alignment.
  224. * In some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)
  225. * See http://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.
  226. * Prefer these methods in priority order (0 > 1 > 2)
  227. */
  228. #ifndef MEM_FORCE_MEMORY_ACCESS /* can be defined externally, on command line for example */
  229. # if defined(__GNUC__) && ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
  230. # define MEM_FORCE_MEMORY_ACCESS 2
  231. # elif (defined(__INTEL_COMPILER) && !defined(WIN32)) || \
  232. (defined(__GNUC__) && ( defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) ))
  233. # define MEM_FORCE_MEMORY_ACCESS 1
  234. # endif
  235. #endif
  236. MEM_STATIC unsigned MEM_32bits(void) { return sizeof(size_t)==4; }
  237. MEM_STATIC unsigned MEM_64bits(void) { return sizeof(size_t)==8; }
  238. MEM_STATIC unsigned MEM_isLittleEndian(void)
  239. {
  240. const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
  241. return one.c[0];
  242. }
  243. #if defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==2)
  244. /* violates C standard, by lying on structure alignment.
  245. Only use if no other choice to achieve best performance on target platform */
  246. MEM_STATIC U16 MEM_read16(const void* memPtr) { return *(const U16*) memPtr; }
  247. MEM_STATIC U32 MEM_read32(const void* memPtr) { return *(const U32*) memPtr; }
  248. MEM_STATIC U64 MEM_read64(const void* memPtr) { return *(const U64*) memPtr; }
  249. MEM_STATIC void MEM_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }
  250. #elif defined(MEM_FORCE_MEMORY_ACCESS) && (MEM_FORCE_MEMORY_ACCESS==1)
  251. /* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
  252. /* currently only defined for gcc and icc */
  253. typedef union { U16 u16; U32 u32; U64 u64; size_t st; } __attribute__((packed)) unalign;
  254. MEM_STATIC U16 MEM_read16(const void* ptr) { return ((const unalign*)ptr)->u16; }
  255. MEM_STATIC U32 MEM_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }
  256. MEM_STATIC U64 MEM_read64(const void* ptr) { return ((const unalign*)ptr)->u64; }
  257. MEM_STATIC void MEM_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; }
  258. #else
  259. /* default method, safe and standard.
  260. can sometimes prove slower */
  261. MEM_STATIC U16 MEM_read16(const void* memPtr)
  262. {
  263. U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
  264. }
  265. MEM_STATIC U32 MEM_read32(const void* memPtr)
  266. {
  267. U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
  268. }
  269. MEM_STATIC U64 MEM_read64(const void* memPtr)
  270. {
  271. U64 val; memcpy(&val, memPtr, sizeof(val)); return val;
  272. }
  273. MEM_STATIC void MEM_write16(void* memPtr, U16 value)
  274. {
  275. memcpy(memPtr, &value, sizeof(value));
  276. }
  277. #endif /* MEM_FORCE_MEMORY_ACCESS */
  278. MEM_STATIC U32 MEM_swap32(U32 in)
  279. {
  280. #if defined(_MSC_VER) /* Visual Studio */
  281. return _byteswap_ulong(in);
  282. #elif defined (__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)
  283. return __builtin_bswap32(in);
  284. #else
  285. return ((in << 24) & 0xff000000 ) |
  286. ((in << 8) & 0x00ff0000 ) |
  287. ((in >> 8) & 0x0000ff00 ) |
  288. ((in >> 24) & 0x000000ff );
  289. #endif
  290. }
  291. MEM_STATIC U64 MEM_swap64(U64 in)
  292. {
  293. #if defined(_MSC_VER) /* Visual Studio */
  294. return _byteswap_uint64(in);
  295. #elif defined (__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)
  296. return __builtin_bswap64(in);
  297. #else
  298. return ((in << 56) & 0xff00000000000000ULL) |
  299. ((in << 40) & 0x00ff000000000000ULL) |
  300. ((in << 24) & 0x0000ff0000000000ULL) |
  301. ((in << 8) & 0x000000ff00000000ULL) |
  302. ((in >> 8) & 0x00000000ff000000ULL) |
  303. ((in >> 24) & 0x0000000000ff0000ULL) |
  304. ((in >> 40) & 0x000000000000ff00ULL) |
  305. ((in >> 56) & 0x00000000000000ffULL);
  306. #endif
  307. }
  308. /*=== Little endian r/w ===*/
  309. MEM_STATIC U16 MEM_readLE16(const void* memPtr)
  310. {
  311. if (MEM_isLittleEndian())
  312. return MEM_read16(memPtr);
  313. else {
  314. const BYTE* p = (const BYTE*)memPtr;
  315. return (U16)(p[0] + (p[1]<<8));
  316. }
  317. }
  318. MEM_STATIC void MEM_writeLE16(void* memPtr, U16 val)
  319. {
  320. if (MEM_isLittleEndian()) {
  321. MEM_write16(memPtr, val);
  322. } else {
  323. BYTE* p = (BYTE*)memPtr;
  324. p[0] = (BYTE)val;
  325. p[1] = (BYTE)(val>>8);
  326. }
  327. }
  328. MEM_STATIC U32 MEM_readLE32(const void* memPtr)
  329. {
  330. if (MEM_isLittleEndian())
  331. return MEM_read32(memPtr);
  332. else
  333. return MEM_swap32(MEM_read32(memPtr));
  334. }
  335. MEM_STATIC U64 MEM_readLE64(const void* memPtr)
  336. {
  337. if (MEM_isLittleEndian())
  338. return MEM_read64(memPtr);
  339. else
  340. return MEM_swap64(MEM_read64(memPtr));
  341. }
  342. MEM_STATIC size_t MEM_readLEST(const void* memPtr)
  343. {
  344. if (MEM_32bits())
  345. return (size_t)MEM_readLE32(memPtr);
  346. else
  347. return (size_t)MEM_readLE64(memPtr);
  348. }
  349. #if defined (__cplusplus)
  350. }
  351. #endif
  352. #endif /* MEM_H_MODULE */
  353. /* ******************************************************************
  354. bitstream
  355. Part of FSE library
  356. header file (to include)
  357. Copyright (C) 2013-2016, Yann Collet.
  358. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  359. Redistribution and use in source and binary forms, with or without
  360. modification, are permitted provided that the following conditions are
  361. met:
  362. * Redistributions of source code must retain the above copyright
  363. notice, this list of conditions and the following disclaimer.
  364. * Redistributions in binary form must reproduce the above
  365. copyright notice, this list of conditions and the following disclaimer
  366. in the documentation and/or other materials provided with the
  367. distribution.
  368. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  369. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  370. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  371. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  372. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  373. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  374. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  375. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  376. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  377. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  378. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  379. You can contact the author at :
  380. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  381. ****************************************************************** */
  382. #ifndef BITSTREAM_H_MODULE
  383. #define BITSTREAM_H_MODULE
  384. #if defined (__cplusplus)
  385. extern "C" {
  386. #endif
  387. /*
  388. * This API consists of small unitary functions, which must be inlined for best performance.
  389. * Since link-time-optimization is not available for all compilers,
  390. * these functions are defined into a .h to be included.
  391. */
  392. /*=========================================
  393. * Target specific
  394. =========================================*/
  395. #if defined(__BMI__) && defined(__GNUC__)
  396. # include <immintrin.h> /* support for bextr (experimental) */
  397. #endif
  398. /*-********************************************
  399. * bitStream decoding API (read backward)
  400. **********************************************/
  401. typedef struct
  402. {
  403. size_t bitContainer;
  404. unsigned bitsConsumed;
  405. const char* ptr;
  406. const char* start;
  407. } BITv07_DStream_t;
  408. typedef enum { BITv07_DStream_unfinished = 0,
  409. BITv07_DStream_endOfBuffer = 1,
  410. BITv07_DStream_completed = 2,
  411. BITv07_DStream_overflow = 3 } BITv07_DStream_status; /* result of BITv07_reloadDStream() */
  412. /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... :( */
  413. MEM_STATIC size_t BITv07_initDStream(BITv07_DStream_t* bitD, const void* srcBuffer, size_t srcSize);
  414. MEM_STATIC size_t BITv07_readBits(BITv07_DStream_t* bitD, unsigned nbBits);
  415. MEM_STATIC BITv07_DStream_status BITv07_reloadDStream(BITv07_DStream_t* bitD);
  416. MEM_STATIC unsigned BITv07_endOfDStream(const BITv07_DStream_t* bitD);
  417. /*-****************************************
  418. * unsafe API
  419. ******************************************/
  420. MEM_STATIC size_t BITv07_readBitsFast(BITv07_DStream_t* bitD, unsigned nbBits);
  421. /* faster, but works only if nbBits >= 1 */
  422. /*-**************************************************************
  423. * Internal functions
  424. ****************************************************************/
  425. MEM_STATIC unsigned BITv07_highbit32 (U32 val)
  426. {
  427. # if defined(_MSC_VER) /* Visual */
  428. unsigned long r=0;
  429. _BitScanReverse ( &r, val );
  430. return (unsigned) r;
  431. # elif defined(__GNUC__) && (__GNUC__ >= 3) /* Use GCC Intrinsic */
  432. return 31 - __builtin_clz (val);
  433. # else /* Software version */
  434. static const unsigned DeBruijnClz[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 };
  435. U32 v = val;
  436. v |= v >> 1;
  437. v |= v >> 2;
  438. v |= v >> 4;
  439. v |= v >> 8;
  440. v |= v >> 16;
  441. return DeBruijnClz[ (U32) (v * 0x07C4ACDDU) >> 27];
  442. # endif
  443. }
  444. /*-********************************************************
  445. * bitStream decoding
  446. **********************************************************/
  447. /*! BITv07_initDStream() :
  448. * Initialize a BITv07_DStream_t.
  449. * `bitD` : a pointer to an already allocated BITv07_DStream_t structure.
  450. * `srcSize` must be the *exact* size of the bitStream, in bytes.
  451. * @return : size of stream (== srcSize) or an errorCode if a problem is detected
  452. */
  453. MEM_STATIC size_t BITv07_initDStream(BITv07_DStream_t* bitD, const void* srcBuffer, size_t srcSize)
  454. {
  455. if (srcSize < 1) { memset(bitD, 0, sizeof(*bitD)); return ERROR(srcSize_wrong); }
  456. if (srcSize >= sizeof(bitD->bitContainer)) { /* normal case */
  457. bitD->start = (const char*)srcBuffer;
  458. bitD->ptr = (const char*)srcBuffer + srcSize - sizeof(bitD->bitContainer);
  459. bitD->bitContainer = MEM_readLEST(bitD->ptr);
  460. { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1];
  461. bitD->bitsConsumed = lastByte ? 8 - BITv07_highbit32(lastByte) : 0;
  462. if (lastByte == 0) return ERROR(GENERIC); /* endMark not present */ }
  463. } else {
  464. bitD->start = (const char*)srcBuffer;
  465. bitD->ptr = bitD->start;
  466. bitD->bitContainer = *(const BYTE*)(bitD->start);
  467. switch(srcSize)
  468. {
  469. case 7: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[6]) << (sizeof(bitD->bitContainer)*8 - 16);/* fall-through */
  470. case 6: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[5]) << (sizeof(bitD->bitContainer)*8 - 24);/* fall-through */
  471. case 5: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[4]) << (sizeof(bitD->bitContainer)*8 - 32);/* fall-through */
  472. case 4: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[3]) << 24; /* fall-through */
  473. case 3: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[2]) << 16; /* fall-through */
  474. case 2: bitD->bitContainer += (size_t)(((const BYTE*)(srcBuffer))[1]) << 8; /* fall-through */
  475. default: break;
  476. }
  477. { BYTE const lastByte = ((const BYTE*)srcBuffer)[srcSize-1];
  478. bitD->bitsConsumed = lastByte ? 8 - BITv07_highbit32(lastByte) : 0;
  479. if (lastByte == 0) return ERROR(GENERIC); /* endMark not present */ }
  480. bitD->bitsConsumed += (U32)(sizeof(bitD->bitContainer) - srcSize)*8;
  481. }
  482. return srcSize;
  483. }
  484. MEM_STATIC size_t BITv07_lookBits(const BITv07_DStream_t* bitD, U32 nbBits)
  485. {
  486. U32 const bitMask = sizeof(bitD->bitContainer)*8 - 1;
  487. return ((bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> 1) >> ((bitMask-nbBits) & bitMask);
  488. }
  489. /*! BITv07_lookBitsFast() :
  490. * unsafe version; only works only if nbBits >= 1 */
  491. MEM_STATIC size_t BITv07_lookBitsFast(const BITv07_DStream_t* bitD, U32 nbBits)
  492. {
  493. U32 const bitMask = sizeof(bitD->bitContainer)*8 - 1;
  494. return (bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> (((bitMask+1)-nbBits) & bitMask);
  495. }
  496. MEM_STATIC void BITv07_skipBits(BITv07_DStream_t* bitD, U32 nbBits)
  497. {
  498. bitD->bitsConsumed += nbBits;
  499. }
  500. MEM_STATIC size_t BITv07_readBits(BITv07_DStream_t* bitD, U32 nbBits)
  501. {
  502. size_t const value = BITv07_lookBits(bitD, nbBits);
  503. BITv07_skipBits(bitD, nbBits);
  504. return value;
  505. }
  506. /*! BITv07_readBitsFast() :
  507. * unsafe version; only works only if nbBits >= 1 */
  508. MEM_STATIC size_t BITv07_readBitsFast(BITv07_DStream_t* bitD, U32 nbBits)
  509. {
  510. size_t const value = BITv07_lookBitsFast(bitD, nbBits);
  511. BITv07_skipBits(bitD, nbBits);
  512. return value;
  513. }
  514. MEM_STATIC BITv07_DStream_status BITv07_reloadDStream(BITv07_DStream_t* bitD)
  515. {
  516. if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8)) /* should not happen => corruption detected */
  517. return BITv07_DStream_overflow;
  518. if (bitD->ptr >= bitD->start + sizeof(bitD->bitContainer)) {
  519. bitD->ptr -= bitD->bitsConsumed >> 3;
  520. bitD->bitsConsumed &= 7;
  521. bitD->bitContainer = MEM_readLEST(bitD->ptr);
  522. return BITv07_DStream_unfinished;
  523. }
  524. if (bitD->ptr == bitD->start) {
  525. if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BITv07_DStream_endOfBuffer;
  526. return BITv07_DStream_completed;
  527. }
  528. { U32 nbBytes = bitD->bitsConsumed >> 3;
  529. BITv07_DStream_status result = BITv07_DStream_unfinished;
  530. if (bitD->ptr - nbBytes < bitD->start) {
  531. nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */
  532. result = BITv07_DStream_endOfBuffer;
  533. }
  534. bitD->ptr -= nbBytes;
  535. bitD->bitsConsumed -= nbBytes*8;
  536. bitD->bitContainer = MEM_readLEST(bitD->ptr); /* reminder : srcSize > sizeof(bitD) */
  537. return result;
  538. }
  539. }
  540. /*! BITv07_endOfDStream() :
  541. * @return Tells if DStream has exactly reached its end (all bits consumed).
  542. */
  543. MEM_STATIC unsigned BITv07_endOfDStream(const BITv07_DStream_t* DStream)
  544. {
  545. return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8));
  546. }
  547. #if defined (__cplusplus)
  548. }
  549. #endif
  550. #endif /* BITSTREAM_H_MODULE */
  551. /* ******************************************************************
  552. FSE : Finite State Entropy codec
  553. Public Prototypes declaration
  554. Copyright (C) 2013-2016, Yann Collet.
  555. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  556. Redistribution and use in source and binary forms, with or without
  557. modification, are permitted provided that the following conditions are
  558. met:
  559. * Redistributions of source code must retain the above copyright
  560. notice, this list of conditions and the following disclaimer.
  561. * Redistributions in binary form must reproduce the above
  562. copyright notice, this list of conditions and the following disclaimer
  563. in the documentation and/or other materials provided with the
  564. distribution.
  565. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  566. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  567. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  568. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  569. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  570. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  571. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  572. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  573. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  574. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  575. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  576. You can contact the author at :
  577. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  578. ****************************************************************** */
  579. #ifndef FSEv07_H
  580. #define FSEv07_H
  581. #if defined (__cplusplus)
  582. extern "C" {
  583. #endif
  584. /*-****************************************
  585. * FSE simple functions
  586. ******************************************/
  587. /*! FSEv07_decompress():
  588. Decompress FSE data from buffer 'cSrc', of size 'cSrcSize',
  589. into already allocated destination buffer 'dst', of size 'dstCapacity'.
  590. @return : size of regenerated data (<= maxDstSize),
  591. or an error code, which can be tested using FSEv07_isError() .
  592. ** Important ** : FSEv07_decompress() does not decompress non-compressible nor RLE data !!!
  593. Why ? : making this distinction requires a header.
  594. Header management is intentionally delegated to the user layer, which can better manage special cases.
  595. */
  596. size_t FSEv07_decompress(void* dst, size_t dstCapacity,
  597. const void* cSrc, size_t cSrcSize);
  598. /* Error Management */
  599. unsigned FSEv07_isError(size_t code); /* tells if a return value is an error code */
  600. const char* FSEv07_getErrorName(size_t code); /* provides error code string (useful for debugging) */
  601. /*-*****************************************
  602. * FSE detailed API
  603. ******************************************/
  604. /*!
  605. FSEv07_decompress() does the following:
  606. 1. read normalized counters with readNCount()
  607. 2. build decoding table 'DTable' from normalized counters
  608. 3. decode the data stream using decoding table 'DTable'
  609. The following API allows targeting specific sub-functions for advanced tasks.
  610. For example, it's possible to compress several blocks using the same 'CTable',
  611. or to save and provide normalized distribution using external method.
  612. */
  613. /* *** DECOMPRESSION *** */
  614. /*! FSEv07_readNCount():
  615. Read compactly saved 'normalizedCounter' from 'rBuffer'.
  616. @return : size read from 'rBuffer',
  617. or an errorCode, which can be tested using FSEv07_isError().
  618. maxSymbolValuePtr[0] and tableLogPtr[0] will also be updated with their respective values */
  619. size_t FSEv07_readNCount (short* normalizedCounter, unsigned* maxSymbolValuePtr, unsigned* tableLogPtr, const void* rBuffer, size_t rBuffSize);
  620. /*! Constructor and Destructor of FSEv07_DTable.
  621. Note that its size depends on 'tableLog' */
  622. typedef unsigned FSEv07_DTable; /* don't allocate that. It's just a way to be more restrictive than void* */
  623. FSEv07_DTable* FSEv07_createDTable(unsigned tableLog);
  624. void FSEv07_freeDTable(FSEv07_DTable* dt);
  625. /*! FSEv07_buildDTable():
  626. Builds 'dt', which must be already allocated, using FSEv07_createDTable().
  627. return : 0, or an errorCode, which can be tested using FSEv07_isError() */
  628. size_t FSEv07_buildDTable (FSEv07_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog);
  629. /*! FSEv07_decompress_usingDTable():
  630. Decompress compressed source `cSrc` of size `cSrcSize` using `dt`
  631. into `dst` which must be already allocated.
  632. @return : size of regenerated data (necessarily <= `dstCapacity`),
  633. or an errorCode, which can be tested using FSEv07_isError() */
  634. size_t FSEv07_decompress_usingDTable(void* dst, size_t dstCapacity, const void* cSrc, size_t cSrcSize, const FSEv07_DTable* dt);
  635. /*!
  636. Tutorial :
  637. ----------
  638. (Note : these functions only decompress FSE-compressed blocks.
  639. If block is uncompressed, use memcpy() instead
  640. If block is a single repeated byte, use memset() instead )
  641. The first step is to obtain the normalized frequencies of symbols.
  642. This can be performed by FSEv07_readNCount() if it was saved using FSEv07_writeNCount().
  643. 'normalizedCounter' must be already allocated, and have at least 'maxSymbolValuePtr[0]+1' cells of signed short.
  644. In practice, that means it's necessary to know 'maxSymbolValue' beforehand,
  645. or size the table to handle worst case situations (typically 256).
  646. FSEv07_readNCount() will provide 'tableLog' and 'maxSymbolValue'.
  647. The result of FSEv07_readNCount() is the number of bytes read from 'rBuffer'.
  648. Note that 'rBufferSize' must be at least 4 bytes, even if useful information is less than that.
  649. If there is an error, the function will return an error code, which can be tested using FSEv07_isError().
  650. The next step is to build the decompression tables 'FSEv07_DTable' from 'normalizedCounter'.
  651. This is performed by the function FSEv07_buildDTable().
  652. The space required by 'FSEv07_DTable' must be already allocated using FSEv07_createDTable().
  653. If there is an error, the function will return an error code, which can be tested using FSEv07_isError().
  654. `FSEv07_DTable` can then be used to decompress `cSrc`, with FSEv07_decompress_usingDTable().
  655. `cSrcSize` must be strictly correct, otherwise decompression will fail.
  656. FSEv07_decompress_usingDTable() result will tell how many bytes were regenerated (<=`dstCapacity`).
  657. If there is an error, the function will return an error code, which can be tested using FSEv07_isError(). (ex: dst buffer too small)
  658. */
  659. #ifdef FSEv07_STATIC_LINKING_ONLY
  660. /* *****************************************
  661. * Static allocation
  662. *******************************************/
  663. /* FSE buffer bounds */
  664. #define FSEv07_NCOUNTBOUND 512
  665. #define FSEv07_BLOCKBOUND(size) (size + (size>>7))
  666. /* It is possible to statically allocate FSE CTable/DTable as a table of unsigned using below macros */
  667. #define FSEv07_DTABLE_SIZE_U32(maxTableLog) (1 + (1<<maxTableLog))
  668. /* *****************************************
  669. * FSE advanced API
  670. *******************************************/
  671. size_t FSEv07_countFast(unsigned* count, unsigned* maxSymbolValuePtr, const void* src, size_t srcSize);
  672. /**< same as FSEv07_count(), but blindly trusts that all byte values within src are <= *maxSymbolValuePtr */
  673. unsigned FSEv07_optimalTableLog_internal(unsigned maxTableLog, size_t srcSize, unsigned maxSymbolValue, unsigned minus);
  674. /**< same as FSEv07_optimalTableLog(), which used `minus==2` */
  675. size_t FSEv07_buildDTable_raw (FSEv07_DTable* dt, unsigned nbBits);
  676. /**< build a fake FSEv07_DTable, designed to read an uncompressed bitstream where each symbol uses nbBits */
  677. size_t FSEv07_buildDTable_rle (FSEv07_DTable* dt, unsigned char symbolValue);
  678. /**< build a fake FSEv07_DTable, designed to always generate the same symbolValue */
  679. /* *****************************************
  680. * FSE symbol decompression API
  681. *******************************************/
  682. typedef struct
  683. {
  684. size_t state;
  685. const void* table; /* precise table may vary, depending on U16 */
  686. } FSEv07_DState_t;
  687. static void FSEv07_initDState(FSEv07_DState_t* DStatePtr, BITv07_DStream_t* bitD, const FSEv07_DTable* dt);
  688. static unsigned char FSEv07_decodeSymbol(FSEv07_DState_t* DStatePtr, BITv07_DStream_t* bitD);
  689. /* *****************************************
  690. * FSE unsafe API
  691. *******************************************/
  692. static unsigned char FSEv07_decodeSymbolFast(FSEv07_DState_t* DStatePtr, BITv07_DStream_t* bitD);
  693. /* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */
  694. /* ====== Decompression ====== */
  695. typedef struct {
  696. U16 tableLog;
  697. U16 fastMode;
  698. } FSEv07_DTableHeader; /* sizeof U32 */
  699. typedef struct
  700. {
  701. unsigned short newState;
  702. unsigned char symbol;
  703. unsigned char nbBits;
  704. } FSEv07_decode_t; /* size == U32 */
  705. MEM_STATIC void FSEv07_initDState(FSEv07_DState_t* DStatePtr, BITv07_DStream_t* bitD, const FSEv07_DTable* dt)
  706. {
  707. const void* ptr = dt;
  708. const FSEv07_DTableHeader* const DTableH = (const FSEv07_DTableHeader*)ptr;
  709. DStatePtr->state = BITv07_readBits(bitD, DTableH->tableLog);
  710. BITv07_reloadDStream(bitD);
  711. DStatePtr->table = dt + 1;
  712. }
  713. MEM_STATIC BYTE FSEv07_peekSymbol(const FSEv07_DState_t* DStatePtr)
  714. {
  715. FSEv07_decode_t const DInfo = ((const FSEv07_decode_t*)(DStatePtr->table))[DStatePtr->state];
  716. return DInfo.symbol;
  717. }
  718. MEM_STATIC void FSEv07_updateState(FSEv07_DState_t* DStatePtr, BITv07_DStream_t* bitD)
  719. {
  720. FSEv07_decode_t const DInfo = ((const FSEv07_decode_t*)(DStatePtr->table))[DStatePtr->state];
  721. U32 const nbBits = DInfo.nbBits;
  722. size_t const lowBits = BITv07_readBits(bitD, nbBits);
  723. DStatePtr->state = DInfo.newState + lowBits;
  724. }
  725. MEM_STATIC BYTE FSEv07_decodeSymbol(FSEv07_DState_t* DStatePtr, BITv07_DStream_t* bitD)
  726. {
  727. FSEv07_decode_t const DInfo = ((const FSEv07_decode_t*)(DStatePtr->table))[DStatePtr->state];
  728. U32 const nbBits = DInfo.nbBits;
  729. BYTE const symbol = DInfo.symbol;
  730. size_t const lowBits = BITv07_readBits(bitD, nbBits);
  731. DStatePtr->state = DInfo.newState + lowBits;
  732. return symbol;
  733. }
  734. /*! FSEv07_decodeSymbolFast() :
  735. unsafe, only works if no symbol has a probability > 50% */
  736. MEM_STATIC BYTE FSEv07_decodeSymbolFast(FSEv07_DState_t* DStatePtr, BITv07_DStream_t* bitD)
  737. {
  738. FSEv07_decode_t const DInfo = ((const FSEv07_decode_t*)(DStatePtr->table))[DStatePtr->state];
  739. U32 const nbBits = DInfo.nbBits;
  740. BYTE const symbol = DInfo.symbol;
  741. size_t const lowBits = BITv07_readBitsFast(bitD, nbBits);
  742. DStatePtr->state = DInfo.newState + lowBits;
  743. return symbol;
  744. }
  745. #ifndef FSEv07_COMMONDEFS_ONLY
  746. /* **************************************************************
  747. * Tuning parameters
  748. ****************************************************************/
  749. /*!MEMORY_USAGE :
  750. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  751. * Increasing memory usage improves compression ratio
  752. * Reduced memory usage can improve speed, due to cache effect
  753. * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
  754. #define FSEv07_MAX_MEMORY_USAGE 14
  755. #define FSEv07_DEFAULT_MEMORY_USAGE 13
  756. /*!FSEv07_MAX_SYMBOL_VALUE :
  757. * Maximum symbol value authorized.
  758. * Required for proper stack allocation */
  759. #define FSEv07_MAX_SYMBOL_VALUE 255
  760. /* **************************************************************
  761. * template functions type & suffix
  762. ****************************************************************/
  763. #define FSEv07_FUNCTION_TYPE BYTE
  764. #define FSEv07_FUNCTION_EXTENSION
  765. #define FSEv07_DECODE_TYPE FSEv07_decode_t
  766. #endif /* !FSEv07_COMMONDEFS_ONLY */
  767. /* ***************************************************************
  768. * Constants
  769. *****************************************************************/
  770. #define FSEv07_MAX_TABLELOG (FSEv07_MAX_MEMORY_USAGE-2)
  771. #define FSEv07_MAX_TABLESIZE (1U<<FSEv07_MAX_TABLELOG)
  772. #define FSEv07_MAXTABLESIZE_MASK (FSEv07_MAX_TABLESIZE-1)
  773. #define FSEv07_DEFAULT_TABLELOG (FSEv07_DEFAULT_MEMORY_USAGE-2)
  774. #define FSEv07_MIN_TABLELOG 5
  775. #define FSEv07_TABLELOG_ABSOLUTE_MAX 15
  776. #if FSEv07_MAX_TABLELOG > FSEv07_TABLELOG_ABSOLUTE_MAX
  777. # error "FSEv07_MAX_TABLELOG > FSEv07_TABLELOG_ABSOLUTE_MAX is not supported"
  778. #endif
  779. #define FSEv07_TABLESTEP(tableSize) ((tableSize>>1) + (tableSize>>3) + 3)
  780. #endif /* FSEv07_STATIC_LINKING_ONLY */
  781. #if defined (__cplusplus)
  782. }
  783. #endif
  784. #endif /* FSEv07_H */
  785. /* ******************************************************************
  786. Huffman coder, part of New Generation Entropy library
  787. header file
  788. Copyright (C) 2013-2016, Yann Collet.
  789. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  790. Redistribution and use in source and binary forms, with or without
  791. modification, are permitted provided that the following conditions are
  792. met:
  793. * Redistributions of source code must retain the above copyright
  794. notice, this list of conditions and the following disclaimer.
  795. * Redistributions in binary form must reproduce the above
  796. copyright notice, this list of conditions and the following disclaimer
  797. in the documentation and/or other materials provided with the
  798. distribution.
  799. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  800. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  801. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  802. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  803. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  804. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  805. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  806. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  807. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  808. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  809. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  810. You can contact the author at :
  811. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  812. ****************************************************************** */
  813. #ifndef HUFv07_H_298734234
  814. #define HUFv07_H_298734234
  815. #if defined (__cplusplus)
  816. extern "C" {
  817. #endif
  818. /* *** simple functions *** */
  819. /**
  820. HUFv07_decompress() :
  821. Decompress HUF data from buffer 'cSrc', of size 'cSrcSize',
  822. into already allocated buffer 'dst', of minimum size 'dstSize'.
  823. `dstSize` : **must** be the ***exact*** size of original (uncompressed) data.
  824. Note : in contrast with FSE, HUFv07_decompress can regenerate
  825. RLE (cSrcSize==1) and uncompressed (cSrcSize==dstSize) data,
  826. because it knows size to regenerate.
  827. @return : size of regenerated data (== dstSize),
  828. or an error code, which can be tested using HUFv07_isError()
  829. */
  830. size_t HUFv07_decompress(void* dst, size_t dstSize,
  831. const void* cSrc, size_t cSrcSize);
  832. /* ****************************************
  833. * Tool functions
  834. ******************************************/
  835. #define HUFv07_BLOCKSIZE_MAX (128 * 1024)
  836. /* Error Management */
  837. unsigned HUFv07_isError(size_t code); /**< tells if a return value is an error code */
  838. const char* HUFv07_getErrorName(size_t code); /**< provides error code string (useful for debugging) */
  839. /* *** Advanced function *** */
  840. #ifdef HUFv07_STATIC_LINKING_ONLY
  841. /* *** Constants *** */
  842. #define HUFv07_TABLELOG_ABSOLUTEMAX 16 /* absolute limit of HUFv07_MAX_TABLELOG. Beyond that value, code does not work */
  843. #define HUFv07_TABLELOG_MAX 12 /* max configured tableLog (for static allocation); can be modified up to HUFv07_ABSOLUTEMAX_TABLELOG */
  844. #define HUFv07_TABLELOG_DEFAULT 11 /* tableLog by default, when not specified */
  845. #define HUFv07_SYMBOLVALUE_MAX 255
  846. #if (HUFv07_TABLELOG_MAX > HUFv07_TABLELOG_ABSOLUTEMAX)
  847. # error "HUFv07_TABLELOG_MAX is too large !"
  848. #endif
  849. /* ****************************************
  850. * Static allocation
  851. ******************************************/
  852. /* HUF buffer bounds */
  853. #define HUFv07_BLOCKBOUND(size) (size + (size>>8) + 8) /* only true if incompressible pre-filtered with fast heuristic */
  854. /* static allocation of HUF's DTable */
  855. typedef U32 HUFv07_DTable;
  856. #define HUFv07_DTABLE_SIZE(maxTableLog) (1 + (1<<(maxTableLog)))
  857. #define HUFv07_CREATE_STATIC_DTABLEX2(DTable, maxTableLog) \
  858. HUFv07_DTable DTable[HUFv07_DTABLE_SIZE((maxTableLog)-1)] = { ((U32)((maxTableLog)-1)*0x1000001) }
  859. #define HUFv07_CREATE_STATIC_DTABLEX4(DTable, maxTableLog) \
  860. HUFv07_DTable DTable[HUFv07_DTABLE_SIZE(maxTableLog)] = { ((U32)(maxTableLog)*0x1000001) }
  861. /* ****************************************
  862. * Advanced decompression functions
  863. ******************************************/
  864. size_t HUFv07_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< single-symbol decoder */
  865. size_t HUFv07_decompress4X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< double-symbols decoder */
  866. size_t HUFv07_decompress4X_DCtx (HUFv07_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< decodes RLE and uncompressed */
  867. size_t HUFv07_decompress4X_hufOnly(HUFv07_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< considers RLE and uncompressed as errors */
  868. size_t HUFv07_decompress4X2_DCtx(HUFv07_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< single-symbol decoder */
  869. size_t HUFv07_decompress4X4_DCtx(HUFv07_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< double-symbols decoder */
  870. size_t HUFv07_decompress1X_DCtx (HUFv07_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);
  871. size_t HUFv07_decompress1X2_DCtx(HUFv07_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< single-symbol decoder */
  872. size_t HUFv07_decompress1X4_DCtx(HUFv07_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /**< double-symbols decoder */
  873. /* ****************************************
  874. * HUF detailed API
  875. ******************************************/
  876. /*!
  877. The following API allows targeting specific sub-functions for advanced tasks.
  878. For example, it's possible to compress several blocks using the same 'CTable',
  879. or to save and regenerate 'CTable' using external methods.
  880. */
  881. /* FSEv07_count() : find it within "fse.h" */
  882. /*! HUFv07_readStats() :
  883. Read compact Huffman tree, saved by HUFv07_writeCTable().
  884. `huffWeight` is destination buffer.
  885. @return : size read from `src` , or an error Code .
  886. Note : Needed by HUFv07_readCTable() and HUFv07_readDTableXn() . */
  887. size_t HUFv07_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  888. U32* nbSymbolsPtr, U32* tableLogPtr,
  889. const void* src, size_t srcSize);
  890. /*
  891. HUFv07_decompress() does the following:
  892. 1. select the decompression algorithm (X2, X4) based on pre-computed heuristics
  893. 2. build Huffman table from save, using HUFv07_readDTableXn()
  894. 3. decode 1 or 4 segments in parallel using HUFv07_decompressSXn_usingDTable
  895. */
  896. /** HUFv07_selectDecoder() :
  897. * Tells which decoder is likely to decode faster,
  898. * based on a set of pre-determined metrics.
  899. * @return : 0==HUFv07_decompress4X2, 1==HUFv07_decompress4X4 .
  900. * Assumption : 0 < cSrcSize < dstSize <= 128 KB */
  901. U32 HUFv07_selectDecoder (size_t dstSize, size_t cSrcSize);
  902. size_t HUFv07_readDTableX2 (HUFv07_DTable* DTable, const void* src, size_t srcSize);
  903. size_t HUFv07_readDTableX4 (HUFv07_DTable* DTable, const void* src, size_t srcSize);
  904. size_t HUFv07_decompress4X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUFv07_DTable* DTable);
  905. size_t HUFv07_decompress4X2_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUFv07_DTable* DTable);
  906. size_t HUFv07_decompress4X4_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUFv07_DTable* DTable);
  907. /* single stream variants */
  908. size_t HUFv07_decompress1X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /* single-symbol decoder */
  909. size_t HUFv07_decompress1X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /* double-symbol decoder */
  910. size_t HUFv07_decompress1X_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUFv07_DTable* DTable);
  911. size_t HUFv07_decompress1X2_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUFv07_DTable* DTable);
  912. size_t HUFv07_decompress1X4_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const HUFv07_DTable* DTable);
  913. #endif /* HUFv07_STATIC_LINKING_ONLY */
  914. #if defined (__cplusplus)
  915. }
  916. #endif
  917. #endif /* HUFv07_H_298734234 */
  918. /*
  919. Common functions of New Generation Entropy library
  920. Copyright (C) 2016, Yann Collet.
  921. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  922. Redistribution and use in source and binary forms, with or without
  923. modification, are permitted provided that the following conditions are
  924. met:
  925. * Redistributions of source code must retain the above copyright
  926. notice, this list of conditions and the following disclaimer.
  927. * Redistributions in binary form must reproduce the above
  928. copyright notice, this list of conditions and the following disclaimer
  929. in the documentation and/or other materials provided with the
  930. distribution.
  931. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  932. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  933. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  934. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  935. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  936. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  937. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  938. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  939. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  940. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  941. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  942. You can contact the author at :
  943. - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
  944. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  945. *************************************************************************** */
  946. /*-****************************************
  947. * FSE Error Management
  948. ******************************************/
  949. unsigned FSEv07_isError(size_t code) { return ERR_isError(code); }
  950. const char* FSEv07_getErrorName(size_t code) { return ERR_getErrorName(code); }
  951. /* **************************************************************
  952. * HUF Error Management
  953. ****************************************************************/
  954. unsigned HUFv07_isError(size_t code) { return ERR_isError(code); }
  955. const char* HUFv07_getErrorName(size_t code) { return ERR_getErrorName(code); }
  956. /*-**************************************************************
  957. * FSE NCount encoding-decoding
  958. ****************************************************************/
  959. static short FSEv07_abs(short a) { return (short)(a<0 ? -a : a); }
  960. size_t FSEv07_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  961. const void* headerBuffer, size_t hbSize)
  962. {
  963. const BYTE* const istart = (const BYTE*) headerBuffer;
  964. const BYTE* const iend = istart + hbSize;
  965. const BYTE* ip = istart;
  966. int nbBits;
  967. int remaining;
  968. int threshold;
  969. U32 bitStream;
  970. int bitCount;
  971. unsigned charnum = 0;
  972. int previous0 = 0;
  973. if (hbSize < 4) return ERROR(srcSize_wrong);
  974. bitStream = MEM_readLE32(ip);
  975. nbBits = (bitStream & 0xF) + FSEv07_MIN_TABLELOG; /* extract tableLog */
  976. if (nbBits > FSEv07_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
  977. bitStream >>= 4;
  978. bitCount = 4;
  979. *tableLogPtr = nbBits;
  980. remaining = (1<<nbBits)+1;
  981. threshold = 1<<nbBits;
  982. nbBits++;
  983. while ((remaining>1) && (charnum<=*maxSVPtr)) {
  984. if (previous0) {
  985. unsigned n0 = charnum;
  986. while ((bitStream & 0xFFFF) == 0xFFFF) {
  987. n0+=24;
  988. if (ip < iend-5) {
  989. ip+=2;
  990. bitStream = MEM_readLE32(ip) >> bitCount;
  991. } else {
  992. bitStream >>= 16;
  993. bitCount+=16;
  994. } }
  995. while ((bitStream & 3) == 3) {
  996. n0+=3;
  997. bitStream>>=2;
  998. bitCount+=2;
  999. }
  1000. n0 += bitStream & 3;
  1001. bitCount += 2;
  1002. if (n0 > *maxSVPtr) return ERROR(maxSymbolValue_tooSmall);
  1003. while (charnum < n0) normalizedCounter[charnum++] = 0;
  1004. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
  1005. ip += bitCount>>3;
  1006. bitCount &= 7;
  1007. bitStream = MEM_readLE32(ip) >> bitCount;
  1008. }
  1009. else
  1010. bitStream >>= 2;
  1011. }
  1012. { short const max = (short)((2*threshold-1)-remaining);
  1013. short count;
  1014. if ((bitStream & (threshold-1)) < (U32)max) {
  1015. count = (short)(bitStream & (threshold-1));
  1016. bitCount += nbBits-1;
  1017. } else {
  1018. count = (short)(bitStream & (2*threshold-1));
  1019. if (count >= threshold) count -= max;
  1020. bitCount += nbBits;
  1021. }
  1022. count--; /* extra accuracy */
  1023. remaining -= FSEv07_abs(count);
  1024. normalizedCounter[charnum++] = count;
  1025. previous0 = !count;
  1026. while (remaining < threshold) {
  1027. nbBits--;
  1028. threshold >>= 1;
  1029. }
  1030. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4)) {
  1031. ip += bitCount>>3;
  1032. bitCount &= 7;
  1033. } else {
  1034. bitCount -= (int)(8 * (iend - 4 - ip));
  1035. ip = iend - 4;
  1036. }
  1037. bitStream = MEM_readLE32(ip) >> (bitCount & 31);
  1038. } } /* while ((remaining>1) && (charnum<=*maxSVPtr)) */
  1039. if (remaining != 1) return ERROR(GENERIC);
  1040. *maxSVPtr = charnum-1;
  1041. ip += (bitCount+7)>>3;
  1042. if ((size_t)(ip-istart) > hbSize) return ERROR(srcSize_wrong);
  1043. return ip-istart;
  1044. }
  1045. /*! HUFv07_readStats() :
  1046. Read compact Huffman tree, saved by HUFv07_writeCTable().
  1047. `huffWeight` is destination buffer.
  1048. @return : size read from `src` , or an error Code .
  1049. Note : Needed by HUFv07_readCTable() and HUFv07_readDTableXn() .
  1050. */
  1051. size_t HUFv07_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  1052. U32* nbSymbolsPtr, U32* tableLogPtr,
  1053. const void* src, size_t srcSize)
  1054. {
  1055. U32 weightTotal;
  1056. const BYTE* ip = (const BYTE*) src;
  1057. size_t iSize;
  1058. size_t oSize;
  1059. if (!srcSize) return ERROR(srcSize_wrong);
  1060. iSize = ip[0];
  1061. //memset(huffWeight, 0, hwSize); /* is not necessary, even though some analyzer complain ... */
  1062. if (iSize >= 128) { /* special header */
  1063. if (iSize >= (242)) { /* RLE */
  1064. static U32 l[14] = { 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128 };
  1065. oSize = l[iSize-242];
  1066. memset(huffWeight, 1, hwSize);
  1067. iSize = 0;
  1068. }
  1069. else { /* Incompressible */
  1070. oSize = iSize - 127;
  1071. iSize = ((oSize+1)/2);
  1072. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  1073. if (oSize >= hwSize) return ERROR(corruption_detected);
  1074. ip += 1;
  1075. { U32 n;
  1076. for (n=0; n<oSize; n+=2) {
  1077. huffWeight[n] = ip[n/2] >> 4;
  1078. huffWeight[n+1] = ip[n/2] & 15;
  1079. } } } }
  1080. else { /* header compressed with FSE (normal case) */
  1081. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  1082. oSize = FSEv07_decompress(huffWeight, hwSize-1, ip+1, iSize); /* max (hwSize-1) values decoded, as last one is implied */
  1083. if (FSEv07_isError(oSize)) return oSize;
  1084. }
  1085. /* collect weight stats */
  1086. memset(rankStats, 0, (HUFv07_TABLELOG_ABSOLUTEMAX + 1) * sizeof(U32));
  1087. weightTotal = 0;
  1088. { U32 n; for (n=0; n<oSize; n++) {
  1089. if (huffWeight[n] >= HUFv07_TABLELOG_ABSOLUTEMAX) return ERROR(corruption_detected);
  1090. rankStats[huffWeight[n]]++;
  1091. weightTotal += (1 << huffWeight[n]) >> 1;
  1092. } }
  1093. if (weightTotal == 0) return ERROR(corruption_detected);
  1094. /* get last non-null symbol weight (implied, total must be 2^n) */
  1095. { U32 const tableLog = BITv07_highbit32(weightTotal) + 1;
  1096. if (tableLog > HUFv07_TABLELOG_ABSOLUTEMAX) return ERROR(corruption_detected);
  1097. *tableLogPtr = tableLog;
  1098. /* determine last weight */
  1099. { U32 const total = 1 << tableLog;
  1100. U32 const rest = total - weightTotal;
  1101. U32 const verif = 1 << BITv07_highbit32(rest);
  1102. U32 const lastWeight = BITv07_highbit32(rest) + 1;
  1103. if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */
  1104. huffWeight[oSize] = (BYTE)lastWeight;
  1105. rankStats[lastWeight]++;
  1106. } }
  1107. /* check tree construction validity */
  1108. if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */
  1109. /* results */
  1110. *nbSymbolsPtr = (U32)(oSize+1);
  1111. return iSize+1;
  1112. }
  1113. /* ******************************************************************
  1114. FSE : Finite State Entropy decoder
  1115. Copyright (C) 2013-2015, Yann Collet.
  1116. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  1117. Redistribution and use in source and binary forms, with or without
  1118. modification, are permitted provided that the following conditions are
  1119. met:
  1120. * Redistributions of source code must retain the above copyright
  1121. notice, this list of conditions and the following disclaimer.
  1122. * Redistributions in binary form must reproduce the above
  1123. copyright notice, this list of conditions and the following disclaimer
  1124. in the documentation and/or other materials provided with the
  1125. distribution.
  1126. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1127. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1128. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1129. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1130. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1131. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1132. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1133. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1134. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1135. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1136. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1137. You can contact the author at :
  1138. - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
  1139. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  1140. ****************************************************************** */
  1141. /* **************************************************************
  1142. * Compiler specifics
  1143. ****************************************************************/
  1144. #ifdef _MSC_VER /* Visual Studio */
  1145. # define FORCE_INLINE static __forceinline
  1146. # include <intrin.h> /* For Visual 2005 */
  1147. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  1148. # pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */
  1149. #else
  1150. # if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
  1151. # ifdef __GNUC__
  1152. # define FORCE_INLINE static inline __attribute__((always_inline))
  1153. # else
  1154. # define FORCE_INLINE static inline
  1155. # endif
  1156. # else
  1157. # define FORCE_INLINE static
  1158. # endif /* __STDC_VERSION__ */
  1159. #endif
  1160. /* **************************************************************
  1161. * Error Management
  1162. ****************************************************************/
  1163. #define FSEv07_isError ERR_isError
  1164. #define FSEv07_STATIC_ASSERT(c) { enum { FSEv07_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  1165. /* **************************************************************
  1166. * Complex types
  1167. ****************************************************************/
  1168. typedef U32 DTable_max_t[FSEv07_DTABLE_SIZE_U32(FSEv07_MAX_TABLELOG)];
  1169. /* **************************************************************
  1170. * Templates
  1171. ****************************************************************/
  1172. /*
  1173. designed to be included
  1174. for type-specific functions (template emulation in C)
  1175. Objective is to write these functions only once, for improved maintenance
  1176. */
  1177. /* safety checks */
  1178. #ifndef FSEv07_FUNCTION_EXTENSION
  1179. # error "FSEv07_FUNCTION_EXTENSION must be defined"
  1180. #endif
  1181. #ifndef FSEv07_FUNCTION_TYPE
  1182. # error "FSEv07_FUNCTION_TYPE must be defined"
  1183. #endif
  1184. /* Function names */
  1185. #define FSEv07_CAT(X,Y) X##Y
  1186. #define FSEv07_FUNCTION_NAME(X,Y) FSEv07_CAT(X,Y)
  1187. #define FSEv07_TYPE_NAME(X,Y) FSEv07_CAT(X,Y)
  1188. /* Function templates */
  1189. FSEv07_DTable* FSEv07_createDTable (unsigned tableLog)
  1190. {
  1191. if (tableLog > FSEv07_TABLELOG_ABSOLUTE_MAX) tableLog = FSEv07_TABLELOG_ABSOLUTE_MAX;
  1192. return (FSEv07_DTable*)malloc( FSEv07_DTABLE_SIZE_U32(tableLog) * sizeof (U32) );
  1193. }
  1194. void FSEv07_freeDTable (FSEv07_DTable* dt)
  1195. {
  1196. free(dt);
  1197. }
  1198. size_t FSEv07_buildDTable(FSEv07_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
  1199. {
  1200. void* const tdPtr = dt+1; /* because *dt is unsigned, 32-bits aligned on 32-bits */
  1201. FSEv07_DECODE_TYPE* const tableDecode = (FSEv07_DECODE_TYPE*) (tdPtr);
  1202. U16 symbolNext[FSEv07_MAX_SYMBOL_VALUE+1];
  1203. U32 const maxSV1 = maxSymbolValue + 1;
  1204. U32 const tableSize = 1 << tableLog;
  1205. U32 highThreshold = tableSize-1;
  1206. /* Sanity Checks */
  1207. if (maxSymbolValue > FSEv07_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge);
  1208. if (tableLog > FSEv07_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
  1209. /* Init, lay down lowprob symbols */
  1210. { FSEv07_DTableHeader DTableH;
  1211. DTableH.tableLog = (U16)tableLog;
  1212. DTableH.fastMode = 1;
  1213. { S16 const largeLimit= (S16)(1 << (tableLog-1));
  1214. U32 s;
  1215. for (s=0; s<maxSV1; s++) {
  1216. if (normalizedCounter[s]==-1) {
  1217. tableDecode[highThreshold--].symbol = (FSEv07_FUNCTION_TYPE)s;
  1218. symbolNext[s] = 1;
  1219. } else {
  1220. if (normalizedCounter[s] >= largeLimit) DTableH.fastMode=0;
  1221. symbolNext[s] = normalizedCounter[s];
  1222. } } }
  1223. memcpy(dt, &DTableH, sizeof(DTableH));
  1224. }
  1225. /* Spread symbols */
  1226. { U32 const tableMask = tableSize-1;
  1227. U32 const step = FSEv07_TABLESTEP(tableSize);
  1228. U32 s, position = 0;
  1229. for (s=0; s<maxSV1; s++) {
  1230. int i;
  1231. for (i=0; i<normalizedCounter[s]; i++) {
  1232. tableDecode[position].symbol = (FSEv07_FUNCTION_TYPE)s;
  1233. position = (position + step) & tableMask;
  1234. while (position > highThreshold) position = (position + step) & tableMask; /* lowprob area */
  1235. } }
  1236. if (position!=0) return ERROR(GENERIC); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
  1237. }
  1238. /* Build Decoding table */
  1239. { U32 u;
  1240. for (u=0; u<tableSize; u++) {
  1241. FSEv07_FUNCTION_TYPE const symbol = (FSEv07_FUNCTION_TYPE)(tableDecode[u].symbol);
  1242. U16 nextState = symbolNext[symbol]++;
  1243. tableDecode[u].nbBits = (BYTE) (tableLog - BITv07_highbit32 ((U32)nextState) );
  1244. tableDecode[u].newState = (U16) ( (nextState << tableDecode[u].nbBits) - tableSize);
  1245. } }
  1246. return 0;
  1247. }
  1248. #ifndef FSEv07_COMMONDEFS_ONLY
  1249. /*-*******************************************************
  1250. * Decompression (Byte symbols)
  1251. *********************************************************/
  1252. size_t FSEv07_buildDTable_rle (FSEv07_DTable* dt, BYTE symbolValue)
  1253. {
  1254. void* ptr = dt;
  1255. FSEv07_DTableHeader* const DTableH = (FSEv07_DTableHeader*)ptr;
  1256. void* dPtr = dt + 1;
  1257. FSEv07_decode_t* const cell = (FSEv07_decode_t*)dPtr;
  1258. DTableH->tableLog = 0;
  1259. DTableH->fastMode = 0;
  1260. cell->newState = 0;
  1261. cell->symbol = symbolValue;
  1262. cell->nbBits = 0;
  1263. return 0;
  1264. }
  1265. size_t FSEv07_buildDTable_raw (FSEv07_DTable* dt, unsigned nbBits)
  1266. {
  1267. void* ptr = dt;
  1268. FSEv07_DTableHeader* const DTableH = (FSEv07_DTableHeader*)ptr;
  1269. void* dPtr = dt + 1;
  1270. FSEv07_decode_t* const dinfo = (FSEv07_decode_t*)dPtr;
  1271. const unsigned tableSize = 1 << nbBits;
  1272. const unsigned tableMask = tableSize - 1;
  1273. const unsigned maxSV1 = tableMask+1;
  1274. unsigned s;
  1275. /* Sanity checks */
  1276. if (nbBits < 1) return ERROR(GENERIC); /* min size */
  1277. /* Build Decoding Table */
  1278. DTableH->tableLog = (U16)nbBits;
  1279. DTableH->fastMode = 1;
  1280. for (s=0; s<maxSV1; s++) {
  1281. dinfo[s].newState = 0;
  1282. dinfo[s].symbol = (BYTE)s;
  1283. dinfo[s].nbBits = (BYTE)nbBits;
  1284. }
  1285. return 0;
  1286. }
  1287. FORCE_INLINE size_t FSEv07_decompress_usingDTable_generic(
  1288. void* dst, size_t maxDstSize,
  1289. const void* cSrc, size_t cSrcSize,
  1290. const FSEv07_DTable* dt, const unsigned fast)
  1291. {
  1292. BYTE* const ostart = (BYTE*) dst;
  1293. BYTE* op = ostart;
  1294. BYTE* const omax = op + maxDstSize;
  1295. BYTE* const olimit = omax-3;
  1296. BITv07_DStream_t bitD;
  1297. FSEv07_DState_t state1;
  1298. FSEv07_DState_t state2;
  1299. /* Init */
  1300. { size_t const errorCode = BITv07_initDStream(&bitD, cSrc, cSrcSize); /* replaced last arg by maxCompressed Size */
  1301. if (FSEv07_isError(errorCode)) return errorCode; }
  1302. FSEv07_initDState(&state1, &bitD, dt);
  1303. FSEv07_initDState(&state2, &bitD, dt);
  1304. #define FSEv07_GETSYMBOL(statePtr) fast ? FSEv07_decodeSymbolFast(statePtr, &bitD) : FSEv07_decodeSymbol(statePtr, &bitD)
  1305. /* 4 symbols per loop */
  1306. for ( ; (BITv07_reloadDStream(&bitD)==BITv07_DStream_unfinished) && (op<olimit) ; op+=4) {
  1307. op[0] = FSEv07_GETSYMBOL(&state1);
  1308. if (FSEv07_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1309. BITv07_reloadDStream(&bitD);
  1310. op[1] = FSEv07_GETSYMBOL(&state2);
  1311. if (FSEv07_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1312. { if (BITv07_reloadDStream(&bitD) > BITv07_DStream_unfinished) { op+=2; break; } }
  1313. op[2] = FSEv07_GETSYMBOL(&state1);
  1314. if (FSEv07_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1315. BITv07_reloadDStream(&bitD);
  1316. op[3] = FSEv07_GETSYMBOL(&state2);
  1317. }
  1318. /* tail */
  1319. /* note : BITv07_reloadDStream(&bitD) >= FSEv07_DStream_partiallyFilled; Ends at exactly BITv07_DStream_completed */
  1320. while (1) {
  1321. if (op>(omax-2)) return ERROR(dstSize_tooSmall);
  1322. *op++ = FSEv07_GETSYMBOL(&state1);
  1323. if (BITv07_reloadDStream(&bitD)==BITv07_DStream_overflow) {
  1324. *op++ = FSEv07_GETSYMBOL(&state2);
  1325. break;
  1326. }
  1327. if (op>(omax-2)) return ERROR(dstSize_tooSmall);
  1328. *op++ = FSEv07_GETSYMBOL(&state2);
  1329. if (BITv07_reloadDStream(&bitD)==BITv07_DStream_overflow) {
  1330. *op++ = FSEv07_GETSYMBOL(&state1);
  1331. break;
  1332. } }
  1333. return op-ostart;
  1334. }
  1335. size_t FSEv07_decompress_usingDTable(void* dst, size_t originalSize,
  1336. const void* cSrc, size_t cSrcSize,
  1337. const FSEv07_DTable* dt)
  1338. {
  1339. const void* ptr = dt;
  1340. const FSEv07_DTableHeader* DTableH = (const FSEv07_DTableHeader*)ptr;
  1341. const U32 fastMode = DTableH->fastMode;
  1342. /* select fast mode (static) */
  1343. if (fastMode) return FSEv07_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 1);
  1344. return FSEv07_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 0);
  1345. }
  1346. size_t FSEv07_decompress(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize)
  1347. {
  1348. const BYTE* const istart = (const BYTE*)cSrc;
  1349. const BYTE* ip = istart;
  1350. short counting[FSEv07_MAX_SYMBOL_VALUE+1];
  1351. DTable_max_t dt; /* Static analyzer seems unable to understand this table will be properly initialized later */
  1352. unsigned tableLog;
  1353. unsigned maxSymbolValue = FSEv07_MAX_SYMBOL_VALUE;
  1354. if (cSrcSize<2) return ERROR(srcSize_wrong); /* too small input size */
  1355. /* normal FSE decoding mode */
  1356. { size_t const NCountLength = FSEv07_readNCount (counting, &maxSymbolValue, &tableLog, istart, cSrcSize);
  1357. if (FSEv07_isError(NCountLength)) return NCountLength;
  1358. if (NCountLength >= cSrcSize) return ERROR(srcSize_wrong); /* too small input size */
  1359. ip += NCountLength;
  1360. cSrcSize -= NCountLength;
  1361. }
  1362. { size_t const errorCode = FSEv07_buildDTable (dt, counting, maxSymbolValue, tableLog);
  1363. if (FSEv07_isError(errorCode)) return errorCode; }
  1364. return FSEv07_decompress_usingDTable (dst, maxDstSize, ip, cSrcSize, dt); /* always return, even if it is an error code */
  1365. }
  1366. #endif /* FSEv07_COMMONDEFS_ONLY */
  1367. /* ******************************************************************
  1368. Huffman decoder, part of New Generation Entropy library
  1369. Copyright (C) 2013-2016, Yann Collet.
  1370. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  1371. Redistribution and use in source and binary forms, with or without
  1372. modification, are permitted provided that the following conditions are
  1373. met:
  1374. * Redistributions of source code must retain the above copyright
  1375. notice, this list of conditions and the following disclaimer.
  1376. * Redistributions in binary form must reproduce the above
  1377. copyright notice, this list of conditions and the following disclaimer
  1378. in the documentation and/or other materials provided with the
  1379. distribution.
  1380. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1381. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1382. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1383. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1384. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1385. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1386. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1387. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1388. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1389. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1390. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1391. You can contact the author at :
  1392. - FSE+HUF source repository : https://github.com/Cyan4973/FiniteStateEntropy
  1393. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  1394. ****************************************************************** */
  1395. /* **************************************************************
  1396. * Compiler specifics
  1397. ****************************************************************/
  1398. #if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  1399. /* inline is defined */
  1400. #elif defined(_MSC_VER)
  1401. # define inline __inline
  1402. #else
  1403. # define inline /* disable inline */
  1404. #endif
  1405. #ifdef _MSC_VER /* Visual Studio */
  1406. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  1407. #endif
  1408. /* **************************************************************
  1409. * Error Management
  1410. ****************************************************************/
  1411. #define HUFv07_STATIC_ASSERT(c) { enum { HUFv07_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  1412. /*-***************************/
  1413. /* generic DTableDesc */
  1414. /*-***************************/
  1415. typedef struct { BYTE maxTableLog; BYTE tableType; BYTE tableLog; BYTE reserved; } DTableDesc;
  1416. static DTableDesc HUFv07_getDTableDesc(const HUFv07_DTable* table)
  1417. {
  1418. DTableDesc dtd;
  1419. memcpy(&dtd, table, sizeof(dtd));
  1420. return dtd;
  1421. }
  1422. /*-***************************/
  1423. /* single-symbol decoding */
  1424. /*-***************************/
  1425. typedef struct { BYTE byte; BYTE nbBits; } HUFv07_DEltX2; /* single-symbol decoding */
  1426. size_t HUFv07_readDTableX2 (HUFv07_DTable* DTable, const void* src, size_t srcSize)
  1427. {
  1428. BYTE huffWeight[HUFv07_SYMBOLVALUE_MAX + 1];
  1429. U32 rankVal[HUFv07_TABLELOG_ABSOLUTEMAX + 1]; /* large enough for values from 0 to 16 */
  1430. U32 tableLog = 0;
  1431. U32 nbSymbols = 0;
  1432. size_t iSize;
  1433. void* const dtPtr = DTable + 1;
  1434. HUFv07_DEltX2* const dt = (HUFv07_DEltX2*)dtPtr;
  1435. HUFv07_STATIC_ASSERT(sizeof(DTableDesc) == sizeof(HUFv07_DTable));
  1436. //memset(huffWeight, 0, sizeof(huffWeight)); /* is not necessary, even though some analyzer complain ... */
  1437. iSize = HUFv07_readStats(huffWeight, HUFv07_SYMBOLVALUE_MAX + 1, rankVal, &nbSymbols, &tableLog, src, srcSize);
  1438. if (HUFv07_isError(iSize)) return iSize;
  1439. /* Table header */
  1440. { DTableDesc dtd = HUFv07_getDTableDesc(DTable);
  1441. if (tableLog > (U32)(dtd.maxTableLog+1)) return ERROR(tableLog_tooLarge); /* DTable too small, huffman tree cannot fit in */
  1442. dtd.tableType = 0;
  1443. dtd.tableLog = (BYTE)tableLog;
  1444. memcpy(DTable, &dtd, sizeof(dtd));
  1445. }
  1446. /* Prepare ranks */
  1447. { U32 n, nextRankStart = 0;
  1448. for (n=1; n<tableLog+1; n++) {
  1449. U32 current = nextRankStart;
  1450. nextRankStart += (rankVal[n] << (n-1));
  1451. rankVal[n] = current;
  1452. } }
  1453. /* fill DTable */
  1454. { U32 n;
  1455. for (n=0; n<nbSymbols; n++) {
  1456. U32 const w = huffWeight[n];
  1457. U32 const length = (1 << w) >> 1;
  1458. U32 i;
  1459. HUFv07_DEltX2 D;
  1460. D.byte = (BYTE)n; D.nbBits = (BYTE)(tableLog + 1 - w);
  1461. for (i = rankVal[w]; i < rankVal[w] + length; i++)
  1462. dt[i] = D;
  1463. rankVal[w] += length;
  1464. } }
  1465. return iSize;
  1466. }
  1467. static BYTE HUFv07_decodeSymbolX2(BITv07_DStream_t* Dstream, const HUFv07_DEltX2* dt, const U32 dtLog)
  1468. {
  1469. size_t const val = BITv07_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */
  1470. BYTE const c = dt[val].byte;
  1471. BITv07_skipBits(Dstream, dt[val].nbBits);
  1472. return c;
  1473. }
  1474. #define HUFv07_DECODE_SYMBOLX2_0(ptr, DStreamPtr) \
  1475. *ptr++ = HUFv07_decodeSymbolX2(DStreamPtr, dt, dtLog)
  1476. #define HUFv07_DECODE_SYMBOLX2_1(ptr, DStreamPtr) \
  1477. if (MEM_64bits() || (HUFv07_TABLELOG_MAX<=12)) \
  1478. HUFv07_DECODE_SYMBOLX2_0(ptr, DStreamPtr)
  1479. #define HUFv07_DECODE_SYMBOLX2_2(ptr, DStreamPtr) \
  1480. if (MEM_64bits()) \
  1481. HUFv07_DECODE_SYMBOLX2_0(ptr, DStreamPtr)
  1482. static inline size_t HUFv07_decodeStreamX2(BYTE* p, BITv07_DStream_t* const bitDPtr, BYTE* const pEnd, const HUFv07_DEltX2* const dt, const U32 dtLog)
  1483. {
  1484. BYTE* const pStart = p;
  1485. /* up to 4 symbols at a time */
  1486. while ((BITv07_reloadDStream(bitDPtr) == BITv07_DStream_unfinished) && (p <= pEnd-4)) {
  1487. HUFv07_DECODE_SYMBOLX2_2(p, bitDPtr);
  1488. HUFv07_DECODE_SYMBOLX2_1(p, bitDPtr);
  1489. HUFv07_DECODE_SYMBOLX2_2(p, bitDPtr);
  1490. HUFv07_DECODE_SYMBOLX2_0(p, bitDPtr);
  1491. }
  1492. /* closer to the end */
  1493. while ((BITv07_reloadDStream(bitDPtr) == BITv07_DStream_unfinished) && (p < pEnd))
  1494. HUFv07_DECODE_SYMBOLX2_0(p, bitDPtr);
  1495. /* no more data to retrieve from bitstream, hence no need to reload */
  1496. while (p < pEnd)
  1497. HUFv07_DECODE_SYMBOLX2_0(p, bitDPtr);
  1498. return pEnd-pStart;
  1499. }
  1500. static size_t HUFv07_decompress1X2_usingDTable_internal(
  1501. void* dst, size_t dstSize,
  1502. const void* cSrc, size_t cSrcSize,
  1503. const HUFv07_DTable* DTable)
  1504. {
  1505. BYTE* op = (BYTE*)dst;
  1506. BYTE* const oend = op + dstSize;
  1507. const void* dtPtr = DTable + 1;
  1508. const HUFv07_DEltX2* const dt = (const HUFv07_DEltX2*)dtPtr;
  1509. BITv07_DStream_t bitD;
  1510. DTableDesc const dtd = HUFv07_getDTableDesc(DTable);
  1511. U32 const dtLog = dtd.tableLog;
  1512. { size_t const errorCode = BITv07_initDStream(&bitD, cSrc, cSrcSize);
  1513. if (HUFv07_isError(errorCode)) return errorCode; }
  1514. HUFv07_decodeStreamX2(op, &bitD, oend, dt, dtLog);
  1515. /* check */
  1516. if (!BITv07_endOfDStream(&bitD)) return ERROR(corruption_detected);
  1517. return dstSize;
  1518. }
  1519. size_t HUFv07_decompress1X2_usingDTable(
  1520. void* dst, size_t dstSize,
  1521. const void* cSrc, size_t cSrcSize,
  1522. const HUFv07_DTable* DTable)
  1523. {
  1524. DTableDesc dtd = HUFv07_getDTableDesc(DTable);
  1525. if (dtd.tableType != 0) return ERROR(GENERIC);
  1526. return HUFv07_decompress1X2_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable);
  1527. }
  1528. size_t HUFv07_decompress1X2_DCtx (HUFv07_DTable* DCtx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1529. {
  1530. const BYTE* ip = (const BYTE*) cSrc;
  1531. size_t const hSize = HUFv07_readDTableX2 (DCtx, cSrc, cSrcSize);
  1532. if (HUFv07_isError(hSize)) return hSize;
  1533. if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
  1534. ip += hSize; cSrcSize -= hSize;
  1535. return HUFv07_decompress1X2_usingDTable_internal (dst, dstSize, ip, cSrcSize, DCtx);
  1536. }
  1537. size_t HUFv07_decompress1X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1538. {
  1539. HUFv07_CREATE_STATIC_DTABLEX2(DTable, HUFv07_TABLELOG_MAX);
  1540. return HUFv07_decompress1X2_DCtx (DTable, dst, dstSize, cSrc, cSrcSize);
  1541. }
  1542. static size_t HUFv07_decompress4X2_usingDTable_internal(
  1543. void* dst, size_t dstSize,
  1544. const void* cSrc, size_t cSrcSize,
  1545. const HUFv07_DTable* DTable)
  1546. {
  1547. /* Check */
  1548. if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
  1549. { const BYTE* const istart = (const BYTE*) cSrc;
  1550. BYTE* const ostart = (BYTE*) dst;
  1551. BYTE* const oend = ostart + dstSize;
  1552. const void* const dtPtr = DTable + 1;
  1553. const HUFv07_DEltX2* const dt = (const HUFv07_DEltX2*)dtPtr;
  1554. /* Init */
  1555. BITv07_DStream_t bitD1;
  1556. BITv07_DStream_t bitD2;
  1557. BITv07_DStream_t bitD3;
  1558. BITv07_DStream_t bitD4;
  1559. size_t const length1 = MEM_readLE16(istart);
  1560. size_t const length2 = MEM_readLE16(istart+2);
  1561. size_t const length3 = MEM_readLE16(istart+4);
  1562. size_t const length4 = cSrcSize - (length1 + length2 + length3 + 6);
  1563. const BYTE* const istart1 = istart + 6; /* jumpTable */
  1564. const BYTE* const istart2 = istart1 + length1;
  1565. const BYTE* const istart3 = istart2 + length2;
  1566. const BYTE* const istart4 = istart3 + length3;
  1567. const size_t segmentSize = (dstSize+3) / 4;
  1568. BYTE* const opStart2 = ostart + segmentSize;
  1569. BYTE* const opStart3 = opStart2 + segmentSize;
  1570. BYTE* const opStart4 = opStart3 + segmentSize;
  1571. BYTE* op1 = ostart;
  1572. BYTE* op2 = opStart2;
  1573. BYTE* op3 = opStart3;
  1574. BYTE* op4 = opStart4;
  1575. U32 endSignal;
  1576. DTableDesc const dtd = HUFv07_getDTableDesc(DTable);
  1577. U32 const dtLog = dtd.tableLog;
  1578. if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
  1579. { size_t const errorCode = BITv07_initDStream(&bitD1, istart1, length1);
  1580. if (HUFv07_isError(errorCode)) return errorCode; }
  1581. { size_t const errorCode = BITv07_initDStream(&bitD2, istart2, length2);
  1582. if (HUFv07_isError(errorCode)) return errorCode; }
  1583. { size_t const errorCode = BITv07_initDStream(&bitD3, istart3, length3);
  1584. if (HUFv07_isError(errorCode)) return errorCode; }
  1585. { size_t const errorCode = BITv07_initDStream(&bitD4, istart4, length4);
  1586. if (HUFv07_isError(errorCode)) return errorCode; }
  1587. /* 16-32 symbols per loop (4-8 symbols per stream) */
  1588. endSignal = BITv07_reloadDStream(&bitD1) | BITv07_reloadDStream(&bitD2) | BITv07_reloadDStream(&bitD3) | BITv07_reloadDStream(&bitD4);
  1589. for ( ; (endSignal==BITv07_DStream_unfinished) && (op4<(oend-7)) ; ) {
  1590. HUFv07_DECODE_SYMBOLX2_2(op1, &bitD1);
  1591. HUFv07_DECODE_SYMBOLX2_2(op2, &bitD2);
  1592. HUFv07_DECODE_SYMBOLX2_2(op3, &bitD3);
  1593. HUFv07_DECODE_SYMBOLX2_2(op4, &bitD4);
  1594. HUFv07_DECODE_SYMBOLX2_1(op1, &bitD1);
  1595. HUFv07_DECODE_SYMBOLX2_1(op2, &bitD2);
  1596. HUFv07_DECODE_SYMBOLX2_1(op3, &bitD3);
  1597. HUFv07_DECODE_SYMBOLX2_1(op4, &bitD4);
  1598. HUFv07_DECODE_SYMBOLX2_2(op1, &bitD1);
  1599. HUFv07_DECODE_SYMBOLX2_2(op2, &bitD2);
  1600. HUFv07_DECODE_SYMBOLX2_2(op3, &bitD3);
  1601. HUFv07_DECODE_SYMBOLX2_2(op4, &bitD4);
  1602. HUFv07_DECODE_SYMBOLX2_0(op1, &bitD1);
  1603. HUFv07_DECODE_SYMBOLX2_0(op2, &bitD2);
  1604. HUFv07_DECODE_SYMBOLX2_0(op3, &bitD3);
  1605. HUFv07_DECODE_SYMBOLX2_0(op4, &bitD4);
  1606. endSignal = BITv07_reloadDStream(&bitD1) | BITv07_reloadDStream(&bitD2) | BITv07_reloadDStream(&bitD3) | BITv07_reloadDStream(&bitD4);
  1607. }
  1608. /* check corruption */
  1609. if (op1 > opStart2) return ERROR(corruption_detected);
  1610. if (op2 > opStart3) return ERROR(corruption_detected);
  1611. if (op3 > opStart4) return ERROR(corruption_detected);
  1612. /* note : op4 supposed already verified within main loop */
  1613. /* finish bitStreams one by one */
  1614. HUFv07_decodeStreamX2(op1, &bitD1, opStart2, dt, dtLog);
  1615. HUFv07_decodeStreamX2(op2, &bitD2, opStart3, dt, dtLog);
  1616. HUFv07_decodeStreamX2(op3, &bitD3, opStart4, dt, dtLog);
  1617. HUFv07_decodeStreamX2(op4, &bitD4, oend, dt, dtLog);
  1618. /* check */
  1619. endSignal = BITv07_endOfDStream(&bitD1) & BITv07_endOfDStream(&bitD2) & BITv07_endOfDStream(&bitD3) & BITv07_endOfDStream(&bitD4);
  1620. if (!endSignal) return ERROR(corruption_detected);
  1621. /* decoded size */
  1622. return dstSize;
  1623. }
  1624. }
  1625. size_t HUFv07_decompress4X2_usingDTable(
  1626. void* dst, size_t dstSize,
  1627. const void* cSrc, size_t cSrcSize,
  1628. const HUFv07_DTable* DTable)
  1629. {
  1630. DTableDesc dtd = HUFv07_getDTableDesc(DTable);
  1631. if (dtd.tableType != 0) return ERROR(GENERIC);
  1632. return HUFv07_decompress4X2_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable);
  1633. }
  1634. size_t HUFv07_decompress4X2_DCtx (HUFv07_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1635. {
  1636. const BYTE* ip = (const BYTE*) cSrc;
  1637. size_t const hSize = HUFv07_readDTableX2 (dctx, cSrc, cSrcSize);
  1638. if (HUFv07_isError(hSize)) return hSize;
  1639. if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
  1640. ip += hSize; cSrcSize -= hSize;
  1641. return HUFv07_decompress4X2_usingDTable_internal (dst, dstSize, ip, cSrcSize, dctx);
  1642. }
  1643. size_t HUFv07_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1644. {
  1645. HUFv07_CREATE_STATIC_DTABLEX2(DTable, HUFv07_TABLELOG_MAX);
  1646. return HUFv07_decompress4X2_DCtx(DTable, dst, dstSize, cSrc, cSrcSize);
  1647. }
  1648. /* *************************/
  1649. /* double-symbols decoding */
  1650. /* *************************/
  1651. typedef struct { U16 sequence; BYTE nbBits; BYTE length; } HUFv07_DEltX4; /* double-symbols decoding */
  1652. typedef struct { BYTE symbol; BYTE weight; } sortedSymbol_t;
  1653. static void HUFv07_fillDTableX4Level2(HUFv07_DEltX4* DTable, U32 sizeLog, const U32 consumed,
  1654. const U32* rankValOrigin, const int minWeight,
  1655. const sortedSymbol_t* sortedSymbols, const U32 sortedListSize,
  1656. U32 nbBitsBaseline, U16 baseSeq)
  1657. {
  1658. HUFv07_DEltX4 DElt;
  1659. U32 rankVal[HUFv07_TABLELOG_ABSOLUTEMAX + 1];
  1660. /* get pre-calculated rankVal */
  1661. memcpy(rankVal, rankValOrigin, sizeof(rankVal));
  1662. /* fill skipped values */
  1663. if (minWeight>1) {
  1664. U32 i, skipSize = rankVal[minWeight];
  1665. MEM_writeLE16(&(DElt.sequence), baseSeq);
  1666. DElt.nbBits = (BYTE)(consumed);
  1667. DElt.length = 1;
  1668. for (i = 0; i < skipSize; i++)
  1669. DTable[i] = DElt;
  1670. }
  1671. /* fill DTable */
  1672. { U32 s; for (s=0; s<sortedListSize; s++) { /* note : sortedSymbols already skipped */
  1673. const U32 symbol = sortedSymbols[s].symbol;
  1674. const U32 weight = sortedSymbols[s].weight;
  1675. const U32 nbBits = nbBitsBaseline - weight;
  1676. const U32 length = 1 << (sizeLog-nbBits);
  1677. const U32 start = rankVal[weight];
  1678. U32 i = start;
  1679. const U32 end = start + length;
  1680. MEM_writeLE16(&(DElt.sequence), (U16)(baseSeq + (symbol << 8)));
  1681. DElt.nbBits = (BYTE)(nbBits + consumed);
  1682. DElt.length = 2;
  1683. do { DTable[i++] = DElt; } while (i<end); /* since length >= 1 */
  1684. rankVal[weight] += length;
  1685. }}
  1686. }
  1687. typedef U32 rankVal_t[HUFv07_TABLELOG_ABSOLUTEMAX][HUFv07_TABLELOG_ABSOLUTEMAX + 1];
  1688. static void HUFv07_fillDTableX4(HUFv07_DEltX4* DTable, const U32 targetLog,
  1689. const sortedSymbol_t* sortedList, const U32 sortedListSize,
  1690. const U32* rankStart, rankVal_t rankValOrigin, const U32 maxWeight,
  1691. const U32 nbBitsBaseline)
  1692. {
  1693. U32 rankVal[HUFv07_TABLELOG_ABSOLUTEMAX + 1];
  1694. const int scaleLog = nbBitsBaseline - targetLog; /* note : targetLog >= srcLog, hence scaleLog <= 1 */
  1695. const U32 minBits = nbBitsBaseline - maxWeight;
  1696. U32 s;
  1697. memcpy(rankVal, rankValOrigin, sizeof(rankVal));
  1698. /* fill DTable */
  1699. for (s=0; s<sortedListSize; s++) {
  1700. const U16 symbol = sortedList[s].symbol;
  1701. const U32 weight = sortedList[s].weight;
  1702. const U32 nbBits = nbBitsBaseline - weight;
  1703. const U32 start = rankVal[weight];
  1704. const U32 length = 1 << (targetLog-nbBits);
  1705. if (targetLog-nbBits >= minBits) { /* enough room for a second symbol */
  1706. U32 sortedRank;
  1707. int minWeight = nbBits + scaleLog;
  1708. if (minWeight < 1) minWeight = 1;
  1709. sortedRank = rankStart[minWeight];
  1710. HUFv07_fillDTableX4Level2(DTable+start, targetLog-nbBits, nbBits,
  1711. rankValOrigin[nbBits], minWeight,
  1712. sortedList+sortedRank, sortedListSize-sortedRank,
  1713. nbBitsBaseline, symbol);
  1714. } else {
  1715. HUFv07_DEltX4 DElt;
  1716. MEM_writeLE16(&(DElt.sequence), symbol);
  1717. DElt.nbBits = (BYTE)(nbBits);
  1718. DElt.length = 1;
  1719. { U32 u;
  1720. const U32 end = start + length;
  1721. for (u = start; u < end; u++) DTable[u] = DElt;
  1722. } }
  1723. rankVal[weight] += length;
  1724. }
  1725. }
  1726. size_t HUFv07_readDTableX4 (HUFv07_DTable* DTable, const void* src, size_t srcSize)
  1727. {
  1728. BYTE weightList[HUFv07_SYMBOLVALUE_MAX + 1];
  1729. sortedSymbol_t sortedSymbol[HUFv07_SYMBOLVALUE_MAX + 1];
  1730. U32 rankStats[HUFv07_TABLELOG_ABSOLUTEMAX + 1] = { 0 };
  1731. U32 rankStart0[HUFv07_TABLELOG_ABSOLUTEMAX + 2] = { 0 };
  1732. U32* const rankStart = rankStart0+1;
  1733. rankVal_t rankVal;
  1734. U32 tableLog, maxW, sizeOfSort, nbSymbols;
  1735. DTableDesc dtd = HUFv07_getDTableDesc(DTable);
  1736. U32 const maxTableLog = dtd.maxTableLog;
  1737. size_t iSize;
  1738. void* dtPtr = DTable+1; /* force compiler to avoid strict-aliasing */
  1739. HUFv07_DEltX4* const dt = (HUFv07_DEltX4*)dtPtr;
  1740. HUFv07_STATIC_ASSERT(sizeof(HUFv07_DEltX4) == sizeof(HUFv07_DTable)); /* if compilation fails here, assertion is false */
  1741. if (maxTableLog > HUFv07_TABLELOG_ABSOLUTEMAX) return ERROR(tableLog_tooLarge);
  1742. //memset(weightList, 0, sizeof(weightList)); /* is not necessary, even though some analyzer complain ... */
  1743. iSize = HUFv07_readStats(weightList, HUFv07_SYMBOLVALUE_MAX + 1, rankStats, &nbSymbols, &tableLog, src, srcSize);
  1744. if (HUFv07_isError(iSize)) return iSize;
  1745. /* check result */
  1746. if (tableLog > maxTableLog) return ERROR(tableLog_tooLarge); /* DTable can't fit code depth */
  1747. /* find maxWeight */
  1748. for (maxW = tableLog; rankStats[maxW]==0; maxW--) {} /* necessarily finds a solution before 0 */
  1749. /* Get start index of each weight */
  1750. { U32 w, nextRankStart = 0;
  1751. for (w=1; w<maxW+1; w++) {
  1752. U32 current = nextRankStart;
  1753. nextRankStart += rankStats[w];
  1754. rankStart[w] = current;
  1755. }
  1756. rankStart[0] = nextRankStart; /* put all 0w symbols at the end of sorted list*/
  1757. sizeOfSort = nextRankStart;
  1758. }
  1759. /* sort symbols by weight */
  1760. { U32 s;
  1761. for (s=0; s<nbSymbols; s++) {
  1762. U32 const w = weightList[s];
  1763. U32 const r = rankStart[w]++;
  1764. sortedSymbol[r].symbol = (BYTE)s;
  1765. sortedSymbol[r].weight = (BYTE)w;
  1766. }
  1767. rankStart[0] = 0; /* forget 0w symbols; this is beginning of weight(1) */
  1768. }
  1769. /* Build rankVal */
  1770. { U32* const rankVal0 = rankVal[0];
  1771. { int const rescale = (maxTableLog-tableLog) - 1; /* tableLog <= maxTableLog */
  1772. U32 nextRankVal = 0;
  1773. U32 w;
  1774. for (w=1; w<maxW+1; w++) {
  1775. U32 current = nextRankVal;
  1776. nextRankVal += rankStats[w] << (w+rescale);
  1777. rankVal0[w] = current;
  1778. } }
  1779. { U32 const minBits = tableLog+1 - maxW;
  1780. U32 consumed;
  1781. for (consumed = minBits; consumed < maxTableLog - minBits + 1; consumed++) {
  1782. U32* const rankValPtr = rankVal[consumed];
  1783. U32 w;
  1784. for (w = 1; w < maxW+1; w++) {
  1785. rankValPtr[w] = rankVal0[w] >> consumed;
  1786. } } } }
  1787. HUFv07_fillDTableX4(dt, maxTableLog,
  1788. sortedSymbol, sizeOfSort,
  1789. rankStart0, rankVal, maxW,
  1790. tableLog+1);
  1791. dtd.tableLog = (BYTE)maxTableLog;
  1792. dtd.tableType = 1;
  1793. memcpy(DTable, &dtd, sizeof(dtd));
  1794. return iSize;
  1795. }
  1796. static U32 HUFv07_decodeSymbolX4(void* op, BITv07_DStream_t* DStream, const HUFv07_DEltX4* dt, const U32 dtLog)
  1797. {
  1798. const size_t val = BITv07_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
  1799. memcpy(op, dt+val, 2);
  1800. BITv07_skipBits(DStream, dt[val].nbBits);
  1801. return dt[val].length;
  1802. }
  1803. static U32 HUFv07_decodeLastSymbolX4(void* op, BITv07_DStream_t* DStream, const HUFv07_DEltX4* dt, const U32 dtLog)
  1804. {
  1805. const size_t val = BITv07_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
  1806. memcpy(op, dt+val, 1);
  1807. if (dt[val].length==1) BITv07_skipBits(DStream, dt[val].nbBits);
  1808. else {
  1809. if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8)) {
  1810. BITv07_skipBits(DStream, dt[val].nbBits);
  1811. if (DStream->bitsConsumed > (sizeof(DStream->bitContainer)*8))
  1812. DStream->bitsConsumed = (sizeof(DStream->bitContainer)*8); /* ugly hack; works only because it's the last symbol. Note : can't easily extract nbBits from just this symbol */
  1813. } }
  1814. return 1;
  1815. }
  1816. #define HUFv07_DECODE_SYMBOLX4_0(ptr, DStreamPtr) \
  1817. ptr += HUFv07_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  1818. #define HUFv07_DECODE_SYMBOLX4_1(ptr, DStreamPtr) \
  1819. if (MEM_64bits() || (HUFv07_TABLELOG_MAX<=12)) \
  1820. ptr += HUFv07_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  1821. #define HUFv07_DECODE_SYMBOLX4_2(ptr, DStreamPtr) \
  1822. if (MEM_64bits()) \
  1823. ptr += HUFv07_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  1824. static inline size_t HUFv07_decodeStreamX4(BYTE* p, BITv07_DStream_t* bitDPtr, BYTE* const pEnd, const HUFv07_DEltX4* const dt, const U32 dtLog)
  1825. {
  1826. BYTE* const pStart = p;
  1827. /* up to 8 symbols at a time */
  1828. while ((BITv07_reloadDStream(bitDPtr) == BITv07_DStream_unfinished) && (p < pEnd-7)) {
  1829. HUFv07_DECODE_SYMBOLX4_2(p, bitDPtr);
  1830. HUFv07_DECODE_SYMBOLX4_1(p, bitDPtr);
  1831. HUFv07_DECODE_SYMBOLX4_2(p, bitDPtr);
  1832. HUFv07_DECODE_SYMBOLX4_0(p, bitDPtr);
  1833. }
  1834. /* closer to end : up to 2 symbols at a time */
  1835. while ((BITv07_reloadDStream(bitDPtr) == BITv07_DStream_unfinished) && (p <= pEnd-2))
  1836. HUFv07_DECODE_SYMBOLX4_0(p, bitDPtr);
  1837. while (p <= pEnd-2)
  1838. HUFv07_DECODE_SYMBOLX4_0(p, bitDPtr); /* no need to reload : reached the end of DStream */
  1839. if (p < pEnd)
  1840. p += HUFv07_decodeLastSymbolX4(p, bitDPtr, dt, dtLog);
  1841. return p-pStart;
  1842. }
  1843. static size_t HUFv07_decompress1X4_usingDTable_internal(
  1844. void* dst, size_t dstSize,
  1845. const void* cSrc, size_t cSrcSize,
  1846. const HUFv07_DTable* DTable)
  1847. {
  1848. BITv07_DStream_t bitD;
  1849. /* Init */
  1850. { size_t const errorCode = BITv07_initDStream(&bitD, cSrc, cSrcSize);
  1851. if (HUFv07_isError(errorCode)) return errorCode;
  1852. }
  1853. /* decode */
  1854. { BYTE* const ostart = (BYTE*) dst;
  1855. BYTE* const oend = ostart + dstSize;
  1856. const void* const dtPtr = DTable+1; /* force compiler to not use strict-aliasing */
  1857. const HUFv07_DEltX4* const dt = (const HUFv07_DEltX4*)dtPtr;
  1858. DTableDesc const dtd = HUFv07_getDTableDesc(DTable);
  1859. HUFv07_decodeStreamX4(ostart, &bitD, oend, dt, dtd.tableLog);
  1860. }
  1861. /* check */
  1862. if (!BITv07_endOfDStream(&bitD)) return ERROR(corruption_detected);
  1863. /* decoded size */
  1864. return dstSize;
  1865. }
  1866. size_t HUFv07_decompress1X4_usingDTable(
  1867. void* dst, size_t dstSize,
  1868. const void* cSrc, size_t cSrcSize,
  1869. const HUFv07_DTable* DTable)
  1870. {
  1871. DTableDesc dtd = HUFv07_getDTableDesc(DTable);
  1872. if (dtd.tableType != 1) return ERROR(GENERIC);
  1873. return HUFv07_decompress1X4_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable);
  1874. }
  1875. size_t HUFv07_decompress1X4_DCtx (HUFv07_DTable* DCtx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1876. {
  1877. const BYTE* ip = (const BYTE*) cSrc;
  1878. size_t const hSize = HUFv07_readDTableX4 (DCtx, cSrc, cSrcSize);
  1879. if (HUFv07_isError(hSize)) return hSize;
  1880. if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
  1881. ip += hSize; cSrcSize -= hSize;
  1882. return HUFv07_decompress1X4_usingDTable_internal (dst, dstSize, ip, cSrcSize, DCtx);
  1883. }
  1884. size_t HUFv07_decompress1X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1885. {
  1886. HUFv07_CREATE_STATIC_DTABLEX4(DTable, HUFv07_TABLELOG_MAX);
  1887. return HUFv07_decompress1X4_DCtx(DTable, dst, dstSize, cSrc, cSrcSize);
  1888. }
  1889. static size_t HUFv07_decompress4X4_usingDTable_internal(
  1890. void* dst, size_t dstSize,
  1891. const void* cSrc, size_t cSrcSize,
  1892. const HUFv07_DTable* DTable)
  1893. {
  1894. if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
  1895. { const BYTE* const istart = (const BYTE*) cSrc;
  1896. BYTE* const ostart = (BYTE*) dst;
  1897. BYTE* const oend = ostart + dstSize;
  1898. const void* const dtPtr = DTable+1;
  1899. const HUFv07_DEltX4* const dt = (const HUFv07_DEltX4*)dtPtr;
  1900. /* Init */
  1901. BITv07_DStream_t bitD1;
  1902. BITv07_DStream_t bitD2;
  1903. BITv07_DStream_t bitD3;
  1904. BITv07_DStream_t bitD4;
  1905. size_t const length1 = MEM_readLE16(istart);
  1906. size_t const length2 = MEM_readLE16(istart+2);
  1907. size_t const length3 = MEM_readLE16(istart+4);
  1908. size_t const length4 = cSrcSize - (length1 + length2 + length3 + 6);
  1909. const BYTE* const istart1 = istart + 6; /* jumpTable */
  1910. const BYTE* const istart2 = istart1 + length1;
  1911. const BYTE* const istart3 = istart2 + length2;
  1912. const BYTE* const istart4 = istart3 + length3;
  1913. size_t const segmentSize = (dstSize+3) / 4;
  1914. BYTE* const opStart2 = ostart + segmentSize;
  1915. BYTE* const opStart3 = opStart2 + segmentSize;
  1916. BYTE* const opStart4 = opStart3 + segmentSize;
  1917. BYTE* op1 = ostart;
  1918. BYTE* op2 = opStart2;
  1919. BYTE* op3 = opStart3;
  1920. BYTE* op4 = opStart4;
  1921. U32 endSignal;
  1922. DTableDesc const dtd = HUFv07_getDTableDesc(DTable);
  1923. U32 const dtLog = dtd.tableLog;
  1924. if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
  1925. { size_t const errorCode = BITv07_initDStream(&bitD1, istart1, length1);
  1926. if (HUFv07_isError(errorCode)) return errorCode; }
  1927. { size_t const errorCode = BITv07_initDStream(&bitD2, istart2, length2);
  1928. if (HUFv07_isError(errorCode)) return errorCode; }
  1929. { size_t const errorCode = BITv07_initDStream(&bitD3, istart3, length3);
  1930. if (HUFv07_isError(errorCode)) return errorCode; }
  1931. { size_t const errorCode = BITv07_initDStream(&bitD4, istart4, length4);
  1932. if (HUFv07_isError(errorCode)) return errorCode; }
  1933. /* 16-32 symbols per loop (4-8 symbols per stream) */
  1934. endSignal = BITv07_reloadDStream(&bitD1) | BITv07_reloadDStream(&bitD2) | BITv07_reloadDStream(&bitD3) | BITv07_reloadDStream(&bitD4);
  1935. for ( ; (endSignal==BITv07_DStream_unfinished) && (op4<(oend-7)) ; ) {
  1936. HUFv07_DECODE_SYMBOLX4_2(op1, &bitD1);
  1937. HUFv07_DECODE_SYMBOLX4_2(op2, &bitD2);
  1938. HUFv07_DECODE_SYMBOLX4_2(op3, &bitD3);
  1939. HUFv07_DECODE_SYMBOLX4_2(op4, &bitD4);
  1940. HUFv07_DECODE_SYMBOLX4_1(op1, &bitD1);
  1941. HUFv07_DECODE_SYMBOLX4_1(op2, &bitD2);
  1942. HUFv07_DECODE_SYMBOLX4_1(op3, &bitD3);
  1943. HUFv07_DECODE_SYMBOLX4_1(op4, &bitD4);
  1944. HUFv07_DECODE_SYMBOLX4_2(op1, &bitD1);
  1945. HUFv07_DECODE_SYMBOLX4_2(op2, &bitD2);
  1946. HUFv07_DECODE_SYMBOLX4_2(op3, &bitD3);
  1947. HUFv07_DECODE_SYMBOLX4_2(op4, &bitD4);
  1948. HUFv07_DECODE_SYMBOLX4_0(op1, &bitD1);
  1949. HUFv07_DECODE_SYMBOLX4_0(op2, &bitD2);
  1950. HUFv07_DECODE_SYMBOLX4_0(op3, &bitD3);
  1951. HUFv07_DECODE_SYMBOLX4_0(op4, &bitD4);
  1952. endSignal = BITv07_reloadDStream(&bitD1) | BITv07_reloadDStream(&bitD2) | BITv07_reloadDStream(&bitD3) | BITv07_reloadDStream(&bitD4);
  1953. }
  1954. /* check corruption */
  1955. if (op1 > opStart2) return ERROR(corruption_detected);
  1956. if (op2 > opStart3) return ERROR(corruption_detected);
  1957. if (op3 > opStart4) return ERROR(corruption_detected);
  1958. /* note : op4 supposed already verified within main loop */
  1959. /* finish bitStreams one by one */
  1960. HUFv07_decodeStreamX4(op1, &bitD1, opStart2, dt, dtLog);
  1961. HUFv07_decodeStreamX4(op2, &bitD2, opStart3, dt, dtLog);
  1962. HUFv07_decodeStreamX4(op3, &bitD3, opStart4, dt, dtLog);
  1963. HUFv07_decodeStreamX4(op4, &bitD4, oend, dt, dtLog);
  1964. /* check */
  1965. { U32 const endCheck = BITv07_endOfDStream(&bitD1) & BITv07_endOfDStream(&bitD2) & BITv07_endOfDStream(&bitD3) & BITv07_endOfDStream(&bitD4);
  1966. if (!endCheck) return ERROR(corruption_detected); }
  1967. /* decoded size */
  1968. return dstSize;
  1969. }
  1970. }
  1971. size_t HUFv07_decompress4X4_usingDTable(
  1972. void* dst, size_t dstSize,
  1973. const void* cSrc, size_t cSrcSize,
  1974. const HUFv07_DTable* DTable)
  1975. {
  1976. DTableDesc dtd = HUFv07_getDTableDesc(DTable);
  1977. if (dtd.tableType != 1) return ERROR(GENERIC);
  1978. return HUFv07_decompress4X4_usingDTable_internal(dst, dstSize, cSrc, cSrcSize, DTable);
  1979. }
  1980. size_t HUFv07_decompress4X4_DCtx (HUFv07_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1981. {
  1982. const BYTE* ip = (const BYTE*) cSrc;
  1983. size_t hSize = HUFv07_readDTableX4 (dctx, cSrc, cSrcSize);
  1984. if (HUFv07_isError(hSize)) return hSize;
  1985. if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
  1986. ip += hSize; cSrcSize -= hSize;
  1987. return HUFv07_decompress4X4_usingDTable_internal(dst, dstSize, ip, cSrcSize, dctx);
  1988. }
  1989. size_t HUFv07_decompress4X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1990. {
  1991. HUFv07_CREATE_STATIC_DTABLEX4(DTable, HUFv07_TABLELOG_MAX);
  1992. return HUFv07_decompress4X4_DCtx(DTable, dst, dstSize, cSrc, cSrcSize);
  1993. }
  1994. /* ********************************/
  1995. /* Generic decompression selector */
  1996. /* ********************************/
  1997. size_t HUFv07_decompress1X_usingDTable(void* dst, size_t maxDstSize,
  1998. const void* cSrc, size_t cSrcSize,
  1999. const HUFv07_DTable* DTable)
  2000. {
  2001. DTableDesc const dtd = HUFv07_getDTableDesc(DTable);
  2002. return dtd.tableType ? HUFv07_decompress1X4_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable) :
  2003. HUFv07_decompress1X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable);
  2004. }
  2005. size_t HUFv07_decompress4X_usingDTable(void* dst, size_t maxDstSize,
  2006. const void* cSrc, size_t cSrcSize,
  2007. const HUFv07_DTable* DTable)
  2008. {
  2009. DTableDesc const dtd = HUFv07_getDTableDesc(DTable);
  2010. return dtd.tableType ? HUFv07_decompress4X4_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable) :
  2011. HUFv07_decompress4X2_usingDTable_internal(dst, maxDstSize, cSrc, cSrcSize, DTable);
  2012. }
  2013. typedef struct { U32 tableTime; U32 decode256Time; } algo_time_t;
  2014. static const algo_time_t algoTime[16 /* Quantization */][3 /* single, double, quad */] =
  2015. {
  2016. /* single, double, quad */
  2017. {{0,0}, {1,1}, {2,2}}, /* Q==0 : impossible */
  2018. {{0,0}, {1,1}, {2,2}}, /* Q==1 : impossible */
  2019. {{ 38,130}, {1313, 74}, {2151, 38}}, /* Q == 2 : 12-18% */
  2020. {{ 448,128}, {1353, 74}, {2238, 41}}, /* Q == 3 : 18-25% */
  2021. {{ 556,128}, {1353, 74}, {2238, 47}}, /* Q == 4 : 25-32% */
  2022. {{ 714,128}, {1418, 74}, {2436, 53}}, /* Q == 5 : 32-38% */
  2023. {{ 883,128}, {1437, 74}, {2464, 61}}, /* Q == 6 : 38-44% */
  2024. {{ 897,128}, {1515, 75}, {2622, 68}}, /* Q == 7 : 44-50% */
  2025. {{ 926,128}, {1613, 75}, {2730, 75}}, /* Q == 8 : 50-56% */
  2026. {{ 947,128}, {1729, 77}, {3359, 77}}, /* Q == 9 : 56-62% */
  2027. {{1107,128}, {2083, 81}, {4006, 84}}, /* Q ==10 : 62-69% */
  2028. {{1177,128}, {2379, 87}, {4785, 88}}, /* Q ==11 : 69-75% */
  2029. {{1242,128}, {2415, 93}, {5155, 84}}, /* Q ==12 : 75-81% */
  2030. {{1349,128}, {2644,106}, {5260,106}}, /* Q ==13 : 81-87% */
  2031. {{1455,128}, {2422,124}, {4174,124}}, /* Q ==14 : 87-93% */
  2032. {{ 722,128}, {1891,145}, {1936,146}}, /* Q ==15 : 93-99% */
  2033. };
  2034. /** HUFv07_selectDecoder() :
  2035. * Tells which decoder is likely to decode faster,
  2036. * based on a set of pre-determined metrics.
  2037. * @return : 0==HUFv07_decompress4X2, 1==HUFv07_decompress4X4 .
  2038. * Assumption : 0 < cSrcSize < dstSize <= 128 KB */
  2039. U32 HUFv07_selectDecoder (size_t dstSize, size_t cSrcSize)
  2040. {
  2041. /* decoder timing evaluation */
  2042. U32 const Q = (U32)(cSrcSize * 16 / dstSize); /* Q < 16 since dstSize > cSrcSize */
  2043. U32 const D256 = (U32)(dstSize >> 8);
  2044. U32 const DTime0 = algoTime[Q][0].tableTime + (algoTime[Q][0].decode256Time * D256);
  2045. U32 DTime1 = algoTime[Q][1].tableTime + (algoTime[Q][1].decode256Time * D256);
  2046. DTime1 += DTime1 >> 3; /* advantage to algorithm using less memory, for cache eviction */
  2047. return DTime1 < DTime0;
  2048. }
  2049. typedef size_t (*decompressionAlgo)(void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);
  2050. size_t HUFv07_decompress (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  2051. {
  2052. static const decompressionAlgo decompress[2] = { HUFv07_decompress4X2, HUFv07_decompress4X4 };
  2053. /* validation checks */
  2054. if (dstSize == 0) return ERROR(dstSize_tooSmall);
  2055. if (cSrcSize > dstSize) return ERROR(corruption_detected); /* invalid */
  2056. if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; } /* not compressed */
  2057. if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */
  2058. { U32 const algoNb = HUFv07_selectDecoder(dstSize, cSrcSize);
  2059. return decompress[algoNb](dst, dstSize, cSrc, cSrcSize);
  2060. }
  2061. //return HUFv07_decompress4X2(dst, dstSize, cSrc, cSrcSize); /* multi-streams single-symbol decoding */
  2062. //return HUFv07_decompress4X4(dst, dstSize, cSrc, cSrcSize); /* multi-streams double-symbols decoding */
  2063. }
  2064. size_t HUFv07_decompress4X_DCtx (HUFv07_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  2065. {
  2066. /* validation checks */
  2067. if (dstSize == 0) return ERROR(dstSize_tooSmall);
  2068. if (cSrcSize > dstSize) return ERROR(corruption_detected); /* invalid */
  2069. if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; } /* not compressed */
  2070. if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */
  2071. { U32 const algoNb = HUFv07_selectDecoder(dstSize, cSrcSize);
  2072. return algoNb ? HUFv07_decompress4X4_DCtx(dctx, dst, dstSize, cSrc, cSrcSize) :
  2073. HUFv07_decompress4X2_DCtx(dctx, dst, dstSize, cSrc, cSrcSize) ;
  2074. }
  2075. }
  2076. size_t HUFv07_decompress4X_hufOnly (HUFv07_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  2077. {
  2078. /* validation checks */
  2079. if (dstSize == 0) return ERROR(dstSize_tooSmall);
  2080. if ((cSrcSize >= dstSize) || (cSrcSize <= 1)) return ERROR(corruption_detected); /* invalid */
  2081. { U32 const algoNb = HUFv07_selectDecoder(dstSize, cSrcSize);
  2082. return algoNb ? HUFv07_decompress4X4_DCtx(dctx, dst, dstSize, cSrc, cSrcSize) :
  2083. HUFv07_decompress4X2_DCtx(dctx, dst, dstSize, cSrc, cSrcSize) ;
  2084. }
  2085. }
  2086. size_t HUFv07_decompress1X_DCtx (HUFv07_DTable* dctx, void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  2087. {
  2088. /* validation checks */
  2089. if (dstSize == 0) return ERROR(dstSize_tooSmall);
  2090. if (cSrcSize > dstSize) return ERROR(corruption_detected); /* invalid */
  2091. if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; } /* not compressed */
  2092. if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */
  2093. { U32 const algoNb = HUFv07_selectDecoder(dstSize, cSrcSize);
  2094. return algoNb ? HUFv07_decompress1X4_DCtx(dctx, dst, dstSize, cSrc, cSrcSize) :
  2095. HUFv07_decompress1X2_DCtx(dctx, dst, dstSize, cSrc, cSrcSize) ;
  2096. }
  2097. }
  2098. /*
  2099. Common functions of Zstd compression library
  2100. Copyright (C) 2015-2016, Yann Collet.
  2101. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  2102. Redistribution and use in source and binary forms, with or without
  2103. modification, are permitted provided that the following conditions are
  2104. met:
  2105. * Redistributions of source code must retain the above copyright
  2106. notice, this list of conditions and the following disclaimer.
  2107. * Redistributions in binary form must reproduce the above
  2108. copyright notice, this list of conditions and the following disclaimer
  2109. in the documentation and/or other materials provided with the
  2110. distribution.
  2111. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2112. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2113. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2114. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2115. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2116. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2117. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2118. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2119. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2120. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2121. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2122. You can contact the author at :
  2123. - zstd homepage : http://www.zstd.net/
  2124. */
  2125. /*-****************************************
  2126. * ZSTD Error Management
  2127. ******************************************/
  2128. /*! ZSTDv07_isError() :
  2129. * tells if a return value is an error code */
  2130. unsigned ZSTDv07_isError(size_t code) { return ERR_isError(code); }
  2131. /*! ZSTDv07_getErrorName() :
  2132. * provides error code string from function result (useful for debugging) */
  2133. const char* ZSTDv07_getErrorName(size_t code) { return ERR_getErrorName(code); }
  2134. /* **************************************************************
  2135. * ZBUFF Error Management
  2136. ****************************************************************/
  2137. unsigned ZBUFFv07_isError(size_t errorCode) { return ERR_isError(errorCode); }
  2138. const char* ZBUFFv07_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
  2139. void* ZSTDv07_defaultAllocFunction(void* opaque, size_t size)
  2140. {
  2141. void* address = malloc(size);
  2142. (void)opaque;
  2143. /* printf("alloc %p, %d opaque=%p \n", address, (int)size, opaque); */
  2144. return address;
  2145. }
  2146. void ZSTDv07_defaultFreeFunction(void* opaque, void* address)
  2147. {
  2148. (void)opaque;
  2149. /* if (address) printf("free %p opaque=%p \n", address, opaque); */
  2150. free(address);
  2151. }
  2152. /*
  2153. zstd_internal - common functions to include
  2154. Header File for include
  2155. Copyright (C) 2014-2016, Yann Collet.
  2156. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  2157. Redistribution and use in source and binary forms, with or without
  2158. modification, are permitted provided that the following conditions are
  2159. met:
  2160. * Redistributions of source code must retain the above copyright
  2161. notice, this list of conditions and the following disclaimer.
  2162. * Redistributions in binary form must reproduce the above
  2163. copyright notice, this list of conditions and the following disclaimer
  2164. in the documentation and/or other materials provided with the
  2165. distribution.
  2166. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2167. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2168. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2169. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2170. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2171. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2172. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2173. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2174. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2175. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2176. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2177. You can contact the author at :
  2178. - zstd homepage : https://www.zstd.net
  2179. */
  2180. #ifndef ZSTDv07_CCOMMON_H_MODULE
  2181. #define ZSTDv07_CCOMMON_H_MODULE
  2182. /*-*************************************
  2183. * Common macros
  2184. ***************************************/
  2185. #define MIN(a,b) ((a)<(b) ? (a) : (b))
  2186. #define MAX(a,b) ((a)>(b) ? (a) : (b))
  2187. /*-*************************************
  2188. * Common constants
  2189. ***************************************/
  2190. #define ZSTDv07_OPT_NUM (1<<12)
  2191. #define ZSTDv07_DICT_MAGIC 0xEC30A437 /* v0.7 */
  2192. #define ZSTDv07_REP_NUM 3
  2193. #define ZSTDv07_REP_INIT ZSTDv07_REP_NUM
  2194. #define ZSTDv07_REP_MOVE (ZSTDv07_REP_NUM-1)
  2195. static const U32 repStartValue[ZSTDv07_REP_NUM] = { 1, 4, 8 };
  2196. #define KB *(1 <<10)
  2197. #define MB *(1 <<20)
  2198. #define GB *(1U<<30)
  2199. #define BIT7 128
  2200. #define BIT6 64
  2201. #define BIT5 32
  2202. #define BIT4 16
  2203. #define BIT1 2
  2204. #define BIT0 1
  2205. #define ZSTDv07_WINDOWLOG_ABSOLUTEMIN 10
  2206. static const size_t ZSTDv07_fcs_fieldSize[4] = { 0, 2, 4, 8 };
  2207. static const size_t ZSTDv07_did_fieldSize[4] = { 0, 1, 2, 4 };
  2208. #define ZSTDv07_BLOCKHEADERSIZE 3 /* C standard doesn't allow `static const` variable to be init using another `static const` variable */
  2209. static const size_t ZSTDv07_blockHeaderSize = ZSTDv07_BLOCKHEADERSIZE;
  2210. typedef enum { bt_compressed, bt_raw, bt_rle, bt_end } blockType_t;
  2211. #define MIN_SEQUENCES_SIZE 1 /* nbSeq==0 */
  2212. #define MIN_CBLOCK_SIZE (1 /*litCSize*/ + 1 /* RLE or RAW */ + MIN_SEQUENCES_SIZE /* nbSeq==0 */) /* for a non-null block */
  2213. #define HufLog 12
  2214. typedef enum { lbt_huffman, lbt_repeat, lbt_raw, lbt_rle } litBlockType_t;
  2215. #define LONGNBSEQ 0x7F00
  2216. #define MINMATCH 3
  2217. #define EQUAL_READ32 4
  2218. #define Litbits 8
  2219. #define MaxLit ((1<<Litbits) - 1)
  2220. #define MaxML 52
  2221. #define MaxLL 35
  2222. #define MaxOff 28
  2223. #define MaxSeq MAX(MaxLL, MaxML) /* Assumption : MaxOff < MaxLL,MaxML */
  2224. #define MLFSELog 9
  2225. #define LLFSELog 9
  2226. #define OffFSELog 8
  2227. #define FSEv07_ENCODING_RAW 0
  2228. #define FSEv07_ENCODING_RLE 1
  2229. #define FSEv07_ENCODING_STATIC 2
  2230. #define FSEv07_ENCODING_DYNAMIC 3
  2231. static const U32 LL_bits[MaxLL+1] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2232. 1, 1, 1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 9,10,11,12,
  2233. 13,14,15,16 };
  2234. static const S16 LL_defaultNorm[MaxLL+1] = { 4, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1,
  2235. 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 1,
  2236. -1,-1,-1,-1 };
  2237. static const U32 LL_defaultNormLog = 6;
  2238. static const U32 ML_bits[MaxML+1] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  2240. 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 8, 9,10,11,
  2241. 12,13,14,15,16 };
  2242. static const S16 ML_defaultNorm[MaxML+1] = { 1, 4, 3, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1,
  2243. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  2244. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,-1,-1,
  2245. -1,-1,-1,-1,-1 };
  2246. static const U32 ML_defaultNormLog = 6;
  2247. static const S16 OF_defaultNorm[MaxOff+1] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1,
  2248. 1, 1, 1, 1, 1, 1, 1, 1,-1,-1,-1,-1,-1 };
  2249. static const U32 OF_defaultNormLog = 5;
  2250. /*-*******************************************
  2251. * Shared functions to include for inlining
  2252. *********************************************/
  2253. static void ZSTDv07_copy8(void* dst, const void* src) { memcpy(dst, src, 8); }
  2254. #define COPY8(d,s) { ZSTDv07_copy8(d,s); d+=8; s+=8; }
  2255. /*! ZSTDv07_wildcopy() :
  2256. * custom version of memcpy(), can copy up to 7 bytes too many (8 bytes if length==0) */
  2257. #define WILDCOPY_OVERLENGTH 8
  2258. MEM_STATIC void ZSTDv07_wildcopy(void* dst, const void* src, ptrdiff_t length)
  2259. {
  2260. const BYTE* ip = (const BYTE*)src;
  2261. BYTE* op = (BYTE*)dst;
  2262. BYTE* const oend = op + length;
  2263. do
  2264. COPY8(op, ip)
  2265. while (op < oend);
  2266. }
  2267. /*-*******************************************
  2268. * Private interfaces
  2269. *********************************************/
  2270. typedef struct ZSTDv07_stats_s ZSTDv07_stats_t;
  2271. typedef struct {
  2272. U32 off;
  2273. U32 len;
  2274. } ZSTDv07_match_t;
  2275. typedef struct {
  2276. U32 price;
  2277. U32 off;
  2278. U32 mlen;
  2279. U32 litlen;
  2280. U32 rep[ZSTDv07_REP_INIT];
  2281. } ZSTDv07_optimal_t;
  2282. struct ZSTDv07_stats_s { U32 unused; };
  2283. typedef struct {
  2284. void* buffer;
  2285. U32* offsetStart;
  2286. U32* offset;
  2287. BYTE* offCodeStart;
  2288. BYTE* litStart;
  2289. BYTE* lit;
  2290. U16* litLengthStart;
  2291. U16* litLength;
  2292. BYTE* llCodeStart;
  2293. U16* matchLengthStart;
  2294. U16* matchLength;
  2295. BYTE* mlCodeStart;
  2296. U32 longLengthID; /* 0 == no longLength; 1 == Lit.longLength; 2 == Match.longLength; */
  2297. U32 longLengthPos;
  2298. /* opt */
  2299. ZSTDv07_optimal_t* priceTable;
  2300. ZSTDv07_match_t* matchTable;
  2301. U32* matchLengthFreq;
  2302. U32* litLengthFreq;
  2303. U32* litFreq;
  2304. U32* offCodeFreq;
  2305. U32 matchLengthSum;
  2306. U32 matchSum;
  2307. U32 litLengthSum;
  2308. U32 litSum;
  2309. U32 offCodeSum;
  2310. U32 log2matchLengthSum;
  2311. U32 log2matchSum;
  2312. U32 log2litLengthSum;
  2313. U32 log2litSum;
  2314. U32 log2offCodeSum;
  2315. U32 factor;
  2316. U32 cachedPrice;
  2317. U32 cachedLitLength;
  2318. const BYTE* cachedLiterals;
  2319. ZSTDv07_stats_t stats;
  2320. } seqStore_t;
  2321. void ZSTDv07_seqToCodes(const seqStore_t* seqStorePtr, size_t const nbSeq);
  2322. /* custom memory allocation functions */
  2323. static const ZSTDv07_customMem defaultCustomMem = { ZSTDv07_defaultAllocFunction, ZSTDv07_defaultFreeFunction, NULL };
  2324. #endif /* ZSTDv07_CCOMMON_H_MODULE */
  2325. /*
  2326. zstd - standard compression library
  2327. Copyright (C) 2014-2016, Yann Collet.
  2328. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  2329. Redistribution and use in source and binary forms, with or without
  2330. modification, are permitted provided that the following conditions are
  2331. met:
  2332. * Redistributions of source code must retain the above copyright
  2333. notice, this list of conditions and the following disclaimer.
  2334. * Redistributions in binary form must reproduce the above
  2335. copyright notice, this list of conditions and the following disclaimer
  2336. in the documentation and/or other materials provided with the
  2337. distribution.
  2338. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2339. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2340. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2341. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2342. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2343. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2344. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2345. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2346. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2347. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2348. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2349. You can contact the author at :
  2350. - zstd homepage : http://www.zstd.net
  2351. */
  2352. /* ***************************************************************
  2353. * Tuning parameters
  2354. *****************************************************************/
  2355. /*!
  2356. * HEAPMODE :
  2357. * Select how default decompression function ZSTDv07_decompress() will allocate memory,
  2358. * in memory stack (0), or in memory heap (1, requires malloc())
  2359. */
  2360. #ifndef ZSTDv07_HEAPMODE
  2361. # define ZSTDv07_HEAPMODE 1
  2362. #endif
  2363. /*-*******************************************************
  2364. * Compiler specifics
  2365. *********************************************************/
  2366. #ifdef _MSC_VER /* Visual Studio */
  2367. # include <intrin.h> /* For Visual 2005 */
  2368. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  2369. # pragma warning(disable : 4324) /* disable: C4324: padded structure */
  2370. # pragma warning(disable : 4100) /* disable: C4100: unreferenced formal parameter */
  2371. #endif
  2372. /*-*************************************
  2373. * Macros
  2374. ***************************************/
  2375. #define ZSTDv07_isError ERR_isError /* for inlining */
  2376. #define FSEv07_isError ERR_isError
  2377. #define HUFv07_isError ERR_isError
  2378. /*_*******************************************************
  2379. * Memory operations
  2380. **********************************************************/
  2381. static void ZSTDv07_copy4(void* dst, const void* src) { memcpy(dst, src, 4); }
  2382. /*-*************************************************************
  2383. * Context management
  2384. ***************************************************************/
  2385. typedef enum { ZSTDds_getFrameHeaderSize, ZSTDds_decodeFrameHeader,
  2386. ZSTDds_decodeBlockHeader, ZSTDds_decompressBlock,
  2387. ZSTDds_decodeSkippableHeader, ZSTDds_skipFrame } ZSTDv07_dStage;
  2388. struct ZSTDv07_DCtx_s
  2389. {
  2390. FSEv07_DTable LLTable[FSEv07_DTABLE_SIZE_U32(LLFSELog)];
  2391. FSEv07_DTable OffTable[FSEv07_DTABLE_SIZE_U32(OffFSELog)];
  2392. FSEv07_DTable MLTable[FSEv07_DTABLE_SIZE_U32(MLFSELog)];
  2393. HUFv07_DTable hufTable[HUFv07_DTABLE_SIZE(HufLog)]; /* can accommodate HUFv07_decompress4X */
  2394. const void* previousDstEnd;
  2395. const void* base;
  2396. const void* vBase;
  2397. const void* dictEnd;
  2398. size_t expected;
  2399. U32 rep[3];
  2400. ZSTDv07_frameParams fParams;
  2401. blockType_t bType; /* used in ZSTDv07_decompressContinue(), to transfer blockType between header decoding and block decoding stages */
  2402. ZSTDv07_dStage stage;
  2403. U32 litEntropy;
  2404. U32 fseEntropy;
  2405. XXH64_state_t xxhState;
  2406. size_t headerSize;
  2407. U32 dictID;
  2408. const BYTE* litPtr;
  2409. ZSTDv07_customMem customMem;
  2410. size_t litSize;
  2411. BYTE litBuffer[ZSTDv07_BLOCKSIZE_ABSOLUTEMAX + WILDCOPY_OVERLENGTH];
  2412. BYTE headerBuffer[ZSTDv07_FRAMEHEADERSIZE_MAX];
  2413. }; /* typedef'd to ZSTDv07_DCtx within "zstd_static.h" */
  2414. int ZSTDv07_isSkipFrame(ZSTDv07_DCtx* dctx);
  2415. size_t ZSTDv07_sizeofDCtx (const ZSTDv07_DCtx* dctx) { return sizeof(*dctx); }
  2416. size_t ZSTDv07_estimateDCtxSize(void) { return sizeof(ZSTDv07_DCtx); }
  2417. size_t ZSTDv07_decompressBegin(ZSTDv07_DCtx* dctx)
  2418. {
  2419. dctx->expected = ZSTDv07_frameHeaderSize_min;
  2420. dctx->stage = ZSTDds_getFrameHeaderSize;
  2421. dctx->previousDstEnd = NULL;
  2422. dctx->base = NULL;
  2423. dctx->vBase = NULL;
  2424. dctx->dictEnd = NULL;
  2425. dctx->hufTable[0] = (HUFv07_DTable)((HufLog)*0x1000001);
  2426. dctx->litEntropy = dctx->fseEntropy = 0;
  2427. dctx->dictID = 0;
  2428. { int i; for (i=0; i<ZSTDv07_REP_NUM; i++) dctx->rep[i] = repStartValue[i]; }
  2429. return 0;
  2430. }
  2431. ZSTDv07_DCtx* ZSTDv07_createDCtx_advanced(ZSTDv07_customMem customMem)
  2432. {
  2433. ZSTDv07_DCtx* dctx;
  2434. if (!customMem.customAlloc && !customMem.customFree)
  2435. customMem = defaultCustomMem;
  2436. if (!customMem.customAlloc || !customMem.customFree)
  2437. return NULL;
  2438. dctx = (ZSTDv07_DCtx*) customMem.customAlloc(customMem.opaque, sizeof(ZSTDv07_DCtx));
  2439. if (!dctx) return NULL;
  2440. memcpy(&dctx->customMem, &customMem, sizeof(ZSTDv07_customMem));
  2441. ZSTDv07_decompressBegin(dctx);
  2442. return dctx;
  2443. }
  2444. ZSTDv07_DCtx* ZSTDv07_createDCtx(void)
  2445. {
  2446. return ZSTDv07_createDCtx_advanced(defaultCustomMem);
  2447. }
  2448. size_t ZSTDv07_freeDCtx(ZSTDv07_DCtx* dctx)
  2449. {
  2450. if (dctx==NULL) return 0; /* support free on NULL */
  2451. dctx->customMem.customFree(dctx->customMem.opaque, dctx);
  2452. return 0; /* reserved as a potential error code in the future */
  2453. }
  2454. void ZSTDv07_copyDCtx(ZSTDv07_DCtx* dstDCtx, const ZSTDv07_DCtx* srcDCtx)
  2455. {
  2456. memcpy(dstDCtx, srcDCtx,
  2457. sizeof(ZSTDv07_DCtx) - (ZSTDv07_BLOCKSIZE_ABSOLUTEMAX+WILDCOPY_OVERLENGTH + ZSTDv07_frameHeaderSize_max)); /* no need to copy workspace */
  2458. }
  2459. /*-*************************************************************
  2460. * Decompression section
  2461. ***************************************************************/
  2462. /* Frame format description
  2463. Frame Header - [ Block Header - Block ] - Frame End
  2464. 1) Frame Header
  2465. - 4 bytes - Magic Number : ZSTDv07_MAGICNUMBER (defined within zstd.h)
  2466. - 1 byte - Frame Descriptor
  2467. 2) Block Header
  2468. - 3 bytes, starting with a 2-bits descriptor
  2469. Uncompressed, Compressed, Frame End, unused
  2470. 3) Block
  2471. See Block Format Description
  2472. 4) Frame End
  2473. - 3 bytes, compatible with Block Header
  2474. */
  2475. /* Frame Header :
  2476. 1 byte - FrameHeaderDescription :
  2477. bit 0-1 : dictID (0, 1, 2 or 4 bytes)
  2478. bit 2 : checksumFlag
  2479. bit 3 : reserved (must be zero)
  2480. bit 4 : reserved (unused, can be any value)
  2481. bit 5 : Single Segment (if 1, WindowLog byte is not present)
  2482. bit 6-7 : FrameContentFieldSize (0, 2, 4, or 8)
  2483. if (SkippedWindowLog && !FrameContentFieldsize) FrameContentFieldsize=1;
  2484. Optional : WindowLog (0 or 1 byte)
  2485. bit 0-2 : octal Fractional (1/8th)
  2486. bit 3-7 : Power of 2, with 0 = 1 KB (up to 2 TB)
  2487. Optional : dictID (0, 1, 2 or 4 bytes)
  2488. Automatic adaptation
  2489. 0 : no dictID
  2490. 1 : 1 - 255
  2491. 2 : 256 - 65535
  2492. 4 : all other values
  2493. Optional : content size (0, 1, 2, 4 or 8 bytes)
  2494. 0 : unknown (fcfs==0 and swl==0)
  2495. 1 : 0-255 bytes (fcfs==0 and swl==1)
  2496. 2 : 256 - 65535+256 (fcfs==1)
  2497. 4 : 0 - 4GB-1 (fcfs==2)
  2498. 8 : 0 - 16EB-1 (fcfs==3)
  2499. */
  2500. /* Compressed Block, format description
  2501. Block = Literal Section - Sequences Section
  2502. Prerequisite : size of (compressed) block, maximum size of regenerated data
  2503. 1) Literal Section
  2504. 1.1) Header : 1-5 bytes
  2505. flags: 2 bits
  2506. 00 compressed by Huff0
  2507. 01 unused
  2508. 10 is Raw (uncompressed)
  2509. 11 is Rle
  2510. Note : using 01 => Huff0 with precomputed table ?
  2511. Note : delta map ? => compressed ?
  2512. 1.1.1) Huff0-compressed literal block : 3-5 bytes
  2513. srcSize < 1 KB => 3 bytes (2-2-10-10) => single stream
  2514. srcSize < 1 KB => 3 bytes (2-2-10-10)
  2515. srcSize < 16KB => 4 bytes (2-2-14-14)
  2516. else => 5 bytes (2-2-18-18)
  2517. big endian convention
  2518. 1.1.2) Raw (uncompressed) literal block header : 1-3 bytes
  2519. size : 5 bits: (IS_RAW<<6) + (0<<4) + size
  2520. 12 bits: (IS_RAW<<6) + (2<<4) + (size>>8)
  2521. size&255
  2522. 20 bits: (IS_RAW<<6) + (3<<4) + (size>>16)
  2523. size>>8&255
  2524. size&255
  2525. 1.1.3) Rle (repeated single byte) literal block header : 1-3 bytes
  2526. size : 5 bits: (IS_RLE<<6) + (0<<4) + size
  2527. 12 bits: (IS_RLE<<6) + (2<<4) + (size>>8)
  2528. size&255
  2529. 20 bits: (IS_RLE<<6) + (3<<4) + (size>>16)
  2530. size>>8&255
  2531. size&255
  2532. 1.1.4) Huff0-compressed literal block, using precomputed CTables : 3-5 bytes
  2533. srcSize < 1 KB => 3 bytes (2-2-10-10) => single stream
  2534. srcSize < 1 KB => 3 bytes (2-2-10-10)
  2535. srcSize < 16KB => 4 bytes (2-2-14-14)
  2536. else => 5 bytes (2-2-18-18)
  2537. big endian convention
  2538. 1- CTable available (stored into workspace ?)
  2539. 2- Small input (fast heuristic ? Full comparison ? depend on clevel ?)
  2540. 1.2) Literal block content
  2541. 1.2.1) Huff0 block, using sizes from header
  2542. See Huff0 format
  2543. 1.2.2) Huff0 block, using prepared table
  2544. 1.2.3) Raw content
  2545. 1.2.4) single byte
  2546. 2) Sequences section
  2547. TO DO
  2548. */
  2549. /** ZSTDv07_frameHeaderSize() :
  2550. * srcSize must be >= ZSTDv07_frameHeaderSize_min.
  2551. * @return : size of the Frame Header */
  2552. static size_t ZSTDv07_frameHeaderSize(const void* src, size_t srcSize)
  2553. {
  2554. if (srcSize < ZSTDv07_frameHeaderSize_min) return ERROR(srcSize_wrong);
  2555. { BYTE const fhd = ((const BYTE*)src)[4];
  2556. U32 const dictID= fhd & 3;
  2557. U32 const directMode = (fhd >> 5) & 1;
  2558. U32 const fcsId = fhd >> 6;
  2559. return ZSTDv07_frameHeaderSize_min + !directMode + ZSTDv07_did_fieldSize[dictID] + ZSTDv07_fcs_fieldSize[fcsId]
  2560. + (directMode && !ZSTDv07_fcs_fieldSize[fcsId]);
  2561. }
  2562. }
  2563. /** ZSTDv07_getFrameParams() :
  2564. * decode Frame Header, or require larger `srcSize`.
  2565. * @return : 0, `fparamsPtr` is correctly filled,
  2566. * >0, `srcSize` is too small, result is expected `srcSize`,
  2567. * or an error code, which can be tested using ZSTDv07_isError() */
  2568. size_t ZSTDv07_getFrameParams(ZSTDv07_frameParams* fparamsPtr, const void* src, size_t srcSize)
  2569. {
  2570. const BYTE* ip = (const BYTE*)src;
  2571. if (srcSize < ZSTDv07_frameHeaderSize_min) return ZSTDv07_frameHeaderSize_min;
  2572. if (MEM_readLE32(src) != ZSTDv07_MAGICNUMBER) {
  2573. if ((MEM_readLE32(src) & 0xFFFFFFF0U) == ZSTDv07_MAGIC_SKIPPABLE_START) {
  2574. if (srcSize < ZSTDv07_skippableHeaderSize) return ZSTDv07_skippableHeaderSize; /* magic number + skippable frame length */
  2575. memset(fparamsPtr, 0, sizeof(*fparamsPtr));
  2576. fparamsPtr->frameContentSize = MEM_readLE32((const char *)src + 4);
  2577. fparamsPtr->windowSize = 0; /* windowSize==0 means a frame is skippable */
  2578. return 0;
  2579. }
  2580. return ERROR(prefix_unknown);
  2581. }
  2582. /* ensure there is enough `srcSize` to fully read/decode frame header */
  2583. { size_t const fhsize = ZSTDv07_frameHeaderSize(src, srcSize);
  2584. if (srcSize < fhsize) return fhsize; }
  2585. { BYTE const fhdByte = ip[4];
  2586. size_t pos = 5;
  2587. U32 const dictIDSizeCode = fhdByte&3;
  2588. U32 const checksumFlag = (fhdByte>>2)&1;
  2589. U32 const directMode = (fhdByte>>5)&1;
  2590. U32 const fcsID = fhdByte>>6;
  2591. U32 const windowSizeMax = 1U << ZSTDv07_WINDOWLOG_MAX;
  2592. U32 windowSize = 0;
  2593. U32 dictID = 0;
  2594. U64 frameContentSize = 0;
  2595. if ((fhdByte & 0x08) != 0) return ERROR(frameParameter_unsupported); /* reserved bits, which must be zero */
  2596. if (!directMode) {
  2597. BYTE const wlByte = ip[pos++];
  2598. U32 const windowLog = (wlByte >> 3) + ZSTDv07_WINDOWLOG_ABSOLUTEMIN;
  2599. if (windowLog > ZSTDv07_WINDOWLOG_MAX) return ERROR(frameParameter_unsupported);
  2600. windowSize = (1U << windowLog);
  2601. windowSize += (windowSize >> 3) * (wlByte&7);
  2602. }
  2603. switch(dictIDSizeCode)
  2604. {
  2605. default: /* impossible */
  2606. case 0 : break;
  2607. case 1 : dictID = ip[pos]; pos++; break;
  2608. case 2 : dictID = MEM_readLE16(ip+pos); pos+=2; break;
  2609. case 3 : dictID = MEM_readLE32(ip+pos); pos+=4; break;
  2610. }
  2611. switch(fcsID)
  2612. {
  2613. default: /* impossible */
  2614. case 0 : if (directMode) frameContentSize = ip[pos]; break;
  2615. case 1 : frameContentSize = MEM_readLE16(ip+pos)+256; break;
  2616. case 2 : frameContentSize = MEM_readLE32(ip+pos); break;
  2617. case 3 : frameContentSize = MEM_readLE64(ip+pos); break;
  2618. }
  2619. if (!windowSize) windowSize = (U32)frameContentSize;
  2620. if (windowSize > windowSizeMax) return ERROR(frameParameter_unsupported);
  2621. fparamsPtr->frameContentSize = frameContentSize;
  2622. fparamsPtr->windowSize = windowSize;
  2623. fparamsPtr->dictID = dictID;
  2624. fparamsPtr->checksumFlag = checksumFlag;
  2625. }
  2626. return 0;
  2627. }
  2628. /** ZSTDv07_getDecompressedSize() :
  2629. * compatible with legacy mode
  2630. * @return : decompressed size if known, 0 otherwise
  2631. note : 0 can mean any of the following :
  2632. - decompressed size is not provided within frame header
  2633. - frame header unknown / not supported
  2634. - frame header not completely provided (`srcSize` too small) */
  2635. unsigned long long ZSTDv07_getDecompressedSize(const void* src, size_t srcSize)
  2636. {
  2637. { ZSTDv07_frameParams fparams;
  2638. size_t const frResult = ZSTDv07_getFrameParams(&fparams, src, srcSize);
  2639. if (frResult!=0) return 0;
  2640. return fparams.frameContentSize;
  2641. }
  2642. }
  2643. /** ZSTDv07_decodeFrameHeader() :
  2644. * `srcSize` must be the size provided by ZSTDv07_frameHeaderSize().
  2645. * @return : 0 if success, or an error code, which can be tested using ZSTDv07_isError() */
  2646. static size_t ZSTDv07_decodeFrameHeader(ZSTDv07_DCtx* dctx, const void* src, size_t srcSize)
  2647. {
  2648. size_t const result = ZSTDv07_getFrameParams(&(dctx->fParams), src, srcSize);
  2649. if (dctx->fParams.dictID && (dctx->dictID != dctx->fParams.dictID)) return ERROR(dictionary_wrong);
  2650. if (dctx->fParams.checksumFlag) XXH64_reset(&dctx->xxhState, 0);
  2651. return result;
  2652. }
  2653. typedef struct
  2654. {
  2655. blockType_t blockType;
  2656. U32 origSize;
  2657. } blockProperties_t;
  2658. /*! ZSTDv07_getcBlockSize() :
  2659. * Provides the size of compressed block from block header `src` */
  2660. size_t ZSTDv07_getcBlockSize(const void* src, size_t srcSize, blockProperties_t* bpPtr)
  2661. {
  2662. const BYTE* const in = (const BYTE* const)src;
  2663. U32 cSize;
  2664. if (srcSize < ZSTDv07_blockHeaderSize) return ERROR(srcSize_wrong);
  2665. bpPtr->blockType = (blockType_t)((*in) >> 6);
  2666. cSize = in[2] + (in[1]<<8) + ((in[0] & 7)<<16);
  2667. bpPtr->origSize = (bpPtr->blockType == bt_rle) ? cSize : 0;
  2668. if (bpPtr->blockType == bt_end) return 0;
  2669. if (bpPtr->blockType == bt_rle) return 1;
  2670. return cSize;
  2671. }
  2672. static size_t ZSTDv07_copyRawBlock(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  2673. {
  2674. if (srcSize > dstCapacity) return ERROR(dstSize_tooSmall);
  2675. memcpy(dst, src, srcSize);
  2676. return srcSize;
  2677. }
  2678. /*! ZSTDv07_decodeLiteralsBlock() :
  2679. @return : nb of bytes read from src (< srcSize ) */
  2680. size_t ZSTDv07_decodeLiteralsBlock(ZSTDv07_DCtx* dctx,
  2681. const void* src, size_t srcSize) /* note : srcSize < BLOCKSIZE */
  2682. {
  2683. const BYTE* const istart = (const BYTE*) src;
  2684. if (srcSize < MIN_CBLOCK_SIZE) return ERROR(corruption_detected);
  2685. switch((litBlockType_t)(istart[0]>> 6))
  2686. {
  2687. case lbt_huffman:
  2688. { size_t litSize, litCSize, singleStream=0;
  2689. U32 lhSize = (istart[0] >> 4) & 3;
  2690. if (srcSize < 5) return ERROR(corruption_detected); /* srcSize >= MIN_CBLOCK_SIZE == 3; here we need up to 5 for lhSize, + cSize (+nbSeq) */
  2691. switch(lhSize)
  2692. {
  2693. case 0: case 1: default: /* note : default is impossible, since lhSize into [0..3] */
  2694. /* 2 - 2 - 10 - 10 */
  2695. lhSize=3;
  2696. singleStream = istart[0] & 16;
  2697. litSize = ((istart[0] & 15) << 6) + (istart[1] >> 2);
  2698. litCSize = ((istart[1] & 3) << 8) + istart[2];
  2699. break;
  2700. case 2:
  2701. /* 2 - 2 - 14 - 14 */
  2702. lhSize=4;
  2703. litSize = ((istart[0] & 15) << 10) + (istart[1] << 2) + (istart[2] >> 6);
  2704. litCSize = ((istart[2] & 63) << 8) + istart[3];
  2705. break;
  2706. case 3:
  2707. /* 2 - 2 - 18 - 18 */
  2708. lhSize=5;
  2709. litSize = ((istart[0] & 15) << 14) + (istart[1] << 6) + (istart[2] >> 2);
  2710. litCSize = ((istart[2] & 3) << 16) + (istart[3] << 8) + istart[4];
  2711. break;
  2712. }
  2713. if (litSize > ZSTDv07_BLOCKSIZE_ABSOLUTEMAX) return ERROR(corruption_detected);
  2714. if (litCSize + lhSize > srcSize) return ERROR(corruption_detected);
  2715. if (HUFv07_isError(singleStream ?
  2716. HUFv07_decompress1X2_DCtx(dctx->hufTable, dctx->litBuffer, litSize, istart+lhSize, litCSize) :
  2717. HUFv07_decompress4X_hufOnly (dctx->hufTable, dctx->litBuffer, litSize, istart+lhSize, litCSize) ))
  2718. return ERROR(corruption_detected);
  2719. dctx->litPtr = dctx->litBuffer;
  2720. dctx->litSize = litSize;
  2721. dctx->litEntropy = 1;
  2722. memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
  2723. return litCSize + lhSize;
  2724. }
  2725. case lbt_repeat:
  2726. { size_t litSize, litCSize;
  2727. U32 lhSize = ((istart[0]) >> 4) & 3;
  2728. if (lhSize != 1) /* only case supported for now : small litSize, single stream */
  2729. return ERROR(corruption_detected);
  2730. if (dctx->litEntropy==0)
  2731. return ERROR(dictionary_corrupted);
  2732. /* 2 - 2 - 10 - 10 */
  2733. lhSize=3;
  2734. litSize = ((istart[0] & 15) << 6) + (istart[1] >> 2);
  2735. litCSize = ((istart[1] & 3) << 8) + istart[2];
  2736. if (litCSize + lhSize > srcSize) return ERROR(corruption_detected);
  2737. { size_t const errorCode = HUFv07_decompress1X4_usingDTable(dctx->litBuffer, litSize, istart+lhSize, litCSize, dctx->hufTable);
  2738. if (HUFv07_isError(errorCode)) return ERROR(corruption_detected);
  2739. }
  2740. dctx->litPtr = dctx->litBuffer;
  2741. dctx->litSize = litSize;
  2742. memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
  2743. return litCSize + lhSize;
  2744. }
  2745. case lbt_raw:
  2746. { size_t litSize;
  2747. U32 lhSize = ((istart[0]) >> 4) & 3;
  2748. switch(lhSize)
  2749. {
  2750. case 0: case 1: default: /* note : default is impossible, since lhSize into [0..3] */
  2751. lhSize=1;
  2752. litSize = istart[0] & 31;
  2753. break;
  2754. case 2:
  2755. litSize = ((istart[0] & 15) << 8) + istart[1];
  2756. break;
  2757. case 3:
  2758. litSize = ((istart[0] & 15) << 16) + (istart[1] << 8) + istart[2];
  2759. break;
  2760. }
  2761. if (lhSize+litSize+WILDCOPY_OVERLENGTH > srcSize) { /* risk reading beyond src buffer with wildcopy */
  2762. if (litSize+lhSize > srcSize) return ERROR(corruption_detected);
  2763. memcpy(dctx->litBuffer, istart+lhSize, litSize);
  2764. dctx->litPtr = dctx->litBuffer;
  2765. dctx->litSize = litSize;
  2766. memset(dctx->litBuffer + dctx->litSize, 0, WILDCOPY_OVERLENGTH);
  2767. return lhSize+litSize;
  2768. }
  2769. /* direct reference into compressed stream */
  2770. dctx->litPtr = istart+lhSize;
  2771. dctx->litSize = litSize;
  2772. return lhSize+litSize;
  2773. }
  2774. case lbt_rle:
  2775. { size_t litSize;
  2776. U32 lhSize = ((istart[0]) >> 4) & 3;
  2777. switch(lhSize)
  2778. {
  2779. case 0: case 1: default: /* note : default is impossible, since lhSize into [0..3] */
  2780. lhSize = 1;
  2781. litSize = istart[0] & 31;
  2782. break;
  2783. case 2:
  2784. litSize = ((istart[0] & 15) << 8) + istart[1];
  2785. break;
  2786. case 3:
  2787. litSize = ((istart[0] & 15) << 16) + (istart[1] << 8) + istart[2];
  2788. if (srcSize<4) return ERROR(corruption_detected); /* srcSize >= MIN_CBLOCK_SIZE == 3; here we need lhSize+1 = 4 */
  2789. break;
  2790. }
  2791. if (litSize > ZSTDv07_BLOCKSIZE_ABSOLUTEMAX) return ERROR(corruption_detected);
  2792. memset(dctx->litBuffer, istart[lhSize], litSize + WILDCOPY_OVERLENGTH);
  2793. dctx->litPtr = dctx->litBuffer;
  2794. dctx->litSize = litSize;
  2795. return lhSize+1;
  2796. }
  2797. default:
  2798. return ERROR(corruption_detected); /* impossible */
  2799. }
  2800. }
  2801. /*! ZSTDv07_buildSeqTable() :
  2802. @return : nb bytes read from src,
  2803. or an error code if it fails, testable with ZSTDv07_isError()
  2804. */
  2805. size_t ZSTDv07_buildSeqTable(FSEv07_DTable* DTable, U32 type, U32 max, U32 maxLog,
  2806. const void* src, size_t srcSize,
  2807. const S16* defaultNorm, U32 defaultLog, U32 flagRepeatTable)
  2808. {
  2809. switch(type)
  2810. {
  2811. case FSEv07_ENCODING_RLE :
  2812. if (!srcSize) return ERROR(srcSize_wrong);
  2813. if ( (*(const BYTE*)src) > max) return ERROR(corruption_detected);
  2814. FSEv07_buildDTable_rle(DTable, *(const BYTE*)src); /* if *src > max, data is corrupted */
  2815. return 1;
  2816. case FSEv07_ENCODING_RAW :
  2817. FSEv07_buildDTable(DTable, defaultNorm, max, defaultLog);
  2818. return 0;
  2819. case FSEv07_ENCODING_STATIC:
  2820. if (!flagRepeatTable) return ERROR(corruption_detected);
  2821. return 0;
  2822. default : /* impossible */
  2823. case FSEv07_ENCODING_DYNAMIC :
  2824. { U32 tableLog;
  2825. S16 norm[MaxSeq+1];
  2826. size_t const headerSize = FSEv07_readNCount(norm, &max, &tableLog, src, srcSize);
  2827. if (FSEv07_isError(headerSize)) return ERROR(corruption_detected);
  2828. if (tableLog > maxLog) return ERROR(corruption_detected);
  2829. FSEv07_buildDTable(DTable, norm, max, tableLog);
  2830. return headerSize;
  2831. } }
  2832. }
  2833. size_t ZSTDv07_decodeSeqHeaders(int* nbSeqPtr,
  2834. FSEv07_DTable* DTableLL, FSEv07_DTable* DTableML, FSEv07_DTable* DTableOffb, U32 flagRepeatTable,
  2835. const void* src, size_t srcSize)
  2836. {
  2837. const BYTE* const istart = (const BYTE* const)src;
  2838. const BYTE* const iend = istart + srcSize;
  2839. const BYTE* ip = istart;
  2840. /* check */
  2841. if (srcSize < MIN_SEQUENCES_SIZE) return ERROR(srcSize_wrong);
  2842. /* SeqHead */
  2843. { int nbSeq = *ip++;
  2844. if (!nbSeq) { *nbSeqPtr=0; return 1; }
  2845. if (nbSeq > 0x7F) {
  2846. if (nbSeq == 0xFF) {
  2847. if (ip+2 > iend) return ERROR(srcSize_wrong);
  2848. nbSeq = MEM_readLE16(ip) + LONGNBSEQ, ip+=2;
  2849. } else {
  2850. if (ip >= iend) return ERROR(srcSize_wrong);
  2851. nbSeq = ((nbSeq-0x80)<<8) + *ip++;
  2852. }
  2853. }
  2854. *nbSeqPtr = nbSeq;
  2855. }
  2856. /* FSE table descriptors */
  2857. { U32 const LLtype = *ip >> 6;
  2858. U32 const OFtype = (*ip >> 4) & 3;
  2859. U32 const MLtype = (*ip >> 2) & 3;
  2860. ip++;
  2861. /* check */
  2862. if (ip > iend-3) return ERROR(srcSize_wrong); /* min : all 3 are "raw", hence no header, but at least xxLog bits per type */
  2863. /* Build DTables */
  2864. { size_t const llhSize = ZSTDv07_buildSeqTable(DTableLL, LLtype, MaxLL, LLFSELog, ip, iend-ip, LL_defaultNorm, LL_defaultNormLog, flagRepeatTable);
  2865. if (ZSTDv07_isError(llhSize)) return ERROR(corruption_detected);
  2866. ip += llhSize;
  2867. }
  2868. { size_t const ofhSize = ZSTDv07_buildSeqTable(DTableOffb, OFtype, MaxOff, OffFSELog, ip, iend-ip, OF_defaultNorm, OF_defaultNormLog, flagRepeatTable);
  2869. if (ZSTDv07_isError(ofhSize)) return ERROR(corruption_detected);
  2870. ip += ofhSize;
  2871. }
  2872. { size_t const mlhSize = ZSTDv07_buildSeqTable(DTableML, MLtype, MaxML, MLFSELog, ip, iend-ip, ML_defaultNorm, ML_defaultNormLog, flagRepeatTable);
  2873. if (ZSTDv07_isError(mlhSize)) return ERROR(corruption_detected);
  2874. ip += mlhSize;
  2875. } }
  2876. return ip-istart;
  2877. }
  2878. typedef struct {
  2879. size_t litLength;
  2880. size_t matchLength;
  2881. size_t offset;
  2882. } seq_t;
  2883. typedef struct {
  2884. BITv07_DStream_t DStream;
  2885. FSEv07_DState_t stateLL;
  2886. FSEv07_DState_t stateOffb;
  2887. FSEv07_DState_t stateML;
  2888. size_t prevOffset[ZSTDv07_REP_INIT];
  2889. } seqState_t;
  2890. static seq_t ZSTDv07_decodeSequence(seqState_t* seqState)
  2891. {
  2892. seq_t seq;
  2893. U32 const llCode = FSEv07_peekSymbol(&(seqState->stateLL));
  2894. U32 const mlCode = FSEv07_peekSymbol(&(seqState->stateML));
  2895. U32 const ofCode = FSEv07_peekSymbol(&(seqState->stateOffb)); /* <= maxOff, by table construction */
  2896. U32 const llBits = LL_bits[llCode];
  2897. U32 const mlBits = ML_bits[mlCode];
  2898. U32 const ofBits = ofCode;
  2899. U32 const totalBits = llBits+mlBits+ofBits;
  2900. static const U32 LL_base[MaxLL+1] = {
  2901. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  2902. 16, 18, 20, 22, 24, 28, 32, 40, 48, 64, 0x80, 0x100, 0x200, 0x400, 0x800, 0x1000,
  2903. 0x2000, 0x4000, 0x8000, 0x10000 };
  2904. static const U32 ML_base[MaxML+1] = {
  2905. 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
  2906. 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
  2907. 35, 37, 39, 41, 43, 47, 51, 59, 67, 83, 99, 0x83, 0x103, 0x203, 0x403, 0x803,
  2908. 0x1003, 0x2003, 0x4003, 0x8003, 0x10003 };
  2909. static const U32 OF_base[MaxOff+1] = {
  2910. 0, 1, 1, 5, 0xD, 0x1D, 0x3D, 0x7D,
  2911. 0xFD, 0x1FD, 0x3FD, 0x7FD, 0xFFD, 0x1FFD, 0x3FFD, 0x7FFD,
  2912. 0xFFFD, 0x1FFFD, 0x3FFFD, 0x7FFFD, 0xFFFFD, 0x1FFFFD, 0x3FFFFD, 0x7FFFFD,
  2913. 0xFFFFFD, 0x1FFFFFD, 0x3FFFFFD, 0x7FFFFFD, 0xFFFFFFD };
  2914. /* sequence */
  2915. { size_t offset;
  2916. if (!ofCode)
  2917. offset = 0;
  2918. else {
  2919. offset = OF_base[ofCode] + BITv07_readBits(&(seqState->DStream), ofBits); /* <= (ZSTDv07_WINDOWLOG_MAX-1) bits */
  2920. if (MEM_32bits()) BITv07_reloadDStream(&(seqState->DStream));
  2921. }
  2922. if (ofCode <= 1) {
  2923. if ((llCode == 0) & (offset <= 1)) offset = 1-offset;
  2924. if (offset) {
  2925. size_t const temp = seqState->prevOffset[offset];
  2926. if (offset != 1) seqState->prevOffset[2] = seqState->prevOffset[1];
  2927. seqState->prevOffset[1] = seqState->prevOffset[0];
  2928. seqState->prevOffset[0] = offset = temp;
  2929. } else {
  2930. offset = seqState->prevOffset[0];
  2931. }
  2932. } else {
  2933. seqState->prevOffset[2] = seqState->prevOffset[1];
  2934. seqState->prevOffset[1] = seqState->prevOffset[0];
  2935. seqState->prevOffset[0] = offset;
  2936. }
  2937. seq.offset = offset;
  2938. }
  2939. seq.matchLength = ML_base[mlCode] + ((mlCode>31) ? BITv07_readBits(&(seqState->DStream), mlBits) : 0); /* <= 16 bits */
  2940. if (MEM_32bits() && (mlBits+llBits>24)) BITv07_reloadDStream(&(seqState->DStream));
  2941. seq.litLength = LL_base[llCode] + ((llCode>15) ? BITv07_readBits(&(seqState->DStream), llBits) : 0); /* <= 16 bits */
  2942. if (MEM_32bits() ||
  2943. (totalBits > 64 - 7 - (LLFSELog+MLFSELog+OffFSELog)) ) BITv07_reloadDStream(&(seqState->DStream));
  2944. /* ANS state update */
  2945. FSEv07_updateState(&(seqState->stateLL), &(seqState->DStream)); /* <= 9 bits */
  2946. FSEv07_updateState(&(seqState->stateML), &(seqState->DStream)); /* <= 9 bits */
  2947. if (MEM_32bits()) BITv07_reloadDStream(&(seqState->DStream)); /* <= 18 bits */
  2948. FSEv07_updateState(&(seqState->stateOffb), &(seqState->DStream)); /* <= 8 bits */
  2949. return seq;
  2950. }
  2951. static
  2952. size_t ZSTDv07_execSequence(BYTE* op,
  2953. BYTE* const oend, seq_t sequence,
  2954. const BYTE** litPtr, const BYTE* const litLimit,
  2955. const BYTE* const base, const BYTE* const vBase, const BYTE* const dictEnd)
  2956. {
  2957. BYTE* const oLitEnd = op + sequence.litLength;
  2958. size_t const sequenceLength = sequence.litLength + sequence.matchLength;
  2959. BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
  2960. BYTE* const oend_w = oend-WILDCOPY_OVERLENGTH;
  2961. const BYTE* const iLitEnd = *litPtr + sequence.litLength;
  2962. const BYTE* match = oLitEnd - sequence.offset;
  2963. /* check */
  2964. if ((oLitEnd>oend_w) | (oMatchEnd>oend)) return ERROR(dstSize_tooSmall); /* last match must start at a minimum distance of WILDCOPY_OVERLENGTH from oend */
  2965. if (iLitEnd > litLimit) return ERROR(corruption_detected); /* over-read beyond lit buffer */
  2966. /* copy Literals */
  2967. ZSTDv07_wildcopy(op, *litPtr, sequence.litLength); /* note : since oLitEnd <= oend-WILDCOPY_OVERLENGTH, no risk of overwrite beyond oend */
  2968. op = oLitEnd;
  2969. *litPtr = iLitEnd; /* update for next sequence */
  2970. /* copy Match */
  2971. if (sequence.offset > (size_t)(oLitEnd - base)) {
  2972. /* offset beyond prefix */
  2973. if (sequence.offset > (size_t)(oLitEnd - vBase)) return ERROR(corruption_detected);
  2974. match = dictEnd - (base-match);
  2975. if (match + sequence.matchLength <= dictEnd) {
  2976. memmove(oLitEnd, match, sequence.matchLength);
  2977. return sequenceLength;
  2978. }
  2979. /* span extDict & currentPrefixSegment */
  2980. { size_t const length1 = dictEnd - match;
  2981. memmove(oLitEnd, match, length1);
  2982. op = oLitEnd + length1;
  2983. sequence.matchLength -= length1;
  2984. match = base;
  2985. if (op > oend_w || sequence.matchLength < MINMATCH) {
  2986. while (op < oMatchEnd) *op++ = *match++;
  2987. return sequenceLength;
  2988. }
  2989. } }
  2990. /* Requirement: op <= oend_w */
  2991. /* match within prefix */
  2992. if (sequence.offset < 8) {
  2993. /* close range match, overlap */
  2994. static const U32 dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */
  2995. static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* substracted */
  2996. int const sub2 = dec64table[sequence.offset];
  2997. op[0] = match[0];
  2998. op[1] = match[1];
  2999. op[2] = match[2];
  3000. op[3] = match[3];
  3001. match += dec32table[sequence.offset];
  3002. ZSTDv07_copy4(op+4, match);
  3003. match -= sub2;
  3004. } else {
  3005. ZSTDv07_copy8(op, match);
  3006. }
  3007. op += 8; match += 8;
  3008. if (oMatchEnd > oend-(16-MINMATCH)) {
  3009. if (op < oend_w) {
  3010. ZSTDv07_wildcopy(op, match, oend_w - op);
  3011. match += oend_w - op;
  3012. op = oend_w;
  3013. }
  3014. while (op < oMatchEnd) *op++ = *match++;
  3015. } else {
  3016. ZSTDv07_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8); /* works even if matchLength < 8 */
  3017. }
  3018. return sequenceLength;
  3019. }
  3020. static size_t ZSTDv07_decompressSequences(
  3021. ZSTDv07_DCtx* dctx,
  3022. void* dst, size_t maxDstSize,
  3023. const void* seqStart, size_t seqSize)
  3024. {
  3025. const BYTE* ip = (const BYTE*)seqStart;
  3026. const BYTE* const iend = ip + seqSize;
  3027. BYTE* const ostart = (BYTE* const)dst;
  3028. BYTE* const oend = ostart + maxDstSize;
  3029. BYTE* op = ostart;
  3030. const BYTE* litPtr = dctx->litPtr;
  3031. const BYTE* const litEnd = litPtr + dctx->litSize;
  3032. FSEv07_DTable* DTableLL = dctx->LLTable;
  3033. FSEv07_DTable* DTableML = dctx->MLTable;
  3034. FSEv07_DTable* DTableOffb = dctx->OffTable;
  3035. const BYTE* const base = (const BYTE*) (dctx->base);
  3036. const BYTE* const vBase = (const BYTE*) (dctx->vBase);
  3037. const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
  3038. int nbSeq;
  3039. /* Build Decoding Tables */
  3040. { size_t const seqHSize = ZSTDv07_decodeSeqHeaders(&nbSeq, DTableLL, DTableML, DTableOffb, dctx->fseEntropy, ip, seqSize);
  3041. if (ZSTDv07_isError(seqHSize)) return seqHSize;
  3042. ip += seqHSize;
  3043. }
  3044. /* Regen sequences */
  3045. if (nbSeq) {
  3046. seqState_t seqState;
  3047. dctx->fseEntropy = 1;
  3048. { U32 i; for (i=0; i<ZSTDv07_REP_INIT; i++) seqState.prevOffset[i] = dctx->rep[i]; }
  3049. { size_t const errorCode = BITv07_initDStream(&(seqState.DStream), ip, iend-ip);
  3050. if (ERR_isError(errorCode)) return ERROR(corruption_detected); }
  3051. FSEv07_initDState(&(seqState.stateLL), &(seqState.DStream), DTableLL);
  3052. FSEv07_initDState(&(seqState.stateOffb), &(seqState.DStream), DTableOffb);
  3053. FSEv07_initDState(&(seqState.stateML), &(seqState.DStream), DTableML);
  3054. for ( ; (BITv07_reloadDStream(&(seqState.DStream)) <= BITv07_DStream_completed) && nbSeq ; ) {
  3055. nbSeq--;
  3056. { seq_t const sequence = ZSTDv07_decodeSequence(&seqState);
  3057. size_t const oneSeqSize = ZSTDv07_execSequence(op, oend, sequence, &litPtr, litEnd, base, vBase, dictEnd);
  3058. if (ZSTDv07_isError(oneSeqSize)) return oneSeqSize;
  3059. op += oneSeqSize;
  3060. } }
  3061. /* check if reached exact end */
  3062. if (nbSeq) return ERROR(corruption_detected);
  3063. /* save reps for next block */
  3064. { U32 i; for (i=0; i<ZSTDv07_REP_INIT; i++) dctx->rep[i] = (U32)(seqState.prevOffset[i]); }
  3065. }
  3066. /* last literal segment */
  3067. { size_t const lastLLSize = litEnd - litPtr;
  3068. //if (litPtr > litEnd) return ERROR(corruption_detected); /* too many literals already used */
  3069. if (lastLLSize > (size_t)(oend-op)) return ERROR(dstSize_tooSmall);
  3070. memcpy(op, litPtr, lastLLSize);
  3071. op += lastLLSize;
  3072. }
  3073. return op-ostart;
  3074. }
  3075. static void ZSTDv07_checkContinuity(ZSTDv07_DCtx* dctx, const void* dst)
  3076. {
  3077. if (dst != dctx->previousDstEnd) { /* not contiguous */
  3078. dctx->dictEnd = dctx->previousDstEnd;
  3079. dctx->vBase = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->base));
  3080. dctx->base = dst;
  3081. dctx->previousDstEnd = dst;
  3082. }
  3083. }
  3084. static size_t ZSTDv07_decompressBlock_internal(ZSTDv07_DCtx* dctx,
  3085. void* dst, size_t dstCapacity,
  3086. const void* src, size_t srcSize)
  3087. { /* blockType == blockCompressed */
  3088. const BYTE* ip = (const BYTE*)src;
  3089. if (srcSize >= ZSTDv07_BLOCKSIZE_ABSOLUTEMAX) return ERROR(srcSize_wrong);
  3090. /* Decode literals sub-block */
  3091. { size_t const litCSize = ZSTDv07_decodeLiteralsBlock(dctx, src, srcSize);
  3092. if (ZSTDv07_isError(litCSize)) return litCSize;
  3093. ip += litCSize;
  3094. srcSize -= litCSize;
  3095. }
  3096. return ZSTDv07_decompressSequences(dctx, dst, dstCapacity, ip, srcSize);
  3097. }
  3098. size_t ZSTDv07_decompressBlock(ZSTDv07_DCtx* dctx,
  3099. void* dst, size_t dstCapacity,
  3100. const void* src, size_t srcSize)
  3101. {
  3102. size_t dSize;
  3103. ZSTDv07_checkContinuity(dctx, dst);
  3104. dSize = ZSTDv07_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize);
  3105. dctx->previousDstEnd = (char*)dst + dSize;
  3106. return dSize;
  3107. }
  3108. /** ZSTDv07_insertBlock() :
  3109. insert `src` block into `dctx` history. Useful to track uncompressed blocks. */
  3110. ZSTDLIBv07_API size_t ZSTDv07_insertBlock(ZSTDv07_DCtx* dctx, const void* blockStart, size_t blockSize)
  3111. {
  3112. ZSTDv07_checkContinuity(dctx, blockStart);
  3113. dctx->previousDstEnd = (const char*)blockStart + blockSize;
  3114. return blockSize;
  3115. }
  3116. size_t ZSTDv07_generateNxBytes(void* dst, size_t dstCapacity, BYTE byte, size_t length)
  3117. {
  3118. if (length > dstCapacity) return ERROR(dstSize_tooSmall);
  3119. memset(dst, byte, length);
  3120. return length;
  3121. }
  3122. /*! ZSTDv07_decompressFrame() :
  3123. * `dctx` must be properly initialized */
  3124. static size_t ZSTDv07_decompressFrame(ZSTDv07_DCtx* dctx,
  3125. void* dst, size_t dstCapacity,
  3126. const void* src, size_t srcSize)
  3127. {
  3128. const BYTE* ip = (const BYTE*)src;
  3129. const BYTE* const iend = ip + srcSize;
  3130. BYTE* const ostart = (BYTE* const)dst;
  3131. BYTE* const oend = ostart + dstCapacity;
  3132. BYTE* op = ostart;
  3133. size_t remainingSize = srcSize;
  3134. /* check */
  3135. if (srcSize < ZSTDv07_frameHeaderSize_min+ZSTDv07_blockHeaderSize) return ERROR(srcSize_wrong);
  3136. /* Frame Header */
  3137. { size_t const frameHeaderSize = ZSTDv07_frameHeaderSize(src, ZSTDv07_frameHeaderSize_min);
  3138. if (ZSTDv07_isError(frameHeaderSize)) return frameHeaderSize;
  3139. if (srcSize < frameHeaderSize+ZSTDv07_blockHeaderSize) return ERROR(srcSize_wrong);
  3140. if (ZSTDv07_decodeFrameHeader(dctx, src, frameHeaderSize)) return ERROR(corruption_detected);
  3141. ip += frameHeaderSize; remainingSize -= frameHeaderSize;
  3142. }
  3143. /* Loop on each block */
  3144. while (1) {
  3145. size_t decodedSize;
  3146. blockProperties_t blockProperties;
  3147. size_t const cBlockSize = ZSTDv07_getcBlockSize(ip, iend-ip, &blockProperties);
  3148. if (ZSTDv07_isError(cBlockSize)) return cBlockSize;
  3149. ip += ZSTDv07_blockHeaderSize;
  3150. remainingSize -= ZSTDv07_blockHeaderSize;
  3151. if (cBlockSize > remainingSize) return ERROR(srcSize_wrong);
  3152. switch(blockProperties.blockType)
  3153. {
  3154. case bt_compressed:
  3155. decodedSize = ZSTDv07_decompressBlock_internal(dctx, op, oend-op, ip, cBlockSize);
  3156. break;
  3157. case bt_raw :
  3158. decodedSize = ZSTDv07_copyRawBlock(op, oend-op, ip, cBlockSize);
  3159. break;
  3160. case bt_rle :
  3161. decodedSize = ZSTDv07_generateNxBytes(op, oend-op, *ip, blockProperties.origSize);
  3162. break;
  3163. case bt_end :
  3164. /* end of frame */
  3165. if (remainingSize) return ERROR(srcSize_wrong);
  3166. decodedSize = 0;
  3167. break;
  3168. default:
  3169. return ERROR(GENERIC); /* impossible */
  3170. }
  3171. if (blockProperties.blockType == bt_end) break; /* bt_end */
  3172. if (ZSTDv07_isError(decodedSize)) return decodedSize;
  3173. if (dctx->fParams.checksumFlag) XXH64_update(&dctx->xxhState, op, decodedSize);
  3174. op += decodedSize;
  3175. ip += cBlockSize;
  3176. remainingSize -= cBlockSize;
  3177. }
  3178. return op-ostart;
  3179. }
  3180. /*! ZSTDv07_decompress_usingPreparedDCtx() :
  3181. * Same as ZSTDv07_decompress_usingDict, but using a reference context `preparedDCtx`, where dictionary has been loaded.
  3182. * It avoids reloading the dictionary each time.
  3183. * `preparedDCtx` must have been properly initialized using ZSTDv07_decompressBegin_usingDict().
  3184. * Requires 2 contexts : 1 for reference (preparedDCtx), which will not be modified, and 1 to run the decompression operation (dctx) */
  3185. size_t ZSTDv07_decompress_usingPreparedDCtx(ZSTDv07_DCtx* dctx, const ZSTDv07_DCtx* refDCtx,
  3186. void* dst, size_t dstCapacity,
  3187. const void* src, size_t srcSize)
  3188. {
  3189. ZSTDv07_copyDCtx(dctx, refDCtx);
  3190. ZSTDv07_checkContinuity(dctx, dst);
  3191. return ZSTDv07_decompressFrame(dctx, dst, dstCapacity, src, srcSize);
  3192. }
  3193. size_t ZSTDv07_decompress_usingDict(ZSTDv07_DCtx* dctx,
  3194. void* dst, size_t dstCapacity,
  3195. const void* src, size_t srcSize,
  3196. const void* dict, size_t dictSize)
  3197. {
  3198. ZSTDv07_decompressBegin_usingDict(dctx, dict, dictSize);
  3199. ZSTDv07_checkContinuity(dctx, dst);
  3200. return ZSTDv07_decompressFrame(dctx, dst, dstCapacity, src, srcSize);
  3201. }
  3202. size_t ZSTDv07_decompressDCtx(ZSTDv07_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  3203. {
  3204. return ZSTDv07_decompress_usingDict(dctx, dst, dstCapacity, src, srcSize, NULL, 0);
  3205. }
  3206. size_t ZSTDv07_decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  3207. {
  3208. #if defined(ZSTDv07_HEAPMODE) && (ZSTDv07_HEAPMODE==1)
  3209. size_t regenSize;
  3210. ZSTDv07_DCtx* const dctx = ZSTDv07_createDCtx();
  3211. if (dctx==NULL) return ERROR(memory_allocation);
  3212. regenSize = ZSTDv07_decompressDCtx(dctx, dst, dstCapacity, src, srcSize);
  3213. ZSTDv07_freeDCtx(dctx);
  3214. return regenSize;
  3215. #else /* stack mode */
  3216. ZSTDv07_DCtx dctx;
  3217. return ZSTDv07_decompressDCtx(&dctx, dst, dstCapacity, src, srcSize);
  3218. #endif
  3219. }
  3220. size_t ZSTDv07_findFrameCompressedSize(const void* src, size_t srcSize)
  3221. {
  3222. const BYTE* ip = (const BYTE*)src;
  3223. size_t remainingSize = srcSize;
  3224. /* check */
  3225. if (srcSize < ZSTDv07_frameHeaderSize_min+ZSTDv07_blockHeaderSize) return ERROR(srcSize_wrong);
  3226. /* Frame Header */
  3227. { size_t const frameHeaderSize = ZSTDv07_frameHeaderSize(src, ZSTDv07_frameHeaderSize_min);
  3228. if (ZSTDv07_isError(frameHeaderSize)) return frameHeaderSize;
  3229. if (MEM_readLE32(src) != ZSTDv07_MAGICNUMBER) return ERROR(prefix_unknown);
  3230. if (srcSize < frameHeaderSize+ZSTDv07_blockHeaderSize) return ERROR(srcSize_wrong);
  3231. ip += frameHeaderSize; remainingSize -= frameHeaderSize;
  3232. }
  3233. /* Loop on each block */
  3234. while (1) {
  3235. blockProperties_t blockProperties;
  3236. size_t const cBlockSize = ZSTDv07_getcBlockSize(ip, remainingSize, &blockProperties);
  3237. if (ZSTDv07_isError(cBlockSize)) return cBlockSize;
  3238. ip += ZSTDv07_blockHeaderSize;
  3239. remainingSize -= ZSTDv07_blockHeaderSize;
  3240. if (blockProperties.blockType == bt_end) break;
  3241. if (cBlockSize > remainingSize) return ERROR(srcSize_wrong);
  3242. ip += cBlockSize;
  3243. remainingSize -= cBlockSize;
  3244. }
  3245. return ip - (const BYTE*)src;
  3246. }
  3247. /*_******************************
  3248. * Streaming Decompression API
  3249. ********************************/
  3250. size_t ZSTDv07_nextSrcSizeToDecompress(ZSTDv07_DCtx* dctx)
  3251. {
  3252. return dctx->expected;
  3253. }
  3254. int ZSTDv07_isSkipFrame(ZSTDv07_DCtx* dctx)
  3255. {
  3256. return dctx->stage == ZSTDds_skipFrame;
  3257. }
  3258. /** ZSTDv07_decompressContinue() :
  3259. * @return : nb of bytes generated into `dst` (necessarily <= `dstCapacity)
  3260. * or an error code, which can be tested using ZSTDv07_isError() */
  3261. size_t ZSTDv07_decompressContinue(ZSTDv07_DCtx* dctx, void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  3262. {
  3263. /* Sanity check */
  3264. if (srcSize != dctx->expected) return ERROR(srcSize_wrong);
  3265. if (dstCapacity) ZSTDv07_checkContinuity(dctx, dst);
  3266. switch (dctx->stage)
  3267. {
  3268. case ZSTDds_getFrameHeaderSize :
  3269. if (srcSize != ZSTDv07_frameHeaderSize_min) return ERROR(srcSize_wrong); /* impossible */
  3270. if ((MEM_readLE32(src) & 0xFFFFFFF0U) == ZSTDv07_MAGIC_SKIPPABLE_START) {
  3271. memcpy(dctx->headerBuffer, src, ZSTDv07_frameHeaderSize_min);
  3272. dctx->expected = ZSTDv07_skippableHeaderSize - ZSTDv07_frameHeaderSize_min; /* magic number + skippable frame length */
  3273. dctx->stage = ZSTDds_decodeSkippableHeader;
  3274. return 0;
  3275. }
  3276. dctx->headerSize = ZSTDv07_frameHeaderSize(src, ZSTDv07_frameHeaderSize_min);
  3277. if (ZSTDv07_isError(dctx->headerSize)) return dctx->headerSize;
  3278. memcpy(dctx->headerBuffer, src, ZSTDv07_frameHeaderSize_min);
  3279. if (dctx->headerSize > ZSTDv07_frameHeaderSize_min) {
  3280. dctx->expected = dctx->headerSize - ZSTDv07_frameHeaderSize_min;
  3281. dctx->stage = ZSTDds_decodeFrameHeader;
  3282. return 0;
  3283. }
  3284. dctx->expected = 0; /* not necessary to copy more */
  3285. /* fall-through */
  3286. case ZSTDds_decodeFrameHeader:
  3287. { size_t result;
  3288. memcpy(dctx->headerBuffer + ZSTDv07_frameHeaderSize_min, src, dctx->expected);
  3289. result = ZSTDv07_decodeFrameHeader(dctx, dctx->headerBuffer, dctx->headerSize);
  3290. if (ZSTDv07_isError(result)) return result;
  3291. dctx->expected = ZSTDv07_blockHeaderSize;
  3292. dctx->stage = ZSTDds_decodeBlockHeader;
  3293. return 0;
  3294. }
  3295. case ZSTDds_decodeBlockHeader:
  3296. { blockProperties_t bp;
  3297. size_t const cBlockSize = ZSTDv07_getcBlockSize(src, ZSTDv07_blockHeaderSize, &bp);
  3298. if (ZSTDv07_isError(cBlockSize)) return cBlockSize;
  3299. if (bp.blockType == bt_end) {
  3300. if (dctx->fParams.checksumFlag) {
  3301. U64 const h64 = XXH64_digest(&dctx->xxhState);
  3302. U32 const h32 = (U32)(h64>>11) & ((1<<22)-1);
  3303. const BYTE* const ip = (const BYTE*)src;
  3304. U32 const check32 = ip[2] + (ip[1] << 8) + ((ip[0] & 0x3F) << 16);
  3305. if (check32 != h32) return ERROR(checksum_wrong);
  3306. }
  3307. dctx->expected = 0;
  3308. dctx->stage = ZSTDds_getFrameHeaderSize;
  3309. } else {
  3310. dctx->expected = cBlockSize;
  3311. dctx->bType = bp.blockType;
  3312. dctx->stage = ZSTDds_decompressBlock;
  3313. }
  3314. return 0;
  3315. }
  3316. case ZSTDds_decompressBlock:
  3317. { size_t rSize;
  3318. switch(dctx->bType)
  3319. {
  3320. case bt_compressed:
  3321. rSize = ZSTDv07_decompressBlock_internal(dctx, dst, dstCapacity, src, srcSize);
  3322. break;
  3323. case bt_raw :
  3324. rSize = ZSTDv07_copyRawBlock(dst, dstCapacity, src, srcSize);
  3325. break;
  3326. case bt_rle :
  3327. return ERROR(GENERIC); /* not yet handled */
  3328. break;
  3329. case bt_end : /* should never happen (filtered at phase 1) */
  3330. rSize = 0;
  3331. break;
  3332. default:
  3333. return ERROR(GENERIC); /* impossible */
  3334. }
  3335. dctx->stage = ZSTDds_decodeBlockHeader;
  3336. dctx->expected = ZSTDv07_blockHeaderSize;
  3337. dctx->previousDstEnd = (char*)dst + rSize;
  3338. if (ZSTDv07_isError(rSize)) return rSize;
  3339. if (dctx->fParams.checksumFlag) XXH64_update(&dctx->xxhState, dst, rSize);
  3340. return rSize;
  3341. }
  3342. case ZSTDds_decodeSkippableHeader:
  3343. { memcpy(dctx->headerBuffer + ZSTDv07_frameHeaderSize_min, src, dctx->expected);
  3344. dctx->expected = MEM_readLE32(dctx->headerBuffer + 4);
  3345. dctx->stage = ZSTDds_skipFrame;
  3346. return 0;
  3347. }
  3348. case ZSTDds_skipFrame:
  3349. { dctx->expected = 0;
  3350. dctx->stage = ZSTDds_getFrameHeaderSize;
  3351. return 0;
  3352. }
  3353. default:
  3354. return ERROR(GENERIC); /* impossible */
  3355. }
  3356. }
  3357. static size_t ZSTDv07_refDictContent(ZSTDv07_DCtx* dctx, const void* dict, size_t dictSize)
  3358. {
  3359. dctx->dictEnd = dctx->previousDstEnd;
  3360. dctx->vBase = (const char*)dict - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->base));
  3361. dctx->base = dict;
  3362. dctx->previousDstEnd = (const char*)dict + dictSize;
  3363. return 0;
  3364. }
  3365. static size_t ZSTDv07_loadEntropy(ZSTDv07_DCtx* dctx, const void* const dict, size_t const dictSize)
  3366. {
  3367. const BYTE* dictPtr = (const BYTE*)dict;
  3368. const BYTE* const dictEnd = dictPtr + dictSize;
  3369. { size_t const hSize = HUFv07_readDTableX4(dctx->hufTable, dict, dictSize);
  3370. if (HUFv07_isError(hSize)) return ERROR(dictionary_corrupted);
  3371. dictPtr += hSize;
  3372. }
  3373. { short offcodeNCount[MaxOff+1];
  3374. U32 offcodeMaxValue=MaxOff, offcodeLog;
  3375. size_t const offcodeHeaderSize = FSEv07_readNCount(offcodeNCount, &offcodeMaxValue, &offcodeLog, dictPtr, dictEnd-dictPtr);
  3376. if (FSEv07_isError(offcodeHeaderSize)) return ERROR(dictionary_corrupted);
  3377. if (offcodeLog > OffFSELog) return ERROR(dictionary_corrupted);
  3378. { size_t const errorCode = FSEv07_buildDTable(dctx->OffTable, offcodeNCount, offcodeMaxValue, offcodeLog);
  3379. if (FSEv07_isError(errorCode)) return ERROR(dictionary_corrupted); }
  3380. dictPtr += offcodeHeaderSize;
  3381. }
  3382. { short matchlengthNCount[MaxML+1];
  3383. unsigned matchlengthMaxValue = MaxML, matchlengthLog;
  3384. size_t const matchlengthHeaderSize = FSEv07_readNCount(matchlengthNCount, &matchlengthMaxValue, &matchlengthLog, dictPtr, dictEnd-dictPtr);
  3385. if (FSEv07_isError(matchlengthHeaderSize)) return ERROR(dictionary_corrupted);
  3386. if (matchlengthLog > MLFSELog) return ERROR(dictionary_corrupted);
  3387. { size_t const errorCode = FSEv07_buildDTable(dctx->MLTable, matchlengthNCount, matchlengthMaxValue, matchlengthLog);
  3388. if (FSEv07_isError(errorCode)) return ERROR(dictionary_corrupted); }
  3389. dictPtr += matchlengthHeaderSize;
  3390. }
  3391. { short litlengthNCount[MaxLL+1];
  3392. unsigned litlengthMaxValue = MaxLL, litlengthLog;
  3393. size_t const litlengthHeaderSize = FSEv07_readNCount(litlengthNCount, &litlengthMaxValue, &litlengthLog, dictPtr, dictEnd-dictPtr);
  3394. if (FSEv07_isError(litlengthHeaderSize)) return ERROR(dictionary_corrupted);
  3395. if (litlengthLog > LLFSELog) return ERROR(dictionary_corrupted);
  3396. { size_t const errorCode = FSEv07_buildDTable(dctx->LLTable, litlengthNCount, litlengthMaxValue, litlengthLog);
  3397. if (FSEv07_isError(errorCode)) return ERROR(dictionary_corrupted); }
  3398. dictPtr += litlengthHeaderSize;
  3399. }
  3400. if (dictPtr+12 > dictEnd) return ERROR(dictionary_corrupted);
  3401. dctx->rep[0] = MEM_readLE32(dictPtr+0); if (dctx->rep[0] == 0 || dctx->rep[0] >= dictSize) return ERROR(dictionary_corrupted);
  3402. dctx->rep[1] = MEM_readLE32(dictPtr+4); if (dctx->rep[1] == 0 || dctx->rep[1] >= dictSize) return ERROR(dictionary_corrupted);
  3403. dctx->rep[2] = MEM_readLE32(dictPtr+8); if (dctx->rep[2] == 0 || dctx->rep[2] >= dictSize) return ERROR(dictionary_corrupted);
  3404. dictPtr += 12;
  3405. dctx->litEntropy = dctx->fseEntropy = 1;
  3406. return dictPtr - (const BYTE*)dict;
  3407. }
  3408. static size_t ZSTDv07_decompress_insertDictionary(ZSTDv07_DCtx* dctx, const void* dict, size_t dictSize)
  3409. {
  3410. if (dictSize < 8) return ZSTDv07_refDictContent(dctx, dict, dictSize);
  3411. { U32 const magic = MEM_readLE32(dict);
  3412. if (magic != ZSTDv07_DICT_MAGIC) {
  3413. return ZSTDv07_refDictContent(dctx, dict, dictSize); /* pure content mode */
  3414. } }
  3415. dctx->dictID = MEM_readLE32((const char*)dict + 4);
  3416. /* load entropy tables */
  3417. dict = (const char*)dict + 8;
  3418. dictSize -= 8;
  3419. { size_t const eSize = ZSTDv07_loadEntropy(dctx, dict, dictSize);
  3420. if (ZSTDv07_isError(eSize)) return ERROR(dictionary_corrupted);
  3421. dict = (const char*)dict + eSize;
  3422. dictSize -= eSize;
  3423. }
  3424. /* reference dictionary content */
  3425. return ZSTDv07_refDictContent(dctx, dict, dictSize);
  3426. }
  3427. size_t ZSTDv07_decompressBegin_usingDict(ZSTDv07_DCtx* dctx, const void* dict, size_t dictSize)
  3428. {
  3429. { size_t const errorCode = ZSTDv07_decompressBegin(dctx);
  3430. if (ZSTDv07_isError(errorCode)) return errorCode; }
  3431. if (dict && dictSize) {
  3432. size_t const errorCode = ZSTDv07_decompress_insertDictionary(dctx, dict, dictSize);
  3433. if (ZSTDv07_isError(errorCode)) return ERROR(dictionary_corrupted);
  3434. }
  3435. return 0;
  3436. }
  3437. struct ZSTDv07_DDict_s {
  3438. void* dict;
  3439. size_t dictSize;
  3440. ZSTDv07_DCtx* refContext;
  3441. }; /* typedef'd tp ZSTDv07_CDict within zstd.h */
  3442. ZSTDv07_DDict* ZSTDv07_createDDict_advanced(const void* dict, size_t dictSize, ZSTDv07_customMem customMem)
  3443. {
  3444. if (!customMem.customAlloc && !customMem.customFree)
  3445. customMem = defaultCustomMem;
  3446. if (!customMem.customAlloc || !customMem.customFree)
  3447. return NULL;
  3448. { ZSTDv07_DDict* const ddict = (ZSTDv07_DDict*) customMem.customAlloc(customMem.opaque, sizeof(*ddict));
  3449. void* const dictContent = customMem.customAlloc(customMem.opaque, dictSize);
  3450. ZSTDv07_DCtx* const dctx = ZSTDv07_createDCtx_advanced(customMem);
  3451. if (!dictContent || !ddict || !dctx) {
  3452. customMem.customFree(customMem.opaque, dictContent);
  3453. customMem.customFree(customMem.opaque, ddict);
  3454. customMem.customFree(customMem.opaque, dctx);
  3455. return NULL;
  3456. }
  3457. memcpy(dictContent, dict, dictSize);
  3458. { size_t const errorCode = ZSTDv07_decompressBegin_usingDict(dctx, dictContent, dictSize);
  3459. if (ZSTDv07_isError(errorCode)) {
  3460. customMem.customFree(customMem.opaque, dictContent);
  3461. customMem.customFree(customMem.opaque, ddict);
  3462. customMem.customFree(customMem.opaque, dctx);
  3463. return NULL;
  3464. } }
  3465. ddict->dict = dictContent;
  3466. ddict->dictSize = dictSize;
  3467. ddict->refContext = dctx;
  3468. return ddict;
  3469. }
  3470. }
  3471. /*! ZSTDv07_createDDict() :
  3472. * Create a digested dictionary, ready to start decompression without startup delay.
  3473. * `dict` can be released after `ZSTDv07_DDict` creation */
  3474. ZSTDv07_DDict* ZSTDv07_createDDict(const void* dict, size_t dictSize)
  3475. {
  3476. ZSTDv07_customMem const allocator = { NULL, NULL, NULL };
  3477. return ZSTDv07_createDDict_advanced(dict, dictSize, allocator);
  3478. }
  3479. size_t ZSTDv07_freeDDict(ZSTDv07_DDict* ddict)
  3480. {
  3481. ZSTDv07_freeFunction const cFree = ddict->refContext->customMem.customFree;
  3482. void* const opaque = ddict->refContext->customMem.opaque;
  3483. ZSTDv07_freeDCtx(ddict->refContext);
  3484. cFree(opaque, ddict->dict);
  3485. cFree(opaque, ddict);
  3486. return 0;
  3487. }
  3488. /*! ZSTDv07_decompress_usingDDict() :
  3489. * Decompression using a pre-digested Dictionary
  3490. * Use dictionary without significant overhead. */
  3491. ZSTDLIBv07_API size_t ZSTDv07_decompress_usingDDict(ZSTDv07_DCtx* dctx,
  3492. void* dst, size_t dstCapacity,
  3493. const void* src, size_t srcSize,
  3494. const ZSTDv07_DDict* ddict)
  3495. {
  3496. return ZSTDv07_decompress_usingPreparedDCtx(dctx, ddict->refContext,
  3497. dst, dstCapacity,
  3498. src, srcSize);
  3499. }
  3500. /*
  3501. Buffered version of Zstd compression library
  3502. Copyright (C) 2015-2016, Yann Collet.
  3503. BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
  3504. Redistribution and use in source and binary forms, with or without
  3505. modification, are permitted provided that the following conditions are
  3506. met:
  3507. * Redistributions of source code must retain the above copyright
  3508. notice, this list of conditions and the following disclaimer.
  3509. * Redistributions in binary form must reproduce the above
  3510. copyright notice, this list of conditions and the following disclaimer
  3511. in the documentation and/or other materials provided with the
  3512. distribution.
  3513. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  3514. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  3515. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  3516. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  3517. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  3518. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  3519. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  3520. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  3521. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  3522. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  3523. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3524. You can contact the author at :
  3525. - zstd homepage : http://www.zstd.net/
  3526. */
  3527. /*-***************************************************************************
  3528. * Streaming decompression howto
  3529. *
  3530. * A ZBUFFv07_DCtx object is required to track streaming operations.
  3531. * Use ZBUFFv07_createDCtx() and ZBUFFv07_freeDCtx() to create/release resources.
  3532. * Use ZBUFFv07_decompressInit() to start a new decompression operation,
  3533. * or ZBUFFv07_decompressInitDictionary() if decompression requires a dictionary.
  3534. * Note that ZBUFFv07_DCtx objects can be re-init multiple times.
  3535. *
  3536. * Use ZBUFFv07_decompressContinue() repetitively to consume your input.
  3537. * *srcSizePtr and *dstCapacityPtr can be any size.
  3538. * The function will report how many bytes were read or written by modifying *srcSizePtr and *dstCapacityPtr.
  3539. * Note that it may not consume the entire input, in which case it's up to the caller to present remaining input again.
  3540. * The content of @dst will be overwritten (up to *dstCapacityPtr) at each function call, so save its content if it matters, or change @dst.
  3541. * @return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to help latency),
  3542. * or 0 when a frame is completely decoded,
  3543. * or an error code, which can be tested using ZBUFFv07_isError().
  3544. *
  3545. * Hint : recommended buffer sizes (not compulsory) : ZBUFFv07_recommendedDInSize() and ZBUFFv07_recommendedDOutSize()
  3546. * output : ZBUFFv07_recommendedDOutSize==128 KB block size is the internal unit, it ensures it's always possible to write a full block when decoded.
  3547. * input : ZBUFFv07_recommendedDInSize == 128KB + 3;
  3548. * just follow indications from ZBUFFv07_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 .
  3549. * *******************************************************************************/
  3550. typedef enum { ZBUFFds_init, ZBUFFds_loadHeader,
  3551. ZBUFFds_read, ZBUFFds_load, ZBUFFds_flush } ZBUFFv07_dStage;
  3552. /* *** Resource management *** */
  3553. struct ZBUFFv07_DCtx_s {
  3554. ZSTDv07_DCtx* zd;
  3555. ZSTDv07_frameParams fParams;
  3556. ZBUFFv07_dStage stage;
  3557. char* inBuff;
  3558. size_t inBuffSize;
  3559. size_t inPos;
  3560. char* outBuff;
  3561. size_t outBuffSize;
  3562. size_t outStart;
  3563. size_t outEnd;
  3564. size_t blockSize;
  3565. BYTE headerBuffer[ZSTDv07_FRAMEHEADERSIZE_MAX];
  3566. size_t lhSize;
  3567. ZSTDv07_customMem customMem;
  3568. }; /* typedef'd to ZBUFFv07_DCtx within "zstd_buffered.h" */
  3569. ZSTDLIBv07_API ZBUFFv07_DCtx* ZBUFFv07_createDCtx_advanced(ZSTDv07_customMem customMem);
  3570. ZBUFFv07_DCtx* ZBUFFv07_createDCtx(void)
  3571. {
  3572. return ZBUFFv07_createDCtx_advanced(defaultCustomMem);
  3573. }
  3574. ZBUFFv07_DCtx* ZBUFFv07_createDCtx_advanced(ZSTDv07_customMem customMem)
  3575. {
  3576. ZBUFFv07_DCtx* zbd;
  3577. if (!customMem.customAlloc && !customMem.customFree)
  3578. customMem = defaultCustomMem;
  3579. if (!customMem.customAlloc || !customMem.customFree)
  3580. return NULL;
  3581. zbd = (ZBUFFv07_DCtx*)customMem.customAlloc(customMem.opaque, sizeof(ZBUFFv07_DCtx));
  3582. if (zbd==NULL) return NULL;
  3583. memset(zbd, 0, sizeof(ZBUFFv07_DCtx));
  3584. memcpy(&zbd->customMem, &customMem, sizeof(ZSTDv07_customMem));
  3585. zbd->zd = ZSTDv07_createDCtx_advanced(customMem);
  3586. if (zbd->zd == NULL) { ZBUFFv07_freeDCtx(zbd); return NULL; }
  3587. zbd->stage = ZBUFFds_init;
  3588. return zbd;
  3589. }
  3590. size_t ZBUFFv07_freeDCtx(ZBUFFv07_DCtx* zbd)
  3591. {
  3592. if (zbd==NULL) return 0; /* support free on null */
  3593. ZSTDv07_freeDCtx(zbd->zd);
  3594. if (zbd->inBuff) zbd->customMem.customFree(zbd->customMem.opaque, zbd->inBuff);
  3595. if (zbd->outBuff) zbd->customMem.customFree(zbd->customMem.opaque, zbd->outBuff);
  3596. zbd->customMem.customFree(zbd->customMem.opaque, zbd);
  3597. return 0;
  3598. }
  3599. /* *** Initialization *** */
  3600. size_t ZBUFFv07_decompressInitDictionary(ZBUFFv07_DCtx* zbd, const void* dict, size_t dictSize)
  3601. {
  3602. zbd->stage = ZBUFFds_loadHeader;
  3603. zbd->lhSize = zbd->inPos = zbd->outStart = zbd->outEnd = 0;
  3604. return ZSTDv07_decompressBegin_usingDict(zbd->zd, dict, dictSize);
  3605. }
  3606. size_t ZBUFFv07_decompressInit(ZBUFFv07_DCtx* zbd)
  3607. {
  3608. return ZBUFFv07_decompressInitDictionary(zbd, NULL, 0);
  3609. }
  3610. /* internal util function */
  3611. MEM_STATIC size_t ZBUFFv07_limitCopy(void* dst, size_t dstCapacity, const void* src, size_t srcSize)
  3612. {
  3613. size_t const length = MIN(dstCapacity, srcSize);
  3614. memcpy(dst, src, length);
  3615. return length;
  3616. }
  3617. /* *** Decompression *** */
  3618. size_t ZBUFFv07_decompressContinue(ZBUFFv07_DCtx* zbd,
  3619. void* dst, size_t* dstCapacityPtr,
  3620. const void* src, size_t* srcSizePtr)
  3621. {
  3622. const char* const istart = (const char*)src;
  3623. const char* const iend = istart + *srcSizePtr;
  3624. const char* ip = istart;
  3625. char* const ostart = (char*)dst;
  3626. char* const oend = ostart + *dstCapacityPtr;
  3627. char* op = ostart;
  3628. U32 notDone = 1;
  3629. while (notDone) {
  3630. switch(zbd->stage)
  3631. {
  3632. case ZBUFFds_init :
  3633. return ERROR(init_missing);
  3634. case ZBUFFds_loadHeader :
  3635. { size_t const hSize = ZSTDv07_getFrameParams(&(zbd->fParams), zbd->headerBuffer, zbd->lhSize);
  3636. if (ZSTDv07_isError(hSize)) return hSize;
  3637. if (hSize != 0) {
  3638. size_t const toLoad = hSize - zbd->lhSize; /* if hSize!=0, hSize > zbd->lhSize */
  3639. if (toLoad > (size_t)(iend-ip)) { /* not enough input to load full header */
  3640. memcpy(zbd->headerBuffer + zbd->lhSize, ip, iend-ip);
  3641. zbd->lhSize += iend-ip;
  3642. *dstCapacityPtr = 0;
  3643. return (hSize - zbd->lhSize) + ZSTDv07_blockHeaderSize; /* remaining header bytes + next block header */
  3644. }
  3645. memcpy(zbd->headerBuffer + zbd->lhSize, ip, toLoad); zbd->lhSize = hSize; ip += toLoad;
  3646. break;
  3647. } }
  3648. /* Consume header */
  3649. { size_t const h1Size = ZSTDv07_nextSrcSizeToDecompress(zbd->zd); /* == ZSTDv07_frameHeaderSize_min */
  3650. size_t const h1Result = ZSTDv07_decompressContinue(zbd->zd, NULL, 0, zbd->headerBuffer, h1Size);
  3651. if (ZSTDv07_isError(h1Result)) return h1Result;
  3652. if (h1Size < zbd->lhSize) { /* long header */
  3653. size_t const h2Size = ZSTDv07_nextSrcSizeToDecompress(zbd->zd);
  3654. size_t const h2Result = ZSTDv07_decompressContinue(zbd->zd, NULL, 0, zbd->headerBuffer+h1Size, h2Size);
  3655. if (ZSTDv07_isError(h2Result)) return h2Result;
  3656. } }
  3657. zbd->fParams.windowSize = MAX(zbd->fParams.windowSize, 1U << ZSTDv07_WINDOWLOG_ABSOLUTEMIN);
  3658. /* Frame header instruct buffer sizes */
  3659. { size_t const blockSize = MIN(zbd->fParams.windowSize, ZSTDv07_BLOCKSIZE_ABSOLUTEMAX);
  3660. zbd->blockSize = blockSize;
  3661. if (zbd->inBuffSize < blockSize) {
  3662. zbd->customMem.customFree(zbd->customMem.opaque, zbd->inBuff);
  3663. zbd->inBuffSize = blockSize;
  3664. zbd->inBuff = (char*)zbd->customMem.customAlloc(zbd->customMem.opaque, blockSize);
  3665. if (zbd->inBuff == NULL) return ERROR(memory_allocation);
  3666. }
  3667. { size_t const neededOutSize = zbd->fParams.windowSize + blockSize + WILDCOPY_OVERLENGTH * 2;
  3668. if (zbd->outBuffSize < neededOutSize) {
  3669. zbd->customMem.customFree(zbd->customMem.opaque, zbd->outBuff);
  3670. zbd->outBuffSize = neededOutSize;
  3671. zbd->outBuff = (char*)zbd->customMem.customAlloc(zbd->customMem.opaque, neededOutSize);
  3672. if (zbd->outBuff == NULL) return ERROR(memory_allocation);
  3673. } } }
  3674. zbd->stage = ZBUFFds_read;
  3675. /* pass-through */
  3676. /* fall-through */
  3677. case ZBUFFds_read:
  3678. { size_t const neededInSize = ZSTDv07_nextSrcSizeToDecompress(zbd->zd);
  3679. if (neededInSize==0) { /* end of frame */
  3680. zbd->stage = ZBUFFds_init;
  3681. notDone = 0;
  3682. break;
  3683. }
  3684. if ((size_t)(iend-ip) >= neededInSize) { /* decode directly from src */
  3685. const int isSkipFrame = ZSTDv07_isSkipFrame(zbd->zd);
  3686. size_t const decodedSize = ZSTDv07_decompressContinue(zbd->zd,
  3687. zbd->outBuff + zbd->outStart, (isSkipFrame ? 0 : zbd->outBuffSize - zbd->outStart),
  3688. ip, neededInSize);
  3689. if (ZSTDv07_isError(decodedSize)) return decodedSize;
  3690. ip += neededInSize;
  3691. if (!decodedSize && !isSkipFrame) break; /* this was just a header */
  3692. zbd->outEnd = zbd->outStart + decodedSize;
  3693. zbd->stage = ZBUFFds_flush;
  3694. break;
  3695. }
  3696. if (ip==iend) { notDone = 0; break; } /* no more input */
  3697. zbd->stage = ZBUFFds_load;
  3698. }
  3699. /* fall-through */
  3700. case ZBUFFds_load:
  3701. { size_t const neededInSize = ZSTDv07_nextSrcSizeToDecompress(zbd->zd);
  3702. size_t const toLoad = neededInSize - zbd->inPos; /* should always be <= remaining space within inBuff */
  3703. size_t loadedSize;
  3704. if (toLoad > zbd->inBuffSize - zbd->inPos) return ERROR(corruption_detected); /* should never happen */
  3705. loadedSize = ZBUFFv07_limitCopy(zbd->inBuff + zbd->inPos, toLoad, ip, iend-ip);
  3706. ip += loadedSize;
  3707. zbd->inPos += loadedSize;
  3708. if (loadedSize < toLoad) { notDone = 0; break; } /* not enough input, wait for more */
  3709. /* decode loaded input */
  3710. { const int isSkipFrame = ZSTDv07_isSkipFrame(zbd->zd);
  3711. size_t const decodedSize = ZSTDv07_decompressContinue(zbd->zd,
  3712. zbd->outBuff + zbd->outStart, zbd->outBuffSize - zbd->outStart,
  3713. zbd->inBuff, neededInSize);
  3714. if (ZSTDv07_isError(decodedSize)) return decodedSize;
  3715. zbd->inPos = 0; /* input is consumed */
  3716. if (!decodedSize && !isSkipFrame) { zbd->stage = ZBUFFds_read; break; } /* this was just a header */
  3717. zbd->outEnd = zbd->outStart + decodedSize;
  3718. zbd->stage = ZBUFFds_flush;
  3719. /* break; */
  3720. /* pass-through */
  3721. }
  3722. }
  3723. /* fall-through */
  3724. case ZBUFFds_flush:
  3725. { size_t const toFlushSize = zbd->outEnd - zbd->outStart;
  3726. size_t const flushedSize = ZBUFFv07_limitCopy(op, oend-op, zbd->outBuff + zbd->outStart, toFlushSize);
  3727. op += flushedSize;
  3728. zbd->outStart += flushedSize;
  3729. if (flushedSize == toFlushSize) {
  3730. zbd->stage = ZBUFFds_read;
  3731. if (zbd->outStart + zbd->blockSize > zbd->outBuffSize)
  3732. zbd->outStart = zbd->outEnd = 0;
  3733. break;
  3734. }
  3735. /* cannot flush everything */
  3736. notDone = 0;
  3737. break;
  3738. }
  3739. default: return ERROR(GENERIC); /* impossible */
  3740. } }
  3741. /* result */
  3742. *srcSizePtr = ip-istart;
  3743. *dstCapacityPtr = op-ostart;
  3744. { size_t nextSrcSizeHint = ZSTDv07_nextSrcSizeToDecompress(zbd->zd);
  3745. nextSrcSizeHint -= zbd->inPos; /* already loaded*/
  3746. return nextSrcSizeHint;
  3747. }
  3748. }
  3749. /* *************************************
  3750. * Tool functions
  3751. ***************************************/
  3752. size_t ZBUFFv07_recommendedDInSize(void) { return ZSTDv07_BLOCKSIZE_ABSOLUTEMAX + ZSTDv07_blockHeaderSize /* block header size*/ ; }
  3753. size_t ZBUFFv07_recommendedDOutSize(void) { return ZSTDv07_BLOCKSIZE_ABSOLUTEMAX; }