diff --git a/ethereumj-core/src/main/java/org/ethereum/db/ByteArrayWrapper.java b/ethereumj-core/src/main/java/org/ethereum/db/ByteArrayWrapper.java new file mode 100644 index 00000000..287f855e --- /dev/null +++ b/ethereumj-core/src/main/java/org/ethereum/db/ByteArrayWrapper.java @@ -0,0 +1,45 @@ +package org.ethereum.db; + +import java.util.Arrays; + +/** + * www.ethereumJ.com + * + * @author: Roman Mandeleil + * Created on: 11/06/2014 15:02 + */ + +public class ByteArrayWrapper { + + private final byte[] data; + + public ByteArrayWrapper(byte[] data) + { + if (data == null) + { + throw new NullPointerException(); + } + this.data = data; + } + + @Override + public boolean equals(Object other) + { + if (!(other instanceof ByteArrayWrapper)) + { + return false; + } + return Arrays.equals(data, ((ByteArrayWrapper)other).data); + } + + @Override + public int hashCode() + { + return Arrays.hashCode(data); + } + + + public byte[] getData() { + return data; + } +} diff --git a/ethereumj-core/src/main/java/org/ethereum/db/TrackDatabase.java b/ethereumj-core/src/main/java/org/ethereum/db/TrackDatabase.java new file mode 100644 index 00000000..221ec255 --- /dev/null +++ b/ethereumj-core/src/main/java/org/ethereum/db/TrackDatabase.java @@ -0,0 +1,76 @@ +package org.ethereum.db; + +import java.util.HashMap; +import java.util.Map; + +/** + * www.ethereumJ.com + * + * @author: Roman Mandeleil + * Created on: 11/06/2014 14:09 + */ + +public class TrackDatabase { + + private Database db; + + private boolean trackingChanges; + private Map changes; + private Map deletes; + + public TrackDatabase(Database db) { + this.db = db; + } + + + public void startTrack(){ + changes = new HashMap<>(); + deletes = new HashMap<>(); + trackingChanges = true; + } + + public void commitTrack(){ + for(ByteArrayWrapper key : changes.keySet()){ + db.put(key.getData(), changes.get(key)); + } + changes = null; + trackingChanges = false; + } + + public void rollbackTrack(){ + changes = new HashMap<>(); + deletes = new HashMap<>(); + changes = null; + trackingChanges = false; + } + + public void put(byte[] key, byte[] value) { + if (trackingChanges){ + changes.put( new ByteArrayWrapper(key) , value); + } else { + db.put(key, value); + } + } + + public byte[] get(byte[] key) { + if(trackingChanges){ + ByteArrayWrapper wKey = new ByteArrayWrapper(key); + if (deletes.get(wKey) != null) return null; + if (changes.get(wKey) != null) return changes.get(wKey); + return db.get(key); + } + return db.get(key); + } + + /** Delete object (key) from db **/ + public void delete(byte[] key) { + if (trackingChanges){ + ByteArrayWrapper wKey = new ByteArrayWrapper(key); + deletes.put(wKey, null); + } else { + db.delete(key); + } + } + + +}