package ru.yandex.webmaster3.worker.util;

import java.util.Arrays;

/**
 * @author avhaliullin
 */
public class ByteBufferBuilder {
    private byte[] buffer;
    private int length;

    public ByteBufferBuilder(int initialCapacity) {
        buffer = new byte[initialCapacity];
    }

    public void append(byte b) {
        resize(1);
        buffer[length++] = b;
    }

    public void append(byte[] other, int offset, int len) {
        resize(len);
        System.arraycopy(other, offset, buffer, length, len);
        length += len;
    }

    private void resize(int appendingLength) {
        if (buffer.length - length < appendingLength) {
            int newLen = (length + appendingLength) * 2;
            buffer = Arrays.copyOf(buffer, newLen);
        }
    }

    public byte[] getBuffer() {
        return buffer;
    }

    public int getLength() {
        return length;
    }

    public void reset() {
        length = 0;
    }
}
