001/**
002 * Java Web Archive Toolkit - Software to read and validate ARC, WARC
003 * and GZip files. (http://jwat.org/)
004 * Copyright 2011-2012 Netarkivet.dk (http://netarkivet.dk/)
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.jwat.common;
019
020import java.io.ByteArrayOutputStream;
021
022/**
023 * A ByteArrayOutputStream with unread capability.
024 *
025 * @author nicl
026 */
027public class ByteArrayOutputStreamWithUnread extends ByteArrayOutputStream {
028
029    /**
030     * Construct an object without specifying an buffer size.
031     */
032    public ByteArrayOutputStreamWithUnread() {
033        super();
034    }
035
036    /**
037     * Construct an object with the specifying buffer size.
038     * @param size buffer size
039     */
040    public ByteArrayOutputStreamWithUnread(int size)  {
041        super(size);
042    }
043
044    /**
045     * Unread a byte by removing it from the buffer.
046     * @param b the int value whose low-order byte is to be unread.
047     */
048    public void unread(int b) {
049        if (count == 0) {
050            throw new IllegalArgumentException("Can not unread more that buffered!");
051        }
052        --count;
053    }
054
055    /**
056     * Unread an array of bytes by removing them from the  buffer.
057     * @param b the byte array to push back
058     */
059    public void unread(byte[] b) {
060        if (count < b.length) {
061            throw new IllegalArgumentException("Can not unread more that buffered!");
062        }
063        count -= b.length;
064    }
065
066    /**
067     * Unread a portion of an array of bytes by removing them from the buffer.
068     * @param b the byte array to unread.
069     * @param off the start offset of the data.
070     * @param len the number of bytes to unread.
071     */
072    public void unread(byte[] b, int off, int len) {
073        if (count < len) {
074            throw new IllegalArgumentException("Can not unread more that buffered!");
075        }
076        count -= len;
077    }
078
079}