package com.jscape.inet.ftp;

import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;

/**
 * CRC computer.
 *
 * @author Alex
 * @version 1.0
 * @see <a href="CRCComputer.java.html">Source code</a>
 */
public final class CRCComputer {

    private static final int BUF_SIZE = 4096;

    /**
     * Computes CRC32 for the provided stream.
     *
     * @param in          input stream
     * @param totalLength length of bytes to include in CRC
     *
     * @return computed CRC
     *
     * @throws java.io.IOException if an I/O error occurs
     */
    public long compute(InputStream in, long totalLength)
            throws IOException {
        CheckedInputStream checkedIn = new CheckedInputStream(in, new CRC32());
        byte[] buf = new byte[BUF_SIZE];
        int read;
        long length = (buf.length > totalLength) ? totalLength : buf.length;

        while ((read = checkedIn.read(buf, 0, (int) length)) != -1 && totalLength > 0) {
            totalLength -= read;
            length = (buf.length > totalLength) ? totalLength : buf.length;
        }

        return checkedIn.getChecksum().getValue();
    }

}
