Mercurial Hosting > luan
diff src/luan/DeepCloner.java @ 77:4bf3d0c0b6b9
make LuanState cloneable
git-svn-id: https://luan-java.googlecode.com/svn/trunk@78 21e917c8-12df-6dd8-5cb6-c86387c605b9
author | fschmidt@gmail.com <fschmidt@gmail.com@21e917c8-12df-6dd8-5cb6-c86387c605b9> |
---|---|
date | Fri, 15 Feb 2013 09:55:17 +0000 |
parents | |
children | 7c08b611125d |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/luan/DeepCloner.java Fri Feb 15 09:55:17 2013 +0000 @@ -0,0 +1,34 @@ +package luan; + +import java.util.Map; +import java.util.IdentityHashMap; + + +public final class DeepCloner { + private final Map<Object,Object> cloned = new IdentityHashMap<Object,Object>(); + + public <T extends DeepCloneable<T>> T deepClone(T obj) { + @SuppressWarnings("unchecked") + T rtn = (T)cloned.get(obj); + if( rtn == null ) { + rtn = obj.shallowClone(); + cloned.put(obj,rtn); + obj.deepenClone(rtn,this); + } + return rtn; + } + + public void deepenClone(Object[] a) { + for( int i=0; i<a.length; i++ ) { + a[i] = get(a[i]); + } + } + + public Object get(Object obj) { + if( !(obj instanceof DeepCloneable) ) + return obj; + @SuppressWarnings("unchecked") + DeepCloneable dc = deepClone((DeepCloneable)obj); + return dc; + } +}