zstd_v04.c 129 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598
  1. /*
  2. * Copyright (c) Yann Collet, Meta Platforms, Inc. and affiliates.
  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. /******************************************
  11. * Includes
  12. ******************************************/
  13. #include <stddef.h> /* size_t, ptrdiff_t */
  14. #include <string.h> /* memcpy */
  15. #include "zstd_v04.h"
  16. #include "../common/compiler.h"
  17. #include "../common/error_private.h"
  18. /* ******************************************************************
  19. * mem.h
  20. *******************************************************************/
  21. #ifndef MEM_H_MODULE
  22. #define MEM_H_MODULE
  23. #if defined (__cplusplus)
  24. extern "C" {
  25. #endif
  26. /******************************************
  27. * Compiler-specific
  28. ******************************************/
  29. #if defined(_MSC_VER) /* Visual Studio */
  30. # include <stdlib.h> /* _byteswap_ulong */
  31. # include <intrin.h> /* _byteswap_* */
  32. #endif
  33. /****************************************************************
  34. * Basic Types
  35. *****************************************************************/
  36. #if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  37. # if defined(_AIX)
  38. # include <inttypes.h>
  39. # else
  40. # include <stdint.h> /* intptr_t */
  41. # endif
  42. typedef uint8_t BYTE;
  43. typedef uint16_t U16;
  44. typedef int16_t S16;
  45. typedef uint32_t U32;
  46. typedef int32_t S32;
  47. typedef uint64_t U64;
  48. typedef int64_t S64;
  49. #else
  50. typedef unsigned char BYTE;
  51. typedef unsigned short U16;
  52. typedef signed short S16;
  53. typedef unsigned int U32;
  54. typedef signed int S32;
  55. typedef unsigned long long U64;
  56. typedef signed long long S64;
  57. #endif
  58. /*-*************************************
  59. * Debug
  60. ***************************************/
  61. #include "../common/debug.h"
  62. #ifndef assert
  63. # define assert(condition) ((void)0)
  64. #endif
  65. /****************************************************************
  66. * Memory I/O
  67. *****************************************************************/
  68. MEM_STATIC unsigned MEM_32bits(void) { return sizeof(void*)==4; }
  69. MEM_STATIC unsigned MEM_64bits(void) { return sizeof(void*)==8; }
  70. MEM_STATIC unsigned MEM_isLittleEndian(void)
  71. {
  72. const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
  73. return one.c[0];
  74. }
  75. MEM_STATIC U16 MEM_read16(const void* memPtr)
  76. {
  77. U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
  78. }
  79. MEM_STATIC U32 MEM_read32(const void* memPtr)
  80. {
  81. U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
  82. }
  83. MEM_STATIC U64 MEM_read64(const void* memPtr)
  84. {
  85. U64 val; memcpy(&val, memPtr, sizeof(val)); return val;
  86. }
  87. MEM_STATIC void MEM_write16(void* memPtr, U16 value)
  88. {
  89. memcpy(memPtr, &value, sizeof(value));
  90. }
  91. MEM_STATIC U16 MEM_readLE16(const void* memPtr)
  92. {
  93. if (MEM_isLittleEndian())
  94. return MEM_read16(memPtr);
  95. else
  96. {
  97. const BYTE* p = (const BYTE*)memPtr;
  98. return (U16)(p[0] + (p[1]<<8));
  99. }
  100. }
  101. MEM_STATIC void MEM_writeLE16(void* memPtr, U16 val)
  102. {
  103. if (MEM_isLittleEndian())
  104. {
  105. MEM_write16(memPtr, val);
  106. }
  107. else
  108. {
  109. BYTE* p = (BYTE*)memPtr;
  110. p[0] = (BYTE)val;
  111. p[1] = (BYTE)(val>>8);
  112. }
  113. }
  114. MEM_STATIC U32 MEM_readLE24(const void* memPtr)
  115. {
  116. return MEM_readLE16(memPtr) + (((const BYTE*)memPtr)[2] << 16);
  117. }
  118. MEM_STATIC U32 MEM_readLE32(const void* memPtr)
  119. {
  120. if (MEM_isLittleEndian())
  121. return MEM_read32(memPtr);
  122. else
  123. {
  124. const BYTE* p = (const BYTE*)memPtr;
  125. return (U32)((U32)p[0] + ((U32)p[1]<<8) + ((U32)p[2]<<16) + ((U32)p[3]<<24));
  126. }
  127. }
  128. MEM_STATIC U64 MEM_readLE64(const void* memPtr)
  129. {
  130. if (MEM_isLittleEndian())
  131. return MEM_read64(memPtr);
  132. else
  133. {
  134. const BYTE* p = (const BYTE*)memPtr;
  135. return (U64)((U64)p[0] + ((U64)p[1]<<8) + ((U64)p[2]<<16) + ((U64)p[3]<<24)
  136. + ((U64)p[4]<<32) + ((U64)p[5]<<40) + ((U64)p[6]<<48) + ((U64)p[7]<<56));
  137. }
  138. }
  139. MEM_STATIC size_t MEM_readLEST(const void* memPtr)
  140. {
  141. if (MEM_32bits())
  142. return (size_t)MEM_readLE32(memPtr);
  143. else
  144. return (size_t)MEM_readLE64(memPtr);
  145. }
  146. #if defined (__cplusplus)
  147. }
  148. #endif
  149. #endif /* MEM_H_MODULE */
  150. /*
  151. zstd - standard compression library
  152. Header File for static linking only
  153. */
  154. #ifndef ZSTD_STATIC_H
  155. #define ZSTD_STATIC_H
  156. /* *************************************
  157. * Types
  158. ***************************************/
  159. #define ZSTD_WINDOWLOG_ABSOLUTEMIN 11
  160. /** from faster to stronger */
  161. typedef enum { ZSTD_fast, ZSTD_greedy, ZSTD_lazy, ZSTD_lazy2, ZSTD_btlazy2 } ZSTD_strategy;
  162. typedef struct
  163. {
  164. U64 srcSize; /* optional : tells how much bytes are present in the frame. Use 0 if not known. */
  165. U32 windowLog; /* largest match distance : larger == more compression, more memory needed during decompression */
  166. U32 contentLog; /* full search segment : larger == more compression, slower, more memory (useless for fast) */
  167. U32 hashLog; /* dispatch table : larger == more memory, faster */
  168. U32 searchLog; /* nb of searches : larger == more compression, slower */
  169. U32 searchLength; /* size of matches : larger == faster decompression, sometimes less compression */
  170. ZSTD_strategy strategy;
  171. } ZSTD_parameters;
  172. typedef ZSTDv04_Dctx ZSTD_DCtx;
  173. /* *************************************
  174. * Advanced functions
  175. ***************************************/
  176. /** ZSTD_decompress_usingDict
  177. * Same as ZSTD_decompressDCtx, using a Dictionary content as prefix
  178. * Note : dict can be NULL, in which case, it's equivalent to ZSTD_decompressDCtx() */
  179. static size_t ZSTD_decompress_usingDict(ZSTD_DCtx* ctx,
  180. void* dst, size_t maxDstSize,
  181. const void* src, size_t srcSize,
  182. const void* dict,size_t dictSize);
  183. /* **************************************
  184. * Streaming functions (direct mode)
  185. ****************************************/
  186. static size_t ZSTD_resetDCtx(ZSTD_DCtx* dctx);
  187. static size_t ZSTD_getFrameParams(ZSTD_parameters* params, const void* src, size_t srcSize);
  188. static void ZSTD_decompress_insertDictionary(ZSTD_DCtx* ctx, const void* src, size_t srcSize);
  189. static size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx);
  190. static size_t ZSTD_decompressContinue(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize);
  191. /**
  192. Streaming decompression, bufferless mode
  193. A ZSTD_DCtx object is required to track streaming operations.
  194. Use ZSTD_createDCtx() / ZSTD_freeDCtx() to manage it.
  195. A ZSTD_DCtx object can be re-used multiple times. Use ZSTD_resetDCtx() to return to fresh status.
  196. First operation is to retrieve frame parameters, using ZSTD_getFrameParams().
  197. This function doesn't consume its input. It needs enough input data to properly decode the frame header.
  198. Objective is to retrieve *params.windowlog, to know minimum amount of memory required during decoding.
  199. Result : 0 when successful, it means the ZSTD_parameters structure has been filled.
  200. >0 : means there is not enough data into src. Provides the expected size to successfully decode header.
  201. errorCode, which can be tested using ZSTD_isError() (For example, if it's not a ZSTD header)
  202. Then, you can optionally insert a dictionary.
  203. This operation must mimic the compressor behavior, otherwise decompression will fail or be corrupted.
  204. Then it's possible to start decompression.
  205. Use ZSTD_nextSrcSizeToDecompress() and ZSTD_decompressContinue() alternatively.
  206. ZSTD_nextSrcSizeToDecompress() tells how much bytes to provide as 'srcSize' to ZSTD_decompressContinue().
  207. ZSTD_decompressContinue() requires this exact amount of bytes, or it will fail.
  208. ZSTD_decompressContinue() needs previous data blocks during decompression, up to (1 << windowlog).
  209. They should preferably be located contiguously, prior to current block. Alternatively, a round buffer is also possible.
  210. @result of ZSTD_decompressContinue() is the number of bytes regenerated within 'dst'.
  211. It can be zero, which is not an error; it just means ZSTD_decompressContinue() has decoded some header.
  212. A frame is fully decoded when ZSTD_nextSrcSizeToDecompress() returns zero.
  213. Context can then be reset to start a new decompression.
  214. */
  215. #endif /* ZSTD_STATIC_H */
  216. /*
  217. zstd_internal - common functions to include
  218. Header File for include
  219. */
  220. #ifndef ZSTD_CCOMMON_H_MODULE
  221. #define ZSTD_CCOMMON_H_MODULE
  222. /* *************************************
  223. * Common macros
  224. ***************************************/
  225. #define MIN(a,b) ((a)<(b) ? (a) : (b))
  226. #define MAX(a,b) ((a)>(b) ? (a) : (b))
  227. /* *************************************
  228. * Common constants
  229. ***************************************/
  230. #define ZSTD_MAGICNUMBER 0xFD2FB524 /* v0.4 */
  231. #define KB *(1 <<10)
  232. #define MB *(1 <<20)
  233. #define GB *(1U<<30)
  234. #define BLOCKSIZE (128 KB) /* define, for static allocation */
  235. static const size_t ZSTD_blockHeaderSize = 3;
  236. static const size_t ZSTD_frameHeaderSize_min = 5;
  237. #define ZSTD_frameHeaderSize_max 5 /* define, for static allocation */
  238. #define BIT7 128
  239. #define BIT6 64
  240. #define BIT5 32
  241. #define BIT4 16
  242. #define BIT1 2
  243. #define BIT0 1
  244. #define IS_RAW BIT0
  245. #define IS_RLE BIT1
  246. #define MINMATCH 4
  247. #define REPCODE_STARTVALUE 4
  248. #define MLbits 7
  249. #define LLbits 6
  250. #define Offbits 5
  251. #define MaxML ((1<<MLbits) - 1)
  252. #define MaxLL ((1<<LLbits) - 1)
  253. #define MaxOff ((1<<Offbits)- 1)
  254. #define MLFSELog 10
  255. #define LLFSELog 10
  256. #define OffFSELog 9
  257. #define MaxSeq MAX(MaxLL, MaxML)
  258. #define MIN_SEQUENCES_SIZE (2 /*seqNb*/ + 2 /*dumps*/ + 3 /*seqTables*/ + 1 /*bitStream*/)
  259. #define MIN_CBLOCK_SIZE (3 /*litCSize*/ + MIN_SEQUENCES_SIZE)
  260. #define ZSTD_CONTENTSIZE_ERROR (0ULL - 2)
  261. typedef enum { bt_compressed, bt_raw, bt_rle, bt_end } blockType_t;
  262. /* ******************************************
  263. * Shared functions to include for inlining
  264. ********************************************/
  265. static void ZSTD_copy8(void* dst, const void* src) { memcpy(dst, src, 8); }
  266. #define COPY8(d,s) { ZSTD_copy8(d,s); d+=8; s+=8; }
  267. /*! ZSTD_wildcopy : custom version of memcpy(), can copy up to 7-8 bytes too many */
  268. static void ZSTD_wildcopy(void* dst, const void* src, ptrdiff_t length)
  269. {
  270. const BYTE* ip = (const BYTE*)src;
  271. BYTE* op = (BYTE*)dst;
  272. BYTE* const oend = op + length;
  273. do
  274. COPY8(op, ip)
  275. while (op < oend);
  276. }
  277. /* ******************************************************************
  278. FSE : Finite State Entropy coder
  279. header file
  280. ****************************************************************** */
  281. #ifndef FSE_H
  282. #define FSE_H
  283. #if defined (__cplusplus)
  284. extern "C" {
  285. #endif
  286. /* *****************************************
  287. * Includes
  288. ******************************************/
  289. #include <stddef.h> /* size_t, ptrdiff_t */
  290. /* *****************************************
  291. * FSE simple functions
  292. ******************************************/
  293. static size_t FSE_decompress(void* dst, size_t maxDstSize,
  294. const void* cSrc, size_t cSrcSize);
  295. /*!
  296. FSE_decompress():
  297. Decompress FSE data from buffer 'cSrc', of size 'cSrcSize',
  298. into already allocated destination buffer 'dst', of size 'maxDstSize'.
  299. return : size of regenerated data (<= maxDstSize)
  300. or an error code, which can be tested using FSE_isError()
  301. ** Important ** : FSE_decompress() doesn't decompress non-compressible nor RLE data !!!
  302. Why ? : making this distinction requires a header.
  303. Header management is intentionally delegated to the user layer, which can better manage special cases.
  304. */
  305. /* *****************************************
  306. * Tool functions
  307. ******************************************/
  308. /* Error Management */
  309. static unsigned FSE_isError(size_t code); /* tells if a return value is an error code */
  310. /* *****************************************
  311. * FSE detailed API
  312. ******************************************/
  313. /*!
  314. FSE_compress() does the following:
  315. 1. count symbol occurrence from source[] into table count[]
  316. 2. normalize counters so that sum(count[]) == Power_of_2 (2^tableLog)
  317. 3. save normalized counters to memory buffer using writeNCount()
  318. 4. build encoding table 'CTable' from normalized counters
  319. 5. encode the data stream using encoding table 'CTable'
  320. FSE_decompress() does the following:
  321. 1. read normalized counters with readNCount()
  322. 2. build decoding table 'DTable' from normalized counters
  323. 3. decode the data stream using decoding table 'DTable'
  324. The following API allows targeting specific sub-functions for advanced tasks.
  325. For example, it's possible to compress several blocks using the same 'CTable',
  326. or to save and provide normalized distribution using external method.
  327. */
  328. /* *** DECOMPRESSION *** */
  329. /*!
  330. FSE_readNCount():
  331. Read compactly saved 'normalizedCounter' from 'rBuffer'.
  332. return : size read from 'rBuffer'
  333. or an errorCode, which can be tested using FSE_isError()
  334. maxSymbolValuePtr[0] and tableLogPtr[0] will also be updated with their respective values */
  335. static size_t FSE_readNCount (short* normalizedCounter, unsigned* maxSymbolValuePtr, unsigned* tableLogPtr, const void* rBuffer, size_t rBuffSize);
  336. /*!
  337. Constructor and Destructor of type FSE_DTable
  338. Note that its size depends on 'tableLog' */
  339. typedef unsigned FSE_DTable; /* don't allocate that. It's just a way to be more restrictive than void* */
  340. /*!
  341. FSE_buildDTable():
  342. Builds 'dt', which must be already allocated, using FSE_createDTable()
  343. return : 0,
  344. or an errorCode, which can be tested using FSE_isError() */
  345. static size_t FSE_buildDTable ( FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog);
  346. /*!
  347. FSE_decompress_usingDTable():
  348. Decompress compressed source 'cSrc' of size 'cSrcSize' using 'dt'
  349. into 'dst' which must be already allocated.
  350. return : size of regenerated data (necessarily <= maxDstSize)
  351. or an errorCode, which can be tested using FSE_isError() */
  352. static size_t FSE_decompress_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const FSE_DTable* dt);
  353. /*!
  354. Tutorial :
  355. ----------
  356. (Note : these functions only decompress FSE-compressed blocks.
  357. If block is uncompressed, use memcpy() instead
  358. If block is a single repeated byte, use memset() instead )
  359. The first step is to obtain the normalized frequencies of symbols.
  360. This can be performed by FSE_readNCount() if it was saved using FSE_writeNCount().
  361. 'normalizedCounter' must be already allocated, and have at least 'maxSymbolValuePtr[0]+1' cells of signed short.
  362. In practice, that means it's necessary to know 'maxSymbolValue' beforehand,
  363. or size the table to handle worst case situations (typically 256).
  364. FSE_readNCount() will provide 'tableLog' and 'maxSymbolValue'.
  365. The result of FSE_readNCount() is the number of bytes read from 'rBuffer'.
  366. Note that 'rBufferSize' must be at least 4 bytes, even if useful information is less than that.
  367. If there is an error, the function will return an error code, which can be tested using FSE_isError().
  368. The next step is to build the decompression tables 'FSE_DTable' from 'normalizedCounter'.
  369. This is performed by the function FSE_buildDTable().
  370. The space required by 'FSE_DTable' must be already allocated using FSE_createDTable().
  371. If there is an error, the function will return an error code, which can be tested using FSE_isError().
  372. 'FSE_DTable' can then be used to decompress 'cSrc', with FSE_decompress_usingDTable().
  373. 'cSrcSize' must be strictly correct, otherwise decompression will fail.
  374. FSE_decompress_usingDTable() result will tell how many bytes were regenerated (<=maxDstSize).
  375. If there is an error, the function will return an error code, which can be tested using FSE_isError(). (ex: dst buffer too small)
  376. */
  377. #if defined (__cplusplus)
  378. }
  379. #endif
  380. #endif /* FSE_H */
  381. /* ******************************************************************
  382. bitstream
  383. Part of NewGen Entropy library
  384. header file (to include)
  385. Copyright (C) 2013-2015, Yann Collet.
  386. BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
  387. Redistribution and use in source and binary forms, with or without
  388. modification, are permitted provided that the following conditions are
  389. met:
  390. * Redistributions of source code must retain the above copyright
  391. notice, this list of conditions and the following disclaimer.
  392. * Redistributions in binary form must reproduce the above
  393. copyright notice, this list of conditions and the following disclaimer
  394. in the documentation and/or other materials provided with the
  395. distribution.
  396. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  397. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  398. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  399. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  400. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  401. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  402. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  403. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  404. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  405. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  406. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  407. You can contact the author at :
  408. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  409. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  410. ****************************************************************** */
  411. #ifndef BITSTREAM_H_MODULE
  412. #define BITSTREAM_H_MODULE
  413. #if defined (__cplusplus)
  414. extern "C" {
  415. #endif
  416. /*
  417. * This API consists of small unitary functions, which highly benefit from being inlined.
  418. * Since link-time-optimization is not available for all compilers,
  419. * these functions are defined into a .h to be included.
  420. */
  421. /**********************************************
  422. * bitStream decompression API (read backward)
  423. **********************************************/
  424. typedef struct
  425. {
  426. size_t bitContainer;
  427. unsigned bitsConsumed;
  428. const char* ptr;
  429. const char* start;
  430. } BIT_DStream_t;
  431. typedef enum { BIT_DStream_unfinished = 0,
  432. BIT_DStream_endOfBuffer = 1,
  433. BIT_DStream_completed = 2,
  434. BIT_DStream_overflow = 3 } BIT_DStream_status; /* result of BIT_reloadDStream() */
  435. /* 1,2,4,8 would be better for bitmap combinations, but slows down performance a bit ... :( */
  436. MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize);
  437. MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, unsigned nbBits);
  438. MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD);
  439. MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* bitD);
  440. /******************************************
  441. * unsafe API
  442. ******************************************/
  443. MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, unsigned nbBits);
  444. /* faster, but works only if nbBits >= 1 */
  445. /****************************************************************
  446. * Helper functions
  447. ****************************************************************/
  448. MEM_STATIC unsigned BIT_highbit32 (U32 val)
  449. {
  450. # if defined(_MSC_VER) /* Visual */
  451. unsigned long r;
  452. return _BitScanReverse(&r, val) ? (unsigned)r : 0;
  453. # elif defined(__GNUC__) && (__GNUC__ >= 3) /* Use GCC Intrinsic */
  454. return __builtin_clz (val) ^ 31;
  455. # else /* Software version */
  456. 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 };
  457. U32 v = val;
  458. unsigned r;
  459. v |= v >> 1;
  460. v |= v >> 2;
  461. v |= v >> 4;
  462. v |= v >> 8;
  463. v |= v >> 16;
  464. r = DeBruijnClz[ (U32) (v * 0x07C4ACDDU) >> 27];
  465. return r;
  466. # endif
  467. }
  468. /**********************************************************
  469. * bitStream decoding
  470. **********************************************************/
  471. /*!BIT_initDStream
  472. * Initialize a BIT_DStream_t.
  473. * @bitD : a pointer to an already allocated BIT_DStream_t structure
  474. * @srcBuffer must point at the beginning of a bitStream
  475. * @srcSize must be the exact size of the bitStream
  476. * @result : size of stream (== srcSize) or an errorCode if a problem is detected
  477. */
  478. MEM_STATIC size_t BIT_initDStream(BIT_DStream_t* bitD, const void* srcBuffer, size_t srcSize)
  479. {
  480. if (srcSize < 1) { memset(bitD, 0, sizeof(*bitD)); return ERROR(srcSize_wrong); }
  481. if (srcSize >= sizeof(size_t)) /* normal case */
  482. {
  483. U32 contain32;
  484. bitD->start = (const char*)srcBuffer;
  485. bitD->ptr = (const char*)srcBuffer + srcSize - sizeof(size_t);
  486. bitD->bitContainer = MEM_readLEST(bitD->ptr);
  487. contain32 = ((const BYTE*)srcBuffer)[srcSize-1];
  488. if (contain32 == 0) return ERROR(GENERIC); /* endMark not present */
  489. bitD->bitsConsumed = 8 - BIT_highbit32(contain32);
  490. }
  491. else
  492. {
  493. U32 contain32;
  494. bitD->start = (const char*)srcBuffer;
  495. bitD->ptr = bitD->start;
  496. bitD->bitContainer = *(const BYTE*)(bitD->start);
  497. switch(srcSize)
  498. {
  499. case 7: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[6]) << (sizeof(size_t)*8 - 16);/* fall-through */
  500. case 6: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[5]) << (sizeof(size_t)*8 - 24);/* fall-through */
  501. case 5: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[4]) << (sizeof(size_t)*8 - 32);/* fall-through */
  502. case 4: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[3]) << 24; /* fall-through */
  503. case 3: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[2]) << 16; /* fall-through */
  504. case 2: bitD->bitContainer += (size_t)(((const BYTE*)(bitD->start))[1]) << 8; /* fall-through */
  505. default: break;
  506. }
  507. contain32 = ((const BYTE*)srcBuffer)[srcSize-1];
  508. if (contain32 == 0) return ERROR(GENERIC); /* endMark not present */
  509. bitD->bitsConsumed = 8 - BIT_highbit32(contain32);
  510. bitD->bitsConsumed += (U32)(sizeof(size_t) - srcSize)*8;
  511. }
  512. return srcSize;
  513. }
  514. MEM_STATIC size_t BIT_lookBits(BIT_DStream_t* bitD, U32 nbBits)
  515. {
  516. const U32 bitMask = sizeof(bitD->bitContainer)*8 - 1;
  517. return ((bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> 1) >> ((bitMask-nbBits) & bitMask);
  518. }
  519. /*! BIT_lookBitsFast :
  520. * unsafe version; only works if nbBits >= 1 */
  521. MEM_STATIC size_t BIT_lookBitsFast(BIT_DStream_t* bitD, U32 nbBits)
  522. {
  523. const U32 bitMask = sizeof(bitD->bitContainer)*8 - 1;
  524. return (bitD->bitContainer << (bitD->bitsConsumed & bitMask)) >> (((bitMask+1)-nbBits) & bitMask);
  525. }
  526. MEM_STATIC void BIT_skipBits(BIT_DStream_t* bitD, U32 nbBits)
  527. {
  528. bitD->bitsConsumed += nbBits;
  529. }
  530. MEM_STATIC size_t BIT_readBits(BIT_DStream_t* bitD, U32 nbBits)
  531. {
  532. size_t value = BIT_lookBits(bitD, nbBits);
  533. BIT_skipBits(bitD, nbBits);
  534. return value;
  535. }
  536. /*!BIT_readBitsFast :
  537. * unsafe version; only works if nbBits >= 1 */
  538. MEM_STATIC size_t BIT_readBitsFast(BIT_DStream_t* bitD, U32 nbBits)
  539. {
  540. size_t value = BIT_lookBitsFast(bitD, nbBits);
  541. BIT_skipBits(bitD, nbBits);
  542. return value;
  543. }
  544. MEM_STATIC BIT_DStream_status BIT_reloadDStream(BIT_DStream_t* bitD)
  545. {
  546. if (bitD->bitsConsumed > (sizeof(bitD->bitContainer)*8)) /* should never happen */
  547. return BIT_DStream_overflow;
  548. if (bitD->ptr >= bitD->start + sizeof(bitD->bitContainer))
  549. {
  550. bitD->ptr -= bitD->bitsConsumed >> 3;
  551. bitD->bitsConsumed &= 7;
  552. bitD->bitContainer = MEM_readLEST(bitD->ptr);
  553. return BIT_DStream_unfinished;
  554. }
  555. if (bitD->ptr == bitD->start)
  556. {
  557. if (bitD->bitsConsumed < sizeof(bitD->bitContainer)*8) return BIT_DStream_endOfBuffer;
  558. return BIT_DStream_completed;
  559. }
  560. {
  561. U32 nbBytes = bitD->bitsConsumed >> 3;
  562. BIT_DStream_status result = BIT_DStream_unfinished;
  563. if (bitD->ptr - nbBytes < bitD->start)
  564. {
  565. nbBytes = (U32)(bitD->ptr - bitD->start); /* ptr > start */
  566. result = BIT_DStream_endOfBuffer;
  567. }
  568. bitD->ptr -= nbBytes;
  569. bitD->bitsConsumed -= nbBytes*8;
  570. bitD->bitContainer = MEM_readLEST(bitD->ptr); /* reminder : srcSize > sizeof(bitD) */
  571. return result;
  572. }
  573. }
  574. /*! BIT_endOfDStream
  575. * @return Tells if DStream has reached its exact end
  576. */
  577. MEM_STATIC unsigned BIT_endOfDStream(const BIT_DStream_t* DStream)
  578. {
  579. return ((DStream->ptr == DStream->start) && (DStream->bitsConsumed == sizeof(DStream->bitContainer)*8));
  580. }
  581. #if defined (__cplusplus)
  582. }
  583. #endif
  584. #endif /* BITSTREAM_H_MODULE */
  585. /* ******************************************************************
  586. FSE : Finite State Entropy coder
  587. header file for static linking (only)
  588. Copyright (C) 2013-2015, Yann Collet
  589. BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
  590. Redistribution and use in source and binary forms, with or without
  591. modification, are permitted provided that the following conditions are
  592. met:
  593. * Redistributions of source code must retain the above copyright
  594. notice, this list of conditions and the following disclaimer.
  595. * Redistributions in binary form must reproduce the above
  596. copyright notice, this list of conditions and the following disclaimer
  597. in the documentation and/or other materials provided with the
  598. distribution.
  599. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  600. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  601. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  602. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  603. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  604. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  605. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  606. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  607. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  608. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  609. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  610. You can contact the author at :
  611. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  612. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  613. ****************************************************************** */
  614. #ifndef FSE_STATIC_H
  615. #define FSE_STATIC_H
  616. #if defined (__cplusplus)
  617. extern "C" {
  618. #endif
  619. /* *****************************************
  620. * Static allocation
  621. *******************************************/
  622. /* FSE buffer bounds */
  623. #define FSE_NCOUNTBOUND 512
  624. #define FSE_BLOCKBOUND(size) (size + (size>>7))
  625. #define FSE_COMPRESSBOUND(size) (FSE_NCOUNTBOUND + FSE_BLOCKBOUND(size)) /* Macro version, useful for static allocation */
  626. /* It is possible to statically allocate FSE CTable/DTable as a table of unsigned using below macros */
  627. #define FSE_CTABLE_SIZE_U32(maxTableLog, maxSymbolValue) (1 + (1<<(maxTableLog-1)) + ((maxSymbolValue+1)*2))
  628. #define FSE_DTABLE_SIZE_U32(maxTableLog) (1 + (1<<maxTableLog))
  629. /* *****************************************
  630. * FSE advanced API
  631. *******************************************/
  632. static size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits);
  633. /* build a fake FSE_DTable, designed to read an uncompressed bitstream where each symbol uses nbBits */
  634. static size_t FSE_buildDTable_rle (FSE_DTable* dt, unsigned char symbolValue);
  635. /* build a fake FSE_DTable, designed to always generate the same symbolValue */
  636. /* *****************************************
  637. * FSE symbol decompression API
  638. *******************************************/
  639. typedef struct
  640. {
  641. size_t state;
  642. const void* table; /* precise table may vary, depending on U16 */
  643. } FSE_DState_t;
  644. static void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt);
  645. static unsigned char FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);
  646. static unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr);
  647. /* *****************************************
  648. * FSE unsafe API
  649. *******************************************/
  650. static unsigned char FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD);
  651. /* faster, but works only if nbBits is always >= 1 (otherwise, result will be corrupted) */
  652. /* *****************************************
  653. * Implementation of inlined functions
  654. *******************************************/
  655. /* decompression */
  656. typedef struct {
  657. U16 tableLog;
  658. U16 fastMode;
  659. } FSE_DTableHeader; /* sizeof U32 */
  660. typedef struct
  661. {
  662. unsigned short newState;
  663. unsigned char symbol;
  664. unsigned char nbBits;
  665. } FSE_decode_t; /* size == U32 */
  666. MEM_STATIC void FSE_initDState(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD, const FSE_DTable* dt)
  667. {
  668. FSE_DTableHeader DTableH;
  669. memcpy(&DTableH, dt, sizeof(DTableH));
  670. DStatePtr->state = BIT_readBits(bitD, DTableH.tableLog);
  671. BIT_reloadDStream(bitD);
  672. DStatePtr->table = dt + 1;
  673. }
  674. MEM_STATIC BYTE FSE_decodeSymbol(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
  675. {
  676. const FSE_decode_t DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
  677. const U32 nbBits = DInfo.nbBits;
  678. BYTE symbol = DInfo.symbol;
  679. size_t lowBits = BIT_readBits(bitD, nbBits);
  680. DStatePtr->state = DInfo.newState + lowBits;
  681. return symbol;
  682. }
  683. MEM_STATIC BYTE FSE_decodeSymbolFast(FSE_DState_t* DStatePtr, BIT_DStream_t* bitD)
  684. {
  685. const FSE_decode_t DInfo = ((const FSE_decode_t*)(DStatePtr->table))[DStatePtr->state];
  686. const U32 nbBits = DInfo.nbBits;
  687. BYTE symbol = DInfo.symbol;
  688. size_t lowBits = BIT_readBitsFast(bitD, nbBits);
  689. DStatePtr->state = DInfo.newState + lowBits;
  690. return symbol;
  691. }
  692. MEM_STATIC unsigned FSE_endOfDState(const FSE_DState_t* DStatePtr)
  693. {
  694. return DStatePtr->state == 0;
  695. }
  696. #if defined (__cplusplus)
  697. }
  698. #endif
  699. #endif /* FSE_STATIC_H */
  700. /* ******************************************************************
  701. FSE : Finite State Entropy coder
  702. Copyright (C) 2013-2015, Yann Collet.
  703. BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
  704. Redistribution and use in source and binary forms, with or without
  705. modification, are permitted provided that the following conditions are
  706. met:
  707. * Redistributions of source code must retain the above copyright
  708. notice, this list of conditions and the following disclaimer.
  709. * Redistributions in binary form must reproduce the above
  710. copyright notice, this list of conditions and the following disclaimer
  711. in the documentation and/or other materials provided with the
  712. distribution.
  713. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  714. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  715. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  716. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  717. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  718. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  719. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  720. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  721. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  722. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  723. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  724. You can contact the author at :
  725. - FSE source repository : https://github.com/Cyan4973/FiniteStateEntropy
  726. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  727. ****************************************************************** */
  728. #ifndef FSE_COMMONDEFS_ONLY
  729. /* **************************************************************
  730. * Tuning parameters
  731. ****************************************************************/
  732. /*!MEMORY_USAGE :
  733. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  734. * Increasing memory usage improves compression ratio
  735. * Reduced memory usage can improve speed, due to cache effect
  736. * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
  737. #define FSE_MAX_MEMORY_USAGE 14
  738. #define FSE_DEFAULT_MEMORY_USAGE 13
  739. /*!FSE_MAX_SYMBOL_VALUE :
  740. * Maximum symbol value authorized.
  741. * Required for proper stack allocation */
  742. #define FSE_MAX_SYMBOL_VALUE 255
  743. /* **************************************************************
  744. * template functions type & suffix
  745. ****************************************************************/
  746. #define FSE_FUNCTION_TYPE BYTE
  747. #define FSE_FUNCTION_EXTENSION
  748. #define FSE_DECODE_TYPE FSE_decode_t
  749. #endif /* !FSE_COMMONDEFS_ONLY */
  750. /* **************************************************************
  751. * Compiler specifics
  752. ****************************************************************/
  753. #ifdef _MSC_VER /* Visual Studio */
  754. # define FORCE_INLINE static __forceinline
  755. # include <intrin.h> /* For Visual 2005 */
  756. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  757. # pragma warning(disable : 4214) /* disable: C4214: non-int bitfields */
  758. #else
  759. # if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
  760. # ifdef __GNUC__
  761. # define FORCE_INLINE static inline __attribute__((always_inline))
  762. # else
  763. # define FORCE_INLINE static inline
  764. # endif
  765. # else
  766. # define FORCE_INLINE static
  767. # endif /* __STDC_VERSION__ */
  768. #endif
  769. /* **************************************************************
  770. * Dependencies
  771. ****************************************************************/
  772. #include <stdlib.h> /* malloc, free, qsort */
  773. #include <string.h> /* memcpy, memset */
  774. #include <stdio.h> /* printf (debug) */
  775. /* ***************************************************************
  776. * Constants
  777. *****************************************************************/
  778. #define FSE_MAX_TABLELOG (FSE_MAX_MEMORY_USAGE-2)
  779. #define FSE_MAX_TABLESIZE (1U<<FSE_MAX_TABLELOG)
  780. #define FSE_MAXTABLESIZE_MASK (FSE_MAX_TABLESIZE-1)
  781. #define FSE_DEFAULT_TABLELOG (FSE_DEFAULT_MEMORY_USAGE-2)
  782. #define FSE_MIN_TABLELOG 5
  783. #define FSE_TABLELOG_ABSOLUTE_MAX 15
  784. #if FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX
  785. #error "FSE_MAX_TABLELOG > FSE_TABLELOG_ABSOLUTE_MAX is not supported"
  786. #endif
  787. /* **************************************************************
  788. * Error Management
  789. ****************************************************************/
  790. #define FSE_STATIC_ASSERT(c) { enum { FSE_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  791. /* **************************************************************
  792. * Complex types
  793. ****************************************************************/
  794. typedef U32 DTable_max_t[FSE_DTABLE_SIZE_U32(FSE_MAX_TABLELOG)];
  795. /*-**************************************************************
  796. * Templates
  797. ****************************************************************/
  798. /*
  799. designed to be included
  800. for type-specific functions (template emulation in C)
  801. Objective is to write these functions only once, for improved maintenance
  802. */
  803. /* safety checks */
  804. #ifndef FSE_FUNCTION_EXTENSION
  805. # error "FSE_FUNCTION_EXTENSION must be defined"
  806. #endif
  807. #ifndef FSE_FUNCTION_TYPE
  808. # error "FSE_FUNCTION_TYPE must be defined"
  809. #endif
  810. /* Function names */
  811. #define FSE_CAT(X,Y) X##Y
  812. #define FSE_FUNCTION_NAME(X,Y) FSE_CAT(X,Y)
  813. #define FSE_TYPE_NAME(X,Y) FSE_CAT(X,Y)
  814. static U32 FSE_tableStep(U32 tableSize) { return (tableSize>>1) + (tableSize>>3) + 3; }
  815. static size_t FSE_buildDTable(FSE_DTable* dt, const short* normalizedCounter, unsigned maxSymbolValue, unsigned tableLog)
  816. {
  817. FSE_DTableHeader DTableH;
  818. void* const tdPtr = dt+1; /* because dt is unsigned, 32-bits aligned on 32-bits */
  819. FSE_DECODE_TYPE* const tableDecode = (FSE_DECODE_TYPE*) (tdPtr);
  820. const U32 tableSize = 1 << tableLog;
  821. const U32 tableMask = tableSize-1;
  822. const U32 step = FSE_tableStep(tableSize);
  823. U16 symbolNext[FSE_MAX_SYMBOL_VALUE+1];
  824. U32 position = 0;
  825. U32 highThreshold = tableSize-1;
  826. const S16 largeLimit= (S16)(1 << (tableLog-1));
  827. U32 noLarge = 1;
  828. U32 s;
  829. /* Sanity Checks */
  830. if (maxSymbolValue > FSE_MAX_SYMBOL_VALUE) return ERROR(maxSymbolValue_tooLarge);
  831. if (tableLog > FSE_MAX_TABLELOG) return ERROR(tableLog_tooLarge);
  832. /* Init, lay down lowprob symbols */
  833. memset(tableDecode, 0, sizeof(FSE_DECODE_TYPE) * (maxSymbolValue+1) ); /* useless init, but keep static analyzer happy, and we don't need to performance optimize legacy decoders */
  834. DTableH.tableLog = (U16)tableLog;
  835. for (s=0; s<=maxSymbolValue; s++)
  836. {
  837. if (normalizedCounter[s]==-1)
  838. {
  839. tableDecode[highThreshold--].symbol = (FSE_FUNCTION_TYPE)s;
  840. symbolNext[s] = 1;
  841. }
  842. else
  843. {
  844. if (normalizedCounter[s] >= largeLimit) noLarge=0;
  845. symbolNext[s] = normalizedCounter[s];
  846. }
  847. }
  848. /* Spread symbols */
  849. for (s=0; s<=maxSymbolValue; s++)
  850. {
  851. int i;
  852. for (i=0; i<normalizedCounter[s]; i++)
  853. {
  854. tableDecode[position].symbol = (FSE_FUNCTION_TYPE)s;
  855. position = (position + step) & tableMask;
  856. while (position > highThreshold) position = (position + step) & tableMask; /* lowprob area */
  857. }
  858. }
  859. if (position!=0) return ERROR(GENERIC); /* position must reach all cells once, otherwise normalizedCounter is incorrect */
  860. /* Build Decoding table */
  861. {
  862. U32 i;
  863. for (i=0; i<tableSize; i++)
  864. {
  865. FSE_FUNCTION_TYPE symbol = (FSE_FUNCTION_TYPE)(tableDecode[i].symbol);
  866. U16 nextState = symbolNext[symbol]++;
  867. tableDecode[i].nbBits = (BYTE) (tableLog - BIT_highbit32 ((U32)nextState) );
  868. tableDecode[i].newState = (U16) ( (nextState << tableDecode[i].nbBits) - tableSize);
  869. }
  870. }
  871. DTableH.fastMode = (U16)noLarge;
  872. memcpy(dt, &DTableH, sizeof(DTableH));
  873. return 0;
  874. }
  875. #ifndef FSE_COMMONDEFS_ONLY
  876. /******************************************
  877. * FSE helper functions
  878. ******************************************/
  879. static unsigned FSE_isError(size_t code) { return ERR_isError(code); }
  880. /****************************************************************
  881. * FSE NCount encoding-decoding
  882. ****************************************************************/
  883. static short FSE_abs(short a)
  884. {
  885. return a<0 ? -a : a;
  886. }
  887. static size_t FSE_readNCount (short* normalizedCounter, unsigned* maxSVPtr, unsigned* tableLogPtr,
  888. const void* headerBuffer, size_t hbSize)
  889. {
  890. const BYTE* const istart = (const BYTE*) headerBuffer;
  891. const BYTE* const iend = istart + hbSize;
  892. const BYTE* ip = istart;
  893. int nbBits;
  894. int remaining;
  895. int threshold;
  896. U32 bitStream;
  897. int bitCount;
  898. unsigned charnum = 0;
  899. int previous0 = 0;
  900. if (hbSize < 4) return ERROR(srcSize_wrong);
  901. bitStream = MEM_readLE32(ip);
  902. nbBits = (bitStream & 0xF) + FSE_MIN_TABLELOG; /* extract tableLog */
  903. if (nbBits > FSE_TABLELOG_ABSOLUTE_MAX) return ERROR(tableLog_tooLarge);
  904. bitStream >>= 4;
  905. bitCount = 4;
  906. *tableLogPtr = nbBits;
  907. remaining = (1<<nbBits)+1;
  908. threshold = 1<<nbBits;
  909. nbBits++;
  910. while ((remaining>1) && (charnum<=*maxSVPtr))
  911. {
  912. if (previous0)
  913. {
  914. unsigned n0 = charnum;
  915. while ((bitStream & 0xFFFF) == 0xFFFF)
  916. {
  917. n0+=24;
  918. if (ip < iend-5)
  919. {
  920. ip+=2;
  921. bitStream = MEM_readLE32(ip) >> bitCount;
  922. }
  923. else
  924. {
  925. bitStream >>= 16;
  926. bitCount+=16;
  927. }
  928. }
  929. while ((bitStream & 3) == 3)
  930. {
  931. n0+=3;
  932. bitStream>>=2;
  933. bitCount+=2;
  934. }
  935. n0 += bitStream & 3;
  936. bitCount += 2;
  937. if (n0 > *maxSVPtr) return ERROR(maxSymbolValue_tooSmall);
  938. while (charnum < n0) normalizedCounter[charnum++] = 0;
  939. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4))
  940. {
  941. ip += bitCount>>3;
  942. bitCount &= 7;
  943. bitStream = MEM_readLE32(ip) >> bitCount;
  944. }
  945. else
  946. bitStream >>= 2;
  947. }
  948. {
  949. const short max = (short)((2*threshold-1)-remaining);
  950. short count;
  951. if ((bitStream & (threshold-1)) < (U32)max)
  952. {
  953. count = (short)(bitStream & (threshold-1));
  954. bitCount += nbBits-1;
  955. }
  956. else
  957. {
  958. count = (short)(bitStream & (2*threshold-1));
  959. if (count >= threshold) count -= max;
  960. bitCount += nbBits;
  961. }
  962. count--; /* extra accuracy */
  963. remaining -= FSE_abs(count);
  964. normalizedCounter[charnum++] = count;
  965. previous0 = !count;
  966. while (remaining < threshold)
  967. {
  968. nbBits--;
  969. threshold >>= 1;
  970. }
  971. {
  972. if ((ip <= iend-7) || (ip + (bitCount>>3) <= iend-4))
  973. {
  974. ip += bitCount>>3;
  975. bitCount &= 7;
  976. }
  977. else
  978. {
  979. bitCount -= (int)(8 * (iend - 4 - ip));
  980. ip = iend - 4;
  981. }
  982. bitStream = MEM_readLE32(ip) >> (bitCount & 31);
  983. }
  984. }
  985. }
  986. if (remaining != 1) return ERROR(GENERIC);
  987. *maxSVPtr = charnum-1;
  988. ip += (bitCount+7)>>3;
  989. if ((size_t)(ip-istart) > hbSize) return ERROR(srcSize_wrong);
  990. return ip-istart;
  991. }
  992. /*********************************************************
  993. * Decompression (Byte symbols)
  994. *********************************************************/
  995. static size_t FSE_buildDTable_rle (FSE_DTable* dt, BYTE symbolValue)
  996. {
  997. void* ptr = dt;
  998. FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
  999. void* dPtr = dt + 1;
  1000. FSE_decode_t* const cell = (FSE_decode_t*)dPtr;
  1001. DTableH->tableLog = 0;
  1002. DTableH->fastMode = 0;
  1003. cell->newState = 0;
  1004. cell->symbol = symbolValue;
  1005. cell->nbBits = 0;
  1006. return 0;
  1007. }
  1008. static size_t FSE_buildDTable_raw (FSE_DTable* dt, unsigned nbBits)
  1009. {
  1010. void* ptr = dt;
  1011. FSE_DTableHeader* const DTableH = (FSE_DTableHeader*)ptr;
  1012. void* dPtr = dt + 1;
  1013. FSE_decode_t* const dinfo = (FSE_decode_t*)dPtr;
  1014. const unsigned tableSize = 1 << nbBits;
  1015. const unsigned tableMask = tableSize - 1;
  1016. const unsigned maxSymbolValue = tableMask;
  1017. unsigned s;
  1018. /* Sanity checks */
  1019. if (nbBits < 1) return ERROR(GENERIC); /* min size */
  1020. /* Build Decoding Table */
  1021. DTableH->tableLog = (U16)nbBits;
  1022. DTableH->fastMode = 1;
  1023. for (s=0; s<=maxSymbolValue; s++)
  1024. {
  1025. dinfo[s].newState = 0;
  1026. dinfo[s].symbol = (BYTE)s;
  1027. dinfo[s].nbBits = (BYTE)nbBits;
  1028. }
  1029. return 0;
  1030. }
  1031. FORCE_INLINE size_t FSE_decompress_usingDTable_generic(
  1032. void* dst, size_t maxDstSize,
  1033. const void* cSrc, size_t cSrcSize,
  1034. const FSE_DTable* dt, const unsigned fast)
  1035. {
  1036. BYTE* const ostart = (BYTE*) dst;
  1037. BYTE* op = ostart;
  1038. BYTE* const omax = op + maxDstSize;
  1039. BYTE* const olimit = omax-3;
  1040. BIT_DStream_t bitD;
  1041. FSE_DState_t state1;
  1042. FSE_DState_t state2;
  1043. size_t errorCode;
  1044. /* Init */
  1045. errorCode = BIT_initDStream(&bitD, cSrc, cSrcSize); /* replaced last arg by maxCompressed Size */
  1046. if (FSE_isError(errorCode)) return errorCode;
  1047. FSE_initDState(&state1, &bitD, dt);
  1048. FSE_initDState(&state2, &bitD, dt);
  1049. #define FSE_GETSYMBOL(statePtr) fast ? FSE_decodeSymbolFast(statePtr, &bitD) : FSE_decodeSymbol(statePtr, &bitD)
  1050. /* 4 symbols per loop */
  1051. for ( ; (BIT_reloadDStream(&bitD)==BIT_DStream_unfinished) && (op<olimit) ; op+=4)
  1052. {
  1053. op[0] = FSE_GETSYMBOL(&state1);
  1054. if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1055. BIT_reloadDStream(&bitD);
  1056. op[1] = FSE_GETSYMBOL(&state2);
  1057. if (FSE_MAX_TABLELOG*4+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1058. { if (BIT_reloadDStream(&bitD) > BIT_DStream_unfinished) { op+=2; break; } }
  1059. op[2] = FSE_GETSYMBOL(&state1);
  1060. if (FSE_MAX_TABLELOG*2+7 > sizeof(bitD.bitContainer)*8) /* This test must be static */
  1061. BIT_reloadDStream(&bitD);
  1062. op[3] = FSE_GETSYMBOL(&state2);
  1063. }
  1064. /* tail */
  1065. /* note : BIT_reloadDStream(&bitD) >= FSE_DStream_partiallyFilled; Ends at exactly BIT_DStream_completed */
  1066. while (1)
  1067. {
  1068. if ( (BIT_reloadDStream(&bitD)>BIT_DStream_completed) || (op==omax) || (BIT_endOfDStream(&bitD) && (fast || FSE_endOfDState(&state1))) )
  1069. break;
  1070. *op++ = FSE_GETSYMBOL(&state1);
  1071. if ( (BIT_reloadDStream(&bitD)>BIT_DStream_completed) || (op==omax) || (BIT_endOfDStream(&bitD) && (fast || FSE_endOfDState(&state2))) )
  1072. break;
  1073. *op++ = FSE_GETSYMBOL(&state2);
  1074. }
  1075. /* end ? */
  1076. if (BIT_endOfDStream(&bitD) && FSE_endOfDState(&state1) && FSE_endOfDState(&state2))
  1077. return op-ostart;
  1078. if (op==omax) return ERROR(dstSize_tooSmall); /* dst buffer is full, but cSrc unfinished */
  1079. return ERROR(corruption_detected);
  1080. }
  1081. static size_t FSE_decompress_usingDTable(void* dst, size_t originalSize,
  1082. const void* cSrc, size_t cSrcSize,
  1083. const FSE_DTable* dt)
  1084. {
  1085. FSE_DTableHeader DTableH;
  1086. U32 fastMode;
  1087. memcpy(&DTableH, dt, sizeof(DTableH));
  1088. fastMode = DTableH.fastMode;
  1089. /* select fast mode (static) */
  1090. if (fastMode) return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 1);
  1091. return FSE_decompress_usingDTable_generic(dst, originalSize, cSrc, cSrcSize, dt, 0);
  1092. }
  1093. static size_t FSE_decompress(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize)
  1094. {
  1095. const BYTE* const istart = (const BYTE*)cSrc;
  1096. const BYTE* ip = istart;
  1097. short counting[FSE_MAX_SYMBOL_VALUE+1];
  1098. DTable_max_t dt; /* Static analyzer seems unable to understand this table will be properly initialized later */
  1099. unsigned tableLog;
  1100. unsigned maxSymbolValue = FSE_MAX_SYMBOL_VALUE;
  1101. size_t errorCode;
  1102. if (cSrcSize<2) return ERROR(srcSize_wrong); /* too small input size */
  1103. /* normal FSE decoding mode */
  1104. errorCode = FSE_readNCount (counting, &maxSymbolValue, &tableLog, istart, cSrcSize);
  1105. if (FSE_isError(errorCode)) return errorCode;
  1106. if (errorCode >= cSrcSize) return ERROR(srcSize_wrong); /* too small input size */
  1107. ip += errorCode;
  1108. cSrcSize -= errorCode;
  1109. errorCode = FSE_buildDTable (dt, counting, maxSymbolValue, tableLog);
  1110. if (FSE_isError(errorCode)) return errorCode;
  1111. /* always return, even if it is an error code */
  1112. return FSE_decompress_usingDTable (dst, maxDstSize, ip, cSrcSize, dt);
  1113. }
  1114. #endif /* FSE_COMMONDEFS_ONLY */
  1115. /* ******************************************************************
  1116. Huff0 : Huffman coder, part of New Generation Entropy library
  1117. header file
  1118. Copyright (C) 2013-2015, Yann Collet.
  1119. BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
  1120. Redistribution and use in source and binary forms, with or without
  1121. modification, are permitted provided that the following conditions are
  1122. met:
  1123. * Redistributions of source code must retain the above copyright
  1124. notice, this list of conditions and the following disclaimer.
  1125. * Redistributions in binary form must reproduce the above
  1126. copyright notice, this list of conditions and the following disclaimer
  1127. in the documentation and/or other materials provided with the
  1128. distribution.
  1129. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1130. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1131. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1132. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1133. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1134. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1135. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1136. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1137. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1138. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1139. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1140. You can contact the author at :
  1141. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  1142. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  1143. ****************************************************************** */
  1144. #ifndef HUFF0_H
  1145. #define HUFF0_H
  1146. #if defined (__cplusplus)
  1147. extern "C" {
  1148. #endif
  1149. /* ****************************************
  1150. * Dependency
  1151. ******************************************/
  1152. #include <stddef.h> /* size_t */
  1153. /* ****************************************
  1154. * Huff0 simple functions
  1155. ******************************************/
  1156. static size_t HUF_decompress(void* dst, size_t dstSize,
  1157. const void* cSrc, size_t cSrcSize);
  1158. /*!
  1159. HUF_decompress():
  1160. Decompress Huff0 data from buffer 'cSrc', of size 'cSrcSize',
  1161. into already allocated destination buffer 'dst', of size 'dstSize'.
  1162. 'dstSize' must be the exact size of original (uncompressed) data.
  1163. Note : in contrast with FSE, HUF_decompress can regenerate RLE (cSrcSize==1) and uncompressed (cSrcSize==dstSize) data, because it knows size to regenerate.
  1164. @return : size of regenerated data (== dstSize)
  1165. or an error code, which can be tested using HUF_isError()
  1166. */
  1167. /* ****************************************
  1168. * Tool functions
  1169. ******************************************/
  1170. /* Error Management */
  1171. static unsigned HUF_isError(size_t code); /* tells if a return value is an error code */
  1172. #if defined (__cplusplus)
  1173. }
  1174. #endif
  1175. #endif /* HUFF0_H */
  1176. /* ******************************************************************
  1177. Huff0 : Huffman coder, part of New Generation Entropy library
  1178. header file for static linking (only)
  1179. Copyright (C) 2013-2015, Yann Collet
  1180. BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
  1181. Redistribution and use in source and binary forms, with or without
  1182. modification, are permitted provided that the following conditions are
  1183. met:
  1184. * Redistributions of source code must retain the above copyright
  1185. notice, this list of conditions and the following disclaimer.
  1186. * Redistributions in binary form must reproduce the above
  1187. copyright notice, this list of conditions and the following disclaimer
  1188. in the documentation and/or other materials provided with the
  1189. distribution.
  1190. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1191. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1192. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1193. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1194. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1195. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1196. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1197. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1198. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1199. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1200. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1201. You can contact the author at :
  1202. - Source repository : https://github.com/Cyan4973/FiniteStateEntropy
  1203. - Public forum : https://groups.google.com/forum/#!forum/lz4c
  1204. ****************************************************************** */
  1205. #ifndef HUFF0_STATIC_H
  1206. #define HUFF0_STATIC_H
  1207. #if defined (__cplusplus)
  1208. extern "C" {
  1209. #endif
  1210. /* ****************************************
  1211. * Static allocation macros
  1212. ******************************************/
  1213. /* static allocation of Huff0's DTable */
  1214. #define HUF_DTABLE_SIZE(maxTableLog) (1 + (1<<maxTableLog)) /* nb Cells; use unsigned short for X2, unsigned int for X4 */
  1215. #define HUF_CREATE_STATIC_DTABLEX2(DTable, maxTableLog) \
  1216. unsigned short DTable[HUF_DTABLE_SIZE(maxTableLog)] = { maxTableLog }
  1217. #define HUF_CREATE_STATIC_DTABLEX4(DTable, maxTableLog) \
  1218. unsigned int DTable[HUF_DTABLE_SIZE(maxTableLog)] = { maxTableLog }
  1219. #define HUF_CREATE_STATIC_DTABLEX6(DTable, maxTableLog) \
  1220. unsigned int DTable[HUF_DTABLE_SIZE(maxTableLog) * 3 / 2] = { maxTableLog }
  1221. /* ****************************************
  1222. * Advanced decompression functions
  1223. ******************************************/
  1224. static size_t HUF_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /* single-symbol decoder */
  1225. static size_t HUF_decompress4X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize); /* double-symbols decoder */
  1226. /* ****************************************
  1227. * Huff0 detailed API
  1228. ******************************************/
  1229. /*!
  1230. HUF_decompress() does the following:
  1231. 1. select the decompression algorithm (X2, X4, X6) based on pre-computed heuristics
  1232. 2. build Huffman table from save, using HUF_readDTableXn()
  1233. 3. decode 1 or 4 segments in parallel using HUF_decompressSXn_usingDTable
  1234. */
  1235. static size_t HUF_readDTableX2 (unsigned short* DTable, const void* src, size_t srcSize);
  1236. static size_t HUF_readDTableX4 (unsigned* DTable, const void* src, size_t srcSize);
  1237. static size_t HUF_decompress4X2_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const unsigned short* DTable);
  1238. static size_t HUF_decompress4X4_usingDTable(void* dst, size_t maxDstSize, const void* cSrc, size_t cSrcSize, const unsigned* DTable);
  1239. #if defined (__cplusplus)
  1240. }
  1241. #endif
  1242. #endif /* HUFF0_STATIC_H */
  1243. /* ******************************************************************
  1244. Huff0 : Huffman coder, part of New Generation Entropy library
  1245. Copyright (C) 2013-2015, Yann Collet.
  1246. BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
  1247. Redistribution and use in source and binary forms, with or without
  1248. modification, are permitted provided that the following conditions are
  1249. met:
  1250. * Redistributions of source code must retain the above copyright
  1251. notice, this list of conditions and the following disclaimer.
  1252. * Redistributions in binary form must reproduce the above
  1253. copyright notice, this list of conditions and the following disclaimer
  1254. in the documentation and/or other materials provided with the
  1255. distribution.
  1256. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1257. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1258. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1259. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1260. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1261. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1262. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1263. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1264. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1265. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1266. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1267. You can contact the author at :
  1268. - FSE+Huff0 source repository : https://github.com/Cyan4973/FiniteStateEntropy
  1269. ****************************************************************** */
  1270. /* **************************************************************
  1271. * Compiler specifics
  1272. ****************************************************************/
  1273. #if defined (__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
  1274. /* inline is defined */
  1275. #elif defined(_MSC_VER)
  1276. # define inline __inline
  1277. #else
  1278. # define inline /* disable inline */
  1279. #endif
  1280. #ifdef _MSC_VER /* Visual Studio */
  1281. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  1282. #endif
  1283. /* **************************************************************
  1284. * Includes
  1285. ****************************************************************/
  1286. #include <stdlib.h> /* malloc, free, qsort */
  1287. #include <string.h> /* memcpy, memset */
  1288. #include <stdio.h> /* printf (debug) */
  1289. /* **************************************************************
  1290. * Constants
  1291. ****************************************************************/
  1292. #define HUF_ABSOLUTEMAX_TABLELOG 16 /* absolute limit of HUF_MAX_TABLELOG. Beyond that value, code does not work */
  1293. #define HUF_MAX_TABLELOG 12 /* max configured tableLog (for static allocation); can be modified up to HUF_ABSOLUTEMAX_TABLELOG */
  1294. #define HUF_DEFAULT_TABLELOG HUF_MAX_TABLELOG /* tableLog by default, when not specified */
  1295. #define HUF_MAX_SYMBOL_VALUE 255
  1296. #if (HUF_MAX_TABLELOG > HUF_ABSOLUTEMAX_TABLELOG)
  1297. # error "HUF_MAX_TABLELOG is too large !"
  1298. #endif
  1299. /* **************************************************************
  1300. * Error Management
  1301. ****************************************************************/
  1302. static unsigned HUF_isError(size_t code) { return ERR_isError(code); }
  1303. #define HUF_STATIC_ASSERT(c) { enum { HUF_static_assert = 1/(int)(!!(c)) }; } /* use only *after* variable declarations */
  1304. /*-*******************************************************
  1305. * Huff0 : Huffman block decompression
  1306. *********************************************************/
  1307. typedef struct { BYTE byte; BYTE nbBits; } HUF_DEltX2; /* single-symbol decoding */
  1308. typedef struct { U16 sequence; BYTE nbBits; BYTE length; } HUF_DEltX4; /* double-symbols decoding */
  1309. typedef struct { BYTE symbol; BYTE weight; } sortedSymbol_t;
  1310. /*! HUF_readStats
  1311. Read compact Huffman tree, saved by HUF_writeCTable
  1312. @huffWeight : destination buffer
  1313. @return : size read from `src`
  1314. */
  1315. static size_t HUF_readStats(BYTE* huffWeight, size_t hwSize, U32* rankStats,
  1316. U32* nbSymbolsPtr, U32* tableLogPtr,
  1317. const void* src, size_t srcSize)
  1318. {
  1319. U32 weightTotal;
  1320. U32 tableLog;
  1321. const BYTE* ip = (const BYTE*) src;
  1322. size_t iSize;
  1323. size_t oSize;
  1324. U32 n;
  1325. if (!srcSize) return ERROR(srcSize_wrong);
  1326. iSize = ip[0];
  1327. //memset(huffWeight, 0, hwSize); /* is not necessary, even though some analyzer complain ... */
  1328. if (iSize >= 128) /* special header */
  1329. {
  1330. if (iSize >= (242)) /* RLE */
  1331. {
  1332. static int l[14] = { 1, 2, 3, 4, 7, 8, 15, 16, 31, 32, 63, 64, 127, 128 };
  1333. oSize = l[iSize-242];
  1334. memset(huffWeight, 1, hwSize);
  1335. iSize = 0;
  1336. }
  1337. else /* Incompressible */
  1338. {
  1339. oSize = iSize - 127;
  1340. iSize = ((oSize+1)/2);
  1341. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  1342. if (oSize >= hwSize) return ERROR(corruption_detected);
  1343. ip += 1;
  1344. for (n=0; n<oSize; n+=2)
  1345. {
  1346. huffWeight[n] = ip[n/2] >> 4;
  1347. huffWeight[n+1] = ip[n/2] & 15;
  1348. }
  1349. }
  1350. }
  1351. else /* header compressed with FSE (normal case) */
  1352. {
  1353. if (iSize+1 > srcSize) return ERROR(srcSize_wrong);
  1354. oSize = FSE_decompress(huffWeight, hwSize-1, ip+1, iSize); /* max (hwSize-1) values decoded, as last one is implied */
  1355. if (FSE_isError(oSize)) return oSize;
  1356. }
  1357. /* collect weight stats */
  1358. memset(rankStats, 0, (HUF_ABSOLUTEMAX_TABLELOG + 1) * sizeof(U32));
  1359. weightTotal = 0;
  1360. for (n=0; n<oSize; n++)
  1361. {
  1362. if (huffWeight[n] >= HUF_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected);
  1363. rankStats[huffWeight[n]]++;
  1364. weightTotal += (1 << huffWeight[n]) >> 1;
  1365. }
  1366. if (weightTotal == 0) return ERROR(corruption_detected);
  1367. /* get last non-null symbol weight (implied, total must be 2^n) */
  1368. tableLog = BIT_highbit32(weightTotal) + 1;
  1369. if (tableLog > HUF_ABSOLUTEMAX_TABLELOG) return ERROR(corruption_detected);
  1370. {
  1371. U32 total = 1 << tableLog;
  1372. U32 rest = total - weightTotal;
  1373. U32 verif = 1 << BIT_highbit32(rest);
  1374. U32 lastWeight = BIT_highbit32(rest) + 1;
  1375. if (verif != rest) return ERROR(corruption_detected); /* last value must be a clean power of 2 */
  1376. huffWeight[oSize] = (BYTE)lastWeight;
  1377. rankStats[lastWeight]++;
  1378. }
  1379. /* check tree construction validity */
  1380. if ((rankStats[1] < 2) || (rankStats[1] & 1)) return ERROR(corruption_detected); /* by construction : at least 2 elts of rank 1, must be even */
  1381. /* results */
  1382. *nbSymbolsPtr = (U32)(oSize+1);
  1383. *tableLogPtr = tableLog;
  1384. return iSize+1;
  1385. }
  1386. /**************************/
  1387. /* single-symbol decoding */
  1388. /**************************/
  1389. static size_t HUF_readDTableX2 (U16* DTable, const void* src, size_t srcSize)
  1390. {
  1391. BYTE huffWeight[HUF_MAX_SYMBOL_VALUE + 1];
  1392. U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1]; /* large enough for values from 0 to 16 */
  1393. U32 tableLog = 0;
  1394. size_t iSize;
  1395. U32 nbSymbols = 0;
  1396. U32 n;
  1397. U32 nextRankStart;
  1398. void* const dtPtr = DTable + 1;
  1399. HUF_DEltX2* const dt = (HUF_DEltX2*)dtPtr;
  1400. HUF_STATIC_ASSERT(sizeof(HUF_DEltX2) == sizeof(U16)); /* if compilation fails here, assertion is false */
  1401. //memset(huffWeight, 0, sizeof(huffWeight)); /* is not necessary, even though some analyzer complain ... */
  1402. iSize = HUF_readStats(huffWeight, HUF_MAX_SYMBOL_VALUE + 1, rankVal, &nbSymbols, &tableLog, src, srcSize);
  1403. if (HUF_isError(iSize)) return iSize;
  1404. /* check result */
  1405. if (tableLog > DTable[0]) return ERROR(tableLog_tooLarge); /* DTable is too small */
  1406. DTable[0] = (U16)tableLog; /* maybe should separate sizeof DTable, as allocated, from used size of DTable, in case of DTable re-use */
  1407. /* Prepare ranks */
  1408. nextRankStart = 0;
  1409. for (n=1; n<=tableLog; n++)
  1410. {
  1411. U32 current = nextRankStart;
  1412. nextRankStart += (rankVal[n] << (n-1));
  1413. rankVal[n] = current;
  1414. }
  1415. /* fill DTable */
  1416. for (n=0; n<nbSymbols; n++)
  1417. {
  1418. const U32 w = huffWeight[n];
  1419. const U32 length = (1 << w) >> 1;
  1420. U32 i;
  1421. HUF_DEltX2 D;
  1422. D.byte = (BYTE)n; D.nbBits = (BYTE)(tableLog + 1 - w);
  1423. for (i = rankVal[w]; i < rankVal[w] + length; i++)
  1424. dt[i] = D;
  1425. rankVal[w] += length;
  1426. }
  1427. return iSize;
  1428. }
  1429. static BYTE HUF_decodeSymbolX2(BIT_DStream_t* Dstream, const HUF_DEltX2* dt, const U32 dtLog)
  1430. {
  1431. const size_t val = BIT_lookBitsFast(Dstream, dtLog); /* note : dtLog >= 1 */
  1432. const BYTE c = dt[val].byte;
  1433. BIT_skipBits(Dstream, dt[val].nbBits);
  1434. return c;
  1435. }
  1436. #define HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr) \
  1437. *ptr++ = HUF_decodeSymbolX2(DStreamPtr, dt, dtLog)
  1438. #define HUF_DECODE_SYMBOLX2_1(ptr, DStreamPtr) \
  1439. if (MEM_64bits() || (HUF_MAX_TABLELOG<=12)) \
  1440. HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr)
  1441. #define HUF_DECODE_SYMBOLX2_2(ptr, DStreamPtr) \
  1442. if (MEM_64bits()) \
  1443. HUF_DECODE_SYMBOLX2_0(ptr, DStreamPtr)
  1444. static inline size_t HUF_decodeStreamX2(BYTE* p, BIT_DStream_t* const bitDPtr, BYTE* const pEnd, const HUF_DEltX2* const dt, const U32 dtLog)
  1445. {
  1446. BYTE* const pStart = p;
  1447. /* up to 4 symbols at a time */
  1448. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p <= pEnd-4))
  1449. {
  1450. HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
  1451. HUF_DECODE_SYMBOLX2_1(p, bitDPtr);
  1452. HUF_DECODE_SYMBOLX2_2(p, bitDPtr);
  1453. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1454. }
  1455. /* closer to the end */
  1456. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p < pEnd))
  1457. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1458. /* no more data to retrieve from bitstream, hence no need to reload */
  1459. while (p < pEnd)
  1460. HUF_DECODE_SYMBOLX2_0(p, bitDPtr);
  1461. return pEnd-pStart;
  1462. }
  1463. static size_t HUF_decompress4X2_usingDTable(
  1464. void* dst, size_t dstSize,
  1465. const void* cSrc, size_t cSrcSize,
  1466. const U16* DTable)
  1467. {
  1468. if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
  1469. {
  1470. const BYTE* const istart = (const BYTE*) cSrc;
  1471. BYTE* const ostart = (BYTE*) dst;
  1472. BYTE* const oend = ostart + dstSize;
  1473. const void* const dtPtr = DTable;
  1474. const HUF_DEltX2* const dt = ((const HUF_DEltX2*)dtPtr) +1;
  1475. const U32 dtLog = DTable[0];
  1476. size_t errorCode;
  1477. /* Init */
  1478. BIT_DStream_t bitD1;
  1479. BIT_DStream_t bitD2;
  1480. BIT_DStream_t bitD3;
  1481. BIT_DStream_t bitD4;
  1482. const size_t length1 = MEM_readLE16(istart);
  1483. const size_t length2 = MEM_readLE16(istart+2);
  1484. const size_t length3 = MEM_readLE16(istart+4);
  1485. size_t length4;
  1486. const BYTE* const istart1 = istart + 6; /* jumpTable */
  1487. const BYTE* const istart2 = istart1 + length1;
  1488. const BYTE* const istart3 = istart2 + length2;
  1489. const BYTE* const istart4 = istart3 + length3;
  1490. const size_t segmentSize = (dstSize+3) / 4;
  1491. BYTE* const opStart2 = ostart + segmentSize;
  1492. BYTE* const opStart3 = opStart2 + segmentSize;
  1493. BYTE* const opStart4 = opStart3 + segmentSize;
  1494. BYTE* op1 = ostart;
  1495. BYTE* op2 = opStart2;
  1496. BYTE* op3 = opStart3;
  1497. BYTE* op4 = opStart4;
  1498. U32 endSignal;
  1499. length4 = cSrcSize - (length1 + length2 + length3 + 6);
  1500. if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
  1501. errorCode = BIT_initDStream(&bitD1, istart1, length1);
  1502. if (HUF_isError(errorCode)) return errorCode;
  1503. errorCode = BIT_initDStream(&bitD2, istart2, length2);
  1504. if (HUF_isError(errorCode)) return errorCode;
  1505. errorCode = BIT_initDStream(&bitD3, istart3, length3);
  1506. if (HUF_isError(errorCode)) return errorCode;
  1507. errorCode = BIT_initDStream(&bitD4, istart4, length4);
  1508. if (HUF_isError(errorCode)) return errorCode;
  1509. /* 16-32 symbols per loop (4-8 symbols per stream) */
  1510. endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
  1511. for ( ; (endSignal==BIT_DStream_unfinished) && (op4<(oend-7)) ; )
  1512. {
  1513. HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
  1514. HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
  1515. HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
  1516. HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
  1517. HUF_DECODE_SYMBOLX2_1(op1, &bitD1);
  1518. HUF_DECODE_SYMBOLX2_1(op2, &bitD2);
  1519. HUF_DECODE_SYMBOLX2_1(op3, &bitD3);
  1520. HUF_DECODE_SYMBOLX2_1(op4, &bitD4);
  1521. HUF_DECODE_SYMBOLX2_2(op1, &bitD1);
  1522. HUF_DECODE_SYMBOLX2_2(op2, &bitD2);
  1523. HUF_DECODE_SYMBOLX2_2(op3, &bitD3);
  1524. HUF_DECODE_SYMBOLX2_2(op4, &bitD4);
  1525. HUF_DECODE_SYMBOLX2_0(op1, &bitD1);
  1526. HUF_DECODE_SYMBOLX2_0(op2, &bitD2);
  1527. HUF_DECODE_SYMBOLX2_0(op3, &bitD3);
  1528. HUF_DECODE_SYMBOLX2_0(op4, &bitD4);
  1529. endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
  1530. }
  1531. /* check corruption */
  1532. if (op1 > opStart2) return ERROR(corruption_detected);
  1533. if (op2 > opStart3) return ERROR(corruption_detected);
  1534. if (op3 > opStart4) return ERROR(corruption_detected);
  1535. /* note : op4 supposed already verified within main loop */
  1536. /* finish bitStreams one by one */
  1537. HUF_decodeStreamX2(op1, &bitD1, opStart2, dt, dtLog);
  1538. HUF_decodeStreamX2(op2, &bitD2, opStart3, dt, dtLog);
  1539. HUF_decodeStreamX2(op3, &bitD3, opStart4, dt, dtLog);
  1540. HUF_decodeStreamX2(op4, &bitD4, oend, dt, dtLog);
  1541. /* check */
  1542. endSignal = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
  1543. if (!endSignal) return ERROR(corruption_detected);
  1544. /* decoded size */
  1545. return dstSize;
  1546. }
  1547. }
  1548. static size_t HUF_decompress4X2 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1549. {
  1550. HUF_CREATE_STATIC_DTABLEX2(DTable, HUF_MAX_TABLELOG);
  1551. const BYTE* ip = (const BYTE*) cSrc;
  1552. size_t errorCode;
  1553. errorCode = HUF_readDTableX2 (DTable, cSrc, cSrcSize);
  1554. if (HUF_isError(errorCode)) return errorCode;
  1555. if (errorCode >= cSrcSize) return ERROR(srcSize_wrong);
  1556. ip += errorCode;
  1557. cSrcSize -= errorCode;
  1558. return HUF_decompress4X2_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
  1559. }
  1560. /***************************/
  1561. /* double-symbols decoding */
  1562. /***************************/
  1563. static void HUF_fillDTableX4Level2(HUF_DEltX4* DTable, U32 sizeLog, const U32 consumed,
  1564. const U32* rankValOrigin, const int minWeight,
  1565. const sortedSymbol_t* sortedSymbols, const U32 sortedListSize,
  1566. U32 nbBitsBaseline, U16 baseSeq)
  1567. {
  1568. HUF_DEltX4 DElt;
  1569. U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1];
  1570. U32 s;
  1571. /* get pre-calculated rankVal */
  1572. memcpy(rankVal, rankValOrigin, sizeof(rankVal));
  1573. /* fill skipped values */
  1574. if (minWeight>1)
  1575. {
  1576. U32 i, skipSize = rankVal[minWeight];
  1577. MEM_writeLE16(&(DElt.sequence), baseSeq);
  1578. DElt.nbBits = (BYTE)(consumed);
  1579. DElt.length = 1;
  1580. for (i = 0; i < skipSize; i++)
  1581. DTable[i] = DElt;
  1582. }
  1583. /* fill DTable */
  1584. for (s=0; s<sortedListSize; s++) /* note : sortedSymbols already skipped */
  1585. {
  1586. const U32 symbol = sortedSymbols[s].symbol;
  1587. const U32 weight = sortedSymbols[s].weight;
  1588. const U32 nbBits = nbBitsBaseline - weight;
  1589. const U32 length = 1 << (sizeLog-nbBits);
  1590. const U32 start = rankVal[weight];
  1591. U32 i = start;
  1592. const U32 end = start + length;
  1593. MEM_writeLE16(&(DElt.sequence), (U16)(baseSeq + (symbol << 8)));
  1594. DElt.nbBits = (BYTE)(nbBits + consumed);
  1595. DElt.length = 2;
  1596. do { DTable[i++] = DElt; } while (i<end); /* since length >= 1 */
  1597. rankVal[weight] += length;
  1598. }
  1599. }
  1600. typedef U32 rankVal_t[HUF_ABSOLUTEMAX_TABLELOG][HUF_ABSOLUTEMAX_TABLELOG + 1];
  1601. static void HUF_fillDTableX4(HUF_DEltX4* DTable, const U32 targetLog,
  1602. const sortedSymbol_t* sortedList, const U32 sortedListSize,
  1603. const U32* rankStart, rankVal_t rankValOrigin, const U32 maxWeight,
  1604. const U32 nbBitsBaseline)
  1605. {
  1606. U32 rankVal[HUF_ABSOLUTEMAX_TABLELOG + 1];
  1607. const int scaleLog = nbBitsBaseline - targetLog; /* note : targetLog >= srcLog, hence scaleLog <= 1 */
  1608. const U32 minBits = nbBitsBaseline - maxWeight;
  1609. U32 s;
  1610. memcpy(rankVal, rankValOrigin, sizeof(rankVal));
  1611. /* fill DTable */
  1612. for (s=0; s<sortedListSize; s++)
  1613. {
  1614. const U16 symbol = sortedList[s].symbol;
  1615. const U32 weight = sortedList[s].weight;
  1616. const U32 nbBits = nbBitsBaseline - weight;
  1617. const U32 start = rankVal[weight];
  1618. const U32 length = 1 << (targetLog-nbBits);
  1619. if (targetLog-nbBits >= minBits) /* enough room for a second symbol */
  1620. {
  1621. U32 sortedRank;
  1622. int minWeight = nbBits + scaleLog;
  1623. if (minWeight < 1) minWeight = 1;
  1624. sortedRank = rankStart[minWeight];
  1625. HUF_fillDTableX4Level2(DTable+start, targetLog-nbBits, nbBits,
  1626. rankValOrigin[nbBits], minWeight,
  1627. sortedList+sortedRank, sortedListSize-sortedRank,
  1628. nbBitsBaseline, symbol);
  1629. }
  1630. else
  1631. {
  1632. U32 i;
  1633. const U32 end = start + length;
  1634. HUF_DEltX4 DElt;
  1635. MEM_writeLE16(&(DElt.sequence), symbol);
  1636. DElt.nbBits = (BYTE)(nbBits);
  1637. DElt.length = 1;
  1638. for (i = start; i < end; i++)
  1639. DTable[i] = DElt;
  1640. }
  1641. rankVal[weight] += length;
  1642. }
  1643. }
  1644. static size_t HUF_readDTableX4 (U32* DTable, const void* src, size_t srcSize)
  1645. {
  1646. BYTE weightList[HUF_MAX_SYMBOL_VALUE + 1];
  1647. sortedSymbol_t sortedSymbol[HUF_MAX_SYMBOL_VALUE + 1];
  1648. U32 rankStats[HUF_ABSOLUTEMAX_TABLELOG + 1] = { 0 };
  1649. U32 rankStart0[HUF_ABSOLUTEMAX_TABLELOG + 2] = { 0 };
  1650. U32* const rankStart = rankStart0+1;
  1651. rankVal_t rankVal;
  1652. U32 tableLog, maxW, sizeOfSort, nbSymbols;
  1653. const U32 memLog = DTable[0];
  1654. size_t iSize;
  1655. void* dtPtr = DTable;
  1656. HUF_DEltX4* const dt = ((HUF_DEltX4*)dtPtr) + 1;
  1657. HUF_STATIC_ASSERT(sizeof(HUF_DEltX4) == sizeof(U32)); /* if compilation fails here, assertion is false */
  1658. if (memLog > HUF_ABSOLUTEMAX_TABLELOG) return ERROR(tableLog_tooLarge);
  1659. //memset(weightList, 0, sizeof(weightList)); /* is not necessary, even though some analyzer complain ... */
  1660. iSize = HUF_readStats(weightList, HUF_MAX_SYMBOL_VALUE + 1, rankStats, &nbSymbols, &tableLog, src, srcSize);
  1661. if (HUF_isError(iSize)) return iSize;
  1662. /* check result */
  1663. if (tableLog > memLog) return ERROR(tableLog_tooLarge); /* DTable can't fit code depth */
  1664. /* find maxWeight */
  1665. for (maxW = tableLog; rankStats[maxW]==0; maxW--)
  1666. { if (!maxW) return ERROR(GENERIC); } /* necessarily finds a solution before maxW==0 */
  1667. /* Get start index of each weight */
  1668. {
  1669. U32 w, nextRankStart = 0;
  1670. for (w=1; w<=maxW; w++)
  1671. {
  1672. U32 current = nextRankStart;
  1673. nextRankStart += rankStats[w];
  1674. rankStart[w] = current;
  1675. }
  1676. rankStart[0] = nextRankStart; /* put all 0w symbols at the end of sorted list*/
  1677. sizeOfSort = nextRankStart;
  1678. }
  1679. /* sort symbols by weight */
  1680. {
  1681. U32 s;
  1682. for (s=0; s<nbSymbols; s++)
  1683. {
  1684. U32 w = weightList[s];
  1685. U32 r = rankStart[w]++;
  1686. sortedSymbol[r].symbol = (BYTE)s;
  1687. sortedSymbol[r].weight = (BYTE)w;
  1688. }
  1689. rankStart[0] = 0; /* forget 0w symbols; this is beginning of weight(1) */
  1690. }
  1691. /* Build rankVal */
  1692. {
  1693. const U32 minBits = tableLog+1 - maxW;
  1694. U32 nextRankVal = 0;
  1695. U32 w, consumed;
  1696. const int rescale = (memLog-tableLog) - 1; /* tableLog <= memLog */
  1697. U32* rankVal0 = rankVal[0];
  1698. for (w=1; w<=maxW; w++)
  1699. {
  1700. U32 current = nextRankVal;
  1701. nextRankVal += rankStats[w] << (w+rescale);
  1702. rankVal0[w] = current;
  1703. }
  1704. for (consumed = minBits; consumed <= memLog - minBits; consumed++)
  1705. {
  1706. U32* rankValPtr = rankVal[consumed];
  1707. for (w = 1; w <= maxW; w++)
  1708. {
  1709. rankValPtr[w] = rankVal0[w] >> consumed;
  1710. }
  1711. }
  1712. }
  1713. HUF_fillDTableX4(dt, memLog,
  1714. sortedSymbol, sizeOfSort,
  1715. rankStart0, rankVal, maxW,
  1716. tableLog+1);
  1717. return iSize;
  1718. }
  1719. static U32 HUF_decodeSymbolX4(void* op, BIT_DStream_t* DStream, const HUF_DEltX4* dt, const U32 dtLog)
  1720. {
  1721. const size_t val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
  1722. memcpy(op, dt+val, 2);
  1723. BIT_skipBits(DStream, dt[val].nbBits);
  1724. return dt[val].length;
  1725. }
  1726. static U32 HUF_decodeLastSymbolX4(void* op, BIT_DStream_t* DStream, const HUF_DEltX4* dt, const U32 dtLog)
  1727. {
  1728. const size_t val = BIT_lookBitsFast(DStream, dtLog); /* note : dtLog >= 1 */
  1729. memcpy(op, dt+val, 1);
  1730. if (dt[val].length==1) BIT_skipBits(DStream, dt[val].nbBits);
  1731. else
  1732. {
  1733. if (DStream->bitsConsumed < (sizeof(DStream->bitContainer)*8))
  1734. {
  1735. BIT_skipBits(DStream, dt[val].nbBits);
  1736. if (DStream->bitsConsumed > (sizeof(DStream->bitContainer)*8))
  1737. 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 */
  1738. }
  1739. }
  1740. return 1;
  1741. }
  1742. #define HUF_DECODE_SYMBOLX4_0(ptr, DStreamPtr) \
  1743. ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  1744. #define HUF_DECODE_SYMBOLX4_1(ptr, DStreamPtr) \
  1745. if (MEM_64bits() || (HUF_MAX_TABLELOG<=12)) \
  1746. ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  1747. #define HUF_DECODE_SYMBOLX4_2(ptr, DStreamPtr) \
  1748. if (MEM_64bits()) \
  1749. ptr += HUF_decodeSymbolX4(ptr, DStreamPtr, dt, dtLog)
  1750. static inline size_t HUF_decodeStreamX4(BYTE* p, BIT_DStream_t* bitDPtr, BYTE* const pEnd, const HUF_DEltX4* const dt, const U32 dtLog)
  1751. {
  1752. BYTE* const pStart = p;
  1753. /* up to 8 symbols at a time */
  1754. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p < pEnd-7))
  1755. {
  1756. HUF_DECODE_SYMBOLX4_2(p, bitDPtr);
  1757. HUF_DECODE_SYMBOLX4_1(p, bitDPtr);
  1758. HUF_DECODE_SYMBOLX4_2(p, bitDPtr);
  1759. HUF_DECODE_SYMBOLX4_0(p, bitDPtr);
  1760. }
  1761. /* closer to the end */
  1762. while ((BIT_reloadDStream(bitDPtr) == BIT_DStream_unfinished) && (p <= pEnd-2))
  1763. HUF_DECODE_SYMBOLX4_0(p, bitDPtr);
  1764. while (p <= pEnd-2)
  1765. HUF_DECODE_SYMBOLX4_0(p, bitDPtr); /* no need to reload : reached the end of DStream */
  1766. if (p < pEnd)
  1767. p += HUF_decodeLastSymbolX4(p, bitDPtr, dt, dtLog);
  1768. return p-pStart;
  1769. }
  1770. static size_t HUF_decompress4X4_usingDTable(
  1771. void* dst, size_t dstSize,
  1772. const void* cSrc, size_t cSrcSize,
  1773. const U32* DTable)
  1774. {
  1775. if (cSrcSize < 10) return ERROR(corruption_detected); /* strict minimum : jump table + 1 byte per stream */
  1776. {
  1777. const BYTE* const istart = (const BYTE*) cSrc;
  1778. BYTE* const ostart = (BYTE*) dst;
  1779. BYTE* const oend = ostart + dstSize;
  1780. const void* const dtPtr = DTable;
  1781. const HUF_DEltX4* const dt = ((const HUF_DEltX4*)dtPtr) +1;
  1782. const U32 dtLog = DTable[0];
  1783. size_t errorCode;
  1784. /* Init */
  1785. BIT_DStream_t bitD1;
  1786. BIT_DStream_t bitD2;
  1787. BIT_DStream_t bitD3;
  1788. BIT_DStream_t bitD4;
  1789. const size_t length1 = MEM_readLE16(istart);
  1790. const size_t length2 = MEM_readLE16(istart+2);
  1791. const size_t length3 = MEM_readLE16(istart+4);
  1792. size_t length4;
  1793. const BYTE* const istart1 = istart + 6; /* jumpTable */
  1794. const BYTE* const istart2 = istart1 + length1;
  1795. const BYTE* const istart3 = istart2 + length2;
  1796. const BYTE* const istart4 = istart3 + length3;
  1797. const size_t segmentSize = (dstSize+3) / 4;
  1798. BYTE* const opStart2 = ostart + segmentSize;
  1799. BYTE* const opStart3 = opStart2 + segmentSize;
  1800. BYTE* const opStart4 = opStart3 + segmentSize;
  1801. BYTE* op1 = ostart;
  1802. BYTE* op2 = opStart2;
  1803. BYTE* op3 = opStart3;
  1804. BYTE* op4 = opStart4;
  1805. U32 endSignal;
  1806. length4 = cSrcSize - (length1 + length2 + length3 + 6);
  1807. if (length4 > cSrcSize) return ERROR(corruption_detected); /* overflow */
  1808. errorCode = BIT_initDStream(&bitD1, istart1, length1);
  1809. if (HUF_isError(errorCode)) return errorCode;
  1810. errorCode = BIT_initDStream(&bitD2, istart2, length2);
  1811. if (HUF_isError(errorCode)) return errorCode;
  1812. errorCode = BIT_initDStream(&bitD3, istart3, length3);
  1813. if (HUF_isError(errorCode)) return errorCode;
  1814. errorCode = BIT_initDStream(&bitD4, istart4, length4);
  1815. if (HUF_isError(errorCode)) return errorCode;
  1816. /* 16-32 symbols per loop (4-8 symbols per stream) */
  1817. endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
  1818. for ( ; (endSignal==BIT_DStream_unfinished) && (op4<(oend-7)) ; )
  1819. {
  1820. HUF_DECODE_SYMBOLX4_2(op1, &bitD1);
  1821. HUF_DECODE_SYMBOLX4_2(op2, &bitD2);
  1822. HUF_DECODE_SYMBOLX4_2(op3, &bitD3);
  1823. HUF_DECODE_SYMBOLX4_2(op4, &bitD4);
  1824. HUF_DECODE_SYMBOLX4_1(op1, &bitD1);
  1825. HUF_DECODE_SYMBOLX4_1(op2, &bitD2);
  1826. HUF_DECODE_SYMBOLX4_1(op3, &bitD3);
  1827. HUF_DECODE_SYMBOLX4_1(op4, &bitD4);
  1828. HUF_DECODE_SYMBOLX4_2(op1, &bitD1);
  1829. HUF_DECODE_SYMBOLX4_2(op2, &bitD2);
  1830. HUF_DECODE_SYMBOLX4_2(op3, &bitD3);
  1831. HUF_DECODE_SYMBOLX4_2(op4, &bitD4);
  1832. HUF_DECODE_SYMBOLX4_0(op1, &bitD1);
  1833. HUF_DECODE_SYMBOLX4_0(op2, &bitD2);
  1834. HUF_DECODE_SYMBOLX4_0(op3, &bitD3);
  1835. HUF_DECODE_SYMBOLX4_0(op4, &bitD4);
  1836. endSignal = BIT_reloadDStream(&bitD1) | BIT_reloadDStream(&bitD2) | BIT_reloadDStream(&bitD3) | BIT_reloadDStream(&bitD4);
  1837. }
  1838. /* check corruption */
  1839. if (op1 > opStart2) return ERROR(corruption_detected);
  1840. if (op2 > opStart3) return ERROR(corruption_detected);
  1841. if (op3 > opStart4) return ERROR(corruption_detected);
  1842. /* note : op4 supposed already verified within main loop */
  1843. /* finish bitStreams one by one */
  1844. HUF_decodeStreamX4(op1, &bitD1, opStart2, dt, dtLog);
  1845. HUF_decodeStreamX4(op2, &bitD2, opStart3, dt, dtLog);
  1846. HUF_decodeStreamX4(op3, &bitD3, opStart4, dt, dtLog);
  1847. HUF_decodeStreamX4(op4, &bitD4, oend, dt, dtLog);
  1848. /* check */
  1849. endSignal = BIT_endOfDStream(&bitD1) & BIT_endOfDStream(&bitD2) & BIT_endOfDStream(&bitD3) & BIT_endOfDStream(&bitD4);
  1850. if (!endSignal) return ERROR(corruption_detected);
  1851. /* decoded size */
  1852. return dstSize;
  1853. }
  1854. }
  1855. static size_t HUF_decompress4X4 (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1856. {
  1857. HUF_CREATE_STATIC_DTABLEX4(DTable, HUF_MAX_TABLELOG);
  1858. const BYTE* ip = (const BYTE*) cSrc;
  1859. size_t hSize = HUF_readDTableX4 (DTable, cSrc, cSrcSize);
  1860. if (HUF_isError(hSize)) return hSize;
  1861. if (hSize >= cSrcSize) return ERROR(srcSize_wrong);
  1862. ip += hSize;
  1863. cSrcSize -= hSize;
  1864. return HUF_decompress4X4_usingDTable (dst, dstSize, ip, cSrcSize, DTable);
  1865. }
  1866. /**********************************/
  1867. /* Generic decompression selector */
  1868. /**********************************/
  1869. typedef struct { U32 tableTime; U32 decode256Time; } algo_time_t;
  1870. static const algo_time_t algoTime[16 /* Quantization */][3 /* single, double, quad */] =
  1871. {
  1872. /* single, double, quad */
  1873. {{0,0}, {1,1}, {2,2}}, /* Q==0 : impossible */
  1874. {{0,0}, {1,1}, {2,2}}, /* Q==1 : impossible */
  1875. {{ 38,130}, {1313, 74}, {2151, 38}}, /* Q == 2 : 12-18% */
  1876. {{ 448,128}, {1353, 74}, {2238, 41}}, /* Q == 3 : 18-25% */
  1877. {{ 556,128}, {1353, 74}, {2238, 47}}, /* Q == 4 : 25-32% */
  1878. {{ 714,128}, {1418, 74}, {2436, 53}}, /* Q == 5 : 32-38% */
  1879. {{ 883,128}, {1437, 74}, {2464, 61}}, /* Q == 6 : 38-44% */
  1880. {{ 897,128}, {1515, 75}, {2622, 68}}, /* Q == 7 : 44-50% */
  1881. {{ 926,128}, {1613, 75}, {2730, 75}}, /* Q == 8 : 50-56% */
  1882. {{ 947,128}, {1729, 77}, {3359, 77}}, /* Q == 9 : 56-62% */
  1883. {{1107,128}, {2083, 81}, {4006, 84}}, /* Q ==10 : 62-69% */
  1884. {{1177,128}, {2379, 87}, {4785, 88}}, /* Q ==11 : 69-75% */
  1885. {{1242,128}, {2415, 93}, {5155, 84}}, /* Q ==12 : 75-81% */
  1886. {{1349,128}, {2644,106}, {5260,106}}, /* Q ==13 : 81-87% */
  1887. {{1455,128}, {2422,124}, {4174,124}}, /* Q ==14 : 87-93% */
  1888. {{ 722,128}, {1891,145}, {1936,146}}, /* Q ==15 : 93-99% */
  1889. };
  1890. typedef size_t (*decompressionAlgo)(void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize);
  1891. static size_t HUF_decompress (void* dst, size_t dstSize, const void* cSrc, size_t cSrcSize)
  1892. {
  1893. static const decompressionAlgo decompress[3] = { HUF_decompress4X2, HUF_decompress4X4, NULL };
  1894. /* estimate decompression time */
  1895. U32 Q;
  1896. const U32 D256 = (U32)(dstSize >> 8);
  1897. U32 Dtime[3];
  1898. U32 algoNb = 0;
  1899. int n;
  1900. /* validation checks */
  1901. if (dstSize == 0) return ERROR(dstSize_tooSmall);
  1902. if (cSrcSize > dstSize) return ERROR(corruption_detected); /* invalid */
  1903. if (cSrcSize == dstSize) { memcpy(dst, cSrc, dstSize); return dstSize; } /* not compressed */
  1904. if (cSrcSize == 1) { memset(dst, *(const BYTE*)cSrc, dstSize); return dstSize; } /* RLE */
  1905. /* decoder timing evaluation */
  1906. Q = (U32)(cSrcSize * 16 / dstSize); /* Q < 16 since dstSize > cSrcSize */
  1907. for (n=0; n<3; n++)
  1908. Dtime[n] = algoTime[Q][n].tableTime + (algoTime[Q][n].decode256Time * D256);
  1909. Dtime[1] += Dtime[1] >> 4; Dtime[2] += Dtime[2] >> 3; /* advantage to algorithms using less memory, for cache eviction */
  1910. if (Dtime[1] < Dtime[0]) algoNb = 1;
  1911. return decompress[algoNb](dst, dstSize, cSrc, cSrcSize);
  1912. //return HUF_decompress4X2(dst, dstSize, cSrc, cSrcSize); /* multi-streams single-symbol decoding */
  1913. //return HUF_decompress4X4(dst, dstSize, cSrc, cSrcSize); /* multi-streams double-symbols decoding */
  1914. //return HUF_decompress4X6(dst, dstSize, cSrc, cSrcSize); /* multi-streams quad-symbols decoding */
  1915. }
  1916. #endif /* ZSTD_CCOMMON_H_MODULE */
  1917. /*
  1918. zstd - decompression module fo v0.4 legacy format
  1919. Copyright (C) 2015-2016, Yann Collet.
  1920. BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
  1921. Redistribution and use in source and binary forms, with or without
  1922. modification, are permitted provided that the following conditions are
  1923. met:
  1924. * Redistributions of source code must retain the above copyright
  1925. notice, this list of conditions and the following disclaimer.
  1926. * Redistributions in binary form must reproduce the above
  1927. copyright notice, this list of conditions and the following disclaimer
  1928. in the documentation and/or other materials provided with the
  1929. distribution.
  1930. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  1931. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  1932. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  1933. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  1934. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  1935. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1936. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  1937. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  1938. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  1939. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  1940. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1941. You can contact the author at :
  1942. - zstd source repository : https://github.com/Cyan4973/zstd
  1943. - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
  1944. */
  1945. /* ***************************************************************
  1946. * Tuning parameters
  1947. *****************************************************************/
  1948. /*!
  1949. * HEAPMODE :
  1950. * Select how default decompression function ZSTD_decompress() will allocate memory,
  1951. * in memory stack (0), or in memory heap (1, requires malloc())
  1952. */
  1953. #ifndef ZSTD_HEAPMODE
  1954. # define ZSTD_HEAPMODE 1
  1955. #endif
  1956. /* *******************************************************
  1957. * Includes
  1958. *********************************************************/
  1959. #include <stdlib.h> /* calloc */
  1960. #include <string.h> /* memcpy, memmove */
  1961. #include <stdio.h> /* debug : printf */
  1962. /* *******************************************************
  1963. * Compiler specifics
  1964. *********************************************************/
  1965. #ifdef _MSC_VER /* Visual Studio */
  1966. # include <intrin.h> /* For Visual 2005 */
  1967. # pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
  1968. # pragma warning(disable : 4324) /* disable: C4324: padded structure */
  1969. #endif
  1970. /* *************************************
  1971. * Local types
  1972. ***************************************/
  1973. typedef struct
  1974. {
  1975. blockType_t blockType;
  1976. U32 origSize;
  1977. } blockProperties_t;
  1978. /* *******************************************************
  1979. * Memory operations
  1980. **********************************************************/
  1981. static void ZSTD_copy4(void* dst, const void* src) { memcpy(dst, src, 4); }
  1982. /* *************************************
  1983. * Error Management
  1984. ***************************************/
  1985. /*! ZSTD_isError
  1986. * tells if a return value is an error code */
  1987. static unsigned ZSTD_isError(size_t code) { return ERR_isError(code); }
  1988. /* *************************************************************
  1989. * Context management
  1990. ***************************************************************/
  1991. typedef enum { ZSTDds_getFrameHeaderSize, ZSTDds_decodeFrameHeader,
  1992. ZSTDds_decodeBlockHeader, ZSTDds_decompressBlock } ZSTD_dStage;
  1993. struct ZSTDv04_Dctx_s
  1994. {
  1995. U32 LLTable[FSE_DTABLE_SIZE_U32(LLFSELog)];
  1996. U32 OffTable[FSE_DTABLE_SIZE_U32(OffFSELog)];
  1997. U32 MLTable[FSE_DTABLE_SIZE_U32(MLFSELog)];
  1998. const void* previousDstEnd;
  1999. const void* base;
  2000. const void* vBase;
  2001. const void* dictEnd;
  2002. size_t expected;
  2003. size_t headerSize;
  2004. ZSTD_parameters params;
  2005. blockType_t bType;
  2006. ZSTD_dStage stage;
  2007. const BYTE* litPtr;
  2008. size_t litSize;
  2009. BYTE litBuffer[BLOCKSIZE + 8 /* margin for wildcopy */];
  2010. BYTE headerBuffer[ZSTD_frameHeaderSize_max];
  2011. }; /* typedef'd to ZSTD_DCtx within "zstd_static.h" */
  2012. static size_t ZSTD_resetDCtx(ZSTD_DCtx* dctx)
  2013. {
  2014. dctx->expected = ZSTD_frameHeaderSize_min;
  2015. dctx->stage = ZSTDds_getFrameHeaderSize;
  2016. dctx->previousDstEnd = NULL;
  2017. dctx->base = NULL;
  2018. dctx->vBase = NULL;
  2019. dctx->dictEnd = NULL;
  2020. return 0;
  2021. }
  2022. static ZSTD_DCtx* ZSTD_createDCtx(void)
  2023. {
  2024. ZSTD_DCtx* dctx = (ZSTD_DCtx*)malloc(sizeof(ZSTD_DCtx));
  2025. if (dctx==NULL) return NULL;
  2026. ZSTD_resetDCtx(dctx);
  2027. return dctx;
  2028. }
  2029. static size_t ZSTD_freeDCtx(ZSTD_DCtx* dctx)
  2030. {
  2031. free(dctx);
  2032. return 0;
  2033. }
  2034. /* *************************************************************
  2035. * Decompression section
  2036. ***************************************************************/
  2037. /** ZSTD_decodeFrameHeader_Part1
  2038. * decode the 1st part of the Frame Header, which tells Frame Header size.
  2039. * srcSize must be == ZSTD_frameHeaderSize_min
  2040. * @return : the full size of the Frame Header */
  2041. static size_t ZSTD_decodeFrameHeader_Part1(ZSTD_DCtx* zc, const void* src, size_t srcSize)
  2042. {
  2043. U32 magicNumber;
  2044. if (srcSize != ZSTD_frameHeaderSize_min) return ERROR(srcSize_wrong);
  2045. magicNumber = MEM_readLE32(src);
  2046. if (magicNumber != ZSTD_MAGICNUMBER) return ERROR(prefix_unknown);
  2047. zc->headerSize = ZSTD_frameHeaderSize_min;
  2048. return zc->headerSize;
  2049. }
  2050. static size_t ZSTD_getFrameParams(ZSTD_parameters* params, const void* src, size_t srcSize)
  2051. {
  2052. U32 magicNumber;
  2053. if (srcSize < ZSTD_frameHeaderSize_min) return ZSTD_frameHeaderSize_max;
  2054. magicNumber = MEM_readLE32(src);
  2055. if (magicNumber != ZSTD_MAGICNUMBER) return ERROR(prefix_unknown);
  2056. memset(params, 0, sizeof(*params));
  2057. params->windowLog = (((const BYTE*)src)[4] & 15) + ZSTD_WINDOWLOG_ABSOLUTEMIN;
  2058. if ((((const BYTE*)src)[4] >> 4) != 0) return ERROR(frameParameter_unsupported); /* reserved bits */
  2059. return 0;
  2060. }
  2061. /** ZSTD_decodeFrameHeader_Part2
  2062. * decode the full Frame Header
  2063. * srcSize must be the size provided by ZSTD_decodeFrameHeader_Part1
  2064. * @return : 0, or an error code, which can be tested using ZSTD_isError() */
  2065. static size_t ZSTD_decodeFrameHeader_Part2(ZSTD_DCtx* zc, const void* src, size_t srcSize)
  2066. {
  2067. size_t result;
  2068. if (srcSize != zc->headerSize) return ERROR(srcSize_wrong);
  2069. result = ZSTD_getFrameParams(&(zc->params), src, srcSize);
  2070. if ((MEM_32bits()) && (zc->params.windowLog > 25)) return ERROR(frameParameter_unsupported);
  2071. return result;
  2072. }
  2073. static size_t ZSTD_getcBlockSize(const void* src, size_t srcSize, blockProperties_t* bpPtr)
  2074. {
  2075. const BYTE* const in = (const BYTE* const)src;
  2076. BYTE headerFlags;
  2077. U32 cSize;
  2078. if (srcSize < 3) return ERROR(srcSize_wrong);
  2079. headerFlags = *in;
  2080. cSize = in[2] + (in[1]<<8) + ((in[0] & 7)<<16);
  2081. bpPtr->blockType = (blockType_t)(headerFlags >> 6);
  2082. bpPtr->origSize = (bpPtr->blockType == bt_rle) ? cSize : 0;
  2083. if (bpPtr->blockType == bt_end) return 0;
  2084. if (bpPtr->blockType == bt_rle) return 1;
  2085. return cSize;
  2086. }
  2087. static size_t ZSTD_copyRawBlock(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2088. {
  2089. if (srcSize > maxDstSize) return ERROR(dstSize_tooSmall);
  2090. if (srcSize > 0) {
  2091. memcpy(dst, src, srcSize);
  2092. }
  2093. return srcSize;
  2094. }
  2095. /** ZSTD_decompressLiterals
  2096. @return : nb of bytes read from src, or an error code*/
  2097. static size_t ZSTD_decompressLiterals(void* dst, size_t* maxDstSizePtr,
  2098. const void* src, size_t srcSize)
  2099. {
  2100. const BYTE* ip = (const BYTE*)src;
  2101. const size_t litSize = (MEM_readLE32(src) & 0x1FFFFF) >> 2; /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
  2102. const size_t litCSize = (MEM_readLE32(ip+2) & 0xFFFFFF) >> 5; /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
  2103. if (litSize > *maxDstSizePtr) return ERROR(corruption_detected);
  2104. if (litCSize + 5 > srcSize) return ERROR(corruption_detected);
  2105. if (HUF_isError(HUF_decompress(dst, litSize, ip+5, litCSize))) return ERROR(corruption_detected);
  2106. *maxDstSizePtr = litSize;
  2107. return litCSize + 5;
  2108. }
  2109. /** ZSTD_decodeLiteralsBlock
  2110. @return : nb of bytes read from src (< srcSize ) */
  2111. static size_t ZSTD_decodeLiteralsBlock(ZSTD_DCtx* dctx,
  2112. const void* src, size_t srcSize) /* note : srcSize < BLOCKSIZE */
  2113. {
  2114. const BYTE* const istart = (const BYTE*) src;
  2115. /* any compressed block with literals segment must be at least this size */
  2116. if (srcSize < MIN_CBLOCK_SIZE) return ERROR(corruption_detected);
  2117. switch(*istart & 3)
  2118. {
  2119. /* compressed */
  2120. case 0:
  2121. {
  2122. size_t litSize = BLOCKSIZE;
  2123. const size_t readSize = ZSTD_decompressLiterals(dctx->litBuffer, &litSize, src, srcSize);
  2124. dctx->litPtr = dctx->litBuffer;
  2125. dctx->litSize = litSize;
  2126. memset(dctx->litBuffer + dctx->litSize, 0, 8);
  2127. return readSize; /* works if it's an error too */
  2128. }
  2129. case IS_RAW:
  2130. {
  2131. const size_t litSize = (MEM_readLE32(istart) & 0xFFFFFF) >> 2; /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
  2132. if (litSize > srcSize-11) /* risk of reading too far with wildcopy */
  2133. {
  2134. if (litSize > BLOCKSIZE) return ERROR(corruption_detected);
  2135. if (litSize > srcSize-3) return ERROR(corruption_detected);
  2136. memcpy(dctx->litBuffer, istart, litSize);
  2137. dctx->litPtr = dctx->litBuffer;
  2138. dctx->litSize = litSize;
  2139. memset(dctx->litBuffer + dctx->litSize, 0, 8);
  2140. return litSize+3;
  2141. }
  2142. /* direct reference into compressed stream */
  2143. dctx->litPtr = istart+3;
  2144. dctx->litSize = litSize;
  2145. return litSize+3; }
  2146. case IS_RLE:
  2147. {
  2148. const size_t litSize = (MEM_readLE32(istart) & 0xFFFFFF) >> 2; /* no buffer issue : srcSize >= MIN_CBLOCK_SIZE */
  2149. if (litSize > BLOCKSIZE) return ERROR(corruption_detected);
  2150. memset(dctx->litBuffer, istart[3], litSize + 8);
  2151. dctx->litPtr = dctx->litBuffer;
  2152. dctx->litSize = litSize;
  2153. return 4;
  2154. }
  2155. default:
  2156. return ERROR(corruption_detected); /* forbidden nominal case */
  2157. }
  2158. }
  2159. static size_t ZSTD_decodeSeqHeaders(int* nbSeq, const BYTE** dumpsPtr, size_t* dumpsLengthPtr,
  2160. FSE_DTable* DTableLL, FSE_DTable* DTableML, FSE_DTable* DTableOffb,
  2161. const void* src, size_t srcSize)
  2162. {
  2163. const BYTE* const istart = (const BYTE* const)src;
  2164. const BYTE* ip = istart;
  2165. const BYTE* const iend = istart + srcSize;
  2166. U32 LLtype, Offtype, MLtype;
  2167. U32 LLlog, Offlog, MLlog;
  2168. size_t dumpsLength;
  2169. /* check */
  2170. if (srcSize < 5) return ERROR(srcSize_wrong);
  2171. /* SeqHead */
  2172. *nbSeq = MEM_readLE16(ip); ip+=2;
  2173. LLtype = *ip >> 6;
  2174. Offtype = (*ip >> 4) & 3;
  2175. MLtype = (*ip >> 2) & 3;
  2176. if (*ip & 2)
  2177. {
  2178. dumpsLength = ip[2];
  2179. dumpsLength += ip[1] << 8;
  2180. ip += 3;
  2181. }
  2182. else
  2183. {
  2184. dumpsLength = ip[1];
  2185. dumpsLength += (ip[0] & 1) << 8;
  2186. ip += 2;
  2187. }
  2188. *dumpsPtr = ip;
  2189. ip += dumpsLength;
  2190. *dumpsLengthPtr = dumpsLength;
  2191. /* check */
  2192. if (ip > iend-3) return ERROR(srcSize_wrong); /* min : all 3 are "raw", hence no header, but at least xxLog bits per type */
  2193. /* sequences */
  2194. {
  2195. S16 norm[MaxML+1]; /* assumption : MaxML >= MaxLL >= MaxOff */
  2196. size_t headerSize;
  2197. /* Build DTables */
  2198. switch(LLtype)
  2199. {
  2200. case bt_rle :
  2201. LLlog = 0;
  2202. FSE_buildDTable_rle(DTableLL, *ip++); break;
  2203. case bt_raw :
  2204. LLlog = LLbits;
  2205. FSE_buildDTable_raw(DTableLL, LLbits); break;
  2206. default :
  2207. { U32 max = MaxLL;
  2208. headerSize = FSE_readNCount(norm, &max, &LLlog, ip, iend-ip);
  2209. if (FSE_isError(headerSize)) return ERROR(GENERIC);
  2210. if (LLlog > LLFSELog) return ERROR(corruption_detected);
  2211. ip += headerSize;
  2212. FSE_buildDTable(DTableLL, norm, max, LLlog);
  2213. } }
  2214. switch(Offtype)
  2215. {
  2216. case bt_rle :
  2217. Offlog = 0;
  2218. if (ip > iend-2) return ERROR(srcSize_wrong); /* min : "raw", hence no header, but at least xxLog bits */
  2219. FSE_buildDTable_rle(DTableOffb, *ip++ & MaxOff); /* if *ip > MaxOff, data is corrupted */
  2220. break;
  2221. case bt_raw :
  2222. Offlog = Offbits;
  2223. FSE_buildDTable_raw(DTableOffb, Offbits); break;
  2224. default :
  2225. { U32 max = MaxOff;
  2226. headerSize = FSE_readNCount(norm, &max, &Offlog, ip, iend-ip);
  2227. if (FSE_isError(headerSize)) return ERROR(GENERIC);
  2228. if (Offlog > OffFSELog) return ERROR(corruption_detected);
  2229. ip += headerSize;
  2230. FSE_buildDTable(DTableOffb, norm, max, Offlog);
  2231. } }
  2232. switch(MLtype)
  2233. {
  2234. case bt_rle :
  2235. MLlog = 0;
  2236. if (ip > iend-2) return ERROR(srcSize_wrong); /* min : "raw", hence no header, but at least xxLog bits */
  2237. FSE_buildDTable_rle(DTableML, *ip++); break;
  2238. case bt_raw :
  2239. MLlog = MLbits;
  2240. FSE_buildDTable_raw(DTableML, MLbits); break;
  2241. default :
  2242. { U32 max = MaxML;
  2243. headerSize = FSE_readNCount(norm, &max, &MLlog, ip, iend-ip);
  2244. if (FSE_isError(headerSize)) return ERROR(GENERIC);
  2245. if (MLlog > MLFSELog) return ERROR(corruption_detected);
  2246. ip += headerSize;
  2247. FSE_buildDTable(DTableML, norm, max, MLlog);
  2248. } } }
  2249. return ip-istart;
  2250. }
  2251. typedef struct {
  2252. size_t litLength;
  2253. size_t offset;
  2254. size_t matchLength;
  2255. } seq_t;
  2256. typedef struct {
  2257. BIT_DStream_t DStream;
  2258. FSE_DState_t stateLL;
  2259. FSE_DState_t stateOffb;
  2260. FSE_DState_t stateML;
  2261. size_t prevOffset;
  2262. const BYTE* dumps;
  2263. const BYTE* dumpsEnd;
  2264. } seqState_t;
  2265. static void ZSTD_decodeSequence(seq_t* seq, seqState_t* seqState)
  2266. {
  2267. size_t litLength;
  2268. size_t prevOffset;
  2269. size_t offset;
  2270. size_t matchLength;
  2271. const BYTE* dumps = seqState->dumps;
  2272. const BYTE* const de = seqState->dumpsEnd;
  2273. /* Literal length */
  2274. litLength = FSE_decodeSymbol(&(seqState->stateLL), &(seqState->DStream));
  2275. prevOffset = litLength ? seq->offset : seqState->prevOffset;
  2276. if (litLength == MaxLL) {
  2277. const U32 add = dumps<de ? *dumps++ : 0;
  2278. if (add < 255) litLength += add;
  2279. else if (dumps + 3 <= de) {
  2280. litLength = MEM_readLE24(dumps);
  2281. dumps += 3;
  2282. }
  2283. if (dumps >= de) { dumps = de-1; } /* late correction, to avoid read overflow (data is now corrupted anyway) */
  2284. }
  2285. /* Offset */
  2286. { static const U32 offsetPrefix[MaxOff+1] = {
  2287. 1 /*fake*/, 1, 2, 4, 8, 16, 32, 64, 128, 256,
  2288. 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144,
  2289. 524288, 1048576, 2097152, 4194304, 8388608, 16777216, 33554432, /*fake*/ 1, 1, 1, 1, 1 };
  2290. U32 offsetCode, nbBits;
  2291. offsetCode = FSE_decodeSymbol(&(seqState->stateOffb), &(seqState->DStream)); /* <= maxOff, by table construction */
  2292. if (MEM_32bits()) BIT_reloadDStream(&(seqState->DStream));
  2293. nbBits = offsetCode - 1;
  2294. if (offsetCode==0) nbBits = 0; /* cmove */
  2295. offset = offsetPrefix[offsetCode] + BIT_readBits(&(seqState->DStream), nbBits);
  2296. if (MEM_32bits()) BIT_reloadDStream(&(seqState->DStream));
  2297. if (offsetCode==0) offset = prevOffset; /* cmove */
  2298. if (offsetCode | !litLength) seqState->prevOffset = seq->offset; /* cmove */
  2299. }
  2300. /* MatchLength */
  2301. matchLength = FSE_decodeSymbol(&(seqState->stateML), &(seqState->DStream));
  2302. if (matchLength == MaxML) {
  2303. const U32 add = dumps<de ? *dumps++ : 0;
  2304. if (add < 255) matchLength += add;
  2305. else if (dumps + 3 <= de){
  2306. matchLength = MEM_readLE24(dumps);
  2307. dumps += 3;
  2308. }
  2309. if (dumps >= de) { dumps = de-1; } /* late correction, to avoid read overflow (data is now corrupted anyway) */
  2310. }
  2311. matchLength += MINMATCH;
  2312. /* save result */
  2313. seq->litLength = litLength;
  2314. seq->offset = offset;
  2315. seq->matchLength = matchLength;
  2316. seqState->dumps = dumps;
  2317. }
  2318. static size_t ZSTD_execSequence(BYTE* op,
  2319. BYTE* const oend, seq_t sequence,
  2320. const BYTE** litPtr, const BYTE* const litLimit,
  2321. const BYTE* const base, const BYTE* const vBase, const BYTE* const dictEnd)
  2322. {
  2323. static const int dec32table[] = { 0, 1, 2, 1, 4, 4, 4, 4 }; /* added */
  2324. static const int dec64table[] = { 8, 8, 8, 7, 8, 9,10,11 }; /* subtracted */
  2325. BYTE* const oLitEnd = op + sequence.litLength;
  2326. const size_t sequenceLength = sequence.litLength + sequence.matchLength;
  2327. BYTE* const oMatchEnd = op + sequenceLength; /* risk : address space overflow (32-bits) */
  2328. BYTE* const oend_8 = oend-8;
  2329. const BYTE* const litEnd = *litPtr + sequence.litLength;
  2330. const BYTE* match = oLitEnd - sequence.offset;
  2331. /* checks */
  2332. size_t const seqLength = sequence.litLength + sequence.matchLength;
  2333. if (seqLength > (size_t)(oend - op)) return ERROR(dstSize_tooSmall);
  2334. if (sequence.litLength > (size_t)(litLimit - *litPtr)) return ERROR(corruption_detected);
  2335. /* Now we know there are no overflow in literal nor match lengths, can use pointer checks */
  2336. if (oLitEnd > oend_8) return ERROR(dstSize_tooSmall);
  2337. if (oMatchEnd > oend) return ERROR(dstSize_tooSmall); /* overwrite beyond dst buffer */
  2338. if (litEnd > litLimit) return ERROR(corruption_detected); /* overRead beyond lit buffer */
  2339. /* copy Literals */
  2340. ZSTD_wildcopy(op, *litPtr, (ptrdiff_t)sequence.litLength); /* note : oLitEnd <= oend-8 : no risk of overwrite beyond oend */
  2341. op = oLitEnd;
  2342. *litPtr = litEnd; /* update for next sequence */
  2343. /* copy Match */
  2344. if (sequence.offset > (size_t)(oLitEnd - base))
  2345. {
  2346. /* offset beyond prefix */
  2347. if (sequence.offset > (size_t)(oLitEnd - vBase))
  2348. return ERROR(corruption_detected);
  2349. match = dictEnd - (base-match);
  2350. if (match + sequence.matchLength <= dictEnd)
  2351. {
  2352. memmove(oLitEnd, match, sequence.matchLength);
  2353. return sequenceLength;
  2354. }
  2355. /* span extDict & currentPrefixSegment */
  2356. {
  2357. size_t length1 = dictEnd - match;
  2358. memmove(oLitEnd, match, length1);
  2359. op = oLitEnd + length1;
  2360. sequence.matchLength -= length1;
  2361. match = base;
  2362. if (op > oend_8 || sequence.matchLength < MINMATCH) {
  2363. while (op < oMatchEnd) *op++ = *match++;
  2364. return sequenceLength;
  2365. }
  2366. }
  2367. }
  2368. /* Requirement: op <= oend_8 */
  2369. /* match within prefix */
  2370. if (sequence.offset < 8) {
  2371. /* close range match, overlap */
  2372. const int sub2 = dec64table[sequence.offset];
  2373. op[0] = match[0];
  2374. op[1] = match[1];
  2375. op[2] = match[2];
  2376. op[3] = match[3];
  2377. match += dec32table[sequence.offset];
  2378. ZSTD_copy4(op+4, match);
  2379. match -= sub2;
  2380. } else {
  2381. ZSTD_copy8(op, match);
  2382. }
  2383. op += 8; match += 8;
  2384. if (oMatchEnd > oend-(16-MINMATCH))
  2385. {
  2386. if (op < oend_8)
  2387. {
  2388. ZSTD_wildcopy(op, match, oend_8 - op);
  2389. match += oend_8 - op;
  2390. op = oend_8;
  2391. }
  2392. while (op < oMatchEnd) *op++ = *match++;
  2393. }
  2394. else
  2395. {
  2396. ZSTD_wildcopy(op, match, (ptrdiff_t)sequence.matchLength-8); /* works even if matchLength < 8, but must be signed */
  2397. }
  2398. return sequenceLength;
  2399. }
  2400. static size_t ZSTD_decompressSequences(
  2401. ZSTD_DCtx* dctx,
  2402. void* dst, size_t maxDstSize,
  2403. const void* seqStart, size_t seqSize)
  2404. {
  2405. const BYTE* ip = (const BYTE*)seqStart;
  2406. const BYTE* const iend = ip + seqSize;
  2407. BYTE* const ostart = (BYTE* const)dst;
  2408. BYTE* op = ostart;
  2409. BYTE* const oend = ostart + maxDstSize;
  2410. size_t errorCode, dumpsLength;
  2411. const BYTE* litPtr = dctx->litPtr;
  2412. const BYTE* const litEnd = litPtr + dctx->litSize;
  2413. int nbSeq;
  2414. const BYTE* dumps;
  2415. U32* DTableLL = dctx->LLTable;
  2416. U32* DTableML = dctx->MLTable;
  2417. U32* DTableOffb = dctx->OffTable;
  2418. const BYTE* const base = (const BYTE*) (dctx->base);
  2419. const BYTE* const vBase = (const BYTE*) (dctx->vBase);
  2420. const BYTE* const dictEnd = (const BYTE*) (dctx->dictEnd);
  2421. /* Build Decoding Tables */
  2422. errorCode = ZSTD_decodeSeqHeaders(&nbSeq, &dumps, &dumpsLength,
  2423. DTableLL, DTableML, DTableOffb,
  2424. ip, iend-ip);
  2425. if (ZSTD_isError(errorCode)) return errorCode;
  2426. ip += errorCode;
  2427. /* Regen sequences */
  2428. {
  2429. seq_t sequence;
  2430. seqState_t seqState;
  2431. memset(&sequence, 0, sizeof(sequence));
  2432. sequence.offset = 4;
  2433. seqState.dumps = dumps;
  2434. seqState.dumpsEnd = dumps + dumpsLength;
  2435. seqState.prevOffset = 4;
  2436. errorCode = BIT_initDStream(&(seqState.DStream), ip, iend-ip);
  2437. if (ERR_isError(errorCode)) return ERROR(corruption_detected);
  2438. FSE_initDState(&(seqState.stateLL), &(seqState.DStream), DTableLL);
  2439. FSE_initDState(&(seqState.stateOffb), &(seqState.DStream), DTableOffb);
  2440. FSE_initDState(&(seqState.stateML), &(seqState.DStream), DTableML);
  2441. for ( ; (BIT_reloadDStream(&(seqState.DStream)) <= BIT_DStream_completed) && nbSeq ; )
  2442. {
  2443. size_t oneSeqSize;
  2444. nbSeq--;
  2445. ZSTD_decodeSequence(&sequence, &seqState);
  2446. oneSeqSize = ZSTD_execSequence(op, oend, sequence, &litPtr, litEnd, base, vBase, dictEnd);
  2447. if (ZSTD_isError(oneSeqSize)) return oneSeqSize;
  2448. op += oneSeqSize;
  2449. }
  2450. /* check if reached exact end */
  2451. if ( !BIT_endOfDStream(&(seqState.DStream)) ) return ERROR(corruption_detected); /* DStream should be entirely and exactly consumed; otherwise data is corrupted */
  2452. /* last literal segment */
  2453. {
  2454. size_t lastLLSize = litEnd - litPtr;
  2455. if (litPtr > litEnd) return ERROR(corruption_detected);
  2456. if (op+lastLLSize > oend) return ERROR(dstSize_tooSmall);
  2457. if (lastLLSize > 0) {
  2458. if (op != litPtr) memcpy(op, litPtr, lastLLSize);
  2459. op += lastLLSize;
  2460. }
  2461. }
  2462. }
  2463. return op-ostart;
  2464. }
  2465. static void ZSTD_checkContinuity(ZSTD_DCtx* dctx, const void* dst)
  2466. {
  2467. if (dst != dctx->previousDstEnd) /* not contiguous */
  2468. {
  2469. dctx->dictEnd = dctx->previousDstEnd;
  2470. dctx->vBase = (const char*)dst - ((const char*)(dctx->previousDstEnd) - (const char*)(dctx->base));
  2471. dctx->base = dst;
  2472. dctx->previousDstEnd = dst;
  2473. }
  2474. }
  2475. static size_t ZSTD_decompressBlock_internal(ZSTD_DCtx* dctx,
  2476. void* dst, size_t maxDstSize,
  2477. const void* src, size_t srcSize)
  2478. {
  2479. /* blockType == blockCompressed */
  2480. const BYTE* ip = (const BYTE*)src;
  2481. size_t litCSize;
  2482. if (srcSize > BLOCKSIZE) return ERROR(corruption_detected);
  2483. /* Decode literals sub-block */
  2484. litCSize = ZSTD_decodeLiteralsBlock(dctx, src, srcSize);
  2485. if (ZSTD_isError(litCSize)) return litCSize;
  2486. ip += litCSize;
  2487. srcSize -= litCSize;
  2488. return ZSTD_decompressSequences(dctx, dst, maxDstSize, ip, srcSize);
  2489. }
  2490. static size_t ZSTD_decompress_usingDict(ZSTD_DCtx* ctx,
  2491. void* dst, size_t maxDstSize,
  2492. const void* src, size_t srcSize,
  2493. const void* dict, size_t dictSize)
  2494. {
  2495. const BYTE* ip = (const BYTE*)src;
  2496. const BYTE* iend = ip + srcSize;
  2497. BYTE* const ostart = (BYTE* const)dst;
  2498. BYTE* op = ostart;
  2499. BYTE* const oend = ostart + maxDstSize;
  2500. size_t remainingSize = srcSize;
  2501. blockProperties_t blockProperties;
  2502. /* init */
  2503. ZSTD_resetDCtx(ctx);
  2504. if (dict)
  2505. {
  2506. ZSTD_decompress_insertDictionary(ctx, dict, dictSize);
  2507. ctx->dictEnd = ctx->previousDstEnd;
  2508. ctx->vBase = (const char*)dst - ((const char*)(ctx->previousDstEnd) - (const char*)(ctx->base));
  2509. ctx->base = dst;
  2510. }
  2511. else
  2512. {
  2513. ctx->vBase = ctx->base = ctx->dictEnd = dst;
  2514. }
  2515. /* Frame Header */
  2516. {
  2517. size_t frameHeaderSize;
  2518. if (srcSize < ZSTD_frameHeaderSize_min+ZSTD_blockHeaderSize) return ERROR(srcSize_wrong);
  2519. frameHeaderSize = ZSTD_decodeFrameHeader_Part1(ctx, src, ZSTD_frameHeaderSize_min);
  2520. if (ZSTD_isError(frameHeaderSize)) return frameHeaderSize;
  2521. if (srcSize < frameHeaderSize+ZSTD_blockHeaderSize) return ERROR(srcSize_wrong);
  2522. ip += frameHeaderSize; remainingSize -= frameHeaderSize;
  2523. frameHeaderSize = ZSTD_decodeFrameHeader_Part2(ctx, src, frameHeaderSize);
  2524. if (ZSTD_isError(frameHeaderSize)) return frameHeaderSize;
  2525. }
  2526. /* Loop on each block */
  2527. while (1)
  2528. {
  2529. size_t decodedSize=0;
  2530. size_t cBlockSize = ZSTD_getcBlockSize(ip, iend-ip, &blockProperties);
  2531. if (ZSTD_isError(cBlockSize)) return cBlockSize;
  2532. ip += ZSTD_blockHeaderSize;
  2533. remainingSize -= ZSTD_blockHeaderSize;
  2534. if (cBlockSize > remainingSize) return ERROR(srcSize_wrong);
  2535. switch(blockProperties.blockType)
  2536. {
  2537. case bt_compressed:
  2538. decodedSize = ZSTD_decompressBlock_internal(ctx, op, oend-op, ip, cBlockSize);
  2539. break;
  2540. case bt_raw :
  2541. decodedSize = ZSTD_copyRawBlock(op, oend-op, ip, cBlockSize);
  2542. break;
  2543. case bt_rle :
  2544. return ERROR(GENERIC); /* not yet supported */
  2545. break;
  2546. case bt_end :
  2547. /* end of frame */
  2548. if (remainingSize) return ERROR(srcSize_wrong);
  2549. break;
  2550. default:
  2551. return ERROR(GENERIC); /* impossible */
  2552. }
  2553. if (cBlockSize == 0) break; /* bt_end */
  2554. if (ZSTD_isError(decodedSize)) return decodedSize;
  2555. op += decodedSize;
  2556. ip += cBlockSize;
  2557. remainingSize -= cBlockSize;
  2558. }
  2559. return op-ostart;
  2560. }
  2561. /* ZSTD_errorFrameSizeInfoLegacy() :
  2562. assumes `cSize` and `dBound` are _not_ NULL */
  2563. static void ZSTD_errorFrameSizeInfoLegacy(size_t* cSize, unsigned long long* dBound, size_t ret)
  2564. {
  2565. *cSize = ret;
  2566. *dBound = ZSTD_CONTENTSIZE_ERROR;
  2567. }
  2568. void ZSTDv04_findFrameSizeInfoLegacy(const void *src, size_t srcSize, size_t* cSize, unsigned long long* dBound)
  2569. {
  2570. const BYTE* ip = (const BYTE*)src;
  2571. size_t remainingSize = srcSize;
  2572. size_t nbBlocks = 0;
  2573. blockProperties_t blockProperties;
  2574. /* Frame Header */
  2575. if (srcSize < ZSTD_frameHeaderSize_min) {
  2576. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(srcSize_wrong));
  2577. return;
  2578. }
  2579. if (MEM_readLE32(src) != ZSTD_MAGICNUMBER) {
  2580. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(prefix_unknown));
  2581. return;
  2582. }
  2583. ip += ZSTD_frameHeaderSize_min; remainingSize -= ZSTD_frameHeaderSize_min;
  2584. /* Loop on each block */
  2585. while (1)
  2586. {
  2587. size_t cBlockSize = ZSTD_getcBlockSize(ip, remainingSize, &blockProperties);
  2588. if (ZSTD_isError(cBlockSize)) {
  2589. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, cBlockSize);
  2590. return;
  2591. }
  2592. ip += ZSTD_blockHeaderSize;
  2593. remainingSize -= ZSTD_blockHeaderSize;
  2594. if (cBlockSize > remainingSize) {
  2595. ZSTD_errorFrameSizeInfoLegacy(cSize, dBound, ERROR(srcSize_wrong));
  2596. return;
  2597. }
  2598. if (cBlockSize == 0) break; /* bt_end */
  2599. ip += cBlockSize;
  2600. remainingSize -= cBlockSize;
  2601. nbBlocks++;
  2602. }
  2603. *cSize = ip - (const BYTE*)src;
  2604. *dBound = nbBlocks * BLOCKSIZE;
  2605. }
  2606. /* ******************************
  2607. * Streaming Decompression API
  2608. ********************************/
  2609. static size_t ZSTD_nextSrcSizeToDecompress(ZSTD_DCtx* dctx)
  2610. {
  2611. return dctx->expected;
  2612. }
  2613. static size_t ZSTD_decompressContinue(ZSTD_DCtx* ctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2614. {
  2615. /* Sanity check */
  2616. if (srcSize != ctx->expected) return ERROR(srcSize_wrong);
  2617. ZSTD_checkContinuity(ctx, dst);
  2618. /* Decompress : frame header; part 1 */
  2619. switch (ctx->stage)
  2620. {
  2621. case ZSTDds_getFrameHeaderSize :
  2622. /* get frame header size */
  2623. if (srcSize != ZSTD_frameHeaderSize_min) return ERROR(srcSize_wrong); /* impossible */
  2624. ctx->headerSize = ZSTD_decodeFrameHeader_Part1(ctx, src, ZSTD_frameHeaderSize_min);
  2625. if (ZSTD_isError(ctx->headerSize)) return ctx->headerSize;
  2626. memcpy(ctx->headerBuffer, src, ZSTD_frameHeaderSize_min);
  2627. if (ctx->headerSize > ZSTD_frameHeaderSize_min) return ERROR(GENERIC); /* impossible */
  2628. ctx->expected = 0; /* not necessary to copy more */
  2629. /* fallthrough */
  2630. case ZSTDds_decodeFrameHeader:
  2631. /* get frame header */
  2632. { size_t const result = ZSTD_decodeFrameHeader_Part2(ctx, ctx->headerBuffer, ctx->headerSize);
  2633. if (ZSTD_isError(result)) return result;
  2634. ctx->expected = ZSTD_blockHeaderSize;
  2635. ctx->stage = ZSTDds_decodeBlockHeader;
  2636. return 0;
  2637. }
  2638. case ZSTDds_decodeBlockHeader:
  2639. /* Decode block header */
  2640. { blockProperties_t bp;
  2641. size_t const blockSize = ZSTD_getcBlockSize(src, ZSTD_blockHeaderSize, &bp);
  2642. if (ZSTD_isError(blockSize)) return blockSize;
  2643. if (bp.blockType == bt_end)
  2644. {
  2645. ctx->expected = 0;
  2646. ctx->stage = ZSTDds_getFrameHeaderSize;
  2647. }
  2648. else
  2649. {
  2650. ctx->expected = blockSize;
  2651. ctx->bType = bp.blockType;
  2652. ctx->stage = ZSTDds_decompressBlock;
  2653. }
  2654. return 0;
  2655. }
  2656. case ZSTDds_decompressBlock:
  2657. {
  2658. /* Decompress : block content */
  2659. size_t rSize;
  2660. switch(ctx->bType)
  2661. {
  2662. case bt_compressed:
  2663. rSize = ZSTD_decompressBlock_internal(ctx, dst, maxDstSize, src, srcSize);
  2664. break;
  2665. case bt_raw :
  2666. rSize = ZSTD_copyRawBlock(dst, maxDstSize, src, srcSize);
  2667. break;
  2668. case bt_rle :
  2669. return ERROR(GENERIC); /* not yet handled */
  2670. break;
  2671. case bt_end : /* should never happen (filtered at phase 1) */
  2672. rSize = 0;
  2673. break;
  2674. default:
  2675. return ERROR(GENERIC);
  2676. }
  2677. ctx->stage = ZSTDds_decodeBlockHeader;
  2678. ctx->expected = ZSTD_blockHeaderSize;
  2679. if (ZSTD_isError(rSize)) return rSize;
  2680. ctx->previousDstEnd = (char*)dst + rSize;
  2681. return rSize;
  2682. }
  2683. default:
  2684. return ERROR(GENERIC); /* impossible */
  2685. }
  2686. }
  2687. static void ZSTD_decompress_insertDictionary(ZSTD_DCtx* ctx, const void* dict, size_t dictSize)
  2688. {
  2689. ctx->dictEnd = ctx->previousDstEnd;
  2690. ctx->vBase = (const char*)dict - ((const char*)(ctx->previousDstEnd) - (const char*)(ctx->base));
  2691. ctx->base = dict;
  2692. ctx->previousDstEnd = (const char*)dict + dictSize;
  2693. }
  2694. /*
  2695. Buffered version of Zstd compression library
  2696. Copyright (C) 2015, Yann Collet.
  2697. BSD 2-Clause License (https://opensource.org/licenses/bsd-license.php)
  2698. Redistribution and use in source and binary forms, with or without
  2699. modification, are permitted provided that the following conditions are
  2700. met:
  2701. * Redistributions of source code must retain the above copyright
  2702. notice, this list of conditions and the following disclaimer.
  2703. * Redistributions in binary form must reproduce the above
  2704. copyright notice, this list of conditions and the following disclaimer
  2705. in the documentation and/or other materials provided with the
  2706. distribution.
  2707. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  2708. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  2709. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  2710. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  2711. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  2712. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2713. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  2714. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  2715. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  2716. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  2717. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2718. You can contact the author at :
  2719. - zstd source repository : https://github.com/Cyan4973/zstd
  2720. - ztsd public forum : https://groups.google.com/forum/#!forum/lz4c
  2721. */
  2722. /* The objects defined into this file should be considered experimental.
  2723. * They are not labelled stable, as their prototype may change in the future.
  2724. * You can use them for tests, provide feedback, or if you can endure risk of future changes.
  2725. */
  2726. /* *************************************
  2727. * Includes
  2728. ***************************************/
  2729. #include <stdlib.h>
  2730. /** ************************************************
  2731. * Streaming decompression
  2732. *
  2733. * A ZBUFF_DCtx object is required to track streaming operation.
  2734. * Use ZBUFF_createDCtx() and ZBUFF_freeDCtx() to create/release resources.
  2735. * Use ZBUFF_decompressInit() to start a new decompression operation.
  2736. * ZBUFF_DCtx objects can be reused multiple times.
  2737. *
  2738. * Use ZBUFF_decompressContinue() repetitively to consume your input.
  2739. * *srcSizePtr and *maxDstSizePtr can be any size.
  2740. * The function will report how many bytes were read or written by modifying *srcSizePtr and *maxDstSizePtr.
  2741. * Note that it may not consume the entire input, in which case it's up to the caller to call again the function with remaining input.
  2742. * The content of dst will be overwritten (up to *maxDstSizePtr) at each function call, so save its content if it matters or change dst .
  2743. * return : a hint to preferred nb of bytes to use as input for next function call (it's only a hint, to improve latency)
  2744. * or 0 when a frame is completely decoded
  2745. * or an error code, which can be tested using ZBUFF_isError().
  2746. *
  2747. * Hint : recommended buffer sizes (not compulsory)
  2748. * output : 128 KB block size is the internal unit, it ensures it's always possible to write a full block when it's decoded.
  2749. * input : just follow indications from ZBUFF_decompressContinue() to minimize latency. It should always be <= 128 KB + 3 .
  2750. * **************************************************/
  2751. typedef enum { ZBUFFds_init, ZBUFFds_readHeader, ZBUFFds_loadHeader, ZBUFFds_decodeHeader,
  2752. ZBUFFds_read, ZBUFFds_load, ZBUFFds_flush } ZBUFF_dStage;
  2753. /* *** Resource management *** */
  2754. #define ZSTD_frameHeaderSize_max 5 /* too magical, should come from reference */
  2755. struct ZBUFFv04_DCtx_s {
  2756. ZSTD_DCtx* zc;
  2757. ZSTD_parameters params;
  2758. char* inBuff;
  2759. size_t inBuffSize;
  2760. size_t inPos;
  2761. char* outBuff;
  2762. size_t outBuffSize;
  2763. size_t outStart;
  2764. size_t outEnd;
  2765. size_t hPos;
  2766. const char* dict;
  2767. size_t dictSize;
  2768. ZBUFF_dStage stage;
  2769. unsigned char headerBuffer[ZSTD_frameHeaderSize_max];
  2770. }; /* typedef'd to ZBUFF_DCtx within "zstd_buffered.h" */
  2771. typedef ZBUFFv04_DCtx ZBUFF_DCtx;
  2772. static ZBUFF_DCtx* ZBUFF_createDCtx(void)
  2773. {
  2774. ZBUFF_DCtx* zbc = (ZBUFF_DCtx*)malloc(sizeof(ZBUFF_DCtx));
  2775. if (zbc==NULL) return NULL;
  2776. memset(zbc, 0, sizeof(*zbc));
  2777. zbc->zc = ZSTD_createDCtx();
  2778. zbc->stage = ZBUFFds_init;
  2779. return zbc;
  2780. }
  2781. static size_t ZBUFF_freeDCtx(ZBUFF_DCtx* zbc)
  2782. {
  2783. if (zbc==NULL) return 0; /* support free on null */
  2784. ZSTD_freeDCtx(zbc->zc);
  2785. free(zbc->inBuff);
  2786. free(zbc->outBuff);
  2787. free(zbc);
  2788. return 0;
  2789. }
  2790. /* *** Initialization *** */
  2791. static size_t ZBUFF_decompressInit(ZBUFF_DCtx* zbc)
  2792. {
  2793. zbc->stage = ZBUFFds_readHeader;
  2794. zbc->hPos = zbc->inPos = zbc->outStart = zbc->outEnd = zbc->dictSize = 0;
  2795. return ZSTD_resetDCtx(zbc->zc);
  2796. }
  2797. static size_t ZBUFF_decompressWithDictionary(ZBUFF_DCtx* zbc, const void* src, size_t srcSize)
  2798. {
  2799. zbc->dict = (const char*)src;
  2800. zbc->dictSize = srcSize;
  2801. return 0;
  2802. }
  2803. static size_t ZBUFF_limitCopy(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2804. {
  2805. size_t length = MIN(maxDstSize, srcSize);
  2806. if (length > 0) {
  2807. memcpy(dst, src, length);
  2808. }
  2809. return length;
  2810. }
  2811. /* *** Decompression *** */
  2812. static size_t ZBUFF_decompressContinue(ZBUFF_DCtx* zbc, void* dst, size_t* maxDstSizePtr, const void* src, size_t* srcSizePtr)
  2813. {
  2814. const char* const istart = (const char*)src;
  2815. const char* ip = istart;
  2816. const char* const iend = istart + *srcSizePtr;
  2817. char* const ostart = (char*)dst;
  2818. char* op = ostart;
  2819. char* const oend = ostart + *maxDstSizePtr;
  2820. U32 notDone = 1;
  2821. DEBUGLOG(5, "ZBUFF_decompressContinue");
  2822. while (notDone)
  2823. {
  2824. switch(zbc->stage)
  2825. {
  2826. case ZBUFFds_init :
  2827. DEBUGLOG(5, "ZBUFF_decompressContinue: stage==ZBUFFds_init => ERROR(init_missing)");
  2828. return ERROR(init_missing);
  2829. case ZBUFFds_readHeader :
  2830. /* read header from src */
  2831. { size_t const headerSize = ZSTD_getFrameParams(&(zbc->params), src, *srcSizePtr);
  2832. if (ZSTD_isError(headerSize)) return headerSize;
  2833. if (headerSize) {
  2834. /* not enough input to decode header : tell how many bytes would be necessary */
  2835. memcpy(zbc->headerBuffer+zbc->hPos, src, *srcSizePtr);
  2836. zbc->hPos += *srcSizePtr;
  2837. *maxDstSizePtr = 0;
  2838. zbc->stage = ZBUFFds_loadHeader;
  2839. return headerSize - zbc->hPos;
  2840. }
  2841. zbc->stage = ZBUFFds_decodeHeader;
  2842. break;
  2843. }
  2844. case ZBUFFds_loadHeader:
  2845. /* complete header from src */
  2846. { size_t headerSize = ZBUFF_limitCopy(
  2847. zbc->headerBuffer + zbc->hPos, ZSTD_frameHeaderSize_max - zbc->hPos,
  2848. src, *srcSizePtr);
  2849. zbc->hPos += headerSize;
  2850. ip += headerSize;
  2851. headerSize = ZSTD_getFrameParams(&(zbc->params), zbc->headerBuffer, zbc->hPos);
  2852. if (ZSTD_isError(headerSize)) return headerSize;
  2853. if (headerSize) {
  2854. /* not enough input to decode header : tell how many bytes would be necessary */
  2855. *maxDstSizePtr = 0;
  2856. return headerSize - zbc->hPos;
  2857. } }
  2858. /* intentional fallthrough */
  2859. case ZBUFFds_decodeHeader:
  2860. /* apply header to create / resize buffers */
  2861. { size_t const neededOutSize = (size_t)1 << zbc->params.windowLog;
  2862. size_t const neededInSize = BLOCKSIZE; /* a block is never > BLOCKSIZE */
  2863. if (zbc->inBuffSize < neededInSize) {
  2864. free(zbc->inBuff);
  2865. zbc->inBuffSize = neededInSize;
  2866. zbc->inBuff = (char*)malloc(neededInSize);
  2867. if (zbc->inBuff == NULL) return ERROR(memory_allocation);
  2868. }
  2869. if (zbc->outBuffSize < neededOutSize) {
  2870. free(zbc->outBuff);
  2871. zbc->outBuffSize = neededOutSize;
  2872. zbc->outBuff = (char*)malloc(neededOutSize);
  2873. if (zbc->outBuff == NULL) return ERROR(memory_allocation);
  2874. } }
  2875. if (zbc->dictSize)
  2876. ZSTD_decompress_insertDictionary(zbc->zc, zbc->dict, zbc->dictSize);
  2877. if (zbc->hPos) {
  2878. /* some data already loaded into headerBuffer : transfer into inBuff */
  2879. memcpy(zbc->inBuff, zbc->headerBuffer, zbc->hPos);
  2880. zbc->inPos = zbc->hPos;
  2881. zbc->hPos = 0;
  2882. zbc->stage = ZBUFFds_load;
  2883. break;
  2884. }
  2885. zbc->stage = ZBUFFds_read;
  2886. /* fall-through */
  2887. case ZBUFFds_read:
  2888. {
  2889. size_t neededInSize = ZSTD_nextSrcSizeToDecompress(zbc->zc);
  2890. if (neededInSize==0) /* end of frame */
  2891. {
  2892. zbc->stage = ZBUFFds_init;
  2893. notDone = 0;
  2894. break;
  2895. }
  2896. if ((size_t)(iend-ip) >= neededInSize)
  2897. {
  2898. /* directly decode from src */
  2899. size_t decodedSize = ZSTD_decompressContinue(zbc->zc,
  2900. zbc->outBuff + zbc->outStart, zbc->outBuffSize - zbc->outStart,
  2901. ip, neededInSize);
  2902. if (ZSTD_isError(decodedSize)) return decodedSize;
  2903. ip += neededInSize;
  2904. if (!decodedSize) break; /* this was just a header */
  2905. zbc->outEnd = zbc->outStart + decodedSize;
  2906. zbc->stage = ZBUFFds_flush;
  2907. break;
  2908. }
  2909. if (ip==iend) { notDone = 0; break; } /* no more input */
  2910. zbc->stage = ZBUFFds_load;
  2911. }
  2912. /* fall-through */
  2913. case ZBUFFds_load:
  2914. {
  2915. size_t neededInSize = ZSTD_nextSrcSizeToDecompress(zbc->zc);
  2916. size_t toLoad = neededInSize - zbc->inPos; /* should always be <= remaining space within inBuff */
  2917. size_t loadedSize;
  2918. if (toLoad > zbc->inBuffSize - zbc->inPos) return ERROR(corruption_detected); /* should never happen */
  2919. loadedSize = ZBUFF_limitCopy(zbc->inBuff + zbc->inPos, toLoad, ip, iend-ip);
  2920. ip += loadedSize;
  2921. zbc->inPos += loadedSize;
  2922. if (loadedSize < toLoad) { notDone = 0; break; } /* not enough input, wait for more */
  2923. {
  2924. size_t decodedSize = ZSTD_decompressContinue(zbc->zc,
  2925. zbc->outBuff + zbc->outStart, zbc->outBuffSize - zbc->outStart,
  2926. zbc->inBuff, neededInSize);
  2927. if (ZSTD_isError(decodedSize)) return decodedSize;
  2928. zbc->inPos = 0; /* input is consumed */
  2929. if (!decodedSize) { zbc->stage = ZBUFFds_read; break; } /* this was just a header */
  2930. zbc->outEnd = zbc->outStart + decodedSize;
  2931. zbc->stage = ZBUFFds_flush;
  2932. /* ZBUFFds_flush follows */
  2933. }
  2934. }
  2935. /* fall-through */
  2936. case ZBUFFds_flush:
  2937. {
  2938. size_t toFlushSize = zbc->outEnd - zbc->outStart;
  2939. size_t flushedSize = ZBUFF_limitCopy(op, oend-op, zbc->outBuff + zbc->outStart, toFlushSize);
  2940. op += flushedSize;
  2941. zbc->outStart += flushedSize;
  2942. if (flushedSize == toFlushSize)
  2943. {
  2944. zbc->stage = ZBUFFds_read;
  2945. if (zbc->outStart + BLOCKSIZE > zbc->outBuffSize)
  2946. zbc->outStart = zbc->outEnd = 0;
  2947. break;
  2948. }
  2949. /* cannot flush everything */
  2950. notDone = 0;
  2951. break;
  2952. }
  2953. default: return ERROR(GENERIC); /* impossible */
  2954. }
  2955. }
  2956. *srcSizePtr = ip-istart;
  2957. *maxDstSizePtr = op-ostart;
  2958. {
  2959. size_t nextSrcSizeHint = ZSTD_nextSrcSizeToDecompress(zbc->zc);
  2960. if (nextSrcSizeHint > 3) nextSrcSizeHint+= 3; /* get the next block header while at it */
  2961. nextSrcSizeHint -= zbc->inPos; /* already loaded*/
  2962. return nextSrcSizeHint;
  2963. }
  2964. }
  2965. /* *************************************
  2966. * Tool functions
  2967. ***************************************/
  2968. unsigned ZBUFFv04_isError(size_t errorCode) { return ERR_isError(errorCode); }
  2969. const char* ZBUFFv04_getErrorName(size_t errorCode) { return ERR_getErrorName(errorCode); }
  2970. size_t ZBUFFv04_recommendedDInSize(void) { return BLOCKSIZE + 3; }
  2971. size_t ZBUFFv04_recommendedDOutSize(void) { return BLOCKSIZE; }
  2972. /*- ========================================================================= -*/
  2973. /* final wrapping stage */
  2974. size_t ZSTDv04_decompressDCtx(ZSTD_DCtx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2975. {
  2976. return ZSTD_decompress_usingDict(dctx, dst, maxDstSize, src, srcSize, NULL, 0);
  2977. }
  2978. size_t ZSTDv04_decompress(void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2979. {
  2980. #if defined(ZSTD_HEAPMODE) && (ZSTD_HEAPMODE==1)
  2981. size_t regenSize;
  2982. ZSTD_DCtx* dctx = ZSTD_createDCtx();
  2983. if (dctx==NULL) return ERROR(memory_allocation);
  2984. regenSize = ZSTDv04_decompressDCtx(dctx, dst, maxDstSize, src, srcSize);
  2985. ZSTD_freeDCtx(dctx);
  2986. return regenSize;
  2987. #else
  2988. ZSTD_DCtx dctx;
  2989. return ZSTDv04_decompressDCtx(&dctx, dst, maxDstSize, src, srcSize);
  2990. #endif
  2991. }
  2992. size_t ZSTDv04_resetDCtx(ZSTDv04_Dctx* dctx) { return ZSTD_resetDCtx(dctx); }
  2993. size_t ZSTDv04_nextSrcSizeToDecompress(ZSTDv04_Dctx* dctx)
  2994. {
  2995. return ZSTD_nextSrcSizeToDecompress(dctx);
  2996. }
  2997. size_t ZSTDv04_decompressContinue(ZSTDv04_Dctx* dctx, void* dst, size_t maxDstSize, const void* src, size_t srcSize)
  2998. {
  2999. return ZSTD_decompressContinue(dctx, dst, maxDstSize, src, srcSize);
  3000. }
  3001. ZBUFFv04_DCtx* ZBUFFv04_createDCtx(void) { return ZBUFF_createDCtx(); }
  3002. size_t ZBUFFv04_freeDCtx(ZBUFFv04_DCtx* dctx) { return ZBUFF_freeDCtx(dctx); }
  3003. size_t ZBUFFv04_decompressInit(ZBUFFv04_DCtx* dctx) { return ZBUFF_decompressInit(dctx); }
  3004. size_t ZBUFFv04_decompressWithDictionary(ZBUFFv04_DCtx* dctx, const void* src, size_t srcSize)
  3005. { return ZBUFF_decompressWithDictionary(dctx, src, srcSize); }
  3006. size_t ZBUFFv04_decompressContinue(ZBUFFv04_DCtx* dctx, void* dst, size_t* maxDstSizePtr, const void* src, size_t* srcSizePtr)
  3007. {
  3008. DEBUGLOG(5, "ZBUFFv04_decompressContinue");
  3009. return ZBUFF_decompressContinue(dctx, dst, maxDstSizePtr, src, srcSizePtr);
  3010. }
  3011. ZSTD_DCtx* ZSTDv04_createDCtx(void) { return ZSTD_createDCtx(); }
  3012. size_t ZSTDv04_freeDCtx(ZSTD_DCtx* dctx) { return ZSTD_freeDCtx(dctx); }