package jp.progressive.rudp;

import java.nio.ByteBuffer;

public class DatagramUtils {
    public static final void putUInt24(ByteBuffer buffer, int value) {
	buffer.put((byte) (value % (1 << 8)));
	buffer.put((byte) (value % (1 << 16) / (1 << 8)));
	buffer.put((byte) (value / (1 << 16)));
    }

    public static final void putUInt24(byte[] bytes, int index, int value) {
	bytes[index + 0] = (byte) (value % (1 << 8));
	bytes[index + 1] = (byte) (value % (1 << 16) / (1 << 8));
	bytes[index + 2] = (byte) (value / (1 << 16));
    }

    public static final int getUInt24(ByteBuffer buffer) {
	int value = buffer.get() & 0xFF;
	value += (buffer.get() & 0xFF) * (1 << 8);
	value += (buffer.get() & 0xFF) * (1 << 16);
	return value;
    }

    public static final byte[] toArray(ByteBuffer buffer) {
	if (buffer.hasArray()) {
	    return buffer.array();
	}
	byte[] bytes = new byte[buffer.limit() - buffer.position()];
	for (int i = 0, len = bytes.length; i < len; i++) {
	    bytes[i] = buffer.get();
	}
	return bytes;
    }

    private DatagramUtils() {
    }
}
