/*
 * JORAM: Java(TM) Open Reliable Asynchronous Messaging
 * Copyright (C) 2008 - 2022 ScalAgent Distributed Technologies
 * Copyright (C) 2008 CNES
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA.
 *
 * Initial developer(s): ScalAgent Distributed Technologies
 * Contributor(s):
 */
package org.ow2.joram.mom.amqp.marshalling;

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

public class TruncatedInputStream extends FilterInputStream {
  private final long limit;
  private long counter = 0L;
  private long mark = 0L;

  public TruncatedInputStream(InputStream in, long limit) {
    super(in);
    this.limit = limit;
  }

  private static long min(long a, long b) {
    return a > b ? b : a;
  }

  @Override
  public int available() throws IOException {
    return (int) min(limit - counter, super.available());
  }

  @Override
  public synchronized void mark(int readlimit) {
    super.mark(readlimit);
    mark = counter;
  }

  @Override
  public int read() throws IOException {
    if (counter < limit) {
      int result = super.read();
      if (result >= 0)
        counter++;
      return result;
    } else {
      return -1;
    }
  }

  @Override
  public int read(byte[] b) throws IOException {
    return read(b, 0, b.length);
  }

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

    if (limit > counter) {
      int result = super.read(b, off, (int) min(len, limit - counter));
      if (result > 0)
        counter += result;
      return result;
    } else {
      return -1;
    }
  }

  @Override
  public synchronized void reset() throws IOException {
    super.reset();
    counter = mark;
  }

  @Override
  public long skip(long n) throws IOException {
    long result = super.skip(min(n, limit - counter));
    counter += result;
    return result;
  }
}
