Skip to content

Instantly share code, notes, and snippets.

@Asmageddon
Created November 4, 2012 20:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Asmageddon/4013485 to your computer and use it in GitHub Desktop.
Save Asmageddon/4013485 to your computer and use it in GitHub Desktop.
Deep copy of anything for Haxe
package com.asmoprime.utils;
/**
* ...
* @author Asmageddon
*/
class Copy {
/**
* Deep copy of anything using reflection (so don't hope for much performance)
**/
public static function copy<T>( v:T ) : T {
if (!Reflect.isObject(v)) { // simple type
return v;
}
else if (Std.is(v, String)) { // string
return v;
}
else if(Std.is( v, Array )) { // array
var result = Type.createInstance(Type.getClass(v), []);
untyped {
for( ii in 0...v.length ) {
result.push(copy(v[ii]));
}
}
return result;
}
else if(Std.is( v, Hash )) { // hashmap
var result = Type.createInstance(Type.getClass(v), []);
untyped {
var keys : Iterator<String> = v.keys();
for( key in keys ) {
result.set(key, copy(v.get(key)));
}
}
return result;
}
else if(Std.is( v, IntHash )) { // integer-indexed hashmap
var result = Type.createInstance(Type.getClass(v), []);
untyped {
var keys : Iterator<Int> = v.keys();
for( key in keys ) {
result.set(key, copy(v.get(key)));
}
}
return result;
}
else if(Std.is( v, List )) { // list
//List would be copied just fine without this special case, but I want to avoid going recursive
var result = Type.createInstance(Type.getClass(v), []);
untyped {
var iter : Iterator<Dynamic> = v.iterator();
for( ii in iter ) {
result.add(ii);
}
}
return result;
}
else if(Type.getClass(v) == null) { // anonymous object
var obj : Dynamic = {};
for( ff in Reflect.fields(v) ) {
Reflect.setField(obj, ff, copy(Reflect.field(v, ff)));
}
return obj;
}
else { // class
var obj = Type.createEmptyInstance(Type.getClass(v));
for(ff in Reflect.fields(v)) {
Reflect.setField(obj, ff, copy(Reflect.field(v, ff)));
}
return obj;
}
return null;
}
}
@thomasuster
Copy link

If someone's looking for something more recent.
https://github.com/thomasuster/cloner

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment