decode.go 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581
  1. package brotli
  2. /* Copyright 2013 Google Inc. All Rights Reserved.
  3. Distributed under MIT license.
  4. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  5. */
  6. const (
  7. decoderResultError = 0
  8. decoderResultSuccess = 1
  9. decoderResultNeedsMoreInput = 2
  10. decoderResultNeedsMoreOutput = 3
  11. )
  12. /**
  13. * Error code for detailed logging / production debugging.
  14. *
  15. * See ::BrotliDecoderGetErrorCode and ::BROTLI_LAST_ERROR_CODE.
  16. */
  17. const (
  18. decoderNoError = 0
  19. decoderSuccess = 1
  20. decoderNeedsMoreInput = 2
  21. decoderNeedsMoreOutput = 3
  22. decoderErrorFormatExuberantNibble = -1
  23. decoderErrorFormatReserved = -2
  24. decoderErrorFormatExuberantMetaNibble = -3
  25. decoderErrorFormatSimpleHuffmanAlphabet = -4
  26. decoderErrorFormatSimpleHuffmanSame = -5
  27. decoderErrorFormatClSpace = -6
  28. decoderErrorFormatHuffmanSpace = -7
  29. decoderErrorFormatContextMapRepeat = -8
  30. decoderErrorFormatBlockLength1 = -9
  31. decoderErrorFormatBlockLength2 = -10
  32. decoderErrorFormatTransform = -11
  33. decoderErrorFormatDictionary = -12
  34. decoderErrorFormatWindowBits = -13
  35. decoderErrorFormatPadding1 = -14
  36. decoderErrorFormatPadding2 = -15
  37. decoderErrorFormatDistance = -16
  38. decoderErrorDictionaryNotSet = -19
  39. decoderErrorInvalidArguments = -20
  40. decoderErrorAllocContextModes = -21
  41. decoderErrorAllocTreeGroups = -22
  42. decoderErrorAllocContextMap = -25
  43. decoderErrorAllocRingBuffer1 = -26
  44. decoderErrorAllocRingBuffer2 = -27
  45. decoderErrorAllocBlockTypeTrees = -30
  46. decoderErrorUnreachable = -31
  47. )
  48. const huffmanTableBits = 8
  49. const huffmanTableMask = 0xFF
  50. /* We need the slack region for the following reasons:
  51. - doing up to two 16-byte copies for fast backward copying
  52. - inserting transformed dictionary word (5 prefix + 24 base + 8 suffix) */
  53. const kRingBufferWriteAheadSlack uint32 = 42
  54. var kCodeLengthCodeOrder = [codeLengthCodes]byte{1, 2, 3, 4, 0, 5, 17, 6, 16, 7, 8, 9, 10, 11, 12, 13, 14, 15}
  55. /* Static prefix code for the complex code length code lengths. */
  56. var kCodeLengthPrefixLength = [16]byte{2, 2, 2, 3, 2, 2, 2, 4, 2, 2, 2, 3, 2, 2, 2, 4}
  57. var kCodeLengthPrefixValue = [16]byte{0, 4, 3, 2, 0, 4, 3, 1, 0, 4, 3, 2, 0, 4, 3, 5}
  58. /* Saves error code and converts it to BrotliDecoderResult. */
  59. func saveErrorCode(s *Reader, e int) int {
  60. s.error_code = int(e)
  61. switch e {
  62. case decoderSuccess:
  63. return decoderResultSuccess
  64. case decoderNeedsMoreInput:
  65. return decoderResultNeedsMoreInput
  66. case decoderNeedsMoreOutput:
  67. return decoderResultNeedsMoreOutput
  68. default:
  69. return decoderResultError
  70. }
  71. }
  72. /* Decodes WBITS by reading 1 - 7 bits, or 0x11 for "Large Window Brotli".
  73. Precondition: bit-reader accumulator has at least 8 bits. */
  74. func decodeWindowBits(s *Reader, br *bitReader) int {
  75. var n uint32
  76. var large_window bool = s.large_window
  77. s.large_window = false
  78. takeBits(br, 1, &n)
  79. if n == 0 {
  80. s.window_bits = 16
  81. return decoderSuccess
  82. }
  83. takeBits(br, 3, &n)
  84. if n != 0 {
  85. s.window_bits = 17 + n
  86. return decoderSuccess
  87. }
  88. takeBits(br, 3, &n)
  89. if n == 1 {
  90. if large_window {
  91. takeBits(br, 1, &n)
  92. if n == 1 {
  93. return decoderErrorFormatWindowBits
  94. }
  95. s.large_window = true
  96. return decoderSuccess
  97. } else {
  98. return decoderErrorFormatWindowBits
  99. }
  100. }
  101. if n != 0 {
  102. s.window_bits = 8 + n
  103. return decoderSuccess
  104. }
  105. s.window_bits = 17
  106. return decoderSuccess
  107. }
  108. /* Decodes a number in the range [0..255], by reading 1 - 11 bits. */
  109. func decodeVarLenUint8(s *Reader, br *bitReader, value *uint32) int {
  110. var bits uint32
  111. switch s.substate_decode_uint8 {
  112. case stateDecodeUint8None:
  113. if !safeReadBits(br, 1, &bits) {
  114. return decoderNeedsMoreInput
  115. }
  116. if bits == 0 {
  117. *value = 0
  118. return decoderSuccess
  119. }
  120. fallthrough
  121. /* Fall through. */
  122. case stateDecodeUint8Short:
  123. if !safeReadBits(br, 3, &bits) {
  124. s.substate_decode_uint8 = stateDecodeUint8Short
  125. return decoderNeedsMoreInput
  126. }
  127. if bits == 0 {
  128. *value = 1
  129. s.substate_decode_uint8 = stateDecodeUint8None
  130. return decoderSuccess
  131. }
  132. /* Use output value as a temporary storage. It MUST be persisted. */
  133. *value = bits
  134. fallthrough
  135. /* Fall through. */
  136. case stateDecodeUint8Long:
  137. if !safeReadBits(br, *value, &bits) {
  138. s.substate_decode_uint8 = stateDecodeUint8Long
  139. return decoderNeedsMoreInput
  140. }
  141. *value = (1 << *value) + bits
  142. s.substate_decode_uint8 = stateDecodeUint8None
  143. return decoderSuccess
  144. default:
  145. return decoderErrorUnreachable
  146. }
  147. }
  148. /* Decodes a metablock length and flags by reading 2 - 31 bits. */
  149. func decodeMetaBlockLength(s *Reader, br *bitReader) int {
  150. var bits uint32
  151. var i int
  152. for {
  153. switch s.substate_metablock_header {
  154. case stateMetablockHeaderNone:
  155. if !safeReadBits(br, 1, &bits) {
  156. return decoderNeedsMoreInput
  157. }
  158. if bits != 0 {
  159. s.is_last_metablock = 1
  160. } else {
  161. s.is_last_metablock = 0
  162. }
  163. s.meta_block_remaining_len = 0
  164. s.is_uncompressed = 0
  165. s.is_metadata = 0
  166. if s.is_last_metablock == 0 {
  167. s.substate_metablock_header = stateMetablockHeaderNibbles
  168. break
  169. }
  170. s.substate_metablock_header = stateMetablockHeaderEmpty
  171. fallthrough
  172. /* Fall through. */
  173. case stateMetablockHeaderEmpty:
  174. if !safeReadBits(br, 1, &bits) {
  175. return decoderNeedsMoreInput
  176. }
  177. if bits != 0 {
  178. s.substate_metablock_header = stateMetablockHeaderNone
  179. return decoderSuccess
  180. }
  181. s.substate_metablock_header = stateMetablockHeaderNibbles
  182. fallthrough
  183. /* Fall through. */
  184. case stateMetablockHeaderNibbles:
  185. if !safeReadBits(br, 2, &bits) {
  186. return decoderNeedsMoreInput
  187. }
  188. s.size_nibbles = uint(byte(bits + 4))
  189. s.loop_counter = 0
  190. if bits == 3 {
  191. s.is_metadata = 1
  192. s.substate_metablock_header = stateMetablockHeaderReserved
  193. break
  194. }
  195. s.substate_metablock_header = stateMetablockHeaderSize
  196. fallthrough
  197. /* Fall through. */
  198. case stateMetablockHeaderSize:
  199. i = s.loop_counter
  200. for ; i < int(s.size_nibbles); i++ {
  201. if !safeReadBits(br, 4, &bits) {
  202. s.loop_counter = i
  203. return decoderNeedsMoreInput
  204. }
  205. if uint(i+1) == s.size_nibbles && s.size_nibbles > 4 && bits == 0 {
  206. return decoderErrorFormatExuberantNibble
  207. }
  208. s.meta_block_remaining_len |= int(bits << uint(i*4))
  209. }
  210. s.substate_metablock_header = stateMetablockHeaderUncompressed
  211. fallthrough
  212. /* Fall through. */
  213. case stateMetablockHeaderUncompressed:
  214. if s.is_last_metablock == 0 {
  215. if !safeReadBits(br, 1, &bits) {
  216. return decoderNeedsMoreInput
  217. }
  218. if bits != 0 {
  219. s.is_uncompressed = 1
  220. } else {
  221. s.is_uncompressed = 0
  222. }
  223. }
  224. s.meta_block_remaining_len++
  225. s.substate_metablock_header = stateMetablockHeaderNone
  226. return decoderSuccess
  227. case stateMetablockHeaderReserved:
  228. if !safeReadBits(br, 1, &bits) {
  229. return decoderNeedsMoreInput
  230. }
  231. if bits != 0 {
  232. return decoderErrorFormatReserved
  233. }
  234. s.substate_metablock_header = stateMetablockHeaderBytes
  235. fallthrough
  236. /* Fall through. */
  237. case stateMetablockHeaderBytes:
  238. if !safeReadBits(br, 2, &bits) {
  239. return decoderNeedsMoreInput
  240. }
  241. if bits == 0 {
  242. s.substate_metablock_header = stateMetablockHeaderNone
  243. return decoderSuccess
  244. }
  245. s.size_nibbles = uint(byte(bits))
  246. s.substate_metablock_header = stateMetablockHeaderMetadata
  247. fallthrough
  248. /* Fall through. */
  249. case stateMetablockHeaderMetadata:
  250. i = s.loop_counter
  251. for ; i < int(s.size_nibbles); i++ {
  252. if !safeReadBits(br, 8, &bits) {
  253. s.loop_counter = i
  254. return decoderNeedsMoreInput
  255. }
  256. if uint(i+1) == s.size_nibbles && s.size_nibbles > 1 && bits == 0 {
  257. return decoderErrorFormatExuberantMetaNibble
  258. }
  259. s.meta_block_remaining_len |= int(bits << uint(i*8))
  260. }
  261. s.meta_block_remaining_len++
  262. s.substate_metablock_header = stateMetablockHeaderNone
  263. return decoderSuccess
  264. default:
  265. return decoderErrorUnreachable
  266. }
  267. }
  268. }
  269. /* Decodes the Huffman code.
  270. This method doesn't read data from the bit reader, BUT drops the amount of
  271. bits that correspond to the decoded symbol.
  272. bits MUST contain at least 15 (BROTLI_HUFFMAN_MAX_CODE_LENGTH) valid bits. */
  273. func decodeSymbol(bits uint32, table []huffmanCode, br *bitReader) uint32 {
  274. table = table[bits&huffmanTableMask:]
  275. if table[0].bits > huffmanTableBits {
  276. var nbits uint32 = uint32(table[0].bits) - huffmanTableBits
  277. dropBits(br, huffmanTableBits)
  278. table = table[uint32(table[0].value)+((bits>>huffmanTableBits)&bitMask(nbits)):]
  279. }
  280. dropBits(br, uint32(table[0].bits))
  281. return uint32(table[0].value)
  282. }
  283. /* Reads and decodes the next Huffman code from bit-stream.
  284. This method peeks 16 bits of input and drops 0 - 15 of them. */
  285. func readSymbol(table []huffmanCode, br *bitReader) uint32 {
  286. return decodeSymbol(get16BitsUnmasked(br), table, br)
  287. }
  288. /* Same as DecodeSymbol, but it is known that there is less than 15 bits of
  289. input are currently available. */
  290. func safeDecodeSymbol(table []huffmanCode, br *bitReader, result *uint32) bool {
  291. var val uint32
  292. var available_bits uint32 = getAvailableBits(br)
  293. if available_bits == 0 {
  294. if table[0].bits == 0 {
  295. *result = uint32(table[0].value)
  296. return true
  297. }
  298. return false /* No valid bits at all. */
  299. }
  300. val = uint32(getBitsUnmasked(br))
  301. table = table[val&huffmanTableMask:]
  302. if table[0].bits <= huffmanTableBits {
  303. if uint32(table[0].bits) <= available_bits {
  304. dropBits(br, uint32(table[0].bits))
  305. *result = uint32(table[0].value)
  306. return true
  307. } else {
  308. return false /* Not enough bits for the first level. */
  309. }
  310. }
  311. if available_bits <= huffmanTableBits {
  312. return false /* Not enough bits to move to the second level. */
  313. }
  314. /* Speculatively drop HUFFMAN_TABLE_BITS. */
  315. val = (val & bitMask(uint32(table[0].bits))) >> huffmanTableBits
  316. available_bits -= huffmanTableBits
  317. table = table[uint32(table[0].value)+val:]
  318. if available_bits < uint32(table[0].bits) {
  319. return false /* Not enough bits for the second level. */
  320. }
  321. dropBits(br, huffmanTableBits+uint32(table[0].bits))
  322. *result = uint32(table[0].value)
  323. return true
  324. }
  325. func safeReadSymbol(table []huffmanCode, br *bitReader, result *uint32) bool {
  326. var val uint32
  327. if safeGetBits(br, 15, &val) {
  328. *result = decodeSymbol(val, table, br)
  329. return true
  330. }
  331. return safeDecodeSymbol(table, br, result)
  332. }
  333. /* Makes a look-up in first level Huffman table. Peeks 8 bits. */
  334. func preloadSymbol(safe int, table []huffmanCode, br *bitReader, bits *uint32, value *uint32) {
  335. if safe != 0 {
  336. return
  337. }
  338. table = table[getBits(br, huffmanTableBits):]
  339. *bits = uint32(table[0].bits)
  340. *value = uint32(table[0].value)
  341. }
  342. /* Decodes the next Huffman code using data prepared by PreloadSymbol.
  343. Reads 0 - 15 bits. Also peeks 8 following bits. */
  344. func readPreloadedSymbol(table []huffmanCode, br *bitReader, bits *uint32, value *uint32) uint32 {
  345. var result uint32 = *value
  346. var ext []huffmanCode
  347. if *bits > huffmanTableBits {
  348. var val uint32 = get16BitsUnmasked(br)
  349. ext = table[val&huffmanTableMask:][*value:]
  350. var mask uint32 = bitMask((*bits - huffmanTableBits))
  351. dropBits(br, huffmanTableBits)
  352. ext = ext[(val>>huffmanTableBits)&mask:]
  353. dropBits(br, uint32(ext[0].bits))
  354. result = uint32(ext[0].value)
  355. } else {
  356. dropBits(br, *bits)
  357. }
  358. preloadSymbol(0, table, br, bits, value)
  359. return result
  360. }
  361. func log2Floor(x uint32) uint32 {
  362. var result uint32 = 0
  363. for x != 0 {
  364. x >>= 1
  365. result++
  366. }
  367. return result
  368. }
  369. /* Reads (s->symbol + 1) symbols.
  370. Totally 1..4 symbols are read, 1..11 bits each.
  371. The list of symbols MUST NOT contain duplicates. */
  372. func readSimpleHuffmanSymbols(alphabet_size uint32, max_symbol uint32, s *Reader) int {
  373. var br *bitReader = &s.br
  374. var max_bits uint32 = log2Floor(alphabet_size - 1)
  375. var i uint32 = s.sub_loop_counter
  376. /* max_bits == 1..11; symbol == 0..3; 1..44 bits will be read. */
  377. var num_symbols uint32 = s.symbol
  378. for i <= num_symbols {
  379. var v uint32
  380. if !safeReadBits(br, max_bits, &v) {
  381. s.sub_loop_counter = i
  382. s.substate_huffman = stateHuffmanSimpleRead
  383. return decoderNeedsMoreInput
  384. }
  385. if v >= max_symbol {
  386. return decoderErrorFormatSimpleHuffmanAlphabet
  387. }
  388. s.symbols_lists_array[i] = uint16(v)
  389. i++
  390. }
  391. for i = 0; i < num_symbols; i++ {
  392. var k uint32 = i + 1
  393. for ; k <= num_symbols; k++ {
  394. if s.symbols_lists_array[i] == s.symbols_lists_array[k] {
  395. return decoderErrorFormatSimpleHuffmanSame
  396. }
  397. }
  398. }
  399. return decoderSuccess
  400. }
  401. /* Process single decoded symbol code length:
  402. A) reset the repeat variable
  403. B) remember code length (if it is not 0)
  404. C) extend corresponding index-chain
  405. D) reduce the Huffman space
  406. E) update the histogram */
  407. func processSingleCodeLength(code_len uint32, symbol *uint32, repeat *uint32, space *uint32, prev_code_len *uint32, symbol_lists symbolList, code_length_histo []uint16, next_symbol []int) {
  408. *repeat = 0
  409. if code_len != 0 { /* code_len == 1..15 */
  410. symbolListPut(symbol_lists, next_symbol[code_len], uint16(*symbol))
  411. next_symbol[code_len] = int(*symbol)
  412. *prev_code_len = code_len
  413. *space -= 32768 >> code_len
  414. code_length_histo[code_len]++
  415. }
  416. (*symbol)++
  417. }
  418. /* Process repeated symbol code length.
  419. A) Check if it is the extension of previous repeat sequence; if the decoded
  420. value is not BROTLI_REPEAT_PREVIOUS_CODE_LENGTH, then it is a new
  421. symbol-skip
  422. B) Update repeat variable
  423. C) Check if operation is feasible (fits alphabet)
  424. D) For each symbol do the same operations as in ProcessSingleCodeLength
  425. PRECONDITION: code_len == BROTLI_REPEAT_PREVIOUS_CODE_LENGTH or
  426. code_len == BROTLI_REPEAT_ZERO_CODE_LENGTH */
  427. func processRepeatedCodeLength(code_len uint32, repeat_delta uint32, alphabet_size uint32, symbol *uint32, repeat *uint32, space *uint32, prev_code_len *uint32, repeat_code_len *uint32, symbol_lists symbolList, code_length_histo []uint16, next_symbol []int) {
  428. var old_repeat uint32 /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */ /* for BROTLI_REPEAT_ZERO_CODE_LENGTH */
  429. var extra_bits uint32 = 3
  430. var new_len uint32 = 0
  431. if code_len == repeatPreviousCodeLength {
  432. new_len = *prev_code_len
  433. extra_bits = 2
  434. }
  435. if *repeat_code_len != new_len {
  436. *repeat = 0
  437. *repeat_code_len = new_len
  438. }
  439. old_repeat = *repeat
  440. if *repeat > 0 {
  441. *repeat -= 2
  442. *repeat <<= extra_bits
  443. }
  444. *repeat += repeat_delta + 3
  445. repeat_delta = *repeat - old_repeat
  446. if *symbol+repeat_delta > alphabet_size {
  447. *symbol = alphabet_size
  448. *space = 0xFFFFF
  449. return
  450. }
  451. if *repeat_code_len != 0 {
  452. var last uint = uint(*symbol + repeat_delta)
  453. var next int = next_symbol[*repeat_code_len]
  454. for {
  455. symbolListPut(symbol_lists, next, uint16(*symbol))
  456. next = int(*symbol)
  457. (*symbol)++
  458. if (*symbol) == uint32(last) {
  459. break
  460. }
  461. }
  462. next_symbol[*repeat_code_len] = next
  463. *space -= repeat_delta << (15 - *repeat_code_len)
  464. code_length_histo[*repeat_code_len] = uint16(uint32(code_length_histo[*repeat_code_len]) + repeat_delta)
  465. } else {
  466. *symbol += repeat_delta
  467. }
  468. }
  469. /* Reads and decodes symbol codelengths. */
  470. func readSymbolCodeLengths(alphabet_size uint32, s *Reader) int {
  471. var br *bitReader = &s.br
  472. var symbol uint32 = s.symbol
  473. var repeat uint32 = s.repeat
  474. var space uint32 = s.space
  475. var prev_code_len uint32 = s.prev_code_len
  476. var repeat_code_len uint32 = s.repeat_code_len
  477. var symbol_lists symbolList = s.symbol_lists
  478. var code_length_histo []uint16 = s.code_length_histo[:]
  479. var next_symbol []int = s.next_symbol[:]
  480. if !warmupBitReader(br) {
  481. return decoderNeedsMoreInput
  482. }
  483. var p []huffmanCode
  484. for symbol < alphabet_size && space > 0 {
  485. p = s.table[:]
  486. var code_len uint32
  487. if !checkInputAmount(br, shortFillBitWindowRead) {
  488. s.symbol = symbol
  489. s.repeat = repeat
  490. s.prev_code_len = prev_code_len
  491. s.repeat_code_len = repeat_code_len
  492. s.space = space
  493. return decoderNeedsMoreInput
  494. }
  495. fillBitWindow16(br)
  496. p = p[getBitsUnmasked(br)&uint64(bitMask(huffmanMaxCodeLengthCodeLength)):]
  497. dropBits(br, uint32(p[0].bits)) /* Use 1..5 bits. */
  498. code_len = uint32(p[0].value) /* code_len == 0..17 */
  499. if code_len < repeatPreviousCodeLength {
  500. processSingleCodeLength(code_len, &symbol, &repeat, &space, &prev_code_len, symbol_lists, code_length_histo, next_symbol) /* code_len == 16..17, extra_bits == 2..3 */
  501. } else {
  502. var extra_bits uint32
  503. if code_len == repeatPreviousCodeLength {
  504. extra_bits = 2
  505. } else {
  506. extra_bits = 3
  507. }
  508. var repeat_delta uint32 = uint32(getBitsUnmasked(br)) & bitMask(extra_bits)
  509. dropBits(br, extra_bits)
  510. processRepeatedCodeLength(code_len, repeat_delta, alphabet_size, &symbol, &repeat, &space, &prev_code_len, &repeat_code_len, symbol_lists, code_length_histo, next_symbol)
  511. }
  512. }
  513. s.space = space
  514. return decoderSuccess
  515. }
  516. func safeReadSymbolCodeLengths(alphabet_size uint32, s *Reader) int {
  517. var br *bitReader = &s.br
  518. var get_byte bool = false
  519. var p []huffmanCode
  520. for s.symbol < alphabet_size && s.space > 0 {
  521. p = s.table[:]
  522. var code_len uint32
  523. var available_bits uint32
  524. var bits uint32 = 0
  525. if get_byte && !pullByte(br) {
  526. return decoderNeedsMoreInput
  527. }
  528. get_byte = false
  529. available_bits = getAvailableBits(br)
  530. if available_bits != 0 {
  531. bits = uint32(getBitsUnmasked(br))
  532. }
  533. p = p[bits&bitMask(huffmanMaxCodeLengthCodeLength):]
  534. if uint32(p[0].bits) > available_bits {
  535. get_byte = true
  536. continue
  537. }
  538. code_len = uint32(p[0].value) /* code_len == 0..17 */
  539. if code_len < repeatPreviousCodeLength {
  540. dropBits(br, uint32(p[0].bits))
  541. processSingleCodeLength(code_len, &s.symbol, &s.repeat, &s.space, &s.prev_code_len, s.symbol_lists, s.code_length_histo[:], s.next_symbol[:]) /* code_len == 16..17, extra_bits == 2..3 */
  542. } else {
  543. var extra_bits uint32 = code_len - 14
  544. var repeat_delta uint32 = (bits >> p[0].bits) & bitMask(extra_bits)
  545. if available_bits < uint32(p[0].bits)+extra_bits {
  546. get_byte = true
  547. continue
  548. }
  549. dropBits(br, uint32(p[0].bits)+extra_bits)
  550. processRepeatedCodeLength(code_len, repeat_delta, alphabet_size, &s.symbol, &s.repeat, &s.space, &s.prev_code_len, &s.repeat_code_len, s.symbol_lists, s.code_length_histo[:], s.next_symbol[:])
  551. }
  552. }
  553. return decoderSuccess
  554. }
  555. /* Reads and decodes 15..18 codes using static prefix code.
  556. Each code is 2..4 bits long. In total 30..72 bits are used. */
  557. func readCodeLengthCodeLengths(s *Reader) int {
  558. var br *bitReader = &s.br
  559. var num_codes uint32 = s.repeat
  560. var space uint32 = s.space
  561. var i uint32 = s.sub_loop_counter
  562. for ; i < codeLengthCodes; i++ {
  563. var code_len_idx byte = kCodeLengthCodeOrder[i]
  564. var ix uint32
  565. var v uint32
  566. if !safeGetBits(br, 4, &ix) {
  567. var available_bits uint32 = getAvailableBits(br)
  568. if available_bits != 0 {
  569. ix = uint32(getBitsUnmasked(br) & 0xF)
  570. } else {
  571. ix = 0
  572. }
  573. if uint32(kCodeLengthPrefixLength[ix]) > available_bits {
  574. s.sub_loop_counter = i
  575. s.repeat = num_codes
  576. s.space = space
  577. s.substate_huffman = stateHuffmanComplex
  578. return decoderNeedsMoreInput
  579. }
  580. }
  581. v = uint32(kCodeLengthPrefixValue[ix])
  582. dropBits(br, uint32(kCodeLengthPrefixLength[ix]))
  583. s.code_length_code_lengths[code_len_idx] = byte(v)
  584. if v != 0 {
  585. space = space - (32 >> v)
  586. num_codes++
  587. s.code_length_histo[v]++
  588. if space-1 >= 32 {
  589. /* space is 0 or wrapped around. */
  590. break
  591. }
  592. }
  593. }
  594. if num_codes != 1 && space != 0 {
  595. return decoderErrorFormatClSpace
  596. }
  597. return decoderSuccess
  598. }
  599. /* Decodes the Huffman tables.
  600. There are 2 scenarios:
  601. A) Huffman code contains only few symbols (1..4). Those symbols are read
  602. directly; their code lengths are defined by the number of symbols.
  603. For this scenario 4 - 49 bits will be read.
  604. B) 2-phase decoding:
  605. B.1) Small Huffman table is decoded; it is specified with code lengths
  606. encoded with predefined entropy code. 32 - 74 bits are used.
  607. B.2) Decoded table is used to decode code lengths of symbols in resulting
  608. Huffman table. In worst case 3520 bits are read. */
  609. func readHuffmanCode(alphabet_size uint32, max_symbol uint32, table []huffmanCode, opt_table_size *uint32, s *Reader) int {
  610. var br *bitReader = &s.br
  611. /* Unnecessary masking, but might be good for safety. */
  612. alphabet_size &= 0x7FF
  613. /* State machine. */
  614. for {
  615. switch s.substate_huffman {
  616. case stateHuffmanNone:
  617. if !safeReadBits(br, 2, &s.sub_loop_counter) {
  618. return decoderNeedsMoreInput
  619. }
  620. /* The value is used as follows:
  621. 1 for simple code;
  622. 0 for no skipping, 2 skips 2 code lengths, 3 skips 3 code lengths */
  623. if s.sub_loop_counter != 1 {
  624. s.space = 32
  625. s.repeat = 0 /* num_codes */
  626. var i int
  627. for i = 0; i <= huffmanMaxCodeLengthCodeLength; i++ {
  628. s.code_length_histo[i] = 0
  629. }
  630. for i = 0; i < codeLengthCodes; i++ {
  631. s.code_length_code_lengths[i] = 0
  632. }
  633. s.substate_huffman = stateHuffmanComplex
  634. continue
  635. }
  636. fallthrough
  637. /* Read symbols, codes & code lengths directly. */
  638. case stateHuffmanSimpleSize:
  639. if !safeReadBits(br, 2, &s.symbol) { /* num_symbols */
  640. s.substate_huffman = stateHuffmanSimpleSize
  641. return decoderNeedsMoreInput
  642. }
  643. s.sub_loop_counter = 0
  644. fallthrough
  645. case stateHuffmanSimpleRead:
  646. {
  647. var result int = readSimpleHuffmanSymbols(alphabet_size, max_symbol, s)
  648. if result != decoderSuccess {
  649. return result
  650. }
  651. }
  652. fallthrough
  653. case stateHuffmanSimpleBuild:
  654. var table_size uint32
  655. if s.symbol == 3 {
  656. var bits uint32
  657. if !safeReadBits(br, 1, &bits) {
  658. s.substate_huffman = stateHuffmanSimpleBuild
  659. return decoderNeedsMoreInput
  660. }
  661. s.symbol += bits
  662. }
  663. table_size = buildSimpleHuffmanTable(table, huffmanTableBits, s.symbols_lists_array[:], s.symbol)
  664. if opt_table_size != nil {
  665. *opt_table_size = table_size
  666. }
  667. s.substate_huffman = stateHuffmanNone
  668. return decoderSuccess
  669. /* Decode Huffman-coded code lengths. */
  670. case stateHuffmanComplex:
  671. {
  672. var i uint32
  673. var result int = readCodeLengthCodeLengths(s)
  674. if result != decoderSuccess {
  675. return result
  676. }
  677. buildCodeLengthsHuffmanTable(s.table[:], s.code_length_code_lengths[:], s.code_length_histo[:])
  678. for i = 0; i < 16; i++ {
  679. s.code_length_histo[i] = 0
  680. }
  681. for i = 0; i <= huffmanMaxCodeLength; i++ {
  682. s.next_symbol[i] = int(i) - (huffmanMaxCodeLength + 1)
  683. symbolListPut(s.symbol_lists, s.next_symbol[i], 0xFFFF)
  684. }
  685. s.symbol = 0
  686. s.prev_code_len = initialRepeatedCodeLength
  687. s.repeat = 0
  688. s.repeat_code_len = 0
  689. s.space = 32768
  690. s.substate_huffman = stateHuffmanLengthSymbols
  691. }
  692. fallthrough
  693. case stateHuffmanLengthSymbols:
  694. var table_size uint32
  695. var result int = readSymbolCodeLengths(max_symbol, s)
  696. if result == decoderNeedsMoreInput {
  697. result = safeReadSymbolCodeLengths(max_symbol, s)
  698. }
  699. if result != decoderSuccess {
  700. return result
  701. }
  702. if s.space != 0 {
  703. return decoderErrorFormatHuffmanSpace
  704. }
  705. table_size = buildHuffmanTable(table, huffmanTableBits, s.symbol_lists, s.code_length_histo[:])
  706. if opt_table_size != nil {
  707. *opt_table_size = table_size
  708. }
  709. s.substate_huffman = stateHuffmanNone
  710. return decoderSuccess
  711. default:
  712. return decoderErrorUnreachable
  713. }
  714. }
  715. }
  716. /* Decodes a block length by reading 3..39 bits. */
  717. func readBlockLength(table []huffmanCode, br *bitReader) uint32 {
  718. var code uint32
  719. var nbits uint32
  720. code = readSymbol(table, br)
  721. nbits = kBlockLengthPrefixCode[code].nbits /* nbits == 2..24 */
  722. return kBlockLengthPrefixCode[code].offset + readBits(br, nbits)
  723. }
  724. /* WARNING: if state is not BROTLI_STATE_READ_BLOCK_LENGTH_NONE, then
  725. reading can't be continued with ReadBlockLength. */
  726. func safeReadBlockLength(s *Reader, result *uint32, table []huffmanCode, br *bitReader) bool {
  727. var index uint32
  728. if s.substate_read_block_length == stateReadBlockLengthNone {
  729. if !safeReadSymbol(table, br, &index) {
  730. return false
  731. }
  732. } else {
  733. index = s.block_length_index
  734. }
  735. {
  736. var bits uint32 /* nbits == 2..24 */
  737. var nbits uint32 = kBlockLengthPrefixCode[index].nbits
  738. if !safeReadBits(br, nbits, &bits) {
  739. s.block_length_index = index
  740. s.substate_read_block_length = stateReadBlockLengthSuffix
  741. return false
  742. }
  743. *result = kBlockLengthPrefixCode[index].offset + bits
  744. s.substate_read_block_length = stateReadBlockLengthNone
  745. return true
  746. }
  747. }
  748. /* Transform:
  749. 1) initialize list L with values 0, 1,... 255
  750. 2) For each input element X:
  751. 2.1) let Y = L[X]
  752. 2.2) remove X-th element from L
  753. 2.3) prepend Y to L
  754. 2.4) append Y to output
  755. In most cases max(Y) <= 7, so most of L remains intact.
  756. To reduce the cost of initialization, we reuse L, remember the upper bound
  757. of Y values, and reinitialize only first elements in L.
  758. Most of input values are 0 and 1. To reduce number of branches, we replace
  759. inner for loop with do-while. */
  760. func inverseMoveToFrontTransform(v []byte, v_len uint32, state *Reader) {
  761. var mtf [256]byte
  762. var i int
  763. for i = 1; i < 256; i++ {
  764. mtf[i] = byte(i)
  765. }
  766. var mtf_1 byte
  767. /* Transform the input. */
  768. for i = 0; uint32(i) < v_len; i++ {
  769. var index int = int(v[i])
  770. var value byte = mtf[index]
  771. v[i] = value
  772. mtf_1 = value
  773. for index >= 1 {
  774. index--
  775. mtf[index+1] = mtf[index]
  776. }
  777. mtf[0] = mtf_1
  778. }
  779. }
  780. /* Decodes a series of Huffman table using ReadHuffmanCode function. */
  781. func huffmanTreeGroupDecode(group *huffmanTreeGroup, s *Reader) int {
  782. if s.substate_tree_group != stateTreeGroupLoop {
  783. s.next = group.codes
  784. s.htree_index = 0
  785. s.substate_tree_group = stateTreeGroupLoop
  786. }
  787. for s.htree_index < int(group.num_htrees) {
  788. var table_size uint32
  789. var result int = readHuffmanCode(uint32(group.alphabet_size), uint32(group.max_symbol), s.next, &table_size, s)
  790. if result != decoderSuccess {
  791. return result
  792. }
  793. group.htrees[s.htree_index] = s.next
  794. s.next = s.next[table_size:]
  795. s.htree_index++
  796. }
  797. s.substate_tree_group = stateTreeGroupNone
  798. return decoderSuccess
  799. }
  800. /* Decodes a context map.
  801. Decoding is done in 4 phases:
  802. 1) Read auxiliary information (6..16 bits) and allocate memory.
  803. In case of trivial context map, decoding is finished at this phase.
  804. 2) Decode Huffman table using ReadHuffmanCode function.
  805. This table will be used for reading context map items.
  806. 3) Read context map items; "0" values could be run-length encoded.
  807. 4) Optionally, apply InverseMoveToFront transform to the resulting map. */
  808. func decodeContextMap(context_map_size uint32, num_htrees *uint32, context_map_arg *[]byte, s *Reader) int {
  809. var br *bitReader = &s.br
  810. var result int = decoderSuccess
  811. switch int(s.substate_context_map) {
  812. case stateContextMapNone:
  813. result = decodeVarLenUint8(s, br, num_htrees)
  814. if result != decoderSuccess {
  815. return result
  816. }
  817. (*num_htrees)++
  818. s.context_index = 0
  819. *context_map_arg = make([]byte, uint(context_map_size))
  820. if *context_map_arg == nil {
  821. return decoderErrorAllocContextMap
  822. }
  823. if *num_htrees <= 1 {
  824. for i := 0; i < int(context_map_size); i++ {
  825. (*context_map_arg)[i] = 0
  826. }
  827. return decoderSuccess
  828. }
  829. s.substate_context_map = stateContextMapReadPrefix
  830. fallthrough
  831. /* Fall through. */
  832. case stateContextMapReadPrefix:
  833. {
  834. var bits uint32
  835. /* In next stage ReadHuffmanCode uses at least 4 bits, so it is safe
  836. to peek 4 bits ahead. */
  837. if !safeGetBits(br, 5, &bits) {
  838. return decoderNeedsMoreInput
  839. }
  840. if bits&1 != 0 { /* Use RLE for zeros. */
  841. s.max_run_length_prefix = (bits >> 1) + 1
  842. dropBits(br, 5)
  843. } else {
  844. s.max_run_length_prefix = 0
  845. dropBits(br, 1)
  846. }
  847. s.substate_context_map = stateContextMapHuffman
  848. }
  849. fallthrough
  850. /* Fall through. */
  851. case stateContextMapHuffman:
  852. {
  853. var alphabet_size uint32 = *num_htrees + s.max_run_length_prefix
  854. result = readHuffmanCode(alphabet_size, alphabet_size, s.context_map_table[:], nil, s)
  855. if result != decoderSuccess {
  856. return result
  857. }
  858. s.code = 0xFFFF
  859. s.substate_context_map = stateContextMapDecode
  860. }
  861. fallthrough
  862. /* Fall through. */
  863. case stateContextMapDecode:
  864. {
  865. var context_index uint32 = s.context_index
  866. var max_run_length_prefix uint32 = s.max_run_length_prefix
  867. var context_map []byte = *context_map_arg
  868. var code uint32 = s.code
  869. var skip_preamble bool = (code != 0xFFFF)
  870. for context_index < context_map_size || skip_preamble {
  871. if !skip_preamble {
  872. if !safeReadSymbol(s.context_map_table[:], br, &code) {
  873. s.code = 0xFFFF
  874. s.context_index = context_index
  875. return decoderNeedsMoreInput
  876. }
  877. if code == 0 {
  878. context_map[context_index] = 0
  879. context_index++
  880. continue
  881. }
  882. if code > max_run_length_prefix {
  883. context_map[context_index] = byte(code - max_run_length_prefix)
  884. context_index++
  885. continue
  886. }
  887. } else {
  888. skip_preamble = false
  889. }
  890. /* RLE sub-stage. */
  891. {
  892. var reps uint32
  893. if !safeReadBits(br, code, &reps) {
  894. s.code = code
  895. s.context_index = context_index
  896. return decoderNeedsMoreInput
  897. }
  898. reps += 1 << code
  899. if context_index+reps > context_map_size {
  900. return decoderErrorFormatContextMapRepeat
  901. }
  902. for {
  903. context_map[context_index] = 0
  904. context_index++
  905. reps--
  906. if reps == 0 {
  907. break
  908. }
  909. }
  910. }
  911. }
  912. }
  913. fallthrough
  914. case stateContextMapTransform:
  915. var bits uint32
  916. if !safeReadBits(br, 1, &bits) {
  917. s.substate_context_map = stateContextMapTransform
  918. return decoderNeedsMoreInput
  919. }
  920. if bits != 0 {
  921. inverseMoveToFrontTransform(*context_map_arg, context_map_size, s)
  922. }
  923. s.substate_context_map = stateContextMapNone
  924. return decoderSuccess
  925. default:
  926. return decoderErrorUnreachable
  927. }
  928. }
  929. /* Decodes a command or literal and updates block type ring-buffer.
  930. Reads 3..54 bits. */
  931. func decodeBlockTypeAndLength(safe int, s *Reader, tree_type int) bool {
  932. var max_block_type uint32 = s.num_block_types[tree_type]
  933. type_tree := s.block_type_trees[tree_type*huffmanMaxSize258:]
  934. len_tree := s.block_len_trees[tree_type*huffmanMaxSize26:]
  935. var br *bitReader = &s.br
  936. var ringbuffer []uint32 = s.block_type_rb[tree_type*2:]
  937. var block_type uint32
  938. if max_block_type <= 1 {
  939. return false
  940. }
  941. /* Read 0..15 + 3..39 bits. */
  942. if safe == 0 {
  943. block_type = readSymbol(type_tree, br)
  944. s.block_length[tree_type] = readBlockLength(len_tree, br)
  945. } else {
  946. var memento bitReaderState
  947. bitReaderSaveState(br, &memento)
  948. if !safeReadSymbol(type_tree, br, &block_type) {
  949. return false
  950. }
  951. if !safeReadBlockLength(s, &s.block_length[tree_type], len_tree, br) {
  952. s.substate_read_block_length = stateReadBlockLengthNone
  953. bitReaderRestoreState(br, &memento)
  954. return false
  955. }
  956. }
  957. if block_type == 1 {
  958. block_type = ringbuffer[1] + 1
  959. } else if block_type == 0 {
  960. block_type = ringbuffer[0]
  961. } else {
  962. block_type -= 2
  963. }
  964. if block_type >= max_block_type {
  965. block_type -= max_block_type
  966. }
  967. ringbuffer[0] = ringbuffer[1]
  968. ringbuffer[1] = block_type
  969. return true
  970. }
  971. func detectTrivialLiteralBlockTypes(s *Reader) {
  972. var i uint
  973. for i = 0; i < 8; i++ {
  974. s.trivial_literal_contexts[i] = 0
  975. }
  976. for i = 0; uint32(i) < s.num_block_types[0]; i++ {
  977. var offset uint = i << literalContextBits
  978. var error uint = 0
  979. var sample uint = uint(s.context_map[offset])
  980. var j uint
  981. for j = 0; j < 1<<literalContextBits; {
  982. var k int
  983. for k = 0; k < 4; k++ {
  984. error |= uint(s.context_map[offset+j]) ^ sample
  985. j++
  986. }
  987. }
  988. if error == 0 {
  989. s.trivial_literal_contexts[i>>5] |= 1 << (i & 31)
  990. }
  991. }
  992. }
  993. func prepareLiteralDecoding(s *Reader) {
  994. var context_mode byte
  995. var trivial uint
  996. var block_type uint32 = s.block_type_rb[1]
  997. var context_offset uint32 = block_type << literalContextBits
  998. s.context_map_slice = s.context_map[context_offset:]
  999. trivial = uint(s.trivial_literal_contexts[block_type>>5])
  1000. s.trivial_literal_context = int((trivial >> (block_type & 31)) & 1)
  1001. s.literal_htree = []huffmanCode(s.literal_hgroup.htrees[s.context_map_slice[0]])
  1002. context_mode = s.context_modes[block_type] & 3
  1003. s.context_lookup = getContextLUT(int(context_mode))
  1004. }
  1005. /* Decodes the block type and updates the state for literal context.
  1006. Reads 3..54 bits. */
  1007. func decodeLiteralBlockSwitchInternal(safe int, s *Reader) bool {
  1008. if !decodeBlockTypeAndLength(safe, s, 0) {
  1009. return false
  1010. }
  1011. prepareLiteralDecoding(s)
  1012. return true
  1013. }
  1014. func decodeLiteralBlockSwitch(s *Reader) {
  1015. decodeLiteralBlockSwitchInternal(0, s)
  1016. }
  1017. func safeDecodeLiteralBlockSwitch(s *Reader) bool {
  1018. return decodeLiteralBlockSwitchInternal(1, s)
  1019. }
  1020. /* Block switch for insert/copy length.
  1021. Reads 3..54 bits. */
  1022. func decodeCommandBlockSwitchInternal(safe int, s *Reader) bool {
  1023. if !decodeBlockTypeAndLength(safe, s, 1) {
  1024. return false
  1025. }
  1026. s.htree_command = []huffmanCode(s.insert_copy_hgroup.htrees[s.block_type_rb[3]])
  1027. return true
  1028. }
  1029. func decodeCommandBlockSwitch(s *Reader) {
  1030. decodeCommandBlockSwitchInternal(0, s)
  1031. }
  1032. func safeDecodeCommandBlockSwitch(s *Reader) bool {
  1033. return decodeCommandBlockSwitchInternal(1, s)
  1034. }
  1035. /* Block switch for distance codes.
  1036. Reads 3..54 bits. */
  1037. func decodeDistanceBlockSwitchInternal(safe int, s *Reader) bool {
  1038. if !decodeBlockTypeAndLength(safe, s, 2) {
  1039. return false
  1040. }
  1041. s.dist_context_map_slice = s.dist_context_map[s.block_type_rb[5]<<distanceContextBits:]
  1042. s.dist_htree_index = s.dist_context_map_slice[s.distance_context]
  1043. return true
  1044. }
  1045. func decodeDistanceBlockSwitch(s *Reader) {
  1046. decodeDistanceBlockSwitchInternal(0, s)
  1047. }
  1048. func safeDecodeDistanceBlockSwitch(s *Reader) bool {
  1049. return decodeDistanceBlockSwitchInternal(1, s)
  1050. }
  1051. func unwrittenBytes(s *Reader, wrap bool) uint {
  1052. var pos uint
  1053. if wrap && s.pos > s.ringbuffer_size {
  1054. pos = uint(s.ringbuffer_size)
  1055. } else {
  1056. pos = uint(s.pos)
  1057. }
  1058. var partial_pos_rb uint = (s.rb_roundtrips * uint(s.ringbuffer_size)) + pos
  1059. return partial_pos_rb - s.partial_pos_out
  1060. }
  1061. /* Dumps output.
  1062. Returns BROTLI_DECODER_NEEDS_MORE_OUTPUT only if there is more output to push
  1063. and either ring-buffer is as big as window size, or |force| is true. */
  1064. func writeRingBuffer(s *Reader, available_out *uint, next_out *[]byte, total_out *uint, force bool) int {
  1065. start := s.ringbuffer[s.partial_pos_out&uint(s.ringbuffer_mask):]
  1066. var to_write uint = unwrittenBytes(s, true)
  1067. var num_written uint = *available_out
  1068. if num_written > to_write {
  1069. num_written = to_write
  1070. }
  1071. if s.meta_block_remaining_len < 0 {
  1072. return decoderErrorFormatBlockLength1
  1073. }
  1074. if next_out != nil && *next_out == nil {
  1075. *next_out = start
  1076. } else {
  1077. if next_out != nil {
  1078. copy(*next_out, start[:num_written])
  1079. *next_out = (*next_out)[num_written:]
  1080. }
  1081. }
  1082. *available_out -= num_written
  1083. s.partial_pos_out += num_written
  1084. if total_out != nil {
  1085. *total_out = s.partial_pos_out
  1086. }
  1087. if num_written < to_write {
  1088. if s.ringbuffer_size == 1<<s.window_bits || force {
  1089. return decoderNeedsMoreOutput
  1090. } else {
  1091. return decoderSuccess
  1092. }
  1093. }
  1094. /* Wrap ring buffer only if it has reached its maximal size. */
  1095. if s.ringbuffer_size == 1<<s.window_bits && s.pos >= s.ringbuffer_size {
  1096. s.pos -= s.ringbuffer_size
  1097. s.rb_roundtrips++
  1098. if uint(s.pos) != 0 {
  1099. s.should_wrap_ringbuffer = 1
  1100. } else {
  1101. s.should_wrap_ringbuffer = 0
  1102. }
  1103. }
  1104. return decoderSuccess
  1105. }
  1106. func wrapRingBuffer(s *Reader) {
  1107. if s.should_wrap_ringbuffer != 0 {
  1108. copy(s.ringbuffer, s.ringbuffer_end[:uint(s.pos)])
  1109. s.should_wrap_ringbuffer = 0
  1110. }
  1111. }
  1112. /* Allocates ring-buffer.
  1113. s->ringbuffer_size MUST be updated by BrotliCalculateRingBufferSize before
  1114. this function is called.
  1115. Last two bytes of ring-buffer are initialized to 0, so context calculation
  1116. could be done uniformly for the first two and all other positions. */
  1117. func ensureRingBuffer(s *Reader) bool {
  1118. var old_ringbuffer []byte
  1119. if s.ringbuffer_size == s.new_ringbuffer_size {
  1120. return true
  1121. }
  1122. spaceNeeded := int(s.new_ringbuffer_size) + int(kRingBufferWriteAheadSlack)
  1123. if len(s.ringbuffer) < spaceNeeded {
  1124. old_ringbuffer = s.ringbuffer
  1125. s.ringbuffer = make([]byte, spaceNeeded)
  1126. }
  1127. s.ringbuffer[s.new_ringbuffer_size-2] = 0
  1128. s.ringbuffer[s.new_ringbuffer_size-1] = 0
  1129. if old_ringbuffer != nil {
  1130. copy(s.ringbuffer, old_ringbuffer[:uint(s.pos)])
  1131. }
  1132. s.ringbuffer_size = s.new_ringbuffer_size
  1133. s.ringbuffer_mask = s.new_ringbuffer_size - 1
  1134. s.ringbuffer_end = s.ringbuffer[s.ringbuffer_size:]
  1135. return true
  1136. }
  1137. func copyUncompressedBlockToOutput(available_out *uint, next_out *[]byte, total_out *uint, s *Reader) int {
  1138. /* TODO: avoid allocation for single uncompressed block. */
  1139. if !ensureRingBuffer(s) {
  1140. return decoderErrorAllocRingBuffer1
  1141. }
  1142. /* State machine */
  1143. for {
  1144. switch s.substate_uncompressed {
  1145. case stateUncompressedNone:
  1146. {
  1147. var nbytes int = int(getRemainingBytes(&s.br))
  1148. if nbytes > s.meta_block_remaining_len {
  1149. nbytes = s.meta_block_remaining_len
  1150. }
  1151. if s.pos+nbytes > s.ringbuffer_size {
  1152. nbytes = s.ringbuffer_size - s.pos
  1153. }
  1154. /* Copy remaining bytes from s->br.buf_ to ring-buffer. */
  1155. copyBytes(s.ringbuffer[s.pos:], &s.br, uint(nbytes))
  1156. s.pos += nbytes
  1157. s.meta_block_remaining_len -= nbytes
  1158. if s.pos < 1<<s.window_bits {
  1159. if s.meta_block_remaining_len == 0 {
  1160. return decoderSuccess
  1161. }
  1162. return decoderNeedsMoreInput
  1163. }
  1164. s.substate_uncompressed = stateUncompressedWrite
  1165. }
  1166. fallthrough
  1167. case stateUncompressedWrite:
  1168. {
  1169. result := writeRingBuffer(s, available_out, next_out, total_out, false)
  1170. if result != decoderSuccess {
  1171. return result
  1172. }
  1173. if s.ringbuffer_size == 1<<s.window_bits {
  1174. s.max_distance = s.max_backward_distance
  1175. }
  1176. s.substate_uncompressed = stateUncompressedNone
  1177. break
  1178. }
  1179. }
  1180. }
  1181. }
  1182. /* Calculates the smallest feasible ring buffer.
  1183. If we know the data size is small, do not allocate more ring buffer
  1184. size than needed to reduce memory usage.
  1185. When this method is called, metablock size and flags MUST be decoded. */
  1186. func calculateRingBufferSize(s *Reader) {
  1187. var window_size int = 1 << s.window_bits
  1188. var new_ringbuffer_size int = window_size
  1189. var min_size int
  1190. /* We need at least 2 bytes of ring buffer size to get the last two
  1191. bytes for context from there */
  1192. if s.ringbuffer_size != 0 {
  1193. min_size = s.ringbuffer_size
  1194. } else {
  1195. min_size = 1024
  1196. }
  1197. var output_size int
  1198. /* If maximum is already reached, no further extension is retired. */
  1199. if s.ringbuffer_size == window_size {
  1200. return
  1201. }
  1202. /* Metadata blocks does not touch ring buffer. */
  1203. if s.is_metadata != 0 {
  1204. return
  1205. }
  1206. if s.ringbuffer == nil {
  1207. output_size = 0
  1208. } else {
  1209. output_size = s.pos
  1210. }
  1211. output_size += s.meta_block_remaining_len
  1212. if min_size < output_size {
  1213. min_size = output_size
  1214. }
  1215. if !(s.canny_ringbuffer_allocation == 0) {
  1216. /* Reduce ring buffer size to save memory when server is unscrupulous.
  1217. In worst case memory usage might be 1.5x bigger for a short period of
  1218. ring buffer reallocation. */
  1219. for new_ringbuffer_size>>1 >= min_size {
  1220. new_ringbuffer_size >>= 1
  1221. }
  1222. }
  1223. s.new_ringbuffer_size = new_ringbuffer_size
  1224. }
  1225. /* Reads 1..256 2-bit context modes. */
  1226. func readContextModes(s *Reader) int {
  1227. var br *bitReader = &s.br
  1228. var i int = s.loop_counter
  1229. for i < int(s.num_block_types[0]) {
  1230. var bits uint32
  1231. if !safeReadBits(br, 2, &bits) {
  1232. s.loop_counter = i
  1233. return decoderNeedsMoreInput
  1234. }
  1235. s.context_modes[i] = byte(bits)
  1236. i++
  1237. }
  1238. return decoderSuccess
  1239. }
  1240. func takeDistanceFromRingBuffer(s *Reader) {
  1241. if s.distance_code == 0 {
  1242. s.dist_rb_idx--
  1243. s.distance_code = s.dist_rb[s.dist_rb_idx&3]
  1244. /* Compensate double distance-ring-buffer roll for dictionary items. */
  1245. s.distance_context = 1
  1246. } else {
  1247. var distance_code int = s.distance_code << 1
  1248. const kDistanceShortCodeIndexOffset uint32 = 0xAAAFFF1B
  1249. const kDistanceShortCodeValueOffset uint32 = 0xFA5FA500
  1250. var v int = (s.dist_rb_idx + int(kDistanceShortCodeIndexOffset>>uint(distance_code))) & 0x3
  1251. /* kDistanceShortCodeIndexOffset has 2-bit values from LSB:
  1252. 3, 2, 1, 0, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2 */
  1253. /* kDistanceShortCodeValueOffset has 2-bit values from LSB:
  1254. -0, 0,-0, 0,-1, 1,-2, 2,-3, 3,-1, 1,-2, 2,-3, 3 */
  1255. s.distance_code = s.dist_rb[v]
  1256. v = int(kDistanceShortCodeValueOffset>>uint(distance_code)) & 0x3
  1257. if distance_code&0x3 != 0 {
  1258. s.distance_code += v
  1259. } else {
  1260. s.distance_code -= v
  1261. if s.distance_code <= 0 {
  1262. /* A huge distance will cause a () soon.
  1263. This is a little faster than failing here. */
  1264. s.distance_code = 0x7FFFFFFF
  1265. }
  1266. }
  1267. }
  1268. }
  1269. func safeReadBitsMaybeZero(br *bitReader, n_bits uint32, val *uint32) bool {
  1270. if n_bits != 0 {
  1271. return safeReadBits(br, n_bits, val)
  1272. } else {
  1273. *val = 0
  1274. return true
  1275. }
  1276. }
  1277. /* Precondition: s->distance_code < 0. */
  1278. func readDistanceInternal(safe int, s *Reader, br *bitReader) bool {
  1279. var distval int
  1280. var memento bitReaderState
  1281. var distance_tree []huffmanCode = []huffmanCode(s.distance_hgroup.htrees[s.dist_htree_index])
  1282. if safe == 0 {
  1283. s.distance_code = int(readSymbol(distance_tree, br))
  1284. } else {
  1285. var code uint32
  1286. bitReaderSaveState(br, &memento)
  1287. if !safeReadSymbol(distance_tree, br, &code) {
  1288. return false
  1289. }
  1290. s.distance_code = int(code)
  1291. }
  1292. /* Convert the distance code to the actual distance by possibly
  1293. looking up past distances from the s->ringbuffer. */
  1294. s.distance_context = 0
  1295. if s.distance_code&^0xF == 0 {
  1296. takeDistanceFromRingBuffer(s)
  1297. s.block_length[2]--
  1298. return true
  1299. }
  1300. distval = s.distance_code - int(s.num_direct_distance_codes)
  1301. if distval >= 0 {
  1302. var nbits uint32
  1303. var postfix int
  1304. var offset int
  1305. if safe == 0 && (s.distance_postfix_bits == 0) {
  1306. nbits = (uint32(distval) >> 1) + 1
  1307. offset = ((2 + (distval & 1)) << nbits) - 4
  1308. s.distance_code = int(s.num_direct_distance_codes) + offset + int(readBits(br, nbits))
  1309. } else {
  1310. /* This branch also works well when s->distance_postfix_bits == 0. */
  1311. var bits uint32
  1312. postfix = distval & s.distance_postfix_mask
  1313. distval >>= s.distance_postfix_bits
  1314. nbits = (uint32(distval) >> 1) + 1
  1315. if safe != 0 {
  1316. if !safeReadBitsMaybeZero(br, nbits, &bits) {
  1317. s.distance_code = -1 /* Restore precondition. */
  1318. bitReaderRestoreState(br, &memento)
  1319. return false
  1320. }
  1321. } else {
  1322. bits = readBits(br, nbits)
  1323. }
  1324. offset = ((2 + (distval & 1)) << nbits) - 4
  1325. s.distance_code = int(s.num_direct_distance_codes) + ((offset + int(bits)) << s.distance_postfix_bits) + postfix
  1326. }
  1327. }
  1328. s.distance_code = s.distance_code - numDistanceShortCodes + 1
  1329. s.block_length[2]--
  1330. return true
  1331. }
  1332. func readDistance(s *Reader, br *bitReader) {
  1333. readDistanceInternal(0, s, br)
  1334. }
  1335. func safeReadDistance(s *Reader, br *bitReader) bool {
  1336. return readDistanceInternal(1, s, br)
  1337. }
  1338. func readCommandInternal(safe int, s *Reader, br *bitReader, insert_length *int) bool {
  1339. var cmd_code uint32
  1340. var insert_len_extra uint32 = 0
  1341. var copy_length uint32
  1342. var v cmdLutElement
  1343. var memento bitReaderState
  1344. if safe == 0 {
  1345. cmd_code = readSymbol(s.htree_command, br)
  1346. } else {
  1347. bitReaderSaveState(br, &memento)
  1348. if !safeReadSymbol(s.htree_command, br, &cmd_code) {
  1349. return false
  1350. }
  1351. }
  1352. v = kCmdLut[cmd_code]
  1353. s.distance_code = int(v.distance_code)
  1354. s.distance_context = int(v.context)
  1355. s.dist_htree_index = s.dist_context_map_slice[s.distance_context]
  1356. *insert_length = int(v.insert_len_offset)
  1357. if safe == 0 {
  1358. if v.insert_len_extra_bits != 0 {
  1359. insert_len_extra = readBits(br, uint32(v.insert_len_extra_bits))
  1360. }
  1361. copy_length = readBits(br, uint32(v.copy_len_extra_bits))
  1362. } else {
  1363. if !safeReadBitsMaybeZero(br, uint32(v.insert_len_extra_bits), &insert_len_extra) || !safeReadBitsMaybeZero(br, uint32(v.copy_len_extra_bits), &copy_length) {
  1364. bitReaderRestoreState(br, &memento)
  1365. return false
  1366. }
  1367. }
  1368. s.copy_length = int(copy_length) + int(v.copy_len_offset)
  1369. s.block_length[1]--
  1370. *insert_length += int(insert_len_extra)
  1371. return true
  1372. }
  1373. func readCommand(s *Reader, br *bitReader, insert_length *int) {
  1374. readCommandInternal(0, s, br, insert_length)
  1375. }
  1376. func safeReadCommand(s *Reader, br *bitReader, insert_length *int) bool {
  1377. return readCommandInternal(1, s, br, insert_length)
  1378. }
  1379. func checkInputAmountMaybeSafe(safe int, br *bitReader, num uint) bool {
  1380. if safe != 0 {
  1381. return true
  1382. }
  1383. return checkInputAmount(br, num)
  1384. }
  1385. func processCommandsInternal(safe int, s *Reader) int {
  1386. var pos int = s.pos
  1387. var i int = s.loop_counter
  1388. var result int = decoderSuccess
  1389. var br *bitReader = &s.br
  1390. var hc []huffmanCode
  1391. if !checkInputAmountMaybeSafe(safe, br, 28) {
  1392. result = decoderNeedsMoreInput
  1393. goto saveStateAndReturn
  1394. }
  1395. if safe == 0 {
  1396. warmupBitReader(br)
  1397. }
  1398. /* Jump into state machine. */
  1399. if s.state == stateCommandBegin {
  1400. goto CommandBegin
  1401. } else if s.state == stateCommandInner {
  1402. goto CommandInner
  1403. } else if s.state == stateCommandPostDecodeLiterals {
  1404. goto CommandPostDecodeLiterals
  1405. } else if s.state == stateCommandPostWrapCopy {
  1406. goto CommandPostWrapCopy
  1407. } else {
  1408. return decoderErrorUnreachable
  1409. }
  1410. CommandBegin:
  1411. if safe != 0 {
  1412. s.state = stateCommandBegin
  1413. }
  1414. if !checkInputAmountMaybeSafe(safe, br, 28) { /* 156 bits + 7 bytes */
  1415. s.state = stateCommandBegin
  1416. result = decoderNeedsMoreInput
  1417. goto saveStateAndReturn
  1418. }
  1419. if s.block_length[1] == 0 {
  1420. if safe != 0 {
  1421. if !safeDecodeCommandBlockSwitch(s) {
  1422. result = decoderNeedsMoreInput
  1423. goto saveStateAndReturn
  1424. }
  1425. } else {
  1426. decodeCommandBlockSwitch(s)
  1427. }
  1428. goto CommandBegin
  1429. }
  1430. /* Read the insert/copy length in the command. */
  1431. if safe != 0 {
  1432. if !safeReadCommand(s, br, &i) {
  1433. result = decoderNeedsMoreInput
  1434. goto saveStateAndReturn
  1435. }
  1436. } else {
  1437. readCommand(s, br, &i)
  1438. }
  1439. if i == 0 {
  1440. goto CommandPostDecodeLiterals
  1441. }
  1442. s.meta_block_remaining_len -= i
  1443. CommandInner:
  1444. if safe != 0 {
  1445. s.state = stateCommandInner
  1446. }
  1447. /* Read the literals in the command. */
  1448. if s.trivial_literal_context != 0 {
  1449. var bits uint32
  1450. var value uint32
  1451. preloadSymbol(safe, s.literal_htree, br, &bits, &value)
  1452. for {
  1453. if !checkInputAmountMaybeSafe(safe, br, 28) { /* 162 bits + 7 bytes */
  1454. s.state = stateCommandInner
  1455. result = decoderNeedsMoreInput
  1456. goto saveStateAndReturn
  1457. }
  1458. if s.block_length[0] == 0 {
  1459. if safe != 0 {
  1460. if !safeDecodeLiteralBlockSwitch(s) {
  1461. result = decoderNeedsMoreInput
  1462. goto saveStateAndReturn
  1463. }
  1464. } else {
  1465. decodeLiteralBlockSwitch(s)
  1466. }
  1467. preloadSymbol(safe, s.literal_htree, br, &bits, &value)
  1468. if s.trivial_literal_context == 0 {
  1469. goto CommandInner
  1470. }
  1471. }
  1472. if safe == 0 {
  1473. s.ringbuffer[pos] = byte(readPreloadedSymbol(s.literal_htree, br, &bits, &value))
  1474. } else {
  1475. var literal uint32
  1476. if !safeReadSymbol(s.literal_htree, br, &literal) {
  1477. result = decoderNeedsMoreInput
  1478. goto saveStateAndReturn
  1479. }
  1480. s.ringbuffer[pos] = byte(literal)
  1481. }
  1482. s.block_length[0]--
  1483. pos++
  1484. if pos == s.ringbuffer_size {
  1485. s.state = stateCommandInnerWrite
  1486. i--
  1487. goto saveStateAndReturn
  1488. }
  1489. i--
  1490. if i == 0 {
  1491. break
  1492. }
  1493. }
  1494. } else {
  1495. var p1 byte = s.ringbuffer[(pos-1)&s.ringbuffer_mask]
  1496. var p2 byte = s.ringbuffer[(pos-2)&s.ringbuffer_mask]
  1497. for {
  1498. var context byte
  1499. if !checkInputAmountMaybeSafe(safe, br, 28) { /* 162 bits + 7 bytes */
  1500. s.state = stateCommandInner
  1501. result = decoderNeedsMoreInput
  1502. goto saveStateAndReturn
  1503. }
  1504. if s.block_length[0] == 0 {
  1505. if safe != 0 {
  1506. if !safeDecodeLiteralBlockSwitch(s) {
  1507. result = decoderNeedsMoreInput
  1508. goto saveStateAndReturn
  1509. }
  1510. } else {
  1511. decodeLiteralBlockSwitch(s)
  1512. }
  1513. if s.trivial_literal_context != 0 {
  1514. goto CommandInner
  1515. }
  1516. }
  1517. context = getContext(p1, p2, s.context_lookup)
  1518. hc = []huffmanCode(s.literal_hgroup.htrees[s.context_map_slice[context]])
  1519. p2 = p1
  1520. if safe == 0 {
  1521. p1 = byte(readSymbol(hc, br))
  1522. } else {
  1523. var literal uint32
  1524. if !safeReadSymbol(hc, br, &literal) {
  1525. result = decoderNeedsMoreInput
  1526. goto saveStateAndReturn
  1527. }
  1528. p1 = byte(literal)
  1529. }
  1530. s.ringbuffer[pos] = p1
  1531. s.block_length[0]--
  1532. pos++
  1533. if pos == s.ringbuffer_size {
  1534. s.state = stateCommandInnerWrite
  1535. i--
  1536. goto saveStateAndReturn
  1537. }
  1538. i--
  1539. if i == 0 {
  1540. break
  1541. }
  1542. }
  1543. }
  1544. if s.meta_block_remaining_len <= 0 {
  1545. s.state = stateMetablockDone
  1546. goto saveStateAndReturn
  1547. }
  1548. CommandPostDecodeLiterals:
  1549. if safe != 0 {
  1550. s.state = stateCommandPostDecodeLiterals
  1551. }
  1552. if s.distance_code >= 0 {
  1553. /* Implicit distance case. */
  1554. if s.distance_code != 0 {
  1555. s.distance_context = 0
  1556. } else {
  1557. s.distance_context = 1
  1558. }
  1559. s.dist_rb_idx--
  1560. s.distance_code = s.dist_rb[s.dist_rb_idx&3]
  1561. } else {
  1562. /* Read distance code in the command, unless it was implicitly zero. */
  1563. if s.block_length[2] == 0 {
  1564. if safe != 0 {
  1565. if !safeDecodeDistanceBlockSwitch(s) {
  1566. result = decoderNeedsMoreInput
  1567. goto saveStateAndReturn
  1568. }
  1569. } else {
  1570. decodeDistanceBlockSwitch(s)
  1571. }
  1572. }
  1573. if safe != 0 {
  1574. if !safeReadDistance(s, br) {
  1575. result = decoderNeedsMoreInput
  1576. goto saveStateAndReturn
  1577. }
  1578. } else {
  1579. readDistance(s, br)
  1580. }
  1581. }
  1582. if s.max_distance != s.max_backward_distance {
  1583. if pos < s.max_backward_distance {
  1584. s.max_distance = pos
  1585. } else {
  1586. s.max_distance = s.max_backward_distance
  1587. }
  1588. }
  1589. i = s.copy_length
  1590. /* Apply copy of LZ77 back-reference, or static dictionary reference if
  1591. the distance is larger than the max LZ77 distance */
  1592. if s.distance_code > s.max_distance {
  1593. /* The maximum allowed distance is BROTLI_MAX_ALLOWED_DISTANCE = 0x7FFFFFFC.
  1594. With this choice, no signed overflow can occur after decoding
  1595. a special distance code (e.g., after adding 3 to the last distance). */
  1596. if s.distance_code > maxAllowedDistance {
  1597. return decoderErrorFormatDistance
  1598. }
  1599. if i >= minDictionaryWordLength && i <= maxDictionaryWordLength {
  1600. var address int = s.distance_code - s.max_distance - 1
  1601. var words *dictionary = s.dictionary
  1602. var trans *transforms = s.transforms
  1603. var offset int = int(s.dictionary.offsets_by_length[i])
  1604. var shift uint32 = uint32(s.dictionary.size_bits_by_length[i])
  1605. var mask int = int(bitMask(shift))
  1606. var word_idx int = address & mask
  1607. var transform_idx int = address >> shift
  1608. /* Compensate double distance-ring-buffer roll. */
  1609. s.dist_rb_idx += s.distance_context
  1610. offset += word_idx * i
  1611. if words.data == nil {
  1612. return decoderErrorDictionaryNotSet
  1613. }
  1614. if transform_idx < int(trans.num_transforms) {
  1615. word := words.data[offset:]
  1616. var len int = i
  1617. if transform_idx == int(trans.cutOffTransforms[0]) {
  1618. copy(s.ringbuffer[pos:], word[:uint(len)])
  1619. } else {
  1620. len = transformDictionaryWord(s.ringbuffer[pos:], word, int(len), trans, transform_idx)
  1621. }
  1622. pos += int(len)
  1623. s.meta_block_remaining_len -= int(len)
  1624. if pos >= s.ringbuffer_size {
  1625. s.state = stateCommandPostWrite1
  1626. goto saveStateAndReturn
  1627. }
  1628. } else {
  1629. return decoderErrorFormatTransform
  1630. }
  1631. } else {
  1632. return decoderErrorFormatDictionary
  1633. }
  1634. } else {
  1635. var src_start int = (pos - s.distance_code) & s.ringbuffer_mask
  1636. copy_dst := s.ringbuffer[pos:]
  1637. copy_src := s.ringbuffer[src_start:]
  1638. var dst_end int = pos + i
  1639. var src_end int = src_start + i
  1640. /* Update the recent distances cache. */
  1641. s.dist_rb[s.dist_rb_idx&3] = s.distance_code
  1642. s.dist_rb_idx++
  1643. s.meta_block_remaining_len -= i
  1644. /* There are 32+ bytes of slack in the ring-buffer allocation.
  1645. Also, we have 16 short codes, that make these 16 bytes irrelevant
  1646. in the ring-buffer. Let's copy over them as a first guess. */
  1647. copy(copy_dst, copy_src[:16])
  1648. if src_end > pos && dst_end > src_start {
  1649. /* Regions intersect. */
  1650. goto CommandPostWrapCopy
  1651. }
  1652. if dst_end >= s.ringbuffer_size || src_end >= s.ringbuffer_size {
  1653. /* At least one region wraps. */
  1654. goto CommandPostWrapCopy
  1655. }
  1656. pos += i
  1657. if i > 16 {
  1658. if i > 32 {
  1659. copy(copy_dst[16:], copy_src[16:][:uint(i-16)])
  1660. } else {
  1661. /* This branch covers about 45% cases.
  1662. Fixed size short copy allows more compiler optimizations. */
  1663. copy(copy_dst[16:], copy_src[16:][:16])
  1664. }
  1665. }
  1666. }
  1667. if s.meta_block_remaining_len <= 0 {
  1668. /* Next metablock, if any. */
  1669. s.state = stateMetablockDone
  1670. goto saveStateAndReturn
  1671. } else {
  1672. goto CommandBegin
  1673. }
  1674. CommandPostWrapCopy:
  1675. {
  1676. var wrap_guard int = s.ringbuffer_size - pos
  1677. for {
  1678. i--
  1679. if i < 0 {
  1680. break
  1681. }
  1682. s.ringbuffer[pos] = s.ringbuffer[(pos-s.distance_code)&s.ringbuffer_mask]
  1683. pos++
  1684. wrap_guard--
  1685. if wrap_guard == 0 {
  1686. s.state = stateCommandPostWrite2
  1687. goto saveStateAndReturn
  1688. }
  1689. }
  1690. }
  1691. if s.meta_block_remaining_len <= 0 {
  1692. /* Next metablock, if any. */
  1693. s.state = stateMetablockDone
  1694. goto saveStateAndReturn
  1695. } else {
  1696. goto CommandBegin
  1697. }
  1698. saveStateAndReturn:
  1699. s.pos = pos
  1700. s.loop_counter = i
  1701. return result
  1702. }
  1703. func processCommands(s *Reader) int {
  1704. return processCommandsInternal(0, s)
  1705. }
  1706. func safeProcessCommands(s *Reader) int {
  1707. return processCommandsInternal(1, s)
  1708. }
  1709. /* Returns the maximum number of distance symbols which can only represent
  1710. distances not exceeding BROTLI_MAX_ALLOWED_DISTANCE. */
  1711. var maxDistanceSymbol_bound = [maxNpostfix + 1]uint32{0, 4, 12, 28}
  1712. var maxDistanceSymbol_diff = [maxNpostfix + 1]uint32{73, 126, 228, 424}
  1713. func maxDistanceSymbol(ndirect uint32, npostfix uint32) uint32 {
  1714. var postfix uint32 = 1 << npostfix
  1715. if ndirect < maxDistanceSymbol_bound[npostfix] {
  1716. return ndirect + maxDistanceSymbol_diff[npostfix] + postfix
  1717. } else if ndirect > maxDistanceSymbol_bound[npostfix]+postfix {
  1718. return ndirect + maxDistanceSymbol_diff[npostfix]
  1719. } else {
  1720. return maxDistanceSymbol_bound[npostfix] + maxDistanceSymbol_diff[npostfix] + postfix
  1721. }
  1722. }
  1723. /* Invariant: input stream is never overconsumed:
  1724. - invalid input implies that the whole stream is invalid -> any amount of
  1725. input could be read and discarded
  1726. - when result is "needs more input", then at least one more byte is REQUIRED
  1727. to complete decoding; all input data MUST be consumed by decoder, so
  1728. client could swap the input buffer
  1729. - when result is "needs more output" decoder MUST ensure that it doesn't
  1730. hold more than 7 bits in bit reader; this saves client from swapping input
  1731. buffer ahead of time
  1732. - when result is "success" decoder MUST return all unused data back to input
  1733. buffer; this is possible because the invariant is held on enter */
  1734. func decoderDecompressStream(s *Reader, available_in *uint, next_in *[]byte, available_out *uint, next_out *[]byte) int {
  1735. var result int = decoderSuccess
  1736. var br *bitReader = &s.br
  1737. /* Do not try to process further in a case of unrecoverable error. */
  1738. if int(s.error_code) < 0 {
  1739. return decoderResultError
  1740. }
  1741. if *available_out != 0 && (next_out == nil || *next_out == nil) {
  1742. return saveErrorCode(s, decoderErrorInvalidArguments)
  1743. }
  1744. if *available_out == 0 {
  1745. next_out = nil
  1746. }
  1747. if s.buffer_length == 0 { /* Just connect bit reader to input stream. */
  1748. br.input_len = *available_in
  1749. br.input = *next_in
  1750. br.byte_pos = 0
  1751. } else {
  1752. /* At least one byte of input is required. More than one byte of input may
  1753. be required to complete the transaction -> reading more data must be
  1754. done in a loop -> do it in a main loop. */
  1755. result = decoderNeedsMoreInput
  1756. br.input = s.buffer.u8[:]
  1757. br.byte_pos = 0
  1758. }
  1759. /* State machine */
  1760. for {
  1761. if result != decoderSuccess {
  1762. /* Error, needs more input/output. */
  1763. if result == decoderNeedsMoreInput {
  1764. if s.ringbuffer != nil { /* Pro-actively push output. */
  1765. var intermediate_result int = writeRingBuffer(s, available_out, next_out, nil, true)
  1766. /* WriteRingBuffer checks s->meta_block_remaining_len validity. */
  1767. if int(intermediate_result) < 0 {
  1768. result = intermediate_result
  1769. break
  1770. }
  1771. }
  1772. if s.buffer_length != 0 { /* Used with internal buffer. */
  1773. if br.byte_pos == br.input_len {
  1774. /* Successfully finished read transaction.
  1775. Accumulator contains less than 8 bits, because internal buffer
  1776. is expanded byte-by-byte until it is enough to complete read. */
  1777. s.buffer_length = 0
  1778. /* Switch to input stream and restart. */
  1779. result = decoderSuccess
  1780. br.input_len = *available_in
  1781. br.input = *next_in
  1782. br.byte_pos = 0
  1783. continue
  1784. } else if *available_in != 0 {
  1785. /* Not enough data in buffer, but can take one more byte from
  1786. input stream. */
  1787. result = decoderSuccess
  1788. s.buffer.u8[s.buffer_length] = (*next_in)[0]
  1789. s.buffer_length++
  1790. br.input_len = uint(s.buffer_length)
  1791. *next_in = (*next_in)[1:]
  1792. (*available_in)--
  1793. /* Retry with more data in buffer. */
  1794. continue
  1795. }
  1796. /* Can't finish reading and no more input. */
  1797. break
  1798. /* Input stream doesn't contain enough input. */
  1799. } else {
  1800. /* Copy tail to internal buffer and return. */
  1801. *next_in = br.input[br.byte_pos:]
  1802. *available_in = br.input_len - br.byte_pos
  1803. for *available_in != 0 {
  1804. s.buffer.u8[s.buffer_length] = (*next_in)[0]
  1805. s.buffer_length++
  1806. *next_in = (*next_in)[1:]
  1807. (*available_in)--
  1808. }
  1809. break
  1810. }
  1811. }
  1812. /* Unreachable. */
  1813. /* Fail or needs more output. */
  1814. if s.buffer_length != 0 {
  1815. /* Just consumed the buffered input and produced some output. Otherwise
  1816. it would result in "needs more input". Reset internal buffer. */
  1817. s.buffer_length = 0
  1818. } else {
  1819. /* Using input stream in last iteration. When decoder switches to input
  1820. stream it has less than 8 bits in accumulator, so it is safe to
  1821. return unused accumulator bits there. */
  1822. bitReaderUnload(br)
  1823. *available_in = br.input_len - br.byte_pos
  1824. *next_in = br.input[br.byte_pos:]
  1825. }
  1826. break
  1827. }
  1828. switch s.state {
  1829. /* Prepare to the first read. */
  1830. case stateUninited:
  1831. if !warmupBitReader(br) {
  1832. result = decoderNeedsMoreInput
  1833. break
  1834. }
  1835. /* Decode window size. */
  1836. result = decodeWindowBits(s, br) /* Reads 1..8 bits. */
  1837. if result != decoderSuccess {
  1838. break
  1839. }
  1840. if s.large_window {
  1841. s.state = stateLargeWindowBits
  1842. break
  1843. }
  1844. s.state = stateInitialize
  1845. case stateLargeWindowBits:
  1846. if !safeReadBits(br, 6, &s.window_bits) {
  1847. result = decoderNeedsMoreInput
  1848. break
  1849. }
  1850. if s.window_bits < largeMinWbits || s.window_bits > largeMaxWbits {
  1851. result = decoderErrorFormatWindowBits
  1852. break
  1853. }
  1854. s.state = stateInitialize
  1855. fallthrough
  1856. /* Maximum distance, see section 9.1. of the spec. */
  1857. /* Fall through. */
  1858. case stateInitialize:
  1859. s.max_backward_distance = (1 << s.window_bits) - windowGap
  1860. /* Allocate memory for both block_type_trees and block_len_trees. */
  1861. s.block_type_trees = make([]huffmanCode, (3 * (huffmanMaxSize258 + huffmanMaxSize26)))
  1862. if s.block_type_trees == nil {
  1863. result = decoderErrorAllocBlockTypeTrees
  1864. break
  1865. }
  1866. s.block_len_trees = s.block_type_trees[3*huffmanMaxSize258:]
  1867. s.state = stateMetablockBegin
  1868. fallthrough
  1869. /* Fall through. */
  1870. case stateMetablockBegin:
  1871. decoderStateMetablockBegin(s)
  1872. s.state = stateMetablockHeader
  1873. fallthrough
  1874. /* Fall through. */
  1875. case stateMetablockHeader:
  1876. result = decodeMetaBlockLength(s, br)
  1877. /* Reads 2 - 31 bits. */
  1878. if result != decoderSuccess {
  1879. break
  1880. }
  1881. if s.is_metadata != 0 || s.is_uncompressed != 0 {
  1882. if !bitReaderJumpToByteBoundary(br) {
  1883. result = decoderErrorFormatPadding1
  1884. break
  1885. }
  1886. }
  1887. if s.is_metadata != 0 {
  1888. s.state = stateMetadata
  1889. break
  1890. }
  1891. if s.meta_block_remaining_len == 0 {
  1892. s.state = stateMetablockDone
  1893. break
  1894. }
  1895. calculateRingBufferSize(s)
  1896. if s.is_uncompressed != 0 {
  1897. s.state = stateUncompressed
  1898. break
  1899. }
  1900. s.loop_counter = 0
  1901. s.state = stateHuffmanCode0
  1902. case stateUncompressed:
  1903. result = copyUncompressedBlockToOutput(available_out, next_out, nil, s)
  1904. if result == decoderSuccess {
  1905. s.state = stateMetablockDone
  1906. }
  1907. case stateMetadata:
  1908. for ; s.meta_block_remaining_len > 0; s.meta_block_remaining_len-- {
  1909. var bits uint32
  1910. /* Read one byte and ignore it. */
  1911. if !safeReadBits(br, 8, &bits) {
  1912. result = decoderNeedsMoreInput
  1913. break
  1914. }
  1915. }
  1916. if result == decoderSuccess {
  1917. s.state = stateMetablockDone
  1918. }
  1919. case stateHuffmanCode0:
  1920. if s.loop_counter >= 3 {
  1921. s.state = stateMetablockHeader2
  1922. break
  1923. }
  1924. /* Reads 1..11 bits. */
  1925. result = decodeVarLenUint8(s, br, &s.num_block_types[s.loop_counter])
  1926. if result != decoderSuccess {
  1927. break
  1928. }
  1929. s.num_block_types[s.loop_counter]++
  1930. if s.num_block_types[s.loop_counter] < 2 {
  1931. s.loop_counter++
  1932. break
  1933. }
  1934. s.state = stateHuffmanCode1
  1935. fallthrough
  1936. case stateHuffmanCode1:
  1937. {
  1938. var alphabet_size uint32 = s.num_block_types[s.loop_counter] + 2
  1939. var tree_offset int = s.loop_counter * huffmanMaxSize258
  1940. result = readHuffmanCode(alphabet_size, alphabet_size, s.block_type_trees[tree_offset:], nil, s)
  1941. if result != decoderSuccess {
  1942. break
  1943. }
  1944. s.state = stateHuffmanCode2
  1945. }
  1946. fallthrough
  1947. case stateHuffmanCode2:
  1948. {
  1949. var alphabet_size uint32 = numBlockLenSymbols
  1950. var tree_offset int = s.loop_counter * huffmanMaxSize26
  1951. result = readHuffmanCode(alphabet_size, alphabet_size, s.block_len_trees[tree_offset:], nil, s)
  1952. if result != decoderSuccess {
  1953. break
  1954. }
  1955. s.state = stateHuffmanCode3
  1956. }
  1957. fallthrough
  1958. case stateHuffmanCode3:
  1959. var tree_offset int = s.loop_counter * huffmanMaxSize26
  1960. if !safeReadBlockLength(s, &s.block_length[s.loop_counter], s.block_len_trees[tree_offset:], br) {
  1961. result = decoderNeedsMoreInput
  1962. break
  1963. }
  1964. s.loop_counter++
  1965. s.state = stateHuffmanCode0
  1966. case stateMetablockHeader2:
  1967. {
  1968. var bits uint32
  1969. if !safeReadBits(br, 6, &bits) {
  1970. result = decoderNeedsMoreInput
  1971. break
  1972. }
  1973. s.distance_postfix_bits = bits & bitMask(2)
  1974. bits >>= 2
  1975. s.num_direct_distance_codes = numDistanceShortCodes + (bits << s.distance_postfix_bits)
  1976. s.distance_postfix_mask = int(bitMask(s.distance_postfix_bits))
  1977. s.context_modes = make([]byte, uint(s.num_block_types[0]))
  1978. if s.context_modes == nil {
  1979. result = decoderErrorAllocContextModes
  1980. break
  1981. }
  1982. s.loop_counter = 0
  1983. s.state = stateContextModes
  1984. }
  1985. fallthrough
  1986. case stateContextModes:
  1987. result = readContextModes(s)
  1988. if result != decoderSuccess {
  1989. break
  1990. }
  1991. s.state = stateContextMap1
  1992. fallthrough
  1993. case stateContextMap1:
  1994. result = decodeContextMap(s.num_block_types[0]<<literalContextBits, &s.num_literal_htrees, &s.context_map, s)
  1995. if result != decoderSuccess {
  1996. break
  1997. }
  1998. detectTrivialLiteralBlockTypes(s)
  1999. s.state = stateContextMap2
  2000. fallthrough
  2001. case stateContextMap2:
  2002. {
  2003. var num_direct_codes uint32 = s.num_direct_distance_codes - numDistanceShortCodes
  2004. var num_distance_codes uint32
  2005. var max_distance_symbol uint32
  2006. if s.large_window {
  2007. num_distance_codes = uint32(distanceAlphabetSize(uint(s.distance_postfix_bits), uint(num_direct_codes), largeMaxDistanceBits))
  2008. max_distance_symbol = maxDistanceSymbol(num_direct_codes, s.distance_postfix_bits)
  2009. } else {
  2010. num_distance_codes = uint32(distanceAlphabetSize(uint(s.distance_postfix_bits), uint(num_direct_codes), maxDistanceBits))
  2011. max_distance_symbol = num_distance_codes
  2012. }
  2013. var allocation_success bool = true
  2014. result = decodeContextMap(s.num_block_types[2]<<distanceContextBits, &s.num_dist_htrees, &s.dist_context_map, s)
  2015. if result != decoderSuccess {
  2016. break
  2017. }
  2018. if !decoderHuffmanTreeGroupInit(s, &s.literal_hgroup, numLiteralSymbols, numLiteralSymbols, s.num_literal_htrees) {
  2019. allocation_success = false
  2020. }
  2021. if !decoderHuffmanTreeGroupInit(s, &s.insert_copy_hgroup, numCommandSymbols, numCommandSymbols, s.num_block_types[1]) {
  2022. allocation_success = false
  2023. }
  2024. if !decoderHuffmanTreeGroupInit(s, &s.distance_hgroup, num_distance_codes, max_distance_symbol, s.num_dist_htrees) {
  2025. allocation_success = false
  2026. }
  2027. if !allocation_success {
  2028. return saveErrorCode(s, decoderErrorAllocTreeGroups)
  2029. }
  2030. s.loop_counter = 0
  2031. s.state = stateTreeGroup
  2032. }
  2033. fallthrough
  2034. case stateTreeGroup:
  2035. var hgroup *huffmanTreeGroup = nil
  2036. switch s.loop_counter {
  2037. case 0:
  2038. hgroup = &s.literal_hgroup
  2039. case 1:
  2040. hgroup = &s.insert_copy_hgroup
  2041. case 2:
  2042. hgroup = &s.distance_hgroup
  2043. default:
  2044. return saveErrorCode(s, decoderErrorUnreachable)
  2045. }
  2046. result = huffmanTreeGroupDecode(hgroup, s)
  2047. if result != decoderSuccess {
  2048. break
  2049. }
  2050. s.loop_counter++
  2051. if s.loop_counter >= 3 {
  2052. prepareLiteralDecoding(s)
  2053. s.dist_context_map_slice = s.dist_context_map
  2054. s.htree_command = []huffmanCode(s.insert_copy_hgroup.htrees[0])
  2055. if !ensureRingBuffer(s) {
  2056. result = decoderErrorAllocRingBuffer2
  2057. break
  2058. }
  2059. s.state = stateCommandBegin
  2060. }
  2061. case stateCommandBegin, stateCommandInner, stateCommandPostDecodeLiterals, stateCommandPostWrapCopy:
  2062. result = processCommands(s)
  2063. if result == decoderNeedsMoreInput {
  2064. result = safeProcessCommands(s)
  2065. }
  2066. case stateCommandInnerWrite, stateCommandPostWrite1, stateCommandPostWrite2:
  2067. result = writeRingBuffer(s, available_out, next_out, nil, false)
  2068. if result != decoderSuccess {
  2069. break
  2070. }
  2071. wrapRingBuffer(s)
  2072. if s.ringbuffer_size == 1<<s.window_bits {
  2073. s.max_distance = s.max_backward_distance
  2074. }
  2075. if s.state == stateCommandPostWrite1 {
  2076. if s.meta_block_remaining_len == 0 {
  2077. /* Next metablock, if any. */
  2078. s.state = stateMetablockDone
  2079. } else {
  2080. s.state = stateCommandBegin
  2081. }
  2082. } else if s.state == stateCommandPostWrite2 {
  2083. s.state = stateCommandPostWrapCopy /* BROTLI_STATE_COMMAND_INNER_WRITE */
  2084. } else {
  2085. if s.loop_counter == 0 {
  2086. if s.meta_block_remaining_len == 0 {
  2087. s.state = stateMetablockDone
  2088. } else {
  2089. s.state = stateCommandPostDecodeLiterals
  2090. }
  2091. break
  2092. }
  2093. s.state = stateCommandInner
  2094. }
  2095. case stateMetablockDone:
  2096. if s.meta_block_remaining_len < 0 {
  2097. result = decoderErrorFormatBlockLength2
  2098. break
  2099. }
  2100. decoderStateCleanupAfterMetablock(s)
  2101. if s.is_last_metablock == 0 {
  2102. s.state = stateMetablockBegin
  2103. break
  2104. }
  2105. if !bitReaderJumpToByteBoundary(br) {
  2106. result = decoderErrorFormatPadding2
  2107. break
  2108. }
  2109. if s.buffer_length == 0 {
  2110. bitReaderUnload(br)
  2111. *available_in = br.input_len - br.byte_pos
  2112. *next_in = br.input[br.byte_pos:]
  2113. }
  2114. s.state = stateDone
  2115. fallthrough
  2116. case stateDone:
  2117. if s.ringbuffer != nil {
  2118. result = writeRingBuffer(s, available_out, next_out, nil, true)
  2119. if result != decoderSuccess {
  2120. break
  2121. }
  2122. }
  2123. return saveErrorCode(s, result)
  2124. }
  2125. }
  2126. return saveErrorCode(s, result)
  2127. }
  2128. func decoderHasMoreOutput(s *Reader) bool {
  2129. /* After unrecoverable error remaining output is considered nonsensical. */
  2130. if int(s.error_code) < 0 {
  2131. return false
  2132. }
  2133. return s.ringbuffer != nil && unwrittenBytes(s, false) != 0
  2134. }
  2135. func decoderGetErrorCode(s *Reader) int {
  2136. return int(s.error_code)
  2137. }
  2138. func decoderErrorString(c int) string {
  2139. switch c {
  2140. case decoderNoError:
  2141. return "NO_ERROR"
  2142. case decoderSuccess:
  2143. return "SUCCESS"
  2144. case decoderNeedsMoreInput:
  2145. return "NEEDS_MORE_INPUT"
  2146. case decoderNeedsMoreOutput:
  2147. return "NEEDS_MORE_OUTPUT"
  2148. case decoderErrorFormatExuberantNibble:
  2149. return "EXUBERANT_NIBBLE"
  2150. case decoderErrorFormatReserved:
  2151. return "RESERVED"
  2152. case decoderErrorFormatExuberantMetaNibble:
  2153. return "EXUBERANT_META_NIBBLE"
  2154. case decoderErrorFormatSimpleHuffmanAlphabet:
  2155. return "SIMPLE_HUFFMAN_ALPHABET"
  2156. case decoderErrorFormatSimpleHuffmanSame:
  2157. return "SIMPLE_HUFFMAN_SAME"
  2158. case decoderErrorFormatClSpace:
  2159. return "CL_SPACE"
  2160. case decoderErrorFormatHuffmanSpace:
  2161. return "HUFFMAN_SPACE"
  2162. case decoderErrorFormatContextMapRepeat:
  2163. return "CONTEXT_MAP_REPEAT"
  2164. case decoderErrorFormatBlockLength1:
  2165. return "BLOCK_LENGTH_1"
  2166. case decoderErrorFormatBlockLength2:
  2167. return "BLOCK_LENGTH_2"
  2168. case decoderErrorFormatTransform:
  2169. return "TRANSFORM"
  2170. case decoderErrorFormatDictionary:
  2171. return "DICTIONARY"
  2172. case decoderErrorFormatWindowBits:
  2173. return "WINDOW_BITS"
  2174. case decoderErrorFormatPadding1:
  2175. return "PADDING_1"
  2176. case decoderErrorFormatPadding2:
  2177. return "PADDING_2"
  2178. case decoderErrorFormatDistance:
  2179. return "DISTANCE"
  2180. case decoderErrorDictionaryNotSet:
  2181. return "DICTIONARY_NOT_SET"
  2182. case decoderErrorInvalidArguments:
  2183. return "INVALID_ARGUMENTS"
  2184. case decoderErrorAllocContextModes:
  2185. return "CONTEXT_MODES"
  2186. case decoderErrorAllocTreeGroups:
  2187. return "TREE_GROUPS"
  2188. case decoderErrorAllocContextMap:
  2189. return "CONTEXT_MAP"
  2190. case decoderErrorAllocRingBuffer1:
  2191. return "RING_BUFFER_1"
  2192. case decoderErrorAllocRingBuffer2:
  2193. return "RING_BUFFER_2"
  2194. case decoderErrorAllocBlockTypeTrees:
  2195. return "BLOCK_TYPE_TREES"
  2196. case decoderErrorUnreachable:
  2197. return "UNREACHABLE"
  2198. default:
  2199. return "INVALID"
  2200. }
  2201. }