/* 
 * E-XML Library:  For XML, XML-RPC, HTTP, and related.
 * Copyright (C) 2002-2008  Elias Ross
 * 
 * genman@noderunner.net
 * http://noderunner.net/~genman
 * 
 * 1025 NE 73RD ST
 * SEATTLE WA 98115
 * USA
 *
 * 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 (at your option) 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.
 * 
 * $Id$
 */

package net.noderunner.http;

import java.io.IOException;
import java.io.OutputStream;

/**
 * An OutputStream wrapper which allows only a certain number of bytes to be
 * output.  This is used in conjunction writing HTTP requests or responses
 * with supplied <code>Content-Length</code> headers.  This stream is
 * unsynchronized.
 *
 * @author Elias Ross
 *
 * @see LimitedInputStream
 *
 */
public class LimitedOutputStream
	extends OutputStream
{

	/**
	 * Number of bytes that can be output.
	 */
	private int remaining;

	/**
	 * The underlying output stream.
	 */
	private OutputStream stream;

	/**
	 * Constructs a limited output stream.
	 *
	 * @param stream must be non-null.
	 * @param lengthLimit limit of bytes of output.
	 *
	 */
	public LimitedOutputStream(OutputStream stream, int lengthLimit) {
		if (stream == null)
			throw new IllegalArgumentException("OutputStream parameter is null");
		this.stream = stream;
		this.remaining = lengthLimit;
	}

	/**
	 * Closes the underlying output stream.  
	 */
	public void close()
		throws IOException
	{
		stream.close();
	}

	/**
	 * Flushes the underlying output stream.  
	 */
	public void flush()
		throws IOException
	{
		stream.flush();
	}

	/**
	 * Writes up to <code>len</code> bytes of data to the output stream,
	 * possibly less if the write limit is reached.
	 */
	public void write(byte b[], int off, int len)
		throws IOException
	{
		if (remaining == 0)
			return;
		if (len > remaining)
			len = remaining;
		stream.write(b, off, len);
		remaining -= len;
	}

	/**
	 * Writes a byte of data to the output stream,
	 * possibly does nothing if the write limit is reached.
	 */
	public void write(int b)
		throws IOException
	{
		if (remaining == 0)
			return;
		stream.write(b);
		remaining--;
	}

  /**
   * Returns a debug string.
   */
	public String toString() {
		return "LimitedOutputStream " + 
			" stream=" + stream +
			" remaining=" + remaining;
	}
}
