001package net.bramp.ffmpeg.io;
002
003import java.io.FilterInputStream;
004import java.io.IOException;
005import java.io.InputStream;
006import java.util.zip.CRC32;
007
008/**
009 * Calculates the CRC32 for all bytes read through the input stream. Using the java.util.zip.CRC32
010 * class to calculate the checksum.
011 */
012public class CRC32InputStream extends FilterInputStream {
013
014  final CRC32 crc = new CRC32();
015
016  /** Constructs a CRC32InputStream wrapping the given input stream. */
017  public CRC32InputStream(InputStream in) {
018    super(in);
019  }
020
021  /** Resets the CRC32 checksum to its initial value. */
022  public void resetCrc() {
023    crc.reset();
024  }
025
026  public long getValue() {
027    return crc.getValue();
028  }
029
030  @Override
031  public int read() throws IOException {
032    int b = in.read();
033    if (b >= 0) {
034      crc.update(b);
035    }
036    return b;
037  }
038
039  @Override
040  public int read(byte[] b) throws IOException {
041    int len = in.read(b);
042    crc.update(b, 0, len);
043    return len;
044  }
045
046  @Override
047  public int read(byte[] b, int off, int len) throws IOException {
048    int actual = in.read(b, off, len);
049    crc.update(b, off, actual);
050    return actual;
051  }
052
053  @Override
054  public long skip(long n) throws IOException {
055    long i = 0;
056    while (i < n) {
057      read();
058      i++;
059    }
060    return i;
061  }
062
063  @Override
064  public synchronized void mark(int readlimit) {
065    throw new UnsupportedOperationException("mark not supported");
066  }
067
068  @Override
069  public synchronized void reset() throws IOException {
070    throw new UnsupportedOperationException("reset not supported");
071  }
072
073  @Override
074  public boolean markSupported() {
075    return false;
076  }
077}