2022-03-12 16:18:12 +00:00
|
|
|
package lib;
|
|
|
|
|
|
|
|
import haxe.Serializer;
|
|
|
|
import haxe.Unserializer;
|
|
|
|
import kernel.fs.FS;
|
|
|
|
import haxe.ds.StringMap;
|
|
|
|
|
|
|
|
/**
|
|
|
|
Key value store with persistence.
|
|
|
|
**/
|
|
|
|
class KVStore {
|
|
|
|
private var kvStore: StringMap<Dynamic> = new StringMap();
|
|
|
|
private final namespace:String;
|
|
|
|
|
|
|
|
public function new(namespace: String) {
|
|
|
|
this.namespace = namespace;
|
|
|
|
}
|
|
|
|
|
|
|
|
private static function getNamespaceFile(namespace: String): String {
|
2023-03-27 22:55:23 +00:00
|
|
|
return '/var/ns/$namespace';
|
2022-03-12 16:18:12 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public function load() {
|
2023-03-27 22:55:23 +00:00
|
|
|
var nsFile = getNamespaceFile(this.namespace);
|
|
|
|
if (FS.exists(nsFile)){
|
|
|
|
var handle = FS.openRead(nsFile);
|
2022-03-12 16:18:12 +00:00
|
|
|
parseFile(handle.readAll());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public function save() {
|
|
|
|
var handle = FS.openWrite(getNamespaceFile(this.namespace));
|
|
|
|
|
|
|
|
handle.write(Serializer.run(this.kvStore));
|
|
|
|
|
|
|
|
handle.close();
|
|
|
|
}
|
|
|
|
|
|
|
|
private function parseFile(content: String) {
|
|
|
|
var unserializer = new Unserializer(content);
|
|
|
|
this.kvStore = unserializer.unserialize();
|
|
|
|
}
|
|
|
|
|
|
|
|
public inline function set(key: String, value: Dynamic) {
|
|
|
|
this.kvStore.set(key,value);
|
|
|
|
}
|
|
|
|
|
|
|
|
public inline function get<T>(key: String): Null<T> {
|
|
|
|
return this.kvStore.get(key);
|
|
|
|
}
|
|
|
|
|
|
|
|
public inline function exists(key: String): Bool {
|
|
|
|
return this.kvStore.exists(key);
|
|
|
|
}
|
|
|
|
|
|
|
|
public inline function clear() {
|
|
|
|
this.kvStore.clear();
|
|
|
|
}
|
|
|
|
|
|
|
|
public inline function remove(key: String): Bool {
|
|
|
|
return this.kvStore.remove(key);
|
|
|
|
}
|
|
|
|
|
|
|
|
public inline function keys(): Iterator<String> {
|
|
|
|
return this.kvStore.keys();
|
|
|
|
}
|
|
|
|
|
|
|
|
public inline function keyValueIterator():KeyValueIterator<String, Dynamic> {
|
|
|
|
return this.kvStore.keyValueIterator();
|
|
|
|
}
|
|
|
|
}
|