
package de.ivu.elect.util;

import java.io.IOException;
import java.io.InputStream;

public class LimitedInputStream extends InputStream {

  private final InputStream inputStream;

  private final int maxBytesVorschau;

  int count = 0;

  public LimitedInputStream(InputStream inputStream, int maxBytesVorschau) {
    super();

    this.inputStream = inputStream;
    this.maxBytesVorschau = maxBytesVorschau;
  }

  @Override
  public int read() throws IOException {
    if (count < maxBytesVorschau) {
      count++;
      return inputStream.read();
    }

    return -1;
  }

  @Override
  public int read(byte[] b) throws IOException {
    if (count < maxBytesVorschau) {
      count += b.length;
      return inputStream.read(b);
    }
    return -1;
  }

  @Override
  public int read(byte[] b, int off, int len) throws IOException {
    int length = len;

    if (length > maxBytesVorschau) {
      length = maxBytesVorschau;
    }

    if (count < maxBytesVorschau) {
      count += length;

      return inputStream.read(b, off, length);
    }

    return -1;
  }

  @Override
  public void close() throws IOException {
    inputStream.close();
  }

  @Override
  public int available() throws IOException {
    return inputStream.available();
  }

  @Override
  public synchronized void mark(int readlimit) {
    inputStream.mark(readlimit);
  }

  @Override
  public boolean markSupported() {
    return inputStream.markSupported();
  }

  @Override
  public synchronized void reset() throws IOException {
    inputStream.reset();
  }

  @Override
  public long skip(long n) throws IOException {
    return inputStream.skip(n);
  }
}
