Debian Codegraph @

src/org/tukaani/xz/XZOutputStream.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
5 package org.tukaani.xz;
6
7 import java.io.OutputStream;
8 import java.io.IOException;
9 import org.tukaani.xz.common.EncoderUtil;
10 import org.tukaani.xz.common.StreamFlags;
11 import org.tukaani.xz.check.Check;
12 import org.tukaani.xz.index.IndexEncoder;
13
14 /**
15 * Compresses into the .xz file format.
16 *
17 * <h2>Examples</h2>
18 * <p>
19 * Getting an output stream to compress with LZMA2 using the default
20 * settings and the default integrity check type (CRC64):
21 * <blockquote><pre>
22 * FileOutputStream outfile = new FileOutputStream("foo.xz");
23 * XZOutputStream outxz = new XZOutputStream(outfile, new LZMA2Options());
24 * </pre></blockquote>
25 * <p>
26 * Using the preset level {@code 8} for LZMA2 (the default is {@code 6})
27 * and SHA-256 instead of CRC64 for integrity checking:
28 * <blockquote><pre>
29 * XZOutputStream outxz = new XZOutputStream(outfile, new LZMA2Options(8),
30 * XZ.CHECK_SHA256);
31 * </pre></blockquote>
32 * <p>
33 * Using the x86 BCJ filter together with LZMA2 to compress x86 executables
34 * and printing the memory usage information before creating the
35 * {@code XZOutputStream}:
36 * <blockquote><pre>
37 * X86Options x86 = new X86Options();
38 * LZMA2Options lzma2 = new LZMA2Options();
39 * FilterOptions[] options = { x86, lzma2 };
40 * System.out.println("Encoder memory usage: "
41 * + FilterOptions.getEncoderMemoryUsage(options)
42 * + " KiB");
43 * System.out.println("Decoder memory usage: "
44 * + FilterOptions.getDecoderMemoryUsage(options)
45 * + " KiB");
46 * XZOutputStream outxz = new XZOutputStream(outfile, options);
47 * </pre></blockquote>
48 */
49 public class XZOutputStream extends FinishableOutputStream {
50 private final ArrayCache arrayCache;
51
52 private OutputStream out;
53 private final StreamFlags streamFlags = new StreamFlags();
54 private final Check check;
55 private final IndexEncoder index = new IndexEncoder();
56
57 private BlockOutputStream blockEncoder = null;
58 private FilterEncoder[] filters;
59
60 /**
61 * True if the current filter chain supports flushing.
62 * If it doesn't support flushing, {@code flush()}
63 * will use {@code endBlock()} as a fallback.
64 */
65 private boolean filtersSupportFlushing;
66
67 private IOException exception = null;
68 private boolean finished = false;
69
70 private final byte[] tempBuf = new byte[1];
71
72 /**
73 * Creates a new XZ compressor using one filter and CRC64 as
74 * the integrity check. This constructor is equivalent to passing
75 * a single-member {@code FilterOptions} array to
76 * {@code XZOutputStream(OutputStream, FilterOptions[])}.
77 *
78 * @param out output stream to which the compressed data
79 * will be written
80 *
81 * @param filterOptions
82 * filter options to use
83 *
84 * @throws UnsupportedOptionsException
85 * invalid filter chain
86 *
87 * @throws IOException may be thrown from {@code out}
88 */
89 public XZOutputStream(OutputStream out, FilterOptions filterOptions)
90 throws IOException {
91 this(out, filterOptions, XZ.CHECK_CRC64);
92 }
93
94 /**
95 * Creates a new XZ compressor using one filter and CRC64 as
96 * the integrity check. This constructor is equivalent to passing
97 * a single-member {@code FilterOptions} array to
98 * {@code XZOutputStream(OutputStream, FilterOptions[], ArrayCache)}.
99 *
100 * @param out output stream to which the compressed data
101 * will be written
102 *
103 * @param filterOptions
104 * filter options to use
105 *
106 * @param arrayCache cache to be used for allocating large arrays
107 *
108 * @throws UnsupportedOptionsException
109 * invalid filter chain
110 *
111 * @throws IOException may be thrown from {@code out}
112 *
113 * @since 1.7
114 */
115 public XZOutputStream(OutputStream out, FilterOptions filterOptions,
116 ArrayCache arrayCache)
117 throws IOException {
118 this(out, filterOptions, XZ.CHECK_CRC64, arrayCache);
119 }
120
121 /**
122 * Creates a new XZ compressor using one filter and the specified
123 * integrity check type. This constructor is equivalent to
124 * passing a single-member {@code FilterOptions} array to
125 * {@code XZOutputStream(OutputStream, FilterOptions[], int)}.
126 *
127 * @param out output stream to which the compressed data
128 * will be written
129 *
130 * @param filterOptions
131 * filter options to use
132 *
133 * @param checkType type of the integrity check,
134 * for example XZ.CHECK_CRC32
135 *
136 * @throws UnsupportedOptionsException
137 * invalid filter chain
138 *
139 * @throws IOException may be thrown from {@code out}
140 */
141 public XZOutputStream(OutputStream out, FilterOptions filterOptions,
142 int checkType) throws IOException {
143 this(out, new FilterOptions[] { filterOptions }, checkType);
144 }
145
146 /**
147 * Creates a new XZ compressor using one filter and the specified
148 * integrity check type. This constructor is equivalent to
149 * passing a single-member {@code FilterOptions} array to
150 * {@code XZOutputStream(OutputStream, FilterOptions[], int, ArrayCache)}.
151 *
152 * @param out output stream to which the compressed data
153 * will be written
154 *
155 * @param filterOptions
156 * filter options to use
157 *
158 * @param checkType type of the integrity check,
159 * for example XZ.CHECK_CRC32
160 *
161 * @param arrayCache cache to be used for allocating large arrays
162 *
163 * @throws UnsupportedOptionsException
164 * invalid filter chain
165 *
166 * @throws IOException may be thrown from {@code out}
167 *
168 * @since 1.7
169 */
170 public XZOutputStream(OutputStream out, FilterOptions filterOptions,
171 int checkType, ArrayCache arrayCache)
172 throws IOException {
173 this(out, new FilterOptions[] { filterOptions }, checkType,
174 arrayCache);
175 }
176
177 /**
178 * Creates a new XZ compressor using 1-4 filters and CRC64 as
179 * the integrity check. This constructor is equivalent
180 * {@code XZOutputStream(out, filterOptions, XZ.CHECK_CRC64)}.
181 *
182 * @param out output stream to which the compressed data
183 * will be written
184 *
185 * @param filterOptions
186 * array of filter options to use
187 *
188 * @throws UnsupportedOptionsException
189 * invalid filter chain
190 *
191 * @throws IOException may be thrown from {@code out}
192 */
193 public XZOutputStream(OutputStream out, FilterOptions[] filterOptions)
194 throws IOException {
195 this(out, filterOptions, XZ.CHECK_CRC64);
196 }
197
198 /**
199 * Creates a new XZ compressor using 1-4 filters and CRC64 as
200 * the integrity check. This constructor is equivalent
201 * {@code XZOutputStream(out, filterOptions, XZ.CHECK_CRC64, arrayCache)}.
202 *
203 * @param out output stream to which the compressed data
204 * will be written
205 *
206 * @param filterOptions
207 * array of filter options to use
208 *
209 * @param arrayCache cache to be used for allocating large arrays
210 *
211 * @throws UnsupportedOptionsException
212 * invalid filter chain
213 *
214 * @throws IOException may be thrown from {@code out}
215 *
216 * @since 1.7
217 */
218 public XZOutputStream(OutputStream out, FilterOptions[] filterOptions,
219 ArrayCache arrayCache)
220 throws IOException {
221 this(out, filterOptions, XZ.CHECK_CRC64, arrayCache);
222 }
223
224 /**
225 * Creates a new XZ compressor using 1-4 filters and the specified
226 * integrity check type.
227 *
228 * @param out output stream to which the compressed data
229 * will be written
230 *
231 * @param filterOptions
232 * array of filter options to use
233 *
234 * @param checkType type of the integrity check,
235 * for example XZ.CHECK_CRC32
236 *
237 * @throws UnsupportedOptionsException
238 * invalid filter chain
239 *
240 * @throws IOException may be thrown from {@code out}
241 */
242 public XZOutputStream(OutputStream out, FilterOptions[] filterOptions,
243 int checkType) throws IOException {
244 this(out, filterOptions, checkType, ArrayCache.getDefaultCache());
245 }
246
247 /**
248 * Creates a new XZ compressor using 1-4 filters and the specified
249 * integrity check type.
250 *
251 * @param out output stream to which the compressed data
252 * will be written
253 *
254 * @param filterOptions
255 * array of filter options to use
256 *
257 * @param checkType type of the integrity check,
258 * for example XZ.CHECK_CRC32
259 *
260 * @param arrayCache cache to be used for allocating large arrays
261 *
262 * @throws UnsupportedOptionsException
263 * invalid filter chain
264 *
265 * @throws IOException may be thrown from {@code out}
266 *
267 * @since 1.7
268 */
269 public XZOutputStream(OutputStream out, FilterOptions[] filterOptions,
270 int checkType, ArrayCache arrayCache)
271 throws IOException {
272 this.arrayCache = arrayCache;
273 this.out = out;
274 setFiltersForNextBlock(filterOptions);
275
276 streamFlags.checkType = checkType;
277 check = Check.getInstance(checkType);
278
279 encodeStreamHeader();
280 }
281
282 /**
283 * Updates the filter chain with a single filter.
284 * This is equivalent to passing a single-member {@code FilterOptions}
285 * array to {@code updateFilters(FilterOptions[])}.
286 *
287 * @param filterOptions
288 * new filter to use
289 *
290 * @throws UnsupportedOptionsException
291 * unsupported filter chain, or trying to change
292 * the filter chain in the middle of a Block
293 */
294 public void updateFilters(FilterOptions filterOptions)
295 throws XZIOException {
296 FilterOptions[] opts = new FilterOptions[1];
297 opts[0] = filterOptions;
298 updateFilters(opts);
299 }
300
301 /**
302 * Updates the filter chain with 1-4 filters.
303 * <p>
304 * Currently this cannot be used to update e.g. LZMA2 options in the
305 * middle of a XZ Block. Use {@code endBlock()} to finish the
306 * current XZ Block before calling this function. The new filter chain
307 * will then be used for the next XZ Block.
308 *
309 * @param filterOptions
310 * new filter chain to use
311 *
312 * @throws UnsupportedOptionsException
313 * unsupported filter chain, or trying to change
314 * the filter chain in the middle of a Block
315 */
316 public void updateFilters(FilterOptions[] filterOptions)
317 throws XZIOException {
318 if (blockEncoder != null)
319 throw new UnsupportedOptionsException("Changing filter options "
320 + "in the middle of a XZ Block not implemented");
321
322 setFiltersForNextBlock(filterOptions);
323 }
324
325 // This is called from updateFilters and from a constructor.
326 // Since 1.10, the constructor doesn't call the public function
327 // updateFilters because it might lead to this-escape if this class
328 // is extended and updateFilters is overridden.
329 private void setFiltersForNextBlock(FilterOptions[] filterOptions)
330 throws XZIOException {
331 if (filterOptions.length < 1 || filterOptions.length > 4)
332 throw new UnsupportedOptionsException(
333 "XZ filter chain must be 1-4 filters");
334
335 filtersSupportFlushing = true;
336 FilterEncoder[] newFilters = new FilterEncoder[filterOptions.length];
337 for (int i = 0; i < filterOptions.length; ++i) {
338 newFilters[i] = filterOptions[i].getFilterEncoder();
339 filtersSupportFlushing &= newFilters[i].supportsFlushing();
340 }
341
342 RawCoder.validate(newFilters);
343 filters = newFilters;
344 }
345
346 /**
347 * Writes one byte to be compressed.
348 *
349 * @throws XZIOException
350 * XZ Stream has grown too big
351 *
352 * @throws XZIOException
353 * {@code finish()} or {@code close()}
354 * was already called
355 *
356 * @throws IOException may be thrown by the underlying output stream
357 */
358 @Override
359 public void write(int b) throws IOException {
360 tempBuf[0] = (byte)b;
361 write(tempBuf, 0, 1);
362 }
363
364 /**
365 * Writes an array of bytes to be compressed.
366 * The compressors tend to do internal buffering and thus the written
367 * data won't be readable from the compressed output immediately.
368 * Use {@code flush()} to force everything written so far to
369 * be written to the underlying output stream, but be aware that
370 * flushing reduces compression ratio.
371 *
372 * @param buf buffer of bytes to be written
373 * @param off start offset in {@code buf}
374 * @param len number of bytes to write
375 *
376 * @throws XZIOException
377 * XZ Stream has grown too big: total file size
378 * about 8&nbsp;EiB or the Index field exceeds
379 * 16&nbsp;GiB; you shouldn't reach these sizes
380 * in practice
381 *
382 * @throws XZIOException
383 * {@code finish()} or {@code close()}
384 * was already called and {@code len > 0}
385 *
386 * @throws IOException may be thrown by the underlying output stream
387 */
388 @Override
389 public void write(byte[] buf, int off, int len) throws IOException {
390 if (off < 0 || len < 0 || off + len < 0 || off + len > buf.length)
391 throw new IndexOutOfBoundsException();
392
393 if (exception != null)
394 throw exception;
395
396 if (finished)
397 throw new XZIOException("Stream finished or closed");
398
399 try {
400 if (blockEncoder == null)
401 blockEncoder = new BlockOutputStream(out, filters, check,
402 arrayCache);
403
404 blockEncoder.write(buf, off, len);
405 } catch (IOException e) {
406 exception = e;
407 throw e;
408 }
409 }
410
411 /**
412 * Finishes the current XZ Block (but not the whole XZ Stream).
413 * This doesn't flush the stream so it's possible that not all data will
414 * be decompressible from the output stream when this function returns.
415 * Call also {@code flush()} if flushing is wanted in addition to
416 * finishing the current XZ Block.
417 * <p>
418 * If there is no unfinished Block open, this function will do nothing.
419 * (No empty XZ Block will be created.)
420 * <p>
421 * This function can be useful, for example, to create
422 * random-accessible .xz files.
423 * <p>
424 * Starting a new XZ Block means that the encoder state is reset.
425 * Doing this very often will increase the size of the compressed
426 * file a lot (more than plain {@code flush()} would do).
427 * <p>
428 * <b>Note:</b> {@code flush()} may call this method, and {@code finish()}
429 * (and thus {@code close()}) will call this method.
430 *
431 * @throws XZIOException
432 * XZ Stream has grown too big
433 *
434 * @throws XZIOException
435 * stream finished or closed
436 *
437 * @throws IOException may be thrown by the underlying output stream
438 */
439 public void endBlock() throws IOException {
440 if (exception != null)
441 throw exception;
442
443 if (finished)
444 throw new XZIOException("Stream finished or closed");
445
446 // NOTE: Once there is threading with multiple Blocks, it's possible
447 // that this function will be more like a barrier that returns
448 // before the last Block has been finished.
449 if (blockEncoder != null) {
450 try {
451 blockEncoder.finish();
452 index.add(blockEncoder.getUnpaddedSize(),
453 blockEncoder.getUncompressedSize());
454 blockEncoder = null;
455 } catch (IOException e) {
456 exception = e;
457 throw e;
458 }
459 }
460 }
461
462 /**
463 * Flushes the encoder and calls {@code out.flush()}.
464 * All buffered pending data will then be decompressible from
465 * the output stream.
466 * <p>
467 * Calling this function very often may increase the compressed
468 * file size a lot. The filter chain options may affect the size
469 * increase too. For example, with LZMA2 the HC4 match finder has
470 * smaller penalty with flushing than BT4.
471 * <p>
472 * Some filters don't support flushing. If the filter chain has
473 * such a filter, {@code flush()} will call {@code endBlock()}
474 * before flushing.
475 *
476 * @throws XZIOException
477 * XZ Stream has grown too big
478 *
479 * @throws XZIOException
480 * stream finished or closed
481 *
482 * @throws IOException may be thrown by the underlying output stream
483 */
484 @Override
485 public void flush() throws IOException {
486 if (exception != null)
487 throw exception;
488
489 if (finished)
490 throw new XZIOException("Stream finished or closed");
491
492 try {
493 if (blockEncoder != null) {
494 if (filtersSupportFlushing) {
495 // This will eventually call out.flush() so
496 // no need to do it here again.
497 blockEncoder.flush();
498 } else {
499 endBlock();
500 out.flush();
501 }
502 } else {
503 out.flush();
504 }
505 } catch (IOException e) {
506 exception = e;
507 throw e;
508 }
509 }
510
511 /**
512 * Finishes compression without closing the underlying stream.
513 * No more data can be written to this stream after finishing
514 * (calling {@code write} with an empty buffer is OK).
515 * <p>
516 * Repeated calls to {@code finish()} do nothing unless
517 * an exception was thrown by this stream earlier. In that case
518 * the same exception is thrown again.
519 * <p>
520 * After finishing, the stream may be closed normally with
521 * {@code close()}. If the stream will be closed anyway, there
522 * usually is no need to call {@code finish()} separately.
523 *
524 * @throws XZIOException
525 * XZ Stream has grown too big
526 *
527 * @throws IOException may be thrown by the underlying output stream
528 */
529 @Override
530 public void finish() throws IOException {
531 if (!finished) {
532 // This checks for pending exceptions so we don't need to
533 // worry about it here.
534 endBlock();
535
536 try {
537 index.encode(out);
538 encodeStreamFooter();
539 } catch (IOException e) {
540 exception = e;
541 throw e;
542 }
543
544 // Set it to true only if everything goes fine. Setting it earlier
545 // would cause repeated calls to finish() do nothing instead of
546 // throwing an exception to indicate an earlier error.
547 finished = true;
548 }
549 }
550
551 /**
552 * Finishes compression and closes the underlying stream.
553 * The underlying stream {@code out} is closed even if finishing
554 * fails. If both finishing and closing fail, the exception thrown
555 * by {@code finish()} is thrown and the exception from the failed
556 * {@code out.close()} is lost.
557 *
558 * @throws XZIOException
559 * XZ Stream has grown too big
560 *
561 * @throws IOException may be thrown by the underlying output stream
562 */
563 @Override
564 public void close() throws IOException {
565 if (out != null) {
566 // If finish() throws an exception, it stores the exception to
567 // the variable "exception". So we can ignore the possible
568 // exception here.
569 try {
570 finish();
571 } catch (IOException e) {}
572
573 try {
574 out.close();
575 } catch (IOException e) {
576 // Remember the exception but only if there is no previous
577 // pending exception.
578 if (exception == null)
579 exception = e;
580 }
581
582 out = null;
583 }
584
585 if (exception != null)
586 throw exception;
587 }
588
589 private void encodeStreamFlags(byte[] buf, int off) {
590 buf[off] = 0x00;
591 buf[off + 1] = (byte)streamFlags.checkType;
592 }
593
594 private void encodeStreamHeader() throws IOException {
595 out.write(XZ.HEADER_MAGIC);
596
597 byte[] buf = new byte[2];
598 encodeStreamFlags(buf, 0);
599 out.write(buf);
600
601 EncoderUtil.writeCRC32(out, buf);
602 }
603
604 private void encodeStreamFooter() throws IOException {
605 byte[] buf = new byte[6];
606 long backwardSize = index.getIndexSize() / 4 - 1;
607 for (int i = 0; i < 4; ++i)
608 buf[i] = (byte)(backwardSize >>> (i * 8));
609
610 encodeStreamFlags(buf, 4);
611
612 EncoderUtil.writeCRC32(out, buf);
613 out.write(buf);
614 out.write(XZ.FOOTER_MAGIC);
615 }
616 }