Repo for the search and displace ingest module that takes odf, docx and pdf and transforms it into .md to be used with search and displace operations
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2129 lines
71 KiB

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