LBDFactory def createKvDb path String LDBKVStore val dir new File path

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
//LBDFactory
def createKvDb(path: String): LDBKVStore = {
val dir = new File(path)
dir.mkdirs()
val options = new Options()
options.createIfMissing(true)
try {
val db = factory.open(dir, options)
new LDBKVStore(db)
} catch {
case x: Throwable =>
log.error(s"Failed to initialize storage: $x. Please check that directory $path could be accessed " +
s"and is not used by some other active node")
java.lang.System.exit(2)
null
}
}
//KVStore.scala
import org.ergoplatform.utils.ByteArrayUtils
import org.iq80.leveldb.{DB, ReadOptions}
import scala.collection.mutable
trait KVStore extends AutoCloseable {
val firstUnusedPrefix: Byte = 0
type K = Array[Byte]
type V = Array[Byte]
protected val db: DB
def get(key: K): Option[V] =
Option(db.get(key))
//todo: getAll used in tests only, remove
def getAll(cond: (K, V) => Boolean): Seq[(K, V)] = {
val ro = new ReadOptions()
ro.snapshot(db.getSnapshot)
val iter = db.iterator(ro)
try {
iter.seekToFirst()
val bf = mutable.ArrayBuffer.empty[(K, V)]
while (iter.hasNext) {
val next = iter.next()
val key = next.getKey
val value = next.getValue
if (cond(key, value)) bf += (key -> value)
}
bf.toList
} finally {
iter.close()
ro.snapshot().close()
}
}
def getAll: Seq[(K, V)] = getAll((_, _) => true)
def getRange(start: K, end: K): Seq[(K, V)] = {
val ro = new ReadOptions()
ro.snapshot(db.getSnapshot)
val iter = db.iterator(ro)
try {
def check(key:Array[Byte]) = {
if (ByteArrayUtils.compare(key, end) <= 0) {
true
} else {
false
}
}
iter.seek(start)
val bf = mutable.ArrayBuffer.empty[(K, V)]
while (iter.hasNext && check(iter.peekNext.getKey)) {
val next = iter.next()
val key = next.getKey
val value = next.getValue
bf += (key -> value)
}
bf.toList
} finally {
iter.close()
ro.snapshot().close()
}
}
def getOrElse(key: K, default: => V): V =
get(key).getOrElse(default)
def get(keys: Seq[K]): Seq[(K, Option[V])] = {
val bf = mutable.ArrayBuffer.empty[(K, Option[V])]
keys.foreach(k => bf += (k -> get(k)))
bf
}
override def close(): Unit = db.close()
}