view core/src/luan/modules/BinaryLuan.java @ 510:2da0bcb979b5

better error messages
author Franklin Schmidt <fschmidt@gmail.com>
date Fri, 22 May 2015 02:28:15 -0600
parents e3b0846dc2ef
children 473e456444ff
line wrap: on
line source

package luan.modules;

import luan.Luan;
import luan.LuanState;
import luan.LuanTable;
import luan.LuanFunction;
import luan.LuanException;
import luan.LuanMethod;
import luan.LuanBit;


public final class BinaryLuan {

	public static Object __index(LuanBit bit,final byte[] binary,Object key) throws LuanException {
		LuanState luan = bit.luan;
		LuanTable mod = (LuanTable)PackageLuan.require(luan,"luan:Binary");
		Object obj = mod.get(luan,key);
		if( obj instanceof LuanFunction ) {
			final LuanFunction fn = (LuanFunction)obj;
			return new LuanFunction() {
				@Override public Object call(LuanState luan,Object[] args) throws LuanException {
					Object[] a = new Object[args.length+1];
					a[0] = binary;
					System.arraycopy(args,0,a,1,args.length);
					return fn.call(luan,a);
				}
			};
		}
		if( bit.el != null )
			throw bit.exception( "invalid index for binary in '"+bit.el.text()+"'" ) ;
		else
			throw bit.exception( "invalid index for binary") ;
	}

	static int start(byte[] binary,int i) {
		int len = binary.length;
		return i==0 ? 0 : i > 0 ? Math.min(i-1,len) : Math.max(len+i,0);
	}

	static int start(byte[] binary,Integer i,int dflt) {
		return i==null ? dflt : start(binary,i);
	}

	static int end(byte[] binary,int i) {
		int len = binary.length;
		return i==0 ? 0 : i > 0 ? Math.min(i,len) : Math.max(len+i+1,0);
	}

	static int end(byte[] binary,Integer i,int dflt) {
		return i==null ? dflt : end(binary,i);
	}

	@LuanMethod public static Byte[] byte_(LuanState luan,byte[] binary,Integer i,Integer j) throws LuanException {
		Utils.checkNotNull(luan,binary);
		int start = start(binary,i,1);
		int end = end(binary,j,start+1);
		Byte[] bytes = new Byte[end-start];
		for( int k=0; k<bytes.length; k++ ) {
			bytes[k] = binary[start+k];
		}
		return bytes;
	}

	@LuanMethod public static byte[] binary(byte... bytes) {
		return bytes;
	}

	public static String to_string(byte[] binary) {
		return new String(binary);
	}

}