zstd_v07.c 197 KB

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