001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.apache.commons.compress.compressors.snappy;
020
021import java.io.IOException;
022import java.io.OutputStream;
023
024import org.apache.commons.compress.compressors.CompressorOutputStream;
025import org.apache.commons.compress.compressors.lz77support.LZ77Compressor;
026import org.apache.commons.compress.compressors.lz77support.Parameters;
027import org.apache.commons.compress.utils.ByteUtils;
028
029/**
030 * CompressorOutputStream for the raw Snappy format.
031 *
032 * <p>This implementation uses an internal buffer in order to handle
033 * the back-references that are at the heart of the LZ77 algorithm.
034 * The size of the buffer must be at least as big as the biggest
035 * offset used in the compressed stream.  The current version of the
036 * Snappy algorithm as defined by Google works on 32k blocks and
037 * doesn't contain offsets bigger than 32k which is the default block
038 * size used by this class.</p>
039 *
040 * <p>The raw Snappy format requires the uncompressed size to be
041 * written at the beginning of the stream using a varint
042 * representation, i.e. the number of bytes needed to write the
043 * information is not known before the uncompressed size is
044 * known. We've chosen to make the uncompressedSize a parameter of the
045 * constructor in favor of buffering the whole output until the size
046 * is known. When using the {@link FramedSnappyCompressorOutputStream}
047 * this limitation is taken care of by the warpping framing
048 * format.</p>
049 *
050 * @see <a href="https://github.com/google/snappy/blob/master/format_description.txt">Snappy compressed format description</a>
051 * @since 1.14
052 * @NotThreadSafe
053 */
054public class SnappyCompressorOutputStream extends CompressorOutputStream {
055    private final LZ77Compressor compressor;
056    private final OutputStream os;
057    private final ByteUtils.ByteConsumer consumer;
058
059    // used in one-arg write method
060    private final byte[] oneByte = new byte[1];
061
062    private boolean finished = false;
063
064    /**
065     * Constructor using the default block size of 32k.
066     *
067     * @param os the outputstream to write compressed data to
068     * @param uncompressedSize the uncompressed size of data
069     * @throws IOException if writing of the size fails
070     */
071    public SnappyCompressorOutputStream(final OutputStream os, final long uncompressedSize) throws IOException {
072        this(os, uncompressedSize, SnappyCompressorInputStream.DEFAULT_BLOCK_SIZE);
073    }
074
075    /**
076     * Constructor using a configurable block size.
077     *
078     * @param os the outputstream to write compressed data to
079     * @param uncompressedSize the uncompressed size of data
080     * @param blockSize the block size used - must be a power of two
081     * @throws IOException if writing of the size fails
082     */
083    public SnappyCompressorOutputStream(final OutputStream os, final long uncompressedSize, final int blockSize)
084        throws IOException {
085        this(os, uncompressedSize, createParameterBuilder(blockSize).build());
086    }
087
088    /**
089     * Constructor providing full control over the underlying LZ77 compressor.
090     *
091     * @param os the outputstream to write compressed data to
092     * @param uncompressedSize the uncompressed size of data
093     * @param params the parameters to use by the compressor - note
094     * that the format itself imposes some limits like a maximum match
095     * length of 64 bytes
096     * @throws IOException if writing of the size fails
097     */
098    public SnappyCompressorOutputStream(final OutputStream os, final long uncompressedSize, Parameters params)
099        throws IOException {
100        this.os = os;
101        consumer = new ByteUtils.OutputStreamByteConsumer(os);
102        compressor = new LZ77Compressor(params, new LZ77Compressor.Callback() {
103                @Override
104                public void accept(LZ77Compressor.Block block) throws IOException {
105                    //System.err.println(block);
106                    if (block instanceof LZ77Compressor.LiteralBlock) {
107                        writeLiteralBlock((LZ77Compressor.LiteralBlock) block);
108                    } else if (block instanceof LZ77Compressor.BackReference) {
109                        writeBackReference((LZ77Compressor.BackReference) block);
110                    }
111                }
112            });
113        writeUncompressedSize(uncompressedSize);
114    }
115
116    @Override
117    public void write(int b) throws IOException {
118        oneByte[0] = (byte) (b & 0xff);
119        write(oneByte);
120    }
121
122    @Override
123    public void write(byte[] data, int off, int len) throws IOException {
124        compressor.compress(data, off, len);
125    }
126
127    @Override
128    public void close() throws IOException {
129        finish();
130        os.close();
131    }
132
133    /**
134     * Compresses all remaining data and writes it to the stream,
135     * doesn't close the underlying stream.
136     * @throws IOException if an error occurs
137     */
138    public void finish() throws IOException {
139        if (!finished) {
140            compressor.finish();
141            finished = true;
142        }
143    }
144
145    private void writeUncompressedSize(long uncompressedSize) throws IOException {
146        boolean more = false;
147        do {
148            int currentByte = (int) (uncompressedSize & 0x7F);
149            more = uncompressedSize > currentByte;
150            if (more) {
151                currentByte |= 0x80;
152            }
153            os.write(currentByte);
154            uncompressedSize >>= 7;
155        } while (more);
156    }
157
158    // literal length is stored as (len - 1) either inside the tag
159    // (six bits minus four flags) or in 1 to 4 bytes after the tag
160    private static final int MAX_LITERAL_SIZE_WITHOUT_SIZE_BYTES = 60;
161    private static final int MAX_LITERAL_SIZE_WITH_ONE_SIZE_BYTE = 1 << 8;
162    private static final int MAX_LITERAL_SIZE_WITH_TWO_SIZE_BYTES = 1 << 16;
163    private static final int MAX_LITERAL_SIZE_WITH_THREE_SIZE_BYTES = 1 << 24;
164
165    private static final int ONE_SIZE_BYTE_MARKER = 60 << 2;
166    private static final int TWO_SIZE_BYTE_MARKER = 61 << 2;
167    private static final int THREE_SIZE_BYTE_MARKER = 62 << 2;
168    private static final int FOUR_SIZE_BYTE_MARKER = 63 << 2;
169
170    private void writeLiteralBlock(LZ77Compressor.LiteralBlock block) throws IOException {
171        int len = block.getLength();
172        if (len <= MAX_LITERAL_SIZE_WITHOUT_SIZE_BYTES) {
173            writeLiteralBlockNoSizeBytes(block, len);
174        } else if (len <= MAX_LITERAL_SIZE_WITH_ONE_SIZE_BYTE) {
175            writeLiteralBlockOneSizeByte(block, len);
176        } else if (len <= MAX_LITERAL_SIZE_WITH_TWO_SIZE_BYTES) {
177            writeLiteralBlockTwoSizeBytes(block, len);
178        } else if (len <= MAX_LITERAL_SIZE_WITH_THREE_SIZE_BYTES) {
179            writeLiteralBlockThreeSizeBytes(block, len);
180        } else {
181            writeLiteralBlockFourSizeBytes(block, len);
182        }
183    }
184
185    private void writeLiteralBlockNoSizeBytes(LZ77Compressor.LiteralBlock block, int len) throws IOException {
186        writeLiteralBlockWithSize(len - 1 << 2, 0, len, block);
187    }
188
189    private void writeLiteralBlockOneSizeByte(LZ77Compressor.LiteralBlock block, int len) throws IOException {
190        writeLiteralBlockWithSize(ONE_SIZE_BYTE_MARKER, 1, len, block);
191    }
192
193    private void writeLiteralBlockTwoSizeBytes(LZ77Compressor.LiteralBlock block, int len) throws IOException {
194        writeLiteralBlockWithSize(TWO_SIZE_BYTE_MARKER, 2, len, block);
195    }
196
197    private void writeLiteralBlockThreeSizeBytes(LZ77Compressor.LiteralBlock block, int len) throws IOException {
198        writeLiteralBlockWithSize(THREE_SIZE_BYTE_MARKER, 3, len, block);
199    }
200
201    private void writeLiteralBlockFourSizeBytes(LZ77Compressor.LiteralBlock block, int len) throws IOException {
202        writeLiteralBlockWithSize(FOUR_SIZE_BYTE_MARKER, 4, len, block);
203    }
204
205    private void writeLiteralBlockWithSize(int tagByte, int sizeBytes, int len, LZ77Compressor.LiteralBlock block)
206        throws IOException {
207        os.write(tagByte);
208        writeLittleEndian(sizeBytes, len - 1);
209        os.write(block.getData(), block.getOffset(), len);
210    }
211
212    private void writeLittleEndian(final int numBytes, int num) throws IOException {
213        ByteUtils.toLittleEndian(consumer, num, numBytes);
214    }
215
216    // Back-references ("copies") have their offset/size information
217    // in two, three or five bytes.
218    private static final int MIN_MATCH_LENGTH_WITH_ONE_OFFSET_BYTE = 4;
219    private static final int MAX_MATCH_LENGTH_WITH_ONE_OFFSET_BYTE = 11;
220    private static final int MAX_OFFSET_WITH_ONE_OFFSET_BYTE = 1 << 11 - 1;
221    private static final int MAX_OFFSET_WITH_TWO_OFFSET_BYTES = 1 << 16 - 1;
222
223    private static final int ONE_BYTE_COPY_TAG = 1;
224    private static final int TWO_BYTE_COPY_TAG = 2;
225    private static final int FOUR_BYTE_COPY_TAG = 3;
226
227    private void writeBackReference(LZ77Compressor.BackReference block) throws IOException {
228        final int len = block.getLength();
229        final int offset = block.getOffset();
230        if (len >= MIN_MATCH_LENGTH_WITH_ONE_OFFSET_BYTE && len <= MAX_MATCH_LENGTH_WITH_ONE_OFFSET_BYTE
231            && offset <= MAX_OFFSET_WITH_ONE_OFFSET_BYTE) {
232            writeBackReferenceWithOneOffsetByte(len, offset);
233        } else if (offset < MAX_OFFSET_WITH_TWO_OFFSET_BYTES) {
234            writeBackReferenceWithTwoOffsetBytes(len, offset);
235        } else {
236            writeBackReferenceWithFourOffsetBytes(len, offset);
237        }
238    }
239
240    private void writeBackReferenceWithOneOffsetByte(int len, int offset) throws IOException {
241        os.write(ONE_BYTE_COPY_TAG | ((len - 4) << 2) | ((offset & 0x700) >> 3));
242        os.write(offset & 0xff);
243    }
244
245    private void writeBackReferenceWithTwoOffsetBytes(int len, int offset) throws IOException {
246        writeBackReferenceWithLittleEndianOffset(TWO_BYTE_COPY_TAG, 2, len, offset);
247    }
248
249    private void writeBackReferenceWithFourOffsetBytes(int len, int offset) throws IOException {
250        writeBackReferenceWithLittleEndianOffset(FOUR_BYTE_COPY_TAG, 4, len, offset);
251    }
252
253    private void writeBackReferenceWithLittleEndianOffset(int tag, int offsetBytes, int len, int offset)
254        throws IOException {
255        os.write(tag | ((len - 1) << 2));
256        writeLittleEndian(offsetBytes, offset);
257    }
258
259    // technically the format could use shorter matches but with a
260    // length of three the offset would be encoded as at least two
261    // bytes in addition to the tag, so yield no compression at all
262    private static final int MIN_MATCH_LENGTH = 4;
263    // Snappy stores the match length in six bits of the tag
264    private static final int MAX_MATCH_LENGTH = 64;
265
266    /**
267     * Returns a builder correctly configured for the Snappy algorithm using the gven block size.
268     * @param blockSize the block size.
269     * @return a builder correctly configured for the Snappy algorithm using the gven block size
270     */
271    public static Parameters.Builder createParameterBuilder(int blockSize) {
272        // the max offset and max literal length defined by the format
273        // are 2^32 - 1 and 2^32 respectively - with blockSize being
274        // an integer we will never exceed that
275        return Parameters.builder(blockSize)
276            .withMinBackReferenceLength(MIN_MATCH_LENGTH)
277            .withMaxBackReferenceLength(MAX_MATCH_LENGTH)
278            .withMaxOffset(blockSize)
279            .withMaxLiteralLength(blockSize);
280    }
281}