001/*
002 * To change this template, choose Tools | Templates
003 * and open the template in the editor.
004 */
005package org.anarres.qemu.manager;
006
007import java.io.ByteArrayOutputStream;
008
009/**
010 *
011 * @author shevek
012 */
013public class IOBuffer extends ByteArrayOutputStream {
014
015    private static final int SIZE = 4096;
016    private static final int ALLOC = SIZE + SIZE >> 2;
017    private byte[] history = new byte[0];
018
019    public IOBuffer() {
020        super(ALLOC);
021    }
022
023    private void capture() {
024        if (count > SIZE - 256) {
025            this.history = super.toByteArray();
026            super.buf = new byte[ALLOC];
027            super.count = 0;
028        }
029    }
030
031    @Override
032    public synchronized void write(byte[] b, int off, int len) {
033        super.write(b, off, len);
034        capture();
035    }
036
037    @Override
038    public synchronized void write(int b) {
039        super.write(b);
040        capture();
041    }
042
043    @Override
044    public synchronized byte[] toByteArray() {
045        byte[] out = new byte[history.length + count];
046        System.arraycopy(history, 0, out, 0, history.length);
047        System.arraycopy(super.buf, 0, out, history.length, count);
048        return out;
049    }
050}