Skip to content

Commit

Permalink
Created AtomicList and InMemoryIndex to support key/value stores used…
Browse files Browse the repository at this point in the history
… as searchable Stores
  • Loading branch information
darkfrog26 committed Jul 27, 2024
1 parent 2a34c7b commit 0ff8d35
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
16 changes: 16 additions & 0 deletions core/src/main/scala/lightdb/util/AtomicList.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package lightdb.util

import java.util.Comparator
import java.util.concurrent.ConcurrentSkipListSet

class AtomicList[T <: Comparable[T]](comparator: Option[Comparator[T]]) {
private val set = new ConcurrentSkipListSet[T](comparator.orNull)

def add(value: T): Boolean = set.add(value)

def remove(value: T): Boolean = set.remove(value)

def iterator: Iterator[T] = set.iterator().asScala

def reverseIterator: Iterator[T] = set.descendingIterator().asScala
}
34 changes: 34 additions & 0 deletions core/src/main/scala/lightdb/util/InMemoryIndex.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package lightdb.util

import lightdb.Id
import lightdb.doc.Document

import java.util.Comparator
import java.util.concurrent.ConcurrentHashMap

class InMemoryIndex[Doc <: Document[Doc], V <: Comparable[V]](comparator: Option[Comparator[V]]) {
private val map = new ConcurrentHashMap[V, List[Id[Doc]]]
private val currentValue = new ConcurrentHashMap[Id[Doc], V]
private val sorted = new AtomicList[V](comparator)

def set(id: Id[Doc], value: V): Unit = {
Option(currentValue.get(id)).foreach(previous => remove(id, previous))
map.compute(value, (_, list) => id :: list)
currentValue.put(id, value)
sorted.add(value)
}

def remove(id: Id[Doc], value: V): Unit = {
map.computeIfPresent(value, (_, list) => list.filterNot(_ == id) match {
case Nil => null
case l => l
})
currentValue.remove(id)
sorted.remove(value)
}

def apply(value: V): List[Id[Doc]] = map.getOrDefault(value, Nil)

def ascending: Iterator[V] = sorted.iterator
def descending: Iterator[V] = sorted.reverseIterator
}

0 comments on commit 0ff8d35

Please sign in to comment.