diff options
Diffstat (limited to 'core/src/main/scala/forge/util')
-rw-r--r-- | core/src/main/scala/forge/util/Args.scala | 9 | ||||
-rw-r--r-- | core/src/main/scala/forge/util/Labelled.scala | 8 | ||||
-rw-r--r-- | core/src/main/scala/forge/util/MultiBiMap.scala | 47 | ||||
-rw-r--r-- | core/src/main/scala/forge/util/OSet.scala | 107 | ||||
-rw-r--r-- | core/src/main/scala/forge/util/PathRef.scala | 57 |
5 files changed, 228 insertions, 0 deletions
diff --git a/core/src/main/scala/forge/util/Args.scala b/core/src/main/scala/forge/util/Args.scala new file mode 100644 index 00000000..23102572 --- /dev/null +++ b/core/src/main/scala/forge/util/Args.scala @@ -0,0 +1,9 @@ +package forge.util + +class Args(val args: IndexedSeq[_], val dest: ammonite.ops.Path){ + def length = args.length + def apply[T](index: Int): T = { + if (index >= 0 && index < args.length) args(index).asInstanceOf[T] + else throw new IndexOutOfBoundsException(s"Index $index outside of range 0 - ${args.length}") + } +} diff --git a/core/src/main/scala/forge/util/Labelled.scala b/core/src/main/scala/forge/util/Labelled.scala new file mode 100644 index 00000000..a79d2d93 --- /dev/null +++ b/core/src/main/scala/forge/util/Labelled.scala @@ -0,0 +1,8 @@ +package forge.util + +import forge.Target +import play.api.libs.json.Format + +case class Labelled[T](target: Target[T], + format: Format[T], + segments: Seq[String]) diff --git a/core/src/main/scala/forge/util/MultiBiMap.scala b/core/src/main/scala/forge/util/MultiBiMap.scala new file mode 100644 index 00000000..cb6ff280 --- /dev/null +++ b/core/src/main/scala/forge/util/MultiBiMap.scala @@ -0,0 +1,47 @@ +package forge.util + +import scala.collection.mutable + +/** + * A map from keys to collections of values: you can assign multiple values + * to any particular key. Also allows lookups in both directions: what values + * are assigned to a key or what key a value is assigned ti. + */ +trait MultiBiMap[K, V]{ + def containsValue(v: V): Boolean + def lookupKey(k: K): OSet[V] + def lookupValue(v: V): K + def lookupValueOpt(v: V): Option[K] + def add(k: K, v: V): Unit + def removeAll(k: K): OSet[V] + def addAll(k: K, vs: TraversableOnce[V]): Unit + def keys(): Iterator[K] + def values(): Iterator[OSet[V]] +} +object MultiBiMap{ + class Mutable[K, V]() extends MultiBiMap[K, V]{ + private[this] val valueToKey = mutable.LinkedHashMap.empty[V, K] + private[this] val keyToValues = mutable.LinkedHashMap.empty[K, OSet.Mutable[V]] + def containsValue(v: V) = valueToKey.contains(v) + def lookupKey(k: K) = keyToValues(k) + def lookupValue(v: V) = valueToKey(v) + def lookupValueOpt(v: V) = valueToKey.get(v) + def add(k: K, v: V): Unit = { + valueToKey(v) = k + keyToValues.getOrElseUpdate(k, new OSet.Mutable[V]()).append(v) + } + def removeAll(k: K): OSet[V] = keyToValues.get(k) match { + case None => OSet() + case Some(vs) => + vs.foreach(valueToKey.remove) + + keyToValues.remove(k) + vs + } + def addAll(k: K, vs: TraversableOnce[V]): Unit = vs.foreach(this.add(k, _)) + + def keys() = keyToValues.keysIterator + + def values() = keyToValues.valuesIterator + } +} diff --git a/core/src/main/scala/forge/util/OSet.scala b/core/src/main/scala/forge/util/OSet.scala new file mode 100644 index 00000000..43743cdc --- /dev/null +++ b/core/src/main/scala/forge/util/OSet.scala @@ -0,0 +1,107 @@ +package forge.util + + +import play.api.libs.json._ + +import scala.collection.mutable + +/** + * A collection with enforced uniqueness, fast contains and deterministic + * ordering. Raises an exception if a duplicate is found; call + * `toSeq.distinct` if you explicitly want to make it swallow duplicates + */ +trait OSet[V] extends TraversableOnce[V]{ + def contains(v: V): Boolean + def items: IndexedSeq[V] + def flatMap[T](f: V => TraversableOnce[T]): OSet[T] + def map[T](f: V => T): OSet[T] + def filter(f: V => Boolean): OSet[V] + def collect[T](f: PartialFunction[V, T]): OSet[T] + def zipWithIndex: OSet[(V, Int)] + def reverse: OSet[V] +} + +object OSet{ + implicit def jsonFormat[T: Format]: Format[OSet[T]] = new Format[OSet[T]] { + def writes(o: OSet[T]) = JsArray(o.items.map(implicitly[Format[T]].writes)) + + def reads(json: JsValue) = json match{ + case x: JsArray => implicitly[Format[Seq[T]]].reads(x).map(OSet.from) + case _ => JsError("OSet needs to be an Array") + } + } + def apply[V](items: V*) = from(items) + + def from[V](items: TraversableOnce[V]): OSet[V] = { + val set = new OSet.Mutable[V]() + items.foreach(set.append) + set + } + + + class Mutable[V]() extends OSet[V]{ + + private[this] val set0 = mutable.LinkedHashSet.empty[V] + def contains(v: V) = set0.contains(v) + def append(v: V) = if (!contains(v)){ + set0.add(v) + + }else { + throw new Exception("Duplicated item inserted into OrderedSet: " + v) + } + def appendAll(vs: Seq[V]) = vs.foreach(append) + def items: IndexedSeq[V] = set0.toIndexedSeq + def set: collection.Set[V] = set0 + + def map[T](f: V => T): OSet[T] = { + val output = new OSet.Mutable[T] + for(i <- items) output.append(f(i)) + output + } + def flatMap[T](f: V => TraversableOnce[T]): OSet[T] = { + val output = new OSet.Mutable[T] + for(i <- items) for(i0 <- f(i)) output.append(i0) + output + } + def filter(f: V => Boolean): OSet[V] = { + val output = new OSet.Mutable[V] + for(i <- items) if (f(i)) output.append(i) + output + } + + def collect[T](f: PartialFunction[V, T]) = this.filter(f.isDefinedAt).map(x => f(x)) + + def zipWithIndex = { + var i = 0 + this.map{ x => + i += 1 + (x, i-1) + } + } + + def reverse = OSet.from(items.reverseIterator) + + // Members declared in scala.collection.GenTraversableOnce + def isTraversableAgain: Boolean = items.isTraversableAgain + def toIterator: Iterator[V] = items.toIterator + def toStream: Stream[V] = items.toStream + + // Members declared in scala.collection.TraversableOnce + def copyToArray[B >: V](xs: Array[B],start: Int,len: Int): Unit = items.copyToArray(xs, start, len) + def exists(p: V => Boolean): Boolean = items.exists(p) + def find(p: V => Boolean): Option[V] = items.find(p) + def forall(p: V => Boolean): Boolean = items.forall(p) + def foreach[U](f: V => U): Unit = items.foreach(f) + def hasDefiniteSize: Boolean = items.hasDefiniteSize + def isEmpty: Boolean = items.isEmpty + def seq: scala.collection.TraversableOnce[V] = items + def toTraversable: Traversable[V] = items + + override def hashCode() = items.hashCode() + override def equals(other: Any) = other match{ + case s: OSet[_] => items.equals(s.items) + case _ => super.equals(other) + } + override def toString = items.mkString("OSet(", ", ", ")") + } +} diff --git a/core/src/main/scala/forge/util/PathRef.scala b/core/src/main/scala/forge/util/PathRef.scala new file mode 100644 index 00000000..dbe1ebbd --- /dev/null +++ b/core/src/main/scala/forge/util/PathRef.scala @@ -0,0 +1,57 @@ +package forge +package util + +import java.io.IOException +import java.nio.file.{FileVisitResult, FileVisitor} +import java.nio.file.attribute.BasicFileAttributes +import java.security.MessageDigest +import java.nio.{file => jnio} +import play.api.libs.json.{Format, Json} + + +/** + * A wrapper around `ammonite.ops.Path` that calculates it's hashcode based + * on the contents of the filesystem underneath it. Used to ensure filesystem + * changes can bust caches which are keyed off hashcodes. + */ +case class PathRef(path: ammonite.ops.Path){ + val md5Hash = { + val digest = MessageDigest.getInstance("MD5") + + val buffer = new Array[Byte](16 * 1024) + jnio.Files.walkFileTree( + path.toNIO, + new FileVisitor[jnio.Path] { + def preVisitDirectory(dir: jnio.Path, attrs: BasicFileAttributes) = { + digest.update(dir.toAbsolutePath.toString.getBytes) + FileVisitResult.CONTINUE + } + + def visitFile(file: jnio.Path, attrs: BasicFileAttributes) = { + digest.update(file.toAbsolutePath.toString.getBytes) + val is = jnio.Files.newInputStream(file) + def rec(): Unit = { + val length = is.read(buffer) + if (length != -1){ + digest.update(buffer, 0, length) + rec() + } + } + rec() + FileVisitResult.CONTINUE + } + + def visitFileFailed(file: jnio.Path, exc: IOException) = FileVisitResult.CONTINUE + def postVisitDirectory(dir: jnio.Path, exc: IOException) = FileVisitResult.CONTINUE + } + ) + + java.util.Arrays.hashCode(digest.digest()) + + } + override def hashCode() = md5Hash +} + +object PathRef{ + implicit def jsonFormatter: Format[PathRef] = Json.format +} |