view src/luan/LuanTable.java @ 1724:32c6b085bb83

test custom nginx
author Vadim Filimonov <fffilimonov@yandex.ru>
date Thu, 11 Aug 2022 12:18:33 +0200
parents 8d257d56dc42
children b1b1f9a14928
line wrap: on
line source

package luan;

import java.util.Iterator;
import java.util.ListIterator;
import java.util.Map;
import java.util.AbstractMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import java.util.HashSet;
import java.util.ConcurrentModificationException;


public final class LuanTable implements LuanMutable {
	private Map map = null;
	private List list = null;
	private LuanTable metatable = null;
	public LuanClosure closure;
	private boolean immutable = false;

	public LuanTable() {}

	public LuanTable(List list) {
		try {
			list();
			int n = list.size();
			for( int i=0; i<n; i++ ) {
				Object val = list.get(i);
				if( val != null )
					rawPut(i+1,val);
			}
		} catch(LuanException e) {
			throw new RuntimeException(e);
		}
	}

	public LuanTable(Map map) {
		try {
			for( Object stupid : map.entrySet() ) {
				Map.Entry entry = (Map.Entry)stupid;
				Object key = entry.getKey();
				Object value = entry.getValue();
				if( key != null && value != null )
					rawPut(key,value);
			}
		} catch(LuanException e) {
			throw new RuntimeException(e);
		}
	}

	public LuanTable(Set set) {
		try {
			for( Object el : set ) {
				if( el != null )
					rawPut(el,Boolean.TRUE);
			}
		} catch(LuanException e) {
			throw new RuntimeException(e);
		}
	}

	public LuanTable(LuanTable tbl) {
		if( tbl.map != null && !tbl.map.isEmpty() )
			this.map = new LinkedHashMap<Object,Object>(tbl.map);
		if( tbl.rawLength() > 0 )
			this.list = new ArrayList<Object>(tbl.list);
		this.metatable = tbl.metatable;
	}

	@Override public boolean isImmutable() {
		return immutable;
	}

	@Override public void makeImmutable() {
		if(immutable)
			return;
		immutable = true;
		LuanMutable.makeImmutable(map);
		LuanMutable.makeImmutable(list);
		LuanMutable.makeImmutable(metatable);
		LuanMutable.makeImmutable(closure);
	}

	private void checkMutable() throws LuanException {
		if( immutable )
			throw new LuanException("table is immutable");
	}

	public boolean isList() {
		return map==null || map.isEmpty();
	}

	public boolean isMap() {
		return map!=null || list==null;
	}

	public List<Object> asList() {
		return list!=null ? list : Collections.emptyList();
	}

	public Map rawMap() {
		return map!=null ? map : Collections.emptyMap();
	}

	public String toStringLuan(Luan luan) throws LuanException {
		LuanFunction fn = luan.getHandlerFunction("__to_string",this);
		if( fn == null )
			return rawToString();
		return Luan.checkString( Luan.first( fn.call(luan,this) ) );
	}

	public String rawToString() {
		return "table: " + Integer.toHexString(hashCode());
	}

	public Object get(Luan luan,Object key) throws LuanException {
		//checkLuan(luan);
		Object value = rawGet(key);
		if( value != null )
			return value;
		Object h = getHandler(luan,"__index");
		if( h==null )
			return null;
		if( h instanceof LuanFunction ) {
			LuanFunction fn = (LuanFunction)h;
			return Luan.first(fn.call(luan,this,key));
		}
		return luan.index(h,key);
	}

	public Object rawGet(Object key) {
		if( list != null ) {
			Integer iT = Luan.asInteger(key);
			if( iT != null ) {
				int i = iT - 1;
				if( i>=0 && i<list.size() )
					return list.get(i);
			}
		}
		if( map==null )
			return null;
		if( key instanceof Number && !(key instanceof Double) ) {
			Number n = (Number)key;
			key = Double.valueOf(n.doubleValue());
		}
		return map.get(key);
	}

	public void put(Luan luan,Object key,Object value) throws LuanException {
		//checkLuan(luan);
		Object h = getHandler(luan,"__new_index");
		if( h==null || rawGet(key)!=null ) {
			rawPut(key,value);
			return;
		}
		if( h instanceof LuanFunction ) {
			LuanFunction fn = (LuanFunction)h;
			fn.call(luan,this,key,value);
			return;
		}
		if( h instanceof LuanTable ) {
			LuanTable tbl = (LuanTable)h;
			tbl.put(luan,key,value);
			return;
		}
		throw new LuanException("invalid type "+Luan.type(h)+" for metamethod __new_index");
	}

