All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.streamnative.pulsar.handlers.kop.storage.ByteArrayStream Maven / Gradle / Ivy

There is a newer version: 4.0.0.4
Show newest version
/**
 * Copyright (c) 2019 - 2024 StreamNative, Inc.. All Rights Reserved.
 */
package io.streamnative.pulsar.handlers.kop.storage;

import java.io.IOException;
import lombok.Getter;

public final class ByteArrayStream {

    @Getter
    private final byte[] writeBuffer;
    private int position = 0;

    public ByteArrayStream(int size) {
        writeBuffer = new byte[size];
    }

    public void writeShort(short v) throws IOException {
        if (position + 2 > capacity()) {
            throw new IOException("Buffer overflow in writeShort, position: " + position + ", capacity: " + capacity()
                + ", value: " + v);
        }
        writeBuffer[position] = (byte) (v >>> 8);
        writeBuffer[position + 1] = (byte) (v);
        position += 2;
    }

    public void writeInt(int v) throws IOException {
        if (position + 4 > capacity()) {
            throw new IOException("Buffer overflow in writeInt, position: " + position + ", capacity: " + capacity()
                + ", value: " + v);
        }
        writeBuffer[position] = (byte) (v >>> 24);
        writeBuffer[position + 1] = (byte) (v >>> 16);
        writeBuffer[position + 2] = (byte) (v >>> 8);
        writeBuffer[position + 3] = (byte) (v);
        position += 4;
    }

    public void writeLong(long v) throws IOException {
        if (position + 8 > capacity()) {
            throw new IOException("Buffer overflow in writeLong, position: " + position + ", capacity: " + capacity()
                + ", value: " + v);
        }
        writeBuffer[position] = (byte) (v >>> 56);
        writeBuffer[position + 1] = (byte) (v >>> 48);
        writeBuffer[position + 2] = (byte) (v >>> 40);
        writeBuffer[position + 3] = (byte) (v >>> 32);
        writeBuffer[position + 4] = (byte) (v >>> 24);
        writeBuffer[position + 5] = (byte) (v >>> 16);
        writeBuffer[position + 6] = (byte) (v >>>  8);
        writeBuffer[position + 7] = (byte) (v);
        position += 8;
    }

    public void write(byte[] bytes) throws IOException {
        if (position + bytes.length > capacity()) {
            throw new IOException("Buffer overflow in write, position: " + position + ", capacity: " + capacity()
                + ", bytes length: " + bytes.length);
        }
        System.arraycopy(bytes, 0, writeBuffer, position, bytes.length);
        position += bytes.length;
    }

    private int capacity() {
        return writeBuffer.length;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy