zstd_v08.c 197 KB

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