2
0

zstd_v02.c 125 KB

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