Debian Codegraph @

src/org/tukaani/xz/lz/LZEncoder.java

raw symbols SCIP
1 // SPDX-License-Identifier: 0BSD
2 // SPDX-FileCopyrightText: The XZ for Java authors and contributors
3 // SPDX-FileContributor: Lasse Collin <[email protected]>
4 // SPDX-FileContributor: Igor Pavlov <https://7-zip.org/>
5
6 package org.tukaani.xz.lz;
7
8 import java.io.OutputStream;
9 import java.io.IOException;
10 import org.tukaani.xz.ArrayCache;
11
12 public abstract class LZEncoder {
13 public static final int MF_HC4 = 0x04;
14 public static final int MF_BT4 = 0x14;
15
16 /**
17 * Number of bytes to keep available before the current byte
18 * when moving the LZ window.
19 */
20 private final int keepSizeBefore;
21
22 /**
23 * Number of bytes that must be available, the current byte included,
24 * to make hasEnoughData return true. Flushing and finishing are
25 * naturally exceptions to this since there cannot be any data after
26 * the end of the uncompressed input.
27 */
28 private final int keepSizeAfter;
29
30 final int matchLenMax;
31 final int niceLen;
32
33 final byte[] buf;
34 final int bufSize; // To avoid buf.length with an array-cached buf.
35
36 int readPos = -1;
37 private int readLimit = -1;
38 private boolean finishing = false;
39 private int writePos = 0;
40 private int pendingSize = 0;
41
42 static void normalize(int[] positions, int positionsCount,
43 int normalizationOffset) {
44 for (int i = 0; i < positionsCount; ++i) {
45 if (positions[i] <= normalizationOffset)
46 positions[i] = 0;
47 else
48 positions[i] -= normalizationOffset;
49 }
50 }
51
52 /**
53 * Gets the size of the LZ window buffer that needs to be allocated.
54 */
55 private static int getBufSize(
56 int dictSize, int extraSizeBefore, int extraSizeAfter,
57 int matchLenMax) {
58 int keepSizeBefore = extraSizeBefore + dictSize;
59 int keepSizeAfter = extraSizeAfter + matchLenMax;
60 int reserveSize = Math.min(dictSize / 2 + (256 << 10), 512 << 20);
61 return keepSizeBefore + keepSizeAfter + reserveSize;
62 }
63
64 /**
65 * Gets approximate memory usage of the LZEncoder base structure and
66 * the match finder as kibibytes.
67 */
68 public static int getMemoryUsage(
69 int dictSize, int extraSizeBefore, int extraSizeAfter,
70 int matchLenMax, int mf) {
71 // Buffer size + a little extra
72 int m = getBufSize(dictSize, extraSizeBefore, extraSizeAfter,
73 matchLenMax) / 1024 + 10;
74
75 switch (mf) {
76 case MF_HC4:
77 m += HC4.getMemoryUsage(dictSize);
78 break;
79
80 case MF_BT4:
81 m += BT4.getMemoryUsage(dictSize);
82 break;
83
84 default:
85 throw new IllegalArgumentException();
86 }
87
88 return m;
89 }
90
91 /**
92 * Creates a new LZEncoder.
93 * <p>
94 * @param dictSize dictionary size
95 *
96 * @param extraSizeBefore
97 * number of bytes to keep available in the
98 * history in addition to dictSize
99 *
100 * @param extraSizeAfter
101 * number of bytes that must be available
102 * after current position + matchLenMax
103 *
104 * @param niceLen if a match of at least {@code niceLen}
105 * bytes is found, be happy with it and
106 * stop looking for longer matches
107 *
108 * @param matchLenMax don't test for matches longer than
109 * {@code matchLenMax} bytes
110 *
111 * @param mf match finder ID
112 *
113 * @param depthLimit match finder search depth limit
114 */
115 public static LZEncoder getInstance(
116 int dictSize, int extraSizeBefore, int extraSizeAfter,
117 int niceLen, int matchLenMax, int mf, int depthLimit,
118 ArrayCache arrayCache) {
119 switch (mf) {
120 case MF_HC4:
121 return new HC4(dictSize, extraSizeBefore, extraSizeAfter,
122 niceLen, matchLenMax, depthLimit, arrayCache);
123
124 case MF_BT4:
125 return new BT4(dictSize, extraSizeBefore, extraSizeAfter,
126 niceLen, matchLenMax, depthLimit, arrayCache);
127 }
128
129 throw new IllegalArgumentException();
130 }
131
132 /**
133 * Creates a new LZEncoder. See {@code getInstance}.
134 */
135 LZEncoder(int dictSize, int extraSizeBefore, int extraSizeAfter,
136 int niceLen, int matchLenMax, ArrayCache arrayCache) {
137 bufSize = getBufSize(dictSize, extraSizeBefore, extraSizeAfter,
138 matchLenMax);
139
140 // MatchLength.getLen might read and ignore extra bytes
141 // at the end of the buffer.
142 buf = arrayCache.getByteArray(bufSize + MatchLength.EXTRA_SIZE, false);
143
144 keepSizeBefore = extraSizeBefore + dictSize;
145 keepSizeAfter = extraSizeAfter + matchLenMax;
146
147 this.matchLenMax = matchLenMax;
148 this.niceLen = niceLen;
149 }
150
151 public void putArraysToCache(ArrayCache arrayCache) {
152 arrayCache.putArray(buf);
153 }
154
155 /**
156 * Sets a preset dictionary. If a preset dictionary is wanted, this
157 * function must be called immediately after creating the LZEncoder
158 * before any data has been encoded.
159 */
160 public void setPresetDict(int dictSize, byte[] presetDict) {
161 assert !isStarted();
162 assert writePos == 0;
163
164 if (presetDict != null) {
165 // If the preset dictionary buffer is bigger than the dictionary
166 // size, copy only the tail of the preset dictionary.
167 int copySize = Math.min(presetDict.length, dictSize);
168 int offset = presetDict.length - copySize;
169 System.arraycopy(presetDict, offset, buf, 0, copySize);
170 writePos += copySize;
171 skip(copySize);
172 }
173 }
174
175 /**
176 * Moves data from the end of the buffer to the beginning, discarding
177 * old data and making space for new input.
178 */
179 private void moveWindow() {
180 // Align the move to a multiple of 16 bytes. LZMA2 needs this
181 // because it uses the lowest bits from readPos to get the
182 // alignment of the uncompressed data.
183 int moveOffset = (readPos + 1 - keepSizeBefore) & ~15;
184 int moveSize = writePos - moveOffset;
185 System.arraycopy(buf, moveOffset, buf, 0, moveSize);
186
187 readPos -= moveOffset;
188 readLimit -= moveOffset;
189 writePos -= moveOffset;
190 }
191
192 /**
193 * Copies new data into the LZEncoder's buffer.
194 */
195 public int fillWindow(byte[] in, int off, int len) {
196 assert !finishing;
197
198 // Move the sliding window if needed.
199 if (readPos >= bufSize - keepSizeAfter)
200 moveWindow();
201
202 // Try to fill the dictionary buffer. If it becomes full,
203 // some of the input bytes may be left unused.
204 if (len > bufSize - writePos)
205 len = bufSize - writePos;
206
207 System.arraycopy(in, off, buf, writePos, len);
208 writePos += len;
209
210 // Set the new readLimit but only if there's enough data to allow
211 // encoding of at least one more byte.
212 if (writePos >= keepSizeAfter)
213 readLimit = writePos - keepSizeAfter;
214
215 processPendingBytes();
216
217 // Tell the caller how much input we actually copied into
218 // the dictionary.
219 return len;
220 }
221
222 /**
223 * Process pending bytes remaining from preset dictionary initialization
224 * or encoder flush operation.
225 */
226 private void processPendingBytes() {
227 // After flushing or setting a preset dictionary there will be
228 // pending data that hasn't been ran through the match finder yet.
229 // Run it through the match finder now if there is enough new data
230 // available (readPos < readLimit) that the encoder may encode at
231 // least one more input byte. This way we don't waste any time
232 // looping in the match finder (and marking the same bytes as
233 // pending again) if the application provides very little new data
234 // per write call.
235 if (pendingSize > 0 && readPos < readLimit) {
236 readPos -= pendingSize;
237 int oldPendingSize = pendingSize;
238 pendingSize = 0;
239 skip(oldPendingSize);
240 assert pendingSize < oldPendingSize;
241 }
242 }
243
244 /**
245 * Returns true if at least one byte has already been run through
246 * the match finder.
247 */
248 public boolean isStarted() {
249 return readPos != -1;
250 }
251
252 /**
253 * Marks that all the input needs to be made available in
254 * the encoded output.
255 */
256 public void setFlushing() {
257 readLimit = writePos - 1;
258 processPendingBytes();
259 }
260
261 /**
262 * Marks that there is no more input remaining. The read position
263 * can be advanced until the end of the data.
264 */
265 public void setFinishing() {
266 readLimit = writePos - 1;
267 finishing = true;
268 processPendingBytes();
269 }
270
271 /**
272 * Tests if there is enough input available to let the caller encode
273 * at least one more byte.
274 */
275 public boolean hasEnoughData(int alreadyReadLen) {
276 return readPos - alreadyReadLen < readLimit;
277 }
278
279 public void copyUncompressed(OutputStream out, int backward, int len)
280 throws IOException {
281 out.write(buf, readPos + 1 - backward, len);
282 }
283
284 /**
285 * Get the number of bytes available, including the current byte.
286 * <p>
287 * Note that the result is undefined if {@code getMatches} or
288 * {@code skip} hasn't been called yet and no preset dictionary
289 * is being used.
290 */
291 public int getAvail() {
292 assert isStarted();
293 return writePos - readPos;
294 }
295
296 /**
297 * Gets the lowest four bits of the absolute offset of the current byte.
298 * Bits other than the lowest four are undefined.
299 */
300 public int getPos() {
301 return readPos;
302 }
303
304 /**
305 * Gets the byte from the given backward offset.
306 * <p>
307 * The current byte is at {@code 0}, the previous byte
308 * at {@code 1} etc. To get a byte at zero-based distance,
309 * use {@code getByte(dist + 1)}.
310 * <p>
311 * This function is equivalent to {@code getByte(0, backward)}.
312 */
313 public int getByte(int backward) {
314 return buf[readPos - backward] & 0xFF;
315 }
316
317 /**
318 * Gets the byte from the given forward minus backward offset.
319 * The forward offset is added to the current position. This lets
320 * one read bytes ahead of the current byte.
321 */
322 public int getByte(int forward, int backward) {
323 return buf[readPos + forward - backward] & 0xFF;
324 }
325
326 /**
327 * Get the length of a match at the given distance.
328 *
329 * @param dist zero-based distance of the match to test
330 * @param lenLimit don't test for a match longer than this
331 *
332 * @return length of the match; it is in the range [0, lenLimit]
333 */
334 public int getMatchLen(int dist, int lenLimit) {
335 return MatchLength.getLen(buf, readPos, dist + 1, 0, lenLimit);
336 }
337
338 /**
339 * Get the length of a match at the given distance and forward offset.
340 *
341 * @param forward forward offset
342 * @param dist zero-based distance of the match to test
343 * @param lenLimit don't test for a match longer than this
344 *
345 * @return length of the match; it is in the range [0, lenLimit]
346 */
347 public int getMatchLen(int forward, int dist, int lenLimit) {
348 return MatchLength.getLen(buf, readPos + forward, dist + 1,
349 0, lenLimit);
350 }
351
352 /**
353 * Verifies that the matches returned by the match finder are valid.
354 * This is meant to be used in an assert statement. This is totally
355 * useless for actual encoding since match finder's results should
356 * naturally always be valid if it isn't broken.
357 *
358 * @param matches return value from {@code getMatches}
359 *
360 * @return true if matches are valid, false if match finder is broken
361 */
362 public boolean verifyMatches(Matches matches) {
363 int lenLimit = Math.min(getAvail(), matchLenMax);
364
365 for (int i = 0; i < matches.count; ++i)
366 if (getMatchLen(matches.dist[i], lenLimit) != matches.len[i])
367 return false;
368
369 return true;
370 }
371
372 /**
373 * Moves to the next byte, checks if there is enough input available,
374 * and returns the amount of input available.
375 *
376 * @param requiredForFlushing
377 * minimum number of available bytes when
378 * flushing; encoding may be continued with
379 * new input after flushing
380 * @param requiredForFinishing
381 * minimum number of available bytes when
382 * finishing; encoding must not be continued
383 * after finishing or the match finder state
384 * may be corrupt
385 *
386 * @return the number of bytes available or zero if there
387 * is not enough input available
388 */
389 int movePos(int requiredForFlushing, int requiredForFinishing) {
390 assert requiredForFlushing >= requiredForFinishing;
391
392 ++readPos;
393 int avail = writePos - readPos;
394
395 if (avail < requiredForFlushing) {
396 if (avail < requiredForFinishing || !finishing) {
397 ++pendingSize;
398 avail = 0;
399 }
400 }
401
402 return avail;
403 }
404
405 /**
406 * Runs match finder for the next byte and returns the matches found.
407 */
408 public abstract Matches getMatches();
409
410 /**
411 * Skips the given number of bytes in the match finder.
412 */
413 public abstract void skip(int len);
414 }