org.snapscript.core.MapState Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of snap Show documentation
Show all versions of snap Show documentation
Dynamic scripting for the JVM
package org.snapscript.core;
import java.util.Iterator;
import java.util.Set;
import org.snapscript.common.Cache;
import org.snapscript.common.CompoundIterator;
import org.snapscript.common.HashCache;
public class MapState implements State {
private final Cache values;
private final Scope scope;
public MapState() {
this(null);
}
public MapState(Scope scope) {
this.values = new HashCache();
this.scope = scope;
}
@Override
public Iterator iterator() {
Set keys = values.keySet();
Iterator inner = keys.iterator();
if(scope != null) {
State state = scope.getState();
Iterator outer = state.iterator();
return new CompoundIterator(inner, outer);
}
return inner;
}
@Override
public Value get(String name) {
Value value = values.fetch(name);
if(value == null && scope != null) {
State state = scope.getState();
if(state == null) {
throw new InternalStateException("Scope for '" + name + "' does not exist");
}
value = state.get(name);
}
return value;
}
@Override
public void add(String name, Value value) {
Value variable = values.fetch(name);
if(variable != null) {
throw new InternalStateException("Variable '" + name + "' already exists");
}
values.cache(name, value);
}
@Override
public String toString() {
return String.valueOf(values);
}
}