zstd_v02.c 134 KB

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