	public Object rawPut(Object key,Object val) throws LuanException {
		checkMutable();
		if( key==null )
			throw new LuanException("table index is nil");
		Integer iT = Luan.asInteger(key);
		if( iT != null ) {
			int i = iT - 1;
			if( list != null || i == 0 ) {
				if( i == list().size() ) {
					if( val != null ) {
						list.add(val);
						mapToList();
					}
					return null;
				} else if( i>=0 && i<list.size() ) {
					Object rtn = list.set(i,val);
					if( val == null ) {
						listToMap(i);
					}
					return rtn;
				}
			}
		}
		if( key instanceof Number && !(key instanceof Double) ) {
			Number n = (Number)key;
			key = Double.valueOf(n.doubleValue());
		}
		if( val == null ) {
			if( map!=null )
				return map.remove(key);
			else
				return null;
		} else {
			if( map==null )
				map = newMap();
			return map.put(key,val);
		}
	}

	private void mapToList() {
		if( map != null ) {
			while(true) {
				Object v = map.remove(Double.valueOf(list.size()+1));
				if( v == null )
					break;
				list.add(v);
			}
		}
	}

	private void listToMap(int from) {
		if( list != null ) {
			while( list.size() > from ) {
				int i = list.size() - 1;
				Object v = list.remove(i);
				if( v != null ) {
					if( map==null )
						map = newMap();
					map.put(i+1,v);
				}
			}
		}
	}

	private List<Object> list() {
		if( list == null ) {
			list = new ArrayList<Object>();
			mapToList();
		}
		return list;
	}

	public void rawInsert(int pos,Object value) throws LuanException {
		checkMutable();
		if( value==null )
			throw new IllegalArgumentException("can't insert a nil value");
		list().add(pos-1,value);
		mapToList();
	}

	public void rawAdd(Object value) throws LuanException {
		checkMutable();
		if( value==null )
			throw new IllegalArgumentException("can't insert a nil value");
		list().add(value);
		mapToList();
	}

	public Object removeFromList(int pos) throws LuanException {
		checkMutable();
		return list().remove(pos-1);
	}

	public void rawSort(Comparator<Object> cmp) throws LuanException {
		checkMutable();
		Collections.sort(list(),cmp);
	}

	public int length(Luan luan) throws LuanException {
		LuanFunction fn = luan.getHandlerFunction("__len",this);
		if( fn != null ) {
			return (Integer)Luan.first(fn.call(luan,this));
		}
		return rawLength();
	}

	public int rawLength() {
		return list==null ? 0 : list.size();
	}

	public Iterable<Map.Entry> iterable(Luan luan) throws LuanException {
		final Iterator<Map.Entry> iter = iterator(luan);
		return new Iterable<Map.Entry>() {
			public Iterator<Map.Entry> iterator() {
				return iter;
			}
		};
	}

	public Iterable<Map.Entry> rawIterable() {
		final Iterator<Map.Entry> iter = rawIterator();
		return new Iterable<Map.Entry>() {
			public Iterator<Map.Entry> iterator() {
				return iter;
			}
		};
	}

