File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\compress\LZFOutputStream.java.html

1 /*
2 * Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License,
3 * Version 1.0, and under the Eclipse Public License, Version 1.0
4 * (http://h2database.com/html/license.html).
5 * Initial Developer: H2 Group
6 */
7 package org.h2.compress;
8
9 import java.io.IOException;
10 import java.io.OutputStream;
11 import org.h2.engine.Constants;
12
13 /**
14 * An output stream to write an LZF stream.
15 * The data is automatically compressed.
16 */
17 public class LZFOutputStream extends OutputStream {
18
19 /**
20 * The file header of a LZF file.
21 */
22 static final int MAGIC = ('H' << 24) | ('2' << 16) | ('I' << 8) | 'S';
23
24 private final OutputStream out;
25 private final CompressLZF compress = new CompressLZF();
26 private final byte[] buffer;
27 private int pos;
28 private byte[] outBuffer;
29
30 public LZFOutputStream(OutputStream out) throws IOException {
31 this.out = out;
32 int len = Constants.IO_BUFFER_SIZE_COMPRESS;
33 buffer = new byte[len];
34 ensureOutput(len);
35 writeInt(MAGIC);
36 }
37
38 private void ensureOutput(int len) {
39 // TODO calculate the maximum overhead (worst case) for the output
40 // buffer
41 int outputLen = (len < 100 ? len + 100 : len) * 2;
42 if (outBuffer == null || outBuffer.length < outputLen) {
43 outBuffer = new byte[outputLen];
44 }
45 }
46
47 public void write(int b) throws IOException {
48 if (pos >= buffer.length) {
49 flush();
50 }
51 buffer[pos++] = (byte) b;
52 }
53
54 private void compressAndWrite(byte[] buff, int len) throws IOException {
55 if (len > 0) {
56 ensureOutput(len);
57 int compressed = compress.compress(buff, len, outBuffer, 0);
58 if (compressed > len) {
59 writeInt(-len);
60 out.write(buff, 0, len);
61 } else {
62 writeInt(compressed);
63 writeInt(len);
64 out.write(outBuffer, 0, compressed);
65 }
66 }
67 }
68
69 private void writeInt(int x) throws IOException {
70 out.write((byte) (x >> 24));
71 out.write((byte) (x >> 16));
72 out.write((byte) (x >> 8));
73 out.write((byte) x);
74 }
75
76 public void write(byte[] buff, int off, int len) throws IOException {
77 while (len > 0) {
78 int copy = Math.min(buffer.length - pos, len);
79 System.arraycopy(buff, off, buffer, pos, copy);
80 pos += copy;
81 if (pos >= buffer.length) {
82 flush();
83 }
84 off += copy;
85 len -= copy;
86 }
87 }
88
89 public void flush() throws IOException {
90 compressAndWrite(buffer, pos);
91 pos = 0;
92 }
93
94 public void close() throws IOException {
95 flush();
96 out.close();
97 }
98
99 }
100