Home | History | Annotate | Download | only in index
      1 /*
      2  * IndexEncoder
      3  *
      4  * Author: Lasse Collin <lasse.collin (at) tukaani.org>
      5  *
      6  * This file has been put into the public domain.
      7  * You can do whatever you want with this file.
      8  */
      9 
     10 package org.tukaani.xz.index;
     11 
     12 import java.io.OutputStream;
     13 import java.io.IOException;
     14 import java.util.ArrayList;
     15 import java.util.Iterator;
     16 import java.util.zip.CheckedOutputStream;
     17 import org.tukaani.xz.common.EncoderUtil;
     18 import org.tukaani.xz.XZIOException;
     19 
     20 public class IndexEncoder extends IndexBase {
     21     private final ArrayList records = new ArrayList();
     22 
     23     public IndexEncoder() {
     24         super(new XZIOException("XZ Stream or its Index has grown too big"));
     25     }
     26 
     27     public void add(long unpaddedSize, long uncompressedSize)
     28             throws XZIOException {
     29         super.add(unpaddedSize, uncompressedSize);
     30         records.add(new IndexRecord(unpaddedSize, uncompressedSize));
     31     }
     32 
     33     public void encode(OutputStream out) throws IOException {
     34         java.util.zip.CRC32 crc32 = new java.util.zip.CRC32();
     35         CheckedOutputStream outChecked = new CheckedOutputStream(out, crc32);
     36 
     37         // Index Indicator
     38         outChecked.write(0x00);
     39 
     40         // Number of Records
     41         EncoderUtil.encodeVLI(outChecked, recordCount);
     42 
     43         // List of Records
     44         for (Iterator i = records.iterator(); i.hasNext(); ) {
     45             IndexRecord record = (IndexRecord)i.next();
     46             EncoderUtil.encodeVLI(outChecked, record.unpadded);
     47             EncoderUtil.encodeVLI(outChecked, record.uncompressed);
     48         }
     49 
     50         // Index Padding
     51         for (int i = getIndexPaddingSize(); i > 0; --i)
     52             outChecked.write(0x00);
     53 
     54         // CRC32
     55         long value = crc32.getValue();
     56         for (int i = 0; i < 4; ++i)
     57             out.write((byte)(value >>> (i * 8)));
     58     }
     59 }
     60