	public Iterator<Map.Entry> iterator(final Luan luan) throws LuanException {
		LuanFunction h = luan.getHandlerFunction("__pairs",this);
		if( h == null )
			return rawIterator();
		final LuanFunction fn = pairs(luan,h);
		return new Iterator<Map.Entry>() {
			private Map.Entry<Object,Object> next = getNext();

			private Map.Entry<Object,Object> getNext() {
				try {
					Object obj = fn.call(luan);
					if( obj==null )
						return null;
					Object[] a = (Object[])obj;
					if( a.length == 0 || a[0]==null )
						return null;
					return new AbstractMap.SimpleEntry<Object,Object>(a[0],a[1]);
				} catch(LuanException e) {
					throw new LuanRuntimeException(e);
				}
			}

			public boolean hasNext() {
				return next != null;
			}

			public Map.Entry<Object,Object> next() {
				Map.Entry<Object,Object> rtn = next;
				next = getNext();
				return rtn;
			}

			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}

	public LuanFunction pairs(Luan luan) throws LuanException {
		return pairs( luan, luan.getHandlerFunction("__pairs",this) );
	}

	private LuanFunction pairs(Luan luan,LuanFunction fn) throws LuanException {
		if( fn==null )
			return rawPairs();
		Object obj = Luan.first(fn.call(luan,this));
		if( !(obj instanceof LuanFunction) )
			throw new LuanException( "metamethod __pairs should return function but returned " + Luan.type(obj) );
		return (LuanFunction)obj;
	}

	private LuanFunction rawPairs() {
		return new LuanFunction() {
			final Iterator<Map.Entry> iter = rawIterator();

			@Override public Object[] call(Luan luan,Object[] args) throws LuanException {
				if( !iter.hasNext() )
					return LuanFunction.NOTHING;
				try {
					Map.Entry<Object,Object> entry = iter.next();
					return new Object[]{entry.getKey(),entry.getValue()};
				} catch(ConcurrentModificationException e) {
					throw new LuanException("table modified while iterating");
				}
			}
		};
	}

	public Iterator<Map.Entry> rawIterator() {
		if( list == null ) {
			if( map == null )
				return Collections.<Map.Entry>emptyList().iterator();
			return map.entrySet().iterator();
		}
		if( map == null )
			return listIterator();
		return new Iterator<Map.Entry>() {
			Iterator<Map.Entry> iter = listIterator();
			boolean isList = true;

			public boolean hasNext() {
				boolean b = iter.hasNext();
				if( !b && isList ) {
					iter = map.entrySet().iterator();
					isList = false;
					b = iter.hasNext();
				}
				return b;
			}

			public Map.Entry<Object,Object> next() {
				return iter.next();
			}

			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}

	private Iterator<Map.Entry> listIterator() {
		if( list == null )
			return Collections.<Map.Entry>emptyList().iterator();
		final ListIterator iter = list.listIterator();
		return new Iterator<Map.Entry>() {

			public boolean hasNext() {
				return iter.hasNext();
			}

			public Map.Entry<Object,Object> next() {
				Integer key = iter.nextIndex()+1;
				return new AbstractMap.SimpleEntry<Object,Object>(key,iter.next());
			}

			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}

	public LuanTable rawSubList(int from,int to) {
		LuanTable tbl = new LuanTable();
		tbl.list = new ArrayList<Object>(list().subList(from-1,to-1));
		return tbl;
	}

	public LuanTable getMetatable() {
		return metatable;
	}

	public void setMetatable(LuanTable metatable) throws LuanException {
		checkMutable();
		this.metatable = metatable;
	}

	public Object getHandler(Luan luan,String op) throws LuanException {
		return metatable==null ? null : luan==null ? metatable.rawGet(op) : metatable.get(luan,op);
	}

	private static Map<Object,Object> newMap() {
		return new LinkedHashMap<Object,Object>();
	}

	public boolean isSet() throws LuanException {
		for( Map.Entry<Object,Object> entry : rawIterable() ) {
			if( !entry.getValue().equals(Boolean.TRUE) )
				return false;
		}
		return true;
	}

	public Set<Object> asSet() throws LuanException {
		Set<Object> set = new HashSet<Object>();
		for( Map.Entry<Object,Object> entry : rawIterable() ) {
			set.add(entry.getKey());
		}
		return set;
	}

	public Map<Object,Object> asMap() throws LuanException {
		Map<Object,Object> map = newMap();
		for( Map.Entry<Object,Object> entry : rawIterable() ) {
			map.put(entry.getKey(),entry.getValue());
		}
		return map;
	}

	public void rawClear() throws LuanException {
		checkMutable();
		map = null;
		list = null;
	}

	public int hashValue() {
		int n = 99;
		if( map != null )
			n ^= map.hashCode();
		if( list != null )
			n ^= list.hashCode();
		return n;
	}

	public boolean isEmpty() {
		return (map==null || map.isEmpty()) && (list==null || list.isEmpty());
	}

	public int rawSize() {
		int n = 0;
		if( map != null )
			n += map.size();
		if( list != null )
			n += list.size();
		return n;
	}

	public Object remove(Object key) throws LuanException {
		checkMutable();
		Object old = rawGet(key);
		rawPut(key,null);
		return old;
	}

	protected void finalize() throws Throwable {
		Object h = getHandler(null,"__gc");
		if( h != null ) {
			LuanFunction fn = Luan.checkFunction(h);
			fn.call(new Luan(),this);  // ??? should be immutable
		}
		super.finalize();
	}

	public LuanFunction fn(Luan luan,String fnName) throws LuanException {
		return (LuanFunction)get(luan,fnName);
	}

	public static void debug(LuanTable table) {
		System.out.println("isMap "+table.isMap());
	}
}