zdeflate.pas 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117
  1. unit zdeflate;
  2. {$goto on}
  3. { Orginal: deflate.h -- internal compression state
  4. deflate.c -- compress data using the deflation algorithm
  5. Copyright (C) 1995-1996 Jean-loup Gailly.
  6. Pascal tranlastion
  7. Copyright (C) 1998 by Jacques Nomssi Nzali
  8. For conditions of distribution and use, see copyright notice in readme.txt
  9. }
  10. { ALGORITHM
  11. The "deflation" process depends on being able to identify portions
  12. of the input text which are identical to earlier input (within a
  13. sliding window trailing behind the input currently being processed).
  14. The most straightforward technique turns out to be the fastest for
  15. most input files: try all possible matches and select the longest.
  16. The key feature of this algorithm is that insertions into the string
  17. dictionary are very simple and thus fast, and deletions are avoided
  18. completely. Insertions are performed at each input character, whereas
  19. string matches are performed only when the previous match ends. So it
  20. is preferable to spend more time in matches to allow very fast string
  21. insertions and avoid deletions. The matching algorithm for small
  22. strings is inspired from that of Rabin & Karp. A brute force approach
  23. is used to find longer strings when a small match has been found.
  24. A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  25. (by Leonid Broukhis).
  26. A previous version of this file used a more sophisticated algorithm
  27. (by Fiala and Greene) which is guaranteed to run in linear amortized
  28. time, but has a larger average cost, uses more memory and is patented.
  29. However the F&G algorithm may be faster for some highly redundant
  30. files if the parameter max_chain_length (described below) is too large.
  31. ACKNOWLEDGEMENTS
  32. The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  33. I found it in 'freeze' written by Leonid Broukhis.
  34. Thanks to many people for bug reports and testing.
  35. REFERENCES
  36. Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  37. Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  38. A description of the Rabin and Karp algorithm is given in the book
  39. "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  40. Fiala,E.R., and Greene,D.H.
  41. Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595}
  42. { $Id: deflate.c,v 1.14 1996/07/02 12:40:55 me Exp $ }
  43. interface
  44. {$I zconf.inc}
  45. uses
  46. zbase;
  47. function deflateInit_(strm : z_streamp;
  48. level : integer;
  49. const version : string;
  50. stream_size : integer) : integer;
  51. function deflateInit (var strm : z_stream; level : integer) : integer;
  52. { Initializes the internal stream state for compression.
  53. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  54. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  55. all (the input data is simply copied a block at a time).
  56. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  57. compression (currently equivalent to level 6).
  58. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  59. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  60. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  61. with the version assumed by the caller (ZLIB_VERSION).
  62. msg is set to null if there is no error message. deflateInit does not
  63. perform any compression: this will be done by deflate(). }
  64. {EXPORT}
  65. function deflate (var strm : z_stream; flush : integer) : integer;
  66. { Performs one or both of the following actions:
  67. - Compress more input starting at next_in and update next_in and avail_in
  68. accordingly. If not all input can be processed (because there is not
  69. enough room in the output buffer), next_in and avail_in are updated and
  70. processing will resume at this point for the next call of deflate().
  71. - Provide more output starting at next_out and update next_out and avail_out
  72. accordingly. This action is forced if the parameter flush is non zero.
  73. Forcing flush frequently degrades the compression ratio, so this parameter
  74. should be set only when necessary (in interactive applications).
  75. Some output may be provided even if flush is not set.
  76. Before the call of deflate(), the application should ensure that at least
  77. one of the actions is possible, by providing more input and/or consuming
  78. more output, and updating avail_in or avail_out accordingly; avail_out
  79. should never be zero before the call. The application can consume the
  80. compressed output when it wants, for example when the output buffer is full
  81. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  82. and with zero avail_out, it must be called again after making room in the
  83. output buffer because there might be more output pending.
  84. If the parameter flush is set to Z_PARTIAL_FLUSH, the current compression
  85. block is terminated and flushed to the output buffer so that the
  86. decompressor can get all input data available so far. For method 9, a future
  87. variant on method 8, the current block will be flushed but not terminated.
  88. Z_SYNC_FLUSH has the same effect as partial flush except that the compressed
  89. output is byte aligned (the compressor can clear its internal bit buffer)
  90. and the current block is always terminated; this can be useful if the
  91. compressor has to be restarted from scratch after an interruption (in which
  92. case the internal state of the compressor may be lost).
  93. If flush is set to Z_FULL_FLUSH, the compression block is terminated, a
  94. special marker is output and the compression dictionary is discarded; this
  95. is useful to allow the decompressor to synchronize if one compressed block
  96. has been damaged (see inflateSync below). Flushing degrades compression and
  97. so should be used only when necessary. Using Z_FULL_FLUSH too often can
  98. seriously degrade the compression. If deflate returns with avail_out == 0,
  99. this function must be called again with the same value of the flush
  100. parameter and more output space (updated avail_out), until the flush is
  101. complete (deflate returns with non-zero avail_out).
  102. If the parameter flush is set to Z_FINISH, all pending input is processed,
  103. all pending output is flushed and deflate returns with Z_STREAM_END if there
  104. was enough output space; if deflate returns with Z_OK, this function must be
  105. called again with Z_FINISH and more output space (updated avail_out) but no
  106. more input data, until it returns with Z_STREAM_END or an error. After
  107. deflate has returned Z_STREAM_END, the only possible operations on the
  108. stream are deflateReset or deflateEnd.
  109. Z_FINISH can be used immediately after deflateInit if all the compression
  110. is to be done in a single step. In this case, avail_out must be at least
  111. 0.1% larger than avail_in plus 12 bytes. If deflate does not return
  112. Z_STREAM_END, then it must be called again as described above.
  113. deflate() may update data_type if it can make a good guess about
  114. the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
  115. binary. This field is only for information purposes and does not affect
  116. the compression algorithm in any manner.
  117. deflate() returns Z_OK if some progress has been made (more input
  118. processed or more output produced), Z_STREAM_END if all input has been
  119. consumed and all output has been produced (only when flush is set to
  120. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  121. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible. }
  122. function deflateEnd (var strm : z_stream) : integer;
  123. { All dynamically allocated data structures for this stream are freed.
  124. This function discards any unprocessed input and does not flush any
  125. pending output.
  126. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  127. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  128. prematurely (some input or output was discarded). In the error case,
  129. msg may be set but then points to a static string (which must not be
  130. deallocated). }
  131. { Advanced functions }
  132. { The following functions are needed only in some special applications. }
  133. {EXPORT}
  134. function deflateInit2 (var strm : z_stream;
  135. level : integer;
  136. method : integer;
  137. windowBits : integer;
  138. memLevel : integer;
  139. strategy : integer) : integer;
  140. function deflateInit2_(var strm : z_stream;
  141. level : integer;
  142. method : integer;
  143. windowBits : integer;
  144. memLevel : integer;
  145. strategy : integer;
  146. const version : string;
  147. stream_size : integer) : integer;
  148. { This is another version of deflateInit with more compression options. The
  149. fields next_in, and opaque must be initialized before by
  150. the caller.
  151. The method parameter is the compression method. It must be Z_DEFLATED in
  152. this version of the library. (Method 9 will allow a 64K history buffer and
  153. partial block flushes.)
  154. The windowBits parameter is the base two logarithm of the window size
  155. (the size of the history buffer). It should be in the range 8..15 for this
  156. version of the library (the value 16 will be allowed for method 9). Larger
  157. values of this parameter result in better compression at the expense of
  158. memory usage. The default value is 15 if deflateInit is used instead.
  159. The memLevel parameter specifies how much memory should be allocated
  160. for the internal compression state. memLevel=1 uses minimum memory but
  161. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  162. for optimal speed. The default value is 8. See zconf.h for total memory
  163. usage as a function of windowBits and memLevel.
  164. The strategy parameter is used to tune the compression algorithm. Use the
  165. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  166. filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
  167. string match). Filtered data consists mostly of small values with a
  168. somewhat random distribution. In this case, the compression algorithm is
  169. tuned to compress them better. The effect of Z_FILTERED is to force more
  170. Huffman coding and less string matching; it is somewhat intermediate
  171. between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
  172. the compression ratio but not the correctness of the compressed output even
  173. if it is not set appropriately.
  174. If next_in is not null, the library will use this buffer to hold also
  175. some history information; the buffer must either hold the entire input
  176. data, or have at least 1<<(windowBits+1) bytes and be writable. If next_in
  177. is null, the library will allocate its own history buffer (and leave next_in
  178. null). next_out need not be provided here but must be provided by the
  179. application for the next call of deflate().
  180. If the history buffer is provided by the application, next_in must
  181. must never be changed by the application since the compressor maintains
  182. information inside this buffer from call to call; the application
  183. must provide more input only by increasing avail_in. next_in is always
  184. reset by the library in this case.
  185. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was
  186. not enough memory, Z_STREAM_ERROR if a parameter is invalid (such as
  187. an invalid method). msg is set to null if there is no error message.
  188. deflateInit2 does not perform any compression: this will be done by
  189. deflate(). }
  190. {EXPORT}
  191. function deflateSetDictionary (var strm : z_stream;
  192. dictionary : Pbyte; {const bytes}
  193. dictLength : cardinal) : integer;
  194. { Initializes the compression dictionary (history buffer) from the given
  195. byte sequence without producing any compressed output. This function must
  196. be called immediately after deflateInit or deflateInit2, before any call
  197. of deflate. The compressor and decompressor must use exactly the same
  198. dictionary (see inflateSetDictionary).
  199. The dictionary should consist of strings (byte sequences) that are likely
  200. to be encountered later in the data to be compressed, with the most commonly
  201. used strings preferably put towards the end of the dictionary. Using a
  202. dictionary is most useful when the data to be compressed is short and
  203. can be predicted with good accuracy; the data can then be compressed better
  204. than with the default empty dictionary. In this version of the library,
  205. only the last 32K bytes of the dictionary are used.
  206. Upon return of this function, strm->adler is set to the Adler32 value
  207. of the dictionary; the decompressor may later use this value to determine
  208. which dictionary has been used by the compressor. (The Adler32 value
  209. applies to the whole dictionary even if only a subset of the dictionary is
  210. actually used by the compressor.)
  211. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  212. parameter is invalid (such as NULL dictionary) or the stream state
  213. is inconsistent (for example if deflate has already been called for this
  214. stream). deflateSetDictionary does not perform any compression: this will
  215. be done by deflate(). }
  216. {EXPORT}
  217. function deflateCopy (dest : z_streamp;
  218. source : z_streamp) : integer;
  219. { Sets the destination stream as a complete copy of the source stream. If
  220. the source stream is using an application-supplied history buffer, a new
  221. buffer is allocated for the destination stream. The compressed output
  222. buffer is always application-supplied. It's the responsibility of the
  223. application to provide the correct values of next_out and avail_out for the
  224. next call of deflate.
  225. This function can be useful when several compression strategies will be
  226. tried, for example when there are several ways of pre-processing the input
  227. data with a filter. The streams that will be discarded should then be freed
  228. by calling deflateEnd. Note that deflateCopy duplicates the internal
  229. compression state which can be quite large, so this strategy is slow and
  230. can consume lots of memory.
  231. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  232. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  233. (such as getmem returns nil). msg is left unchanged in both source and
  234. destination. }
  235. {EXPORT}
  236. function deflateReset (var strm : z_stream) : integer;
  237. { This function is equivalent to deflateEnd followed by deflateInit,
  238. but does not free and reallocate all the internal compression state.
  239. The stream will keep the same compression level and any other attributes
  240. that may have been set by deflateInit2.
  241. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  242. stream state was inconsistent (such as getmem or state being NIL). }
  243. {EXPORT}
  244. function deflateParams (var strm : z_stream; level : integer; strategy : integer) : integer;
  245. { Dynamically update the compression level and compression strategy.
  246. This can be used to switch between compression and straight copy of
  247. the input data, or to switch to a different kind of input data requiring
  248. a different strategy. If the compression level is changed, the input
  249. available so far is compressed with the old level (and may be flushed);
  250. the new level will take effect only at the next call of deflate().
  251. Before the call of deflateParams, the stream state must be set as for
  252. a call of deflate(), since the currently available input may have to
  253. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  254. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  255. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  256. if strm->avail_out was zero. }
  257. const
  258. deflate_copyright : string = ' deflate 1.1.2 Copyright 1995-1998 Jean-loup Gailly ';
  259. { If you use the zlib library in a product, an acknowledgment is welcome
  260. in the documentation of your product. If for some reason you cannot
  261. include such an acknowledgment, I would appreciate that you keep this
  262. copyright string in the executable of your product. }
  263. implementation
  264. uses
  265. trees, adler;
  266. { ===========================================================================
  267. Function prototypes. }
  268. type
  269. block_state = (
  270. need_more, { block not completed, need more input or more output }
  271. block_done, { block flush performed }
  272. finish_started, { finish started, need only more output at next deflate }
  273. finish_done); { finish done, accept no more input or output }
  274. { Compression function. Returns the block state after the call. }
  275. type
  276. compress_func = function(var s : deflate_state; flush : integer) : block_state;
  277. {local}
  278. procedure fill_window(var s : deflate_state); forward;
  279. {local}
  280. function deflate_stored(var s : deflate_state; flush : integer) : block_state; far; forward;
  281. {local}
  282. function deflate_fast(var s : deflate_state; flush : integer) : block_state; far; forward;
  283. {local}
  284. function deflate_slow(var s : deflate_state; flush : integer) : block_state; far; forward;
  285. {local}
  286. procedure lm_init(var s : deflate_state); forward;
  287. {local}
  288. procedure putShortMSB(var s : deflate_state; b : cardinal); forward;
  289. {local}
  290. procedure flush_pending (var strm : z_stream); forward;
  291. {local}
  292. function read_buf(strm : z_streamp;
  293. buf : Pbyte;
  294. size : cardinal) : cardinal; forward;
  295. {$ifdef ASMV}
  296. procedure match_init; { asm code initialization }
  297. function longest_match(var deflate_state; cur_match : IPos) : cardinal; forward;
  298. {$else}
  299. {local}
  300. function longest_match(var s : deflate_state; cur_match : IPos) : cardinal;
  301. forward;
  302. {$endif}
  303. {$ifdef ZLIB_DEBUG}
  304. {local}
  305. procedure check_match(var s : deflate_state;
  306. start, match : IPos;
  307. length : integer); forward;
  308. {$endif}
  309. { ==========================================================================
  310. local data }
  311. const
  312. ZNIL = 0;
  313. { Tail of hash chains }
  314. const
  315. TOO_FAR = 4096;
  316. { Matches of length 3 are discarded if their distance exceeds TOO_FAR }
  317. const
  318. MIN_LOOKAHEAD = (MAX_MATCH+MIN_MATCH+1);
  319. { Minimum amount of lookahead, except at the end of the input file.
  320. See deflate.c for comments about the MIN_MATCH+1. }
  321. {macro MAX_DIST(var s : deflate_state) : cardinal;
  322. begin
  323. MAX_DIST := (s.w_size - MIN_LOOKAHEAD);
  324. end;
  325. In order to simplify the code, particularly on 16 bit machines, match
  326. distances are limited to MAX_DIST instead of WSIZE. }
  327. { Values for max_lazy_match, good_match and max_chain_length, depending on
  328. the desired pack level (0..9). The values given below have been tuned to
  329. exclude worst case performance for pathological files. Better values may be
  330. found for specific files. }
  331. type
  332. config = record
  333. good_length : word; { reduce lazy search above this match length }
  334. max_lazy : word; { do not perform lazy search above this match length }
  335. nice_length : word; { quit search above this match length }
  336. max_chain : word;
  337. func : compress_func;
  338. end;
  339. {local}
  340. const
  341. configuration_table : array[0..10-1] of config = (
  342. { good lazy nice chain }
  343. {0} (good_length:0; max_lazy:0; nice_length:0; max_chain:0; func:@deflate_stored), { store only }
  344. {1} (good_length:4; max_lazy:4; nice_length:8; max_chain:4; func:@deflate_fast), { maximum speed, no lazy matches }
  345. {2} (good_length:4; max_lazy:5; nice_length:16; max_chain:8; func:@deflate_fast),
  346. {3} (good_length:4; max_lazy:6; nice_length:32; max_chain:32; func:@deflate_fast),
  347. {4} (good_length:4; max_lazy:4; nice_length:16; max_chain:16; func:@deflate_slow), { lazy matches }
  348. {5} (good_length:8; max_lazy:16; nice_length:32; max_chain:32; func:@deflate_slow),
  349. {6} (good_length:8; max_lazy:16; nice_length:128; max_chain:128; func:@deflate_slow),
  350. {7} (good_length:8; max_lazy:32; nice_length:128; max_chain:256; func:@deflate_slow),
  351. {8} (good_length:32; max_lazy:128; nice_length:258; max_chain:1024; func:@deflate_slow),
  352. {9} (good_length:32; max_lazy:258; nice_length:258; max_chain:4096; func:@deflate_slow)); { maximum compression }
  353. { Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  354. For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  355. meaning. }
  356. const
  357. EQUAL = 0;
  358. { result of memcmp for equal strings }
  359. { ==========================================================================
  360. Update a hash value with the given input byte
  361. IN assertion: all calls to to UPDATE_HASH are made with consecutive
  362. input characters, so that a running hash key can be computed from the
  363. previous key instead of complete recalculation each time.
  364. macro UPDATE_HASH(s,h,c)
  365. h := (( (h) shl s^.hash_shift) xor (c)) and s^.hash_mask;
  366. }
  367. { ===========================================================================
  368. Insert string str in the dictionary and set match_head to the previous head
  369. of the hash chain (the most recent string with same hash key). Return
  370. the previous length of the hash chain.
  371. If this file is compiled with -DFASTEST, the compression level is forced
  372. to 1, and no hash chains are maintained.
  373. IN assertion: all calls to to INSERT_STRING are made with consecutive
  374. input characters and the first MIN_MATCH bytes of str are valid
  375. (except for the last MIN_MATCH-1 bytes of the input file). }
  376. procedure INSERT_STRING(var s : deflate_state;
  377. str : cardinal;
  378. var match_head : IPos);
  379. begin
  380. {$ifdef FASTEST}
  381. {UPDATE_HASH(s, s.ins_h, s.window[(str) + (MIN_MATCH-1)])}
  382. s.ins_h := ((s.ins_h shl s.hash_shift) xor
  383. (s.window^[(str) + (MIN_MATCH-1)])) and s.hash_mask;
  384. match_head := s.head[s.ins_h]
  385. s.head[s.ins_h] := Pos(str);
  386. {$else}
  387. {UPDATE_HASH(s, s.ins_h, s.window[(str) + (MIN_MATCH-1)])}
  388. s.ins_h := ((s.ins_h shl s.hash_shift) xor
  389. (s.window^[(str) + (MIN_MATCH-1)])) and s.hash_mask;
  390. match_head := s.head^[s.ins_h];
  391. s.prev^[(str) and s.w_mask] := match_head;
  392. s.head^[s.ins_h] := Pos(str);
  393. {$endif}
  394. end;
  395. { =========================================================================
  396. Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  397. prev[] will be initialized on the fly.
  398. macro CLEAR_HASH(s)
  399. s^.head[s^.hash_size-1] := ZNIL;
  400. zmemzero(Pbyte(s^.head), cardinal(s^.hash_size-1)*sizeof(s^.head^[0]));
  401. }
  402. { ======================================================================== }
  403. function deflateInit2_(var strm : z_stream;
  404. level : integer;
  405. method : integer;
  406. windowBits : integer;
  407. memLevel : integer;
  408. strategy : integer;
  409. const version : string;
  410. stream_size : integer) : integer;
  411. var
  412. s : deflate_state_ptr;
  413. noheader : integer;
  414. overlay : Pwordarray;
  415. { We overlay pending_buf and d_buf+l_buf. This works since the average
  416. output size for (length,distance) codes is <= 24 bits. }
  417. begin
  418. noheader := 0;
  419. if (version = '') or (version[1] <> ZLIB_VERSION[1]) or
  420. (stream_size <> sizeof(z_stream)) then
  421. begin
  422. deflateInit2_ := Z_VERSION_ERROR;
  423. exit;
  424. end;
  425. {
  426. if strm=nil then
  427. begin
  428. deflateInit2_ := Z_STREAM_ERROR;
  429. exit;
  430. end;
  431. }
  432. { SetLength(strm.msg, 255); }
  433. strm.msg := '';
  434. if (level = Z_DEFAULT_COMPRESSION) then
  435. level := 6;
  436. {$ifdef FASTEST}
  437. level := 1;
  438. {$endif}
  439. if (windowBits < 0) then { undocumented feature: suppress zlib header }
  440. begin
  441. noheader := 1;
  442. windowBits := -windowBits;
  443. end;
  444. if (memLevel < 1) or (memLevel > MAX_MEM_LEVEL) or (method <> Z_DEFLATED)
  445. or (windowBits < 8) or (windowBits > 15) or (level < 0)
  446. or (level > 9) or (strategy < 0) or (strategy > Z_HUFFMAN_ONLY) then
  447. begin
  448. deflateInit2_ := Z_STREAM_ERROR;
  449. exit;
  450. end;
  451. getmem(s,sizeof(deflate_state));
  452. if (s = nil) then
  453. begin
  454. deflateInit2_ := Z_MEM_ERROR;
  455. exit;
  456. end;
  457. strm.state := pInternal_state(s);
  458. s^.strm := @strm;
  459. s^.noheader := noheader;
  460. s^.w_bits := windowBits;
  461. s^.w_size := 1 shl s^.w_bits;
  462. s^.w_mask := s^.w_size - 1;
  463. s^.hash_bits := memLevel + 7;
  464. s^.hash_size := 1 shl s^.hash_bits;
  465. s^.hash_mask := s^.hash_size - 1;
  466. s^.hash_shift := ((s^.hash_bits+MIN_MATCH-1) div MIN_MATCH);
  467. getmem(s^.window,s^.w_size*2*sizeof(byte));
  468. getmem(s^.prev,s^.w_size*sizeof(pos));
  469. getmem(s^.head,s^.hash_size*sizeof(pos));
  470. s^.lit_bufsize := 1 shl (memLevel + 6); { 16K elements by default }
  471. getmem(overlay,s^.lit_bufsize*(sizeof(word)+2));
  472. s^.pending_buf := Pbytearray(overlay);
  473. s^.pending_buf_size := longint(s^.lit_bufsize) * (sizeof(word)+longint(2));
  474. if (s^.window=nil) or (s^.prev=nil) or (s^.head=nil) or
  475. (s^.pending_buf=nil) then
  476. begin
  477. {ERR_MSG(Z_MEM_ERROR);}
  478. strm.msg := z_errmsg[z_errbase-Z_MEM_ERROR];
  479. deflateEnd (strm);
  480. deflateInit2_ := Z_MEM_ERROR;
  481. exit;
  482. end;
  483. s^.d_buf := Pwordarray( @overlay^[s^.lit_bufsize div sizeof(word)] );
  484. s^.l_buf := Pbytearray( @s^.pending_buf^[(1+sizeof(word))*s^.lit_bufsize] );
  485. s^.level := level;
  486. s^.strategy := strategy;
  487. s^.method := Byte(method);
  488. deflateInit2_ := deflateReset(strm);
  489. end;
  490. { ========================================================================= }
  491. function deflateInit2(var strm : z_stream;
  492. level : integer;
  493. method : integer;
  494. windowBits : integer;
  495. memLevel : integer;
  496. strategy : integer) : integer;
  497. { a macro }
  498. begin
  499. deflateInit2 := deflateInit2_(strm, level, method, windowBits,
  500. memLevel, strategy, ZLIB_VERSION, sizeof(z_stream));
  501. end;
  502. { ========================================================================= }
  503. function deflateInit_(strm : z_streamp;
  504. level : integer;
  505. const version : string;
  506. stream_size : integer) : integer;
  507. begin
  508. if strm=nil then
  509. deflateInit_ := Z_STREAM_ERROR
  510. else
  511. deflateInit_ := deflateInit2_(strm^, level, Z_DEFLATED, MAX_WBITS,
  512. DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, version, stream_size);
  513. { To do: ignore strm^.next_in if we use it as window }
  514. end;
  515. { ========================================================================= }
  516. function deflateInit(var strm : z_stream; level : integer) : integer;
  517. { deflateInit is a macro to allow checking the zlib version
  518. and the compiler's view of z_stream: }
  519. begin
  520. deflateInit := deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS,
  521. DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, ZLIB_VERSION, sizeof(z_stream));
  522. end;
  523. { ======================================================================== }
  524. function deflateSetDictionary (var strm : z_stream;
  525. dictionary : Pbyte;
  526. dictLength : cardinal) : integer;
  527. var
  528. s : deflate_state_ptr;
  529. length : cardinal;
  530. n : cardinal;
  531. hash_head : IPos;
  532. var
  533. MAX_DIST : cardinal; {macro}
  534. begin
  535. length := dictLength;
  536. hash_head := 0;
  537. if {(@strm=nil) or}
  538. (strm.state=nil) or (dictionary=nil)
  539. or (deflate_state_ptr(strm.state)^.status<>INIT_STATE) then
  540. begin
  541. deflateSetDictionary := Z_STREAM_ERROR;
  542. exit;
  543. end;
  544. s := deflate_state_ptr(strm.state);
  545. strm.adler := adler32(strm.adler, dictionary, dictLength);
  546. if (length < MIN_MATCH) then
  547. begin
  548. deflateSetDictionary := Z_OK;
  549. exit;
  550. end;
  551. MAX_DIST := (s^.w_size - MIN_LOOKAHEAD);
  552. if (length > MAX_DIST) then
  553. begin
  554. length := MAX_DIST;
  555. {$ifndef USE_DICT_HEAD}
  556. inc(dictionary, dictLength - length); { use the tail of the dictionary }
  557. {$endif}
  558. end;
  559. move(dictionary^,Pbyte(s^.window)^,length);
  560. s^.strstart := length;
  561. s^.block_start := longint(length);
  562. { Insert all strings in the hash table (except for the last two bytes).
  563. s^.lookahead stays null, so s^.ins_h will be recomputed at the next
  564. call of fill_window. }
  565. s^.ins_h := s^.window^[0];
  566. {UPDATE_HASH(s, s^.ins_h, s^.window[1]);}
  567. s^.ins_h := ((s^.ins_h shl s^.hash_shift) xor (s^.window^[1]))
  568. and s^.hash_mask;
  569. for n := 0 to length - MIN_MATCH do
  570. INSERT_STRING(s^, n, hash_head);
  571. {if (hash_head <> 0) then
  572. hash_head := 0; - to make compiler happy }
  573. deflateSetDictionary := Z_OK;
  574. end;
  575. { ======================================================================== }
  576. function deflateReset (var strm : z_stream) : integer;
  577. var
  578. s : deflate_state_ptr;
  579. begin
  580. if {(@strm=nil) or}
  581. (strm.state=nil) then
  582. begin
  583. deflateReset := Z_STREAM_ERROR;
  584. exit;
  585. end;
  586. strm.total_out := 0;
  587. strm.total_in := 0;
  588. strm.msg := ''; { use freemem if we ever allocate msg dynamically }
  589. strm.data_type := Z_UNKNOWN;
  590. s := deflate_state_ptr(strm.state);
  591. s^.pending := 0;
  592. s^.pending_out := Pbyte(s^.pending_buf);
  593. if (s^.noheader < 0) then
  594. begin
  595. s^.noheader := 0; { was set to -1 by deflate(..., Z_FINISH); }
  596. end;
  597. if s^.noheader <> 0 then
  598. s^.status := BUSY_STATE
  599. else
  600. s^.status := INIT_STATE;
  601. strm.adler := 1;
  602. s^.last_flush := Z_NO_FLUSH;
  603. _tr_init(s^);
  604. lm_init(s^);
  605. deflateReset := Z_OK;
  606. end;
  607. { ======================================================================== }
  608. function deflateParams(var strm : z_stream;
  609. level : integer;
  610. strategy : integer) : integer;
  611. var
  612. s : deflate_state_ptr;
  613. func : compress_func;
  614. err : integer;
  615. begin
  616. err := Z_OK;
  617. if {(@strm=nil) or} (strm.state=nil) then
  618. begin
  619. deflateParams := Z_STREAM_ERROR;
  620. exit;
  621. end;
  622. s := deflate_state_ptr(strm.state);
  623. if (level = Z_DEFAULT_COMPRESSION) then
  624. begin
  625. level := 6;
  626. end;
  627. if (level < 0) or (level > 9) or (strategy < 0)
  628. or (strategy > Z_HUFFMAN_ONLY) then
  629. begin
  630. deflateParams := Z_STREAM_ERROR;
  631. exit;
  632. end;
  633. func := configuration_table[s^.level].func;
  634. if (@func <> @configuration_table[level].func)
  635. and (strm.total_in <> 0) then
  636. begin
  637. { Flush the last buffer: }
  638. err := deflate(strm, Z_PARTIAL_FLUSH);
  639. end;
  640. if (s^.level <> level) then
  641. begin
  642. s^.level := level;
  643. s^.max_lazy_match := configuration_table[level].max_lazy;
  644. s^.good_match := configuration_table[level].good_length;
  645. s^.nice_match := configuration_table[level].nice_length;
  646. s^.max_chain_length := configuration_table[level].max_chain;
  647. end;
  648. s^.strategy := strategy;
  649. deflateParams := err;
  650. end;
  651. { =========================================================================
  652. Put a short in the pending buffer. The 16-bit value is put in MSB order.
  653. IN assertion: the stream state is correct and there is enough room in
  654. pending_buf. }
  655. {local}
  656. procedure putShortMSB (var s : deflate_state; b : cardinal);
  657. begin
  658. s.pending_buf^[s.pending] := Byte(b shr 8);
  659. inc(s.pending);
  660. s.pending_buf^[s.pending] := Byte(b and $ff);
  661. inc(s.pending);
  662. end;
  663. { =========================================================================
  664. Flush as much pending output as possible. All deflate() output goes
  665. through this function so some applications may wish to modify it
  666. to avoid allocating a large strm^.next_out buffer and copying into it.
  667. (See also read_buf()). }
  668. {local}
  669. procedure flush_pending(var strm : z_stream);
  670. var
  671. len : cardinal;
  672. s : deflate_state_ptr;
  673. begin
  674. s := deflate_state_ptr(strm.state);
  675. len := s^.pending;
  676. if (len > strm.avail_out) then
  677. len := strm.avail_out;
  678. if (len = 0) then
  679. exit;
  680. move(s^.pending_out^,strm.next_out^,len);
  681. inc(strm.next_out, len);
  682. inc(s^.pending_out, len);
  683. inc(strm.total_out, len);
  684. dec(strm.avail_out, len);
  685. dec(s^.pending, len);
  686. if (s^.pending = 0) then
  687. begin
  688. s^.pending_out := Pbyte(s^.pending_buf);
  689. end;
  690. end;
  691. { ========================================================================= }
  692. function deflate (var strm : z_stream; flush : integer) : integer;
  693. var
  694. old_flush : integer; { value of flush param for previous deflate call }
  695. s : deflate_state_ptr;
  696. var
  697. header : cardinal;
  698. level_flags : cardinal;
  699. var
  700. bstate : block_state;
  701. begin
  702. if {(@strm=nil) or} (strm.state=nil)
  703. or (flush > Z_FINISH) or (flush < 0) then
  704. begin
  705. deflate := Z_STREAM_ERROR;
  706. exit;
  707. end;
  708. s := deflate_state_ptr(strm.state);
  709. if (strm.next_out=nil) or
  710. ((strm.next_in=nil) and (strm.avail_in<>0)) or
  711. ((s^.status=FINISH_STATE) and (flush<>Z_FINISH)) then
  712. begin
  713. {ERR_RETURN(strm^, Z_STREAM_ERROR);}
  714. strm.msg := z_errmsg[z_errbase - Z_STREAM_ERROR];
  715. deflate := Z_STREAM_ERROR;
  716. exit;
  717. end;
  718. if (strm.avail_out = 0) then
  719. begin
  720. {ERR_RETURN(strm^, Z_BUF_ERROR);}
  721. strm.msg := z_errmsg[z_errbase - Z_BUF_ERROR];
  722. deflate := Z_BUF_ERROR;
  723. exit;
  724. end;
  725. s^.strm := @strm; { just in case }
  726. old_flush := s^.last_flush;
  727. s^.last_flush := flush;
  728. { Write the zlib header }
  729. if (s^.status = INIT_STATE) then
  730. begin
  731. header := (Z_DEFLATED + ((s^.w_bits-8) shl 4)) shl 8;
  732. level_flags := (s^.level-1) shr 1;
  733. if (level_flags > 3) then
  734. level_flags := 3;
  735. header := header or (level_flags shl 6);
  736. if (s^.strstart <> 0) then
  737. header := header or PRESET_DICT;
  738. inc(header, 31 - (header mod 31));
  739. s^.status := BUSY_STATE;
  740. putShortMSB(s^, header);
  741. { Save the adler32 of the preset dictionary: }
  742. if (s^.strstart <> 0) then
  743. begin
  744. putShortMSB(s^, cardinal(strm.adler shr 16));
  745. putShortMSB(s^, cardinal(strm.adler and $ffff));
  746. end;
  747. strm.adler := longint(1);
  748. end;
  749. { Flush as much pending output as possible }
  750. if (s^.pending <> 0) then
  751. begin
  752. flush_pending(strm);
  753. if (strm.avail_out = 0) then
  754. begin
  755. { Since avail_out is 0, deflate will be called again with
  756. more output space, but possibly with both pending and
  757. avail_in equal to zero. There won't be anything to do,
  758. but this is not an error situation so make sure we
  759. return OK instead of BUF_ERROR at next call of deflate: }
  760. s^.last_flush := -1;
  761. deflate := Z_OK;
  762. exit;
  763. end;
  764. { Make sure there is something to do and avoid duplicate consecutive
  765. flushes. For repeated and useless calls with Z_FINISH, we keep
  766. returning Z_STREAM_END instead of Z_BUFF_ERROR. }
  767. end
  768. else
  769. if (strm.avail_in = 0) and (flush <= old_flush)
  770. and (flush <> Z_FINISH) then
  771. begin
  772. {ERR_RETURN(strm^, Z_BUF_ERROR);}
  773. strm.msg := z_errmsg[z_errbase - Z_BUF_ERROR];
  774. deflate := Z_BUF_ERROR;
  775. exit;
  776. end;
  777. { User must not provide more input after the first FINISH: }
  778. if (s^.status = FINISH_STATE) and (strm.avail_in <> 0) then
  779. begin
  780. {ERR_RETURN(strm^, Z_BUF_ERROR);}
  781. strm.msg := z_errmsg[z_errbase - Z_BUF_ERROR];
  782. deflate := Z_BUF_ERROR;
  783. exit;
  784. end;
  785. { Start a new block or continue the current one. }
  786. if (strm.avail_in <> 0) or (s^.lookahead <> 0)
  787. or ((flush <> Z_NO_FLUSH) and (s^.status <> FINISH_STATE)) then
  788. begin
  789. bstate := configuration_table[s^.level].func(s^, flush);
  790. if (bstate = finish_started) or (bstate = finish_done) then
  791. s^.status := FINISH_STATE;
  792. if (bstate = need_more) or (bstate = finish_started) then
  793. begin
  794. if (strm.avail_out = 0) then
  795. s^.last_flush := -1; { avoid BUF_ERROR next call, see above }
  796. deflate := Z_OK;
  797. exit;
  798. { If flush != Z_NO_FLUSH && avail_out == 0, the next call
  799. of deflate should use the same flush parameter to make sure
  800. that the flush is complete. So we don't have to output an
  801. empty block here, this will be done at next call. This also
  802. ensures that for a very small output buffer, we emit at most
  803. one empty block. }
  804. end;
  805. if (bstate = block_done) then
  806. begin
  807. if (flush = Z_PARTIAL_FLUSH) then
  808. _tr_align(s^)
  809. else
  810. begin { FULL_FLUSH or SYNC_FLUSH }
  811. _tr_stored_block(s^, nil, 0, FALSE);
  812. { For a full flush, this empty block will be recognized
  813. as a special marker by inflate_sync(). }
  814. if (flush = Z_FULL_FLUSH) then
  815. begin
  816. {macro CLEAR_HASH(s);} { forget history }
  817. s^.head^[s^.hash_size-1] := ZNIL;
  818. fillchar(Pbyte(s^.head)^,cardinal(s^.hash_size-1)*sizeof(s^.head^[0]),0);
  819. end;
  820. end;
  821. flush_pending(strm);
  822. if (strm.avail_out = 0) then
  823. begin
  824. s^.last_flush := -1; { avoid BUF_ERROR at next call, see above }
  825. deflate := Z_OK;
  826. exit;
  827. end;
  828. end;
  829. end;
  830. {$IFDEF ZLIB_DEBUG}
  831. Assert(strm.avail_out > 0, 'bug2');
  832. {$ENDIF}
  833. if (flush <> Z_FINISH) then
  834. begin
  835. deflate := Z_OK;
  836. exit;
  837. end;
  838. if (s^.noheader <> 0) then
  839. begin
  840. deflate := Z_STREAM_END;
  841. exit;
  842. end;
  843. { Write the zlib trailer (adler32) }
  844. putShortMSB(s^, cardinal(strm.adler shr 16));
  845. putShortMSB(s^, cardinal(strm.adler and $ffff));
  846. flush_pending(strm);
  847. { If avail_out is zero, the application will call deflate again
  848. to flush the rest. }
  849. s^.noheader := -1; { write the trailer only once! }
  850. if s^.pending <> 0 then
  851. deflate := Z_OK
  852. else
  853. deflate := Z_STREAM_END;
  854. end;
  855. { ========================================================================= }
  856. function deflateEnd (var strm : z_stream) : integer;
  857. var
  858. status : integer;
  859. s : deflate_state_ptr;
  860. begin
  861. if {(@strm=nil) or} (strm.state=nil) then
  862. begin
  863. deflateEnd := Z_STREAM_ERROR;
  864. exit;
  865. end;
  866. s := deflate_state_ptr(strm.state);
  867. status := s^.status;
  868. if (status <> INIT_STATE) and (status <> BUSY_STATE) and
  869. (status <> FINISH_STATE) then
  870. begin
  871. deflateEnd := Z_STREAM_ERROR;
  872. exit;
  873. end;
  874. { Deallocate in reverse order of allocations: }
  875. freemem(s^.pending_buf);
  876. freemem(s^.head);
  877. freemem(s^.prev);
  878. freemem(s^.window);
  879. freemem(s);
  880. strm.state := nil;
  881. if status = BUSY_STATE then
  882. deflateEnd := Z_DATA_ERROR
  883. else
  884. deflateEnd := Z_OK;
  885. end;
  886. { =========================================================================
  887. Copy the source state to the destination state.
  888. To simplify the source, this is not supported for 16-bit MSDOS (which
  889. doesn't have enough memory anyway to duplicate compression states). }
  890. { ========================================================================= }
  891. function deflateCopy (dest, source : z_streamp) : integer;
  892. {$ifndef MAXSEG_64K}
  893. var
  894. ds : deflate_state_ptr;
  895. ss : deflate_state_ptr;
  896. overlay : Pwordarray;
  897. {$endif}
  898. begin
  899. {$ifdef MAXSEG_64K}
  900. deflateCopy := Z_STREAM_ERROR;
  901. exit;
  902. {$else}
  903. if (source=nil) or (dest=nil) or (source^.state=nil) then
  904. begin
  905. deflateCopy := Z_STREAM_ERROR;
  906. exit;
  907. end;
  908. ss := deflate_state_ptr(source^.state);
  909. dest^ := source^;
  910. getmem(ds,sizeof(deflate_state));
  911. if ds=nil then
  912. begin
  913. deflateCopy := Z_MEM_ERROR;
  914. exit;
  915. end;
  916. dest^.state := pInternal_state(ds);
  917. ds^ := ss^;
  918. ds^.strm := dest;
  919. getmem(ds^.window,ds^.w_size*2*sizeof(byte));
  920. getmem(ds^.prev,ds^.w_size*sizeof(pos));
  921. getmem(ds^.head,ds^.hash_size*sizeof(pos));
  922. getmem(overlay,ds^.lit_bufsize*(sizeof(word)+2));
  923. ds^.pending_buf := Pbytearray ( overlay );
  924. if (ds^.window=nil) or (ds^.prev=nil) or (ds^.head=nil)
  925. or (ds^.pending_buf=nil) then
  926. begin
  927. deflateEnd (dest^);
  928. deflateCopy := Z_MEM_ERROR;
  929. exit;
  930. end;
  931. move(Pbyte(ss^.window)^,Pbyte(ds^.window)^,ds^.w_size * 2 * sizeof(byte));
  932. move(Pbyte(ss^.prev)^,Pbyte(ds^.prev)^,ds^.w_size * sizeof(pos));
  933. move(Pbyte(ss^.head)^,Pbyte(ds^.head)^,ds^.hash_size * sizeof(pos));
  934. move(Pbyte(ss^.pending_buf)^,Pbyte(ds^.pending_buf)^,cardinal(ds^.pending_buf_size));
  935. ds^.pending_out := @ds^.pending_buf^[ptruint(ss^.pending_out) - ptruint(ss^.pending_buf)];
  936. ds^.d_buf := Pwordarray(@overlay^[ds^.lit_bufsize div sizeof(word)] );
  937. ds^.l_buf := Pbytearray(@ds^.pending_buf^[(1+sizeof(word))*ds^.lit_bufsize]);
  938. ds^.l_desc.dyn_tree := tree_ptr(@ds^.dyn_ltree);
  939. ds^.d_desc.dyn_tree := tree_ptr(@ds^.dyn_dtree);
  940. ds^.bl_desc.dyn_tree := tree_ptr(@ds^.bl_tree);
  941. deflateCopy := Z_OK;
  942. {$endif}
  943. end;
  944. { ===========================================================================
  945. Read a new buffer from the current input stream, update the adler32
  946. and total number of bytes read. All deflate() input goes through
  947. this function so some applications may wish to modify it to avoid
  948. allocating a large strm^.next_in buffer and copying from it.
  949. (See also flush_pending()). }
  950. {local}
  951. function read_buf(strm:z_streamp;buf:Pbyte;size:cardinal):cardinal;
  952. var len:cardinal;
  953. begin
  954. len:=strm^.avail_in;
  955. if len>size then
  956. len:=size;
  957. dec(strm^.avail_in, len);
  958. if len<>0 then
  959. begin
  960. if deflate_state_ptr(strm^.state)^.noheader=0 then
  961. strm^.adler:=adler32(strm^.adler,strm^.next_in,len);
  962. move(strm^.next_in^,buf^,len);
  963. inc(strm^.next_in,len);
  964. inc(strm^.total_in,len);
  965. end;
  966. read_buf:=len;
  967. end;
  968. { ===========================================================================
  969. Initialize the "longest match" routines for a new zlib stream }
  970. {local}
  971. procedure lm_init (var s : deflate_state);
  972. begin
  973. s.window_size := longint( 2*s.w_size);
  974. {macro CLEAR_HASH(s);}
  975. s.head^[s.hash_size-1] := ZNIL;
  976. fillchar(Pbyte(s.head)^, cardinal(s.hash_size-1)*sizeof(s.head^[0]),0);
  977. { Set the default configuration parameters: }
  978. s.max_lazy_match := configuration_table[s.level].max_lazy;
  979. s.good_match := configuration_table[s.level].good_length;
  980. s.nice_match := configuration_table[s.level].nice_length;
  981. s.max_chain_length := configuration_table[s.level].max_chain;
  982. s.strstart := 0;
  983. s.block_start := longint(0);
  984. s.lookahead := 0;
  985. s.prev_length := MIN_MATCH-1;
  986. s.match_length := MIN_MATCH-1;
  987. s.match_available := FALSE;
  988. s.ins_h := 0;
  989. {$ifdef ASMV}
  990. match_init; { initialize the asm code }
  991. {$endif}
  992. end;
  993. { ===========================================================================
  994. Set match_start to the longest match starting at the given string and
  995. return its length. Matches shorter or equal to prev_length are discarded,
  996. in which case the result is equal to prev_length and match_start is
  997. garbage.
  998. IN assertions: cur_match is the head of the hash chain for the current
  999. string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  1000. OUT assertion: the match length is not greater than s^.lookahead. }
  1001. {$ifndef ASMV}
  1002. { For 80x86 and 680x0, an optimized version will be provided in match.asm or
  1003. match.S. The code will be functionally equivalent. }
  1004. {$ifndef FASTEST}
  1005. {local}
  1006. function longest_match(var s : deflate_state;
  1007. cur_match : IPos { current match }
  1008. ) : cardinal;
  1009. label
  1010. nextstep;
  1011. var
  1012. chain_length : cardinal; { max hash chain length }
  1013. {register} scan : Pbyte; { current string }
  1014. {register} match : Pbyte; { matched string }
  1015. {register} len : integer; { length of current match }
  1016. best_len : integer; { best match length so far }
  1017. nice_match : integer; { stop if match longint enough }
  1018. limit : IPos;
  1019. prev : pzPosfArray;
  1020. wmask : cardinal;
  1021. {$ifdef UNALIGNED_OK}
  1022. {register} strend : Pbyte;
  1023. {register} scan_start : word;
  1024. {register} scan_end : word;
  1025. {$else}
  1026. {register} strend : Pbyte;
  1027. {register} scan_end1 : Byte;
  1028. {register} scan_end : Byte;
  1029. {$endif}
  1030. var
  1031. MAX_DIST : cardinal;
  1032. begin
  1033. chain_length := s.max_chain_length; { max hash chain length }
  1034. scan := @(s.window^[s.strstart]);
  1035. best_len := s.prev_length; { best match length so far }
  1036. nice_match := s.nice_match; { stop if match longint enough }
  1037. MAX_DIST := s.w_size - MIN_LOOKAHEAD;
  1038. {In order to simplify the code, particularly on 16 bit machines, match
  1039. distances are limited to MAX_DIST instead of WSIZE. }
  1040. if s.strstart > IPos(MAX_DIST) then
  1041. limit := s.strstart - IPos(MAX_DIST)
  1042. else
  1043. limit := ZNIL;
  1044. { Stop when cur_match becomes <= limit. To simplify the code,
  1045. we prevent matches with the string of window index 0. }
  1046. prev := s.prev;
  1047. wmask := s.w_mask;
  1048. {$ifdef UNALIGNED_OK}
  1049. { Compare two bytes at a time. Note: this is not always beneficial.
  1050. Try with and without -DUNALIGNED_OK to check. }
  1051. strend := Pbyte(@(s.window^[s.strstart + MAX_MATCH - 1]));
  1052. scan_start := pushf(scan)^;
  1053. scan_end := Pwordarray(scan)^[best_len-1]; { fix }
  1054. {$else}
  1055. strend := Pbyte(@(s.window^[s.strstart + MAX_MATCH]));
  1056. {$IFOPT R+} {$R-} {$DEFINE NoRangeCheck} {$ENDIF}
  1057. scan_end1 := Pbytearray(scan)^[best_len-1];
  1058. {$IFDEF NoRangeCheck} {$R+} {$UNDEF NoRangeCheck} {$ENDIF}
  1059. scan_end := Pbytearray(scan)^[best_len];
  1060. {$endif}
  1061. { The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1062. It is easy to get rid of this optimization if necessary. }
  1063. {$IFDEF ZLIB_DEBUG}
  1064. Assert((s.hash_bits >= 8) and (MAX_MATCH = 258), 'Code too clever');
  1065. {$ENDIF}
  1066. { Do not waste too much time if we already have a good match: }
  1067. if (s.prev_length >= s.good_match) then
  1068. begin
  1069. chain_length := chain_length shr 2;
  1070. end;
  1071. { Do not look for matches beyond the end of the input. This is necessary
  1072. to make deflate deterministic. }
  1073. if (cardinal(nice_match) > s.lookahead) then
  1074. nice_match := s.lookahead;
  1075. {$IFDEF ZLIB_DEBUG}
  1076. Assert(longint(s.strstart) <= s.window_size-MIN_LOOKAHEAD, 'need lookahead');
  1077. {$ENDIF}
  1078. repeat
  1079. {$IFDEF ZLIB_DEBUG}
  1080. Assert(cur_match < s.strstart, 'no future');
  1081. {$ENDIF}
  1082. match := @(s.window^[cur_match]);
  1083. { Skip to next match if the match length cannot increase
  1084. or if the match length is less than 2: }
  1085. {$undef DO_UNALIGNED_OK}
  1086. {$ifdef UNALIGNED_OK}
  1087. {$ifdef MAX_MATCH_IS_258}
  1088. {$define DO_UNALIGNED_OK}
  1089. {$endif}
  1090. {$endif}
  1091. {$ifdef DO_UNALIGNED_OK}
  1092. { This code assumes sizeof(cardinal short) = 2. Do not use
  1093. UNALIGNED_OK if your compiler uses a different size. }
  1094. {$IFOPT R+} {$R-} {$DEFINE NoRangeCheck} {$ENDIF}
  1095. if (match[best_len-1]<>scan_end) or
  1096. (match^ <> scan_start) then
  1097. goto nextstep; {continue;}
  1098. {$IFDEF NoRangeCheck} {$R+} {$UNDEF NoRangeCheck} {$ENDIF}
  1099. { It is not necessary to compare scan[2] and match[2] since they are
  1100. always equal when the other bytes match, given that the hash keys
  1101. are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  1102. strstart+3, +5, ... up to strstart+257. We check for insufficient
  1103. lookahead only every 4th comparison; the 128th check will be made
  1104. at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  1105. necessary to put more guard bytes at the end of the window, or
  1106. to check more often for insufficient lookahead. }
  1107. {$IFDEF ZLIB_DEBUG}
  1108. Assert(pzByteArray(scan)^[2] = pzByteArray(match)^[2], 'scan[2]?');
  1109. {$ENDIF}
  1110. inc(scan);
  1111. inc(match);
  1112. repeat
  1113. inc(scan,2); inc(match,2); if scan^<>match^ then break;
  1114. inc(scan,2); inc(match,2); if scan^<>match^ then break;
  1115. inc(scan,2); inc(match,2); if scan^<>match^ then break;
  1116. inc(scan,2); inc(match,2); if scan^<>match^ then break;
  1117. until ptruint(scan)>=ptruint(strend);
  1118. { The funny "do while" generates better code on most compilers }
  1119. { Here, scan <= window+strstart+257 }
  1120. {$IFDEF ZLIB_DEBUG}
  1121. {$ifopt R+} {$define RangeCheck} {$endif} {$R-}
  1122. Assert(ptruint(scan) <=
  1123. ptruint(@(s.window^[cardinal(s.window_size-1)])),
  1124. 'wild scan');
  1125. {$ifdef RangeCheck} {$R+} {$undef RangeCheck} {$endif}
  1126. {$ENDIF}
  1127. if scan^=match^ then
  1128. inc(scan);
  1129. len := (MAX_MATCH - 1) - integer(ptruint(strend)) + integer(ptruint(scan));
  1130. scan := strend;
  1131. dec(scan, (MAX_MATCH-1));
  1132. {$else} { UNALIGNED_OK }
  1133. {$IFOPT R+} {$R-} {$DEFINE NoRangeCheck} {$ENDIF}
  1134. if (Pbytearray(match)^[best_len] <> scan_end) or
  1135. (Pbytearray(match)^[best_len-1] <> scan_end1) or
  1136. (match^ <> scan^) then
  1137. goto nextstep; {continue;}
  1138. {$IFDEF NoRangeCheck} {$R+} {$UNDEF NoRangeCheck} {$ENDIF}
  1139. inc(match);
  1140. if (match^ <> Pbytearray(scan)^[1]) then
  1141. goto nextstep; {continue;}
  1142. { The check at best_len-1 can be removed because it will be made
  1143. again later. (This heuristic is not always a win.)
  1144. It is not necessary to compare scan[2] and match[2] since they
  1145. are always equal when the other bytes match, given that
  1146. the hash keys are equal and that HASH_BITS >= 8. }
  1147. inc(scan, 2);
  1148. inc(match);
  1149. {$IFDEF ZLIB_DEBUG}
  1150. Assert( scan^ = match^, 'match[2]?');
  1151. {$ENDIF}
  1152. { We check for insufficient lookahead only every 8th comparison;
  1153. the 256th check will be made at strstart+258. }
  1154. repeat
  1155. inc(scan); inc(match); if scan^ <> match^ then break;
  1156. inc(scan); inc(match); if scan^ <> match^ then break;
  1157. inc(scan); inc(match); if scan^ <> match^ then break;
  1158. inc(scan); inc(match); if scan^ <> match^ then break;
  1159. inc(scan); inc(match); if scan^ <> match^ then break;
  1160. inc(scan); inc(match); if scan^ <> match^ then break;
  1161. inc(scan); inc(match); if scan^ <> match^ then break;
  1162. inc(scan); inc(match); if scan^ <> match^ then break;
  1163. until ptruint(scan)>=ptruint(strend);
  1164. {$IFDEF ZLIB_DEBUG}
  1165. Assert(ptruint(scan) <=
  1166. ptruint(@(s.window^[cardinal(s.window_size-1)])),
  1167. 'wild scan');
  1168. {$ENDIF}
  1169. len := MAX_MATCH - (ptruint(strend) - ptruint(scan));
  1170. scan := strend;
  1171. dec(scan, MAX_MATCH);
  1172. {$endif} { UNALIGNED_OK }
  1173. if (len > best_len) then
  1174. begin
  1175. s.match_start := cur_match;
  1176. best_len := len;
  1177. if (len >= nice_match) then
  1178. break;
  1179. {$IFOPT R+} {$R-} {$DEFINE NoRangeCheck} {$ENDIF}
  1180. {$ifdef UNALIGNED_OK}
  1181. scan_end := Pbytearray(scan)^[best_len-1];
  1182. {$else}
  1183. scan_end1 := Pbytearray(scan)^[best_len-1];
  1184. scan_end := Pbytearray(scan)^[best_len];
  1185. {$endif}
  1186. {$IFDEF NoRangeCheck} {$R+} {$UNDEF NoRangeCheck} {$ENDIF}
  1187. end;
  1188. nextstep:
  1189. cur_match := prev^[cur_match and wmask];
  1190. dec(chain_length);
  1191. until (cur_match <= limit) or (chain_length = 0);
  1192. if (cardinal(best_len) <= s.lookahead) then
  1193. longest_match := cardinal(best_len)
  1194. else
  1195. longest_match := s.lookahead;
  1196. end;
  1197. {$endif} { ASMV }
  1198. {$else} { FASTEST }
  1199. { ---------------------------------------------------------------------------
  1200. Optimized version for level = 1 only }
  1201. {local}
  1202. function longest_match(var s : deflate_state;
  1203. cur_match : IPos { current match }
  1204. ) : cardinal;
  1205. var
  1206. {register} scan : Pbyte; { current string }
  1207. {register} match : Pbyte; { matched string }
  1208. {register} len : integer; { length of current match }
  1209. {register} strend : Pbyte;
  1210. begin
  1211. scan := @s.window^[s.strstart];
  1212. strend := @s.window^[s.strstart + MAX_MATCH];
  1213. { The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  1214. It is easy to get rid of this optimization if necessary. }
  1215. {$IFDEF ZLIB_DEBUG}
  1216. Assert((s.hash_bits >= 8) and (MAX_MATCH = 258), 'Code too clever');
  1217. Assert(longint(s.strstart) <= s.window_size-MIN_LOOKAHEAD, 'need lookahead');
  1218. Assert(cur_match < s.strstart, 'no future');
  1219. {$ENDIF}
  1220. match := s.window + cur_match;
  1221. { Return failure if the match length is less than 2: }
  1222. if (match[0] <> scan[0]) or (match[1] <> scan[1]) then
  1223. begin
  1224. longest_match := MIN_MATCH-1;
  1225. exit;
  1226. end;
  1227. { The check at best_len-1 can be removed because it will be made
  1228. again later. (This heuristic is not always a win.)
  1229. It is not necessary to compare scan[2] and match[2] since they
  1230. are always equal when the other bytes match, given that
  1231. the hash keys are equal and that HASH_BITS >= 8. }
  1232. scan += 2, match += 2;
  1233. Assert(scan^ = match^, 'match[2]?');
  1234. { We check for insufficient lookahead only every 8th comparison;
  1235. the 256th check will be made at strstart+258. }
  1236. repeat
  1237. inc(scan); inc(match); if scan^<>match^ then break;
  1238. inc(scan); inc(match); if scan^<>match^ then break;
  1239. inc(scan); inc(match); if scan^<>match^ then break;
  1240. inc(scan); inc(match); if scan^<>match^ then break;
  1241. inc(scan); inc(match); if scan^<>match^ then break;
  1242. inc(scan); inc(match); if scan^<>match^ then break;
  1243. inc(scan); inc(match); if scan^<>match^ then break;
  1244. inc(scan); inc(match); if scan^<>match^ then break;
  1245. until (ptruint(scan) >= ptruint(strend));
  1246. Assert(scan <= s.window+cardinal(s.window_size-1), 'wild scan');
  1247. len := MAX_MATCH - integer(strend - scan);
  1248. if (len < MIN_MATCH) then
  1249. begin
  1250. return := MIN_MATCH - 1;
  1251. exit;
  1252. end;
  1253. s.match_start := cur_match;
  1254. if len <= s.lookahead then
  1255. longest_match := len
  1256. else
  1257. longest_match := s.lookahead;
  1258. end;
  1259. {$endif} { FASTEST }
  1260. {$ifdef ZLIB_DEBUG}
  1261. { ===========================================================================
  1262. Check that the match at match_start is indeed a match. }
  1263. {local}
  1264. procedure check_match(var s : deflate_state;
  1265. start, match : IPos;
  1266. length : integer);
  1267. begin
  1268. exit;
  1269. { check that the match is indeed a match }
  1270. if (zmemcmp(Pbyte(@s.window^[match]),
  1271. Pbyte(@s.window^[start]), length) <> EQUAL) then
  1272. begin
  1273. WriteLn(' start ',start,', match ',match ,' length ', length);
  1274. repeat
  1275. Write(char(s.window^[match]), char(s.window^[start]));
  1276. inc(match);
  1277. inc(start);
  1278. dec(length);
  1279. Until (length = 0);
  1280. z_error('invalid match');
  1281. end;
  1282. if (z_verbose > 1) then
  1283. begin
  1284. Write('\\[',start-match,',',length,']');
  1285. repeat
  1286. Write(char(s.window^[start]));
  1287. inc(start);
  1288. dec(length);
  1289. Until (length = 0);
  1290. end;
  1291. end;
  1292. {$endif}
  1293. { ===========================================================================
  1294. Fill the window when the lookahead becomes insufficient.
  1295. Updates strstart and lookahead.
  1296. IN assertion: lookahead < MIN_LOOKAHEAD
  1297. OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  1298. At least one byte has been read, or avail_in = 0; reads are
  1299. performed for at least two bytes (required for the zip translate_eol
  1300. option -- not supported here). }
  1301. {local}
  1302. procedure fill_window(var s : deflate_state);
  1303. var
  1304. {register} n, m : cardinal;
  1305. {register} p : pPosf;
  1306. more : cardinal; { Amount of free space at the end of the window. }
  1307. wsize : cardinal;
  1308. begin
  1309. wsize := s.w_size;
  1310. repeat
  1311. more := cardinal(s.window_size -longint(s.lookahead) -longint(s.strstart));
  1312. { Deal with !@#$% 64K limit: }
  1313. if (more = 0) and (s.strstart = 0) and (s.lookahead = 0) then
  1314. more := wsize
  1315. else
  1316. if (more = cardinal(-1)) then
  1317. begin
  1318. { Very unlikely, but possible on 16 bit machine if strstart = 0
  1319. and lookahead = 1 (input done one byte at time) }
  1320. dec(more);
  1321. { If the window is almost full and there is insufficient lookahead,
  1322. move the upper half to the lower one to make room in the upper half.}
  1323. end
  1324. else
  1325. if (s.strstart >= wsize+ {MAX_DIST}(wsize-MIN_LOOKAHEAD)) then
  1326. begin
  1327. move(s.window^[wsize],Pbyte(s.window)^,wsize);
  1328. dec(s.match_start, wsize);
  1329. dec(s.strstart, wsize); { we now have strstart >= MAX_DIST }
  1330. dec(s.block_start, longint(wsize));
  1331. { Slide the hash table (could be avoided with 32 bit values
  1332. at the expense of memory usage). We slide even when level = 0
  1333. to keep the hash table consistent if we switch back to level > 0
  1334. later. (Using level 0 permanently is not an optimal usage of
  1335. zlib, so we don't care about this pathological case.) }
  1336. n := s.hash_size;
  1337. p := @s.head^[n];
  1338. repeat
  1339. dec(p);
  1340. m := p^;
  1341. if (m >= wsize) then
  1342. p^ := Pos(m-wsize)
  1343. else
  1344. p^ := Pos(ZNIL);
  1345. dec(n);
  1346. Until (n=0);
  1347. n := wsize;
  1348. {$ifndef FASTEST}
  1349. p := @s.prev^[n];
  1350. repeat
  1351. dec(p);
  1352. m := p^;
  1353. if (m >= wsize) then
  1354. p^ := Pos(m-wsize)
  1355. else
  1356. p^:= Pos(ZNIL);
  1357. { If n is not on any hash chain, prev^[n] is garbage but
  1358. its value will never be used. }
  1359. dec(n);
  1360. Until (n=0);
  1361. {$endif}
  1362. inc(more, wsize);
  1363. end;
  1364. if (s.strm^.avail_in = 0) then
  1365. exit;
  1366. {* If there was no sliding:
  1367. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  1368. * more == window_size - lookahead - strstart
  1369. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  1370. * => more >= window_size - 2*WSIZE + 2
  1371. * In the BIG_MEM or MMAP case (not yet supported),
  1372. * window_size == input_size + MIN_LOOKAHEAD &&
  1373. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  1374. * Otherwise, window_size == 2*WSIZE so more >= 2.
  1375. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. }
  1376. {$IFDEF ZLIB_DEBUG}
  1377. Assert(more >= 2, 'more < 2');
  1378. {$ENDIF}
  1379. n := read_buf(s.strm, Pbyte(@(s.window^[s.strstart + s.lookahead])),
  1380. more);
  1381. inc(s.lookahead, n);
  1382. { Initialize the hash value now that we have some input: }
  1383. if (s.lookahead >= MIN_MATCH) then
  1384. begin
  1385. s.ins_h := s.window^[s.strstart];
  1386. {UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]);}
  1387. s.ins_h := ((s.ins_h shl s.hash_shift) xor s.window^[s.strstart+1])
  1388. and s.hash_mask;
  1389. {$ifdef MIN_MATCH <> 3}
  1390. Call UPDATE_HASH() MIN_MATCH-3 more times
  1391. {$endif}
  1392. end;
  1393. { If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  1394. but this is not important since only literal bytes will be emitted. }
  1395. until (s.lookahead >= MIN_LOOKAHEAD) or (s.strm^.avail_in = 0);
  1396. end;
  1397. { ===========================================================================
  1398. Flush the current block, with given end-of-file flag.
  1399. IN assertion: strstart is set to the end of the current match. }
  1400. procedure FLUSH_BLOCK_ONLY(var s : deflate_state; eof : boolean); {macro}
  1401. begin
  1402. if (s.block_start >= 0) then
  1403. _tr_flush_block(s, Pbyte(@s.window^[s.block_start]),
  1404. longint(longint(s.strstart) - s.block_start), eof)
  1405. else
  1406. _tr_flush_block(s, nil,
  1407. longint(longint(s.strstart) - s.block_start), eof);
  1408. s.block_start := s.strstart;
  1409. flush_pending(s.strm^);
  1410. {$IFDEF ZLIB_DEBUG}
  1411. Tracev('[FLUSH]');
  1412. {$ENDIF}
  1413. end;
  1414. { Same but force premature exit if necessary.
  1415. macro FLUSH_BLOCK(var s : deflate_state; eof : boolean) : boolean;
  1416. var
  1417. result : block_state;
  1418. begin
  1419. FLUSH_BLOCK_ONLY(s, eof);
  1420. if (s.strm^.avail_out = 0) then
  1421. begin
  1422. if eof then
  1423. result := finish_started
  1424. else
  1425. result := need_more;
  1426. exit;
  1427. end;
  1428. end;
  1429. }
  1430. { ===========================================================================
  1431. Copy without compression as much as possible from the input stream, return
  1432. the current block state.
  1433. This function does not insert new strings in the dictionary since
  1434. uncompressible data is probably not useful. This function is used
  1435. only for the level=0 compression option.
  1436. NOTE: this function should be optimized to avoid extra copying from
  1437. window to pending_buf. }
  1438. {local}
  1439. function deflate_stored(var s : deflate_state; flush : integer) : block_state;
  1440. { Stored blocks are limited to 0xffff bytes, pending_buf is limited
  1441. to pending_buf_size, and each stored block has a 5 byte header: }
  1442. var
  1443. max_block_size : longint;
  1444. max_start : longint;
  1445. begin
  1446. max_block_size := $ffff;
  1447. if (max_block_size > s.pending_buf_size - 5) then
  1448. max_block_size := s.pending_buf_size - 5;
  1449. { Copy as much as possible from input to output: }
  1450. while TRUE do
  1451. begin
  1452. { Fill the window as much as possible: }
  1453. if (s.lookahead <= 1) then
  1454. begin
  1455. {$IFDEF ZLIB_DEBUG}
  1456. Assert( (s.strstart < s.w_size + {MAX_DIST}s.w_size-MIN_LOOKAHEAD) or
  1457. (s.block_start >= longint(s.w_size)), 'slide too late');
  1458. {$ENDIF}
  1459. fill_window(s);
  1460. if (s.lookahead = 0) and (flush = Z_NO_FLUSH) then
  1461. begin
  1462. deflate_stored := need_more;
  1463. exit;
  1464. end;
  1465. if (s.lookahead = 0) then
  1466. break; { flush the current block }
  1467. end;
  1468. {$IFDEF ZLIB_DEBUG}
  1469. Assert(s.block_start >= 0, 'block gone');
  1470. {$ENDIF}
  1471. inc(s.strstart, s.lookahead);
  1472. s.lookahead := 0;
  1473. { Emit a stored block if pending_buf will be full: }
  1474. max_start := s.block_start + max_block_size;
  1475. if (s.strstart = 0) or (longint(s.strstart) >= max_start) then
  1476. begin
  1477. { strstart = 0 is possible when wraparound on 16-bit machine }
  1478. s.lookahead := cardinal(s.strstart) - cardinal(max_start);
  1479. s.strstart := cardinal(max_start);
  1480. {FLUSH_BLOCK(s, FALSE);}
  1481. FLUSH_BLOCK_ONLY(s, FALSE);
  1482. if (s.strm^.avail_out = 0) then
  1483. begin
  1484. deflate_stored := need_more;
  1485. exit;
  1486. end;
  1487. end;
  1488. { Flush if we may have to slide, otherwise block_start may become
  1489. negative and the data will be gone: }
  1490. if (s.strstart - cardinal(s.block_start) >= {MAX_DIST}
  1491. s.w_size-MIN_LOOKAHEAD) then
  1492. begin
  1493. {FLUSH_BLOCK(s, FALSE);}
  1494. FLUSH_BLOCK_ONLY(s, FALSE);
  1495. if (s.strm^.avail_out = 0) then
  1496. begin
  1497. deflate_stored := need_more;
  1498. exit;
  1499. end;
  1500. end;
  1501. end;
  1502. {FLUSH_BLOCK(s, flush = Z_FINISH);}
  1503. FLUSH_BLOCK_ONLY(s, flush = Z_FINISH);
  1504. if (s.strm^.avail_out = 0) then
  1505. begin
  1506. if flush = Z_FINISH then
  1507. deflate_stored := finish_started
  1508. else
  1509. deflate_stored := need_more;
  1510. exit;
  1511. end;
  1512. if flush = Z_FINISH then
  1513. deflate_stored := finish_done
  1514. else
  1515. deflate_stored := block_done;
  1516. end;
  1517. { ===========================================================================
  1518. Compress as much as possible from the input stream, return the current
  1519. block state.
  1520. This function does not perform lazy evaluation of matches and inserts
  1521. new strings in the dictionary only for unmatched strings or for short
  1522. matches. It is used only for the fast compression options. }
  1523. {local}
  1524. function deflate_fast(var s : deflate_state; flush : integer) : block_state;
  1525. var
  1526. hash_head : IPos; { head of the hash chain }
  1527. bflush : boolean; { set if current block must be flushed }
  1528. begin
  1529. hash_head := ZNIL;
  1530. while TRUE do
  1531. begin
  1532. { Make sure that we always have enough lookahead, except
  1533. at the end of the input file. We need MAX_MATCH bytes
  1534. for the next match, plus MIN_MATCH bytes to insert the
  1535. string following the next match. }
  1536. if (s.lookahead < MIN_LOOKAHEAD) then
  1537. begin
  1538. fill_window(s);
  1539. if (s.lookahead < MIN_LOOKAHEAD) and (flush = Z_NO_FLUSH) then
  1540. begin
  1541. deflate_fast := need_more;
  1542. exit;
  1543. end;
  1544. if (s.lookahead = 0) then
  1545. break; { flush the current block }
  1546. end;
  1547. { Insert the string window[strstart .. strstart+2] in the
  1548. dictionary, and set hash_head to the head of the hash chain: }
  1549. if (s.lookahead >= MIN_MATCH) then
  1550. INSERT_STRING(s, s.strstart, hash_head);
  1551. { Find the longest match, discarding those <= prev_length.
  1552. At this point we have always match_length < MIN_MATCH }
  1553. if (hash_head <> ZNIL) and
  1554. (s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD){MAX_DIST}) then
  1555. begin
  1556. { To simplify the code, we prevent matches with the string
  1557. of window index 0 (in particular we have to avoid a match
  1558. of the string with itself at the start of the input file). }
  1559. if (s.strategy <> Z_HUFFMAN_ONLY) then
  1560. begin
  1561. s.match_length := longest_match (s, hash_head);
  1562. end;
  1563. { longest_match() sets match_start }
  1564. end;
  1565. if (s.match_length >= MIN_MATCH) then
  1566. begin
  1567. {$IFDEF ZLIB_DEBUG}
  1568. check_match(s, s.strstart, s.match_start, s.match_length);
  1569. {$ENDIF}
  1570. {_tr_tally_dist(s, s.strstart - s.match_start,
  1571. s.match_length - MIN_MATCH, bflush);}
  1572. bflush := _tr_tally(s, s.strstart - s.match_start,
  1573. s.match_length - MIN_MATCH);
  1574. dec(s.lookahead, s.match_length);
  1575. { Insert new strings in the hash table only if the match length
  1576. is not too large. This saves time but degrades compression. }
  1577. {$ifndef FASTEST}
  1578. if (s.match_length <= s.max_insert_length)
  1579. and (s.lookahead >= MIN_MATCH) then
  1580. begin
  1581. dec(s.match_length); { string at strstart already in hash table }
  1582. repeat
  1583. inc(s.strstart);
  1584. INSERT_STRING(s, s.strstart, hash_head);
  1585. { strstart never exceeds WSIZE-MAX_MATCH, so there are
  1586. always MIN_MATCH bytes ahead. }
  1587. dec(s.match_length);
  1588. until (s.match_length = 0);
  1589. inc(s.strstart);
  1590. end
  1591. else
  1592. {$endif}
  1593. begin
  1594. inc(s.strstart, s.match_length);
  1595. s.match_length := 0;
  1596. s.ins_h := s.window^[s.strstart];
  1597. {UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]);}
  1598. s.ins_h := (( s.ins_h shl s.hash_shift) xor
  1599. s.window^[s.strstart+1]) and s.hash_mask;
  1600. if MIN_MATCH <> 3 then { the linker removes this }
  1601. begin
  1602. {Call UPDATE_HASH() MIN_MATCH-3 more times}
  1603. end;
  1604. { If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  1605. matter since it will be recomputed at next deflate call. }
  1606. end;
  1607. end
  1608. else
  1609. begin
  1610. { No match, output a literal byte }
  1611. {$IFDEF ZLIB_DEBUG}
  1612. Tracevv(char(s.window^[s.strstart]));
  1613. {$ENDIF}
  1614. {_tr_tally_lit (s, 0, s.window^[s.strstart], bflush);}
  1615. bflush := _tr_tally (s, 0, s.window^[s.strstart]);
  1616. dec(s.lookahead);
  1617. inc(s.strstart);
  1618. end;
  1619. if bflush then
  1620. begin {FLUSH_BLOCK(s, FALSE);}
  1621. FLUSH_BLOCK_ONLY(s, FALSE);
  1622. if (s.strm^.avail_out = 0) then
  1623. begin
  1624. deflate_fast := need_more;
  1625. exit;
  1626. end;
  1627. end;
  1628. end;
  1629. {FLUSH_BLOCK(s, flush = Z_FINISH);}
  1630. FLUSH_BLOCK_ONLY(s, flush = Z_FINISH);
  1631. if (s.strm^.avail_out = 0) then
  1632. begin
  1633. if flush = Z_FINISH then
  1634. deflate_fast := finish_started
  1635. else
  1636. deflate_fast := need_more;
  1637. exit;
  1638. end;
  1639. if flush = Z_FINISH then
  1640. deflate_fast := finish_done
  1641. else
  1642. deflate_fast := block_done;
  1643. end;
  1644. { ===========================================================================
  1645. Same as above, but achieves better compression. We use a lazy
  1646. evaluation for matches: a match is finally adopted only if there is
  1647. no better match at the next window position. }
  1648. {local}
  1649. function deflate_slow(var s : deflate_state; flush : integer) : block_state;
  1650. var
  1651. hash_head : IPos; { head of hash chain }
  1652. bflush : boolean; { set if current block must be flushed }
  1653. var
  1654. max_insert : cardinal;
  1655. begin
  1656. hash_head := ZNIL;
  1657. { Process the input block. }
  1658. repeat
  1659. { Make sure that we always have enough lookahead, except
  1660. at the end of the input file. We need MAX_MATCH bytes
  1661. for the next match, plus MIN_MATCH bytes to insert the
  1662. string following the next match. }
  1663. if (s.lookahead < MIN_LOOKAHEAD) then
  1664. begin
  1665. fill_window(s);
  1666. if (s.lookahead < MIN_LOOKAHEAD) and (flush = Z_NO_FLUSH) then
  1667. begin
  1668. deflate_slow := need_more;
  1669. exit;
  1670. end;
  1671. if s.lookahead=0 then
  1672. break; { flush the current block }
  1673. end;
  1674. { Insert the string window[strstart .. strstart+2] in the
  1675. dictionary, and set hash_head to the head of the hash chain: }
  1676. if (s.lookahead >= MIN_MATCH) then
  1677. INSERT_STRING(s, s.strstart, hash_head);
  1678. { Find the longest match, discarding those <= prev_length. }
  1679. s.prev_length := s.match_length;
  1680. s.prev_match := s.match_start;
  1681. s.match_length := MIN_MATCH-1;
  1682. if (hash_head <> ZNIL) and (s.prev_length < s.max_lazy_match) and
  1683. (s.strstart - hash_head <= {MAX_DIST}(s.w_size-MIN_LOOKAHEAD)) then
  1684. begin
  1685. { To simplify the code, we prevent matches with the string
  1686. of window index 0 (in particular we have to avoid a match
  1687. of the string with itself at the start of the input file). }
  1688. if (s.strategy <> Z_HUFFMAN_ONLY) then
  1689. s.match_length := longest_match (s, hash_head);
  1690. { longest_match() sets match_start }
  1691. if (s.match_length <= 5) and ((s.strategy = Z_FILTERED) or
  1692. ((s.match_length = MIN_MATCH) and
  1693. (s.strstart - s.match_start > TOO_FAR))) then
  1694. begin
  1695. { If prev_match is also MIN_MATCH, match_start is garbage
  1696. but we will ignore the current match anyway. }
  1697. s.match_length := MIN_MATCH-1;
  1698. end;
  1699. end;
  1700. { If there was a match at the previous step and the current
  1701. match is not better, output the previous match: }
  1702. if (s.prev_length>=MIN_MATCH) and (s.match_length<=s.prev_length) then
  1703. begin
  1704. max_insert := s.strstart + s.lookahead - MIN_MATCH;
  1705. { Do not insert strings in hash table beyond this. }
  1706. {$ifdef ZLIB_DEBUG}
  1707. check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  1708. {$endif}
  1709. {_tr_tally_dist(s, s->strstart -1 - s->prev_match,
  1710. s->prev_length - MIN_MATCH, bflush);}
  1711. bflush := _tr_tally(s, s.strstart -1 - s.prev_match,
  1712. s.prev_length - MIN_MATCH);
  1713. { Insert in hash table all strings up to the end of the match.
  1714. strstart-1 and strstart are already inserted. If there is not
  1715. enough lookahead, the last two strings are not inserted in
  1716. the hash table. }
  1717. {$ifdef ZLIB_DEBUG}
  1718. if s.lookahead<s.prev_length-1 then
  1719. runerror(255);
  1720. {$endif}
  1721. dec(s.lookahead, s.prev_length-1);
  1722. dec(s.prev_length, 2);
  1723. repeat
  1724. inc(s.strstart);
  1725. if s.strstart<=max_insert then
  1726. INSERT_STRING(s, s.strstart, hash_head);
  1727. dec(s.prev_length);
  1728. until s.prev_length = 0;
  1729. s.match_available := false;
  1730. s.match_length := MIN_MATCH-1;
  1731. inc(s.strstart);
  1732. if bflush then {FLUSH_BLOCK(s, FALSE);}
  1733. begin
  1734. FLUSH_BLOCK_ONLY(s,false);
  1735. if s.strm^.avail_out=0 then
  1736. begin
  1737. deflate_slow := need_more;
  1738. exit;
  1739. end;
  1740. end;
  1741. end
  1742. else
  1743. if s.match_available then
  1744. begin
  1745. { If there was no match at the previous position, output a
  1746. single literal. If there was a match but the current match
  1747. is longer, truncate the previous match to a single literal. }
  1748. {$IFDEF ZLIB_DEBUG}
  1749. Tracevv(char(s.window^[s.strstart-1]));
  1750. {$ENDIF}
  1751. bflush := _tr_tally (s, 0, s.window^[s.strstart-1]);
  1752. if bflush then
  1753. FLUSH_BLOCK_ONLY(s, FALSE);
  1754. inc(s.strstart);
  1755. {$ifdef ZLIB_DEBUG}
  1756. if s.lookahead=0 then
  1757. runerror(255);
  1758. {$endif}
  1759. dec(s.lookahead);
  1760. if (s.strm^.avail_out = 0) then
  1761. begin
  1762. deflate_slow := need_more;
  1763. exit;
  1764. end;
  1765. end
  1766. else
  1767. begin
  1768. { There is no previous match to compare with, wait for
  1769. the next step to decide. }
  1770. s.match_available := TRUE;
  1771. inc(s.strstart);
  1772. {$ifdef ZLIB_DEBUG}
  1773. if s.lookahead=0 then
  1774. runerror(255);
  1775. {$endif}
  1776. dec(s.lookahead);
  1777. end;
  1778. until false;
  1779. {$IFDEF ZLIB_DEBUG}
  1780. Assert (flush <> Z_NO_FLUSH, 'no flush?');
  1781. {$ENDIF}
  1782. if (s.match_available) then
  1783. begin
  1784. {$IFDEF ZLIB_DEBUG}
  1785. Tracevv(char(s.window^[s.strstart-1]));
  1786. bflush :=
  1787. {$ENDIF}
  1788. _tr_tally (s, 0, s.window^[s.strstart-1]);
  1789. s.match_available := FALSE;
  1790. end;
  1791. {FLUSH_BLOCK(s, flush = Z_FINISH);}
  1792. FLUSH_BLOCK_ONLY(s, flush = Z_FINISH);
  1793. if (s.strm^.avail_out = 0) then
  1794. begin
  1795. if flush = Z_FINISH then
  1796. deflate_slow := finish_started
  1797. else
  1798. deflate_slow := need_more;
  1799. exit;
  1800. end;
  1801. if flush = Z_FINISH then
  1802. deflate_slow := finish_done
  1803. else
  1804. deflate_slow := block_done;
  1805. end;
  1806. end.