package mcmas.utils;

import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
import java.security.InvalidParameterException;

import org.jocl.Sizeof;

public class BuffersUtils {
	
	public static long sizeOf(Buffer buffer) {
		if (buffer instanceof ByteBuffer || buffer instanceof CharBuffer) {
			return buffer.capacity() * Sizeof.cl_char;
		} else if (buffer instanceof ShortBuffer) {
			return buffer.capacity() * Sizeof.cl_short;
		} else if (buffer instanceof IntBuffer) {
			return buffer.capacity() * Sizeof.cl_int;
		} else if (buffer instanceof LongBuffer) {
			return buffer.capacity() * Sizeof.cl_long;
		} else if (buffer instanceof FloatBuffer) {
			return buffer.capacity() * Sizeof.cl_float;
		} else if (buffer instanceof DoubleBuffer) {
			return buffer.capacity() * Sizeof.cl_double;
		} else {
			throw new InvalidParameterException("Unknown buffer type: " + buffer.getClass());
		}
	}
	
	public static ByteBuffer directByteBuffer(int size) {
		return ByteBuffer.allocateDirect(size);
	}
	
	public static ShortBuffer directShortBuffer(int size) {
		return ByteBuffer.allocateDirect(size * Sizeof.cl_short).asShortBuffer();
	}
	
	public static IntBuffer directIntBuffer(int size) {
		return ByteBuffer.allocateDirect(size * Sizeof.cl_int).asIntBuffer();
	}
	
	public static LongBuffer directLongBuffer(int size) {
		return ByteBuffer.allocateDirect(size * Sizeof.cl_long).asLongBuffer();
	}
	
	public static FloatBuffer directFloatBuffer(int size) {
		return ByteBuffer.allocateDirect(size * Sizeof.cl_float).asFloatBuffer();
	}
	
	public static DoubleBuffer directDoubleBuffer(int size) {
		return ByteBuffer.allocateDirect(size * Sizeof.cl_double).asDoubleBuffer();
	}
	
	
}
