namespaces.scala 1.11 KB
Newer Older
Kunshan Wang's avatar
Kunshan Wang committed
1 2 3 4 5 6 7 8 9 10
package uvm

abstract class Namespace[T <: Identified] {
  def apply(id: Int): T
  def apply(name: String): T

  def get(id: Int): Option[T]
  def get(name: String): Option[T]

  def add(obj: T): Unit
Kunshan Wang's avatar
Kunshan Wang committed
11 12
  
  def all: Iterable[T]
Kunshan Wang's avatar
Kunshan Wang committed
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
}

class SimpleNamespace[T <: Identified] extends Namespace[T] {
  private type MapType[K, V] = collection.mutable.HashMap[K, V]

  private val idMap = new MapType[Int, T]()
  private val nameMap = new MapType[String, T]()

  def apply(id: Int): T = idMap(id)
  def apply(name: String): T = nameMap(name)

  def get(id: Int): Option[T] = idMap.get(id)
  def get(name: String): Option[T] = nameMap.get(name)

  def add(obj: T): Unit = {
    for (obj2 <- get(obj.id)) {
      throw new NameConflictException(
        "Object %s ID-conflicts with %s".format(obj.repr, obj2.repr))
    }

    for (name <- obj.name; obj2 <- get(name)) {
      throw new NameConflictException(
        "Object %s name-conflicts with %s".format(obj.repr, obj2.repr))
    }

    idMap.put(obj.id, obj)
    obj.name match {
      case None =>
      case Some(name) => nameMap.put(name, obj)
    }
  }
Kunshan Wang's avatar
Kunshan Wang committed
44 45
  
  def all = idMap.values
Kunshan Wang's avatar
Kunshan Wang committed
46
}