repo
string | commit
string | message
string | diff
string |
---|---|---|---|
djspiewak/scala-collections
|
83df4bb0e94e867bfcffff30928d4670ba56aeb0
|
Created specs for vector persistence (I'm still not convinced that I did it right)
|
diff --git a/src/spec/scala/VectorSpecs.scala b/src/spec/scala/VectorSpecs.scala
index 1857a5a..95eecf2 100644
--- a/src/spec/scala/VectorSpecs.scala
+++ b/src/spec/scala/VectorSpecs.scala
@@ -1,426 +1,467 @@
import org.specs._
import org.scalacheck._
import com.codecommit.collection.{EmptyVector, Vector}
object VectorSpecs extends Specification with ScalaCheck {
import Prop._
val vector = Vector[Int]()
implicit def arbitraryVector[A](implicit arb: Arbitrary[A]): Arbitrary[Vector[A]] = {
Arbitrary(for {
data <- Arbitrary.arbitrary[List[A]]
} yield data.foldLeft(Vector[A]()) { _ + _ })
}
"vector" should {
"store a single element" in {
val prop = forAll { (i: Int, e: Int) =>
i >= 0 ==> ((vector(0) = e)(0) == e)
}
prop must pass
}
"implement length" in {
val prop = forAll { (list: List[Int]) =>
val vec = list.foldLeft(Vector[Int]()) { _ + _ }
vec.length == list.length
}
prop must pass
}
"replace single element" in {
val prop = forAll { (vec: Vector[Int], i: Int) =>
((0 to vec.length) contains i) ==> {
val newVector = (vec(i) = "test")(i) = "newTest"
newVector(i) == "newTest"
}
}
prop must pass
}
"fail on apply out-of-bounds" in {
val prop = forAll { (vec: Vector[Int], i: Int) =>
!((0 until vec.length) contains i) ==> {
try {
vec(i)
false
} catch {
case _: IndexOutOfBoundsException => true
}
}
}
prop must pass
}
"fail on update out-of-bounds" in {
val prop = forAll { (vec: Vector[Int], i: Int) =>
!((0 to vec.length) contains i) ==> {
try {
vec(i) = 42
false
} catch {
case _: IndexOutOfBoundsException => true
}
}
}
prop must pass
}
"pop elements" in {
val prop = forAll { vec: Vector[Int] =>
vec.length > 0 ==> {
val popped = vec.pop
var back = popped.length == vec.length - 1
for (i <- 0 until popped.length) {
back &&= popped(i) == vec(i)
}
back
}
}
prop must pass(set(maxSize -> 3000, minTestsOk -> 1000))
}
"fail on pop empty vector" in {
val caughtExcept = try {
EmptyVector.pop
false
} catch {
case _: IllegalStateException => true
}
caughtExcept mustEqual true
}
"store multiple elements in order" in {
val prop = forAll { list: List[Int] =>
val newVector = list.foldLeft(vector) { _ + _ }
val res = for (i <- 0 until list.length) yield newVector(i) == list(i)
res forall { _ == true }
}
prop must pass
}
"store lots of elements" in {
val LENGTH = 100000
val vector = (0 until LENGTH).foldLeft(Vector[Int]()) { _ + _ }
vector.length mustEqual LENGTH
for (i <- 0 until LENGTH) {
vector(i) mustEqual i
}
}
+ "maintain both old and new versions after conj" in {
+ val prop = forAll { vec: Vector[Int] =>
+ val vec2 = vec + 42
+ for (i <- 0 until vec.length) {
+ vec2(i) aka ("Index " + i + " in derivative") mustEqual vec(i) aka ("Index " + i + " in origin")
+ }
+ vec2.last mustEqual 42
+ }
+
+ prop must pass(set(maxSize -> 3000, minTestsOk -> 1000))
+ }
+
+ "maintain both old and new versions after update" in {
+ val prop = forAll { (vec: Vector[Int], i: Int) =>
+ (!vec.isEmpty && i > Math.MIN_INT) ==> {
+ val idx = Math.abs(i) % vec.length
+ val vec2 = vec(idx) = 42
+ for (i <- 0 until vec.length if i != idx) {
+ vec2(i) aka ("Index " + i + " in derivative") mustEqual vec(i) aka ("Index " + i + " in origin")
+ }
+ vec2(idx) mustEqual 42
+ }
+ }
+
+ prop must pass(set(maxSize -> 3000, minTestsOk -> 1000))
+ }
+
+ "maintain both old and new versions after pop" in {
+ val prop = forAll { vec: Vector[Int] =>
+ !vec.isEmpty ==> {
+ val vec2 = vec.pop
+ for (i <- 0 until vec.length - 1) {
+ vec2(i) aka ("Index " + i + " in derivative") mustEqual vec(i) aka ("Index " + i + " in origin")
+ }
+ vec2.length mustEqual vec.length - 1
+ }
+ }
+
+ prop must pass(set(maxSize -> 3000, minTestsOk -> 1000))
+ }
+
"implement filter" in {
val prop = forAll { (vec: Vector[Int], f: (Int)=>Boolean) =>
val filtered = vec filter f
var back = filtered forall f
for (e <- vec) {
if (f(e)) {
back &&= filtered.contains(e)
}
}
back
}
prop must pass
}
"implement foldLeft" in {
val prop = forAll { list: List[Int] =>
val vec = list.foldLeft(Vector[Int]()) { _ + _ }
vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ }
}
prop must pass
}
"implement forall" in {
val prop = forAll { (vec: Vector[Int], f: (Int)=>Boolean) =>
val bool = vec forall f
var back = true
for (e <- vec) {
back &&= f(e)
}
(back && bool) || (!back && !bool)
}
prop must pass
}
"implement flatMap" in {
val prop = forAll { (vec: Vector[Int], f: (Int)=>Vector[Int]) =>
val mapped = vec flatMap f
var back = true
var i = 0
var n = 0
while (i < vec.length) {
val res = f(vec(i))
var inner = 0
while (inner < res.length) {
back &&= mapped(n) == res(inner)
inner += 1
n += 1
}
i += 1
}
back
}
prop must pass
}
"implement map" in {
val prop = forAll { (vec: Vector[Int], f: (Int)=>Int) =>
val mapped = vec map f
var back = vec.length == mapped.length
for (i <- 0 until vec.length) {
back &&= mapped(i) == f(vec(i))
}
back
}
prop must pass
}
"implement reverse" in {
val prop = forAll { v: Vector[Int] =>
val reversed = v.reverse
var back = v.length == reversed.length
for (i <- 0 until v.length) {
back &&= reversed(i) == v(v.length - i - 1)
}
back
}
prop must pass
}
"append to reverse" in {
val prop = forAll { (v: Vector[Int], n: Int) =>
val rev = v.reverse
val add = rev + n
var back = add.length == rev.length + 1
for (i <- 0 until rev.length) {
back &&= add(i) == rev(i)
}
back && add(rev.length) == n
}
prop must pass
}
"map on reverse" in {
val prop = forAll { (v: Vector[Int], f: (Int)=>Int) =>
val rev = v.reverse
val mapped = rev map f
var back = mapped.length == rev.length
for (i <- 0 until rev.length) {
back &&= mapped(i) == f(rev(i))
}
back
}
prop must pass
}
"implement subseq" in {
val prop = forAll { (v: Vector[Int], from: Int, end: Int) =>
try {
val sub = v.subseq(from, end)
var back = sub.length == end - from
for (i <- 0 until sub.length) {
back &&= sub(i) == v(i + from)
}
back
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"append to subseq" in {
val prop = forAll { (v: Vector[Int], from: Int, end: Int, n: Int) =>
try {
val sub = v.subseq(from, end)
val add = sub + n
var back = add.length == sub.length + 1
for (i <- 0 until sub.length) {
back &&= add(i) == sub(i)
}
back && add(sub.length) == n
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"update subseq" in {
val prop = forAll { (v: Vector[Int], from: Int, end: Int, mi: Int) =>
try {
val sub = v.subseq(from, end)
val add = sub(mi) = 42
var back = add.length == sub.length + (if (mi == sub.length) 1 else 0)
for (i <- 0 until sub.length; if i != mi) {
back &&= add(i) == sub(i)
}
back && add(mi) == 42
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length || !(0 to (end - from) contains mi)
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"map on subseq" in {
val prop = forAll { (v: Vector[Int], from: Int, end: Int, f: (Int)=>Int) =>
try {
val sub = v.subseq(from, end)
val mapped = sub map f
var back = mapped.length == sub.length
for (i <- 0 until sub.length) {
back &&= mapped(i) == f(sub(i))
}
back
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"implement zip" in {
val prop = forAll { (first: Vector[Int], second: Vector[Double]) =>
val zip = first zip second
var back = zip.length == Math.min(first.length, second.length)
for (i <- 0 until zip.length) {
var (left, right) = zip(i)
back &&= (left == first(i) && right == second(i))
}
back
}
prop must pass
}
"implement zipWithIndex" in {
val prop = forAll { vec: Vector[Int] =>
val zip = vec.zipWithIndex
var back = zip.length == vec.length
for (i <- 0 until zip.length) {
val (elem, index) = zip(i)
back &&= (index == i && elem == vec(i))
}
back
}
prop must pass
}
"implement equals" in {
{
val prop = forAll { list: List[Int] =>
val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
vecA == vecB
}
prop must pass
}
{
val prop = forAll { (vecA: Vector[Int], vecB: Vector[Int]) =>
vecA.length != vecB.length ==> (vecA != vecB)
}
prop must pass
}
{
val prop = forAll { (listA: List[Int], listB: List[Int]) =>
val vecA = listA.foldLeft(Vector[Int]()) { _ + _ }
val vecB = listB.foldLeft(Vector[Int]()) { _ + _ }
listA != listB ==> (vecA != vecB)
}
prop must pass
}
{
val prop = forAll { (vec: Vector[Int], data: Int) => vec != data }
prop must pass
}
}
"implement hashCode" in {
val prop = forAll { list: List[Int] =>
val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
vecA.hashCode == vecB.hashCode
}
prop must pass
}
"implement extractor" in {
val vec1 = Vector(1, 2, 3)
vec1 must beLike {
case Vector(a, b, c) => (a, b, c) == (1, 2, 3)
}
val vec2 = Vector("daniel", "chris", "joseph")
vec2 must beLike {
case Vector(a, b, c) => (a, b, c) == ("daniel", "chris", "joseph")
}
}
}
}
|
djspiewak/scala-collections
|
3ce079bacbfe92a45f6bfdb21ccc95a6e2732b36
|
Eliminated polymorphic array use to optimize performance on Scala 2.7 (and eliminate pesky ArrayStoreExceptions)
|
diff --git a/src/main/scala/com/codecommit/collection/Vector.scala b/src/main/scala/com/codecommit/collection/Vector.scala
index cad74a2..0db62a6 100644
--- a/src/main/scala/com/codecommit/collection/Vector.scala
+++ b/src/main/scala/com/codecommit/collection/Vector.scala
@@ -1,751 +1,819 @@
/**
Copyright (c) 2007-2008, Rich Hickey
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Clojure nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**/
package com.codecommit.collection
import Vector._
import VectorCases._
/**
* A straight port of Clojure's <code>PersistentVector</code> class.
*
* @author Daniel Spiewak
* @author Rich Hickey
*/
class Vector[+T] private (val length: Int, trie: Case, tail: Array[AnyRef]) extends RandomAccessSeq[T] { outer =>
private val tailOff = length - tail.length
/*
* The design of this data structure inherantly requires heterogenous arrays.
* It is *possible* to design around this, but the result is comparatively
* quite inefficient. With respect to this fact, I have left the original
* (somewhat dynamically-typed) implementation in place.
*/
private[collection] def this() = this(0, Zero, EmptyArray)
def apply(i: Int): T = {
if (i >= 0 && i < length) {
if (i >= tailOff) {
tail(i & 0x01f).asInstanceOf[T]
} else {
var arr = trie(i)
arr(i & 0x01f).asInstanceOf[T]
}
} else throw new IndexOutOfBoundsException(i.toString)
}
def update[A >: T](i: Int, obj: A): Vector[A] = {
if (i >= 0 && i < length) {
if (i >= tailOff) {
val newTail = new Array[AnyRef](tail.length)
Array.copy(tail, 0, newTail, 0, tail.length)
newTail(i & 0x01f) = obj.asInstanceOf[AnyRef]
new Vector[A](length, trie, newTail)
} else {
new Vector[A](length, trie(i) = obj.asInstanceOf[AnyRef], tail)
}
} else if (i == length) {
this + obj
} else throw new IndexOutOfBoundsException(i.toString)
}
override def ++[A >: T](other: Iterable[A]) = other.foldLeft(this: Vector[A]) { _ + _ }
def +[A >: T](obj: A): Vector[A] = {
if (tail.length < 32) {
val tail2 = new Array[AnyRef](tail.length + 1)
Array.copy(tail, 0, tail2, 0, tail.length)
tail2(tail.length) = obj.asInstanceOf[AnyRef]
new Vector[A](length + 1, trie, tail2)
} else {
new Vector[A](length + 1, trie + tail, array(obj.asInstanceOf[AnyRef]))
}
}
/**
* Removes the <i>tail</i> element of this vector.
*/
def pop: Vector[T] = {
if (length == 0) {
throw new IllegalStateException("Can't pop empty vector")
} else if (length == 1) {
EmptyVector
} else if (tail.length > 1) {
val tail2 = new Array[AnyRef](tail.length - 1)
Array.copy(tail, 0, tail2, 0, tail2.length)
new Vector[T](length - 1, trie, tail2)
} else {
val (trie2, tail2) = trie.pop
new Vector[T](length - 1, trie2, tail2)
}
}
override def filter(p: (T)=>Boolean) = {
var back = new Vector[T]
var i = 0
while (i < length) {
val e = apply(i)
if (p(e)) back += e
i += 1
}
back
}
override def flatMap[A](f: (T)=>Iterable[A]) = {
var back = new Vector[A]
var i = 0
while (i < length) {
f(apply(i)) foreach { back += _ }
i += 1
}
back
}
override def map[A](f: (T)=>A) = {
var back = new Vector[A]
var i = 0
while (i < length) {
back += f(apply(i))
i += 1
}
back
}
override def reverse: Vector[T] = new VectorProjection[T] {
override val length = outer.length
override def apply(i: Int) = outer.apply(length - i - 1)
}
override def subseq(from: Int, end: Int) = subVector(from, end)
def subVector(from: Int, end: Int): Vector[T] = {
if (from < 0) {
throw new IndexOutOfBoundsException(from.toString)
} else if (end >= length) {
throw new IndexOutOfBoundsException(end.toString)
} else if (end <= from) {
throw new IllegalArgumentException("Invalid range: " + from + ".." + end)
} else {
new VectorProjection[T] {
override val length = end - from
override def apply(i: Int) = outer.apply(i + from)
}
}
}
def zip[A](that: Vector[A]) = {
var back = new Vector[(T, A)]
var i = 0
val limit = Math.min(length, that.length)
while (i < limit) {
back += (apply(i), that(i))
i += 1
}
back
}
def zipWithIndex = {
var back = new Vector[(T, Int)]
var i = 0
while (i < length) {
back += (apply(i), i)
i += 1
}
back
}
override def equals(other: Any) = other match {
case vec:Vector[T] => {
var back = length == vec.length
var i = 0
while (i < length) {
back &&= apply(i) == vec.apply(i)
i += 1
}
back
}
case _ => false
}
override def hashCode = foldLeft(0) { _ ^ _.hashCode }
}
object Vector {
private[collection] val EmptyArray = new Array[AnyRef](0)
def apply[T](elems: T*) = elems.foldLeft(EmptyVector:Vector[T]) { _ + _ }
def unapplySeq[T](vec: Vector[T]): Option[Seq[T]] = Some(vec)
@inline
private[collection] def array(elem: AnyRef) = {
val back = new Array[AnyRef](1)
back(0) = elem
back
}
}
object EmptyVector extends Vector[Nothing]
private[collection] abstract class VectorProjection[+T] extends Vector[T] {
override val length: Int
override def apply(i: Int): T
override def +[A >: T](e: A) = innerCopy + e
override def update[A >: T](i: Int, e: A) = {
if (i < 0) {
throw new IndexOutOfBoundsException(i.toString)
} else if (i > length) {
throw new IndexOutOfBoundsException(i.toString)
} else innerCopy(i) = e
}
private lazy val innerCopy = foldLeft(EmptyVector:Vector[T]) { _ + _ }
}
private[collection] object VectorCases {
- private val SingletonArray1 = new Array[Array[AnyRef]](1)
- private val SingletonArray2 = new Array[Array[Array[AnyRef]]](1)
- private val SingletonArray3 = new Array[Array[Array[Array[AnyRef]]]](1)
- private val SingletonArray4 = new Array[Array[Array[Array[Array[AnyRef]]]]](1)
-
- private def copy[A](array: Array[A], length: Int): Array[A] = {
- val array2 = new Array[A](length)
- Array.copy(array, 0, array2, 0, Math.min(array.length, length))
+ @inline
+ private[this] def copy1(array1: Array[AnyRef], array2: Array[AnyRef]) = {
+ Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length))
+ array2
+ }
+
+ @inline
+ private[this] def copy2(array1: Array[Array[AnyRef]], array2: Array[Array[AnyRef]]) = {
+ Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length))
+ array2
+ }
+
+ @inline
+ private[this] def copy3(array1: Array[Array[Array[AnyRef]]], array2: Array[Array[Array[AnyRef]]]) = {
+ Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length))
array2
}
- private def copy[A](array: Array[A]): Array[A] = copy(array, array.length)
+ @inline
+ private[this] def copy4(array1: Array[Array[Array[Array[AnyRef]]]], array2: Array[Array[Array[Array[AnyRef]]]]) = {
+ Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length))
+ array2
+ }
+
+ @inline
+ private[this] def copy5(array1: Array[Array[Array[Array[Array[AnyRef]]]]], array2: Array[Array[Array[Array[Array[AnyRef]]]]]) = {
+ Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length))
+ array2
+ }
+
+ @inline
+ private[this] def copy6(array1: Array[Array[Array[Array[Array[Array[AnyRef]]]]]], array2: Array[Array[Array[Array[Array[Array[AnyRef]]]]]]) = {
+ Array.copy(array1, 0, array2, 0, Math.min(array1.length, array2.length))
+ array2
+ }
sealed trait Case {
type Self <: Case
val shift: Int
def apply(i: Int): Array[AnyRef]
def update(i: Int, obj: AnyRef): Self
def +(node: Array[AnyRef]): Case
def pop: (Case, Array[AnyRef])
}
case object Zero extends Case {
type Self = Nothing
val shift = -1
def apply(i: Int) = throw new IndexOutOfBoundsException(i.toString)
def update(i: Int, obj: AnyRef) = throw new IndexOutOfBoundsException(i.toString)
def +(node: Array[AnyRef]) = One(node)
def pop = throw new IndexOutOfBoundsException("Cannot pop an empty Vector")
}
case class One(trie: Array[AnyRef]) extends Case {
type Self = One
val shift = 0
def apply(i: Int) = trie
def update(i: Int, obj: AnyRef) = {
- val trie2 = copy(trie)
+ val trie2 = copy1(trie, new Array[AnyRef](trie.length))
trie2(i & 0x01f) = obj
One(trie2)
}
def +(tail: Array[AnyRef]) = {
val trie2 = new Array[Array[AnyRef]](2)
trie2(0) = trie
trie2(1) = tail
Two(trie2)
}
def pop = (Zero, trie)
}
case class Two(trie: Array[Array[AnyRef]]) extends Case {
type Self = Two
val shift = 5
def apply(i: Int) = trie((i >>> 5) & 0x01f)
def update(i: Int, obj: AnyRef) = {
- val trie2a = copy(trie)
+ val trie2a = copy2(trie, new Array[Array[AnyRef]](trie.length))
- val trie2b = copy(trie2a((i >>> 5) & 0x01f))
+ val trie2b = {
+ val target = trie2a((i >>> 5) & 0x01f)
+ copy1(target, new Array[AnyRef](target.length))
+ }
trie2a((i >>> 5) & 0x01f) = trie2b
trie2b(i & 0x01f) = obj
Two(trie2a)
}
def +(tail: Array[AnyRef]) = {
if (trie.length >= 32) {
val trie2 = new Array[Array[Array[AnyRef]]](2)
trie2(0) = trie
- trie2(1) = SingletonArray1
+ trie2(1) = new Array[Array[AnyRef]](1)
trie2(1)(0) = tail
Three(trie2)
} else {
- val trie2 = copy(trie, trie.length + 1)
+ val trie2 = copy2(trie, new Array[Array[AnyRef]](trie.length + 1))
trie2(trie.length) = tail
Two(trie2)
}
}
def pop = {
if (trie.length == 2) {
(One(trie(0)), trie.last)
} else {
- val trie2 = copy(trie, trie.length - 1)
+ val trie2 = copy2(trie, new Array[Array[AnyRef]](trie.length - 1))
(Two(trie2), trie.last)
}
}
}
case class Three(trie: Array[Array[Array[AnyRef]]]) extends Case {
type Self = Three
val shift = 10
def apply(i: Int) = {
val a = trie((i >>> 10) & 0x01f)
a((i >>> 5) & 0x01f)
}
def update(i: Int, obj: AnyRef) = {
- val trie2a = copy(trie)
+ val trie2a = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length))
- val trie2b = copy(trie2a((i >>> 10) & 0x01f))
+ val trie2b = {
+ val target = trie2a((i >>> 10) & 0x01f)
+ copy2(target, new Array[Array[AnyRef]](target.length))
+ }
trie2a((i >>> 10) & 0x01f) = trie2b
- val trie2c = copy(trie2b((i >>> 5) & 0x01f))
+ val trie2c = {
+ val target = trie2b((i >>> 5) & 0x01f)
+ copy1(target, new Array[AnyRef](target.length))
+ }
trie2b((i >>> 5) & 0x01f) = trie2c
trie2c(i & 0x01f) = obj
Three(trie2a)
}
def +(tail: Array[AnyRef]) = {
if (trie.last.length >= 32) {
if (trie.length >= 32) {
val trie2 = new Array[Array[Array[Array[AnyRef]]]](2)
trie2(0) = trie
- trie2(1) = SingletonArray2
- trie2(1)(0) = SingletonArray1
+ trie2(1) = new Array[Array[Array[AnyRef]]](1)
+ trie2(1)(0) = new Array[Array[AnyRef]](1)
trie2(1)(0)(0) = tail
Four(trie2)
} else {
- val trie2 = copy(trie, trie.length + 1)
- trie2(trie.length) = SingletonArray1
+ val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length + 1))
+ trie2(trie.length) = new Array[Array[AnyRef]](1)
trie2(trie.length)(0) = tail
Three(trie2)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
+ val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length))
+ trie2(trie2.length - 1) = copy2(trie2.last, new Array[Array[AnyRef]](trie2.last.length + 1))
trie2.last(trie.last.length) = tail
Three(trie2)
}
}
def pop = {
if (trie.last.length == 1) {
if (trie.length == 2) {
(Two(trie(0)), trie.last.last)
} else {
- val trie2 = copy(trie, trie.length - 1)
+ val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length - 1))
(Three(trie2), trie.last.last)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ val trie2 = copy3(trie, new Array[Array[Array[AnyRef]]](trie.length))
+ trie2(trie2.length - 1) = copy2(trie2.last, new Array[Array[AnyRef]](trie2.last.length - 1))
(Three(trie2), trie.last.last)
}
}
}
case class Four(trie: Array[Array[Array[Array[AnyRef]]]]) extends Case {
type Self = Four
val shift = 15
def apply(i: Int) = {
val a = trie((i >>> 15) & 0x01f)
val b = a((i >>> 10) & 0x01f)
b((i >>> 5) & 0x01f)
}
def update(i: Int, obj: AnyRef) = {
- val trie2a = copy(trie)
+ val trie2a = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length))
- val trie2b = copy(trie2a((i >>> 15) & 0x01f))
+ val trie2b = {
+ val target = trie2a((i >>> 15) & 0x01f)
+ copy3(target, new Array[Array[Array[AnyRef]]](target.length))
+ }
trie2a((i >>> 15) & 0x01f) = trie2b
- val trie2c = copy(trie2b((i >>> 10) & 0x01f))
+ val trie2c = {
+ val target = trie2b((i >>> 10) & 0x01f)
+ copy2(target, new Array[Array[AnyRef]](target.length))
+ }
trie2b((i >>> 10) & 0x01f) = trie2c
- val trie2d = copy(trie2c((i >>> 5) & 0x01f))
+ val trie2d = {
+ val target = trie2c((i >>> 5) & 0x01f)
+ copy1(target, new Array[AnyRef](target.length))
+ }
trie2c((i >>> 5) & 0x01f) = trie2d
trie2d(i & 0x01f) = obj
Four(trie2a)
}
def +(tail: Array[AnyRef]) = {
if (trie.last.last.length >= 32) {
if (trie.last.length >= 32) {
if (trie.length >= 32) {
val trie2 = new Array[Array[Array[Array[Array[AnyRef]]]]](2)
trie2(0) = trie
- trie2(1) = SingletonArray3
- trie2(1)(0) = SingletonArray2
- trie2(1)(0)(0) = SingletonArray1
+ trie2(1) = new Array[Array[Array[Array[AnyRef]]]](1)
+ trie2(1)(0) = new Array[Array[Array[AnyRef]]](1)
+ trie2(1)(0)(0) = new Array[Array[AnyRef]](1)
trie2(1)(0)(0)(0) = tail
Five(trie2)
} else {
- val trie2 = copy(trie, trie.length + 1)
- trie2(trie.length) = SingletonArray2
- trie2(trie.length)(0) = SingletonArray1
+ val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length + 1))
+ trie2(trie.length) = new Array[Array[Array[AnyRef]]](1)
+ trie2(trie.length)(0) = new Array[Array[AnyRef]](1)
trie2(trie.length)(0)(0) = tail
Four(trie2)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
- trie2.last(trie.last.length) = SingletonArray1
+ val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length))
+ trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length + 1))
+ trie2.last(trie.last.length) = new Array[Array[AnyRef]](1)
trie2.last.last(0) = tail
Four(trie2)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length + 1)
+ val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length))
+ trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length))
+ trie2.last(trie2.last.length - 1) = copy2(trie2.last.last, new Array[Array[AnyRef]](trie2.last.last.length + 1))
trie2.last.last(trie.last.last.length) = tail
Four(trie2)
}
}
def pop = {
if (trie.last.last.length == 1) {
if (trie.last.length == 1) {
if (trie.length == 2) {
(Three(trie(0)), trie.last.last.last)
} else {
- val trie2 = copy(trie, trie.length - 1)
+ val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length - 1))
(Four(trie2), trie.last.last.last)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length))
+ trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length - 1))
(Four(trie2), trie.last.last.last)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ val trie2 = copy4(trie, new Array[Array[Array[Array[AnyRef]]]](trie.length))
+ trie2(trie2.length - 1) = copy3(trie2.last, new Array[Array[Array[AnyRef]]](trie2.last.length - 1))
+ trie2.last(trie2.last.length - 1) = copy2(trie2.last.last, new Array[Array[AnyRef]](trie2.last.last.length - 1))
(Four(trie2), trie.last.last.last)
}
}
}
case class Five(trie: Array[Array[Array[Array[Array[AnyRef]]]]]) extends Case {
type Self = Five
val shift = 20
def apply(i: Int) = {
val a = trie((i >>> 20) & 0x01f)
val b = a((i >>> 15) & 0x01f)
val c = b((i >>> 10) & 0x01f)
c((i >>> 5) & 0x01f)
}
def update(i: Int, obj: AnyRef) = {
- val trie2a = copy(trie)
+ val trie2a = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length))
- val trie2b = copy(trie2a((i >>> 20) & 0x01f))
+ val trie2b = {
+ val target = trie2a((i >>> 20) & 0x01f)
+ copy4(target, new Array[Array[Array[Array[AnyRef]]]](target.length))
+ }
trie2a((i >>> 20) & 0x01f) = trie2b
- val trie2c = copy(trie2b((i >>> 15) & 0x01f))
+ val trie2c = {
+ val target = trie2b((i >>> 15) & 0x01f)
+ copy3(target, new Array[Array[Array[AnyRef]]](target.length))
+ }
trie2b((i >>> 15) & 0x01f) = trie2c
- val trie2d = copy(trie2c((i >>> 10) & 0x01f))
+ val trie2d = {
+ val target = trie2c((i >>> 10) & 0x01f)
+ copy2(target, new Array[Array[AnyRef]](target.length))
+ }
trie2c((i >>> 10) & 0x01f) = trie2d
- val trie2e = copy(trie2d((i >>> 5) & 0x01f))
+ val trie2e = {
+ val target = trie2d((i >>> 5) & 0x01f)
+ copy1(target, new Array[AnyRef](target.length))
+ }
trie2d((i >>> 5) & 0x01f) = trie2e
trie2e(i & 0x01f) = obj
Five(trie2a)
}
def +(tail: Array[AnyRef]) = {
if (trie.last.last.last.length >= 32) {
if (trie.last.last.length >= 32) {
if (trie.last.length >= 32) {
if (trie.length >= 32) {
val trie2 = new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](2)
trie2(0) = trie
- trie2(1) = SingletonArray4
- trie2(1)(0) = SingletonArray3
- trie2(1)(0)(0) = SingletonArray2
- trie2(1)(0)(0)(0) = SingletonArray1
+ trie2(1) = new Array[Array[Array[Array[Array[AnyRef]]]]](1)
+ trie2(1)(0) = new Array[Array[Array[Array[AnyRef]]]](1)
+ trie2(1)(0)(0) = new Array[Array[Array[AnyRef]]](1)
+ trie2(1)(0)(0)(0) = new Array[Array[AnyRef]](1)
trie2(1)(0)(0)(0)(0) = tail
Six(trie2)
} else {
- val trie2 = copy(trie, trie.length + 1)
- trie2(trie.length) = SingletonArray3
- trie2(trie.length)(0) = SingletonArray2
- trie2(trie.length)(0)(0) = SingletonArray1
+ val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length + 1))
+ trie2(trie.length) = new Array[Array[Array[Array[AnyRef]]]](1)
+ trie2(trie.length)(0) = new Array[Array[Array[AnyRef]]](1)
+ trie2(trie.length)(0)(0) = new Array[Array[AnyRef]](1)
trie2(trie.length)(0)(0)(0) = tail
Five(trie2)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
- trie2.last(trie.last.length) = SingletonArray2
- trie2.last.last(0) = SingletonArray1
+ val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length))
+ trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length + 1))
+ trie2.last(trie.last.length) = new Array[Array[Array[AnyRef]]](1)
+ trie2.last.last(0) = new Array[Array[AnyRef]](1)
trie2.last.last.last(0) = tail
Five(trie2)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length + 1)
- trie2.last.last(trie.last.last.length) = SingletonArray1
+ val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length))
+ trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length))
+ trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length + 1))
+ trie2.last.last(trie.last.last.length) = new Array[Array[AnyRef]](1)
trie2.last.last.last(0) = tail
Five(trie2)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last)
- trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length + 1)
+ val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length))
+ trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length))
+ trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length))
+ trie2.last.last(trie2.last.last.length - 1) = copy2(trie2.last.last.last, new Array[Array[AnyRef]](trie2.last.last.last.length + 1))
trie2.last.last.last(trie.last.last.last.length) = tail
Five(trie2)
}
}
def pop = {
if (trie.last.last.last.length == 1) {
if (trie.last.last.length == 1) {
if (trie.last.length == 1) {
if (trie.length == 2) {
(Four(trie(0)), trie.last.last.last.last)
} else {
- val trie2 = copy(trie, trie.length - 1)
+ val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length - 1))
(Five(trie2), trie.last.last.last.last)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length))
+ trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length - 1))
(Five(trie2), trie.last.last.last.last)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length))
+ trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length - 1))
+ trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length - 1))
(Five(trie2), trie.last.last.last.last)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
- trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length - 1)
+ val trie2 = copy5(trie, new Array[Array[Array[Array[Array[AnyRef]]]]](trie.length))
+ trie2(trie2.length - 1) = copy4(trie2.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.length - 1))
+ trie2.last(trie2.last.length - 1) = copy3(trie2.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.length - 1))
+ trie2.last.last(trie2.last.last.length - 1) = copy2(trie2.last.last.last, new Array[Array[AnyRef]](trie2.last.last.last.length - 1))
(Five(trie2), trie.last.last.last.last)
}
}
}
case class Six(trie: Array[Array[Array[Array[Array[Array[AnyRef]]]]]]) extends Case {
type Self = Six
val shift = 25
def apply(i: Int) = {
val a = trie((i >>> 25) & 0x01f)
val b = a((i >>> 20) & 0x01f)
val c = b((i >>> 15) & 0x01f)
val d = c((i >>> 10) & 0x01f)
d((i >>> 5) & 0x01f)
}
def update(i: Int, obj: AnyRef) = {
- val trie2a = copy(trie)
+ val trie2a = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length))
- val trie2b = copy(trie2a((i >>> 25) & 0x01f))
+ val trie2b = {
+ val target = trie2a((i >>> 25) & 0x01f)
+ copy5(target, new Array[Array[Array[Array[Array[AnyRef]]]]](target.length))
+ }
trie2a((i >>> 25) & 0x01f) = trie2b
- val trie2c = copy(trie2b((i >>> 20) & 0x01f))
+ val trie2c = {
+ val target = trie2b((i >>> 20) & 0x01f)
+ copy4(target, new Array[Array[Array[Array[AnyRef]]]](target.length))
+ }
trie2b((i >>> 20) & 0x01f) = trie2c
- val trie2d = copy(trie2c((i >>> 15) & 0x01f))
+ val trie2d = {
+ val target = trie2c((i >>> 15) & 0x01f)
+ copy3(target, new Array[Array[Array[AnyRef]]](target.length))
+ }
trie2c((i >>> 15) & 0x01f) = trie2d
- val trie2e = copy(trie2d((i >>> 10) & 0x01f))
+ val trie2e = {
+ val target = trie2d((i >>> 10) & 0x01f)
+ copy2(target, new Array[Array[AnyRef]](target.length))
+ }
trie2d((i >>> 10) & 0x01f) = trie2e
- val trie2f = copy(trie2e((i >>> 5) & 0x01f))
+ val trie2f = {
+ val target = trie2e((i >>> 5) & 0x01f)
+ copy1(target, new Array[AnyRef](target.length))
+ }
trie2e((i >>> 5) & 0x01f) = trie2f
trie2f(i & 0x01f) = obj
Six(trie2a)
}
def +(tail: Array[AnyRef]) = {
if (trie.last.last.last.last.length >= 32) {
if (trie.last.last.last.length >= 32) {
if (trie.last.last.length >= 32) {
if (trie.last.length >= 32) {
if (trie.length >= 32) {
throw new IndexOutOfBoundsException("Cannot grow vector beyond integer bounds")
} else {
- val trie2 = copy(trie, trie.length + 1)
- trie2(trie.length) = SingletonArray4
- trie2(trie.length)(0) = SingletonArray3
- trie2(trie.length)(0)(0) = SingletonArray2
- trie2(trie.length)(0)(0)(0) = SingletonArray1
+ val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length + 1))
+ trie2(trie.length) = new Array[Array[Array[Array[Array[AnyRef]]]]](1)
+ trie2(trie.length)(0) = new Array[Array[Array[Array[AnyRef]]]](1)
+ trie2(trie.length)(0)(0) = new Array[Array[Array[AnyRef]]](1)
+ trie2(trie.length)(0)(0)(0) = new Array[Array[AnyRef]](1)
trie2(trie.length)(0)(0)(0)(0) = tail
Six(trie2)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
- trie2.last(trie.last.length) = SingletonArray3
- trie2.last.last(0) = SingletonArray2
- trie2.last.last.last(0) = SingletonArray1
+ val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length))
+ trie2(trie2.length - 1) = copy5(trie2.last, new Array[Array[Array[Array[Array[AnyRef]]]]](trie2.last.length + 1))
+ trie2.last(trie.last.length) = new Array[Array[Array[Array[AnyRef]]]](1)
+ trie2.last.last(0) = new Array[Array[Array[AnyRef]]](1)
+ trie2.last.last.last(0) = new Array[Array[AnyRef]](1)
trie2.last.last.last.last(0) = tail
Six(trie2)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length + 1)
- trie2.last.last(trie.last.last.length) = SingletonArray2
- trie2.last.last.last(0) = SingletonArray1
+ val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length))
+ trie2(trie2.length - 1) = copy5(trie2.last, new Array[Array[Array[Array[Array[AnyRef]]]]](trie2.last.length))
+ trie2.last(trie2.last.length - 1) = copy4(trie2.last.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.last.length + 1))
+ trie2.last.last(trie.last.last.length) = new Array[Array[Array[AnyRef]]](1)
+ trie2.last.last.last(0) = new Array[Array[AnyRef]](1)
trie2.last.last.last.last(0) = tail
Six(trie2)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last)
- trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length + 1)
- trie2.last.last.last(trie.last.last.last.length) = SingletonArray1
+ val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length))
+ trie2(trie2.length - 1) = copy5(trie2.last, new Array[Array[Array[Array[Array[AnyRef]]]]](trie2.last.length))
+ trie2.last(trie2.last.length - 1) = copy4(trie2.last.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.last.length))
+ trie2.last.last(trie2.last.last.length - 1) = copy3(trie2.last.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.last.length + 1))
+ trie2.last.last.last(trie.last.last.last.length) = new Array[Array[AnyRef]](1)
trie2.last.last.last.last(0) = tail
Six(trie2)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last)
- trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last)
- trie2.last.last.last(trie.last.last.last.length - 1) = copy(trie2.last.last.last.last, trie2.last.last.last.last.length + 1)
+ val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length))
+ trie2(trie2.length - 1) = copy5(trie2.last, new Array[Array[Array[Array[Array[AnyRef]]]]](trie2.last.length))
+ trie2.last(trie2.last.length - 1) = copy4(trie2.last.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.last.length))
+ trie2.last.last(trie2.last.last.length - 1) = copy3(trie2.last.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.last.length))
+ trie2.last.last.last(trie.last.last.last.length - 1) = copy2(trie2.last.last.last.last, new Array[Array[AnyRef]](trie2.last.last.last.last.length + 1))
trie2.last.last.last.last(trie.last.last.last.last.length) = tail
Six(trie2)
}
}
def pop = {
if (trie.last.last.last.last.length == 1) {
if (trie.last.last.last.length == 1) {
if (trie.last.last.length == 1) {
if (trie.last.length == 1) {
if (trie.length == 2) {
(Five(trie(0)), trie.last.last.last.last.last)
} else {
- val trie2 = copy(trie, trie.length - 1)
+ val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length - 1))
(Six(trie2), trie.last.last.last.last.last)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length))
+ trie2(trie2.length - 1) = copy5(trie2.last, new Array[Array[Array[Array[Array[AnyRef]]]]](trie2.last.length - 1))
(Six(trie2), trie.last.last.last.last.last)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length))
+ trie2(trie2.length - 1) = copy5(trie2.last, new Array[Array[Array[Array[Array[AnyRef]]]]](trie2.last.length - 1))
+ trie2.last(trie2.last.length - 1) = copy4(trie2.last.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.last.length - 1))
(Six(trie2), trie.last.last.last.last.last)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
- trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length - 1)
+ val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length))
+ trie2(trie2.length - 1) = copy5(trie2.last, new Array[Array[Array[Array[Array[AnyRef]]]]](trie2.last.length - 1))
+ trie2.last(trie2.last.length - 1) = copy4(trie2.last.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.last.length - 1))
+ trie2.last.last(trie2.last.last.length - 1) = copy3(trie2.last.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.last.length - 1))
(Six(trie2), trie.last.last.last.last.last)
}
} else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
- trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length - 1)
- trie2.last.last.last(trie2.last.last.last.length - 1) = copy(trie2.last.last.last.last, trie2.last.last.last.last.length - 1)
+ val trie2 = copy6(trie, new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](trie.length))
+ trie2(trie2.length - 1) = copy5(trie2.last, new Array[Array[Array[Array[Array[AnyRef]]]]](trie2.last.length - 1))
+ trie2.last(trie2.last.length - 1) = copy4(trie2.last.last, new Array[Array[Array[Array[AnyRef]]]](trie2.last.last.length - 1))
+ trie2.last.last(trie2.last.last.length - 1) = copy3(trie2.last.last.last, new Array[Array[Array[AnyRef]]](trie2.last.last.last.length - 1))
+ trie2.last.last.last(trie2.last.last.last.length - 1) = copy2(trie2.last.last.last.last, new Array[Array[AnyRef]](trie2.last.last.last.last.length - 1))
(Six(trie2), trie.last.last.last.last.last)
}
}
}
}
|
djspiewak/scala-collections
|
e4e9279e23a08c186538deed1abc90feb3bd760d
|
Swapped ExpVector in for Vector implementation
|
diff --git a/src/main/scala/com/codecommit/collection/ExpVector.scala b/src/main/scala/com/codecommit/collection/ExpVector.scala
deleted file mode 100644
index 4061c99..0000000
--- a/src/main/scala/com/codecommit/collection/ExpVector.scala
+++ /dev/null
@@ -1,751 +0,0 @@
-/**
- Copyright (c) 2007-2008, Rich Hickey
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- * Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials provided
- with the distribution.
-
- * Neither the name of Clojure nor the names of its contributors
- may be used to endorse or promote products derived from this
- software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- **/
-
-package com.codecommit.collection
-
-import ExpVector._
-import VectorCases._
-
-/**
- * A straight port of Clojure's <code>PersistentVector</code> class.
- *
- * @author Daniel Spiewak
- * @author Rich Hickey
- */
-class ExpVector[+T] private (val length: Int, trie: Case, tail: Array[AnyRef]) extends RandomAccessSeq[T] { outer =>
- private val tailOff = length - tail.length
-
- /*
- * The design of this data structure inherantly requires heterogenous arrays.
- * It is *possible* to design around this, but the result is comparatively
- * quite inefficient. With respect to this fact, I have left the original
- * (somewhat dynamically-typed) implementation in place.
- */
-
- private[collection] def this() = this(0, Zero, EmptyArray)
-
- def apply(i: Int): T = {
- if (i >= 0 && i < length) {
- if (i >= tailOff) {
- tail(i & 0x01f).asInstanceOf[T]
- } else {
- var arr = trie(i)
- arr(i & 0x01f).asInstanceOf[T]
- }
- } else throw new IndexOutOfBoundsException(i.toString)
- }
-
- def update[A >: T](i: Int, obj: A): ExpVector[A] = {
- if (i >= 0 && i < length) {
- if (i >= tailOff) {
- val newTail = new Array[AnyRef](tail.length)
- Array.copy(tail, 0, newTail, 0, tail.length)
- newTail(i & 0x01f) = obj.asInstanceOf[AnyRef]
-
- new ExpVector[A](length, trie, newTail)
- } else {
- new ExpVector[A](length, trie(i) = obj.asInstanceOf[AnyRef], tail)
- }
- } else if (i == length) {
- this + obj
- } else throw new IndexOutOfBoundsException(i.toString)
- }
-
- override def ++[A >: T](other: Iterable[A]) = other.foldLeft(this: ExpVector[A]) { _ + _ }
-
- def +[A >: T](obj: A): ExpVector[A] = {
- if (tail.length < 32) {
- val tail2 = new Array[AnyRef](tail.length + 1)
- Array.copy(tail, 0, tail2, 0, tail.length)
- tail2(tail.length) = obj.asInstanceOf[AnyRef]
-
- new ExpVector[A](length + 1, trie, tail2)
- } else {
- new ExpVector[A](length + 1, trie + tail, array(obj.asInstanceOf[AnyRef]))
- }
- }
-
- /**
- * Removes the <i>tail</i> element of this vector.
- */
- def pop: ExpVector[T] = {
- if (length == 0) {
- throw new IllegalStateException("Can't pop empty vector")
- } else if (length == 1) {
- EmptyExpVector
- } else if (tail.length > 1) {
- val tail2 = new Array[AnyRef](tail.length - 1)
- Array.copy(tail, 0, tail2, 0, tail2.length)
-
- new ExpVector[T](length - 1, trie, tail2)
- } else {
- val (trie2, tail2) = trie.pop
- new ExpVector[T](length - 1, trie2, tail2)
- }
- }
-
- override def filter(p: (T)=>Boolean) = {
- var back = new ExpVector[T]
- var i = 0
-
- while (i < length) {
- val e = apply(i)
- if (p(e)) back += e
-
- i += 1
- }
-
- back
- }
-
- override def flatMap[A](f: (T)=>Iterable[A]) = {
- var back = new ExpVector[A]
- var i = 0
-
- while (i < length) {
- f(apply(i)) foreach { back += _ }
- i += 1
- }
-
- back
- }
-
- override def map[A](f: (T)=>A) = {
- var back = new ExpVector[A]
- var i = 0
-
- while (i < length) {
- back += f(apply(i))
- i += 1
- }
-
- back
- }
-
- override def reverse: ExpVector[T] = new ExpVectorProjection[T] {
- override val length = outer.length
-
- override def apply(i: Int) = outer.apply(length - i - 1)
- }
-
- override def subseq(from: Int, end: Int) = subExpVector(from, end)
-
- def subExpVector(from: Int, end: Int): ExpVector[T] = {
- if (from < 0) {
- throw new IndexOutOfBoundsException(from.toString)
- } else if (end >= length) {
- throw new IndexOutOfBoundsException(end.toString)
- } else if (end <= from) {
- throw new IllegalArgumentException("Invalid range: " + from + ".." + end)
- } else {
- new ExpVectorProjection[T] {
- override val length = end - from
-
- override def apply(i: Int) = outer.apply(i + from)
- }
- }
- }
-
- def zip[A](that: ExpVector[A]) = {
- var back = new ExpVector[(T, A)]
- var i = 0
-
- val limit = Math.min(length, that.length)
- while (i < limit) {
- back += (apply(i), that(i))
- i += 1
- }
-
- back
- }
-
- def zipWithIndex = {
- var back = new ExpVector[(T, Int)]
- var i = 0
-
- while (i < length) {
- back += (apply(i), i)
- i += 1
- }
-
- back
- }
-
- override def equals(other: Any) = other match {
- case vec:ExpVector[T] => {
- var back = length == vec.length
- var i = 0
-
- while (i < length) {
- back &&= apply(i) == vec.apply(i)
- i += 1
- }
-
- back
- }
-
- case _ => false
- }
-
- override def hashCode = foldLeft(0) { _ ^ _.hashCode }
-}
-
-object ExpVector {
- private[collection] val EmptyArray = new Array[AnyRef](0)
-
- def apply[T](elems: T*) = elems.foldLeft(EmptyExpVector:ExpVector[T]) { _ + _ }
-
- def unapplySeq[T](vec: ExpVector[T]): Option[Seq[T]] = Some(vec)
-
- @inline
- private[collection] def array(elem: AnyRef) = {
- val back = new Array[AnyRef](1)
- back(0) = elem
- back
- }
-}
-
-object EmptyExpVector extends ExpVector[Nothing]
-
-private[collection] abstract class ExpVectorProjection[+T] extends ExpVector[T] {
- override val length: Int
- override def apply(i: Int): T
-
- override def +[A >: T](e: A) = innerCopy + e
-
- override def update[A >: T](i: Int, e: A) = {
- if (i < 0) {
- throw new IndexOutOfBoundsException(i.toString)
- } else if (i > length) {
- throw new IndexOutOfBoundsException(i.toString)
- } else innerCopy(i) = e
- }
-
- private lazy val innerCopy = foldLeft(EmptyExpVector:ExpVector[T]) { _ + _ }
-}
-
-private[collection] object VectorCases {
- private val SingletonArray1 = new Array[Array[AnyRef]](1)
- private val SingletonArray2 = new Array[Array[Array[AnyRef]]](1)
- private val SingletonArray3 = new Array[Array[Array[Array[AnyRef]]]](1)
- private val SingletonArray4 = new Array[Array[Array[Array[Array[AnyRef]]]]](1)
-
- private def copy[A](array: Array[A], length: Int): Array[A] = {
- val array2 = new Array[A](length)
- Array.copy(array, 0, array2, 0, Math.min(array.length, length))
- array2
- }
-
- private def copy[A](array: Array[A]): Array[A] = copy(array, array.length)
-
- sealed trait Case {
- type Self <: Case
-
- val shift: Int
-
- def apply(i: Int): Array[AnyRef]
- def update(i: Int, obj: AnyRef): Self
-
- def +(node: Array[AnyRef]): Case
- def pop: (Case, Array[AnyRef])
- }
-
- case object Zero extends Case {
- type Self = Nothing
-
- val shift = -1
-
- def apply(i: Int) = throw new IndexOutOfBoundsException(i.toString)
- def update(i: Int, obj: AnyRef) = throw new IndexOutOfBoundsException(i.toString)
-
- def +(node: Array[AnyRef]) = One(node)
- def pop = throw new IndexOutOfBoundsException("Cannot pop an empty Vector")
- }
-
- case class One(trie: Array[AnyRef]) extends Case {
- type Self = One
-
- val shift = 0
-
- def apply(i: Int) = trie
-
- def update(i: Int, obj: AnyRef) = {
- val trie2 = copy(trie)
- trie2(i & 0x01f) = obj
- One(trie2)
- }
-
- def +(tail: Array[AnyRef]) = {
- val trie2 = new Array[Array[AnyRef]](2)
- trie2(0) = trie
- trie2(1) = tail
- Two(trie2)
- }
-
- def pop = (Zero, trie)
- }
-
- case class Two(trie: Array[Array[AnyRef]]) extends Case {
- type Self = Two
-
- val shift = 5
-
- def apply(i: Int) = trie((i >>> 5) & 0x01f)
-
- def update(i: Int, obj: AnyRef) = {
- val trie2a = copy(trie)
-
- val trie2b = copy(trie2a((i >>> 5) & 0x01f))
- trie2a((i >>> 5) & 0x01f) = trie2b
-
- trie2b(i & 0x01f) = obj
- Two(trie2a)
- }
-
- def +(tail: Array[AnyRef]) = {
- if (trie.length >= 32) {
- val trie2 = new Array[Array[Array[AnyRef]]](2)
- trie2(0) = trie
-
- trie2(1) = SingletonArray1
- trie2(1)(0) = tail
-
- Three(trie2)
- } else {
- val trie2 = copy(trie, trie.length + 1)
- trie2(trie.length) = tail
- Two(trie2)
- }
- }
-
- def pop = {
- if (trie.length == 2) {
- (One(trie(0)), trie.last)
- } else {
- val trie2 = copy(trie, trie.length - 1)
- (Two(trie2), trie.last)
- }
- }
- }
-
- case class Three(trie: Array[Array[Array[AnyRef]]]) extends Case {
- type Self = Three
-
- val shift = 10
-
- def apply(i: Int) = {
- val a = trie((i >>> 10) & 0x01f)
- a((i >>> 5) & 0x01f)
- }
-
- def update(i: Int, obj: AnyRef) = {
- val trie2a = copy(trie)
-
- val trie2b = copy(trie2a((i >>> 10) & 0x01f))
- trie2a((i >>> 10) & 0x01f) = trie2b
-
- val trie2c = copy(trie2b((i >>> 5) & 0x01f))
- trie2b((i >>> 5) & 0x01f) = trie2c
-
- trie2c(i & 0x01f) = obj
- Three(trie2a)
- }
-
- def +(tail: Array[AnyRef]) = {
- if (trie.last.length >= 32) {
- if (trie.length >= 32) {
- val trie2 = new Array[Array[Array[Array[AnyRef]]]](2)
- trie2(0) = trie
-
- trie2(1) = SingletonArray2
- trie2(1)(0) = SingletonArray1
- trie2(1)(0)(0) = tail
-
- Four(trie2)
- } else {
- val trie2 = copy(trie, trie.length + 1)
- trie2(trie.length) = SingletonArray1
- trie2(trie.length)(0) = tail
- Three(trie2)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
- trie2.last(trie.last.length) = tail
- Three(trie2)
- }
- }
-
- def pop = {
- if (trie.last.length == 1) {
- if (trie.length == 2) {
- (Two(trie(0)), trie.last.last)
- } else {
- val trie2 = copy(trie, trie.length - 1)
- (Three(trie2), trie.last.last)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- (Three(trie2), trie.last.last)
- }
- }
- }
-
- case class Four(trie: Array[Array[Array[Array[AnyRef]]]]) extends Case {
- type Self = Four
-
- val shift = 15
-
- def apply(i: Int) = {
- val a = trie((i >>> 15) & 0x01f)
- val b = a((i >>> 10) & 0x01f)
- b((i >>> 5) & 0x01f)
- }
-
- def update(i: Int, obj: AnyRef) = {
- val trie2a = copy(trie)
-
- val trie2b = copy(trie2a((i >>> 15) & 0x01f))
- trie2a((i >>> 15) & 0x01f) = trie2b
-
- val trie2c = copy(trie2b((i >>> 10) & 0x01f))
- trie2b((i >>> 10) & 0x01f) = trie2c
-
- val trie2d = copy(trie2c((i >>> 5) & 0x01f))
- trie2c((i >>> 5) & 0x01f) = trie2d
-
- trie2d(i & 0x01f) = obj
- Four(trie2a)
- }
-
- def +(tail: Array[AnyRef]) = {
- if (trie.last.last.length >= 32) {
- if (trie.last.length >= 32) {
- if (trie.length >= 32) {
- val trie2 = new Array[Array[Array[Array[Array[AnyRef]]]]](2)
- trie2(0) = trie
-
- trie2(1) = SingletonArray3
- trie2(1)(0) = SingletonArray2
- trie2(1)(0)(0) = SingletonArray1
- trie2(1)(0)(0)(0) = tail
-
- Five(trie2)
- } else {
- val trie2 = copy(trie, trie.length + 1)
- trie2(trie.length) = SingletonArray2
- trie2(trie.length)(0) = SingletonArray1
- trie2(trie.length)(0)(0) = tail
- Four(trie2)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
- trie2.last(trie.last.length) = SingletonArray1
- trie2.last.last(0) = tail
- Four(trie2)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length + 1)
- trie2.last.last(trie.last.last.length) = tail
- Four(trie2)
- }
- }
-
- def pop = {
- if (trie.last.last.length == 1) {
- if (trie.last.length == 1) {
- if (trie.length == 2) {
- (Three(trie(0)), trie.last.last.last)
- } else {
- val trie2 = copy(trie, trie.length - 1)
- (Four(trie2), trie.last.last.last)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- (Four(trie2), trie.last.last.last)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
- (Four(trie2), trie.last.last.last)
- }
- }
- }
-
- case class Five(trie: Array[Array[Array[Array[Array[AnyRef]]]]]) extends Case {
- type Self = Five
-
- val shift = 20
-
- def apply(i: Int) = {
- val a = trie((i >>> 20) & 0x01f)
- val b = a((i >>> 15) & 0x01f)
- val c = b((i >>> 10) & 0x01f)
- c((i >>> 5) & 0x01f)
- }
-
- def update(i: Int, obj: AnyRef) = {
- val trie2a = copy(trie)
-
- val trie2b = copy(trie2a((i >>> 20) & 0x01f))
- trie2a((i >>> 20) & 0x01f) = trie2b
-
- val trie2c = copy(trie2b((i >>> 15) & 0x01f))
- trie2b((i >>> 15) & 0x01f) = trie2c
-
- val trie2d = copy(trie2c((i >>> 10) & 0x01f))
- trie2c((i >>> 10) & 0x01f) = trie2d
-
- val trie2e = copy(trie2d((i >>> 5) & 0x01f))
- trie2d((i >>> 5) & 0x01f) = trie2e
-
- trie2e(i & 0x01f) = obj
- Five(trie2a)
- }
-
- def +(tail: Array[AnyRef]) = {
- if (trie.last.last.last.length >= 32) {
- if (trie.last.last.length >= 32) {
- if (trie.last.length >= 32) {
- if (trie.length >= 32) {
- val trie2 = new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](2)
- trie2(0) = trie
-
- trie2(1) = SingletonArray4
- trie2(1)(0) = SingletonArray3
- trie2(1)(0)(0) = SingletonArray2
- trie2(1)(0)(0)(0) = SingletonArray1
- trie2(1)(0)(0)(0)(0) = tail
-
- Six(trie2)
- } else {
- val trie2 = copy(trie, trie.length + 1)
- trie2(trie.length) = SingletonArray3
- trie2(trie.length)(0) = SingletonArray2
- trie2(trie.length)(0)(0) = SingletonArray1
- trie2(trie.length)(0)(0)(0) = tail
- Five(trie2)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
- trie2.last(trie.last.length) = SingletonArray2
- trie2.last.last(0) = SingletonArray1
- trie2.last.last.last(0) = tail
- Five(trie2)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length + 1)
- trie2.last.last(trie.last.last.length) = SingletonArray1
- trie2.last.last.last(0) = tail
- Five(trie2)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last)
- trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length + 1)
- trie2.last.last.last(trie.last.last.last.length) = tail
- Five(trie2)
- }
- }
-
- def pop = {
- if (trie.last.last.last.length == 1) {
- if (trie.last.last.length == 1) {
- if (trie.last.length == 1) {
- if (trie.length == 2) {
- (Four(trie(0)), trie.last.last.last.last)
- } else {
- val trie2 = copy(trie, trie.length - 1)
- (Five(trie2), trie.last.last.last.last)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- (Five(trie2), trie.last.last.last.last)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
- (Five(trie2), trie.last.last.last.last)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
- trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length - 1)
- (Five(trie2), trie.last.last.last.last)
- }
- }
- }
-
- case class Six(trie: Array[Array[Array[Array[Array[Array[AnyRef]]]]]]) extends Case {
- type Self = Six
-
- val shift = 25
-
- def apply(i: Int) = {
- val a = trie((i >>> 25) & 0x01f)
- val b = a((i >>> 20) & 0x01f)
- val c = b((i >>> 15) & 0x01f)
- val d = c((i >>> 10) & 0x01f)
- d((i >>> 5) & 0x01f)
- }
-
- def update(i: Int, obj: AnyRef) = {
- val trie2a = copy(trie)
-
- val trie2b = copy(trie2a((i >>> 25) & 0x01f))
- trie2a((i >>> 25) & 0x01f) = trie2b
-
- val trie2c = copy(trie2b((i >>> 20) & 0x01f))
- trie2b((i >>> 20) & 0x01f) = trie2c
-
- val trie2d = copy(trie2c((i >>> 15) & 0x01f))
- trie2c((i >>> 15) & 0x01f) = trie2d
-
- val trie2e = copy(trie2d((i >>> 10) & 0x01f))
- trie2d((i >>> 10) & 0x01f) = trie2e
-
- val trie2f = copy(trie2e((i >>> 5) & 0x01f))
- trie2e((i >>> 5) & 0x01f) = trie2f
-
- trie2f(i & 0x01f) = obj
- Six(trie2a)
- }
-
- def +(tail: Array[AnyRef]) = {
- if (trie.last.last.last.last.length >= 32) {
- if (trie.last.last.last.length >= 32) {
- if (trie.last.last.length >= 32) {
- if (trie.last.length >= 32) {
- if (trie.length >= 32) {
- throw new IndexOutOfBoundsException("Cannot grow vector beyond integer bounds")
- } else {
- val trie2 = copy(trie, trie.length + 1)
- trie2(trie.length) = SingletonArray4
- trie2(trie.length)(0) = SingletonArray3
- trie2(trie.length)(0)(0) = SingletonArray2
- trie2(trie.length)(0)(0)(0) = SingletonArray1
- trie2(trie.length)(0)(0)(0)(0) = tail
- Six(trie2)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
- trie2.last(trie.last.length) = SingletonArray3
- trie2.last.last(0) = SingletonArray2
- trie2.last.last.last(0) = SingletonArray1
- trie2.last.last.last.last(0) = tail
- Six(trie2)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length + 1)
- trie2.last.last(trie.last.last.length) = SingletonArray2
- trie2.last.last.last(0) = SingletonArray1
- trie2.last.last.last.last(0) = tail
- Six(trie2)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last)
- trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length + 1)
- trie2.last.last.last(trie.last.last.last.length) = SingletonArray1
- trie2.last.last.last.last(0) = tail
- Six(trie2)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last)
- trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last)
- trie2.last.last.last(trie.last.last.last.length - 1) = copy(trie2.last.last.last.last, trie2.last.last.last.last.length + 1)
- trie2.last.last.last.last(trie.last.last.last.last.length) = tail
- Six(trie2)
- }
- }
-
- def pop = {
- if (trie.last.last.last.last.length == 1) {
- if (trie.last.last.last.length == 1) {
- if (trie.last.last.length == 1) {
- if (trie.last.length == 1) {
- if (trie.length == 2) {
- (Five(trie(0)), trie.last.last.last.last.last)
- } else {
- val trie2 = copy(trie, trie.length - 1)
- (Six(trie2), trie.last.last.last.last.last)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- (Six(trie2), trie.last.last.last.last.last)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
- (Six(trie2), trie.last.last.last.last.last)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
- trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length - 1)
- (Six(trie2), trie.last.last.last.last.last)
- }
- } else {
- val trie2 = copy(trie)
- trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
- trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
- trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length - 1)
- trie2.last.last.last(trie2.last.last.last.length - 1) = copy(trie2.last.last.last.last, trie2.last.last.last.last.length - 1)
- (Six(trie2), trie.last.last.last.last.last)
- }
- }
- }
-}
diff --git a/src/main/scala/com/codecommit/collection/Vector.scala b/src/main/scala/com/codecommit/collection/Vector.scala
index 5bbfc96..cad74a2 100644
--- a/src/main/scala/com/codecommit/collection/Vector.scala
+++ b/src/main/scala/com/codecommit/collection/Vector.scala
@@ -1,351 +1,751 @@
/**
Copyright (c) 2007-2008, Rich Hickey
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Clojure nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**/
package com.codecommit.collection
import Vector._
+import VectorCases._
/**
* A straight port of Clojure's <code>PersistentVector</code> class.
*
* @author Daniel Spiewak
* @author Rich Hickey
*/
-class Vector[+T] private (val length: Int, shift: Int, root: Array[AnyRef], tail: Array[AnyRef]) extends RandomAccessSeq[T] { outer =>
+class Vector[+T] private (val length: Int, trie: Case, tail: Array[AnyRef]) extends RandomAccessSeq[T] { outer =>
private val tailOff = length - tail.length
/*
* The design of this data structure inherantly requires heterogenous arrays.
* It is *possible* to design around this, but the result is comparatively
* quite inefficient. With respect to this fact, I have left the original
* (somewhat dynamically-typed) implementation in place.
*/
- private[collection] def this() = this(0, 5, EmptyArray, EmptyArray)
+ private[collection] def this() = this(0, Zero, EmptyArray)
def apply(i: Int): T = {
if (i >= 0 && i < length) {
if (i >= tailOff) {
tail(i & 0x01f).asInstanceOf[T]
} else {
- var arr = root
- var level = shift
-
- while (level > 0) {
- arr = arr((i >>> level) & 0x01f).asInstanceOf[Array[AnyRef]]
- level -= 5
- }
-
+ var arr = trie(i)
arr(i & 0x01f).asInstanceOf[T]
}
} else throw new IndexOutOfBoundsException(i.toString)
}
def update[A >: T](i: Int, obj: A): Vector[A] = {
if (i >= 0 && i < length) {
if (i >= tailOff) {
val newTail = new Array[AnyRef](tail.length)
Array.copy(tail, 0, newTail, 0, tail.length)
newTail(i & 0x01f) = obj.asInstanceOf[AnyRef]
- new Vector[A](length, shift, root, newTail)
+ new Vector[A](length, trie, newTail)
} else {
- new Vector[A](length, shift, doAssoc(shift, root, i, obj), tail)
+ new Vector[A](length, trie(i) = obj.asInstanceOf[AnyRef], tail)
}
} else if (i == length) {
this + obj
} else throw new IndexOutOfBoundsException(i.toString)
}
- private def doAssoc[A >: T](level: Int, arr: Array[AnyRef], i: Int, obj: A): Array[AnyRef] = {
- val ret = new Array[AnyRef](arr.length)
- Array.copy(arr, 0, ret, 0, arr.length)
-
- if (level == 0) {
- ret(i & 0x01f) = obj.asInstanceOf[AnyRef]
- } else {
- val subidx = (i >>> level) & 0x01f
- ret(subidx) = doAssoc(level - 5, arr(subidx).asInstanceOf[Array[AnyRef]], i, obj)
- }
-
- ret
- }
-
- override def ++[A >: T](other: Iterable[A]) = other.foldLeft(this:Vector[A]) { _ + _ }
+ override def ++[A >: T](other: Iterable[A]) = other.foldLeft(this: Vector[A]) { _ + _ }
def +[A >: T](obj: A): Vector[A] = {
if (tail.length < 32) {
- val newTail = new Array[AnyRef](tail.length + 1)
- Array.copy(tail, 0, newTail, 0, tail.length)
- newTail(tail.length) = obj.asInstanceOf[AnyRef]
+ val tail2 = new Array[AnyRef](tail.length + 1)
+ Array.copy(tail, 0, tail2, 0, tail.length)
+ tail2(tail.length) = obj.asInstanceOf[AnyRef]
- new Vector[A](length + 1, shift, root, newTail)
+ new Vector[A](length + 1, trie, tail2)
} else {
- var (newRoot, expansion) = pushTail(shift - 5, root, tail, null)
- var newShift = shift
-
- if (expansion != null) {
- newRoot = array(newRoot, expansion)
- newShift += 5
- }
-
- new Vector[A](length + 1, newShift, newRoot, array(obj.asInstanceOf[AnyRef]))
- }
- }
-
- private def pushTail(level: Int, arr: Array[AnyRef], tailNode: Array[AnyRef], expansion: AnyRef): (Array[AnyRef], AnyRef) = {
- val newChild = if (level == 0) tailNode else {
- val (newChild, subExpansion) = pushTail(level - 5, arr(arr.length - 1).asInstanceOf[Array[AnyRef]], tailNode, expansion)
-
- if (subExpansion == null) {
- val ret = new Array[AnyRef](arr.length)
- Array.copy(arr, 0, ret, 0, arr.length)
-
- ret(arr.length - 1) = newChild
-
- return (ret, null)
- } else subExpansion
- }
-
- // expansion
- if (arr.length == 32) {
- (arr, array(newChild))
- } else {
- val ret = new Array[AnyRef](arr.length + 1)
- Array.copy(arr, 0, ret, 0, arr.length)
- ret(arr.length) = newChild
-
- (ret, null)
+ new Vector[A](length + 1, trie + tail, array(obj.asInstanceOf[AnyRef]))
}
}
/**
* Removes the <i>tail</i> element of this vector.
*/
def pop: Vector[T] = {
if (length == 0) {
throw new IllegalStateException("Can't pop empty vector")
} else if (length == 1) {
EmptyVector
} else if (tail.length > 1) {
- val newTail = new Array[AnyRef](tail.length - 1)
- Array.copy(tail, 0, newTail, 0, newTail.length)
+ val tail2 = new Array[AnyRef](tail.length - 1)
+ Array.copy(tail, 0, tail2, 0, tail2.length)
- new Vector[T](length - 1, shift, root, newTail)
+ new Vector[T](length - 1, trie, tail2)
} else {
- var (newRoot, pTail) = popTail(shift - 5, root, null)
- var newShift = shift
-
- if (newRoot == null) {
- newRoot = EmptyArray
- }
-
- if (shift > 5 && newRoot.length == 1) {
- newRoot = newRoot(0).asInstanceOf[Array[AnyRef]]
- newShift -= 5
- }
-
- new Vector[T](length - 1, newShift, newRoot, pTail.asInstanceOf[Array[AnyRef]])
- }
- }
-
- private def popTail(shift: Int, arr: Array[AnyRef], pTail: AnyRef): (Array[AnyRef], AnyRef) = {
- val newPTail = if (shift > 0) {
- val (newChild, subPTail) = popTail(shift - 5, arr(arr.length - 1).asInstanceOf[Array[AnyRef]], pTail)
-
- if (newChild != null) {
- val ret = new Array[AnyRef](arr.length)
- Array.copy(arr, 0, ret, 0, arr.length)
-
- ret(arr.length - 1) = newChild
-
- return (ret, subPTail)
- }
- subPTail
- } else if (shift == 0) {
- arr(arr.length - 1)
- } else pTail
-
- // contraction
- if (arr.length == 1) {
- (null, newPTail)
- } else {
- val ret = new Array[AnyRef](arr.length - 1)
- Array.copy(arr, 0, ret, 0, ret.length)
-
- (ret, newPTail)
+ val (trie2, tail2) = trie.pop
+ new Vector[T](length - 1, trie2, tail2)
}
}
override def filter(p: (T)=>Boolean) = {
var back = new Vector[T]
var i = 0
while (i < length) {
val e = apply(i)
if (p(e)) back += e
i += 1
}
back
}
override def flatMap[A](f: (T)=>Iterable[A]) = {
var back = new Vector[A]
var i = 0
while (i < length) {
f(apply(i)) foreach { back += _ }
i += 1
}
back
}
override def map[A](f: (T)=>A) = {
var back = new Vector[A]
var i = 0
while (i < length) {
back += f(apply(i))
i += 1
}
back
}
override def reverse: Vector[T] = new VectorProjection[T] {
override val length = outer.length
override def apply(i: Int) = outer.apply(length - i - 1)
}
override def subseq(from: Int, end: Int) = subVector(from, end)
def subVector(from: Int, end: Int): Vector[T] = {
if (from < 0) {
throw new IndexOutOfBoundsException(from.toString)
} else if (end >= length) {
throw new IndexOutOfBoundsException(end.toString)
} else if (end <= from) {
throw new IllegalArgumentException("Invalid range: " + from + ".." + end)
} else {
new VectorProjection[T] {
override val length = end - from
override def apply(i: Int) = outer.apply(i + from)
}
}
}
def zip[A](that: Vector[A]) = {
var back = new Vector[(T, A)]
var i = 0
val limit = Math.min(length, that.length)
while (i < limit) {
back += (apply(i), that(i))
i += 1
}
back
}
def zipWithIndex = {
var back = new Vector[(T, Int)]
var i = 0
while (i < length) {
back += (apply(i), i)
i += 1
}
back
}
override def equals(other: Any) = other match {
case vec:Vector[T] => {
var back = length == vec.length
var i = 0
while (i < length) {
back &&= apply(i) == vec.apply(i)
i += 1
}
back
}
case _ => false
}
override def hashCode = foldLeft(0) { _ ^ _.hashCode }
}
object Vector {
private[collection] val EmptyArray = new Array[AnyRef](0)
def apply[T](elems: T*) = elems.foldLeft(EmptyVector:Vector[T]) { _ + _ }
def unapplySeq[T](vec: Vector[T]): Option[Seq[T]] = Some(vec)
@inline
- private[collection] def array(elems: AnyRef*) = {
- val back = new Array[AnyRef](elems.length)
- Array.copy(elems, 0, back, 0, back.length)
-
+ private[collection] def array(elem: AnyRef) = {
+ val back = new Array[AnyRef](1)
+ back(0) = elem
back
}
}
object EmptyVector extends Vector[Nothing]
private[collection] abstract class VectorProjection[+T] extends Vector[T] {
override val length: Int
override def apply(i: Int): T
override def +[A >: T](e: A) = innerCopy + e
override def update[A >: T](i: Int, e: A) = {
if (i < 0) {
throw new IndexOutOfBoundsException(i.toString)
} else if (i > length) {
throw new IndexOutOfBoundsException(i.toString)
} else innerCopy(i) = e
}
private lazy val innerCopy = foldLeft(EmptyVector:Vector[T]) { _ + _ }
}
+private[collection] object VectorCases {
+ private val SingletonArray1 = new Array[Array[AnyRef]](1)
+ private val SingletonArray2 = new Array[Array[Array[AnyRef]]](1)
+ private val SingletonArray3 = new Array[Array[Array[Array[AnyRef]]]](1)
+ private val SingletonArray4 = new Array[Array[Array[Array[Array[AnyRef]]]]](1)
+
+ private def copy[A](array: Array[A], length: Int): Array[A] = {
+ val array2 = new Array[A](length)
+ Array.copy(array, 0, array2, 0, Math.min(array.length, length))
+ array2
+ }
+
+ private def copy[A](array: Array[A]): Array[A] = copy(array, array.length)
+
+ sealed trait Case {
+ type Self <: Case
+
+ val shift: Int
+
+ def apply(i: Int): Array[AnyRef]
+ def update(i: Int, obj: AnyRef): Self
+
+ def +(node: Array[AnyRef]): Case
+ def pop: (Case, Array[AnyRef])
+ }
+
+ case object Zero extends Case {
+ type Self = Nothing
+
+ val shift = -1
+
+ def apply(i: Int) = throw new IndexOutOfBoundsException(i.toString)
+ def update(i: Int, obj: AnyRef) = throw new IndexOutOfBoundsException(i.toString)
+
+ def +(node: Array[AnyRef]) = One(node)
+ def pop = throw new IndexOutOfBoundsException("Cannot pop an empty Vector")
+ }
+
+ case class One(trie: Array[AnyRef]) extends Case {
+ type Self = One
+
+ val shift = 0
+
+ def apply(i: Int) = trie
+
+ def update(i: Int, obj: AnyRef) = {
+ val trie2 = copy(trie)
+ trie2(i & 0x01f) = obj
+ One(trie2)
+ }
+
+ def +(tail: Array[AnyRef]) = {
+ val trie2 = new Array[Array[AnyRef]](2)
+ trie2(0) = trie
+ trie2(1) = tail
+ Two(trie2)
+ }
+
+ def pop = (Zero, trie)
+ }
+
+ case class Two(trie: Array[Array[AnyRef]]) extends Case {
+ type Self = Two
+
+ val shift = 5
+
+ def apply(i: Int) = trie((i >>> 5) & 0x01f)
+
+ def update(i: Int, obj: AnyRef) = {
+ val trie2a = copy(trie)
+
+ val trie2b = copy(trie2a((i >>> 5) & 0x01f))
+ trie2a((i >>> 5) & 0x01f) = trie2b
+
+ trie2b(i & 0x01f) = obj
+ Two(trie2a)
+ }
+
+ def +(tail: Array[AnyRef]) = {
+ if (trie.length >= 32) {
+ val trie2 = new Array[Array[Array[AnyRef]]](2)
+ trie2(0) = trie
+
+ trie2(1) = SingletonArray1
+ trie2(1)(0) = tail
+
+ Three(trie2)
+ } else {
+ val trie2 = copy(trie, trie.length + 1)
+ trie2(trie.length) = tail
+ Two(trie2)
+ }
+ }
+
+ def pop = {
+ if (trie.length == 2) {
+ (One(trie(0)), trie.last)
+ } else {
+ val trie2 = copy(trie, trie.length - 1)
+ (Two(trie2), trie.last)
+ }
+ }
+ }
+
+ case class Three(trie: Array[Array[Array[AnyRef]]]) extends Case {
+ type Self = Three
+
+ val shift = 10
+
+ def apply(i: Int) = {
+ val a = trie((i >>> 10) & 0x01f)
+ a((i >>> 5) & 0x01f)
+ }
+
+ def update(i: Int, obj: AnyRef) = {
+ val trie2a = copy(trie)
+
+ val trie2b = copy(trie2a((i >>> 10) & 0x01f))
+ trie2a((i >>> 10) & 0x01f) = trie2b
+
+ val trie2c = copy(trie2b((i >>> 5) & 0x01f))
+ trie2b((i >>> 5) & 0x01f) = trie2c
+
+ trie2c(i & 0x01f) = obj
+ Three(trie2a)
+ }
+
+ def +(tail: Array[AnyRef]) = {
+ if (trie.last.length >= 32) {
+ if (trie.length >= 32) {
+ val trie2 = new Array[Array[Array[Array[AnyRef]]]](2)
+ trie2(0) = trie
+
+ trie2(1) = SingletonArray2
+ trie2(1)(0) = SingletonArray1
+ trie2(1)(0)(0) = tail
+
+ Four(trie2)
+ } else {
+ val trie2 = copy(trie, trie.length + 1)
+ trie2(trie.length) = SingletonArray1
+ trie2(trie.length)(0) = tail
+ Three(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
+ trie2.last(trie.last.length) = tail
+ Three(trie2)
+ }
+ }
+
+ def pop = {
+ if (trie.last.length == 1) {
+ if (trie.length == 2) {
+ (Two(trie(0)), trie.last.last)
+ } else {
+ val trie2 = copy(trie, trie.length - 1)
+ (Three(trie2), trie.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ (Three(trie2), trie.last.last)
+ }
+ }
+ }
+
+ case class Four(trie: Array[Array[Array[Array[AnyRef]]]]) extends Case {
+ type Self = Four
+
+ val shift = 15
+
+ def apply(i: Int) = {
+ val a = trie((i >>> 15) & 0x01f)
+ val b = a((i >>> 10) & 0x01f)
+ b((i >>> 5) & 0x01f)
+ }
+
+ def update(i: Int, obj: AnyRef) = {
+ val trie2a = copy(trie)
+
+ val trie2b = copy(trie2a((i >>> 15) & 0x01f))
+ trie2a((i >>> 15) & 0x01f) = trie2b
+
+ val trie2c = copy(trie2b((i >>> 10) & 0x01f))
+ trie2b((i >>> 10) & 0x01f) = trie2c
+
+ val trie2d = copy(trie2c((i >>> 5) & 0x01f))
+ trie2c((i >>> 5) & 0x01f) = trie2d
+
+ trie2d(i & 0x01f) = obj
+ Four(trie2a)
+ }
+
+ def +(tail: Array[AnyRef]) = {
+ if (trie.last.last.length >= 32) {
+ if (trie.last.length >= 32) {
+ if (trie.length >= 32) {
+ val trie2 = new Array[Array[Array[Array[Array[AnyRef]]]]](2)
+ trie2(0) = trie
+
+ trie2(1) = SingletonArray3
+ trie2(1)(0) = SingletonArray2
+ trie2(1)(0)(0) = SingletonArray1
+ trie2(1)(0)(0)(0) = tail
+
+ Five(trie2)
+ } else {
+ val trie2 = copy(trie, trie.length + 1)
+ trie2(trie.length) = SingletonArray2
+ trie2(trie.length)(0) = SingletonArray1
+ trie2(trie.length)(0)(0) = tail
+ Four(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
+ trie2.last(trie.last.length) = SingletonArray1
+ trie2.last.last(0) = tail
+ Four(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length + 1)
+ trie2.last.last(trie.last.last.length) = tail
+ Four(trie2)
+ }
+ }
+
+ def pop = {
+ if (trie.last.last.length == 1) {
+ if (trie.last.length == 1) {
+ if (trie.length == 2) {
+ (Three(trie(0)), trie.last.last.last)
+ } else {
+ val trie2 = copy(trie, trie.length - 1)
+ (Four(trie2), trie.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ (Four(trie2), trie.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ (Four(trie2), trie.last.last.last)
+ }
+ }
+ }
+
+ case class Five(trie: Array[Array[Array[Array[Array[AnyRef]]]]]) extends Case {
+ type Self = Five
+
+ val shift = 20
+
+ def apply(i: Int) = {
+ val a = trie((i >>> 20) & 0x01f)
+ val b = a((i >>> 15) & 0x01f)
+ val c = b((i >>> 10) & 0x01f)
+ c((i >>> 5) & 0x01f)
+ }
+
+ def update(i: Int, obj: AnyRef) = {
+ val trie2a = copy(trie)
+
+ val trie2b = copy(trie2a((i >>> 20) & 0x01f))
+ trie2a((i >>> 20) & 0x01f) = trie2b
+
+ val trie2c = copy(trie2b((i >>> 15) & 0x01f))
+ trie2b((i >>> 15) & 0x01f) = trie2c
+
+ val trie2d = copy(trie2c((i >>> 10) & 0x01f))
+ trie2c((i >>> 10) & 0x01f) = trie2d
+
+ val trie2e = copy(trie2d((i >>> 5) & 0x01f))
+ trie2d((i >>> 5) & 0x01f) = trie2e
+
+ trie2e(i & 0x01f) = obj
+ Five(trie2a)
+ }
+
+ def +(tail: Array[AnyRef]) = {
+ if (trie.last.last.last.length >= 32) {
+ if (trie.last.last.length >= 32) {
+ if (trie.last.length >= 32) {
+ if (trie.length >= 32) {
+ val trie2 = new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](2)
+ trie2(0) = trie
+
+ trie2(1) = SingletonArray4
+ trie2(1)(0) = SingletonArray3
+ trie2(1)(0)(0) = SingletonArray2
+ trie2(1)(0)(0)(0) = SingletonArray1
+ trie2(1)(0)(0)(0)(0) = tail
+
+ Six(trie2)
+ } else {
+ val trie2 = copy(trie, trie.length + 1)
+ trie2(trie.length) = SingletonArray3
+ trie2(trie.length)(0) = SingletonArray2
+ trie2(trie.length)(0)(0) = SingletonArray1
+ trie2(trie.length)(0)(0)(0) = tail
+ Five(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
+ trie2.last(trie.last.length) = SingletonArray2
+ trie2.last.last(0) = SingletonArray1
+ trie2.last.last.last(0) = tail
+ Five(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length + 1)
+ trie2.last.last(trie.last.last.length) = SingletonArray1
+ trie2.last.last.last(0) = tail
+ Five(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last)
+ trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length + 1)
+ trie2.last.last.last(trie.last.last.last.length) = tail
+ Five(trie2)
+ }
+ }
+
+ def pop = {
+ if (trie.last.last.last.length == 1) {
+ if (trie.last.last.length == 1) {
+ if (trie.last.length == 1) {
+ if (trie.length == 2) {
+ (Four(trie(0)), trie.last.last.last.last)
+ } else {
+ val trie2 = copy(trie, trie.length - 1)
+ (Five(trie2), trie.last.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ (Five(trie2), trie.last.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ (Five(trie2), trie.last.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length - 1)
+ (Five(trie2), trie.last.last.last.last)
+ }
+ }
+ }
+
+ case class Six(trie: Array[Array[Array[Array[Array[Array[AnyRef]]]]]]) extends Case {
+ type Self = Six
+
+ val shift = 25
+
+ def apply(i: Int) = {
+ val a = trie((i >>> 25) & 0x01f)
+ val b = a((i >>> 20) & 0x01f)
+ val c = b((i >>> 15) & 0x01f)
+ val d = c((i >>> 10) & 0x01f)
+ d((i >>> 5) & 0x01f)
+ }
+
+ def update(i: Int, obj: AnyRef) = {
+ val trie2a = copy(trie)
+
+ val trie2b = copy(trie2a((i >>> 25) & 0x01f))
+ trie2a((i >>> 25) & 0x01f) = trie2b
+
+ val trie2c = copy(trie2b((i >>> 20) & 0x01f))
+ trie2b((i >>> 20) & 0x01f) = trie2c
+
+ val trie2d = copy(trie2c((i >>> 15) & 0x01f))
+ trie2c((i >>> 15) & 0x01f) = trie2d
+
+ val trie2e = copy(trie2d((i >>> 10) & 0x01f))
+ trie2d((i >>> 10) & 0x01f) = trie2e
+
+ val trie2f = copy(trie2e((i >>> 5) & 0x01f))
+ trie2e((i >>> 5) & 0x01f) = trie2f
+
+ trie2f(i & 0x01f) = obj
+ Six(trie2a)
+ }
+
+ def +(tail: Array[AnyRef]) = {
+ if (trie.last.last.last.last.length >= 32) {
+ if (trie.last.last.last.length >= 32) {
+ if (trie.last.last.length >= 32) {
+ if (trie.last.length >= 32) {
+ if (trie.length >= 32) {
+ throw new IndexOutOfBoundsException("Cannot grow vector beyond integer bounds")
+ } else {
+ val trie2 = copy(trie, trie.length + 1)
+ trie2(trie.length) = SingletonArray4
+ trie2(trie.length)(0) = SingletonArray3
+ trie2(trie.length)(0)(0) = SingletonArray2
+ trie2(trie.length)(0)(0)(0) = SingletonArray1
+ trie2(trie.length)(0)(0)(0)(0) = tail
+ Six(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
+ trie2.last(trie.last.length) = SingletonArray3
+ trie2.last.last(0) = SingletonArray2
+ trie2.last.last.last(0) = SingletonArray1
+ trie2.last.last.last.last(0) = tail
+ Six(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length + 1)
+ trie2.last.last(trie.last.last.length) = SingletonArray2
+ trie2.last.last.last(0) = SingletonArray1
+ trie2.last.last.last.last(0) = tail
+ Six(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last)
+ trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length + 1)
+ trie2.last.last.last(trie.last.last.last.length) = SingletonArray1
+ trie2.last.last.last.last(0) = tail
+ Six(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last)
+ trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last)
+ trie2.last.last.last(trie.last.last.last.length - 1) = copy(trie2.last.last.last.last, trie2.last.last.last.last.length + 1)
+ trie2.last.last.last.last(trie.last.last.last.last.length) = tail
+ Six(trie2)
+ }
+ }
+
+ def pop = {
+ if (trie.last.last.last.last.length == 1) {
+ if (trie.last.last.last.length == 1) {
+ if (trie.last.last.length == 1) {
+ if (trie.last.length == 1) {
+ if (trie.length == 2) {
+ (Five(trie(0)), trie.last.last.last.last.last)
+ } else {
+ val trie2 = copy(trie, trie.length - 1)
+ (Six(trie2), trie.last.last.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ (Six(trie2), trie.last.last.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ (Six(trie2), trie.last.last.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length - 1)
+ (Six(trie2), trie.last.last.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length - 1)
+ trie2.last.last.last(trie2.last.last.last.length - 1) = copy(trie2.last.last.last.last, trie2.last.last.last.last.length - 1)
+ (Six(trie2), trie.last.last.last.last.last)
+ }
+ }
+ }
+}
|
djspiewak/scala-collections
|
11f05df7ae7c0a1fd04a8fd4a66d20d93e7778b3
|
Created experimental Vector implementation with inline cases
|
diff --git a/src/main/scala/com/codecommit/collection/ExpVector.scala b/src/main/scala/com/codecommit/collection/ExpVector.scala
new file mode 100644
index 0000000..4061c99
--- /dev/null
+++ b/src/main/scala/com/codecommit/collection/ExpVector.scala
@@ -0,0 +1,751 @@
+/**
+ Copyright (c) 2007-2008, Rich Hickey
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+ * Neither the name of Clojure nor the names of its contributors
+ may be used to endorse or promote products derived from this
+ software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ **/
+
+package com.codecommit.collection
+
+import ExpVector._
+import VectorCases._
+
+/**
+ * A straight port of Clojure's <code>PersistentVector</code> class.
+ *
+ * @author Daniel Spiewak
+ * @author Rich Hickey
+ */
+class ExpVector[+T] private (val length: Int, trie: Case, tail: Array[AnyRef]) extends RandomAccessSeq[T] { outer =>
+ private val tailOff = length - tail.length
+
+ /*
+ * The design of this data structure inherantly requires heterogenous arrays.
+ * It is *possible* to design around this, but the result is comparatively
+ * quite inefficient. With respect to this fact, I have left the original
+ * (somewhat dynamically-typed) implementation in place.
+ */
+
+ private[collection] def this() = this(0, Zero, EmptyArray)
+
+ def apply(i: Int): T = {
+ if (i >= 0 && i < length) {
+ if (i >= tailOff) {
+ tail(i & 0x01f).asInstanceOf[T]
+ } else {
+ var arr = trie(i)
+ arr(i & 0x01f).asInstanceOf[T]
+ }
+ } else throw new IndexOutOfBoundsException(i.toString)
+ }
+
+ def update[A >: T](i: Int, obj: A): ExpVector[A] = {
+ if (i >= 0 && i < length) {
+ if (i >= tailOff) {
+ val newTail = new Array[AnyRef](tail.length)
+ Array.copy(tail, 0, newTail, 0, tail.length)
+ newTail(i & 0x01f) = obj.asInstanceOf[AnyRef]
+
+ new ExpVector[A](length, trie, newTail)
+ } else {
+ new ExpVector[A](length, trie(i) = obj.asInstanceOf[AnyRef], tail)
+ }
+ } else if (i == length) {
+ this + obj
+ } else throw new IndexOutOfBoundsException(i.toString)
+ }
+
+ override def ++[A >: T](other: Iterable[A]) = other.foldLeft(this: ExpVector[A]) { _ + _ }
+
+ def +[A >: T](obj: A): ExpVector[A] = {
+ if (tail.length < 32) {
+ val tail2 = new Array[AnyRef](tail.length + 1)
+ Array.copy(tail, 0, tail2, 0, tail.length)
+ tail2(tail.length) = obj.asInstanceOf[AnyRef]
+
+ new ExpVector[A](length + 1, trie, tail2)
+ } else {
+ new ExpVector[A](length + 1, trie + tail, array(obj.asInstanceOf[AnyRef]))
+ }
+ }
+
+ /**
+ * Removes the <i>tail</i> element of this vector.
+ */
+ def pop: ExpVector[T] = {
+ if (length == 0) {
+ throw new IllegalStateException("Can't pop empty vector")
+ } else if (length == 1) {
+ EmptyExpVector
+ } else if (tail.length > 1) {
+ val tail2 = new Array[AnyRef](tail.length - 1)
+ Array.copy(tail, 0, tail2, 0, tail2.length)
+
+ new ExpVector[T](length - 1, trie, tail2)
+ } else {
+ val (trie2, tail2) = trie.pop
+ new ExpVector[T](length - 1, trie2, tail2)
+ }
+ }
+
+ override def filter(p: (T)=>Boolean) = {
+ var back = new ExpVector[T]
+ var i = 0
+
+ while (i < length) {
+ val e = apply(i)
+ if (p(e)) back += e
+
+ i += 1
+ }
+
+ back
+ }
+
+ override def flatMap[A](f: (T)=>Iterable[A]) = {
+ var back = new ExpVector[A]
+ var i = 0
+
+ while (i < length) {
+ f(apply(i)) foreach { back += _ }
+ i += 1
+ }
+
+ back
+ }
+
+ override def map[A](f: (T)=>A) = {
+ var back = new ExpVector[A]
+ var i = 0
+
+ while (i < length) {
+ back += f(apply(i))
+ i += 1
+ }
+
+ back
+ }
+
+ override def reverse: ExpVector[T] = new ExpVectorProjection[T] {
+ override val length = outer.length
+
+ override def apply(i: Int) = outer.apply(length - i - 1)
+ }
+
+ override def subseq(from: Int, end: Int) = subExpVector(from, end)
+
+ def subExpVector(from: Int, end: Int): ExpVector[T] = {
+ if (from < 0) {
+ throw new IndexOutOfBoundsException(from.toString)
+ } else if (end >= length) {
+ throw new IndexOutOfBoundsException(end.toString)
+ } else if (end <= from) {
+ throw new IllegalArgumentException("Invalid range: " + from + ".." + end)
+ } else {
+ new ExpVectorProjection[T] {
+ override val length = end - from
+
+ override def apply(i: Int) = outer.apply(i + from)
+ }
+ }
+ }
+
+ def zip[A](that: ExpVector[A]) = {
+ var back = new ExpVector[(T, A)]
+ var i = 0
+
+ val limit = Math.min(length, that.length)
+ while (i < limit) {
+ back += (apply(i), that(i))
+ i += 1
+ }
+
+ back
+ }
+
+ def zipWithIndex = {
+ var back = new ExpVector[(T, Int)]
+ var i = 0
+
+ while (i < length) {
+ back += (apply(i), i)
+ i += 1
+ }
+
+ back
+ }
+
+ override def equals(other: Any) = other match {
+ case vec:ExpVector[T] => {
+ var back = length == vec.length
+ var i = 0
+
+ while (i < length) {
+ back &&= apply(i) == vec.apply(i)
+ i += 1
+ }
+
+ back
+ }
+
+ case _ => false
+ }
+
+ override def hashCode = foldLeft(0) { _ ^ _.hashCode }
+}
+
+object ExpVector {
+ private[collection] val EmptyArray = new Array[AnyRef](0)
+
+ def apply[T](elems: T*) = elems.foldLeft(EmptyExpVector:ExpVector[T]) { _ + _ }
+
+ def unapplySeq[T](vec: ExpVector[T]): Option[Seq[T]] = Some(vec)
+
+ @inline
+ private[collection] def array(elem: AnyRef) = {
+ val back = new Array[AnyRef](1)
+ back(0) = elem
+ back
+ }
+}
+
+object EmptyExpVector extends ExpVector[Nothing]
+
+private[collection] abstract class ExpVectorProjection[+T] extends ExpVector[T] {
+ override val length: Int
+ override def apply(i: Int): T
+
+ override def +[A >: T](e: A) = innerCopy + e
+
+ override def update[A >: T](i: Int, e: A) = {
+ if (i < 0) {
+ throw new IndexOutOfBoundsException(i.toString)
+ } else if (i > length) {
+ throw new IndexOutOfBoundsException(i.toString)
+ } else innerCopy(i) = e
+ }
+
+ private lazy val innerCopy = foldLeft(EmptyExpVector:ExpVector[T]) { _ + _ }
+}
+
+private[collection] object VectorCases {
+ private val SingletonArray1 = new Array[Array[AnyRef]](1)
+ private val SingletonArray2 = new Array[Array[Array[AnyRef]]](1)
+ private val SingletonArray3 = new Array[Array[Array[Array[AnyRef]]]](1)
+ private val SingletonArray4 = new Array[Array[Array[Array[Array[AnyRef]]]]](1)
+
+ private def copy[A](array: Array[A], length: Int): Array[A] = {
+ val array2 = new Array[A](length)
+ Array.copy(array, 0, array2, 0, Math.min(array.length, length))
+ array2
+ }
+
+ private def copy[A](array: Array[A]): Array[A] = copy(array, array.length)
+
+ sealed trait Case {
+ type Self <: Case
+
+ val shift: Int
+
+ def apply(i: Int): Array[AnyRef]
+ def update(i: Int, obj: AnyRef): Self
+
+ def +(node: Array[AnyRef]): Case
+ def pop: (Case, Array[AnyRef])
+ }
+
+ case object Zero extends Case {
+ type Self = Nothing
+
+ val shift = -1
+
+ def apply(i: Int) = throw new IndexOutOfBoundsException(i.toString)
+ def update(i: Int, obj: AnyRef) = throw new IndexOutOfBoundsException(i.toString)
+
+ def +(node: Array[AnyRef]) = One(node)
+ def pop = throw new IndexOutOfBoundsException("Cannot pop an empty Vector")
+ }
+
+ case class One(trie: Array[AnyRef]) extends Case {
+ type Self = One
+
+ val shift = 0
+
+ def apply(i: Int) = trie
+
+ def update(i: Int, obj: AnyRef) = {
+ val trie2 = copy(trie)
+ trie2(i & 0x01f) = obj
+ One(trie2)
+ }
+
+ def +(tail: Array[AnyRef]) = {
+ val trie2 = new Array[Array[AnyRef]](2)
+ trie2(0) = trie
+ trie2(1) = tail
+ Two(trie2)
+ }
+
+ def pop = (Zero, trie)
+ }
+
+ case class Two(trie: Array[Array[AnyRef]]) extends Case {
+ type Self = Two
+
+ val shift = 5
+
+ def apply(i: Int) = trie((i >>> 5) & 0x01f)
+
+ def update(i: Int, obj: AnyRef) = {
+ val trie2a = copy(trie)
+
+ val trie2b = copy(trie2a((i >>> 5) & 0x01f))
+ trie2a((i >>> 5) & 0x01f) = trie2b
+
+ trie2b(i & 0x01f) = obj
+ Two(trie2a)
+ }
+
+ def +(tail: Array[AnyRef]) = {
+ if (trie.length >= 32) {
+ val trie2 = new Array[Array[Array[AnyRef]]](2)
+ trie2(0) = trie
+
+ trie2(1) = SingletonArray1
+ trie2(1)(0) = tail
+
+ Three(trie2)
+ } else {
+ val trie2 = copy(trie, trie.length + 1)
+ trie2(trie.length) = tail
+ Two(trie2)
+ }
+ }
+
+ def pop = {
+ if (trie.length == 2) {
+ (One(trie(0)), trie.last)
+ } else {
+ val trie2 = copy(trie, trie.length - 1)
+ (Two(trie2), trie.last)
+ }
+ }
+ }
+
+ case class Three(trie: Array[Array[Array[AnyRef]]]) extends Case {
+ type Self = Three
+
+ val shift = 10
+
+ def apply(i: Int) = {
+ val a = trie((i >>> 10) & 0x01f)
+ a((i >>> 5) & 0x01f)
+ }
+
+ def update(i: Int, obj: AnyRef) = {
+ val trie2a = copy(trie)
+
+ val trie2b = copy(trie2a((i >>> 10) & 0x01f))
+ trie2a((i >>> 10) & 0x01f) = trie2b
+
+ val trie2c = copy(trie2b((i >>> 5) & 0x01f))
+ trie2b((i >>> 5) & 0x01f) = trie2c
+
+ trie2c(i & 0x01f) = obj
+ Three(trie2a)
+ }
+
+ def +(tail: Array[AnyRef]) = {
+ if (trie.last.length >= 32) {
+ if (trie.length >= 32) {
+ val trie2 = new Array[Array[Array[Array[AnyRef]]]](2)
+ trie2(0) = trie
+
+ trie2(1) = SingletonArray2
+ trie2(1)(0) = SingletonArray1
+ trie2(1)(0)(0) = tail
+
+ Four(trie2)
+ } else {
+ val trie2 = copy(trie, trie.length + 1)
+ trie2(trie.length) = SingletonArray1
+ trie2(trie.length)(0) = tail
+ Three(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
+ trie2.last(trie.last.length) = tail
+ Three(trie2)
+ }
+ }
+
+ def pop = {
+ if (trie.last.length == 1) {
+ if (trie.length == 2) {
+ (Two(trie(0)), trie.last.last)
+ } else {
+ val trie2 = copy(trie, trie.length - 1)
+ (Three(trie2), trie.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ (Three(trie2), trie.last.last)
+ }
+ }
+ }
+
+ case class Four(trie: Array[Array[Array[Array[AnyRef]]]]) extends Case {
+ type Self = Four
+
+ val shift = 15
+
+ def apply(i: Int) = {
+ val a = trie((i >>> 15) & 0x01f)
+ val b = a((i >>> 10) & 0x01f)
+ b((i >>> 5) & 0x01f)
+ }
+
+ def update(i: Int, obj: AnyRef) = {
+ val trie2a = copy(trie)
+
+ val trie2b = copy(trie2a((i >>> 15) & 0x01f))
+ trie2a((i >>> 15) & 0x01f) = trie2b
+
+ val trie2c = copy(trie2b((i >>> 10) & 0x01f))
+ trie2b((i >>> 10) & 0x01f) = trie2c
+
+ val trie2d = copy(trie2c((i >>> 5) & 0x01f))
+ trie2c((i >>> 5) & 0x01f) = trie2d
+
+ trie2d(i & 0x01f) = obj
+ Four(trie2a)
+ }
+
+ def +(tail: Array[AnyRef]) = {
+ if (trie.last.last.length >= 32) {
+ if (trie.last.length >= 32) {
+ if (trie.length >= 32) {
+ val trie2 = new Array[Array[Array[Array[Array[AnyRef]]]]](2)
+ trie2(0) = trie
+
+ trie2(1) = SingletonArray3
+ trie2(1)(0) = SingletonArray2
+ trie2(1)(0)(0) = SingletonArray1
+ trie2(1)(0)(0)(0) = tail
+
+ Five(trie2)
+ } else {
+ val trie2 = copy(trie, trie.length + 1)
+ trie2(trie.length) = SingletonArray2
+ trie2(trie.length)(0) = SingletonArray1
+ trie2(trie.length)(0)(0) = tail
+ Four(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
+ trie2.last(trie.last.length) = SingletonArray1
+ trie2.last.last(0) = tail
+ Four(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length + 1)
+ trie2.last.last(trie.last.last.length) = tail
+ Four(trie2)
+ }
+ }
+
+ def pop = {
+ if (trie.last.last.length == 1) {
+ if (trie.last.length == 1) {
+ if (trie.length == 2) {
+ (Three(trie(0)), trie.last.last.last)
+ } else {
+ val trie2 = copy(trie, trie.length - 1)
+ (Four(trie2), trie.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ (Four(trie2), trie.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ (Four(trie2), trie.last.last.last)
+ }
+ }
+ }
+
+ case class Five(trie: Array[Array[Array[Array[Array[AnyRef]]]]]) extends Case {
+ type Self = Five
+
+ val shift = 20
+
+ def apply(i: Int) = {
+ val a = trie((i >>> 20) & 0x01f)
+ val b = a((i >>> 15) & 0x01f)
+ val c = b((i >>> 10) & 0x01f)
+ c((i >>> 5) & 0x01f)
+ }
+
+ def update(i: Int, obj: AnyRef) = {
+ val trie2a = copy(trie)
+
+ val trie2b = copy(trie2a((i >>> 20) & 0x01f))
+ trie2a((i >>> 20) & 0x01f) = trie2b
+
+ val trie2c = copy(trie2b((i >>> 15) & 0x01f))
+ trie2b((i >>> 15) & 0x01f) = trie2c
+
+ val trie2d = copy(trie2c((i >>> 10) & 0x01f))
+ trie2c((i >>> 10) & 0x01f) = trie2d
+
+ val trie2e = copy(trie2d((i >>> 5) & 0x01f))
+ trie2d((i >>> 5) & 0x01f) = trie2e
+
+ trie2e(i & 0x01f) = obj
+ Five(trie2a)
+ }
+
+ def +(tail: Array[AnyRef]) = {
+ if (trie.last.last.last.length >= 32) {
+ if (trie.last.last.length >= 32) {
+ if (trie.last.length >= 32) {
+ if (trie.length >= 32) {
+ val trie2 = new Array[Array[Array[Array[Array[Array[AnyRef]]]]]](2)
+ trie2(0) = trie
+
+ trie2(1) = SingletonArray4
+ trie2(1)(0) = SingletonArray3
+ trie2(1)(0)(0) = SingletonArray2
+ trie2(1)(0)(0)(0) = SingletonArray1
+ trie2(1)(0)(0)(0)(0) = tail
+
+ Six(trie2)
+ } else {
+ val trie2 = copy(trie, trie.length + 1)
+ trie2(trie.length) = SingletonArray3
+ trie2(trie.length)(0) = SingletonArray2
+ trie2(trie.length)(0)(0) = SingletonArray1
+ trie2(trie.length)(0)(0)(0) = tail
+ Five(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
+ trie2.last(trie.last.length) = SingletonArray2
+ trie2.last.last(0) = SingletonArray1
+ trie2.last.last.last(0) = tail
+ Five(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length + 1)
+ trie2.last.last(trie.last.last.length) = SingletonArray1
+ trie2.last.last.last(0) = tail
+ Five(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last)
+ trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length + 1)
+ trie2.last.last.last(trie.last.last.last.length) = tail
+ Five(trie2)
+ }
+ }
+
+ def pop = {
+ if (trie.last.last.last.length == 1) {
+ if (trie.last.last.length == 1) {
+ if (trie.last.length == 1) {
+ if (trie.length == 2) {
+ (Four(trie(0)), trie.last.last.last.last)
+ } else {
+ val trie2 = copy(trie, trie.length - 1)
+ (Five(trie2), trie.last.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ (Five(trie2), trie.last.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ (Five(trie2), trie.last.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length - 1)
+ (Five(trie2), trie.last.last.last.last)
+ }
+ }
+ }
+
+ case class Six(trie: Array[Array[Array[Array[Array[Array[AnyRef]]]]]]) extends Case {
+ type Self = Six
+
+ val shift = 25
+
+ def apply(i: Int) = {
+ val a = trie((i >>> 25) & 0x01f)
+ val b = a((i >>> 20) & 0x01f)
+ val c = b((i >>> 15) & 0x01f)
+ val d = c((i >>> 10) & 0x01f)
+ d((i >>> 5) & 0x01f)
+ }
+
+ def update(i: Int, obj: AnyRef) = {
+ val trie2a = copy(trie)
+
+ val trie2b = copy(trie2a((i >>> 25) & 0x01f))
+ trie2a((i >>> 25) & 0x01f) = trie2b
+
+ val trie2c = copy(trie2b((i >>> 20) & 0x01f))
+ trie2b((i >>> 20) & 0x01f) = trie2c
+
+ val trie2d = copy(trie2c((i >>> 15) & 0x01f))
+ trie2c((i >>> 15) & 0x01f) = trie2d
+
+ val trie2e = copy(trie2d((i >>> 10) & 0x01f))
+ trie2d((i >>> 10) & 0x01f) = trie2e
+
+ val trie2f = copy(trie2e((i >>> 5) & 0x01f))
+ trie2e((i >>> 5) & 0x01f) = trie2f
+
+ trie2f(i & 0x01f) = obj
+ Six(trie2a)
+ }
+
+ def +(tail: Array[AnyRef]) = {
+ if (trie.last.last.last.last.length >= 32) {
+ if (trie.last.last.last.length >= 32) {
+ if (trie.last.last.length >= 32) {
+ if (trie.last.length >= 32) {
+ if (trie.length >= 32) {
+ throw new IndexOutOfBoundsException("Cannot grow vector beyond integer bounds")
+ } else {
+ val trie2 = copy(trie, trie.length + 1)
+ trie2(trie.length) = SingletonArray4
+ trie2(trie.length)(0) = SingletonArray3
+ trie2(trie.length)(0)(0) = SingletonArray2
+ trie2(trie.length)(0)(0)(0) = SingletonArray1
+ trie2(trie.length)(0)(0)(0)(0) = tail
+ Six(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length + 1)
+ trie2.last(trie.last.length) = SingletonArray3
+ trie2.last.last(0) = SingletonArray2
+ trie2.last.last.last(0) = SingletonArray1
+ trie2.last.last.last.last(0) = tail
+ Six(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length + 1)
+ trie2.last.last(trie.last.last.length) = SingletonArray2
+ trie2.last.last.last(0) = SingletonArray1
+ trie2.last.last.last.last(0) = tail
+ Six(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last)
+ trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length + 1)
+ trie2.last.last.last(trie.last.last.last.length) = SingletonArray1
+ trie2.last.last.last.last(0) = tail
+ Six(trie2)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last)
+ trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last)
+ trie2.last.last.last(trie.last.last.last.length - 1) = copy(trie2.last.last.last.last, trie2.last.last.last.last.length + 1)
+ trie2.last.last.last.last(trie.last.last.last.last.length) = tail
+ Six(trie2)
+ }
+ }
+
+ def pop = {
+ if (trie.last.last.last.last.length == 1) {
+ if (trie.last.last.last.length == 1) {
+ if (trie.last.last.length == 1) {
+ if (trie.last.length == 1) {
+ if (trie.length == 2) {
+ (Five(trie(0)), trie.last.last.last.last.last)
+ } else {
+ val trie2 = copy(trie, trie.length - 1)
+ (Six(trie2), trie.last.last.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ (Six(trie2), trie.last.last.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ (Six(trie2), trie.last.last.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length - 1)
+ (Six(trie2), trie.last.last.last.last.last)
+ }
+ } else {
+ val trie2 = copy(trie)
+ trie2(trie2.length - 1) = copy(trie2.last, trie2.last.length - 1)
+ trie2.last(trie2.last.length - 1) = copy(trie2.last.last, trie2.last.last.length - 1)
+ trie2.last.last(trie2.last.last.length - 1) = copy(trie2.last.last.last, trie2.last.last.last.length - 1)
+ trie2.last.last.last(trie2.last.last.last.length - 1) = copy(trie2.last.last.last.last, trie2.last.last.last.last.length - 1)
+ (Six(trie2), trie.last.last.last.last.last)
+ }
+ }
+ }
+}
|
djspiewak/scala-collections
|
826d6d0f6f2e5d7f64937e65f925afa5658187dc
|
Removed obsolete code
|
diff --git a/src/main/scala/com/codecommit/collection/FingerTree.scala b/src/main/scala/com/codecommit/collection/FingerTree.scala
index 193fb4f..07c1095 100644
--- a/src/main/scala/com/codecommit/collection/FingerTree.scala
+++ b/src/main/scala/com/codecommit/collection/FingerTree.scala
@@ -1,269 +1,259 @@
package com.codecommit.collection
object FingerTree {
sealed trait FingerTree[+A] {
val isEmpty: Boolean
def headLeft: A
def tailLeft: FingerTree[A]
def headRight: A
def tailRight: FingerTree[A]
def +:[B >: A](b: B): FingerTree[B]
def +[B >: A](b: B): FingerTree[B]
def viewLeft: FTViewLeft[FingerTree, A]
def viewRight: FTViewRight[FingerTree, A]
def iterator: Iterator[A]
}
case class Single[+A](a: A) extends FingerTree[A] {
val headLeft = a
val tailLeft = Empty
val headRight = a
val tailRight = Empty
val isEmpty = false
def +:[B >: A](b: B) = Deep(One(b), Empty, One(a))
- def +:[B >: A](node: Node[B]) = node match {
- case Node2(b, c) => Deep(Two(b, c), Empty, One(a))
- case Node3(b, c, d) => Deep(Two(b, c), Empty, Two(d, a))
- }
-
def +[B >: A](b: B) = Deep(One(a), Empty, One(b))
- def +[B >: A](node: Node[B]) = node match {
- case Node2(b, c) => Deep(One(a), Empty, Two(b, c))
- case Node3(b, c, d) => Deep(Two(a, b), Empty, Two(c, d))
- }
-
def viewLeft = FTConsLeft[FingerTree, A](a, Empty)
def viewRight = FTConsRight[FingerTree, A](Empty, a)
def iterator = new Iterator[A] {
var hasNext = true
def next = {
hasNext = false
a
}
}
override def toString = "FingerTree(Single(%s))".format(a)
}
case class Deep[+A](prefix: Digit[A], tree: FingerTree[Node[A]], suffix: Digit[A]) extends FingerTree[A] {
val isEmpty = false
val headLeft = prefix.headLeft
val headRight = suffix.headRight
def tailLeft = viewLeft.tail
def tailRight = viewRight.tail
def +:[B >: A](b: B) = prefix match {
case Four(d, e, f, g) => Deep(Two(b, d), Node3(d, e, f) +: tree, suffix)
case partial => Deep(b :: partial, tree, suffix)
}
def +[B >: A](b: B) = suffix match {
case Four(g, f, e, d) => Deep(prefix, tree + Node3(g, f, e), Two(d, b))
case partial => Deep(prefix, tree, partial + b)
}
def viewLeft = {
def deep(prefix: Digit[A], tree: FingerTree[Node[A]], suffix: Digit[A]) = prefix match {
case One(_) => {
tree.viewLeft match {
case FTConsLeft(a, newTree) => Deep(a.toDigit, newTree, suffix)
case FTNilLeft() => suffix.toTree
}
}
case prefix => Deep(prefix.tailLeft, tree, suffix)
}
FTConsLeft(prefix.headLeft, deep(prefix, tree, suffix))
}
def viewRight = {
def deep(prefix: Digit[A], tree: FingerTree[Node[A]], suffix: Digit[A]) = suffix match {
case One(_) => {
tree.viewRight match {
case FTConsRight(newTree, a) => Deep(prefix, newTree, a.toDigit)
case FTNilRight() => prefix.toTree
}
}
case suffix => Deep(prefix, tree, suffix.tailRight)
}
FTConsRight(deep(prefix, tree, suffix.tailRight), suffix.headRight)
}
def iterator = prefix.iterator ++ (tree.iterator flatMap { _.toList.iterator }) ++ suffix.iterator
override def toString = "FingerTree(%s, %s, %s)".format(prefix, tree, suffix)
}
case object Empty extends FingerTree[Nothing] {
val isEmpty = true
def headLeft = throw new NoSuchElementException("headLeft on empty finger tree")
def tailLeft = throw new NoSuchElementException("tailLeft on empty finger tree")
def headRight = throw new NoSuchElementException("headRight on empty finger tree")
def tailRight = throw new NoSuchElementException("tailRight on empty finger tree")
def +:[A](a: A) = Single(a)
def +[A](a: A) = Single(a)
def viewLeft = FTNilLeft[FingerTree]()
def viewRight = FTNilRight[FingerTree]()
def iterator = new Iterator[Nothing] {
val hasNext = false
def next = throw new NoSuchElementException
}
override def toString = "FingerTree(Empty)"
}
sealed trait Node[+A] {
def toDigit: Digit[A]
def toList: List[A]
}
case class Node2[+A](a1: A, a2: A) extends Node[A] {
def toDigit = Two(a1, a2)
def toList = List(a1, a2)
override def toString = "Node2(%s, %s)".format(a1, a2)
}
case class Node3[+A](a1: A, a2: A, a3: A) extends Node[A] {
def toDigit = Three(a1, a2, a3)
def toList = List(a1, a2, a3)
override def toString = "Node3(%s, %s, %s)".format(a1, a2, a3)
}
sealed trait FTViewLeft[+S[+_], +A] {
def head: A
def tail: S[A]
}
case class FTConsLeft[+S[+_], +A](head: A, tail: S[A]) extends FTViewLeft[S, A]
case class FTNilLeft[+S[+_]]() extends FTViewLeft[S, Nothing] {
def head = throw new NoSuchElementException("head on empty view")
def tail = throw new NoSuchElementException("tail on empty view")
}
sealed trait FTViewRight[+S[+_], +A] {
def tail: S[A]
def head: A
}
case class FTConsRight[+S[+_], +A](tail: S[A], head: A) extends FTViewRight[S, A]
case class FTNilRight[+S[+_]]() extends FTViewRight[S, Nothing] {
def tail = throw new NoSuchElementException("tail on empty view")
def head = throw new NoSuchElementException("head on empty view")
}
sealed trait Digit[+A] {
val headLeft: A
def tailLeft: Digit[A]
val headRight: A
def tailRight: Digit[A]
def ::[B >: A](b: B): Digit[B]
def +[B >: A](b: B): Digit[B]
def toTree: FingerTree[A]
def iterator: Iterator[A]
}
case class One[+A](a1: A) extends Digit[A] {
val headLeft = a1
def tailLeft = throw new NoSuchElementException("tail on digit: one")
val headRight = a1
def tailRight = throw new NoSuchElementException("tail on digit: one")
def ::[B >: A](b: B) = Two(b, a1)
def +[B >: A](b: B) = Two(a1, b)
def toTree = Single(a1)
def iterator = new Iterator[A] {
var hasNext = true
def next = {
hasNext = false
a1
}
}
}
case class Two[+A](a1: A, a2: A) extends Digit[A] {
val headLeft = a1
def tailLeft = One(a2)
val headRight = a2
def tailRight = One(a1)
def ::[B >: A](b: B) = Three(b, a1, a2)
def +[B >: A](b: B) = Three(a1, a2, b)
def toTree = a1 +: Single(a2)
def iterator = (a1 :: a2 :: Nil).iterator
}
case class Three[+A](a1: A, a2: A, a3: A) extends Digit[A] {
val headLeft = a1
def tailLeft = Two(a2, a3)
val headRight = a3
def tailRight = Two(a1, a2)
def ::[B >: A](b: B) = Four(b, a1, a2, a3)
def +[B >: A](b: B) = Four(a1, a2, a3, b)
def toTree = a1 +: a2 +: Single(a3)
def iterator = (a1 :: a2 :: a3 :: Nil).iterator
}
case class Four[+A](a1: A, a2: A, a3: A, a4: A) extends Digit[A] {
val headLeft = a1
def tailLeft = Three(a2, a3, a4)
val headRight = a4
def tailRight = Three(a1, a2, a3)
def ::[B >: A](b: B) = throw new UnsupportedOperationException(":: on Four")
def +[B >: A](b: B) = throw new UnsupportedOperationException("+ on Four")
def toTree = a1 +: a2 +: a3 +: Single(a4)
def iterator = (a1 :: a2 :: a3 :: a4 :: Nil).iterator
}
}
|
djspiewak/scala-collections
|
f87dea9a151a721d5619230bd99482976960fff5
|
Adjusted Deep implementation to use Digit rather than List
|
diff --git a/src/main/scala/com/codecommit/collection/FingerTree.scala b/src/main/scala/com/codecommit/collection/FingerTree.scala
index a9f2c09..193fb4f 100644
--- a/src/main/scala/com/codecommit/collection/FingerTree.scala
+++ b/src/main/scala/com/codecommit/collection/FingerTree.scala
@@ -1,181 +1,269 @@
package com.codecommit.collection
object FingerTree {
sealed trait FingerTree[+A] {
val isEmpty: Boolean
def headLeft: A
def tailLeft: FingerTree[A]
def headRight: A
def tailRight: FingerTree[A]
def +:[B >: A](b: B): FingerTree[B]
def +[B >: A](b: B): FingerTree[B]
def viewLeft: FTViewLeft[FingerTree, A]
def viewRight: FTViewRight[FingerTree, A]
def iterator: Iterator[A]
}
case class Single[+A](a: A) extends FingerTree[A] {
val headLeft = a
val tailLeft = Empty
val headRight = a
val tailRight = Empty
val isEmpty = false
- def +:[B >: A](b: B) = Deep(List(b), Empty, List(a))
+ def +:[B >: A](b: B) = Deep(One(b), Empty, One(a))
def +:[B >: A](node: Node[B]) = node match {
- case Node2(b, c) => Deep(List(b, c), Empty, List(a))
- case Node3(b, c, d) => Deep(List(b, c), Empty, List(d, a))
+ case Node2(b, c) => Deep(Two(b, c), Empty, One(a))
+ case Node3(b, c, d) => Deep(Two(b, c), Empty, Two(d, a))
}
- def +[B >: A](b: B) = Deep(List(a), Empty, List(b))
+ def +[B >: A](b: B) = Deep(One(a), Empty, One(b))
def +[B >: A](node: Node[B]) = node match {
- case Node2(b, c) => Deep(List(a), Empty, List(b, c))
- case Node3(b, c, d) => Deep(List(a, b), Empty, List(c, d))
+ case Node2(b, c) => Deep(One(a), Empty, Two(b, c))
+ case Node3(b, c, d) => Deep(Two(a, b), Empty, Two(c, d))
}
def viewLeft = FTConsLeft[FingerTree, A](a, Empty)
def viewRight = FTConsRight[FingerTree, A](Empty, a)
def iterator = new Iterator[A] {
var hasNext = true
def next = {
hasNext = false
a
}
}
override def toString = "FingerTree(Single(%s))".format(a)
}
- case class Deep[+A](prefix: List[A], tree: FingerTree[Node[A]], suffix: List[A]) extends FingerTree[A] {
+ case class Deep[+A](prefix: Digit[A], tree: FingerTree[Node[A]], suffix: Digit[A]) extends FingerTree[A] {
val isEmpty = false
- val headLeft = prefix.head
- val headRight = suffix.last
+ val headLeft = prefix.headLeft
+ val headRight = suffix.headRight
def tailLeft = viewLeft.tail
def tailRight = viewRight.tail
def +:[B >: A](b: B) = prefix match {
- case d :: e :: f :: g :: Nil => Deep(List(b, d), Node3(d, e, f) +: tree, suffix)
+ case Four(d, e, f, g) => Deep(Two(b, d), Node3(d, e, f) +: tree, suffix)
case partial => Deep(b :: partial, tree, suffix)
}
def +[B >: A](b: B) = suffix match {
- case g :: f :: e :: d :: Nil => Deep(prefix, tree + Node3(g, f, e), List(d, b))
- case partial => Deep(prefix, tree, partial ::: List(b))
+ case Four(g, f, e, d) => Deep(prefix, tree + Node3(g, f, e), Two(d, b))
+ case partial => Deep(prefix, tree, partial + b)
}
def viewLeft = {
- def deep(prefix: List[A], tree: FingerTree[Node[A]], suffix: List[A]) = prefix match {
- case Nil => {
+ def deep(prefix: Digit[A], tree: FingerTree[Node[A]], suffix: Digit[A]) = prefix match {
+ case One(_) => {
tree.viewLeft match {
- case FTConsLeft(a, newTree) => Deep(a.toList, newTree, suffix)
- case FTNilLeft() => (suffix :\ (Empty: FingerTree[A])) { _ +: _ }
+ case FTConsLeft(a, newTree) => Deep(a.toDigit, newTree, suffix)
+ case FTNilLeft() => suffix.toTree
}
}
- case prefix => Deep(prefix, tree, suffix)
+ case prefix => Deep(prefix.tailLeft, tree, suffix)
}
- FTConsLeft(prefix.head, deep(prefix.tail, tree, suffix))
+ FTConsLeft(prefix.headLeft, deep(prefix, tree, suffix))
}
def viewRight = {
- def deep(prefix: List[A], tree: FingerTree[Node[A]], suffix: List[A]) = suffix match {
- case Nil => {
+ def deep(prefix: Digit[A], tree: FingerTree[Node[A]], suffix: Digit[A]) = suffix match {
+ case One(_) => {
tree.viewRight match {
- case FTConsRight(newTree, a) => Deep(prefix, newTree, a.toList)
- case FTNilRight() => (prefix :\ (Empty: FingerTree[A])) { _ +: _ }
+ case FTConsRight(newTree, a) => Deep(prefix, newTree, a.toDigit)
+ case FTNilRight() => prefix.toTree
}
}
- case suffix => Deep(prefix, tree, suffix)
+ case suffix => Deep(prefix, tree, suffix.tailRight)
}
- FTConsRight(deep(prefix, tree, suffix dropRight 1), suffix.last)
+ FTConsRight(deep(prefix, tree, suffix.tailRight), suffix.headRight)
}
def iterator = prefix.iterator ++ (tree.iterator flatMap { _.toList.iterator }) ++ suffix.iterator
override def toString = "FingerTree(%s, %s, %s)".format(prefix, tree, suffix)
}
case object Empty extends FingerTree[Nothing] {
val isEmpty = true
def headLeft = throw new NoSuchElementException("headLeft on empty finger tree")
def tailLeft = throw new NoSuchElementException("tailLeft on empty finger tree")
def headRight = throw new NoSuchElementException("headRight on empty finger tree")
def tailRight = throw new NoSuchElementException("tailRight on empty finger tree")
def +:[A](a: A) = Single(a)
def +[A](a: A) = Single(a)
def viewLeft = FTNilLeft[FingerTree]()
def viewRight = FTNilRight[FingerTree]()
def iterator = new Iterator[Nothing] {
val hasNext = false
def next = throw new NoSuchElementException
}
override def toString = "FingerTree(Empty)"
}
sealed trait Node[+A] {
+ def toDigit: Digit[A]
def toList: List[A]
}
case class Node2[+A](a1: A, a2: A) extends Node[A] {
+ def toDigit = Two(a1, a2)
+
def toList = List(a1, a2)
override def toString = "Node2(%s, %s)".format(a1, a2)
}
case class Node3[+A](a1: A, a2: A, a3: A) extends Node[A] {
+ def toDigit = Three(a1, a2, a3)
+
def toList = List(a1, a2, a3)
override def toString = "Node3(%s, %s, %s)".format(a1, a2, a3)
}
sealed trait FTViewLeft[+S[+_], +A] {
def head: A
def tail: S[A]
}
case class FTConsLeft[+S[+_], +A](head: A, tail: S[A]) extends FTViewLeft[S, A]
case class FTNilLeft[+S[+_]]() extends FTViewLeft[S, Nothing] {
def head = throw new NoSuchElementException("head on empty view")
def tail = throw new NoSuchElementException("tail on empty view")
}
sealed trait FTViewRight[+S[+_], +A] {
def tail: S[A]
def head: A
}
case class FTConsRight[+S[+_], +A](tail: S[A], head: A) extends FTViewRight[S, A]
case class FTNilRight[+S[+_]]() extends FTViewRight[S, Nothing] {
def tail = throw new NoSuchElementException("tail on empty view")
def head = throw new NoSuchElementException("head on empty view")
}
+
+
+ sealed trait Digit[+A] {
+ val headLeft: A
+ def tailLeft: Digit[A]
+
+ val headRight: A
+ def tailRight: Digit[A]
+
+ def ::[B >: A](b: B): Digit[B]
+ def +[B >: A](b: B): Digit[B]
+
+ def toTree: FingerTree[A]
+
+ def iterator: Iterator[A]
+ }
+
+ case class One[+A](a1: A) extends Digit[A] {
+ val headLeft = a1
+ def tailLeft = throw new NoSuchElementException("tail on digit: one")
+
+ val headRight = a1
+ def tailRight = throw new NoSuchElementException("tail on digit: one")
+
+ def ::[B >: A](b: B) = Two(b, a1)
+ def +[B >: A](b: B) = Two(a1, b)
+
+ def toTree = Single(a1)
+
+ def iterator = new Iterator[A] {
+ var hasNext = true
+
+ def next = {
+ hasNext = false
+ a1
+ }
+ }
+ }
+
+ case class Two[+A](a1: A, a2: A) extends Digit[A] {
+ val headLeft = a1
+ def tailLeft = One(a2)
+
+ val headRight = a2
+ def tailRight = One(a1)
+
+ def ::[B >: A](b: B) = Three(b, a1, a2)
+ def +[B >: A](b: B) = Three(a1, a2, b)
+
+ def toTree = a1 +: Single(a2)
+
+ def iterator = (a1 :: a2 :: Nil).iterator
+ }
+
+ case class Three[+A](a1: A, a2: A, a3: A) extends Digit[A] {
+ val headLeft = a1
+ def tailLeft = Two(a2, a3)
+
+ val headRight = a3
+ def tailRight = Two(a1, a2)
+
+ def ::[B >: A](b: B) = Four(b, a1, a2, a3)
+ def +[B >: A](b: B) = Four(a1, a2, a3, b)
+
+ def toTree = a1 +: a2 +: Single(a3)
+
+ def iterator = (a1 :: a2 :: a3 :: Nil).iterator
+ }
+
+ case class Four[+A](a1: A, a2: A, a3: A, a4: A) extends Digit[A] {
+ val headLeft = a1
+ def tailLeft = Three(a2, a3, a4)
+
+ val headRight = a4
+ def tailRight = Three(a1, a2, a3)
+
+ def ::[B >: A](b: B) = throw new UnsupportedOperationException(":: on Four")
+ def +[B >: A](b: B) = throw new UnsupportedOperationException("+ on Four")
+
+ def toTree = a1 +: a2 +: a3 +: Single(a4)
+
+ def iterator = (a1 :: a2 :: a3 :: a4 :: Nil).iterator
+ }
}
|
djspiewak/scala-collections
|
116862af1d6c32caf5f3466d7c3eb7832174cd48
|
Added benchmarking for FingerQueue
|
diff --git a/src/test/scala/QueuePerf.scala b/src/test/scala/QueuePerf.scala
index 0be4e94..ae10599 100644
--- a/src/test/scala/QueuePerf.scala
+++ b/src/test/scala/QueuePerf.scala
@@ -1,179 +1,245 @@
-import com.codecommit.collection.BankersQueue
+import com.codecommit.collection.{BankersQueue, FingerQueue}
import scala.collection.immutable.Queue
object QueuePerf {
import PerfLib._
def main(args: Array[String]) {
println()
// ==========================================================================
{
title("Enqueue 100,000 values")
val data = new Array[Int](100000)
for (i <- 0 until data.length) {
data(i) = Math.round(Math.random).toInt
}
+ val queueOp = "Queue" -> time {
+ var q = Queue[Int]()
+ var i = 0
+
+ while (i < data.length) {
+ q = q enqueue data(i)
+ i += 1
+ }
+ }
+
val bankersQueueOp = "BankersQueue" -> time {
var q = BankersQueue[Int]()
var i = 0
while (i < data.length) {
q += data(i)
i += 1
}
}
- val queueOp = "Queue" -> time {
- var q = Queue[Int]()
+ bankersQueueOp compare queueOp
+
+ val fingerQueueOp = "FingerQueue" -> time {
+ var q = FingerQueue[Int]()
var i = 0
while (i < data.length) {
- q = q enqueue data(i)
+ q += data(i)
i += 1
}
}
- bankersQueueOp compare queueOp
+ fingerQueueOp compare queueOp
+
div('=')
}
// ==========================================================================
{
title("Dequeue 100,000 values")
val data = new Array[Int](100000)
for (i <- 0 until data.length) {
data(i) = Math.round(Math.random).toInt
}
- val bq = (BankersQueue[Int]() /: data) { _ + _ }
val rq = (Queue[Int]() /: data) { _ enqueue _ }
+ val bq = (BankersQueue[Int]() /: data) { _ + _ }
+ val fq = (FingerQueue[Int]() /: data) { _ + _ }
+
+ val queueOp = "Queue" -> time {
+ var q = rq
+ var i = 0
+
+ while (i < data.length) {
+ q = q.dequeue._2
+ i += 1
+ }
+ }
val bankersQueueOp = "BankersQueue" -> time {
var q = bq
var i = 0
while (i < data.length) {
q = q.dequeue._2
i += 1
}
}
- val queueOp = "Queue" -> time {
- var q = rq
+ bankersQueueOp compare queueOp
+
+ val fingerQueueOp = "FingerQueue" -> time {
+ var q = fq
var i = 0
while (i < data.length) {
q = q.dequeue._2
i += 1
}
}
- bankersQueueOp compare queueOp
+ fingerQueueOp compare queueOp
+
div('=')
}
// ==========================================================================
{
title("Enqueue AND Dequeue 100,000 values")
val data = new Array[Int](100000)
for (i <- 0 until data.length) {
data(i) = Math.round(Math.random).toInt
}
+ val queueOp = "Queue" -> time {
+ var q = Queue[Int]()
+ var i = 0
+
+ while (i < data.length) {
+ q = q enqueue data(i)
+ i += 1
+ }
+
+ while (i < data.length) {
+ q = q.dequeue._2
+ i += 1
+ }
+ }
+
val bankersQueueOp = "BankersQueue" -> time {
var q = BankersQueue[Int]()
var i = 0
while (i < data.length) {
q += data(i)
i += 1
}
i = 0
while (i < data.length) {
q = q.dequeue._2
i += 1
}
}
- val queueOp = "Queue" -> time {
- var q = Queue[Int]()
+ bankersQueueOp compare queueOp
+
+ val fingerQueueOp = "FingerQueue" -> time {
+ var q = FingerQueue[Int]()
var i = 0
while (i < data.length) {
- q = q enqueue data(i)
+ q += data(i)
i += 1
}
+ i = 0
+
while (i < data.length) {
q = q.dequeue._2
i += 1
}
}
- bankersQueueOp compare queueOp
+ fingerQueueOp compare queueOp
+
div('=')
}
// ==========================================================================
{
title("Randomly Enqueue AND Dequeue 10,000 values")
val (_, data) = (1 to 10000).foldLeft((0, List[(Int, Int)]())) {
case ((total, tail), _) => {
val numen = Math.round(Math.random * 200).toInt + 1
val back = total + numen
val numde = Math.round(Math.random * (back - 1)).toInt
(back - numde, (numen -> numde) :: tail)
}
}
val rdata = data.reverse
+ val queueOp = "Queue" -> time {
+ var q = Queue[Int]()
+
+ for ((numen, numde) <- rdata) {
+ var i = 0
+ while (i < numen) {
+ q = q enqueue 0
+ i += 1
+ }
+ i = 0
+ while (i < numde) {
+ q = q.dequeue._2
+ i += 1
+ }
+ }
+ }
+
val bankersQueueOp = "BankersQueue" -> time {
var q = BankersQueue[Int]()
for ((numen, numde) <- rdata) {
var i = 0
while (i < numen) {
q = q enqueue 0
i += 1
}
i = 0
while (i < numde) {
q = q.dequeue._2
i += 1
}
}
}
- val queueOp = "Queue" -> time {
- var q = Queue[Int]()
+ bankersQueueOp compare queueOp
+
+ val fingerQueueOp = "FingerQueue" -> time {
+ var q = FingerQueue[Int]()
for ((numen, numde) <- rdata) {
var i = 0
while (i < numen) {
q = q enqueue 0
i += 1
}
i = 0
while (i < numde) {
q = q.dequeue._2
i += 1
}
}
}
- bankersQueueOp compare queueOp
+ fingerQueueOp compare queueOp
div('=')
}
}
}
|
djspiewak/scala-collections
|
a07c5cce1f73fa115fb821eb0e1e63bc695799a3
|
Fixed views for non-Nil prefixes/suffixes
|
diff --git a/src/main/scala/com/codecommit/collection/FingerTree.scala b/src/main/scala/com/codecommit/collection/FingerTree.scala
index 6fafcfc..a9f2c09 100644
--- a/src/main/scala/com/codecommit/collection/FingerTree.scala
+++ b/src/main/scala/com/codecommit/collection/FingerTree.scala
@@ -1,159 +1,181 @@
package com.codecommit.collection
object FingerTree {
sealed trait FingerTree[+A] {
val isEmpty: Boolean
def headLeft: A
def tailLeft: FingerTree[A]
def headRight: A
def tailRight: FingerTree[A]
def +:[B >: A](b: B): FingerTree[B]
def +[B >: A](b: B): FingerTree[B]
def viewLeft: FTViewLeft[FingerTree, A]
def viewRight: FTViewRight[FingerTree, A]
def iterator: Iterator[A]
}
case class Single[+A](a: A) extends FingerTree[A] {
val headLeft = a
val tailLeft = Empty
val headRight = a
val tailRight = Empty
val isEmpty = false
def +:[B >: A](b: B) = Deep(List(b), Empty, List(a))
def +:[B >: A](node: Node[B]) = node match {
case Node2(b, c) => Deep(List(b, c), Empty, List(a))
case Node3(b, c, d) => Deep(List(b, c), Empty, List(d, a))
}
def +[B >: A](b: B) = Deep(List(a), Empty, List(b))
def +[B >: A](node: Node[B]) = node match {
case Node2(b, c) => Deep(List(a), Empty, List(b, c))
case Node3(b, c, d) => Deep(List(a, b), Empty, List(c, d))
}
def viewLeft = FTConsLeft[FingerTree, A](a, Empty)
def viewRight = FTConsRight[FingerTree, A](Empty, a)
def iterator = new Iterator[A] {
var hasNext = true
def next = {
hasNext = false
a
}
}
+
+ override def toString = "FingerTree(Single(%s))".format(a)
}
case class Deep[+A](prefix: List[A], tree: FingerTree[Node[A]], suffix: List[A]) extends FingerTree[A] {
val isEmpty = false
val headLeft = prefix.head
val headRight = suffix.last
def tailLeft = viewLeft.tail
def tailRight = viewRight.tail
def +:[B >: A](b: B) = prefix match {
case d :: e :: f :: g :: Nil => Deep(List(b, d), Node3(d, e, f) +: tree, suffix)
case partial => Deep(b :: partial, tree, suffix)
}
def +[B >: A](b: B) = suffix match {
case g :: f :: e :: d :: Nil => Deep(prefix, tree + Node3(g, f, e), List(d, b))
case partial => Deep(prefix, tree, partial ::: List(b))
}
def viewLeft = {
- def deep(prefix: List[A], tree: FingerTree[Node[A]], suffix: List[A]) = tree.viewLeft match {
- case FTConsLeft(a, newTree) => Deep(a.toList, newTree, suffix)
- case FTNilLeft() => (suffix :\ (Empty: FingerTree[A])) { _ +: _ }
+ def deep(prefix: List[A], tree: FingerTree[Node[A]], suffix: List[A]) = prefix match {
+ case Nil => {
+ tree.viewLeft match {
+ case FTConsLeft(a, newTree) => Deep(a.toList, newTree, suffix)
+ case FTNilLeft() => (suffix :\ (Empty: FingerTree[A])) { _ +: _ }
+ }
+ }
+
+ case prefix => Deep(prefix, tree, suffix)
}
FTConsLeft(prefix.head, deep(prefix.tail, tree, suffix))
}
def viewRight = {
- def deep(prefix: List[A], tree: FingerTree[Node[A]], suffix: List[A]) = tree.viewRight match {
- case FTConsRight(newTree, a) => Deep(prefix, newTree, a.toList)
- case FTNilRight() => (prefix :\ (Empty: FingerTree[A])) { _ +: _ }
+ def deep(prefix: List[A], tree: FingerTree[Node[A]], suffix: List[A]) = suffix match {
+ case Nil => {
+ tree.viewRight match {
+ case FTConsRight(newTree, a) => Deep(prefix, newTree, a.toList)
+ case FTNilRight() => (prefix :\ (Empty: FingerTree[A])) { _ +: _ }
+ }
+ }
+
+ case suffix => Deep(prefix, tree, suffix)
}
FTConsRight(deep(prefix, tree, suffix dropRight 1), suffix.last)
}
def iterator = prefix.iterator ++ (tree.iterator flatMap { _.toList.iterator }) ++ suffix.iterator
+
+ override def toString = "FingerTree(%s, %s, %s)".format(prefix, tree, suffix)
}
case object Empty extends FingerTree[Nothing] {
val isEmpty = true
def headLeft = throw new NoSuchElementException("headLeft on empty finger tree")
def tailLeft = throw new NoSuchElementException("tailLeft on empty finger tree")
def headRight = throw new NoSuchElementException("headRight on empty finger tree")
def tailRight = throw new NoSuchElementException("tailRight on empty finger tree")
def +:[A](a: A) = Single(a)
def +[A](a: A) = Single(a)
def viewLeft = FTNilLeft[FingerTree]()
def viewRight = FTNilRight[FingerTree]()
def iterator = new Iterator[Nothing] {
val hasNext = false
def next = throw new NoSuchElementException
}
+
+ override def toString = "FingerTree(Empty)"
}
sealed trait Node[+A] {
def toList: List[A]
}
case class Node2[+A](a1: A, a2: A) extends Node[A] {
def toList = List(a1, a2)
+
+ override def toString = "Node2(%s, %s)".format(a1, a2)
}
case class Node3[+A](a1: A, a2: A, a3: A) extends Node[A] {
def toList = List(a1, a2, a3)
+
+ override def toString = "Node3(%s, %s, %s)".format(a1, a2, a3)
}
sealed trait FTViewLeft[+S[+_], +A] {
def head: A
def tail: S[A]
}
case class FTConsLeft[+S[+_], +A](head: A, tail: S[A]) extends FTViewLeft[S, A]
case class FTNilLeft[+S[+_]]() extends FTViewLeft[S, Nothing] {
def head = throw new NoSuchElementException("head on empty view")
def tail = throw new NoSuchElementException("tail on empty view")
}
sealed trait FTViewRight[+S[+_], +A] {
def tail: S[A]
def head: A
}
case class FTConsRight[+S[+_], +A](tail: S[A], head: A) extends FTViewRight[S, A]
case class FTNilRight[+S[+_]]() extends FTViewRight[S, Nothing] {
def tail = throw new NoSuchElementException("tail on empty view")
def head = throw new NoSuchElementException("head on empty view")
}
}
|
djspiewak/scala-collections
|
886ed2e4a38b2d7c626590e4a74b761483c57458
|
Initial implementation of a finger tree and associated queue
|
diff --git a/src/main/scala/com/codecommit/collection/FingerQueue.scala b/src/main/scala/com/codecommit/collection/FingerQueue.scala
new file mode 100644
index 0000000..7882aad
--- /dev/null
+++ b/src/main/scala/com/codecommit/collection/FingerQueue.scala
@@ -0,0 +1,45 @@
+package com.codecommit.collection
+
+import scala.collection.{generic, immutable, mutable, LinearSeqLike}
+import generic.{CanBuildFrom, GenericCompanion, GenericTraversableTemplate, SeqFactory}
+import immutable.LinearSeq
+import mutable.{Builder, ListBuffer}
+
+import FingerTree._
+
+class FingerQueue[+A] private (deque: FingerTree[A])
+ extends LinearSeq[A]
+ with GenericTraversableTemplate[A, FingerQueue]
+ with LinearSeqLike[A, FingerQueue[A]] {
+
+ override val companion = FingerQueue
+
+ override val isEmpty = deque.isEmpty
+
+ override def head = deque.headLeft
+
+ override def tail = new FingerQueue(deque.tailLeft)
+
+ def +[B >: A](b: B) = enqueue(b)
+
+ def enqueue[B >: A](b: B) = new FingerQueue(deque + b)
+
+ def dequeue: (A, FingerQueue[A]) = (head, tail)
+
+ def length = iterator.length
+
+ def apply(i: Int) = iterator.toStream(i)
+
+ override def iterator = deque.iterator
+}
+
+object FingerQueue extends SeqFactory[FingerQueue] {
+ implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, FingerQueue[A]] = new GenericCanBuildFrom[A]
+
+ def newBuilder[A]: Builder[A, FingerQueue[A]] =
+ new ListBuffer[A] mapResult { x => new FingerQueue((x :\ (Empty: FingerTree[A])) { _ +: _ }) }
+
+ override def empty[A]: FingerQueue[A] = new FingerQueue[A](Empty)
+
+ override def apply[A](xs: A*): FingerQueue[A] = new FingerQueue((xs :\ (Empty: FingerTree[A])) { _ +: _ })
+}
diff --git a/src/main/scala/com/codecommit/collection/FingerTree.scala b/src/main/scala/com/codecommit/collection/FingerTree.scala
new file mode 100644
index 0000000..6fafcfc
--- /dev/null
+++ b/src/main/scala/com/codecommit/collection/FingerTree.scala
@@ -0,0 +1,159 @@
+package com.codecommit.collection
+
+object FingerTree {
+ sealed trait FingerTree[+A] {
+ val isEmpty: Boolean
+
+ def headLeft: A
+ def tailLeft: FingerTree[A]
+
+ def headRight: A
+ def tailRight: FingerTree[A]
+
+ def +:[B >: A](b: B): FingerTree[B]
+ def +[B >: A](b: B): FingerTree[B]
+
+ def viewLeft: FTViewLeft[FingerTree, A]
+ def viewRight: FTViewRight[FingerTree, A]
+
+ def iterator: Iterator[A]
+ }
+
+ case class Single[+A](a: A) extends FingerTree[A] {
+ val headLeft = a
+ val tailLeft = Empty
+
+ val headRight = a
+ val tailRight = Empty
+
+ val isEmpty = false
+
+ def +:[B >: A](b: B) = Deep(List(b), Empty, List(a))
+
+ def +:[B >: A](node: Node[B]) = node match {
+ case Node2(b, c) => Deep(List(b, c), Empty, List(a))
+ case Node3(b, c, d) => Deep(List(b, c), Empty, List(d, a))
+ }
+
+ def +[B >: A](b: B) = Deep(List(a), Empty, List(b))
+
+ def +[B >: A](node: Node[B]) = node match {
+ case Node2(b, c) => Deep(List(a), Empty, List(b, c))
+ case Node3(b, c, d) => Deep(List(a, b), Empty, List(c, d))
+ }
+
+ def viewLeft = FTConsLeft[FingerTree, A](a, Empty)
+ def viewRight = FTConsRight[FingerTree, A](Empty, a)
+
+ def iterator = new Iterator[A] {
+ var hasNext = true
+
+ def next = {
+ hasNext = false
+ a
+ }
+ }
+ }
+
+ case class Deep[+A](prefix: List[A], tree: FingerTree[Node[A]], suffix: List[A]) extends FingerTree[A] {
+ val isEmpty = false
+
+ val headLeft = prefix.head
+ val headRight = suffix.last
+
+ def tailLeft = viewLeft.tail
+ def tailRight = viewRight.tail
+
+ def +:[B >: A](b: B) = prefix match {
+ case d :: e :: f :: g :: Nil => Deep(List(b, d), Node3(d, e, f) +: tree, suffix)
+ case partial => Deep(b :: partial, tree, suffix)
+ }
+
+ def +[B >: A](b: B) = suffix match {
+ case g :: f :: e :: d :: Nil => Deep(prefix, tree + Node3(g, f, e), List(d, b))
+ case partial => Deep(prefix, tree, partial ::: List(b))
+ }
+
+ def viewLeft = {
+ def deep(prefix: List[A], tree: FingerTree[Node[A]], suffix: List[A]) = tree.viewLeft match {
+ case FTConsLeft(a, newTree) => Deep(a.toList, newTree, suffix)
+ case FTNilLeft() => (suffix :\ (Empty: FingerTree[A])) { _ +: _ }
+ }
+
+ FTConsLeft(prefix.head, deep(prefix.tail, tree, suffix))
+ }
+
+ def viewRight = {
+ def deep(prefix: List[A], tree: FingerTree[Node[A]], suffix: List[A]) = tree.viewRight match {
+ case FTConsRight(newTree, a) => Deep(prefix, newTree, a.toList)
+ case FTNilRight() => (prefix :\ (Empty: FingerTree[A])) { _ +: _ }
+ }
+
+ FTConsRight(deep(prefix, tree, suffix dropRight 1), suffix.last)
+ }
+
+ def iterator = prefix.iterator ++ (tree.iterator flatMap { _.toList.iterator }) ++ suffix.iterator
+ }
+
+ case object Empty extends FingerTree[Nothing] {
+ val isEmpty = true
+
+ def headLeft = throw new NoSuchElementException("headLeft on empty finger tree")
+ def tailLeft = throw new NoSuchElementException("tailLeft on empty finger tree")
+
+ def headRight = throw new NoSuchElementException("headRight on empty finger tree")
+ def tailRight = throw new NoSuchElementException("tailRight on empty finger tree")
+
+ def +:[A](a: A) = Single(a)
+
+ def +[A](a: A) = Single(a)
+
+ def viewLeft = FTNilLeft[FingerTree]()
+ def viewRight = FTNilRight[FingerTree]()
+
+ def iterator = new Iterator[Nothing] {
+ val hasNext = false
+
+ def next = throw new NoSuchElementException
+ }
+ }
+
+
+ sealed trait Node[+A] {
+ def toList: List[A]
+ }
+
+ case class Node2[+A](a1: A, a2: A) extends Node[A] {
+ def toList = List(a1, a2)
+ }
+
+ case class Node3[+A](a1: A, a2: A, a3: A) extends Node[A] {
+ def toList = List(a1, a2, a3)
+ }
+
+
+ sealed trait FTViewLeft[+S[+_], +A] {
+ def head: A
+ def tail: S[A]
+ }
+
+ case class FTConsLeft[+S[+_], +A](head: A, tail: S[A]) extends FTViewLeft[S, A]
+
+ case class FTNilLeft[+S[+_]]() extends FTViewLeft[S, Nothing] {
+ def head = throw new NoSuchElementException("head on empty view")
+ def tail = throw new NoSuchElementException("tail on empty view")
+ }
+
+
+ sealed trait FTViewRight[+S[+_], +A] {
+ def tail: S[A]
+ def head: A
+ }
+
+ case class FTConsRight[+S[+_], +A](tail: S[A], head: A) extends FTViewRight[S, A]
+
+ case class FTNilRight[+S[+_]]() extends FTViewRight[S, Nothing] {
+ def tail = throw new NoSuchElementException("tail on empty view")
+ def head = throw new NoSuchElementException("head on empty view")
+ }
+}
|
djspiewak/scala-collections
|
4fca3733c6157c4eaaf3ea85c2affee0d891a61b
|
Added long-lived queue benchmark
|
diff --git a/src/test/scala/QueuePerf.scala b/src/test/scala/QueuePerf.scala
index 4e5588a..0be4e94 100644
--- a/src/test/scala/QueuePerf.scala
+++ b/src/test/scala/QueuePerf.scala
@@ -1,124 +1,179 @@
import com.codecommit.collection.BankersQueue
import scala.collection.immutable.Queue
object QueuePerf {
import PerfLib._
def main(args: Array[String]) {
println()
// ==========================================================================
{
title("Enqueue 100,000 values")
val data = new Array[Int](100000)
for (i <- 0 until data.length) {
data(i) = Math.round(Math.random).toInt
}
val bankersQueueOp = "BankersQueue" -> time {
var q = BankersQueue[Int]()
var i = 0
while (i < data.length) {
q += data(i)
i += 1
}
}
val queueOp = "Queue" -> time {
var q = Queue[Int]()
var i = 0
while (i < data.length) {
q = q enqueue data(i)
i += 1
}
}
bankersQueueOp compare queueOp
div('=')
}
// ==========================================================================
{
title("Dequeue 100,000 values")
val data = new Array[Int](100000)
for (i <- 0 until data.length) {
data(i) = Math.round(Math.random).toInt
}
val bq = (BankersQueue[Int]() /: data) { _ + _ }
val rq = (Queue[Int]() /: data) { _ enqueue _ }
val bankersQueueOp = "BankersQueue" -> time {
var q = bq
var i = 0
while (i < data.length) {
q = q.dequeue._2
i += 1
}
}
val queueOp = "Queue" -> time {
var q = rq
var i = 0
while (i < data.length) {
q = q.dequeue._2
i += 1
}
}
bankersQueueOp compare queueOp
div('=')
}
// ==========================================================================
{
title("Enqueue AND Dequeue 100,000 values")
val data = new Array[Int](100000)
for (i <- 0 until data.length) {
data(i) = Math.round(Math.random).toInt
}
val bankersQueueOp = "BankersQueue" -> time {
var q = BankersQueue[Int]()
var i = 0
while (i < data.length) {
q += data(i)
i += 1
}
i = 0
while (i < data.length) {
q = q.dequeue._2
i += 1
}
}
val queueOp = "Queue" -> time {
var q = Queue[Int]()
var i = 0
while (i < data.length) {
q = q enqueue data(i)
i += 1
}
while (i < data.length) {
q = q.dequeue._2
i += 1
}
}
bankersQueueOp compare queueOp
div('=')
}
+
+ // ==========================================================================
+ {
+ title("Randomly Enqueue AND Dequeue 10,000 values")
+
+ val (_, data) = (1 to 10000).foldLeft((0, List[(Int, Int)]())) {
+ case ((total, tail), _) => {
+ val numen = Math.round(Math.random * 200).toInt + 1
+ val back = total + numen
+ val numde = Math.round(Math.random * (back - 1)).toInt
+
+ (back - numde, (numen -> numde) :: tail)
+ }
+ }
+
+ val rdata = data.reverse
+
+ val bankersQueueOp = "BankersQueue" -> time {
+ var q = BankersQueue[Int]()
+
+ for ((numen, numde) <- rdata) {
+ var i = 0
+ while (i < numen) {
+ q = q enqueue 0
+ i += 1
+ }
+ i = 0
+ while (i < numde) {
+ q = q.dequeue._2
+ i += 1
+ }
+ }
+ }
+
+ val queueOp = "Queue" -> time {
+ var q = Queue[Int]()
+
+ for ((numen, numde) <- rdata) {
+ var i = 0
+ while (i < numen) {
+ q = q enqueue 0
+ i += 1
+ }
+ i = 0
+ while (i < numde) {
+ q = q.dequeue._2
+ i += 1
+ }
+ }
+ }
+
+ bankersQueueOp compare queueOp
+
+ div('=')
+ }
}
}
|
djspiewak/scala-collections
|
7e86289256636da30fc2f5ab40fd47952570c924
|
Converted front parameter to strict evaluation (we have to force front anyway)
|
diff --git a/src/main/scala/com/codecommit/collection/BankersQueue.scala b/src/main/scala/com/codecommit/collection/BankersQueue.scala
index 25fa5bf..1dc4595 100644
--- a/src/main/scala/com/codecommit/collection/BankersQueue.scala
+++ b/src/main/scala/com/codecommit/collection/BankersQueue.scala
@@ -1,74 +1,72 @@
package com.codecommit.collection
import scala.collection.{generic, immutable, mutable, LinearSeqLike}
import generic.{CanBuildFrom, GenericCompanion, GenericTraversableTemplate, SeqFactory}
import immutable.LinearSeq
import mutable.{Builder, ListBuffer}
/**
* An implementation of Okasaki's fast persistent Banker's Queue data structure
* (provides a better constant factor than the default {@link scala.collection.immutable.Queue}).
*/
-class BankersQueue[+A] private (private val fsize: Int, _front: =>Stream[A], private val rsize: Int, private val rear: List[A])
+class BankersQueue[+A] private (private val fsize: Int, private val front: Stream[A], private val rsize: Int, private val rear: List[A])
extends LinearSeq[A]
with GenericTraversableTemplate[A, BankersQueue]
with LinearSeqLike[A, BankersQueue[A]] {
- private lazy val front = _front
-
override val companion: GenericCompanion[BankersQueue] = BankersQueue
val length: Int = fsize + rsize
override def isEmpty = length == 0
override def head: A = front match {
case hd #:: _ => hd
case _ => throw new NoSuchElementException("head on empty queue")
}
override def tail: BankersQueue[A] = front match {
case _ #:: tail => check(new BankersQueue(fsize - 1, tail, rsize, rear))
case _ => throw new NoSuchElementException("tail on empty queue")
}
def apply(i: Int) = {
if (i < fsize)
front(i)
else if (i < fsize + rsize)
rear(rsize - (i - fsize) - 1)
else {
assert(i > length)
throw new NoSuchElementException("index out of range: " + i)
}
}
def +[B >: A](b: B) = enqueue(b)
- def enqueue[B >: A](b: B) = check(new BankersQueue(fsize, _front, rsize + 1, b :: rear))
+ def enqueue[B >: A](b: B) = check(new BankersQueue(fsize, front, rsize + 1, b :: rear))
def dequeue: (A, BankersQueue[A]) = front match {
case hd #:: tail => (hd, check(new BankersQueue(fsize - 1, tail, rsize, rear)))
case _ => throw new NoSuchElementException("dequeue on empty queue")
}
override def iterator = (front ++ rear.reverse).iterator // force for traversal
private def check[B](q: BankersQueue[B]) = {
if (q.rsize <= q.fsize)
q
else
new BankersQueue(q.fsize + q.rsize, q.front ++ q.rear.reverse, 0, Nil)
}
}
object BankersQueue extends SeqFactory[BankersQueue] {
implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, BankersQueue[A]] = new GenericCanBuildFrom[A]
def newBuilder[A]: Builder[A, BankersQueue[A]] =
new ListBuffer[A] mapResult { x => new BankersQueue[A](x.length, x.reverse.toStream, 0, Nil) }
override def empty[A]: BankersQueue[A] = new BankersQueue[A](0, Stream(), 0, Nil)
override def apply[A](xs: A*): BankersQueue[A] = new BankersQueue[A](xs.length, xs.reverse.toStream, 0, Nil)
}
|
djspiewak/scala-collections
|
9c464ebdbd795045d2c6c6fde8098f983c96c258
|
Switched tail Stream to List
|
diff --git a/src/main/scala/com/codecommit/collection/BankersQueue.scala b/src/main/scala/com/codecommit/collection/BankersQueue.scala
index 8f9911a..25fa5bf 100644
--- a/src/main/scala/com/codecommit/collection/BankersQueue.scala
+++ b/src/main/scala/com/codecommit/collection/BankersQueue.scala
@@ -1,74 +1,74 @@
package com.codecommit.collection
import scala.collection.{generic, immutable, mutable, LinearSeqLike}
import generic.{CanBuildFrom, GenericCompanion, GenericTraversableTemplate, SeqFactory}
import immutable.LinearSeq
import mutable.{Builder, ListBuffer}
/**
* An implementation of Okasaki's fast persistent Banker's Queue data structure
* (provides a better constant factor than the default {@link scala.collection.immutable.Queue}).
*/
-class BankersQueue[+A] private (private val fsize: Int, _front: =>Stream[A], private val rsize: Int, private val rear: Stream[A])
+class BankersQueue[+A] private (private val fsize: Int, _front: =>Stream[A], private val rsize: Int, private val rear: List[A])
extends LinearSeq[A]
with GenericTraversableTemplate[A, BankersQueue]
with LinearSeqLike[A, BankersQueue[A]] {
private lazy val front = _front
override val companion: GenericCompanion[BankersQueue] = BankersQueue
val length: Int = fsize + rsize
override def isEmpty = length == 0
override def head: A = front match {
case hd #:: _ => hd
case _ => throw new NoSuchElementException("head on empty queue")
}
override def tail: BankersQueue[A] = front match {
case _ #:: tail => check(new BankersQueue(fsize - 1, tail, rsize, rear))
case _ => throw new NoSuchElementException("tail on empty queue")
}
def apply(i: Int) = {
if (i < fsize)
front(i)
else if (i < fsize + rsize)
rear(rsize - (i - fsize) - 1)
else {
assert(i > length)
throw new NoSuchElementException("index out of range: " + i)
}
}
def +[B >: A](b: B) = enqueue(b)
- def enqueue[B >: A](b: B) = check(new BankersQueue(fsize, _front, rsize + 1, Stream.cons(b, rear)))
+ def enqueue[B >: A](b: B) = check(new BankersQueue(fsize, _front, rsize + 1, b :: rear))
def dequeue: (A, BankersQueue[A]) = front match {
case hd #:: tail => (hd, check(new BankersQueue(fsize - 1, tail, rsize, rear)))
case _ => throw new NoSuchElementException("dequeue on empty queue")
}
override def iterator = (front ++ rear.reverse).iterator // force for traversal
private def check[B](q: BankersQueue[B]) = {
if (q.rsize <= q.fsize)
q
else
- new BankersQueue(q.fsize + q.rsize, q.front ++ q.rear.reverse, 0, Stream())
+ new BankersQueue(q.fsize + q.rsize, q.front ++ q.rear.reverse, 0, Nil)
}
}
object BankersQueue extends SeqFactory[BankersQueue] {
implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, BankersQueue[A]] = new GenericCanBuildFrom[A]
def newBuilder[A]: Builder[A, BankersQueue[A]] =
- new ListBuffer[A] mapResult { x => new BankersQueue[A](x.length, x.reverse.toStream, 0, Stream()) }
+ new ListBuffer[A] mapResult { x => new BankersQueue[A](x.length, x.reverse.toStream, 0, Nil) }
- override def empty[A]: BankersQueue[A] = new BankersQueue[A](0, Stream(), 0, Stream())
+ override def empty[A]: BankersQueue[A] = new BankersQueue[A](0, Stream(), 0, Nil)
- override def apply[A](xs: A*): BankersQueue[A] = new BankersQueue[A](xs.length, xs.reverse.toStream, 0, Stream())
+ override def apply[A](xs: A*): BankersQueue[A] = new BankersQueue[A](xs.length, xs.reverse.toStream, 0, Nil)
}
|
djspiewak/scala-collections
|
6787bd948910ba8161171296d03fd98bd1e42534
|
Avoid chaining together lazy operations indefinitely
|
diff --git a/src/main/scala/com/codecommit/collection/BankersQueue.scala b/src/main/scala/com/codecommit/collection/BankersQueue.scala
index b944da6..8f9911a 100644
--- a/src/main/scala/com/codecommit/collection/BankersQueue.scala
+++ b/src/main/scala/com/codecommit/collection/BankersQueue.scala
@@ -1,74 +1,74 @@
package com.codecommit.collection
import scala.collection.{generic, immutable, mutable, LinearSeqLike}
import generic.{CanBuildFrom, GenericCompanion, GenericTraversableTemplate, SeqFactory}
import immutable.LinearSeq
import mutable.{Builder, ListBuffer}
/**
* An implementation of Okasaki's fast persistent Banker's Queue data structure
* (provides a better constant factor than the default {@link scala.collection.immutable.Queue}).
*/
class BankersQueue[+A] private (private val fsize: Int, _front: =>Stream[A], private val rsize: Int, private val rear: Stream[A])
extends LinearSeq[A]
with GenericTraversableTemplate[A, BankersQueue]
with LinearSeqLike[A, BankersQueue[A]] {
private lazy val front = _front
override val companion: GenericCompanion[BankersQueue] = BankersQueue
val length: Int = fsize + rsize
override def isEmpty = length == 0
override def head: A = front match {
case hd #:: _ => hd
case _ => throw new NoSuchElementException("head on empty queue")
}
override def tail: BankersQueue[A] = front match {
case _ #:: tail => check(new BankersQueue(fsize - 1, tail, rsize, rear))
case _ => throw new NoSuchElementException("tail on empty queue")
}
def apply(i: Int) = {
if (i < fsize)
front(i)
else if (i < fsize + rsize)
rear(rsize - (i - fsize) - 1)
else {
assert(i > length)
throw new NoSuchElementException("index out of range: " + i)
}
}
def +[B >: A](b: B) = enqueue(b)
- def enqueue[B >: A](b: B) = check(new BankersQueue(fsize, front, rsize + 1, Stream.cons(b, rear)))
+ def enqueue[B >: A](b: B) = check(new BankersQueue(fsize, _front, rsize + 1, Stream.cons(b, rear)))
def dequeue: (A, BankersQueue[A]) = front match {
case hd #:: tail => (hd, check(new BankersQueue(fsize - 1, tail, rsize, rear)))
case _ => throw new NoSuchElementException("dequeue on empty queue")
}
override def iterator = (front ++ rear.reverse).iterator // force for traversal
private def check[B](q: BankersQueue[B]) = {
if (q.rsize <= q.fsize)
q
else
new BankersQueue(q.fsize + q.rsize, q.front ++ q.rear.reverse, 0, Stream())
}
}
object BankersQueue extends SeqFactory[BankersQueue] {
implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, BankersQueue[A]] = new GenericCanBuildFrom[A]
def newBuilder[A]: Builder[A, BankersQueue[A]] =
new ListBuffer[A] mapResult { x => new BankersQueue[A](x.length, x.reverse.toStream, 0, Stream()) }
override def empty[A]: BankersQueue[A] = new BankersQueue[A](0, Stream(), 0, Stream())
override def apply[A](xs: A*): BankersQueue[A] = new BankersQueue[A](xs.length, xs.reverse.toStream, 0, Stream())
}
|
djspiewak/scala-collections
|
98b908cafa5555bd420df7312d5d14d488543bbb
|
Removed laziness from rear (it's unnecessary anyway)
|
diff --git a/src/main/scala/com/codecommit/collection/BankersQueue.scala b/src/main/scala/com/codecommit/collection/BankersQueue.scala
index ff881b3..b944da6 100644
--- a/src/main/scala/com/codecommit/collection/BankersQueue.scala
+++ b/src/main/scala/com/codecommit/collection/BankersQueue.scala
@@ -1,75 +1,74 @@
package com.codecommit.collection
import scala.collection.{generic, immutable, mutable, LinearSeqLike}
import generic.{CanBuildFrom, GenericCompanion, GenericTraversableTemplate, SeqFactory}
import immutable.LinearSeq
import mutable.{Builder, ListBuffer}
/**
* An implementation of Okasaki's fast persistent Banker's Queue data structure
* (provides a better constant factor than the default {@link scala.collection.immutable.Queue}).
*/
-class BankersQueue[+A] private (private val fsize: Int, _front: =>Stream[A], private val rsize: Int, _rear: =>Stream[A])
+class BankersQueue[+A] private (private val fsize: Int, _front: =>Stream[A], private val rsize: Int, private val rear: Stream[A])
extends LinearSeq[A]
with GenericTraversableTemplate[A, BankersQueue]
with LinearSeqLike[A, BankersQueue[A]] {
private lazy val front = _front
- private lazy val rear = _rear
override val companion: GenericCompanion[BankersQueue] = BankersQueue
val length: Int = fsize + rsize
override def isEmpty = length == 0
override def head: A = front match {
case hd #:: _ => hd
case _ => throw new NoSuchElementException("head on empty queue")
}
override def tail: BankersQueue[A] = front match {
case _ #:: tail => check(new BankersQueue(fsize - 1, tail, rsize, rear))
case _ => throw new NoSuchElementException("tail on empty queue")
}
def apply(i: Int) = {
if (i < fsize)
front(i)
else if (i < fsize + rsize)
rear(rsize - (i - fsize) - 1)
else {
assert(i > length)
throw new NoSuchElementException("index out of range: " + i)
}
}
def +[B >: A](b: B) = enqueue(b)
def enqueue[B >: A](b: B) = check(new BankersQueue(fsize, front, rsize + 1, Stream.cons(b, rear)))
def dequeue: (A, BankersQueue[A]) = front match {
case hd #:: tail => (hd, check(new BankersQueue(fsize - 1, tail, rsize, rear)))
case _ => throw new NoSuchElementException("dequeue on empty queue")
}
override def iterator = (front ++ rear.reverse).iterator // force for traversal
private def check[B](q: BankersQueue[B]) = {
if (q.rsize <= q.fsize)
q
else
new BankersQueue(q.fsize + q.rsize, q.front ++ q.rear.reverse, 0, Stream())
}
}
object BankersQueue extends SeqFactory[BankersQueue] {
implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, BankersQueue[A]] = new GenericCanBuildFrom[A]
def newBuilder[A]: Builder[A, BankersQueue[A]] =
new ListBuffer[A] mapResult { x => new BankersQueue[A](x.length, x.reverse.toStream, 0, Stream()) }
override def empty[A]: BankersQueue[A] = new BankersQueue[A](0, Stream(), 0, Stream())
override def apply[A](xs: A*): BankersQueue[A] = new BankersQueue[A](xs.length, xs.reverse.toStream, 0, Stream())
}
|
djspiewak/scala-collections
|
ac7465918dfa318cb53cfc05f3eebee506a91f6a
|
Added performance test for BankersQueue
|
diff --git a/do_perf b/do_perf
index c50b49f..60473d8 100755
--- a/do_perf
+++ b/do_perf
@@ -1,8 +1,8 @@
#!/bin/sh
buildr test:compile
if [ "$?" ]; then
echo ===============================================================================
- exec java -Xmx2048m -Xms512m -server -cp "${SCALA_HOME}/lib/scala-library.jar:target/classes:target/test/classes" VectorPerf
+ exec java -Xmx2048m -Xms512m -server -cp "${SCALA28_HOME}/lib/scala-library.jar:target/classes:target/test/classes" QueuePerf
fi
diff --git a/src/test/scala/QueuePerf.scala b/src/test/scala/QueuePerf.scala
new file mode 100644
index 0000000..4e5588a
--- /dev/null
+++ b/src/test/scala/QueuePerf.scala
@@ -0,0 +1,124 @@
+import com.codecommit.collection.BankersQueue
+import scala.collection.immutable.Queue
+
+object QueuePerf {
+ import PerfLib._
+
+ def main(args: Array[String]) {
+ println()
+
+ // ==========================================================================
+ {
+ title("Enqueue 100,000 values")
+
+ val data = new Array[Int](100000)
+ for (i <- 0 until data.length) {
+ data(i) = Math.round(Math.random).toInt
+ }
+
+ val bankersQueueOp = "BankersQueue" -> time {
+ var q = BankersQueue[Int]()
+ var i = 0
+
+ while (i < data.length) {
+ q += data(i)
+ i += 1
+ }
+ }
+
+ val queueOp = "Queue" -> time {
+ var q = Queue[Int]()
+ var i = 0
+
+ while (i < data.length) {
+ q = q enqueue data(i)
+ i += 1
+ }
+ }
+
+ bankersQueueOp compare queueOp
+ div('=')
+ }
+
+ // ==========================================================================
+ {
+ title("Dequeue 100,000 values")
+
+ val data = new Array[Int](100000)
+ for (i <- 0 until data.length) {
+ data(i) = Math.round(Math.random).toInt
+ }
+
+ val bq = (BankersQueue[Int]() /: data) { _ + _ }
+ val rq = (Queue[Int]() /: data) { _ enqueue _ }
+
+ val bankersQueueOp = "BankersQueue" -> time {
+ var q = bq
+ var i = 0
+
+ while (i < data.length) {
+ q = q.dequeue._2
+ i += 1
+ }
+ }
+
+ val queueOp = "Queue" -> time {
+ var q = rq
+ var i = 0
+
+ while (i < data.length) {
+ q = q.dequeue._2
+ i += 1
+ }
+ }
+
+ bankersQueueOp compare queueOp
+ div('=')
+ }
+
+ // ==========================================================================
+ {
+ title("Enqueue AND Dequeue 100,000 values")
+
+ val data = new Array[Int](100000)
+ for (i <- 0 until data.length) {
+ data(i) = Math.round(Math.random).toInt
+ }
+
+ val bankersQueueOp = "BankersQueue" -> time {
+ var q = BankersQueue[Int]()
+ var i = 0
+
+ while (i < data.length) {
+ q += data(i)
+ i += 1
+ }
+
+ i = 0
+
+ while (i < data.length) {
+ q = q.dequeue._2
+ i += 1
+ }
+ }
+
+ val queueOp = "Queue" -> time {
+ var q = Queue[Int]()
+ var i = 0
+
+ while (i < data.length) {
+ q = q enqueue data(i)
+ i += 1
+ }
+
+ while (i < data.length) {
+ q = q.dequeue._2
+ i += 1
+ }
+ }
+
+ bankersQueueOp compare queueOp
+ div('=')
+ }
+ }
+}
|
djspiewak/scala-collections
|
2dc79cf7a7a79d97fca4bbe0d414839fca538add
|
Added some minimal specs for BankersQueue
|
diff --git a/src/spec/scala/BankersQueueSpecs.scala b/src/spec/scala/BankersQueueSpecs.scala
new file mode 100644
index 0000000..0805eda
--- /dev/null
+++ b/src/spec/scala/BankersQueueSpecs.scala
@@ -0,0 +1,38 @@
+import com.codecommit.collection.BankersQueue
+
+import org.specs._
+import org.scalacheck._
+
+object BankersQueueSpecs extends Specification with ScalaCheck {
+ import Prop._
+
+ "BankersQueue" should {
+ "adhear to fifo" in {
+ val prop = forAll { xs: List[Int] =>
+ val q = (BankersQueue[Int]() /: xs) { _ + _ }
+ xs.foldLeft(q) { (q, i) =>
+ val (i2, q2) = q.dequeue
+ i2 mustEqual i
+ q2
+ }
+ true
+ }
+
+ prop must pass
+ }
+
+ "define apply from head" in {
+ val prop = forAll { (i: Int, xs: List[Int]) =>
+ !xs.isEmpty ==> {
+ val idx = abs(i % xs.length)
+ val q = (BankersQueue[Int]() /: xs) { _ + _ }
+ q(idx) mustEqual xs(idx)
+ }
+ }
+
+ prop must pass
+ }
+ }
+
+ def abs(i: Int) = Math.abs(i) // workaround for scalac bug
+}
|
djspiewak/scala-collections
|
0abaa76b34c4924c42be097ff7a8d0fe937bc00b
|
Added an implementation of Okasaki's Banker's Queue
|
diff --git a/src/main/scala/com/codecommit/collection/BankersQueue.scala b/src/main/scala/com/codecommit/collection/BankersQueue.scala
new file mode 100644
index 0000000..ff881b3
--- /dev/null
+++ b/src/main/scala/com/codecommit/collection/BankersQueue.scala
@@ -0,0 +1,75 @@
+package com.codecommit.collection
+
+import scala.collection.{generic, immutable, mutable, LinearSeqLike}
+import generic.{CanBuildFrom, GenericCompanion, GenericTraversableTemplate, SeqFactory}
+import immutable.LinearSeq
+import mutable.{Builder, ListBuffer}
+
+/**
+ * An implementation of Okasaki's fast persistent Banker's Queue data structure
+ * (provides a better constant factor than the default {@link scala.collection.immutable.Queue}).
+ */
+class BankersQueue[+A] private (private val fsize: Int, _front: =>Stream[A], private val rsize: Int, _rear: =>Stream[A])
+ extends LinearSeq[A]
+ with GenericTraversableTemplate[A, BankersQueue]
+ with LinearSeqLike[A, BankersQueue[A]] {
+
+ private lazy val front = _front
+ private lazy val rear = _rear
+
+ override val companion: GenericCompanion[BankersQueue] = BankersQueue
+
+ val length: Int = fsize + rsize
+
+ override def isEmpty = length == 0
+
+ override def head: A = front match {
+ case hd #:: _ => hd
+ case _ => throw new NoSuchElementException("head on empty queue")
+ }
+
+ override def tail: BankersQueue[A] = front match {
+ case _ #:: tail => check(new BankersQueue(fsize - 1, tail, rsize, rear))
+ case _ => throw new NoSuchElementException("tail on empty queue")
+ }
+
+ def apply(i: Int) = {
+ if (i < fsize)
+ front(i)
+ else if (i < fsize + rsize)
+ rear(rsize - (i - fsize) - 1)
+ else {
+ assert(i > length)
+ throw new NoSuchElementException("index out of range: " + i)
+ }
+ }
+
+ def +[B >: A](b: B) = enqueue(b)
+
+ def enqueue[B >: A](b: B) = check(new BankersQueue(fsize, front, rsize + 1, Stream.cons(b, rear)))
+
+ def dequeue: (A, BankersQueue[A]) = front match {
+ case hd #:: tail => (hd, check(new BankersQueue(fsize - 1, tail, rsize, rear)))
+ case _ => throw new NoSuchElementException("dequeue on empty queue")
+ }
+
+ override def iterator = (front ++ rear.reverse).iterator // force for traversal
+
+ private def check[B](q: BankersQueue[B]) = {
+ if (q.rsize <= q.fsize)
+ q
+ else
+ new BankersQueue(q.fsize + q.rsize, q.front ++ q.rear.reverse, 0, Stream())
+ }
+}
+
+object BankersQueue extends SeqFactory[BankersQueue] {
+ implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, BankersQueue[A]] = new GenericCanBuildFrom[A]
+
+ def newBuilder[A]: Builder[A, BankersQueue[A]] =
+ new ListBuffer[A] mapResult { x => new BankersQueue[A](x.length, x.reverse.toStream, 0, Stream()) }
+
+ override def empty[A]: BankersQueue[A] = new BankersQueue[A](0, Stream(), 0, Stream())
+
+ override def apply[A](xs: A*): BankersQueue[A] = new BankersQueue[A](xs.length, xs.reverse.toStream, 0, Stream())
+}
|
djspiewak/scala-collections
|
ca4c839b133d69edb2499818700678f7750b5d73
|
Made everything (ish) work under Scala 2.8
|
diff --git a/src/main/scala/com/codecommit/collection/BloomSetArray.scala b/src/main/scala/com/codecommit/collection/BloomSetArray.scala
index e0bdcf8..8df3fac 100644
--- a/src/main/scala/com/codecommit/collection/BloomSetArray.scala
+++ b/src/main/scala/com/codecommit/collection/BloomSetArray.scala
@@ -1,74 +1,74 @@
package com.codecommit.collection
import java.io.{InputStream, OutputStream}
import java.util.Random
class BloomSetArray[+T] private (k: Int, contents: Array[Int]) {
def this(width: Int, k: Int) = this(k, new Array[Int](width))
def +[A >: T](e: A) = {
val newContents = cloneArray(contents)
add(newContents)(e)
new BloomSetArray[A](k, newContents)
}
def ++[A >: T](col: Iterable[A]) = {
val newContents = cloneArray(contents)
val addNew = add(newContents) _
col foreach addNew
new BloomSetArray[A](k, newContents)
}
def contains[A >: T](e: A) = {
val total = (0 until k).foldLeft(0) { (acc, i) => acc + contents(hash(e, i, contents.length)) }
total == k
}
def store(os: OutputStream) {
os.write(k)
os.write(contents.length)
contents foreach { os.write(_) }
}
private def add(contents: Array[Int])(e: Any) = {
for (i <- 0 until k) {
contents(hash(e, i, contents.length)) = 1
}
}
private def hash(e: Any, iters: Int, bounds: Int): Int = if (iters == 0) 0 else {
Math.abs(twist(e.hashCode + iters + hash(e, iters - 1, bounds)) % bounds)
}
private def twist(i: Int) = new Random(i).nextInt()
- private def cloneArray[A](a: Array[A]) = {
+ private def cloneArray[A : Manifest](a: Array[A]) = {
val back = new Array[A](a.length)
Array.copy(a, 0, back, 0, a.length)
back
}
}
object BloomSetArray {
val DEFAULT_WIDTH = 200
val DEFAULT_K = 4
def apply[T](elems: T*) = {
new BloomSetArray[T](DEFAULT_WIDTH, DEFAULT_K) ++ elems
}
def load[T](is: InputStream) = {
val k = is.read()
val contents = new Array[Int](is.read())
for (i <- 0 until contents.length) {
contents(i) = is.read()
}
new BloomSetArray[T](k, contents)
}
}
diff --git a/src/main/scala/com/codecommit/collection/HashTrie.scala b/src/main/scala/com/codecommit/collection/HashTrie.scala
index 2814bf0..6e1de3f 100644
--- a/src/main/scala/com/codecommit/collection/HashTrie.scala
+++ b/src/main/scala/com/codecommit/collection/HashTrie.scala
@@ -1,361 +1,361 @@
/**
Copyright (c) 2007-2008, Rich Hickey
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Clojure nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**/
package com.codecommit.collection
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
* @author Rich Hickey
*/
final class HashTrie[K, +V] private (root: Node[K, V]) extends Map[K, V] {
- lazy val size = root.size
+ override lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
- override def +[A >: V](pair: (K, A)) = pair match {
+ override def +[A >: V](pair: (K, A)): HashTrie[K, A] = pair match {
case (k, v) => update(k, v)
}
- def update[A >: V](key: K, value: A) = new HashTrie(root(0, key, key.hashCode) = value)
+ override def update[A >: V](key: K, value: A): HashTrie[K, A] = new HashTrie(root(0, key, key.hashCode) = value)
def -(key: K) = new HashTrie(root.remove(key, key.hashCode))
- def elements = root.elements
+ def iterator = root.elements
def empty[A]: HashTrie[K, A] = new HashTrie(new EmptyNode[K])
def diagnose = root.toString
}
object HashTrie {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashTrie[K, V]) { _ + _ }
def unapplySeq[K, V](map: HashTrie[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](shift: Int, key: K, hash: Int, value: V) = new LeafNode(key, hash, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] abstract class SingleNode[K, +V] extends Node[K, V] {
val hash: Int
}
private[collection] class LeafNode[K, +V](key: K, val hash: Int, value: V) extends SingleNode[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](shift: Int, key: K, hash: Int, value: A) = {
if (this.key == key) {
if (this.value == value) this else new LeafNode(key, hash, value)
} else if (this.hash == hash) {
new CollisionNode(hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(this, key, hash, value)
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](val hash: Int, bucket: List[(K, V)]) extends SingleNode[K, V] {
lazy val size = bucket.length
def this(hash: Int, pairs: (K, V)*) = this(hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for ((k, v) <- bucket) yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(hash, if (found) newBucket else (key, value) :: bucket)
} else {
BitmappedNode(shift)(this, key, hash, value)
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == bucket.length) this else {
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(key, hash, value)
} else new CollisionNode(hash, newBucket)
}
}
def elements = bucket.elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else {
val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = new LeafNode(key, hash, value)
val newBits = bits | mask
if (newBits == ~0) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node == table(i)) {
this
} else if (node.isInstanceOf[EmptyNode[_]]) {
if (size == 1) new EmptyNode[K] else {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, newTable.length)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
}
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
table.foldLeft(emptyElements) { (it, e) =>
if (e == null) it else it ++ e.elements
}
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(node: SingleNode[K, V], key: K, hash: Int, value: V) = {
val table = new Array[Node[K, V]](Math.max((hash >>> shift) & 0x01f, (node.hash >>> shift) & 0x01f) + 1)
val preBits = {
val i = (node.hash >>> shift) & 0x01f
table(i) = node
1 << i
}
val bits = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((preBits & mask) == mask) {
table(i) = (table(i)(shift + 5, key, hash) = value)
} else {
table(i) = new LeafNode(key, hash, value)
}
preBits | mask
}
new BitmappedNode(shift)(table, bits)
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = table((hash >>> shift) & 0x01f)(key, hash)
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val node = table(i).remove(key, hash)
if (node == table(i)) this else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, ~mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
}
def elements = table.foldLeft(emptyElements) { _ ++ _.elements }
override def toString = "FullNode(" + table.foldLeft("") { _.toString + ", " + _.toString } + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
diff --git a/src/spec/scala/BloomSpecs.scala b/src/spec/scala/BloomSpecs.scala
deleted file mode 100644
index a586fdd..0000000
--- a/src/spec/scala/BloomSpecs.scala
+++ /dev/null
@@ -1,136 +0,0 @@
-import org.specs._
-import org.scalacheck._
-
-import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
-import com.codecommit.collection.BloomSet
-
-object BloomSpecs extends Specification with ScalaCheck {
- import Prop._
-
- "bloom set" should {
- "store single element once" in {
- (BloomSet[String]() + "test") contains "test" mustEqual true
- }
-
- "store single element n times" in {
- val prop = forAll { ls: List[String] =>
- val set = ls.foldLeft(BloomSet[String]()) { _ + _ }
-
- ls.foldLeft(true) { _ && set(_) }
- }
-
- prop must pass
- }
-
- "store duplicate elements n times" in {
- val prop = forAll { ls: List[String] =>
- var set = ls.foldLeft(BloomSet[String]()) { _ + _ }
- set = ls.foldLeft(set) { _ + _ }
-
- ls.foldLeft(true) { _ && set(_) }
- }
-
- prop must pass
- }
-
- "handle ++ Iterable" in {
- val prop = forAll { (first: List[String], last: List[String]) =>
- var set = first.foldLeft(BloomSet[String]()) { _ + _ }
- set ++= last
-
- first.foldLeft(true) { _ && set(_) } && last.foldLeft(true) { _ && set(_) }
- }
-
- prop must pass
- }
-
- "handle ++ BloomSet" in {
- val prop = forAll { (first: List[String], last: List[String]) =>
- var set = first.foldLeft(BloomSet[String]()) { _ + _ }
- set ++= last.foldLeft(BloomSet[String]()) { _ + _ }
-
- first.foldLeft(true) { _ && set(_) } && last.foldLeft(true) { _ && set(_) }
- }
-
- prop must pass
- }
-
- "be immutable" in {
- val prop = forAll { (ls: List[String], item: String) =>
- val set = ls.foldLeft(new BloomSet[String](10000, 5)) { _ + _ }
-
- // might fail, but it is doubtful
- (set.accuracy > 0.999 && !ls.contains(item)) ==> {
- val newSet = set + item
-
- ls.foldLeft(true) { _ && set(_) } &&
- !set.contains(item) &&
- ls.foldLeft(true) { _ && newSet(_) } &&
- newSet.contains(item)
- }
- }
-
- prop must pass(set(minTestsOk -> 100, maxDiscarded -> 5000, minSize -> 0, maxSize -> 100))
- }
-
- "construct using companion" in {
- val set = BloomSet("daniel", "chris", "joseph", "renee")
-
- set contains "daniel" mustEqual true
- set contains "chris" mustEqual true
- set contains "joseph" mustEqual true
- set contains "renee" mustEqual true
- }
-
- "implement equivalency" in {
- val prop = forAll { nums: List[Int] =>
- val set1 = nums.foldLeft(BloomSet[Int]()) { _ + _}
- val set2 = nums.foldLeft(BloomSet[Int]()) { _ + _}
-
- set1 == set2
- }
-
- prop must pass
- }
-
- "implement hashing" in {
- val prop = forAll { nums: List[Int] =>
- val set1 = nums.foldLeft(BloomSet[Int]()) { _ + _}
- val set2 = nums.foldLeft(BloomSet[Int]()) { _ + _}
-
- set1.hashCode == set2.hashCode
- }
-
- prop must pass
- }
-
- "persist properly" in {
- skip("Disabling for now")
-
- val prop = forAll { (width: Int, k: Int, ls: List[Int]) => (width > 0 && k > 0) ==> {
- val set = ls.foldLeft(new BloomSet[Int](width, k)) { _ + _ }
- val os = new ByteArrayOutputStream
-
- set.store(os)
- val is = new ByteArrayInputStream(os.toByteArray)
-
- val newSet = BloomSet.load[Int](is)
-
- ls.foldLeft(true) { _ && newSet(_) } &&
- newSet.width == set.width &&
- newSet.k == set.k &&
- newSet.size == set.size
- }
- }
-
- prop must pass
- }
-
- "calculate accuracy" in {
- BloomSet[Int]().accuracy mustEqual 1d
-
- val set = (0 until 1000).foldLeft(BloomSet[Int]()) { _ + _ }
- set.accuracy must beCloseTo(0d, 0.0000001d)
- }
- }
-}
diff --git a/src/test/scala/HashPerf.scala b/src/test/scala/HashPerf.scala
index 0d03b71..71b865c 100644
--- a/src/test/scala/HashPerf.scala
+++ b/src/test/scala/HashPerf.scala
@@ -1,399 +1,327 @@
-import com.codecommit.collection.{HashTrie, VectorHashMap}
+import com.codecommit.collection.HashTrie
import scala.collection.immutable.TreeHashMap
object HashPerf {
import PerfLib._
def main(args: Array[String]) {
println()
val data = "The quick brown fox jumped over the lazy red dog"
//==========================================================================
{
title("Fill 100000 Random Keys")
val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
indexes(i) = Math.random.toString
}
val hashTrieOp = "HashTrie" -> time {
var map = HashTrie[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
val mapOp = "Map" -> time {
var map = Map[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
hashTrieOp compare mapOp
- val intMapOp = "TreeHashMap" -> time {
+ /* val intMapOp = "TreeHashMap" -> time {
var map = TreeHashMap[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
- hashTrieOp compare intMapOp
-
- val vectorMapOp = "VectorHashMap" -> time {
- var map = VectorHashMap[String, String]()
- var i = 0
-
- while (i < indexes.length) {
- map = map(indexes(i)) = data
- i += 1
- }
- }
-
- hashTrieOp compare vectorMapOp
+ hashTrieOp compare intMapOp */
val mutableMapOp = "mutable.Map" -> time {
val map = scala.collection.mutable.Map[String, String]()
var i = 0
while (i < indexes.length) {
map(indexes(i)) = data
i += 1
}
}
hashTrieOp compare mutableMapOp
div('=')
}
println()
//==========================================================================
{
title("Read 100000 Random Keys")
val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
indexes(i) = Math.random.toString
}
var hashTrie = HashTrie[String, String]()
{
var i = 0
while (i < indexes.length) {
hashTrie = hashTrie(indexes(i)) = data
i += 1
}
}
var immutableMap = Map[String, String]()
{
var i = 0
while (i < indexes.length) {
immutableMap = immutableMap(indexes(i)) = data
i += 1
}
}
val hashTrieOp = "HashTrie" -> time {
var i = 0
while (i < indexes.length) {
hashTrie(indexes(i))
i += 1
}
}
val mapOp = "Map" -> time {
var i = 0
while (i < indexes.length) {
immutableMap(indexes(i))
i += 1
}
}
hashTrieOp compare mapOp
- var intMap = TreeHashMap[String, String]()
+ /* var intMap = TreeHashMap[String, String]()
{
var i = 0
while (i < indexes.length) {
intMap = intMap(indexes(i)) = data
i += 1
}
}
val intMapOp = "TreeHashMap" -> time {
var i = 0
while (i < indexes.length) {
intMap(indexes(i))
i += 1
}
}
- hashTrieOp compare intMapOp
-
- var vectorMap = VectorHashMap[String, String]()
-
- {
- var i = 0
-
- while (i < indexes.length) {
- vectorMap = vectorMap(indexes(i)) = data
- i += 1
- }
- }
-
- val vectorMapOp = "VectorHashMap" -> time {
- var i = 0
- while (i < indexes.length) {
- vectorMap(indexes(i))
- i += 1
- }
- }
-
- hashTrieOp compare vectorMapOp
+ hashTrieOp compare intMapOp */
val mutableMap = scala.collection.mutable.Map[String, String]()
{
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i)) = data
i += 1
}
}
val mutableMapOp = "mutable.Map" -> time {
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i))
i += 1
}
}
hashTrieOp compare mutableMapOp
div('=')
}
println()
//==========================================================================
{
title("Remove 50000 Random Keys")
val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
indexes(i) = Math.random.toString
}
var hashTrie = HashTrie[String, String]()
{
var i = 0
while (i < indexes.length) {
hashTrie = hashTrie(indexes(i)) = data
i += 1
}
}
var immutableMap = Map[String, String]()
{
var i = 0
while (i < indexes.length) {
immutableMap = immutableMap(indexes(i)) = data
i += 1
}
}
val hashTrieOp = "HashTrie" -> time {
var i = 0
var map = hashTrie
while (i < indexes.length) {
map -= indexes(i)
i += 1
}
}
val mapOp = "Map" -> time {
var i = 0
var map = immutableMap
while (i < indexes.length) {
immutableMap -= indexes(i)
i += 1
}
}
hashTrieOp compare mapOp
- var intMap = TreeHashMap[String, String]()
+ /* var intMap = TreeHashMap[String, String]()
{
var i = 0
while (i < indexes.length) {
intMap = intMap(indexes(i)) = data
i += 1
}
- }
+ } */
- val intMapOp = "TreeHashMap" -> time {
+ /* val intMapOp = "TreeHashMap" -> time {
var i = 0
var map = intMap
while (i < indexes.length) {
map -= indexes(i)
i += 1
}
}
- hashTrieOp compare intMapOp
-
- var vectorMap = VectorHashMap[String, String]()
+ hashTrieOp compare intMapOp */
- {
- var i = 0
-
- while (i < indexes.length) {
- vectorMap = vectorMap(indexes(i)) = data
- i += 1
- }
- }
-
- val vectorMapOp = "VectorHashMap" -> time {
- var i = 0
- var map = vectorMap
-
- while (i < indexes.length) {
- map -= indexes(i)
- i += 1
- }
- }
-
- hashTrieOp compare vectorMapOp
div('=')
}
println()
//==========================================================================
{
title("Loop Over 100000 Random Keys (#foreach)")
val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
indexes(i) = Math.random.toString
}
var hashTrie = HashTrie[String, String]()
{
var i = 0
while (i < indexes.length) {
hashTrie = hashTrie(indexes(i)) = data
i += 1
}
}
var immutableMap = Map[String, String]()
{
var i = 0
while (i < indexes.length) {
immutableMap = immutableMap(indexes(i)) = data
i += 1
}
}
val hashTrieOp = "HashTrie" -> time {
hashTrie foreach { case (k, v) => () }
}
val mapOp = "Map" -> time {
immutableMap foreach { case (k, v) => () }
}
hashTrieOp compare mapOp
- var intMap = TreeHashMap[String, String]()
+ /* var intMap = TreeHashMap[String, String]()
{
var i = 0
while (i < indexes.length) {
intMap = intMap(indexes(i)) = data
i += 1
}
}
val intMapOp = "TreeHashMap" -> time {
intMap foreach { case (k, v) => () }
}
- hashTrieOp compare intMapOp
-
- var vectorMap = VectorHashMap[String, String]()
-
- {
- var i = 0
-
- while (i < indexes.length) {
- vectorMap = vectorMap(indexes(i)) = data
- i += 1
- }
- }
-
- val vectorMapOp = "VectorHashMap" -> time {
- vectorMap foreach { case (k, v) => () }
- }
-
- hashTrieOp compare vectorMapOp
+ hashTrieOp compare intMapOp */
val mutableMap = scala.collection.mutable.Map[String, String]()
{
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i)) = data
i += 1
}
}
val mutableMapOp = "mutable.Map" -> time {
mutableMap foreach { case (k, v) => () }
}
hashTrieOp compare mutableMapOp
div('=')
}
}
}
|
djspiewak/scala-collections
|
c165fa8697f0d147487f9dd5c2edd08dd9f3374c
|
Added build cruft to move forward to Scala 2.8; eliminated obsolete collections
|
diff --git a/buildfile b/buildfile
index 9aab134..9cc3b78 100644
--- a/buildfile
+++ b/buildfile
@@ -1,14 +1,26 @@
+ENV['SCALA_HOME'] = ENV['SCALA28_HOME']
+
require 'buildr/scala'
#require 'buildr/java/cobertura'
-repositories.remote << 'http://repo1.maven.org/maven2/'
+repositories.remote << 'http://repo1.maven.org/maven2'
+repositories.remote << 'http://scala-tools.org/repo-snapshots'
+
+Buildr::Scala::Specs.dependencies.delete_if do |str|
+ str =~ /specs/ ||
+ str =~ /scalacheck/
+end
+
+Buildr::Scala::Specs.dependencies << 'org.scala-tools.testing:specs_2.8.0.RC3:jar:1.6.5-SNAPSHOT'
+Buildr::Scala::Specs.dependencies << 'org.scala-tools.testing:scalacheck_2.8.0.RC3:jar:1.7'
+
desc 'A few collections classes for fun and profit'
define 'collection' do
project.version = '0.1.0'
project.group = 'com.codecommit'
test.using :specs
package :jar
end
diff --git a/src/main/scala/com/codecommit/collection/BloomSet.scala b/src/main/scala/com/codecommit/collection/BloomSet.scala
deleted file mode 100644
index 2586d4f..0000000
--- a/src/main/scala/com/codecommit/collection/BloomSet.scala
+++ /dev/null
@@ -1,212 +0,0 @@
-package com.codecommit.collection
-
-import java.io.{InputStream, OutputStream}
-
-import BloomSet._
-
-class BloomSet[A] private (val size: Int, val k: Int, private val contents: Vector[Boolean]) extends ((A)=>Boolean) {
- val width = contents.length
-
- /**
- * <p>A value between 0 and 1 which estimates the accuracy of the bloom filter.
- * This estimate is precisely the inverse of the probability function for
- * a bloom filter of a given size, width and number of hash functions. The
- * probability function given by the following expression in LaTeX math syntax:</p>
- *
- * <p><code>(1 - e^{-kn/m})^k</code> where <i>k</i> is the number of hash functions,
- * <i>n</i> is the number of elements in the bloom filter and <i>m</i> is the
- * width.</p>
- *
- * <p>It is important to remember that this is only an estimate of the accuracy.
- * Likewise, it assumes perfectly ideal hash functions, thus it is somewhat
- * more optimistic than the reality of the implementation.</p>
- */
- lazy val accuracy = {
- val exp = ((k:Double) * size) / width
- val probability = Math.pow(1 - Math.exp(-exp), k)
-
- 1d - probability
- }
-
- /**
- * Returns the optimal value of <i>k</i> for a bloom filter with the current
- * properties (width and size). Useful in reducing false-positives on sets
- * with a limited range in size.
- */
- lazy val optimalK = {
- val num = (9:Double) * width
- val dem = (13:Double) * size
- Math.max((num / dem).intValue, 1)
- }
-
- def this(width: Int, k: Int) = this(0, k, alloc(width))
-
- def +(e: A) = new BloomSet[A](size + 1, k, add(contents)(e))
-
- def ++(col: Iterable[A]) = {
- var length = 0
- val newContents = col.foldLeft(contents) { (c, e) =>
- length += 1
- add(c)(e)
- }
-
- new BloomSet[A](size + length, k, newContents)
- }
-
- /**
- * Computes the union of two bloom filters and returns the result. Note that
- * this operation is only defined for filters of the same width. Filters which
- * have a different value of <i>k</i> (different number of hash functions) can
- * be unioned, but the result will have a higher probability of false positives
- * than either of the operands. The <i>k</i> value of the resulting filter is
- * computed to be the minimum <i>k</i> of the two operands. The <i>size</i> of
- * the resulting filter is precisely the combined size of the operands. This
- * of course means that for sets with intersecting items the size will be
- * slightly large.
- */
- def ++(set: BloomSet[A]) = {
- if (set.width != width) {
- throw new IllegalArgumentException("Bloom filter union is only defined for " +
- "sets of the same width (" + set.width + " != " + width + ")")
- }
-
- val newContents = (0 until width).foldLeft(contents) { (c, i) =>
- c(i) ||= set.contents(i)
- }
-
- new BloomSet[A](size + set.size, Math.min(set.k, k), newContents) // min guarantees no false negatives
- }
-
- def contains(e: A) = {
- (0 until k).foldLeft(true) { (acc, i) =>
- acc && contents(hash(e, i, contents.length))
- }
- }
-
- def apply(e: A) = contains(e)
-
- def store(os: OutputStream) {
- os.write(convertToBytes(size))
- os.write(convertToBytes(k))
- os.write(convertToBytes(contents.length))
-
- var num = 0
- var card = 0
- for (b <- contents) {
- num = (num << 1) | (if (b) 1 else 0) // construct mask
- card += 1
-
- if (card == 8) {
- os.write(num)
-
- num = 0
- card = 0
- }
- }
-
- if (card != 0) {
- os.write(num)
- }
- }
-
- override def equals(other: Any) = other match {
- case set: BloomSet[A] => {
- val back = (size == set.size) &&
- (k == set.k) &&
- (contents.length == set.contents.length)
-
- (0 until contents.length).foldLeft(back) { (acc, i) =>
- acc && (contents(i) == set.contents(i))
- }
- }
-
- case _ => false
- }
-
- override def hashCode = {
- (0 until width).foldLeft(size ^ k ^ width) { (acc, i) =>
- acc ^ (if (contents(i)) i else 0)
- }
- }
-
- protected def add(contents: Vector[Boolean])(e: Any) = {
- var back = contents
-
- for (i <- 0 until k) {
- back = back(hash(e, i, back.length)) = true
- }
-
- back
- }
-}
-
-object BloomSet {
- def apply[A](e: A*) = e.foldLeft(new BloomSet[A](200, 4)) { _ + _ }
-
- def load[A](is: InputStream) = {
- val buf = new Array[Byte](4)
-
- is.read(buf)
- val size = convertToInt(buf)
-
- is.read(buf)
- val k = convertToInt(buf)
-
- is.read(buf)
- val width = convertToInt(buf)
-
- var contents = Vector[Boolean]()
- for (_ <- 0 until (width / 8)) {
- var num = is.read()
- var buf: List[Boolean] = Nil
-
- for (_ <- 0 until 8) {
- buf = ((num & 1) == 1) :: buf
- num >>= 1
- }
-
- contents = contents ++ buf
- }
-
- if (width % 8 != 0) {
- var buf: List[Boolean] = Nil
- var num = is.read()
-
- for (_ <- 0 until (width % 8)) {
- buf = ((num & 1) == 1) :: buf
- num >>= 1
- }
-
- contents = contents ++ buf
- }
-
- new BloomSet[A](size, k, contents)
- }
-
- private[collection] def convertToBytes(i: Int) = {
- val buf = new Array[Byte](4)
-
- buf(0) = ((i & 0xff000000) >>> 24).byteValue
- buf(1) = ((i & 0x00ff0000) >>> 16).byteValue
- buf(2) = ((i & 0x0000ff00) >>> 8).byteValue
- buf(3) = ((i & 0x000000ff)).byteValue
-
- buf
- }
-
- private[collection] def convertToInt(buf: Array[Byte]) = {
- ((buf(0) & 0xFF) << 24) |
- ((buf(1) & 0xFF) << 16) |
- ((buf(2) & 0xFF) << 8) |
- (buf(3) & 0xFF)
- }
-
- private[collection] def alloc(size: Int) = {
- (0 until size).foldLeft(Vector[Boolean]()) { (c, i) => c + false }
- }
-
- private[collection] def hash(e: Any, iters: Int, bounds: Int): Int = {
- val rand = new Random(e.hashCode)
- (0 until iters).foldLeft(rand.nextInt(bounds)) { (x, y) => rand.nextInt(bounds) }
- }
-}
diff --git a/src/main/scala/com/codecommit/collection/PathVector.scala b/src/main/scala/com/codecommit/collection/PathVector.scala
deleted file mode 100644
index 4b44a07..0000000
--- a/src/main/scala/com/codecommit/collection/PathVector.scala
+++ /dev/null
@@ -1,290 +0,0 @@
-package com.codecommit.collection
-
-import Math.max
-import PathVector._
-
-/**
- * <p>An immutable implementation of the {@link Seq} interface with an array
- * backend. Effectively, this class is an immutable vector. The only wrinkle
- * in this design is the ability to store elements in <i>completely</i> arbitrary
- * indexes (to enable use as a random-access array). Thus, the length of this
- * data structure is effectively infinite. The {@link #length} field is defined
- * to return the maximum index of the elements in the vector.</p>
- *
- * <p>The underlying data structure for the persistent vector is a trie with an
- * extremely high branching factor (by default: 32). Each trie node contains
- * an array representing each branch. This implementation allows almost-constant
- * time access coupled with minimal data-copying on insert. The ratio between
- * these two is controlled by the branching factor. A higher branching factor
- * will lead to a better worst-case access time (asymtotically more constant)
- * while a lower branching factor will result in asymtotically less data
- * copying on insert.</p>
- *
- * <p>As is natural for an immutable data structure, this vector is parameterized
- * covariantly. This poses a few minor difficulties in implementation, due to
- * the fact that arrays, as mutable containers, are parameterized
- * <i>invariantly</i>. To get around this, some up-casting is utilized durring
- * insertion. This is considered to be sound due to the fact that the type
- * system will ensure that the casting is always upwards, rather than down (which
- * is where the mutability concerns come into play).</p>
- *
- * <p>The underlying determinant for the trie structure in this implementation is
- * the big-endian component value of the index in question, converted into a path
- * to the final trie node. This still yields a maximum depth of 7 (when dealing
- * with 32-bit integer indexes and a branching factor of 32), but the average
- * depth of the trie is higher and its width is proportionately lower. This
- * yields far more efficient write operations than a bit-partitioned trie, as well
- * as a tremendously reduced memory footprint. Additionally, this implementation
- * allows a configurable branching factor, whereas the branching factor of a
- * bit-partitioned implemnetation must always be a factor of 2.</p>
- *
- * @author Daniel Spiewak
- */
-class PathVector[+T] private (private val data: Option[T], val length: Int, val branchingFactor: Int,
- private val left: Seq[PathVector[T]], private val right: Seq[PathVector[T]]) extends RandomAccessSeq[T] { outer =>
-
- def this(branchingFactor: Int) = this(None, 0, branchingFactor, EmptyArray, EmptyArray)
-
- def this() = this(32)
-
- def apply(i: Int) = getOrElse(i, null.asInstanceOf[T])
-
- def get(i: Int) = locate(computePath(i, branchingFactor))
-
- def getOrElse[A >: T](i: Int, default: A) = get(i) match {
- case Some(x) => x
- case None => default
- }
-
- private def locate(path: List[Int]): Option[T] = path match {
- case hd :: tail => {
- val branches = if (hd < (branchingFactor / 2)) left else right
- val node = if (hd < branches.length) branches(hd) else null.asInstanceOf[PathVector[T]]
-
- if (node == null) None else node.locate(tail)
- }
-
- case Nil => data
- }
-
- // somewhat less efficient than it could be
- override def ++[A >: T](other: Iterable[A]) = other.foldLeft(this:PathVector[A]) { _ + _ }
-
- def +[A >: T](e: A) = update(length, e)
-
- def update[A >: T](i: Int, e: A) = store(computePath(i, branchingFactor), e)
-
- private def store[A >: T](path: List[Int], e: A): PathVector[A] = path match {
- case hd :: tail => {
- val branches = if (hd < (branchingFactor / 2)) left else right
- val node = if (hd < branches.length) branches(hd) else null.asInstanceOf[PathVector[T]]
- val vector = if (node == null) EmptyPathVector(branchingFactor) else node
-
- val newBranches = new Array[PathVector[A]](max(branches.length, hd + 1))
- Array.copy(branches, 0, newBranches, 0, branches.length)
-
- newBranches(hd) = vector.store(tail, e)
-
- val newLeft = if (hd < (branchingFactor / 2)) newBranches else left
- val newRight = if (hd < (branchingFactor / 2)) right else newBranches
-
- new PathVector(data, max(length, flattenPath(path, branchingFactor) + 1), branchingFactor, newLeft, newRight)
- }
-
- case Nil => new PathVector(Some(e), max(length, flattenPath(path, branchingFactor) + 1), branchingFactor, left, right)
- }
-
- override def filter(p: (T)=>Boolean) = {
- var back = new PathVector[T]
- var i = 0
-
- while (i < length) {
- val e = apply(i)
- if (p(e)) back += e
-
- i += 1
- }
-
- back
- }
-
- override def flatMap[A](f: (T)=>Iterable[A]) = {
- var back = new PathVector[A]
- var i = 0
-
- while (i < length) {
- f(apply(i)) foreach { back += _ }
- i += 1
- }
-
- back
- }
-
- override def map[A](f: (T)=>A): PathVector[A] = {
- var back = new PathVector[A]
- var i = 0
-
- while (i < length) {
- back += f(apply(i))
- i += 1
- }
-
- back
- }
-
- override def reverse = new PathVector[T](branchingFactor) {
- override val length = outer.length
-
- override def get(i: Int) = outer.get(length - i - 1)
-
- override def update[A >: T](i: Int, e: A) = {
- var back = new PathVector[A]
-
- foreachOption { (c, x) =>
- back = back(c) = if (c == i) e else x
- }
-
- if (i < 0) {
- throw new IndexOutOfBoundsException(i.toString)
- } else if (i >= length) {
- back(i) = e
- } else {
- back
- }
- }
- }
-
- override def subseq(from: Int, end: Int) = subPathVector(from, end)
-
- def subPathVector(from: Int, end: Int) = {
- if (from < 0) {
- throw new IndexOutOfBoundsException(from.toString)
- } else if (end <= from) {
- throw new IllegalArgumentException("Invalid range: " + from + ".." + end)
- } else {
- new PathVector[T](branchingFactor) {
- override val length = end - from
-
- override def get(i: Int) = outer.get(i + from)
-
- override def update[A >: T](i: Int, e: A) = {
- var back = new PathVector[A]
-
- foreachOption { (c, x) =>
- back = back(c) = if (c == i) e else x
- }
-
- if (i < 0) {
- throw new IndexOutOfBoundsException(i.toString)
- } else if (i >= length) {
- back(i) = e
- } else {
- back
- }
- }
- }
- }
- }
-
- def zip[A](that: PathVector[A]) = {
- var back = new PathVector[(T, A)]
- var i = 0
-
- val limit = max(length, that.length)
- while (i < limit) {
- back += (apply(i), that(i))
- i += 1
- }
-
- back
- }
-
- def zipWithIndex = {
- var back = new PathVector[(T, Int)]
- var i = 0
-
- while (i < length) {
- back += (apply(i), i)
- i += 1
- }
-
- back
- }
-
- override def equals(other: Any) = other match {
- case vec:PathVector[T] => {
- var back = length == vec.length
- var i = 0
-
- while (i < length) {
- back &&= get(i) == vec.get(i)
- i += 1
- }
-
- back
- }
-
- case _ => false
- }
-
- @inline
- private def foreachOption(f: (Int, T)=>Unit) = {
- var i = 0
- while (i < length) {
- get(i) match {
- case Some(x) => f(i, x)
- case None => ()
- }
-
- i += 1
- }
- }
-}
-
-object PathVector {
- private[collection] val EmptyArray = new Array[PathVector[Nothing]](0)
-
- def apply[T](elems: T*) = {
- var vector = new PathVector[T]
- var i = 0
-
- for (e <- elems) {
- vector = vector(i) = e
- i += 1
- }
- vector
- }
-
- @inline
- private[collection] def computePath(total: Int, base: Int) = {
- if (total < 0) {
- throw new IndexOutOfBoundsException(total.toString)
- } else {
- var back: List[Int] = Nil
- var num = total
-
- do {
- back = (num % base) :: back
- num /= base
- } while (num > 0)
-
- back
- }
- }
-
- @inline
- private[collection] def flattenPath(path: List[Int], base: Int) = path.foldLeft(0) { _ * base + _ }
-}
-
-object EmptyPathVector {
- private var cache = Map[Int, PathVector[Nothing]]()
-
- def apply(branchingFactor: Int) = {
- if (cache contains branchingFactor) cache(branchingFactor) else {
- val back = new PathVector[Nothing](branchingFactor)
- cache += (branchingFactor -> back)
-
- back
- }
- }
-}
diff --git a/src/main/scala/com/codecommit/collection/Vector.scala b/src/main/scala/com/codecommit/collection/Vector.scala
deleted file mode 100644
index 5bbfc96..0000000
--- a/src/main/scala/com/codecommit/collection/Vector.scala
+++ /dev/null
@@ -1,351 +0,0 @@
-/**
- Copyright (c) 2007-2008, Rich Hickey
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
-
- * Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- * Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials provided
- with the distribution.
-
- * Neither the name of Clojure nor the names of its contributors
- may be used to endorse or promote products derived from this
- software without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- **/
-
-package com.codecommit.collection
-
-import Vector._
-
-/**
- * A straight port of Clojure's <code>PersistentVector</code> class.
- *
- * @author Daniel Spiewak
- * @author Rich Hickey
- */
-class Vector[+T] private (val length: Int, shift: Int, root: Array[AnyRef], tail: Array[AnyRef]) extends RandomAccessSeq[T] { outer =>
- private val tailOff = length - tail.length
-
- /*
- * The design of this data structure inherantly requires heterogenous arrays.
- * It is *possible* to design around this, but the result is comparatively
- * quite inefficient. With respect to this fact, I have left the original
- * (somewhat dynamically-typed) implementation in place.
- */
-
- private[collection] def this() = this(0, 5, EmptyArray, EmptyArray)
-
- def apply(i: Int): T = {
- if (i >= 0 && i < length) {
- if (i >= tailOff) {
- tail(i & 0x01f).asInstanceOf[T]
- } else {
- var arr = root
- var level = shift
-
- while (level > 0) {
- arr = arr((i >>> level) & 0x01f).asInstanceOf[Array[AnyRef]]
- level -= 5
- }
-
- arr(i & 0x01f).asInstanceOf[T]
- }
- } else throw new IndexOutOfBoundsException(i.toString)
- }
-
- def update[A >: T](i: Int, obj: A): Vector[A] = {
- if (i >= 0 && i < length) {
- if (i >= tailOff) {
- val newTail = new Array[AnyRef](tail.length)
- Array.copy(tail, 0, newTail, 0, tail.length)
- newTail(i & 0x01f) = obj.asInstanceOf[AnyRef]
-
- new Vector[A](length, shift, root, newTail)
- } else {
- new Vector[A](length, shift, doAssoc(shift, root, i, obj), tail)
- }
- } else if (i == length) {
- this + obj
- } else throw new IndexOutOfBoundsException(i.toString)
- }
-
- private def doAssoc[A >: T](level: Int, arr: Array[AnyRef], i: Int, obj: A): Array[AnyRef] = {
- val ret = new Array[AnyRef](arr.length)
- Array.copy(arr, 0, ret, 0, arr.length)
-
- if (level == 0) {
- ret(i & 0x01f) = obj.asInstanceOf[AnyRef]
- } else {
- val subidx = (i >>> level) & 0x01f
- ret(subidx) = doAssoc(level - 5, arr(subidx).asInstanceOf[Array[AnyRef]], i, obj)
- }
-
- ret
- }
-
- override def ++[A >: T](other: Iterable[A]) = other.foldLeft(this:Vector[A]) { _ + _ }
-
- def +[A >: T](obj: A): Vector[A] = {
- if (tail.length < 32) {
- val newTail = new Array[AnyRef](tail.length + 1)
- Array.copy(tail, 0, newTail, 0, tail.length)
- newTail(tail.length) = obj.asInstanceOf[AnyRef]
-
- new Vector[A](length + 1, shift, root, newTail)
- } else {
- var (newRoot, expansion) = pushTail(shift - 5, root, tail, null)
- var newShift = shift
-
- if (expansion != null) {
- newRoot = array(newRoot, expansion)
- newShift += 5
- }
-
- new Vector[A](length + 1, newShift, newRoot, array(obj.asInstanceOf[AnyRef]))
- }
- }
-
- private def pushTail(level: Int, arr: Array[AnyRef], tailNode: Array[AnyRef], expansion: AnyRef): (Array[AnyRef], AnyRef) = {
- val newChild = if (level == 0) tailNode else {
- val (newChild, subExpansion) = pushTail(level - 5, arr(arr.length - 1).asInstanceOf[Array[AnyRef]], tailNode, expansion)
-
- if (subExpansion == null) {
- val ret = new Array[AnyRef](arr.length)
- Array.copy(arr, 0, ret, 0, arr.length)
-
- ret(arr.length - 1) = newChild
-
- return (ret, null)
- } else subExpansion
- }
-
- // expansion
- if (arr.length == 32) {
- (arr, array(newChild))
- } else {
- val ret = new Array[AnyRef](arr.length + 1)
- Array.copy(arr, 0, ret, 0, arr.length)
- ret(arr.length) = newChild
-
- (ret, null)
- }
- }
-
- /**
- * Removes the <i>tail</i> element of this vector.
- */
- def pop: Vector[T] = {
- if (length == 0) {
- throw new IllegalStateException("Can't pop empty vector")
- } else if (length == 1) {
- EmptyVector
- } else if (tail.length > 1) {
- val newTail = new Array[AnyRef](tail.length - 1)
- Array.copy(tail, 0, newTail, 0, newTail.length)
-
- new Vector[T](length - 1, shift, root, newTail)
- } else {
- var (newRoot, pTail) = popTail(shift - 5, root, null)
- var newShift = shift
-
- if (newRoot == null) {
- newRoot = EmptyArray
- }
-
- if (shift > 5 && newRoot.length == 1) {
- newRoot = newRoot(0).asInstanceOf[Array[AnyRef]]
- newShift -= 5
- }
-
- new Vector[T](length - 1, newShift, newRoot, pTail.asInstanceOf[Array[AnyRef]])
- }
- }
-
- private def popTail(shift: Int, arr: Array[AnyRef], pTail: AnyRef): (Array[AnyRef], AnyRef) = {
- val newPTail = if (shift > 0) {
- val (newChild, subPTail) = popTail(shift - 5, arr(arr.length - 1).asInstanceOf[Array[AnyRef]], pTail)
-
- if (newChild != null) {
- val ret = new Array[AnyRef](arr.length)
- Array.copy(arr, 0, ret, 0, arr.length)
-
- ret(arr.length - 1) = newChild
-
- return (ret, subPTail)
- }
- subPTail
- } else if (shift == 0) {
- arr(arr.length - 1)
- } else pTail
-
- // contraction
- if (arr.length == 1) {
- (null, newPTail)
- } else {
- val ret = new Array[AnyRef](arr.length - 1)
- Array.copy(arr, 0, ret, 0, ret.length)
-
- (ret, newPTail)
- }
- }
-
- override def filter(p: (T)=>Boolean) = {
- var back = new Vector[T]
- var i = 0
-
- while (i < length) {
- val e = apply(i)
- if (p(e)) back += e
-
- i += 1
- }
-
- back
- }
-
- override def flatMap[A](f: (T)=>Iterable[A]) = {
- var back = new Vector[A]
- var i = 0
-
- while (i < length) {
- f(apply(i)) foreach { back += _ }
- i += 1
- }
-
- back
- }
-
- override def map[A](f: (T)=>A) = {
- var back = new Vector[A]
- var i = 0
-
- while (i < length) {
- back += f(apply(i))
- i += 1
- }
-
- back
- }
-
- override def reverse: Vector[T] = new VectorProjection[T] {
- override val length = outer.length
-
- override def apply(i: Int) = outer.apply(length - i - 1)
- }
-
- override def subseq(from: Int, end: Int) = subVector(from, end)
-
- def subVector(from: Int, end: Int): Vector[T] = {
- if (from < 0) {
- throw new IndexOutOfBoundsException(from.toString)
- } else if (end >= length) {
- throw new IndexOutOfBoundsException(end.toString)
- } else if (end <= from) {
- throw new IllegalArgumentException("Invalid range: " + from + ".." + end)
- } else {
- new VectorProjection[T] {
- override val length = end - from
-
- override def apply(i: Int) = outer.apply(i + from)
- }
- }
- }
-
- def zip[A](that: Vector[A]) = {
- var back = new Vector[(T, A)]
- var i = 0
-
- val limit = Math.min(length, that.length)
- while (i < limit) {
- back += (apply(i), that(i))
- i += 1
- }
-
- back
- }
-
- def zipWithIndex = {
- var back = new Vector[(T, Int)]
- var i = 0
-
- while (i < length) {
- back += (apply(i), i)
- i += 1
- }
-
- back
- }
-
- override def equals(other: Any) = other match {
- case vec:Vector[T] => {
- var back = length == vec.length
- var i = 0
-
- while (i < length) {
- back &&= apply(i) == vec.apply(i)
- i += 1
- }
-
- back
- }
-
- case _ => false
- }
-
- override def hashCode = foldLeft(0) { _ ^ _.hashCode }
-}
-
-object Vector {
- private[collection] val EmptyArray = new Array[AnyRef](0)
-
- def apply[T](elems: T*) = elems.foldLeft(EmptyVector:Vector[T]) { _ + _ }
-
- def unapplySeq[T](vec: Vector[T]): Option[Seq[T]] = Some(vec)
-
- @inline
- private[collection] def array(elems: AnyRef*) = {
- val back = new Array[AnyRef](elems.length)
- Array.copy(elems, 0, back, 0, back.length)
-
- back
- }
-}
-
-object EmptyVector extends Vector[Nothing]
-
-private[collection] abstract class VectorProjection[+T] extends Vector[T] {
- override val length: Int
- override def apply(i: Int): T
-
- override def +[A >: T](e: A) = innerCopy + e
-
- override def update[A >: T](i: Int, e: A) = {
- if (i < 0) {
- throw new IndexOutOfBoundsException(i.toString)
- } else if (i > length) {
- throw new IndexOutOfBoundsException(i.toString)
- } else innerCopy(i) = e
- }
-
- private lazy val innerCopy = foldLeft(EmptyVector:Vector[T]) { _ + _ }
-}
-
diff --git a/src/main/scala/com/codecommit/collection/VectorHashMap.scala b/src/main/scala/com/codecommit/collection/VectorHashMap.scala
deleted file mode 100644
index e51220d..0000000
--- a/src/main/scala/com/codecommit/collection/VectorHashMap.scala
+++ /dev/null
@@ -1,129 +0,0 @@
-package com.codecommit.collection
-
-import VectorHashMap._
-
-class VectorHashMap[K, +V] private (table: Vector[List[(K, V)]], val size: Int) extends Map[K, V] {
-
- def this() = this(allocate[K, V](10), 0)
-
- def get(key: K) = {
- def traverseBucket(bucket: List[(K, V)]): Option[V] = bucket match {
- case (k, v) :: tail => if (k == key) Some(v) else traverseBucket(tail)
- case Nil => None
- }
-
- val b = table(computeHash(key, table.length))
- if (b == null) None else traverseBucket(b)
- }
-
- override def +[A >: V](pair: (K, A)) = update(pair._1, pair._2)
-
- def update[A >: V](key: K, value: A) = {
- val (replaced, newTable) = store(grow(table, size))(key, value.asInstanceOf[V])
- new VectorHashMap[K, A](newTable, if (replaced) size else size + 1)
- }
-
- def -(key: K): VectorHashMap[K, V] = {
- val i = computeHash(key, table.length)
- val b = table(i)
-
- val (removed, newTable) = if (b == null) {
- (false, table)
- } else {
- def traverseBucket(bucket: List[(K, V)]): (Boolean, List[(K, V)]) = bucket match {
- case (k, v) :: tail => {
- if (k == key) {
- (true, tail)
- } else {
- val (found, newTail) = traverseBucket(tail)
- (found, (k, v) :: newTail)
- }
- }
-
- case Nil => (false, Nil)
- }
-
- val (found, newBucket) = traverseBucket(b)
- if (found) {
- (true, table(i) = newBucket)
- } else {
- (false, table)
- }
- }
-
- if (removed) {
- new VectorHashMap[K, V](newTable, size - 1)
- } else this
- }
-
- def elements: Iterator[(K, V)] = {
- val iterTable = table flatMap { // quick and dirty
- case null => Vector[(K, V)]()
-
- case bucket => bucket.foldLeft(Vector[(K, V)]()) { _ + _ }
- }
-
- iterTable.elements
- }
-
- def empty[C] = new VectorHashMap[K, C]()
-}
-
-object VectorHashMap {
-
- def apply[K, V](pairs: (K, V)*) = {
- pairs.foldLeft(new VectorHashMap[K, V]()) { _ + _ }
- }
-
- @inline
- private def computeHash[K](key: K, length: Int) = Math.abs(key.hashCode % length)
-
- @inline
- private[collection] def allocate[K, V](length: Int) = {
- (0 until length).foldLeft(Vector[List[(K, V)]]()) { (v, n) => v + null }
- }
-
- @inline
- private[collection] def grow[K, V](table: Vector[List[(K, V)]], size: Int) = {
- if (size >= table.length) {
- table.foldLeft(allocate[K, V](table.length * 2)) { (table, bucket) =>
- if (bucket == null) table else {
- bucket.foldLeft(table) { (table, pair) =>
- val (key, value) = pair
- store(table)(key, value)._2
- }
- }
- }
- } else table
- }
-
- @inline
- private[collection] def store[K, V, A >: V](table: Vector[List[(K, V)]])(key: K, value: A) = {
- val i = computeHash(key, table.length)
- val b = table(i)
-
- if (b == null) {
- (false, table(i) = (key, value) :: Nil)
- } else {
- def traverseBucket(bucket: List[(K, V)]): (Boolean, List[(K, A)]) = bucket match {
- case (k, v) :: tail => {
- if (k == key) {
- (true, (key, value) :: tail)
- } else {
- val (found, newTail) = traverseBucket(tail)
- (found, (k, v) :: newTail)
- }
- }
-
- case Nil => (false, Nil)
- }
-
- val (found, newBucket) = traverseBucket(b)
- if (found) {
- (true, table(i) = newBucket)
- } else {
- (false, table(i) = ((key, value) :: b))
- }
- }
- }
-}
diff --git a/src/spec/scala/PathVectorSpecs.scala b/src/spec/scala/PathVectorSpecs.scala
deleted file mode 100644
index 376d511..0000000
--- a/src/spec/scala/PathVectorSpecs.scala
+++ /dev/null
@@ -1,303 +0,0 @@
-import org.specs._
-import org.scalacheck._
-
-import com.codecommit.collection.PathVector
-
-object PathVectorSpecs extends Specification with ScalaCheck {
- import Prop._
-
- val vector = PathVector[Int]()
-
- implicit def arbitraryPathVector[A](implicit arb: Arbitrary[A]): Arbitrary[PathVector[A]] = {
- Arbitrary(for {
- data <- Arbitrary.arbitrary[List[A]]
- indexes <- Gen.containerOfN[List, Int](data.length, Gen.choose(0, Math.MAX_INT - 1))
- } yield {
- var vec = new PathVector[A]
-
- var i = 0
- for (d <- data) {
- vec(indexes(i)) = d
- i += 1
- }
-
- vec
- })
- }
-
-
- "path vector" should {
- "have infinite bounds" in {
- vector.length mustEqual 0 // finite length
-
- val prop = forAll { i: Int => // infinite bounds
- i >= 0 ==> (vector(i) == 0)
- }
-
- prop must pass
- }
-
- "store a single element" in {
- val prop = forAll { (i: Int, e: Int) =>
- i >= 0 ==> ((vector(0) = e)(0) == e)
- }
-
- prop must pass
- }
-
- "replace single element" in {
- val prop = forAll { (vec: PathVector[String], i: Int) =>
- i >= 0 ==> {
- val newPathVector = (vec(i) = "test")(i) = "newTest"
- newPathVector(i) == "newTest"
- }
- }
-
- prop must pass
- }
-
- "store multiple elements in order" in {
- val prop = forAll { list: List[Int] =>
- val newPathVector = list.foldLeft(vector) { _ + _ }
- val res = for (i <- 0 until list.length) yield newPathVector(i) == list(i)
-
- res forall { _ == true }
- }
-
- prop must pass
- }
-
- "store lots of elements" in {
- val LENGTH = 100000
- val vector = (0 until LENGTH).foldLeft(PathVector[Int]()) { _ + _ }
-
- vector.length mustEqual LENGTH
- for (i <- 0 until LENGTH) {
- vector(i) mustEqual i
- }
- }
-
- "store at arbitrary points" in {
- val vector = PathVector(1, 2, 3, 4, 5)
- val prop = forAll { others: List[(Int, Int)] =>
- val (newPathVector, resMap) = others.foldLeft(vector, Map[Int, Int]()) { (inTuple, tuple) =>
- val (i, value) = tuple
- val (vec, map) = inTuple
-
- if (i < 0) (vec, map) else (vec(i) = value, map + (i -> value))
- }
-
- val res = for {
- (i, _) <- others
- } yield if (i < 0) true else newPathVector(i) == resMap(i)
-
- res forall { _ == true }
- }
-
- prop must pass
- }
-
- "implement filter" in {
- val prop = forAll { (vec: PathVector[Int], f: (Int)=>Boolean) =>
- val filtered = vec filter f
-
- var back = filtered forall f
- for (e <- vec) {
- if (f(e)) {
- back &&= filtered.contains(e)
- }
- }
- back
- }
-
- prop must pass
- }
-
- "implement foldLeft" in {
- val prop = forAll { list: List[Int] =>
- val vec = list.foldLeft(new PathVector[Int]) { _ + _ }
- vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ }
- }
-
- prop must pass
- }
-
- "implement forall" in {
- val prop = forAll { (vec: PathVector[Int], f: (Int)=>Boolean) =>
- val bool = vec forall f
-
- var back = true
- for (e <- vec) {
- back &&= f(e)
- }
-
- (back && bool) || (!back && !bool)
- }
-
- prop must pass
- }
-
- "implement map" in {
- val prop = forAll { (vec: PathVector[Int], f: (Int)=>Int) =>
- val mapped = vec map f
-
- var back = vec.length == mapped.length
- for (i <- 0 until vec.length) {
- back &&= mapped(i) == f(vec(i))
- }
- back
- }
-
- prop must pass
- }
-
- "implement reverse" in {
- val prop = forAll { v: PathVector[Int] =>
- val reversed = v.reverse
-
- var back = v.length == reversed.length
- for (i <- 0 until v.length) {
- back &&= reversed(i) == v(v.length - i - 1)
- }
- back
- }
-
- prop must pass
- }
-
- "append to reverse" in {
- val prop = forAll { (v: PathVector[Int], n: Int) =>
- val rev = v.reverse
- val add = rev + n
-
- var back = add.length == rev.length + 1
- for (i <- 0 until rev.length) {
- back &&= add(i) == rev(i)
- }
- back && add(rev.length) == n
- }
-
- prop must pass
- }
-
- "map on reverse" in {
- val prop = forAll { (v: PathVector[Int], f: (Int)=>Int) =>
- val rev = v.reverse
- val mapped = rev map f
-
- var back = mapped.length == rev.length
- for (i <- 0 until rev.length) {
- back &&= mapped(i) == f(rev(i))
- }
- back
- }
-
- prop must pass
- }
-
- "implement subseq" in {
- skip("Disabling for now")
- val prop = forAll { (v: PathVector[Int], from: Int, end: Int) =>
- try {
- val sub = v.subseq(from, end)
-
- var back = sub.length == end - from
- for (i <- 0 until sub.length) {
- back &&= sub(i) == v(i + from)
- }
- back
- } catch {
- case _:IndexOutOfBoundsException => from < 0
- case _:IllegalArgumentException => end <= from
- }
- }
-
- prop must pass
- }
-
- "append to subseq" in {
- skip("Disabling for now")
-
- val prop = forAll { (v: PathVector[Int], from: Int, end: Int, n: Int) =>
- try {
- val sub = v.subseq(from, end)
- val add = sub + n
-
- var back = add.length == sub.length + 1
- for (i <- 0 until sub.length) {
- back &&= add(i) == sub(i)
- }
- back && add(sub.length) == n
- } catch {
- case _:IndexOutOfBoundsException => from < 0
- case _:IllegalArgumentException => end <= from
- }
- }
-
- prop must pass
- }
-
- "map on subseq" in {
- skip("Disabling for now")
- val prop = forAll { (v: PathVector[Int], from: Int, end: Int, f: (Int)=>Int) =>
- try {
- val sub = v.subseq(from, end)
- val mapped = sub map f
-
- var back = mapped.length == sub.length
- for (i <- 0 until sub.length) {
- back &&= mapped(i) == f(sub(i))
- }
- back
- } catch {
- case _:IndexOutOfBoundsException => from < 0
- case _:IllegalArgumentException => end <= from
- }
- }
-
- prop must pass
- }
-
- "implement zip" in {
- val prop = forAll { (first: PathVector[Int], second: PathVector[Double]) =>
- val zip = first zip second
-
- var back = zip.length == Math.max(first.length, second.length)
- for (i <- 0 until zip.length) {
- var (left, right) = zip(i)
- back &&= (left == first(i) && right == second(i))
- }
- back
- }
-
- prop must pass
- }
-
- "implement zipWithIndex" in {
- val prop = forAll { vec: PathVector[Int] =>
- val zip = vec.zipWithIndex
-
- var back = zip.length == vec.length
- for (i <- 0 until zip.length) {
- val (elem, index) = zip(i)
-
- back &&= (index == i && elem == vec(i))
- }
- back
- }
-
- prop must pass
- }
-
- "implement equals" in {
- val prop = forAll { list: List[Int] =>
- val vecA = list.foldLeft(new PathVector[Int]) { _ + _ }
- val vecB = list.foldLeft(new PathVector[Int]) { _ + _ }
-
- vecA == vecB
- }
-
- prop must pass
- }
- }
-}
diff --git a/src/spec/scala/VectorSpecs.scala b/src/spec/scala/VectorSpecs.scala
deleted file mode 100644
index 1857a5a..0000000
--- a/src/spec/scala/VectorSpecs.scala
+++ /dev/null
@@ -1,426 +0,0 @@
-import org.specs._
-import org.scalacheck._
-
-import com.codecommit.collection.{EmptyVector, Vector}
-
-object VectorSpecs extends Specification with ScalaCheck {
- import Prop._
-
- val vector = Vector[Int]()
-
- implicit def arbitraryVector[A](implicit arb: Arbitrary[A]): Arbitrary[Vector[A]] = {
- Arbitrary(for {
- data <- Arbitrary.arbitrary[List[A]]
- } yield data.foldLeft(Vector[A]()) { _ + _ })
- }
-
- "vector" should {
- "store a single element" in {
- val prop = forAll { (i: Int, e: Int) =>
- i >= 0 ==> ((vector(0) = e)(0) == e)
- }
-
- prop must pass
- }
-
- "implement length" in {
- val prop = forAll { (list: List[Int]) =>
- val vec = list.foldLeft(Vector[Int]()) { _ + _ }
- vec.length == list.length
- }
-
- prop must pass
- }
-
- "replace single element" in {
- val prop = forAll { (vec: Vector[Int], i: Int) =>
- ((0 to vec.length) contains i) ==> {
- val newVector = (vec(i) = "test")(i) = "newTest"
- newVector(i) == "newTest"
- }
- }
-
- prop must pass
- }
-
- "fail on apply out-of-bounds" in {
- val prop = forAll { (vec: Vector[Int], i: Int) =>
- !((0 until vec.length) contains i) ==> {
- try {
- vec(i)
- false
- } catch {
- case _: IndexOutOfBoundsException => true
- }
- }
- }
-
- prop must pass
- }
-
- "fail on update out-of-bounds" in {
- val prop = forAll { (vec: Vector[Int], i: Int) =>
- !((0 to vec.length) contains i) ==> {
- try {
- vec(i) = 42
- false
- } catch {
- case _: IndexOutOfBoundsException => true
- }
- }
- }
-
- prop must pass
- }
-
- "pop elements" in {
- val prop = forAll { vec: Vector[Int] =>
- vec.length > 0 ==> {
- val popped = vec.pop
- var back = popped.length == vec.length - 1
-
- for (i <- 0 until popped.length) {
- back &&= popped(i) == vec(i)
- }
-
- back
- }
- }
-
- prop must pass(set(maxSize -> 3000, minTestsOk -> 1000))
- }
-
- "fail on pop empty vector" in {
- val caughtExcept = try {
- EmptyVector.pop
- false
- } catch {
- case _: IllegalStateException => true
- }
-
- caughtExcept mustEqual true
- }
-
- "store multiple elements in order" in {
- val prop = forAll { list: List[Int] =>
- val newVector = list.foldLeft(vector) { _ + _ }
- val res = for (i <- 0 until list.length) yield newVector(i) == list(i)
-
- res forall { _ == true }
- }
-
- prop must pass
- }
-
- "store lots of elements" in {
- val LENGTH = 100000
- val vector = (0 until LENGTH).foldLeft(Vector[Int]()) { _ + _ }
-
- vector.length mustEqual LENGTH
- for (i <- 0 until LENGTH) {
- vector(i) mustEqual i
- }
- }
-
- "implement filter" in {
- val prop = forAll { (vec: Vector[Int], f: (Int)=>Boolean) =>
- val filtered = vec filter f
-
- var back = filtered forall f
- for (e <- vec) {
- if (f(e)) {
- back &&= filtered.contains(e)
- }
- }
- back
- }
-
- prop must pass
- }
-
- "implement foldLeft" in {
- val prop = forAll { list: List[Int] =>
- val vec = list.foldLeft(Vector[Int]()) { _ + _ }
- vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ }
- }
-
- prop must pass
- }
-
- "implement forall" in {
- val prop = forAll { (vec: Vector[Int], f: (Int)=>Boolean) =>
- val bool = vec forall f
-
- var back = true
- for (e <- vec) {
- back &&= f(e)
- }
-
- (back && bool) || (!back && !bool)
- }
-
- prop must pass
- }
-
- "implement flatMap" in {
- val prop = forAll { (vec: Vector[Int], f: (Int)=>Vector[Int]) =>
- val mapped = vec flatMap f
-
- var back = true
-
- var i = 0
- var n = 0
-
- while (i < vec.length) {
- val res = f(vec(i))
-
- var inner = 0
- while (inner < res.length) {
- back &&= mapped(n) == res(inner)
-
- inner += 1
- n += 1
- }
-
- i += 1
- }
-
- back
- }
-
- prop must pass
- }
-
- "implement map" in {
- val prop = forAll { (vec: Vector[Int], f: (Int)=>Int) =>
- val mapped = vec map f
-
- var back = vec.length == mapped.length
- for (i <- 0 until vec.length) {
- back &&= mapped(i) == f(vec(i))
- }
- back
- }
-
- prop must pass
- }
-
- "implement reverse" in {
- val prop = forAll { v: Vector[Int] =>
- val reversed = v.reverse
-
- var back = v.length == reversed.length
- for (i <- 0 until v.length) {
- back &&= reversed(i) == v(v.length - i - 1)
- }
- back
- }
-
- prop must pass
- }
-
- "append to reverse" in {
- val prop = forAll { (v: Vector[Int], n: Int) =>
- val rev = v.reverse
- val add = rev + n
-
- var back = add.length == rev.length + 1
- for (i <- 0 until rev.length) {
- back &&= add(i) == rev(i)
- }
- back && add(rev.length) == n
- }
-
- prop must pass
- }
-
- "map on reverse" in {
- val prop = forAll { (v: Vector[Int], f: (Int)=>Int) =>
- val rev = v.reverse
- val mapped = rev map f
-
- var back = mapped.length == rev.length
- for (i <- 0 until rev.length) {
- back &&= mapped(i) == f(rev(i))
- }
- back
- }
-
- prop must pass
- }
-
- "implement subseq" in {
- val prop = forAll { (v: Vector[Int], from: Int, end: Int) =>
- try {
- val sub = v.subseq(from, end)
-
- var back = sub.length == end - from
-
- for (i <- 0 until sub.length) {
- back &&= sub(i) == v(i + from)
- }
-
- back
- } catch {
- case _:IndexOutOfBoundsException => from < 0 || end >= v.length
- case _:IllegalArgumentException => end <= from
- }
- }
-
- prop must pass
- }
-
- "append to subseq" in {
- val prop = forAll { (v: Vector[Int], from: Int, end: Int, n: Int) =>
- try {
- val sub = v.subseq(from, end)
- val add = sub + n
-
- var back = add.length == sub.length + 1
- for (i <- 0 until sub.length) {
- back &&= add(i) == sub(i)
- }
- back && add(sub.length) == n
- } catch {
- case _:IndexOutOfBoundsException => from < 0 || end >= v.length
- case _:IllegalArgumentException => end <= from
- }
- }
-
- prop must pass
- }
-
- "update subseq" in {
- val prop = forAll { (v: Vector[Int], from: Int, end: Int, mi: Int) =>
- try {
- val sub = v.subseq(from, end)
- val add = sub(mi) = 42
-
- var back = add.length == sub.length + (if (mi == sub.length) 1 else 0)
- for (i <- 0 until sub.length; if i != mi) {
- back &&= add(i) == sub(i)
- }
- back && add(mi) == 42
- } catch {
- case _:IndexOutOfBoundsException => from < 0 || end >= v.length || !(0 to (end - from) contains mi)
- case _:IllegalArgumentException => end <= from
- }
- }
-
- prop must pass
- }
-
- "map on subseq" in {
- val prop = forAll { (v: Vector[Int], from: Int, end: Int, f: (Int)=>Int) =>
- try {
- val sub = v.subseq(from, end)
- val mapped = sub map f
-
- var back = mapped.length == sub.length
- for (i <- 0 until sub.length) {
- back &&= mapped(i) == f(sub(i))
- }
- back
- } catch {
- case _:IndexOutOfBoundsException => from < 0 || end >= v.length
- case _:IllegalArgumentException => end <= from
- }
- }
-
- prop must pass
- }
-
- "implement zip" in {
- val prop = forAll { (first: Vector[Int], second: Vector[Double]) =>
- val zip = first zip second
-
- var back = zip.length == Math.min(first.length, second.length)
- for (i <- 0 until zip.length) {
- var (left, right) = zip(i)
- back &&= (left == first(i) && right == second(i))
- }
- back
- }
-
- prop must pass
- }
-
- "implement zipWithIndex" in {
- val prop = forAll { vec: Vector[Int] =>
- val zip = vec.zipWithIndex
-
- var back = zip.length == vec.length
- for (i <- 0 until zip.length) {
- val (elem, index) = zip(i)
-
- back &&= (index == i && elem == vec(i))
- }
- back
- }
-
- prop must pass
- }
-
- "implement equals" in {
- {
- val prop = forAll { list: List[Int] =>
- val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
- val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
-
- vecA == vecB
- }
-
- prop must pass
- }
-
- {
- val prop = forAll { (vecA: Vector[Int], vecB: Vector[Int]) =>
- vecA.length != vecB.length ==> (vecA != vecB)
- }
-
- prop must pass
- }
-
- {
- val prop = forAll { (listA: List[Int], listB: List[Int]) =>
- val vecA = listA.foldLeft(Vector[Int]()) { _ + _ }
- val vecB = listB.foldLeft(Vector[Int]()) { _ + _ }
-
- listA != listB ==> (vecA != vecB)
- }
-
- prop must pass
- }
-
- {
- val prop = forAll { (vec: Vector[Int], data: Int) => vec != data }
-
- prop must pass
- }
- }
-
- "implement hashCode" in {
- val prop = forAll { list: List[Int] =>
- val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
- val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
-
- vecA.hashCode == vecB.hashCode
- }
-
- prop must pass
- }
-
- "implement extractor" in {
- val vec1 = Vector(1, 2, 3)
- vec1 must beLike {
- case Vector(a, b, c) => (a, b, c) == (1, 2, 3)
- }
-
- val vec2 = Vector("daniel", "chris", "joseph")
- vec2 must beLike {
- case Vector(a, b, c) => (a, b, c) == ("daniel", "chris", "joseph")
- }
- }
- }
-}
-
diff --git a/src/test/scala/VectorPerf.scala b/src/test/scala/VectorPerf.scala
deleted file mode 100644
index 0e7349e..0000000
--- a/src/test/scala/VectorPerf.scala
+++ /dev/null
@@ -1,320 +0,0 @@
-import com.codecommit.collection.Vector
-
-import scala.collection.mutable.ArrayBuffer
-import scala.collection.immutable.IntMap
-
-object VectorPerf {
- import PerfLib._
-
- def main(args: Array[String]) {
- println()
-
- //==========================================================================
- {
- title("Fill 100000 Sequential Indexes")
-
- val vectorOp = "Vector" -> time {
- var vec = Vector[Int]()
- var i = 0
-
- while (i < 100000) {
- vec += i
- i += 1
- }
- }
-
- val arrayOp = "ArrayBuffer" -> time {
- var arr = new ArrayBuffer[Int]
- var i = 0
-
- while (i < 100000) {
- arr += i
- i += 1
- }
- }
-
- vectorOp compare arrayOp
-
- val intMapOp = "IntMap" -> time {
- var map = IntMap[Int]()
- var i = 0
-
- while (i < 100000) {
- map = map(i) = i
- i += 1
- }
- }
-
- vectorOp compare intMapOp
-
- val oldIntMapOp = "Map[Int, _]" -> time {
- var map = Map[Int, Int]()
- var i = 0
-
- while (i < 100000) {
- map = map(i) = i
- i += 1
- }
- }
-
- vectorOp compare oldIntMapOp
-
- div('=')
- println()
- }
-
- //==========================================================================
- {
- title("Read 100000 Sequential Indexes")
-
- var vec = Vector[Int]()
- for (i <- 0 until 100000) {
- vec += i
- }
-
- var arr = new ArrayBuffer[Int]
- for (i <- 0 until 100000) {
- arr += i
- }
-
- var bitVec = Vector[Int]()
- for (i <- 0 until 100000) {
- bitVec += i
- }
-
- var map = IntMap[Int]()
- for (i <- 0 until 100000) {
- map = map(i) = i
- }
-
- var oldMap = Map[Int, Int]()
- for (i <- 0 until 100000) {
- oldMap = oldMap(i) = i
- }
-
- val vectorOp = "Vector" -> time {
- var i = 0
- while (i < vec.length) {
- vec(i)
- i += 1
- }
- }
-
- val arrayOp = "ArrayBuffer" -> time {
- var i = 0
- while (i < arr.size) {
- arr(i)
- i += 1
- }
- }
-
- vectorOp compare arrayOp
-
- val intMapOp = "IntMap" -> time {
- var i = 0
- while (i < vec.length) { // map.size is unsuitable
- map(i)
- i += 1
- }
- }
-
- vectorOp compare intMapOp
-
- val oldIntMapOp = "Map[Int, _]" -> time {
- var i = 0
- while (i < vec.length) { // map.size is unsuitable
- oldMap(i)
- i += 1
- }
- }
-
- vectorOp compare oldIntMapOp
-
- div('=')
- println()
- }
-
- //==========================================================================
- {
- title("Read 100000 Random Indexes")
-
- val indexes = new Array[Int](100000)
- var max = -1
- for (i <- 0 until indexes.length) {
- indexes(i) = Math.round(Math.random * 40000000).toInt
- max = Math.max(max, indexes(i))
- }
-
- var vec = Vector[Int]()
- for (i <- 0 to max) { // unplesant hack
- vec += 0
- }
-
- for (i <- 0 until indexes.length) {
- vec = vec(indexes(i)) = i
- }
-
- val arr = new ArrayBuffer[Int]
- for (i <- 0 to max) { // unplesant hack
- arr += 0
- }
-
- for (i <- 0 until indexes.length) {
- arr(indexes(i)) = i
- }
-
- var bitVec = Vector[Int]()
- for (i <- 0 to max) { // unplesant hack
- bitVec += 0
- }
-
- for (i <- 0 until indexes.length) {
- bitVec(indexes(i)) = i
- }
-
- var map = IntMap[Int]()
- for (i <- 0 until indexes.length) {
- map = map(indexes(i)) = i
- }
-
- var oldMap = Map[Int, Int]()
- for (i <- 0 until indexes.length) {
- oldMap = map(indexes(i)) = i
- }
-
- val vectorOp = "Vector" -> time {
- var i = 0
- while (i < indexes.length) {
- vec(indexes(i))
- i += 1
- }
- }
-
- val arrayOp = "ArrayBuffer" -> time {
- var i = 0
- while (i < indexes.length) {
- arr(indexes(i))
- i += 1
- }
- }
-
- vectorOp compare arrayOp
-
- val intMapOp = "IntMap" -> time {
- var i = 0
- while (i < indexes.length) {
- map(indexes(i))
- i += 1
- }
- }
-
- vectorOp compare intMapOp
-
- val oldIntMapOp = "Map[Int, _]" -> time {
- var i = 0
- while (i < indexes.length) {
- oldMap(indexes(i))
- i += 1
- }
- }
-
- vectorOp compare oldIntMapOp
-
- div('=')
- println()
- }
-
- //==========================================================================
- {
- title("Reverse of Length 100000")
-
- var vec = Vector[Int]()
- for (i <- 0 until 100000) {
- vec += i
- }
-
- var arr = new ArrayBuffer[Int]
- for (i <- 0 until 100000) {
- arr += i
- }
-
- var bitVec = Vector[Int]()
- for (i <- 0 until 100000) {
- bitVec += i
- }
-
- var map = IntMap[Int]()
- for (i <- 0 until 100000) {
- map = map(i) = i
- }
-
- val vectorOp = "Vector" -> time {
- vec.reverse
- }
-
- val arrayOp = "ArrayBuffer" -> time {
- arr.reverse
- }
-
- vectorOp compare arrayOp
-
- div('=')
- println()
- }
-
- //==========================================================================
- {
- title("Compute Length (100000)")
-
- var vec = Vector[Int]()
- for (i <- 0 until 100000) {
- vec += i
- }
-
- var arr = new ArrayBuffer[Int]
- for (i <- 0 until 100000) {
- arr += i
- }
-
- var bitVec = Vector[Int]()
- for (i <- 0 until 100000) {
- bitVec += i
- }
-
- var map = IntMap[Int]()
- for (i <- 0 until 100000) {
- map = map(i) = i
- }
-
- var oldMap = Map[Int, Int]()
- for (i <- 0 until 100000) {
- oldMap = oldMap(i) = i
- }
-
- val vectorOp = "Vector" -> time {
- vec.length
- }
-
- val arrayOp = "ArrayBuffer" -> time {
- arr.length
- }
-
- vectorOp compare arrayOp
-
- val intMapOp = "IntMap" -> time {
- map.size
- }
-
- vectorOp compare intMapOp
-
- val oldIntMapOp = "Map[Int, _]" -> time {
- oldMap.size
- }
-
- vectorOp compare oldIntMapOp
-
- div('=')
- println()
- }
- }
-}
|
djspiewak/scala-collections
|
6cdf77c9ac8e6de3e5b63360e1b28c4168e88cd8
|
Fixed up everything for the latest version of ScalaCheck
|
diff --git a/buildfile b/buildfile
index 9d64a91..9aab134 100644
--- a/buildfile
+++ b/buildfile
@@ -1,15 +1,14 @@
require 'buildr/scala'
#require 'buildr/java/cobertura'
-require 'buildr/groovy'
repositories.remote << 'http://repo1.maven.org/maven2/'
desc 'A few collections classes for fun and profit'
define 'collection' do
project.version = '0.1.0'
project.group = 'com.codecommit'
test.using :specs
package :jar
end
diff --git a/src/spec/scala/BloomSpecs.scala b/src/spec/scala/BloomSpecs.scala
index f4a2d32..a586fdd 100644
--- a/src/spec/scala/BloomSpecs.scala
+++ b/src/spec/scala/BloomSpecs.scala
@@ -1,134 +1,136 @@
import org.specs._
import org.scalacheck._
import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
import com.codecommit.collection.BloomSet
object BloomSpecs extends Specification with ScalaCheck {
import Prop._
"bloom set" should {
"store single element once" in {
(BloomSet[String]() + "test") contains "test" mustEqual true
}
"store single element n times" in {
- val prop = property { ls: List[String] =>
+ val prop = forAll { ls: List[String] =>
val set = ls.foldLeft(BloomSet[String]()) { _ + _ }
ls.foldLeft(true) { _ && set(_) }
}
prop must pass
}
"store duplicate elements n times" in {
- val prop = property { ls: List[String] =>
+ val prop = forAll { ls: List[String] =>
var set = ls.foldLeft(BloomSet[String]()) { _ + _ }
set = ls.foldLeft(set) { _ + _ }
ls.foldLeft(true) { _ && set(_) }
}
prop must pass
}
"handle ++ Iterable" in {
- val prop = property { (first: List[String], last: List[String]) =>
+ val prop = forAll { (first: List[String], last: List[String]) =>
var set = first.foldLeft(BloomSet[String]()) { _ + _ }
set ++= last
first.foldLeft(true) { _ && set(_) } && last.foldLeft(true) { _ && set(_) }
}
prop must pass
}
"handle ++ BloomSet" in {
- val prop = property { (first: List[String], last: List[String]) =>
+ val prop = forAll { (first: List[String], last: List[String]) =>
var set = first.foldLeft(BloomSet[String]()) { _ + _ }
set ++= last.foldLeft(BloomSet[String]()) { _ + _ }
first.foldLeft(true) { _ && set(_) } && last.foldLeft(true) { _ && set(_) }
}
prop must pass
}
"be immutable" in {
- val prop = property { (ls: List[String], item: String) =>
+ val prop = forAll { (ls: List[String], item: String) =>
val set = ls.foldLeft(new BloomSet[String](10000, 5)) { _ + _ }
// might fail, but it is doubtful
(set.accuracy > 0.999 && !ls.contains(item)) ==> {
val newSet = set + item
ls.foldLeft(true) { _ && set(_) } &&
!set.contains(item) &&
ls.foldLeft(true) { _ && newSet(_) } &&
newSet.contains(item)
}
}
prop must pass(set(minTestsOk -> 100, maxDiscarded -> 5000, minSize -> 0, maxSize -> 100))
}
"construct using companion" in {
val set = BloomSet("daniel", "chris", "joseph", "renee")
set contains "daniel" mustEqual true
set contains "chris" mustEqual true
set contains "joseph" mustEqual true
set contains "renee" mustEqual true
}
"implement equivalency" in {
- val prop = property { nums: List[Int] =>
+ val prop = forAll { nums: List[Int] =>
val set1 = nums.foldLeft(BloomSet[Int]()) { _ + _}
val set2 = nums.foldLeft(BloomSet[Int]()) { _ + _}
set1 == set2
}
prop must pass
}
"implement hashing" in {
- val prop = property { nums: List[Int] =>
+ val prop = forAll { nums: List[Int] =>
val set1 = nums.foldLeft(BloomSet[Int]()) { _ + _}
val set2 = nums.foldLeft(BloomSet[Int]()) { _ + _}
set1.hashCode == set2.hashCode
}
prop must pass
}
"persist properly" in {
- val prop = property { (width: Int, k: Int, ls: List[Int]) => (width > 0 && k > 0) ==> {
+ skip("Disabling for now")
+
+ val prop = forAll { (width: Int, k: Int, ls: List[Int]) => (width > 0 && k > 0) ==> {
val set = ls.foldLeft(new BloomSet[Int](width, k)) { _ + _ }
val os = new ByteArrayOutputStream
set.store(os)
val is = new ByteArrayInputStream(os.toByteArray)
val newSet = BloomSet.load[Int](is)
ls.foldLeft(true) { _ && newSet(_) } &&
newSet.width == set.width &&
newSet.k == set.k &&
newSet.size == set.size
}
}
prop must pass
}
"calculate accuracy" in {
BloomSet[Int]().accuracy mustEqual 1d
val set = (0 until 1000).foldLeft(BloomSet[Int]()) { _ + _ }
set.accuracy must beCloseTo(0d, 0.0000001d)
}
}
}
diff --git a/src/spec/scala/HashTrieSpecs.scala b/src/spec/scala/HashTrieSpecs.scala
index cb88a02..e5d73f7 100644
--- a/src/spec/scala/HashTrieSpecs.scala
+++ b/src/spec/scala/HashTrieSpecs.scala
@@ -1,101 +1,101 @@
import org.specs._
import org.scalacheck._
import com.codecommit.collection.HashTrie
object HashTrieSpecs extends Specification with ScalaCheck {
import Prop._
"it" should {
"store ints" in {
- val prop = property { src: List[Int] =>
+ val prop = forAll { src: List[Int] =>
val map = src.foldLeft(new HashTrie[Int, Int]) { (m, v) => m(v) = -v }
src forall { v => map(v) == -v }
}
prop must pass(set(maxSize -> 5000, minTestsOk -> 2000))
}
"store strings" in {
- val prop = property { src: List[String] =>
+ val prop = forAll { src: List[String] =>
val map = src.foldLeft(new HashTrie[String, Int]) { (m, v) => m(v) = v.length }
src forall { v => map(v) == v.length }
}
prop must pass
}
"preserve values across changes" in {
- val prop = property { (map: HashTrie[String, String], ls: List[String], f: (String)=>String) =>
+ val prop = forAll { (map: HashTrie[String, String], ls: List[String], f: (String)=>String) =>
val filtered = ls filter { !map.contains(_) }
filtered.length > 0 ==> {
val newMap = filtered.foldLeft(map) { (m, k) => m(k) = f(k) }
(map forall { case (k, v) => newMap(k) == v }) && (filtered forall { v => newMap(v) == f(v) })
}
}
prop must pass
}
"calculate size" in {
- val prop = property { (ls: Set[Int], f: (Int)=>Int) =>
+ val prop = forAll { (ls: Set[Int], f: (Int)=>Int) =>
val map = ls.foldLeft(new HashTrie[Int, Int]) { (m, v) => m(v) = f(v) }
map.size == ls.size
}
prop must pass
}
"remove ints" in {
- val prop = property { map: HashTrie[Int, String] =>
+ val prop = forAll { map: HashTrie[Int, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next // insufficient
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
"remove strings" in {
- val prop = property { map: HashTrie[String, String] =>
+ val prop = forAll { map: HashTrie[String, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
"define empty" in {
- val prop = property { map: HashTrie[String, String] =>
+ val prop = forAll { map: HashTrie[String, String] =>
map.empty.size == 0
}
prop must pass
}
}
implicit def arbHashTrie[K](implicit ak: Arbitrary[List[K]]): Arbitrary[HashTrie[K, String]] = {
Arbitrary(for {
keys <- ak.arbitrary
} yield keys.foldLeft(new HashTrie[K, String]) { (m, k) => m(k) = k.toString })
}
implicit def arbSet[A](implicit arb: Arbitrary[List[A]]): Arbitrary[Set[A]] = {
Arbitrary(for {
ls <- arb.arbitrary
} yield ls.foldLeft(Set[A]()) { _ + _ })
}
}
diff --git a/src/spec/scala/PathVectorSpecs.scala b/src/spec/scala/PathVectorSpecs.scala
index 390405a..376d511 100644
--- a/src/spec/scala/PathVectorSpecs.scala
+++ b/src/spec/scala/PathVectorSpecs.scala
@@ -1,299 +1,303 @@
import org.specs._
import org.scalacheck._
import com.codecommit.collection.PathVector
object PathVectorSpecs extends Specification with ScalaCheck {
import Prop._
val vector = PathVector[Int]()
implicit def arbitraryPathVector[A](implicit arb: Arbitrary[A]): Arbitrary[PathVector[A]] = {
Arbitrary(for {
data <- Arbitrary.arbitrary[List[A]]
indexes <- Gen.containerOfN[List, Int](data.length, Gen.choose(0, Math.MAX_INT - 1))
} yield {
var vec = new PathVector[A]
var i = 0
for (d <- data) {
vec(indexes(i)) = d
i += 1
}
vec
})
}
"path vector" should {
"have infinite bounds" in {
vector.length mustEqual 0 // finite length
- val prop = property { i: Int => // infinite bounds
+ val prop = forAll { i: Int => // infinite bounds
i >= 0 ==> (vector(i) == 0)
}
prop must pass
}
"store a single element" in {
- val prop = property { (i: Int, e: Int) =>
+ val prop = forAll { (i: Int, e: Int) =>
i >= 0 ==> ((vector(0) = e)(0) == e)
}
prop must pass
}
"replace single element" in {
- val prop = property { (vec: PathVector[String], i: Int) =>
+ val prop = forAll { (vec: PathVector[String], i: Int) =>
i >= 0 ==> {
val newPathVector = (vec(i) = "test")(i) = "newTest"
newPathVector(i) == "newTest"
}
}
prop must pass
}
"store multiple elements in order" in {
- val prop = property { list: List[Int] =>
+ val prop = forAll { list: List[Int] =>
val newPathVector = list.foldLeft(vector) { _ + _ }
val res = for (i <- 0 until list.length) yield newPathVector(i) == list(i)
res forall { _ == true }
}
prop must pass
}
"store lots of elements" in {
val LENGTH = 100000
val vector = (0 until LENGTH).foldLeft(PathVector[Int]()) { _ + _ }
vector.length mustEqual LENGTH
for (i <- 0 until LENGTH) {
vector(i) mustEqual i
}
}
"store at arbitrary points" in {
val vector = PathVector(1, 2, 3, 4, 5)
- val prop = property { others: List[(Int, Int)] =>
+ val prop = forAll { others: List[(Int, Int)] =>
val (newPathVector, resMap) = others.foldLeft(vector, Map[Int, Int]()) { (inTuple, tuple) =>
val (i, value) = tuple
val (vec, map) = inTuple
if (i < 0) (vec, map) else (vec(i) = value, map + (i -> value))
}
val res = for {
(i, _) <- others
} yield if (i < 0) true else newPathVector(i) == resMap(i)
res forall { _ == true }
}
prop must pass
}
"implement filter" in {
- val prop = property { (vec: PathVector[Int], f: (Int)=>Boolean) =>
+ val prop = forAll { (vec: PathVector[Int], f: (Int)=>Boolean) =>
val filtered = vec filter f
var back = filtered forall f
for (e <- vec) {
if (f(e)) {
back &&= filtered.contains(e)
}
}
back
}
prop must pass
}
"implement foldLeft" in {
- val prop = property { list: List[Int] =>
+ val prop = forAll { list: List[Int] =>
val vec = list.foldLeft(new PathVector[Int]) { _ + _ }
vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ }
}
prop must pass
}
"implement forall" in {
- val prop = property { (vec: PathVector[Int], f: (Int)=>Boolean) =>
+ val prop = forAll { (vec: PathVector[Int], f: (Int)=>Boolean) =>
val bool = vec forall f
var back = true
for (e <- vec) {
back &&= f(e)
}
(back && bool) || (!back && !bool)
}
prop must pass
}
"implement map" in {
- val prop = property { (vec: PathVector[Int], f: (Int)=>Int) =>
+ val prop = forAll { (vec: PathVector[Int], f: (Int)=>Int) =>
val mapped = vec map f
var back = vec.length == mapped.length
for (i <- 0 until vec.length) {
back &&= mapped(i) == f(vec(i))
}
back
}
prop must pass
}
"implement reverse" in {
- val prop = property { v: PathVector[Int] =>
+ val prop = forAll { v: PathVector[Int] =>
val reversed = v.reverse
var back = v.length == reversed.length
for (i <- 0 until v.length) {
back &&= reversed(i) == v(v.length - i - 1)
}
back
}
prop must pass
}
"append to reverse" in {
- val prop = property { (v: PathVector[Int], n: Int) =>
+ val prop = forAll { (v: PathVector[Int], n: Int) =>
val rev = v.reverse
val add = rev + n
var back = add.length == rev.length + 1
for (i <- 0 until rev.length) {
back &&= add(i) == rev(i)
}
back && add(rev.length) == n
}
prop must pass
}
"map on reverse" in {
- val prop = property { (v: PathVector[Int], f: (Int)=>Int) =>
+ val prop = forAll { (v: PathVector[Int], f: (Int)=>Int) =>
val rev = v.reverse
val mapped = rev map f
var back = mapped.length == rev.length
for (i <- 0 until rev.length) {
back &&= mapped(i) == f(rev(i))
}
back
}
prop must pass
}
"implement subseq" in {
- val prop = property { (v: PathVector[Int], from: Int, end: Int) =>
+ skip("Disabling for now")
+ val prop = forAll { (v: PathVector[Int], from: Int, end: Int) =>
try {
val sub = v.subseq(from, end)
var back = sub.length == end - from
for (i <- 0 until sub.length) {
back &&= sub(i) == v(i + from)
}
back
} catch {
case _:IndexOutOfBoundsException => from < 0
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"append to subseq" in {
- val prop = property { (v: PathVector[Int], from: Int, end: Int, n: Int) =>
+ skip("Disabling for now")
+
+ val prop = forAll { (v: PathVector[Int], from: Int, end: Int, n: Int) =>
try {
val sub = v.subseq(from, end)
val add = sub + n
var back = add.length == sub.length + 1
for (i <- 0 until sub.length) {
back &&= add(i) == sub(i)
}
back && add(sub.length) == n
} catch {
case _:IndexOutOfBoundsException => from < 0
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"map on subseq" in {
- val prop = property { (v: PathVector[Int], from: Int, end: Int, f: (Int)=>Int) =>
+ skip("Disabling for now")
+ val prop = forAll { (v: PathVector[Int], from: Int, end: Int, f: (Int)=>Int) =>
try {
val sub = v.subseq(from, end)
val mapped = sub map f
var back = mapped.length == sub.length
for (i <- 0 until sub.length) {
back &&= mapped(i) == f(sub(i))
}
back
} catch {
case _:IndexOutOfBoundsException => from < 0
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"implement zip" in {
- val prop = property { (first: PathVector[Int], second: PathVector[Double]) =>
+ val prop = forAll { (first: PathVector[Int], second: PathVector[Double]) =>
val zip = first zip second
var back = zip.length == Math.max(first.length, second.length)
for (i <- 0 until zip.length) {
var (left, right) = zip(i)
back &&= (left == first(i) && right == second(i))
}
back
}
prop must pass
}
"implement zipWithIndex" in {
- val prop = property { vec: PathVector[Int] =>
+ val prop = forAll { vec: PathVector[Int] =>
val zip = vec.zipWithIndex
var back = zip.length == vec.length
for (i <- 0 until zip.length) {
val (elem, index) = zip(i)
back &&= (index == i && elem == vec(i))
}
back
}
prop must pass
}
"implement equals" in {
- val prop = property { list: List[Int] =>
+ val prop = forAll { list: List[Int] =>
val vecA = list.foldLeft(new PathVector[Int]) { _ + _ }
val vecB = list.foldLeft(new PathVector[Int]) { _ + _ }
vecA == vecB
}
prop must pass
}
}
}
diff --git a/src/spec/scala/VectorSpecs.scala b/src/spec/scala/VectorSpecs.scala
index eda5c82..1857a5a 100644
--- a/src/spec/scala/VectorSpecs.scala
+++ b/src/spec/scala/VectorSpecs.scala
@@ -1,426 +1,426 @@
import org.specs._
import org.scalacheck._
import com.codecommit.collection.{EmptyVector, Vector}
object VectorSpecs extends Specification with ScalaCheck {
import Prop._
val vector = Vector[Int]()
implicit def arbitraryVector[A](implicit arb: Arbitrary[A]): Arbitrary[Vector[A]] = {
Arbitrary(for {
data <- Arbitrary.arbitrary[List[A]]
} yield data.foldLeft(Vector[A]()) { _ + _ })
}
"vector" should {
"store a single element" in {
- val prop = property { (i: Int, e: Int) =>
+ val prop = forAll { (i: Int, e: Int) =>
i >= 0 ==> ((vector(0) = e)(0) == e)
}
prop must pass
}
"implement length" in {
- val prop = property { (list: List[Int]) =>
+ val prop = forAll { (list: List[Int]) =>
val vec = list.foldLeft(Vector[Int]()) { _ + _ }
vec.length == list.length
}
prop must pass
}
"replace single element" in {
- val prop = property { (vec: Vector[Int], i: Int) =>
+ val prop = forAll { (vec: Vector[Int], i: Int) =>
((0 to vec.length) contains i) ==> {
val newVector = (vec(i) = "test")(i) = "newTest"
newVector(i) == "newTest"
}
}
prop must pass
}
"fail on apply out-of-bounds" in {
- val prop = property { (vec: Vector[Int], i: Int) =>
+ val prop = forAll { (vec: Vector[Int], i: Int) =>
!((0 until vec.length) contains i) ==> {
try {
vec(i)
false
} catch {
case _: IndexOutOfBoundsException => true
}
}
}
prop must pass
}
"fail on update out-of-bounds" in {
- val prop = property { (vec: Vector[Int], i: Int) =>
+ val prop = forAll { (vec: Vector[Int], i: Int) =>
!((0 to vec.length) contains i) ==> {
try {
vec(i) = 42
false
} catch {
case _: IndexOutOfBoundsException => true
}
}
}
prop must pass
}
"pop elements" in {
- val prop = property { vec: Vector[Int] =>
+ val prop = forAll { vec: Vector[Int] =>
vec.length > 0 ==> {
val popped = vec.pop
var back = popped.length == vec.length - 1
for (i <- 0 until popped.length) {
back &&= popped(i) == vec(i)
}
back
}
}
prop must pass(set(maxSize -> 3000, minTestsOk -> 1000))
}
"fail on pop empty vector" in {
val caughtExcept = try {
EmptyVector.pop
false
} catch {
case _: IllegalStateException => true
}
caughtExcept mustEqual true
}
"store multiple elements in order" in {
- val prop = property { list: List[Int] =>
+ val prop = forAll { list: List[Int] =>
val newVector = list.foldLeft(vector) { _ + _ }
val res = for (i <- 0 until list.length) yield newVector(i) == list(i)
res forall { _ == true }
}
prop must pass
}
"store lots of elements" in {
val LENGTH = 100000
val vector = (0 until LENGTH).foldLeft(Vector[Int]()) { _ + _ }
vector.length mustEqual LENGTH
for (i <- 0 until LENGTH) {
vector(i) mustEqual i
}
}
"implement filter" in {
- val prop = property { (vec: Vector[Int], f: (Int)=>Boolean) =>
+ val prop = forAll { (vec: Vector[Int], f: (Int)=>Boolean) =>
val filtered = vec filter f
var back = filtered forall f
for (e <- vec) {
if (f(e)) {
back &&= filtered.contains(e)
}
}
back
}
prop must pass
}
"implement foldLeft" in {
- val prop = property { list: List[Int] =>
+ val prop = forAll { list: List[Int] =>
val vec = list.foldLeft(Vector[Int]()) { _ + _ }
vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ }
}
prop must pass
}
"implement forall" in {
- val prop = property { (vec: Vector[Int], f: (Int)=>Boolean) =>
+ val prop = forAll { (vec: Vector[Int], f: (Int)=>Boolean) =>
val bool = vec forall f
var back = true
for (e <- vec) {
back &&= f(e)
}
(back && bool) || (!back && !bool)
}
prop must pass
}
"implement flatMap" in {
- val prop = property { (vec: Vector[Int], f: (Int)=>Vector[Int]) =>
+ val prop = forAll { (vec: Vector[Int], f: (Int)=>Vector[Int]) =>
val mapped = vec flatMap f
var back = true
var i = 0
var n = 0
while (i < vec.length) {
val res = f(vec(i))
var inner = 0
while (inner < res.length) {
back &&= mapped(n) == res(inner)
inner += 1
n += 1
}
i += 1
}
back
}
prop must pass
}
"implement map" in {
- val prop = property { (vec: Vector[Int], f: (Int)=>Int) =>
+ val prop = forAll { (vec: Vector[Int], f: (Int)=>Int) =>
val mapped = vec map f
var back = vec.length == mapped.length
for (i <- 0 until vec.length) {
back &&= mapped(i) == f(vec(i))
}
back
}
prop must pass
}
"implement reverse" in {
- val prop = property { v: Vector[Int] =>
+ val prop = forAll { v: Vector[Int] =>
val reversed = v.reverse
var back = v.length == reversed.length
for (i <- 0 until v.length) {
back &&= reversed(i) == v(v.length - i - 1)
}
back
}
prop must pass
}
"append to reverse" in {
- val prop = property { (v: Vector[Int], n: Int) =>
+ val prop = forAll { (v: Vector[Int], n: Int) =>
val rev = v.reverse
val add = rev + n
var back = add.length == rev.length + 1
for (i <- 0 until rev.length) {
back &&= add(i) == rev(i)
}
back && add(rev.length) == n
}
prop must pass
}
"map on reverse" in {
- val prop = property { (v: Vector[Int], f: (Int)=>Int) =>
+ val prop = forAll { (v: Vector[Int], f: (Int)=>Int) =>
val rev = v.reverse
val mapped = rev map f
var back = mapped.length == rev.length
for (i <- 0 until rev.length) {
back &&= mapped(i) == f(rev(i))
}
back
}
prop must pass
}
"implement subseq" in {
- val prop = property { (v: Vector[Int], from: Int, end: Int) =>
+ val prop = forAll { (v: Vector[Int], from: Int, end: Int) =>
try {
val sub = v.subseq(from, end)
var back = sub.length == end - from
for (i <- 0 until sub.length) {
back &&= sub(i) == v(i + from)
}
back
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"append to subseq" in {
- val prop = property { (v: Vector[Int], from: Int, end: Int, n: Int) =>
+ val prop = forAll { (v: Vector[Int], from: Int, end: Int, n: Int) =>
try {
val sub = v.subseq(from, end)
val add = sub + n
var back = add.length == sub.length + 1
for (i <- 0 until sub.length) {
back &&= add(i) == sub(i)
}
back && add(sub.length) == n
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"update subseq" in {
- val prop = property { (v: Vector[Int], from: Int, end: Int, mi: Int) =>
+ val prop = forAll { (v: Vector[Int], from: Int, end: Int, mi: Int) =>
try {
val sub = v.subseq(from, end)
val add = sub(mi) = 42
var back = add.length == sub.length + (if (mi == sub.length) 1 else 0)
for (i <- 0 until sub.length; if i != mi) {
back &&= add(i) == sub(i)
}
back && add(mi) == 42
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length || !(0 to (end - from) contains mi)
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"map on subseq" in {
- val prop = property { (v: Vector[Int], from: Int, end: Int, f: (Int)=>Int) =>
+ val prop = forAll { (v: Vector[Int], from: Int, end: Int, f: (Int)=>Int) =>
try {
val sub = v.subseq(from, end)
val mapped = sub map f
var back = mapped.length == sub.length
for (i <- 0 until sub.length) {
back &&= mapped(i) == f(sub(i))
}
back
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"implement zip" in {
- val prop = property { (first: Vector[Int], second: Vector[Double]) =>
+ val prop = forAll { (first: Vector[Int], second: Vector[Double]) =>
val zip = first zip second
var back = zip.length == Math.min(first.length, second.length)
for (i <- 0 until zip.length) {
var (left, right) = zip(i)
back &&= (left == first(i) && right == second(i))
}
back
}
prop must pass
}
"implement zipWithIndex" in {
- val prop = property { vec: Vector[Int] =>
+ val prop = forAll { vec: Vector[Int] =>
val zip = vec.zipWithIndex
var back = zip.length == vec.length
for (i <- 0 until zip.length) {
val (elem, index) = zip(i)
back &&= (index == i && elem == vec(i))
}
back
}
prop must pass
}
"implement equals" in {
{
- val prop = property { list: List[Int] =>
+ val prop = forAll { list: List[Int] =>
val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
vecA == vecB
}
prop must pass
}
{
- val prop = property { (vecA: Vector[Int], vecB: Vector[Int]) =>
+ val prop = forAll { (vecA: Vector[Int], vecB: Vector[Int]) =>
vecA.length != vecB.length ==> (vecA != vecB)
}
prop must pass
}
{
- val prop = property { (listA: List[Int], listB: List[Int]) =>
+ val prop = forAll { (listA: List[Int], listB: List[Int]) =>
val vecA = listA.foldLeft(Vector[Int]()) { _ + _ }
val vecB = listB.foldLeft(Vector[Int]()) { _ + _ }
listA != listB ==> (vecA != vecB)
}
prop must pass
}
{
- val prop = property { (vec: Vector[Int], data: Int) => vec != data }
+ val prop = forAll { (vec: Vector[Int], data: Int) => vec != data }
prop must pass
}
}
"implement hashCode" in {
- val prop = property { list: List[Int] =>
+ val prop = forAll { list: List[Int] =>
val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
vecA.hashCode == vecB.hashCode
}
prop must pass
}
"implement extractor" in {
val vec1 = Vector(1, 2, 3)
vec1 must beLike {
case Vector(a, b, c) => (a, b, c) == (1, 2, 3)
}
val vec2 = Vector("daniel", "chris", "joseph")
vec2 must beLike {
case Vector(a, b, c) => (a, b, c) == ("daniel", "chris", "joseph")
}
}
}
}
|
djspiewak/scala-collections
|
883d4606378fa879ed83120bdde7fa01d608f094
|
Removed cobertura from default build
|
diff --git a/buildfile b/buildfile
index ed5616b..9d64a91 100644
--- a/buildfile
+++ b/buildfile
@@ -1,15 +1,15 @@
require 'buildr/scala'
-require 'buildr/java/cobertura'
+#require 'buildr/java/cobertura'
require 'buildr/groovy'
-repositories.remote << 'http://www.ibiblio.org/maven2'
+repositories.remote << 'http://repo1.maven.org/maven2/'
desc 'A few collections classes for fun and profit'
define 'collection' do
project.version = '0.1.0'
project.group = 'com.codecommit'
test.using :specs
package :jar
end
|
djspiewak/scala-collections
|
f60315249528fd84fc3f1e365636def2210a684b
|
Added .gitignore
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..27a7dfc
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+reports/
+target/
|
djspiewak/scala-collections
|
0607d9aa02945761af83140ddf650463696ebe7c
|
No need to explitly add the scala-tools repo
|
diff --git a/buildfile b/buildfile
index 4b703a2..ed5616b 100644
--- a/buildfile
+++ b/buildfile
@@ -1,16 +1,15 @@
require 'buildr/scala'
require 'buildr/java/cobertura'
require 'buildr/groovy'
repositories.remote << 'http://www.ibiblio.org/maven2'
-repositories.remote << 'http://scala-tools.org/repo-releases'
desc 'A few collections classes for fun and profit'
define 'collection' do
project.version = '0.1.0'
project.group = 'com.codecommit'
test.using :specs
package :jar
end
|
djspiewak/scala-collections
|
692c4d8613ad9dd600b29ccbf9fb88813113053e
|
New cobertura support in Buildr
|
diff --git a/buildfile b/buildfile
index fd3e4db..4b703a2 100644
--- a/buildfile
+++ b/buildfile
@@ -1,15 +1,16 @@
require 'buildr/scala'
-#require 'buildr/cobertura'
+require 'buildr/java/cobertura'
+require 'buildr/groovy'
repositories.remote << 'http://www.ibiblio.org/maven2'
repositories.remote << 'http://scala-tools.org/repo-releases'
desc 'A few collections classes for fun and profit'
define 'collection' do
project.version = '0.1.0'
project.group = 'com.codecommit'
-
+
test.using :specs
package :jar
end
|
djspiewak/scala-collections
|
d918818053d7a31ed7e7036bd69396a42ec58eb0
|
Whitespace fun
|
diff --git a/buildfile b/buildfile
index 92e7f07..fd3e4db 100644
--- a/buildfile
+++ b/buildfile
@@ -1,15 +1,15 @@
require 'buildr/scala'
#require 'buildr/cobertura'
repositories.remote << 'http://www.ibiblio.org/maven2'
repositories.remote << 'http://scala-tools.org/repo-releases'
desc 'A few collections classes for fun and profit'
define 'collection' do
project.version = '0.1.0'
project.group = 'com.codecommit'
-
+
test.using :specs
package :jar
end
|
djspiewak/scala-collections
|
d5a7e13f238cb5526afbdce6371ff444676b7704
|
Fixed mistake in subseq spec
|
diff --git a/src/spec/scala/VectorSpecs.scala b/src/spec/scala/VectorSpecs.scala
index 1a97c79..eda5c82 100644
--- a/src/spec/scala/VectorSpecs.scala
+++ b/src/spec/scala/VectorSpecs.scala
@@ -1,426 +1,426 @@
import org.specs._
import org.scalacheck._
import com.codecommit.collection.{EmptyVector, Vector}
object VectorSpecs extends Specification with ScalaCheck {
import Prop._
val vector = Vector[Int]()
implicit def arbitraryVector[A](implicit arb: Arbitrary[A]): Arbitrary[Vector[A]] = {
Arbitrary(for {
data <- Arbitrary.arbitrary[List[A]]
} yield data.foldLeft(Vector[A]()) { _ + _ })
}
"vector" should {
"store a single element" in {
val prop = property { (i: Int, e: Int) =>
i >= 0 ==> ((vector(0) = e)(0) == e)
}
prop must pass
}
"implement length" in {
val prop = property { (list: List[Int]) =>
val vec = list.foldLeft(Vector[Int]()) { _ + _ }
vec.length == list.length
}
prop must pass
}
"replace single element" in {
val prop = property { (vec: Vector[Int], i: Int) =>
((0 to vec.length) contains i) ==> {
val newVector = (vec(i) = "test")(i) = "newTest"
newVector(i) == "newTest"
}
}
prop must pass
}
"fail on apply out-of-bounds" in {
val prop = property { (vec: Vector[Int], i: Int) =>
!((0 until vec.length) contains i) ==> {
try {
vec(i)
false
} catch {
case _: IndexOutOfBoundsException => true
}
}
}
prop must pass
}
"fail on update out-of-bounds" in {
val prop = property { (vec: Vector[Int], i: Int) =>
!((0 to vec.length) contains i) ==> {
try {
vec(i) = 42
false
} catch {
case _: IndexOutOfBoundsException => true
}
}
}
prop must pass
}
"pop elements" in {
val prop = property { vec: Vector[Int] =>
vec.length > 0 ==> {
val popped = vec.pop
var back = popped.length == vec.length - 1
for (i <- 0 until popped.length) {
back &&= popped(i) == vec(i)
}
back
}
}
prop must pass(set(maxSize -> 3000, minTestsOk -> 1000))
}
"fail on pop empty vector" in {
val caughtExcept = try {
EmptyVector.pop
false
} catch {
case _: IllegalStateException => true
}
caughtExcept mustEqual true
}
"store multiple elements in order" in {
val prop = property { list: List[Int] =>
val newVector = list.foldLeft(vector) { _ + _ }
val res = for (i <- 0 until list.length) yield newVector(i) == list(i)
res forall { _ == true }
}
prop must pass
}
"store lots of elements" in {
val LENGTH = 100000
val vector = (0 until LENGTH).foldLeft(Vector[Int]()) { _ + _ }
vector.length mustEqual LENGTH
for (i <- 0 until LENGTH) {
vector(i) mustEqual i
}
}
"implement filter" in {
val prop = property { (vec: Vector[Int], f: (Int)=>Boolean) =>
val filtered = vec filter f
var back = filtered forall f
for (e <- vec) {
if (f(e)) {
back &&= filtered.contains(e)
}
}
back
}
prop must pass
}
"implement foldLeft" in {
val prop = property { list: List[Int] =>
val vec = list.foldLeft(Vector[Int]()) { _ + _ }
vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ }
}
prop must pass
}
"implement forall" in {
val prop = property { (vec: Vector[Int], f: (Int)=>Boolean) =>
val bool = vec forall f
var back = true
for (e <- vec) {
back &&= f(e)
}
(back && bool) || (!back && !bool)
}
prop must pass
}
"implement flatMap" in {
val prop = property { (vec: Vector[Int], f: (Int)=>Vector[Int]) =>
val mapped = vec flatMap f
var back = true
var i = 0
var n = 0
while (i < vec.length) {
val res = f(vec(i))
var inner = 0
while (inner < res.length) {
back &&= mapped(n) == res(inner)
inner += 1
n += 1
}
i += 1
}
back
}
prop must pass
}
"implement map" in {
val prop = property { (vec: Vector[Int], f: (Int)=>Int) =>
val mapped = vec map f
var back = vec.length == mapped.length
for (i <- 0 until vec.length) {
back &&= mapped(i) == f(vec(i))
}
back
}
prop must pass
}
"implement reverse" in {
val prop = property { v: Vector[Int] =>
val reversed = v.reverse
var back = v.length == reversed.length
for (i <- 0 until v.length) {
back &&= reversed(i) == v(v.length - i - 1)
}
back
}
prop must pass
}
"append to reverse" in {
val prop = property { (v: Vector[Int], n: Int) =>
val rev = v.reverse
val add = rev + n
var back = add.length == rev.length + 1
for (i <- 0 until rev.length) {
back &&= add(i) == rev(i)
}
back && add(rev.length) == n
}
prop must pass
}
"map on reverse" in {
val prop = property { (v: Vector[Int], f: (Int)=>Int) =>
val rev = v.reverse
val mapped = rev map f
var back = mapped.length == rev.length
for (i <- 0 until rev.length) {
back &&= mapped(i) == f(rev(i))
}
back
}
prop must pass
}
"implement subseq" in {
val prop = property { (v: Vector[Int], from: Int, end: Int) =>
try {
val sub = v.subseq(from, end)
var back = sub.length == end - from
for (i <- 0 until sub.length) {
back &&= sub(i) == v(i + from)
}
back
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"append to subseq" in {
val prop = property { (v: Vector[Int], from: Int, end: Int, n: Int) =>
try {
val sub = v.subseq(from, end)
val add = sub + n
var back = add.length == sub.length + 1
for (i <- 0 until sub.length) {
back &&= add(i) == sub(i)
}
back && add(sub.length) == n
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"update subseq" in {
val prop = property { (v: Vector[Int], from: Int, end: Int, mi: Int) =>
try {
val sub = v.subseq(from, end)
val add = sub(mi) = 42
- var back = add.length == (if (mi == add.length) sub.length + 1 else sub.length)
+ var back = add.length == sub.length + (if (mi == sub.length) 1 else 0)
for (i <- 0 until sub.length; if i != mi) {
back &&= add(i) == sub(i)
}
back && add(mi) == 42
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length || !(0 to (end - from) contains mi)
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"map on subseq" in {
val prop = property { (v: Vector[Int], from: Int, end: Int, f: (Int)=>Int) =>
try {
val sub = v.subseq(from, end)
val mapped = sub map f
var back = mapped.length == sub.length
for (i <- 0 until sub.length) {
back &&= mapped(i) == f(sub(i))
}
back
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"implement zip" in {
val prop = property { (first: Vector[Int], second: Vector[Double]) =>
val zip = first zip second
var back = zip.length == Math.min(first.length, second.length)
for (i <- 0 until zip.length) {
var (left, right) = zip(i)
back &&= (left == first(i) && right == second(i))
}
back
}
prop must pass
}
"implement zipWithIndex" in {
val prop = property { vec: Vector[Int] =>
val zip = vec.zipWithIndex
var back = zip.length == vec.length
for (i <- 0 until zip.length) {
val (elem, index) = zip(i)
back &&= (index == i && elem == vec(i))
}
back
}
prop must pass
}
"implement equals" in {
{
val prop = property { list: List[Int] =>
val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
vecA == vecB
}
prop must pass
}
{
val prop = property { (vecA: Vector[Int], vecB: Vector[Int]) =>
vecA.length != vecB.length ==> (vecA != vecB)
}
prop must pass
}
{
val prop = property { (listA: List[Int], listB: List[Int]) =>
val vecA = listA.foldLeft(Vector[Int]()) { _ + _ }
val vecB = listB.foldLeft(Vector[Int]()) { _ + _ }
listA != listB ==> (vecA != vecB)
}
prop must pass
}
{
val prop = property { (vec: Vector[Int], data: Int) => vec != data }
prop must pass
}
}
"implement hashCode" in {
val prop = property { list: List[Int] =>
val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
vecA.hashCode == vecB.hashCode
}
prop must pass
}
"implement extractor" in {
val vec1 = Vector(1, 2, 3)
vec1 must beLike {
case Vector(a, b, c) => (a, b, c) == (1, 2, 3)
}
val vec2 = Vector("daniel", "chris", "joseph")
vec2 must beLike {
case Vector(a, b, c) => (a, b, c) == ("daniel", "chris", "joseph")
}
}
}
}
|
djspiewak/scala-collections
|
ab066de3669952e3d5d486b3e3f432028c1933c1
|
Use :specs in special fork of Buildr
|
diff --git a/build.yaml b/build.yaml
deleted file mode 100644
index 6e00ca9..0000000
--- a/build.yaml
+++ /dev/null
@@ -1,2 +0,0 @@
-scala.check: 1.5
-scala.specs: 1.4.1
diff --git a/buildfile b/buildfile
index 2a9c92a..92e7f07 100644
--- a/buildfile
+++ b/buildfile
@@ -1,15 +1,15 @@
require 'buildr/scala'
#require 'buildr/cobertura'
repositories.remote << 'http://www.ibiblio.org/maven2'
repositories.remote << 'http://scala-tools.org/repo-releases'
desc 'A few collections classes for fun and profit'
define 'collection' do
project.version = '0.1.0'
project.group = 'com.codecommit'
+
+ test.using :specs
- test.using :specs=>true
-
package :jar
end
diff --git a/src/spec/scala/BloomSpecs.scala b/src/spec/scala/BloomSpecs.scala
new file mode 100644
index 0000000..f4a2d32
--- /dev/null
+++ b/src/spec/scala/BloomSpecs.scala
@@ -0,0 +1,134 @@
+import org.specs._
+import org.scalacheck._
+
+import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
+import com.codecommit.collection.BloomSet
+
+object BloomSpecs extends Specification with ScalaCheck {
+ import Prop._
+
+ "bloom set" should {
+ "store single element once" in {
+ (BloomSet[String]() + "test") contains "test" mustEqual true
+ }
+
+ "store single element n times" in {
+ val prop = property { ls: List[String] =>
+ val set = ls.foldLeft(BloomSet[String]()) { _ + _ }
+
+ ls.foldLeft(true) { _ && set(_) }
+ }
+
+ prop must pass
+ }
+
+ "store duplicate elements n times" in {
+ val prop = property { ls: List[String] =>
+ var set = ls.foldLeft(BloomSet[String]()) { _ + _ }
+ set = ls.foldLeft(set) { _ + _ }
+
+ ls.foldLeft(true) { _ && set(_) }
+ }
+
+ prop must pass
+ }
+
+ "handle ++ Iterable" in {
+ val prop = property { (first: List[String], last: List[String]) =>
+ var set = first.foldLeft(BloomSet[String]()) { _ + _ }
+ set ++= last
+
+ first.foldLeft(true) { _ && set(_) } && last.foldLeft(true) { _ && set(_) }
+ }
+
+ prop must pass
+ }
+
+ "handle ++ BloomSet" in {
+ val prop = property { (first: List[String], last: List[String]) =>
+ var set = first.foldLeft(BloomSet[String]()) { _ + _ }
+ set ++= last.foldLeft(BloomSet[String]()) { _ + _ }
+
+ first.foldLeft(true) { _ && set(_) } && last.foldLeft(true) { _ && set(_) }
+ }
+
+ prop must pass
+ }
+
+ "be immutable" in {
+ val prop = property { (ls: List[String], item: String) =>
+ val set = ls.foldLeft(new BloomSet[String](10000, 5)) { _ + _ }
+
+ // might fail, but it is doubtful
+ (set.accuracy > 0.999 && !ls.contains(item)) ==> {
+ val newSet = set + item
+
+ ls.foldLeft(true) { _ && set(_) } &&
+ !set.contains(item) &&
+ ls.foldLeft(true) { _ && newSet(_) } &&
+ newSet.contains(item)
+ }
+ }
+
+ prop must pass(set(minTestsOk -> 100, maxDiscarded -> 5000, minSize -> 0, maxSize -> 100))
+ }
+
+ "construct using companion" in {
+ val set = BloomSet("daniel", "chris", "joseph", "renee")
+
+ set contains "daniel" mustEqual true
+ set contains "chris" mustEqual true
+ set contains "joseph" mustEqual true
+ set contains "renee" mustEqual true
+ }
+
+ "implement equivalency" in {
+ val prop = property { nums: List[Int] =>
+ val set1 = nums.foldLeft(BloomSet[Int]()) { _ + _}
+ val set2 = nums.foldLeft(BloomSet[Int]()) { _ + _}
+
+ set1 == set2
+ }
+
+ prop must pass
+ }
+
+ "implement hashing" in {
+ val prop = property { nums: List[Int] =>
+ val set1 = nums.foldLeft(BloomSet[Int]()) { _ + _}
+ val set2 = nums.foldLeft(BloomSet[Int]()) { _ + _}
+
+ set1.hashCode == set2.hashCode
+ }
+
+ prop must pass
+ }
+
+ "persist properly" in {
+ val prop = property { (width: Int, k: Int, ls: List[Int]) => (width > 0 && k > 0) ==> {
+ val set = ls.foldLeft(new BloomSet[Int](width, k)) { _ + _ }
+ val os = new ByteArrayOutputStream
+
+ set.store(os)
+ val is = new ByteArrayInputStream(os.toByteArray)
+
+ val newSet = BloomSet.load[Int](is)
+
+ ls.foldLeft(true) { _ && newSet(_) } &&
+ newSet.width == set.width &&
+ newSet.k == set.k &&
+ newSet.size == set.size
+ }
+ }
+
+ prop must pass
+ }
+
+ "calculate accuracy" in {
+ BloomSet[Int]().accuracy mustEqual 1d
+
+ val set = (0 until 1000).foldLeft(BloomSet[Int]()) { _ + _ }
+ set.accuracy must beCloseTo(0d, 0.0000001d)
+ }
+ }
+}
diff --git a/src/spec/scala/HashTrieSpecs.scala b/src/spec/scala/HashTrieSpecs.scala
new file mode 100644
index 0000000..cb88a02
--- /dev/null
+++ b/src/spec/scala/HashTrieSpecs.scala
@@ -0,0 +1,101 @@
+import org.specs._
+import org.scalacheck._
+
+import com.codecommit.collection.HashTrie
+
+object HashTrieSpecs extends Specification with ScalaCheck {
+ import Prop._
+
+ "it" should {
+ "store ints" in {
+ val prop = property { src: List[Int] =>
+ val map = src.foldLeft(new HashTrie[Int, Int]) { (m, v) => m(v) = -v }
+ src forall { v => map(v) == -v }
+ }
+
+ prop must pass(set(maxSize -> 5000, minTestsOk -> 2000))
+ }
+
+ "store strings" in {
+ val prop = property { src: List[String] =>
+ val map = src.foldLeft(new HashTrie[String, Int]) { (m, v) => m(v) = v.length }
+ src forall { v => map(v) == v.length }
+ }
+
+ prop must pass
+ }
+
+ "preserve values across changes" in {
+ val prop = property { (map: HashTrie[String, String], ls: List[String], f: (String)=>String) =>
+ val filtered = ls filter { !map.contains(_) }
+
+ filtered.length > 0 ==> {
+ val newMap = filtered.foldLeft(map) { (m, k) => m(k) = f(k) }
+
+ (map forall { case (k, v) => newMap(k) == v }) && (filtered forall { v => newMap(v) == f(v) })
+ }
+ }
+
+ prop must pass
+ }
+
+ "calculate size" in {
+ val prop = property { (ls: Set[Int], f: (Int)=>Int) =>
+ val map = ls.foldLeft(new HashTrie[Int, Int]) { (m, v) => m(v) = f(v) }
+ map.size == ls.size
+ }
+
+ prop must pass
+ }
+
+ "remove ints" in {
+ val prop = property { map: HashTrie[Int, String] =>
+ map.size > 0 ==> {
+ val (rm, _) = map.elements.next // insufficient
+ val newMap = map - rm
+
+ !newMap.contains(rm) &&
+ (newMap forall { case (k, v) => map(k) == v }) &&
+ newMap.size == map.size - 1
+ }
+ }
+
+ prop must pass
+ }
+
+ "remove strings" in {
+ val prop = property { map: HashTrie[String, String] =>
+ map.size > 0 ==> {
+ val (rm, _) = map.elements.next
+ val newMap = map - rm
+
+ !newMap.contains(rm) &&
+ (newMap forall { case (k, v) => map(k) == v }) &&
+ newMap.size == map.size - 1
+ }
+ }
+
+ prop must pass
+ }
+
+ "define empty" in {
+ val prop = property { map: HashTrie[String, String] =>
+ map.empty.size == 0
+ }
+
+ prop must pass
+ }
+ }
+
+ implicit def arbHashTrie[K](implicit ak: Arbitrary[List[K]]): Arbitrary[HashTrie[K, String]] = {
+ Arbitrary(for {
+ keys <- ak.arbitrary
+ } yield keys.foldLeft(new HashTrie[K, String]) { (m, k) => m(k) = k.toString })
+ }
+
+ implicit def arbSet[A](implicit arb: Arbitrary[List[A]]): Arbitrary[Set[A]] = {
+ Arbitrary(for {
+ ls <- arb.arbitrary
+ } yield ls.foldLeft(Set[A]()) { _ + _ })
+ }
+}
diff --git a/src/spec/scala/PathVectorSpecs.scala b/src/spec/scala/PathVectorSpecs.scala
new file mode 100644
index 0000000..390405a
--- /dev/null
+++ b/src/spec/scala/PathVectorSpecs.scala
@@ -0,0 +1,299 @@
+import org.specs._
+import org.scalacheck._
+
+import com.codecommit.collection.PathVector
+
+object PathVectorSpecs extends Specification with ScalaCheck {
+ import Prop._
+
+ val vector = PathVector[Int]()
+
+ implicit def arbitraryPathVector[A](implicit arb: Arbitrary[A]): Arbitrary[PathVector[A]] = {
+ Arbitrary(for {
+ data <- Arbitrary.arbitrary[List[A]]
+ indexes <- Gen.containerOfN[List, Int](data.length, Gen.choose(0, Math.MAX_INT - 1))
+ } yield {
+ var vec = new PathVector[A]
+
+ var i = 0
+ for (d <- data) {
+ vec(indexes(i)) = d
+ i += 1
+ }
+
+ vec
+ })
+ }
+
+
+ "path vector" should {
+ "have infinite bounds" in {
+ vector.length mustEqual 0 // finite length
+
+ val prop = property { i: Int => // infinite bounds
+ i >= 0 ==> (vector(i) == 0)
+ }
+
+ prop must pass
+ }
+
+ "store a single element" in {
+ val prop = property { (i: Int, e: Int) =>
+ i >= 0 ==> ((vector(0) = e)(0) == e)
+ }
+
+ prop must pass
+ }
+
+ "replace single element" in {
+ val prop = property { (vec: PathVector[String], i: Int) =>
+ i >= 0 ==> {
+ val newPathVector = (vec(i) = "test")(i) = "newTest"
+ newPathVector(i) == "newTest"
+ }
+ }
+
+ prop must pass
+ }
+
+ "store multiple elements in order" in {
+ val prop = property { list: List[Int] =>
+ val newPathVector = list.foldLeft(vector) { _ + _ }
+ val res = for (i <- 0 until list.length) yield newPathVector(i) == list(i)
+
+ res forall { _ == true }
+ }
+
+ prop must pass
+ }
+
+ "store lots of elements" in {
+ val LENGTH = 100000
+ val vector = (0 until LENGTH).foldLeft(PathVector[Int]()) { _ + _ }
+
+ vector.length mustEqual LENGTH
+ for (i <- 0 until LENGTH) {
+ vector(i) mustEqual i
+ }
+ }
+
+ "store at arbitrary points" in {
+ val vector = PathVector(1, 2, 3, 4, 5)
+ val prop = property { others: List[(Int, Int)] =>
+ val (newPathVector, resMap) = others.foldLeft(vector, Map[Int, Int]()) { (inTuple, tuple) =>
+ val (i, value) = tuple
+ val (vec, map) = inTuple
+
+ if (i < 0) (vec, map) else (vec(i) = value, map + (i -> value))
+ }
+
+ val res = for {
+ (i, _) <- others
+ } yield if (i < 0) true else newPathVector(i) == resMap(i)
+
+ res forall { _ == true }
+ }
+
+ prop must pass
+ }
+
+ "implement filter" in {
+ val prop = property { (vec: PathVector[Int], f: (Int)=>Boolean) =>
+ val filtered = vec filter f
+
+ var back = filtered forall f
+ for (e <- vec) {
+ if (f(e)) {
+ back &&= filtered.contains(e)
+ }
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement foldLeft" in {
+ val prop = property { list: List[Int] =>
+ val vec = list.foldLeft(new PathVector[Int]) { _ + _ }
+ vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ }
+ }
+
+ prop must pass
+ }
+
+ "implement forall" in {
+ val prop = property { (vec: PathVector[Int], f: (Int)=>Boolean) =>
+ val bool = vec forall f
+
+ var back = true
+ for (e <- vec) {
+ back &&= f(e)
+ }
+
+ (back && bool) || (!back && !bool)
+ }
+
+ prop must pass
+ }
+
+ "implement map" in {
+ val prop = property { (vec: PathVector[Int], f: (Int)=>Int) =>
+ val mapped = vec map f
+
+ var back = vec.length == mapped.length
+ for (i <- 0 until vec.length) {
+ back &&= mapped(i) == f(vec(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement reverse" in {
+ val prop = property { v: PathVector[Int] =>
+ val reversed = v.reverse
+
+ var back = v.length == reversed.length
+ for (i <- 0 until v.length) {
+ back &&= reversed(i) == v(v.length - i - 1)
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "append to reverse" in {
+ val prop = property { (v: PathVector[Int], n: Int) =>
+ val rev = v.reverse
+ val add = rev + n
+
+ var back = add.length == rev.length + 1
+ for (i <- 0 until rev.length) {
+ back &&= add(i) == rev(i)
+ }
+ back && add(rev.length) == n
+ }
+
+ prop must pass
+ }
+
+ "map on reverse" in {
+ val prop = property { (v: PathVector[Int], f: (Int)=>Int) =>
+ val rev = v.reverse
+ val mapped = rev map f
+
+ var back = mapped.length == rev.length
+ for (i <- 0 until rev.length) {
+ back &&= mapped(i) == f(rev(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement subseq" in {
+ val prop = property { (v: PathVector[Int], from: Int, end: Int) =>
+ try {
+ val sub = v.subseq(from, end)
+
+ var back = sub.length == end - from
+ for (i <- 0 until sub.length) {
+ back &&= sub(i) == v(i + from)
+ }
+ back
+ } catch {
+ case _:IndexOutOfBoundsException => from < 0
+ case _:IllegalArgumentException => end <= from
+ }
+ }
+
+ prop must pass
+ }
+
+ "append to subseq" in {
+ val prop = property { (v: PathVector[Int], from: Int, end: Int, n: Int) =>
+ try {
+ val sub = v.subseq(from, end)
+ val add = sub + n
+
+ var back = add.length == sub.length + 1
+ for (i <- 0 until sub.length) {
+ back &&= add(i) == sub(i)
+ }
+ back && add(sub.length) == n
+ } catch {
+ case _:IndexOutOfBoundsException => from < 0
+ case _:IllegalArgumentException => end <= from
+ }
+ }
+
+ prop must pass
+ }
+
+ "map on subseq" in {
+ val prop = property { (v: PathVector[Int], from: Int, end: Int, f: (Int)=>Int) =>
+ try {
+ val sub = v.subseq(from, end)
+ val mapped = sub map f
+
+ var back = mapped.length == sub.length
+ for (i <- 0 until sub.length) {
+ back &&= mapped(i) == f(sub(i))
+ }
+ back
+ } catch {
+ case _:IndexOutOfBoundsException => from < 0
+ case _:IllegalArgumentException => end <= from
+ }
+ }
+
+ prop must pass
+ }
+
+ "implement zip" in {
+ val prop = property { (first: PathVector[Int], second: PathVector[Double]) =>
+ val zip = first zip second
+
+ var back = zip.length == Math.max(first.length, second.length)
+ for (i <- 0 until zip.length) {
+ var (left, right) = zip(i)
+ back &&= (left == first(i) && right == second(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement zipWithIndex" in {
+ val prop = property { vec: PathVector[Int] =>
+ val zip = vec.zipWithIndex
+
+ var back = zip.length == vec.length
+ for (i <- 0 until zip.length) {
+ val (elem, index) = zip(i)
+
+ back &&= (index == i && elem == vec(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement equals" in {
+ val prop = property { list: List[Int] =>
+ val vecA = list.foldLeft(new PathVector[Int]) { _ + _ }
+ val vecB = list.foldLeft(new PathVector[Int]) { _ + _ }
+
+ vecA == vecB
+ }
+
+ prop must pass
+ }
+ }
+}
diff --git a/src/spec/scala/VectorSpecs.scala b/src/spec/scala/VectorSpecs.scala
new file mode 100644
index 0000000..1a97c79
--- /dev/null
+++ b/src/spec/scala/VectorSpecs.scala
@@ -0,0 +1,426 @@
+import org.specs._
+import org.scalacheck._
+
+import com.codecommit.collection.{EmptyVector, Vector}
+
+object VectorSpecs extends Specification with ScalaCheck {
+ import Prop._
+
+ val vector = Vector[Int]()
+
+ implicit def arbitraryVector[A](implicit arb: Arbitrary[A]): Arbitrary[Vector[A]] = {
+ Arbitrary(for {
+ data <- Arbitrary.arbitrary[List[A]]
+ } yield data.foldLeft(Vector[A]()) { _ + _ })
+ }
+
+ "vector" should {
+ "store a single element" in {
+ val prop = property { (i: Int, e: Int) =>
+ i >= 0 ==> ((vector(0) = e)(0) == e)
+ }
+
+ prop must pass
+ }
+
+ "implement length" in {
+ val prop = property { (list: List[Int]) =>
+ val vec = list.foldLeft(Vector[Int]()) { _ + _ }
+ vec.length == list.length
+ }
+
+ prop must pass
+ }
+
+ "replace single element" in {
+ val prop = property { (vec: Vector[Int], i: Int) =>
+ ((0 to vec.length) contains i) ==> {
+ val newVector = (vec(i) = "test")(i) = "newTest"
+ newVector(i) == "newTest"
+ }
+ }
+
+ prop must pass
+ }
+
+ "fail on apply out-of-bounds" in {
+ val prop = property { (vec: Vector[Int], i: Int) =>
+ !((0 until vec.length) contains i) ==> {
+ try {
+ vec(i)
+ false
+ } catch {
+ case _: IndexOutOfBoundsException => true
+ }
+ }
+ }
+
+ prop must pass
+ }
+
+ "fail on update out-of-bounds" in {
+ val prop = property { (vec: Vector[Int], i: Int) =>
+ !((0 to vec.length) contains i) ==> {
+ try {
+ vec(i) = 42
+ false
+ } catch {
+ case _: IndexOutOfBoundsException => true
+ }
+ }
+ }
+
+ prop must pass
+ }
+
+ "pop elements" in {
+ val prop = property { vec: Vector[Int] =>
+ vec.length > 0 ==> {
+ val popped = vec.pop
+ var back = popped.length == vec.length - 1
+
+ for (i <- 0 until popped.length) {
+ back &&= popped(i) == vec(i)
+ }
+
+ back
+ }
+ }
+
+ prop must pass(set(maxSize -> 3000, minTestsOk -> 1000))
+ }
+
+ "fail on pop empty vector" in {
+ val caughtExcept = try {
+ EmptyVector.pop
+ false
+ } catch {
+ case _: IllegalStateException => true
+ }
+
+ caughtExcept mustEqual true
+ }
+
+ "store multiple elements in order" in {
+ val prop = property { list: List[Int] =>
+ val newVector = list.foldLeft(vector) { _ + _ }
+ val res = for (i <- 0 until list.length) yield newVector(i) == list(i)
+
+ res forall { _ == true }
+ }
+
+ prop must pass
+ }
+
+ "store lots of elements" in {
+ val LENGTH = 100000
+ val vector = (0 until LENGTH).foldLeft(Vector[Int]()) { _ + _ }
+
+ vector.length mustEqual LENGTH
+ for (i <- 0 until LENGTH) {
+ vector(i) mustEqual i
+ }
+ }
+
+ "implement filter" in {
+ val prop = property { (vec: Vector[Int], f: (Int)=>Boolean) =>
+ val filtered = vec filter f
+
+ var back = filtered forall f
+ for (e <- vec) {
+ if (f(e)) {
+ back &&= filtered.contains(e)
+ }
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement foldLeft" in {
+ val prop = property { list: List[Int] =>
+ val vec = list.foldLeft(Vector[Int]()) { _ + _ }
+ vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ }
+ }
+
+ prop must pass
+ }
+
+ "implement forall" in {
+ val prop = property { (vec: Vector[Int], f: (Int)=>Boolean) =>
+ val bool = vec forall f
+
+ var back = true
+ for (e <- vec) {
+ back &&= f(e)
+ }
+
+ (back && bool) || (!back && !bool)
+ }
+
+ prop must pass
+ }
+
+ "implement flatMap" in {
+ val prop = property { (vec: Vector[Int], f: (Int)=>Vector[Int]) =>
+ val mapped = vec flatMap f
+
+ var back = true
+
+ var i = 0
+ var n = 0
+
+ while (i < vec.length) {
+ val res = f(vec(i))
+
+ var inner = 0
+ while (inner < res.length) {
+ back &&= mapped(n) == res(inner)
+
+ inner += 1
+ n += 1
+ }
+
+ i += 1
+ }
+
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement map" in {
+ val prop = property { (vec: Vector[Int], f: (Int)=>Int) =>
+ val mapped = vec map f
+
+ var back = vec.length == mapped.length
+ for (i <- 0 until vec.length) {
+ back &&= mapped(i) == f(vec(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement reverse" in {
+ val prop = property { v: Vector[Int] =>
+ val reversed = v.reverse
+
+ var back = v.length == reversed.length
+ for (i <- 0 until v.length) {
+ back &&= reversed(i) == v(v.length - i - 1)
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "append to reverse" in {
+ val prop = property { (v: Vector[Int], n: Int) =>
+ val rev = v.reverse
+ val add = rev + n
+
+ var back = add.length == rev.length + 1
+ for (i <- 0 until rev.length) {
+ back &&= add(i) == rev(i)
+ }
+ back && add(rev.length) == n
+ }
+
+ prop must pass
+ }
+
+ "map on reverse" in {
+ val prop = property { (v: Vector[Int], f: (Int)=>Int) =>
+ val rev = v.reverse
+ val mapped = rev map f
+
+ var back = mapped.length == rev.length
+ for (i <- 0 until rev.length) {
+ back &&= mapped(i) == f(rev(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement subseq" in {
+ val prop = property { (v: Vector[Int], from: Int, end: Int) =>
+ try {
+ val sub = v.subseq(from, end)
+
+ var back = sub.length == end - from
+
+ for (i <- 0 until sub.length) {
+ back &&= sub(i) == v(i + from)
+ }
+
+ back
+ } catch {
+ case _:IndexOutOfBoundsException => from < 0 || end >= v.length
+ case _:IllegalArgumentException => end <= from
+ }
+ }
+
+ prop must pass
+ }
+
+ "append to subseq" in {
+ val prop = property { (v: Vector[Int], from: Int, end: Int, n: Int) =>
+ try {
+ val sub = v.subseq(from, end)
+ val add = sub + n
+
+ var back = add.length == sub.length + 1
+ for (i <- 0 until sub.length) {
+ back &&= add(i) == sub(i)
+ }
+ back && add(sub.length) == n
+ } catch {
+ case _:IndexOutOfBoundsException => from < 0 || end >= v.length
+ case _:IllegalArgumentException => end <= from
+ }
+ }
+
+ prop must pass
+ }
+
+ "update subseq" in {
+ val prop = property { (v: Vector[Int], from: Int, end: Int, mi: Int) =>
+ try {
+ val sub = v.subseq(from, end)
+ val add = sub(mi) = 42
+
+ var back = add.length == (if (mi == add.length) sub.length + 1 else sub.length)
+ for (i <- 0 until sub.length; if i != mi) {
+ back &&= add(i) == sub(i)
+ }
+ back && add(mi) == 42
+ } catch {
+ case _:IndexOutOfBoundsException => from < 0 || end >= v.length || !(0 to (end - from) contains mi)
+ case _:IllegalArgumentException => end <= from
+ }
+ }
+
+ prop must pass
+ }
+
+ "map on subseq" in {
+ val prop = property { (v: Vector[Int], from: Int, end: Int, f: (Int)=>Int) =>
+ try {
+ val sub = v.subseq(from, end)
+ val mapped = sub map f
+
+ var back = mapped.length == sub.length
+ for (i <- 0 until sub.length) {
+ back &&= mapped(i) == f(sub(i))
+ }
+ back
+ } catch {
+ case _:IndexOutOfBoundsException => from < 0 || end >= v.length
+ case _:IllegalArgumentException => end <= from
+ }
+ }
+
+ prop must pass
+ }
+
+ "implement zip" in {
+ val prop = property { (first: Vector[Int], second: Vector[Double]) =>
+ val zip = first zip second
+
+ var back = zip.length == Math.min(first.length, second.length)
+ for (i <- 0 until zip.length) {
+ var (left, right) = zip(i)
+ back &&= (left == first(i) && right == second(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement zipWithIndex" in {
+ val prop = property { vec: Vector[Int] =>
+ val zip = vec.zipWithIndex
+
+ var back = zip.length == vec.length
+ for (i <- 0 until zip.length) {
+ val (elem, index) = zip(i)
+
+ back &&= (index == i && elem == vec(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement equals" in {
+ {
+ val prop = property { list: List[Int] =>
+ val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
+ val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
+
+ vecA == vecB
+ }
+
+ prop must pass
+ }
+
+ {
+ val prop = property { (vecA: Vector[Int], vecB: Vector[Int]) =>
+ vecA.length != vecB.length ==> (vecA != vecB)
+ }
+
+ prop must pass
+ }
+
+ {
+ val prop = property { (listA: List[Int], listB: List[Int]) =>
+ val vecA = listA.foldLeft(Vector[Int]()) { _ + _ }
+ val vecB = listB.foldLeft(Vector[Int]()) { _ + _ }
+
+ listA != listB ==> (vecA != vecB)
+ }
+
+ prop must pass
+ }
+
+ {
+ val prop = property { (vec: Vector[Int], data: Int) => vec != data }
+
+ prop must pass
+ }
+ }
+
+ "implement hashCode" in {
+ val prop = property { list: List[Int] =>
+ val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
+ val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
+
+ vecA.hashCode == vecB.hashCode
+ }
+
+ prop must pass
+ }
+
+ "implement extractor" in {
+ val vec1 = Vector(1, 2, 3)
+ vec1 must beLike {
+ case Vector(a, b, c) => (a, b, c) == (1, 2, 3)
+ }
+
+ val vec2 = Vector("daniel", "chris", "joseph")
+ vec2 must beLike {
+ case Vector(a, b, c) => (a, b, c) == ("daniel", "chris", "joseph")
+ }
+ }
+ }
+}
+
|
djspiewak/scala-collections
|
27fa0e10a94e02e412c8b21396bb7cdf68d3b269
|
Added a new performance test
|
diff --git a/src/test/scala/HashPerf.scala b/src/test/scala/HashPerf.scala
index e2a52f4..0d03b71 100644
--- a/src/test/scala/HashPerf.scala
+++ b/src/test/scala/HashPerf.scala
@@ -1,296 +1,399 @@
import com.codecommit.collection.{HashTrie, VectorHashMap}
import scala.collection.immutable.TreeHashMap
object HashPerf {
import PerfLib._
def main(args: Array[String]) {
println()
val data = "The quick brown fox jumped over the lazy red dog"
//==========================================================================
{
title("Fill 100000 Random Keys")
val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
indexes(i) = Math.random.toString
}
val hashTrieOp = "HashTrie" -> time {
var map = HashTrie[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
val mapOp = "Map" -> time {
var map = Map[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
hashTrieOp compare mapOp
val intMapOp = "TreeHashMap" -> time {
var map = TreeHashMap[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
hashTrieOp compare intMapOp
val vectorMapOp = "VectorHashMap" -> time {
var map = VectorHashMap[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
hashTrieOp compare vectorMapOp
val mutableMapOp = "mutable.Map" -> time {
val map = scala.collection.mutable.Map[String, String]()
var i = 0
while (i < indexes.length) {
map(indexes(i)) = data
i += 1
}
}
hashTrieOp compare mutableMapOp
div('=')
}
println()
//==========================================================================
{
title("Read 100000 Random Keys")
val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
indexes(i) = Math.random.toString
}
var hashTrie = HashTrie[String, String]()
{
var i = 0
while (i < indexes.length) {
hashTrie = hashTrie(indexes(i)) = data
i += 1
}
}
var immutableMap = Map[String, String]()
{
var i = 0
while (i < indexes.length) {
immutableMap = immutableMap(indexes(i)) = data
i += 1
}
}
val hashTrieOp = "HashTrie" -> time {
var i = 0
while (i < indexes.length) {
hashTrie(indexes(i))
i += 1
}
}
val mapOp = "Map" -> time {
var i = 0
while (i < indexes.length) {
immutableMap(indexes(i))
i += 1
}
}
hashTrieOp compare mapOp
var intMap = TreeHashMap[String, String]()
{
var i = 0
while (i < indexes.length) {
intMap = intMap(indexes(i)) = data
i += 1
}
}
val intMapOp = "TreeHashMap" -> time {
var i = 0
while (i < indexes.length) {
intMap(indexes(i))
i += 1
}
}
hashTrieOp compare intMapOp
var vectorMap = VectorHashMap[String, String]()
{
var i = 0
while (i < indexes.length) {
vectorMap = vectorMap(indexes(i)) = data
i += 1
}
}
val vectorMapOp = "VectorHashMap" -> time {
var i = 0
while (i < indexes.length) {
vectorMap(indexes(i))
i += 1
}
}
hashTrieOp compare vectorMapOp
val mutableMap = scala.collection.mutable.Map[String, String]()
{
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i)) = data
i += 1
}
}
val mutableMapOp = "mutable.Map" -> time {
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i))
i += 1
}
}
hashTrieOp compare mutableMapOp
div('=')
}
println()
+ //==========================================================================
+ {
+ title("Remove 50000 Random Keys")
+
+ val indexes = new Array[String](100000)
+ for (i <- 0 until indexes.length) {
+ indexes(i) = Math.random.toString
+ }
+
+ var hashTrie = HashTrie[String, String]()
+
+ {
+ var i = 0
+
+ while (i < indexes.length) {
+ hashTrie = hashTrie(indexes(i)) = data
+ i += 1
+ }
+ }
+
+ var immutableMap = Map[String, String]()
+
+ {
+ var i = 0
+
+ while (i < indexes.length) {
+ immutableMap = immutableMap(indexes(i)) = data
+ i += 1
+ }
+ }
+
+
+ val hashTrieOp = "HashTrie" -> time {
+ var i = 0
+ var map = hashTrie
+ while (i < indexes.length) {
+ map -= indexes(i)
+ i += 1
+ }
+ }
+
+ val mapOp = "Map" -> time {
+ var i = 0
+ var map = immutableMap
+
+ while (i < indexes.length) {
+ immutableMap -= indexes(i)
+ i += 1
+ }
+ }
+
+ hashTrieOp compare mapOp
+
+ var intMap = TreeHashMap[String, String]()
+
+ {
+ var i = 0
+
+ while (i < indexes.length) {
+ intMap = intMap(indexes(i)) = data
+ i += 1
+ }
+ }
+
+ val intMapOp = "TreeHashMap" -> time {
+ var i = 0
+ var map = intMap
+
+ while (i < indexes.length) {
+ map -= indexes(i)
+ i += 1
+ }
+ }
+
+ hashTrieOp compare intMapOp
+
+ var vectorMap = VectorHashMap[String, String]()
+
+ {
+ var i = 0
+
+ while (i < indexes.length) {
+ vectorMap = vectorMap(indexes(i)) = data
+ i += 1
+ }
+ }
+
+ val vectorMapOp = "VectorHashMap" -> time {
+ var i = 0
+ var map = vectorMap
+
+ while (i < indexes.length) {
+ map -= indexes(i)
+ i += 1
+ }
+ }
+
+ hashTrieOp compare vectorMapOp
+ div('=')
+ }
+
+ println()
+
//==========================================================================
{
title("Loop Over 100000 Random Keys (#foreach)")
val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
indexes(i) = Math.random.toString
}
var hashTrie = HashTrie[String, String]()
{
var i = 0
while (i < indexes.length) {
hashTrie = hashTrie(indexes(i)) = data
i += 1
}
}
var immutableMap = Map[String, String]()
{
var i = 0
while (i < indexes.length) {
immutableMap = immutableMap(indexes(i)) = data
i += 1
}
}
val hashTrieOp = "HashTrie" -> time {
hashTrie foreach { case (k, v) => () }
}
val mapOp = "Map" -> time {
immutableMap foreach { case (k, v) => () }
}
hashTrieOp compare mapOp
var intMap = TreeHashMap[String, String]()
{
var i = 0
while (i < indexes.length) {
intMap = intMap(indexes(i)) = data
i += 1
}
}
val intMapOp = "TreeHashMap" -> time {
intMap foreach { case (k, v) => () }
}
hashTrieOp compare intMapOp
var vectorMap = VectorHashMap[String, String]()
{
var i = 0
while (i < indexes.length) {
vectorMap = vectorMap(indexes(i)) = data
i += 1
}
}
val vectorMapOp = "VectorHashMap" -> time {
vectorMap foreach { case (k, v) => () }
}
hashTrieOp compare vectorMapOp
val mutableMap = scala.collection.mutable.Map[String, String]()
{
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i)) = data
i += 1
}
}
val mutableMapOp = "mutable.Map" -> time {
mutableMap foreach { case (k, v) => () }
}
hashTrieOp compare mutableMapOp
div('=')
}
}
}
|
djspiewak/scala-collections
|
533928a759a95215b84676358bf5f3b911c2c0d2
|
Semantic bugfix
|
diff --git a/src/main/scala/com/codecommit/collection/HashTrie.scala b/src/main/scala/com/codecommit/collection/HashTrie.scala
index 8d4bb6d..2814bf0 100644
--- a/src/main/scala/com/codecommit/collection/HashTrie.scala
+++ b/src/main/scala/com/codecommit/collection/HashTrie.scala
@@ -1,361 +1,361 @@
/**
Copyright (c) 2007-2008, Rich Hickey
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Clojure nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**/
package com.codecommit.collection
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
* @author Rich Hickey
*/
final class HashTrie[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashTrie(root(0, key, key.hashCode) = value)
def -(key: K) = new HashTrie(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashTrie[K, A] = new HashTrie(new EmptyNode[K])
def diagnose = root.toString
}
object HashTrie {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashTrie[K, V]) { _ + _ }
def unapplySeq[K, V](map: HashTrie[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](shift: Int, key: K, hash: Int, value: V) = new LeafNode(key, hash, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] abstract class SingleNode[K, +V] extends Node[K, V] {
val hash: Int
}
private[collection] class LeafNode[K, +V](key: K, val hash: Int, value: V) extends SingleNode[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](shift: Int, key: K, hash: Int, value: A) = {
if (this.key == key) {
if (this.value == value) this else new LeafNode(key, hash, value)
} else if (this.hash == hash) {
new CollisionNode(hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(this, key, hash, value)
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](val hash: Int, bucket: List[(K, V)]) extends SingleNode[K, V] {
lazy val size = bucket.length
def this(hash: Int, pairs: (K, V)*) = this(hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for ((k, v) <- bucket) yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(hash, if (found) newBucket else (key, value) :: bucket)
} else {
BitmappedNode(shift)(this, key, hash, value)
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == bucket.length) this else {
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(key, hash, value)
} else new CollisionNode(hash, newBucket)
}
}
def elements = bucket.elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else {
val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = new LeafNode(key, hash, value)
val newBits = bits | mask
if (newBits == ~0) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node == table(i)) {
this
} else if (node.isInstanceOf[EmptyNode[_]]) {
if (size == 1) new EmptyNode[K] else {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
- val newTable = new Array[Node[K, V]](if (i + 1 == table.length) table.length - 1 else table.length)
+ val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, newTable.length)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
}
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
table.foldLeft(emptyElements) { (it, e) =>
if (e == null) it else it ++ e.elements
}
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(node: SingleNode[K, V], key: K, hash: Int, value: V) = {
val table = new Array[Node[K, V]](Math.max((hash >>> shift) & 0x01f, (node.hash >>> shift) & 0x01f) + 1)
val preBits = {
val i = (node.hash >>> shift) & 0x01f
table(i) = node
1 << i
}
val bits = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((preBits & mask) == mask) {
table(i) = (table(i)(shift + 5, key, hash) = value)
} else {
table(i) = new LeafNode(key, hash, value)
}
preBits | mask
}
new BitmappedNode(shift)(table, bits)
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = table((hash >>> shift) & 0x01f)(key, hash)
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val node = table(i).remove(key, hash)
if (node == table(i)) this else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, ~mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
}
def elements = table.foldLeft(emptyElements) { _ ++ _.elements }
override def toString = "FullNode(" + table.foldLeft("") { _.toString + ", " + _.toString } + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
|
djspiewak/scala-collections
|
f7ee2a420dcb64da04b1e60563491ce763354db6
|
Bitsy stylistic change
|
diff --git a/src/main/scala/com/codecommit/collection/HashTrie.scala b/src/main/scala/com/codecommit/collection/HashTrie.scala
index 4dd9cd9..8d4bb6d 100644
--- a/src/main/scala/com/codecommit/collection/HashTrie.scala
+++ b/src/main/scala/com/codecommit/collection/HashTrie.scala
@@ -1,361 +1,361 @@
/**
Copyright (c) 2007-2008, Rich Hickey
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Clojure nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**/
package com.codecommit.collection
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
* @author Rich Hickey
*/
final class HashTrie[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashTrie(root(0, key, key.hashCode) = value)
def -(key: K) = new HashTrie(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashTrie[K, A] = new HashTrie(new EmptyNode[K])
def diagnose = root.toString
}
object HashTrie {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashTrie[K, V]) { _ + _ }
def unapplySeq[K, V](map: HashTrie[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](shift: Int, key: K, hash: Int, value: V) = new LeafNode(key, hash, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] abstract class SingleNode[K, +V] extends Node[K, V] {
val hash: Int
}
private[collection] class LeafNode[K, +V](key: K, val hash: Int, value: V) extends SingleNode[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](shift: Int, key: K, hash: Int, value: A) = {
if (this.key == key) {
if (this.value == value) this else new LeafNode(key, hash, value)
} else if (this.hash == hash) {
new CollisionNode(hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(this, key, hash, value)
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](val hash: Int, bucket: List[(K, V)]) extends SingleNode[K, V] {
lazy val size = bucket.length
def this(hash: Int, pairs: (K, V)*) = this(hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for ((k, v) <- bucket) yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(hash, if (found) newBucket else (key, value) :: bucket)
} else {
BitmappedNode(shift)(this, key, hash, value)
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == bucket.length) this else {
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(key, hash, value)
} else new CollisionNode(hash, newBucket)
}
}
def elements = bucket.elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else {
val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = new LeafNode(key, hash, value)
val newBits = bits | mask
if (newBits == ~0) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node == table(i)) {
this
} else if (node.isInstanceOf[EmptyNode[_]]) {
if (size == 1) new EmptyNode[K] else {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](if (i + 1 == table.length) table.length - 1 else table.length)
Array.copy(table, 0, newTable, 0, newTable.length)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
}
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
table.foldLeft(emptyElements) { (it, e) =>
if (e == null) it else it ++ e.elements
}
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(node: SingleNode[K, V], key: K, hash: Int, value: V) = {
val table = new Array[Node[K, V]](Math.max((hash >>> shift) & 0x01f, (node.hash >>> shift) & 0x01f) + 1)
val preBits = {
val i = (node.hash >>> shift) & 0x01f
table(i) = node
1 << i
}
val bits = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((preBits & mask) == mask) {
table(i) = (table(i)(shift + 5, key, hash) = value)
} else {
table(i) = new LeafNode(key, hash, value)
}
preBits | mask
}
new BitmappedNode(shift)(table, bits)
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = table((hash >>> shift) & 0x01f)(key, hash)
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val node = table(i).remove(key, hash)
if (node == table(i)) this else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
- new BitmappedNode(shift)(newTable, ~0 ^ mask)
+ new BitmappedNode(shift)(newTable, ~mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
}
def elements = table.foldLeft(emptyElements) { _ ++ _.elements }
override def toString = "FullNode(" + table.foldLeft("") { _.toString + ", " + _.toString } + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
|
djspiewak/scala-collections
|
5397ba84e04bf4fa999ab9e000c9886158708f90
|
Re-added build.yaml
|
diff --git a/build.yaml b/build.yaml
new file mode 100644
index 0000000..6e00ca9
--- /dev/null
+++ b/build.yaml
@@ -0,0 +1,2 @@
+scala.check: 1.5
+scala.specs: 1.4.1
|
djspiewak/scala-collections
|
ebf44d0f159a5302ab4aedf3a9eff7066d7f5f52
|
Fixed bitmap creation optimization
|
diff --git a/src/main/scala/com/codecommit/collection/HashTrie.scala b/src/main/scala/com/codecommit/collection/HashTrie.scala
index a5d8f5f..4dd9cd9 100644
--- a/src/main/scala/com/codecommit/collection/HashTrie.scala
+++ b/src/main/scala/com/codecommit/collection/HashTrie.scala
@@ -1,351 +1,361 @@
/**
Copyright (c) 2007-2008, Rich Hickey
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Clojure nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**/
package com.codecommit.collection
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
* @author Rich Hickey
*/
final class HashTrie[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashTrie(root(0, key, key.hashCode) = value)
def -(key: K) = new HashTrie(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashTrie[K, A] = new HashTrie(new EmptyNode[K])
def diagnose = root.toString
}
object HashTrie {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashTrie[K, V]) { _ + _ }
def unapplySeq[K, V](map: HashTrie[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](shift: Int, key: K, hash: Int, value: V) = new LeafNode(key, hash, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] abstract class SingleNode[K, +V] extends Node[K, V] {
val hash: Int
}
private[collection] class LeafNode[K, +V](key: K, val hash: Int, value: V) extends SingleNode[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](shift: Int, key: K, hash: Int, value: A) = {
if (this.key == key) {
if (this.value == value) this else new LeafNode(key, hash, value)
} else if (this.hash == hash) {
new CollisionNode(hash, this.key -> this.value, key -> value)
} else {
- BitmappedNode(shift)(this, new LeafNode(key, hash, value))
+ BitmappedNode(shift)(this, key, hash, value)
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](val hash: Int, bucket: List[(K, V)]) extends SingleNode[K, V] {
lazy val size = bucket.length
def this(hash: Int, pairs: (K, V)*) = this(hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for ((k, v) <- bucket) yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(hash, if (found) newBucket else (key, value) :: bucket)
} else {
- BitmappedNode(shift)(this, new LeafNode(key, hash, value))
+ BitmappedNode(shift)(this, key, hash, value)
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == bucket.length) this else {
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(key, hash, value)
} else new CollisionNode(hash, newBucket)
}
}
def elements = bucket.elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else {
val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = new LeafNode(key, hash, value)
val newBits = bits | mask
if (newBits == ~0) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node == table(i)) {
this
} else if (node.isInstanceOf[EmptyNode[_]]) {
if (size == 1) new EmptyNode[K] else {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](if (i + 1 == table.length) table.length - 1 else table.length)
Array.copy(table, 0, newTable, 0, newTable.length)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
}
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
table.foldLeft(emptyElements) { (it, e) =>
if (e == null) it else it ++ e.elements
}
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
- def apply[K, V](shift: Int)(nodes: SingleNode[K, V]*) = {
- val table = new Array[Node[K, V]](nodes.foldLeft(0) { (x, node) =>
- Math.max(x, (node.hash >>> shift) & 0x01f)
- } + 1)
+ def apply[K, V](shift: Int)(node: SingleNode[K, V], key: K, hash: Int, value: V) = {
+ val table = new Array[Node[K, V]](Math.max((hash >>> shift) & 0x01f, (node.hash >>> shift) & 0x01f) + 1)
- val bits = nodes.foldLeft(0) { (bits, node) =>
+ val preBits = {
val i = (node.hash >>> shift) & 0x01f
table(i) = node
+ 1 << i
+ }
+
+ val bits = {
+ val i = (hash >>> shift) & 0x01f
+ val mask = 1 << i
+
+ if ((preBits & mask) == mask) {
+ table(i) = (table(i)(shift + 5, key, hash) = value)
+ } else {
+ table(i) = new LeafNode(key, hash, value)
+ }
- bits | (1 << i)
+ preBits | mask
}
new BitmappedNode(shift)(table, bits)
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = table((hash >>> shift) & 0x01f)(key, hash)
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val node = table(i).remove(key, hash)
if (node == table(i)) this else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, ~0 ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
}
def elements = table.foldLeft(emptyElements) { _ ++ _.elements }
override def toString = "FullNode(" + table.foldLeft("") { _.toString + ", " + _.toString } + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
|
djspiewak/scala-collections
|
5cd0239e78d37858bba8d415ba5d6b02310c1aa2
|
Reduced the number of new nodes necessary
|
diff --git a/src/main/scala/com/codecommit/collection/HashTrie.scala b/src/main/scala/com/codecommit/collection/HashTrie.scala
index d92c406..a5d8f5f 100644
--- a/src/main/scala/com/codecommit/collection/HashTrie.scala
+++ b/src/main/scala/com/codecommit/collection/HashTrie.scala
@@ -1,356 +1,351 @@
/**
Copyright (c) 2007-2008, Rich Hickey
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Clojure nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**/
package com.codecommit.collection
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
* @author Rich Hickey
*/
final class HashTrie[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashTrie(root(0, key, key.hashCode) = value)
def -(key: K) = new HashTrie(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashTrie[K, A] = new HashTrie(new EmptyNode[K])
def diagnose = root.toString
}
object HashTrie {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashTrie[K, V]) { _ + _ }
def unapplySeq[K, V](map: HashTrie[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](shift: Int, key: K, hash: Int, value: V) = new LeafNode(key, hash, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
+private[collection] abstract class SingleNode[K, +V] extends Node[K, V] {
+ val hash: Int
+}
+
-private[collection] class LeafNode[K, +V](key: K, hash: Int, value: V) extends Node[K, V] {
+private[collection] class LeafNode[K, +V](key: K, val hash: Int, value: V) extends SingleNode[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](shift: Int, key: K, hash: Int, value: A) = {
if (this.key == key) {
if (this.value == value) this else new LeafNode(key, hash, value)
} else if (this.hash == hash) {
new CollisionNode(hash, this.key -> this.value, key -> value)
} else {
- BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
+ BitmappedNode(shift)(this, new LeafNode(key, hash, value))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
-private[collection] class CollisionNode[K, +V](hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
+private[collection] class CollisionNode[K, +V](val hash: Int, bucket: List[(K, V)]) extends SingleNode[K, V] {
lazy val size = bucket.length
def this(hash: Int, pairs: (K, V)*) = this(hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for ((k, v) <- bucket) yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(hash, if (found) newBucket else (key, value) :: bucket)
} else {
- val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
- BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
+ BitmappedNode(shift)(this, new LeafNode(key, hash, value))
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == bucket.length) this else {
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(key, hash, value)
} else new CollisionNode(hash, newBucket)
}
}
def elements = bucket.elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else {
val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = new LeafNode(key, hash, value)
val newBits = bits | mask
if (newBits == ~0) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node == table(i)) {
this
} else if (node.isInstanceOf[EmptyNode[_]]) {
if (size == 1) new EmptyNode[K] else {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](if (i + 1 == table.length) table.length - 1 else table.length)
Array.copy(table, 0, newTable, 0, newTable.length)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
}
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
table.foldLeft(emptyElements) { (it, e) =>
if (e == null) it else it ++ e.elements
}
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
- def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
- val table = new Array[Node[K, V]](pairs.foldLeft(0) { (x, pair) =>
- val (_, hash, _) = pair
- Math.max(x, (hash >>> shift) & 0x01f)
+ def apply[K, V](shift: Int)(nodes: SingleNode[K, V]*) = {
+ val table = new Array[Node[K, V]](nodes.foldLeft(0) { (x, node) =>
+ Math.max(x, (node.hash >>> shift) & 0x01f)
} + 1)
- val bits = pairs.foldLeft(0) { (bits, pair) =>
- val (key, hash, value) = pair
- val i = (hash >>> shift) & 0x01f
- val mask = 1 << i
+ val bits = nodes.foldLeft(0) { (bits, node) =>
+ val i = (node.hash >>> shift) & 0x01f
+ table(i) = node
- if ((bits & mask) == mask) {
- table(i) = (table(i)(shift + 5, key, hash) = value)
- } else {
- table(i) = new LeafNode(key, hash, value)
- }
-
- bits | mask
+ bits | (1 << i)
}
new BitmappedNode(shift)(table, bits)
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = table((hash >>> shift) & 0x01f)(key, hash)
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val node = table(i).remove(key, hash)
if (node == table(i)) this else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, ~0 ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
}
def elements = table.foldLeft(emptyElements) { _ ++ _.elements }
override def toString = "FullNode(" + table.foldLeft("") { _.toString + ", " + _.toString } + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
|
djspiewak/scala-collections
|
95669e92cb5a8b0c649866c3b73dc882c20c5d07
|
Improved efficiency of the #elements method
|
diff --git a/src/main/scala/com/codecommit/collection/HashTrie.scala b/src/main/scala/com/codecommit/collection/HashTrie.scala
index cb288a7..d92c406 100644
--- a/src/main/scala/com/codecommit/collection/HashTrie.scala
+++ b/src/main/scala/com/codecommit/collection/HashTrie.scala
@@ -1,355 +1,356 @@
/**
Copyright (c) 2007-2008, Rich Hickey
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Clojure nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**/
package com.codecommit.collection
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
* @author Rich Hickey
*/
final class HashTrie[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashTrie(root(0, key, key.hashCode) = value)
def -(key: K) = new HashTrie(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashTrie[K, A] = new HashTrie(new EmptyNode[K])
def diagnose = root.toString
}
object HashTrie {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashTrie[K, V]) { _ + _ }
def unapplySeq[K, V](map: HashTrie[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](shift: Int, key: K, hash: Int, value: V) = new LeafNode(key, hash, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] class LeafNode[K, +V](key: K, hash: Int, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](shift: Int, key: K, hash: Int, value: A) = {
if (this.key == key) {
if (this.value == value) this else new LeafNode(key, hash, value)
} else if (this.hash == hash) {
new CollisionNode(hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
def this(hash: Int, pairs: (K, V)*) = this(hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for ((k, v) <- bucket) yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == bucket.length) this else {
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(key, hash, value)
} else new CollisionNode(hash, newBucket)
}
}
def elements = bucket.elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else {
val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = new LeafNode(key, hash, value)
val newBits = bits | mask
if (newBits == ~0) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node == table(i)) {
this
} else if (node.isInstanceOf[EmptyNode[_]]) {
if (size == 1) new EmptyNode[K] else {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](if (i + 1 == table.length) table.length - 1 else table.length)
Array.copy(table, 0, newTable, 0, newTable.length)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
}
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
- val iters = table flatMap { n =>
- if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
+ table.foldLeft(emptyElements) { (it, e) =>
+ if (e == null) it else it ++ e.elements
}
-
- iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
val table = new Array[Node[K, V]](pairs.foldLeft(0) { (x, pair) =>
val (_, hash, _) = pair
Math.max(x, (hash >>> shift) & 0x01f)
} + 1)
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
table(i) = (table(i)(shift + 5, key, hash) = value)
} else {
table(i) = new LeafNode(key, hash, value)
}
bits | mask
}
new BitmappedNode(shift)(table, bits)
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = table((hash >>> shift) & 0x01f)(key, hash)
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val node = table(i).remove(key, hash)
if (node == table(i)) this else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, ~0 ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
}
- def elements = {
- val iters = table map { _.elements }
- iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
- }
+ def elements = table.foldLeft(emptyElements) { _ ++ _.elements }
override def toString = "FullNode(" + table.foldLeft("") { _.toString + ", " + _.toString } + ")"
+
+ private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
+ val hasNext = false
+
+ val next = null
+ }
}
|
djspiewak/scala-collections
|
bb2a4233a9cfbcff0d65f69670489207f36ca230
|
Added hash map growth; performance tests
|
diff --git a/src/main/scala/com/codecommit/collection/VectorHashMap.scala b/src/main/scala/com/codecommit/collection/VectorHashMap.scala
index 12bda5a..e51220d 100644
--- a/src/main/scala/com/codecommit/collection/VectorHashMap.scala
+++ b/src/main/scala/com/codecommit/collection/VectorHashMap.scala
@@ -1,97 +1,129 @@
package com.codecommit.collection
+import VectorHashMap._
+
class VectorHashMap[K, +V] private (table: Vector[List[(K, V)]], val size: Int) extends Map[K, V] {
- def this() = this(Vector[List[(K, V)]](), 0)
+ def this() = this(allocate[K, V](10), 0)
def get(key: K) = {
def traverseBucket(bucket: List[(K, V)]): Option[V] = bucket match {
case (k, v) :: tail => if (k == key) Some(v) else traverseBucket(tail)
case Nil => None
}
- val b = table(computeHash(key))
+ val b = table(computeHash(key, table.length))
if (b == null) None else traverseBucket(b)
}
override def +[A >: V](pair: (K, A)) = update(pair._1, pair._2)
def update[A >: V](key: K, value: A) = {
- val i = computeHash(key)
- val b = table(i)
-
- val (replaced, newTable) = if (b == null) {
- (false, table(i) = (key, value) :: Nil)
- } else {
- def traverseBucket(bucket: List[(K, V)]): (Boolean, List[(K, A)]) = bucket match {
- case (k, v) :: tail => {
- if (k == key) {
- (true, (key, value) :: tail)
- } else {
- val (found, newTail) = traverseBucket(tail)
- (found, (k, v) :: newTail)
- }
- }
-
- case Nil => (false, Nil)
- }
-
- val (found, newBucket) = traverseBucket(b)
- if (found) {
- (true, table(i) = newBucket)
- } else {
- (false, table(i) = ((key, value) :: b))
- }
- }
-
+ val (replaced, newTable) = store(grow(table, size))(key, value.asInstanceOf[V])
new VectorHashMap[K, A](newTable, if (replaced) size else size + 1)
}
def -(key: K): VectorHashMap[K, V] = {
- val i = computeHash(key)
+ val i = computeHash(key, table.length)
val b = table(i)
val (removed, newTable) = if (b == null) {
(false, table)
} else {
def traverseBucket(bucket: List[(K, V)]): (Boolean, List[(K, V)]) = bucket match {
case (k, v) :: tail => {
if (k == key) {
(true, tail)
} else {
val (found, newTail) = traverseBucket(tail)
(found, (k, v) :: newTail)
}
}
case Nil => (false, Nil)
}
val (found, newBucket) = traverseBucket(b)
if (found) {
(true, table(i) = newBucket)
} else {
(false, table)
}
}
if (removed) {
new VectorHashMap[K, V](newTable, size - 1)
} else this
}
def elements: Iterator[(K, V)] = {
val iterTable = table flatMap { // quick and dirty
case null => Vector[(K, V)]()
case bucket => bucket.foldLeft(Vector[(K, V)]()) { _ + _ }
}
iterTable.elements
}
def empty[C] = new VectorHashMap[K, C]()
+}
+
+object VectorHashMap {
+
+ def apply[K, V](pairs: (K, V)*) = {
+ pairs.foldLeft(new VectorHashMap[K, V]()) { _ + _ }
+ }
+
+ @inline
+ private def computeHash[K](key: K, length: Int) = Math.abs(key.hashCode % length)
+
+ @inline
+ private[collection] def allocate[K, V](length: Int) = {
+ (0 until length).foldLeft(Vector[List[(K, V)]]()) { (v, n) => v + null }
+ }
@inline
- private def computeHash(key: K) = key.hashCode % table.length
+ private[collection] def grow[K, V](table: Vector[List[(K, V)]], size: Int) = {
+ if (size >= table.length) {
+ table.foldLeft(allocate[K, V](table.length * 2)) { (table, bucket) =>
+ if (bucket == null) table else {
+ bucket.foldLeft(table) { (table, pair) =>
+ val (key, value) = pair
+ store(table)(key, value)._2
+ }
+ }
+ }
+ } else table
+ }
+
+ @inline
+ private[collection] def store[K, V, A >: V](table: Vector[List[(K, V)]])(key: K, value: A) = {
+ val i = computeHash(key, table.length)
+ val b = table(i)
+
+ if (b == null) {
+ (false, table(i) = (key, value) :: Nil)
+ } else {
+ def traverseBucket(bucket: List[(K, V)]): (Boolean, List[(K, A)]) = bucket match {
+ case (k, v) :: tail => {
+ if (k == key) {
+ (true, (key, value) :: tail)
+ } else {
+ val (found, newTail) = traverseBucket(tail)
+ (found, (k, v) :: newTail)
+ }
+ }
+
+ case Nil => (false, Nil)
+ }
+
+ val (found, newBucket) = traverseBucket(b)
+ if (found) {
+ (true, table(i) = newBucket)
+ } else {
+ (false, table(i) = ((key, value) :: b))
+ }
+ }
+ }
}
diff --git a/src/test/scala/HashPerf.scala b/src/test/scala/HashPerf.scala
index b12eefa..e2a52f4 100644
--- a/src/test/scala/HashPerf.scala
+++ b/src/test/scala/HashPerf.scala
@@ -1,246 +1,296 @@
-import com.codecommit.collection.HashTrie
+import com.codecommit.collection.{HashTrie, VectorHashMap}
import scala.collection.immutable.TreeHashMap
object HashPerf {
import PerfLib._
def main(args: Array[String]) {
println()
val data = "The quick brown fox jumped over the lazy red dog"
//==========================================================================
{
title("Fill 100000 Random Keys")
val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
indexes(i) = Math.random.toString
}
- val hashMapOp = "HashTrie" -> time {
+ val hashTrieOp = "HashTrie" -> time {
var map = HashTrie[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
val mapOp = "Map" -> time {
var map = Map[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
- hashMapOp compare mapOp
+ hashTrieOp compare mapOp
val intMapOp = "TreeHashMap" -> time {
var map = TreeHashMap[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
- hashMapOp compare intMapOp
+ hashTrieOp compare intMapOp
+
+ val vectorMapOp = "VectorHashMap" -> time {
+ var map = VectorHashMap[String, String]()
+ var i = 0
+
+ while (i < indexes.length) {
+ map = map(indexes(i)) = data
+ i += 1
+ }
+ }
+
+ hashTrieOp compare vectorMapOp
val mutableMapOp = "mutable.Map" -> time {
val map = scala.collection.mutable.Map[String, String]()
var i = 0
while (i < indexes.length) {
map(indexes(i)) = data
i += 1
}
}
- hashMapOp compare mutableMapOp
+ hashTrieOp compare mutableMapOp
div('=')
}
println()
//==========================================================================
{
title("Read 100000 Random Keys")
val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
indexes(i) = Math.random.toString
}
- var hashMap = HashTrie[String, String]()
+ var hashTrie = HashTrie[String, String]()
{
var i = 0
while (i < indexes.length) {
- hashMap = hashMap(indexes(i)) = data
+ hashTrie = hashTrie(indexes(i)) = data
i += 1
}
}
var immutableMap = Map[String, String]()
{
var i = 0
while (i < indexes.length) {
immutableMap = immutableMap(indexes(i)) = data
i += 1
}
}
- val hashMapOp = "HashTrie" -> time {
+ val hashTrieOp = "HashTrie" -> time {
var i = 0
while (i < indexes.length) {
- hashMap(indexes(i))
+ hashTrie(indexes(i))
i += 1
}
}
val mapOp = "Map" -> time {
var i = 0
while (i < indexes.length) {
immutableMap(indexes(i))
i += 1
}
}
- hashMapOp compare mapOp
+ hashTrieOp compare mapOp
var intMap = TreeHashMap[String, String]()
{
var i = 0
while (i < indexes.length) {
intMap = intMap(indexes(i)) = data
i += 1
}
}
val intMapOp = "TreeHashMap" -> time {
var i = 0
while (i < indexes.length) {
intMap(indexes(i))
i += 1
}
}
- hashMapOp compare intMapOp
+ hashTrieOp compare intMapOp
+
+ var vectorMap = VectorHashMap[String, String]()
+
+ {
+ var i = 0
+
+ while (i < indexes.length) {
+ vectorMap = vectorMap(indexes(i)) = data
+ i += 1
+ }
+ }
+
+ val vectorMapOp = "VectorHashMap" -> time {
+ var i = 0
+ while (i < indexes.length) {
+ vectorMap(indexes(i))
+ i += 1
+ }
+ }
+
+ hashTrieOp compare vectorMapOp
val mutableMap = scala.collection.mutable.Map[String, String]()
{
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i)) = data
i += 1
}
}
val mutableMapOp = "mutable.Map" -> time {
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i))
i += 1
}
}
- hashMapOp compare mutableMapOp
+ hashTrieOp compare mutableMapOp
div('=')
}
println()
//==========================================================================
{
title("Loop Over 100000 Random Keys (#foreach)")
val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
indexes(i) = Math.random.toString
}
- var hashMap = HashTrie[String, String]()
+ var hashTrie = HashTrie[String, String]()
{
var i = 0
while (i < indexes.length) {
- hashMap = hashMap(indexes(i)) = data
+ hashTrie = hashTrie(indexes(i)) = data
i += 1
}
}
var immutableMap = Map[String, String]()
{
var i = 0
while (i < indexes.length) {
immutableMap = immutableMap(indexes(i)) = data
i += 1
}
}
- val hashMapOp = "HashTrie" -> time {
- hashMap foreach { case (k, v) => () }
+ val hashTrieOp = "HashTrie" -> time {
+ hashTrie foreach { case (k, v) => () }
}
val mapOp = "Map" -> time {
immutableMap foreach { case (k, v) => () }
}
- hashMapOp compare mapOp
+ hashTrieOp compare mapOp
var intMap = TreeHashMap[String, String]()
{
var i = 0
while (i < indexes.length) {
intMap = intMap(indexes(i)) = data
i += 1
}
}
val intMapOp = "TreeHashMap" -> time {
intMap foreach { case (k, v) => () }
}
- hashMapOp compare intMapOp
+ hashTrieOp compare intMapOp
+
+ var vectorMap = VectorHashMap[String, String]()
+
+ {
+ var i = 0
+
+ while (i < indexes.length) {
+ vectorMap = vectorMap(indexes(i)) = data
+ i += 1
+ }
+ }
+
+ val vectorMapOp = "VectorHashMap" -> time {
+ vectorMap foreach { case (k, v) => () }
+ }
+
+ hashTrieOp compare vectorMapOp
val mutableMap = scala.collection.mutable.Map[String, String]()
{
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i)) = data
i += 1
}
}
val mutableMapOp = "mutable.Map" -> time {
mutableMap foreach { case (k, v) => () }
}
- hashMapOp compare mutableMapOp
+ hashTrieOp compare mutableMapOp
div('=')
}
}
}
|
djspiewak/scala-collections
|
d9a0c4020f8a7a52456ffa00f124d00940d6bafa
|
Added prototype of a Vector-based persistent HashMap
|
diff --git a/src/main/scala/com/codecommit/collection/VectorHashMap.scala b/src/main/scala/com/codecommit/collection/VectorHashMap.scala
new file mode 100644
index 0000000..12bda5a
--- /dev/null
+++ b/src/main/scala/com/codecommit/collection/VectorHashMap.scala
@@ -0,0 +1,97 @@
+package com.codecommit.collection
+
+class VectorHashMap[K, +V] private (table: Vector[List[(K, V)]], val size: Int) extends Map[K, V] {
+
+ def this() = this(Vector[List[(K, V)]](), 0)
+
+ def get(key: K) = {
+ def traverseBucket(bucket: List[(K, V)]): Option[V] = bucket match {
+ case (k, v) :: tail => if (k == key) Some(v) else traverseBucket(tail)
+ case Nil => None
+ }
+
+ val b = table(computeHash(key))
+ if (b == null) None else traverseBucket(b)
+ }
+
+ override def +[A >: V](pair: (K, A)) = update(pair._1, pair._2)
+
+ def update[A >: V](key: K, value: A) = {
+ val i = computeHash(key)
+ val b = table(i)
+
+ val (replaced, newTable) = if (b == null) {
+ (false, table(i) = (key, value) :: Nil)
+ } else {
+ def traverseBucket(bucket: List[(K, V)]): (Boolean, List[(K, A)]) = bucket match {
+ case (k, v) :: tail => {
+ if (k == key) {
+ (true, (key, value) :: tail)
+ } else {
+ val (found, newTail) = traverseBucket(tail)
+ (found, (k, v) :: newTail)
+ }
+ }
+
+ case Nil => (false, Nil)
+ }
+
+ val (found, newBucket) = traverseBucket(b)
+ if (found) {
+ (true, table(i) = newBucket)
+ } else {
+ (false, table(i) = ((key, value) :: b))
+ }
+ }
+
+ new VectorHashMap[K, A](newTable, if (replaced) size else size + 1)
+ }
+
+ def -(key: K): VectorHashMap[K, V] = {
+ val i = computeHash(key)
+ val b = table(i)
+
+ val (removed, newTable) = if (b == null) {
+ (false, table)
+ } else {
+ def traverseBucket(bucket: List[(K, V)]): (Boolean, List[(K, V)]) = bucket match {
+ case (k, v) :: tail => {
+ if (k == key) {
+ (true, tail)
+ } else {
+ val (found, newTail) = traverseBucket(tail)
+ (found, (k, v) :: newTail)
+ }
+ }
+
+ case Nil => (false, Nil)
+ }
+
+ val (found, newBucket) = traverseBucket(b)
+ if (found) {
+ (true, table(i) = newBucket)
+ } else {
+ (false, table)
+ }
+ }
+
+ if (removed) {
+ new VectorHashMap[K, V](newTable, size - 1)
+ } else this
+ }
+
+ def elements: Iterator[(K, V)] = {
+ val iterTable = table flatMap { // quick and dirty
+ case null => Vector[(K, V)]()
+
+ case bucket => bucket.foldLeft(Vector[(K, V)]()) { _ + _ }
+ }
+
+ iterTable.elements
+ }
+
+ def empty[C] = new VectorHashMap[K, C]()
+
+ @inline
+ private def computeHash(key: K) = key.hashCode % table.length
+}
|
djspiewak/scala-collections
|
23fa583f6f2349ae96973c081cb51394bd368dbb
|
Added some more specs (up to 98% coverage!)
|
diff --git a/src/test/scala/VectorSpecs.scala b/src/test/scala/VectorSpecs.scala
index d59bb0b..1a97c79 100644
--- a/src/test/scala/VectorSpecs.scala
+++ b/src/test/scala/VectorSpecs.scala
@@ -1,332 +1,426 @@
import org.specs._
import org.scalacheck._
-import com.codecommit.collection.Vector
+import com.codecommit.collection.{EmptyVector, Vector}
object VectorSpecs extends Specification with ScalaCheck {
import Prop._
val vector = Vector[Int]()
implicit def arbitraryVector[A](implicit arb: Arbitrary[A]): Arbitrary[Vector[A]] = {
Arbitrary(for {
data <- Arbitrary.arbitrary[List[A]]
} yield data.foldLeft(Vector[A]()) { _ + _ })
}
"vector" should {
"store a single element" in {
val prop = property { (i: Int, e: Int) =>
i >= 0 ==> ((vector(0) = e)(0) == e)
}
prop must pass
}
+ "implement length" in {
+ val prop = property { (list: List[Int]) =>
+ val vec = list.foldLeft(Vector[Int]()) { _ + _ }
+ vec.length == list.length
+ }
+
+ prop must pass
+ }
+
"replace single element" in {
val prop = property { (vec: Vector[Int], i: Int) =>
((0 to vec.length) contains i) ==> {
val newVector = (vec(i) = "test")(i) = "newTest"
newVector(i) == "newTest"
}
}
prop must pass
}
+ "fail on apply out-of-bounds" in {
+ val prop = property { (vec: Vector[Int], i: Int) =>
+ !((0 until vec.length) contains i) ==> {
+ try {
+ vec(i)
+ false
+ } catch {
+ case _: IndexOutOfBoundsException => true
+ }
+ }
+ }
+
+ prop must pass
+ }
+
+ "fail on update out-of-bounds" in {
+ val prop = property { (vec: Vector[Int], i: Int) =>
+ !((0 to vec.length) contains i) ==> {
+ try {
+ vec(i) = 42
+ false
+ } catch {
+ case _: IndexOutOfBoundsException => true
+ }
+ }
+ }
+
+ prop must pass
+ }
+
"pop elements" in {
val prop = property { vec: Vector[Int] =>
vec.length > 0 ==> {
val popped = vec.pop
-
var back = popped.length == vec.length - 1
- var i = 0
- while (i < popped.length) {
+ for (i <- 0 until popped.length) {
back &&= popped(i) == vec(i)
- i += 1
}
back
}
}
- prop must pass
+ prop must pass(set(maxSize -> 3000, minTestsOk -> 1000))
+ }
+
+ "fail on pop empty vector" in {
+ val caughtExcept = try {
+ EmptyVector.pop
+ false
+ } catch {
+ case _: IllegalStateException => true
+ }
+
+ caughtExcept mustEqual true
}
"store multiple elements in order" in {
val prop = property { list: List[Int] =>
val newVector = list.foldLeft(vector) { _ + _ }
val res = for (i <- 0 until list.length) yield newVector(i) == list(i)
res forall { _ == true }
}
prop must pass
}
"store lots of elements" in {
val LENGTH = 100000
val vector = (0 until LENGTH).foldLeft(Vector[Int]()) { _ + _ }
vector.length mustEqual LENGTH
for (i <- 0 until LENGTH) {
vector(i) mustEqual i
}
}
"implement filter" in {
val prop = property { (vec: Vector[Int], f: (Int)=>Boolean) =>
val filtered = vec filter f
var back = filtered forall f
for (e <- vec) {
if (f(e)) {
back &&= filtered.contains(e)
}
}
back
}
prop must pass
}
"implement foldLeft" in {
val prop = property { list: List[Int] =>
val vec = list.foldLeft(Vector[Int]()) { _ + _ }
vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ }
}
prop must pass
}
"implement forall" in {
val prop = property { (vec: Vector[Int], f: (Int)=>Boolean) =>
val bool = vec forall f
var back = true
for (e <- vec) {
back &&= f(e)
}
(back && bool) || (!back && !bool)
}
prop must pass
}
"implement flatMap" in {
val prop = property { (vec: Vector[Int], f: (Int)=>Vector[Int]) =>
val mapped = vec flatMap f
var back = true
var i = 0
var n = 0
while (i < vec.length) {
val res = f(vec(i))
var inner = 0
while (inner < res.length) {
back &&= mapped(n) == res(inner)
inner += 1
n += 1
}
i += 1
}
back
}
prop must pass
}
"implement map" in {
val prop = property { (vec: Vector[Int], f: (Int)=>Int) =>
val mapped = vec map f
var back = vec.length == mapped.length
for (i <- 0 until vec.length) {
back &&= mapped(i) == f(vec(i))
}
back
}
prop must pass
}
"implement reverse" in {
val prop = property { v: Vector[Int] =>
val reversed = v.reverse
var back = v.length == reversed.length
for (i <- 0 until v.length) {
back &&= reversed(i) == v(v.length - i - 1)
}
back
}
prop must pass
}
"append to reverse" in {
val prop = property { (v: Vector[Int], n: Int) =>
val rev = v.reverse
val add = rev + n
var back = add.length == rev.length + 1
for (i <- 0 until rev.length) {
back &&= add(i) == rev(i)
}
back && add(rev.length) == n
}
prop must pass
}
"map on reverse" in {
val prop = property { (v: Vector[Int], f: (Int)=>Int) =>
val rev = v.reverse
val mapped = rev map f
var back = mapped.length == rev.length
for (i <- 0 until rev.length) {
back &&= mapped(i) == f(rev(i))
}
back
}
prop must pass
}
"implement subseq" in {
val prop = property { (v: Vector[Int], from: Int, end: Int) =>
try {
val sub = v.subseq(from, end)
var back = sub.length == end - from
for (i <- 0 until sub.length) {
back &&= sub(i) == v(i + from)
}
back
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"append to subseq" in {
val prop = property { (v: Vector[Int], from: Int, end: Int, n: Int) =>
try {
val sub = v.subseq(from, end)
val add = sub + n
var back = add.length == sub.length + 1
for (i <- 0 until sub.length) {
back &&= add(i) == sub(i)
}
back && add(sub.length) == n
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
+ "update subseq" in {
+ val prop = property { (v: Vector[Int], from: Int, end: Int, mi: Int) =>
+ try {
+ val sub = v.subseq(from, end)
+ val add = sub(mi) = 42
+
+ var back = add.length == (if (mi == add.length) sub.length + 1 else sub.length)
+ for (i <- 0 until sub.length; if i != mi) {
+ back &&= add(i) == sub(i)
+ }
+ back && add(mi) == 42
+ } catch {
+ case _:IndexOutOfBoundsException => from < 0 || end >= v.length || !(0 to (end - from) contains mi)
+ case _:IllegalArgumentException => end <= from
+ }
+ }
+
+ prop must pass
+ }
+
"map on subseq" in {
val prop = property { (v: Vector[Int], from: Int, end: Int, f: (Int)=>Int) =>
try {
val sub = v.subseq(from, end)
val mapped = sub map f
var back = mapped.length == sub.length
for (i <- 0 until sub.length) {
back &&= mapped(i) == f(sub(i))
}
back
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"implement zip" in {
val prop = property { (first: Vector[Int], second: Vector[Double]) =>
val zip = first zip second
var back = zip.length == Math.min(first.length, second.length)
for (i <- 0 until zip.length) {
var (left, right) = zip(i)
back &&= (left == first(i) && right == second(i))
}
back
}
prop must pass
}
"implement zipWithIndex" in {
val prop = property { vec: Vector[Int] =>
val zip = vec.zipWithIndex
var back = zip.length == vec.length
for (i <- 0 until zip.length) {
val (elem, index) = zip(i)
back &&= (index == i && elem == vec(i))
}
back
}
prop must pass
}
"implement equals" in {
- val prop = property { list: List[Int] =>
- val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
- val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
+ {
+ val prop = property { list: List[Int] =>
+ val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
+ val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
+
+ vecA == vecB
+ }
- vecA == vecB
+ prop must pass
}
- prop must pass
+ {
+ val prop = property { (vecA: Vector[Int], vecB: Vector[Int]) =>
+ vecA.length != vecB.length ==> (vecA != vecB)
+ }
+
+ prop must pass
+ }
+
+ {
+ val prop = property { (listA: List[Int], listB: List[Int]) =>
+ val vecA = listA.foldLeft(Vector[Int]()) { _ + _ }
+ val vecB = listB.foldLeft(Vector[Int]()) { _ + _ }
+
+ listA != listB ==> (vecA != vecB)
+ }
+
+ prop must pass
+ }
+
+ {
+ val prop = property { (vec: Vector[Int], data: Int) => vec != data }
+
+ prop must pass
+ }
}
"implement hashCode" in {
val prop = property { list: List[Int] =>
val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
vecA.hashCode == vecB.hashCode
}
prop must pass
}
"implement extractor" in {
val vec1 = Vector(1, 2, 3)
vec1 must beLike {
case Vector(a, b, c) => (a, b, c) == (1, 2, 3)
}
val vec2 = Vector("daniel", "chris", "joseph")
vec2 must beLike {
case Vector(a, b, c) => (a, b, c) == ("daniel", "chris", "joseph")
}
}
}
}
|
djspiewak/scala-collections
|
cd9a39bf7b5e631ace3968406d2d784d23161881
|
Replaced tabs with spaces
|
diff --git a/src/main/scala/com/codecommit/collection/Vector.scala b/src/main/scala/com/codecommit/collection/Vector.scala
index 670bdd4..5bbfc96 100644
--- a/src/main/scala/com/codecommit/collection/Vector.scala
+++ b/src/main/scala/com/codecommit/collection/Vector.scala
@@ -1,351 +1,351 @@
/**
Copyright (c) 2007-2008, Rich Hickey
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Clojure nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**/
package com.codecommit.collection
import Vector._
/**
* A straight port of Clojure's <code>PersistentVector</code> class.
*
* @author Daniel Spiewak
* @author Rich Hickey
*/
class Vector[+T] private (val length: Int, shift: Int, root: Array[AnyRef], tail: Array[AnyRef]) extends RandomAccessSeq[T] { outer =>
private val tailOff = length - tail.length
/*
* The design of this data structure inherantly requires heterogenous arrays.
* It is *possible* to design around this, but the result is comparatively
* quite inefficient. With respect to this fact, I have left the original
* (somewhat dynamically-typed) implementation in place.
*/
private[collection] def this() = this(0, 5, EmptyArray, EmptyArray)
def apply(i: Int): T = {
if (i >= 0 && i < length) {
if (i >= tailOff) {
- tail(i & 0x01f).asInstanceOf[T]
+ tail(i & 0x01f).asInstanceOf[T]
} else {
var arr = root
var level = shift
while (level > 0) {
arr = arr((i >>> level) & 0x01f).asInstanceOf[Array[AnyRef]]
level -= 5
}
arr(i & 0x01f).asInstanceOf[T]
}
- } else throw new IndexOutOfBoundsException(i.toString)
+ } else throw new IndexOutOfBoundsException(i.toString)
}
def update[A >: T](i: Int, obj: A): Vector[A] = {
if (i >= 0 && i < length) {
if (i >= tailOff) {
val newTail = new Array[AnyRef](tail.length)
Array.copy(tail, 0, newTail, 0, tail.length)
newTail(i & 0x01f) = obj.asInstanceOf[AnyRef]
new Vector[A](length, shift, root, newTail)
- } else {
+ } else {
new Vector[A](length, shift, doAssoc(shift, root, i, obj), tail)
}
- } else if (i == length) {
- this + obj
+ } else if (i == length) {
+ this + obj
} else throw new IndexOutOfBoundsException(i.toString)
}
private def doAssoc[A >: T](level: Int, arr: Array[AnyRef], i: Int, obj: A): Array[AnyRef] = {
val ret = new Array[AnyRef](arr.length)
Array.copy(arr, 0, ret, 0, arr.length)
if (level == 0) {
ret(i & 0x01f) = obj.asInstanceOf[AnyRef]
- } else {
+ } else {
val subidx = (i >>> level) & 0x01f
ret(subidx) = doAssoc(level - 5, arr(subidx).asInstanceOf[Array[AnyRef]], i, obj)
- }
+ }
ret
}
override def ++[A >: T](other: Iterable[A]) = other.foldLeft(this:Vector[A]) { _ + _ }
def +[A >: T](obj: A): Vector[A] = {
if (tail.length < 32) {
val newTail = new Array[AnyRef](tail.length + 1)
Array.copy(tail, 0, newTail, 0, tail.length)
newTail(tail.length) = obj.asInstanceOf[AnyRef]
new Vector[A](length + 1, shift, root, newTail)
- } else {
+ } else {
var (newRoot, expansion) = pushTail(shift - 5, root, tail, null)
var newShift = shift
if (expansion != null) {
newRoot = array(newRoot, expansion)
newShift += 5
}
new Vector[A](length + 1, newShift, newRoot, array(obj.asInstanceOf[AnyRef]))
}
}
private def pushTail(level: Int, arr: Array[AnyRef], tailNode: Array[AnyRef], expansion: AnyRef): (Array[AnyRef], AnyRef) = {
val newChild = if (level == 0) tailNode else {
val (newChild, subExpansion) = pushTail(level - 5, arr(arr.length - 1).asInstanceOf[Array[AnyRef]], tailNode, expansion)
if (subExpansion == null) {
val ret = new Array[AnyRef](arr.length)
Array.copy(arr, 0, ret, 0, arr.length)
ret(arr.length - 1) = newChild
return (ret, null)
- } else subExpansion
- }
+ } else subExpansion
+ }
// expansion
if (arr.length == 32) {
(arr, array(newChild))
} else {
val ret = new Array[AnyRef](arr.length + 1)
Array.copy(arr, 0, ret, 0, arr.length)
ret(arr.length) = newChild
(ret, null)
}
}
/**
* Removes the <i>tail</i> element of this vector.
*/
def pop: Vector[T] = {
if (length == 0) {
throw new IllegalStateException("Can't pop empty vector")
} else if (length == 1) {
EmptyVector
} else if (tail.length > 1) {
val newTail = new Array[AnyRef](tail.length - 1)
Array.copy(tail, 0, newTail, 0, newTail.length)
new Vector[T](length - 1, shift, root, newTail)
- } else {
+ } else {
var (newRoot, pTail) = popTail(shift - 5, root, null)
var newShift = shift
if (newRoot == null) {
newRoot = EmptyArray
}
if (shift > 5 && newRoot.length == 1) {
newRoot = newRoot(0).asInstanceOf[Array[AnyRef]]
newShift -= 5
}
new Vector[T](length - 1, newShift, newRoot, pTail.asInstanceOf[Array[AnyRef]])
}
}
private def popTail(shift: Int, arr: Array[AnyRef], pTail: AnyRef): (Array[AnyRef], AnyRef) = {
val newPTail = if (shift > 0) {
val (newChild, subPTail) = popTail(shift - 5, arr(arr.length - 1).asInstanceOf[Array[AnyRef]], pTail)
if (newChild != null) {
val ret = new Array[AnyRef](arr.length)
Array.copy(arr, 0, ret, 0, arr.length)
ret(arr.length - 1) = newChild
return (ret, subPTail)
- }
+ }
subPTail
- } else if (shift == 0) {
+ } else if (shift == 0) {
arr(arr.length - 1)
} else pTail
// contraction
if (arr.length == 1) {
(null, newPTail)
} else {
val ret = new Array[AnyRef](arr.length - 1)
Array.copy(arr, 0, ret, 0, ret.length)
(ret, newPTail)
}
}
override def filter(p: (T)=>Boolean) = {
var back = new Vector[T]
var i = 0
while (i < length) {
val e = apply(i)
if (p(e)) back += e
i += 1
}
back
}
override def flatMap[A](f: (T)=>Iterable[A]) = {
var back = new Vector[A]
var i = 0
while (i < length) {
f(apply(i)) foreach { back += _ }
i += 1
}
back
}
override def map[A](f: (T)=>A) = {
var back = new Vector[A]
var i = 0
while (i < length) {
back += f(apply(i))
i += 1
}
back
}
override def reverse: Vector[T] = new VectorProjection[T] {
override val length = outer.length
override def apply(i: Int) = outer.apply(length - i - 1)
}
override def subseq(from: Int, end: Int) = subVector(from, end)
def subVector(from: Int, end: Int): Vector[T] = {
if (from < 0) {
throw new IndexOutOfBoundsException(from.toString)
} else if (end >= length) {
throw new IndexOutOfBoundsException(end.toString)
} else if (end <= from) {
throw new IllegalArgumentException("Invalid range: " + from + ".." + end)
} else {
new VectorProjection[T] {
override val length = end - from
override def apply(i: Int) = outer.apply(i + from)
}
}
}
def zip[A](that: Vector[A]) = {
var back = new Vector[(T, A)]
var i = 0
val limit = Math.min(length, that.length)
while (i < limit) {
back += (apply(i), that(i))
i += 1
}
back
}
def zipWithIndex = {
var back = new Vector[(T, Int)]
var i = 0
while (i < length) {
back += (apply(i), i)
i += 1
}
back
}
override def equals(other: Any) = other match {
case vec:Vector[T] => {
var back = length == vec.length
var i = 0
while (i < length) {
back &&= apply(i) == vec.apply(i)
i += 1
}
back
}
case _ => false
}
override def hashCode = foldLeft(0) { _ ^ _.hashCode }
}
object Vector {
private[collection] val EmptyArray = new Array[AnyRef](0)
def apply[T](elems: T*) = elems.foldLeft(EmptyVector:Vector[T]) { _ + _ }
def unapplySeq[T](vec: Vector[T]): Option[Seq[T]] = Some(vec)
@inline
private[collection] def array(elems: AnyRef*) = {
val back = new Array[AnyRef](elems.length)
Array.copy(elems, 0, back, 0, back.length)
back
}
}
object EmptyVector extends Vector[Nothing]
private[collection] abstract class VectorProjection[+T] extends Vector[T] {
override val length: Int
override def apply(i: Int): T
override def +[A >: T](e: A) = innerCopy + e
override def update[A >: T](i: Int, e: A) = {
if (i < 0) {
throw new IndexOutOfBoundsException(i.toString)
} else if (i > length) {
throw new IndexOutOfBoundsException(i.toString)
} else innerCopy(i) = e
}
private lazy val innerCopy = foldLeft(EmptyVector:Vector[T]) { _ + _ }
}
|
djspiewak/scala-collections
|
63f72d1cc116c946c48bed1e088dec926fcb6311
|
Added a little more attribution
|
diff --git a/src/main/scala/com/codecommit/collection/HashTrie.scala b/src/main/scala/com/codecommit/collection/HashTrie.scala
index a4b1e9c..cb288a7 100644
--- a/src/main/scala/com/codecommit/collection/HashTrie.scala
+++ b/src/main/scala/com/codecommit/collection/HashTrie.scala
@@ -1,354 +1,355 @@
/**
Copyright (c) 2007-2008, Rich Hickey
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Clojure nor the names of its contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
**/
package com.codecommit.collection
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
+ * @author Rich Hickey
*/
final class HashTrie[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashTrie(root(0, key, key.hashCode) = value)
def -(key: K) = new HashTrie(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashTrie[K, A] = new HashTrie(new EmptyNode[K])
def diagnose = root.toString
}
object HashTrie {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashTrie[K, V]) { _ + _ }
def unapplySeq[K, V](map: HashTrie[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](shift: Int, key: K, hash: Int, value: V) = new LeafNode(key, hash, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] class LeafNode[K, +V](key: K, hash: Int, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](shift: Int, key: K, hash: Int, value: A) = {
if (this.key == key) {
if (this.value == value) this else new LeafNode(key, hash, value)
} else if (this.hash == hash) {
new CollisionNode(hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
def this(hash: Int, pairs: (K, V)*) = this(hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for ((k, v) <- bucket) yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == bucket.length) this else {
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(key, hash, value)
} else new CollisionNode(hash, newBucket)
}
}
def elements = bucket.elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else {
val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = new LeafNode(key, hash, value)
val newBits = bits | mask
if (newBits == ~0) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node == table(i)) {
this
} else if (node.isInstanceOf[EmptyNode[_]]) {
if (size == 1) new EmptyNode[K] else {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](if (i + 1 == table.length) table.length - 1 else table.length)
Array.copy(table, 0, newTable, 0, newTable.length)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
}
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
val iters = table flatMap { n =>
if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
}
iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
val table = new Array[Node[K, V]](pairs.foldLeft(0) { (x, pair) =>
val (_, hash, _) = pair
Math.max(x, (hash >>> shift) & 0x01f)
} + 1)
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
table(i) = (table(i)(shift + 5, key, hash) = value)
} else {
table(i) = new LeafNode(key, hash, value)
}
bits | mask
}
new BitmappedNode(shift)(table, bits)
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = table((hash >>> shift) & 0x01f)(key, hash)
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val node = table(i).remove(key, hash)
if (node == table(i)) this else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, ~0 ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
}
def elements = {
val iters = table map { _.elements }
iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
}
override def toString = "FullNode(" + table.foldLeft("") { _.toString + ", " + _.toString } + ")"
}
|
djspiewak/scala-collections
|
ca63f092168c868485e3c7fd094b5f0f1413102f
|
Added new copyright notice (BSD license)
|
diff --git a/src/main/scala/com/codecommit/collection/HashTrie.scala b/src/main/scala/com/codecommit/collection/HashTrie.scala
index 9cf586a..a4b1e9c 100644
--- a/src/main/scala/com/codecommit/collection/HashTrie.scala
+++ b/src/main/scala/com/codecommit/collection/HashTrie.scala
@@ -1,320 +1,354 @@
+/**
+ Copyright (c) 2007-2008, Rich Hickey
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+ * Neither the name of Clojure nor the names of its contributors
+ may be used to endorse or promote products derived from this
+ software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ **/
+
package com.codecommit.collection
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
*/
final class HashTrie[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashTrie(root(0, key, key.hashCode) = value)
def -(key: K) = new HashTrie(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashTrie[K, A] = new HashTrie(new EmptyNode[K])
def diagnose = root.toString
}
object HashTrie {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashTrie[K, V]) { _ + _ }
def unapplySeq[K, V](map: HashTrie[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](shift: Int, key: K, hash: Int, value: V) = new LeafNode(key, hash, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] class LeafNode[K, +V](key: K, hash: Int, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](shift: Int, key: K, hash: Int, value: A) = {
if (this.key == key) {
if (this.value == value) this else new LeafNode(key, hash, value)
} else if (this.hash == hash) {
new CollisionNode(hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
def this(hash: Int, pairs: (K, V)*) = this(hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for ((k, v) <- bucket) yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == bucket.length) this else {
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(key, hash, value)
} else new CollisionNode(hash, newBucket)
}
}
def elements = bucket.elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else {
val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = new LeafNode(key, hash, value)
val newBits = bits | mask
if (newBits == ~0) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node == table(i)) {
this
} else if (node.isInstanceOf[EmptyNode[_]]) {
if (size == 1) new EmptyNode[K] else {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](if (i + 1 == table.length) table.length - 1 else table.length)
Array.copy(table, 0, newTable, 0, newTable.length)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
}
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
val iters = table flatMap { n =>
if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
}
iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
val table = new Array[Node[K, V]](pairs.foldLeft(0) { (x, pair) =>
val (_, hash, _) = pair
Math.max(x, (hash >>> shift) & 0x01f)
} + 1)
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
table(i) = (table(i)(shift + 5, key, hash) = value)
} else {
table(i) = new LeafNode(key, hash, value)
}
bits | mask
}
new BitmappedNode(shift)(table, bits)
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = table((hash >>> shift) & 0x01f)(key, hash)
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val node = table(i).remove(key, hash)
if (node == table(i)) this else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, ~0 ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
}
def elements = {
val iters = table map { _.elements }
iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
}
override def toString = "FullNode(" + table.foldLeft("") { _.toString + ", " + _.toString } + ")"
}
diff --git a/src/main/scala/com/codecommit/collection/Vector.scala b/src/main/scala/com/codecommit/collection/Vector.scala
index dba0355..670bdd4 100644
--- a/src/main/scala/com/codecommit/collection/Vector.scala
+++ b/src/main/scala/com/codecommit/collection/Vector.scala
@@ -1,327 +1,351 @@
-/*
- * Copyright (c) Rich Hickey. All rights reserved.
- * The use and distribution terms for this software are covered by the
- * Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
- * which can be found in the file CPL.TXT at the root of this distribution.
- * By using this software in any fashion, you are agreeing to be bound by
- * the terms of this license.
- * You must not remove this notice, or any other, from this software.
- */
+/**
+ Copyright (c) 2007-2008, Rich Hickey
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+ * Neither the name of Clojure nor the names of its contributors
+ may be used to endorse or promote products derived from this
+ software without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ **/
package com.codecommit.collection
import Vector._
/**
* A straight port of Clojure's <code>PersistentVector</code> class.
*
* @author Daniel Spiewak
* @author Rich Hickey
*/
class Vector[+T] private (val length: Int, shift: Int, root: Array[AnyRef], tail: Array[AnyRef]) extends RandomAccessSeq[T] { outer =>
private val tailOff = length - tail.length
/*
* The design of this data structure inherantly requires heterogenous arrays.
* It is *possible* to design around this, but the result is comparatively
* quite inefficient. With respect to this fact, I have left the original
* (somewhat dynamically-typed) implementation in place.
*/
private[collection] def this() = this(0, 5, EmptyArray, EmptyArray)
def apply(i: Int): T = {
if (i >= 0 && i < length) {
if (i >= tailOff) {
tail(i & 0x01f).asInstanceOf[T]
} else {
var arr = root
var level = shift
while (level > 0) {
arr = arr((i >>> level) & 0x01f).asInstanceOf[Array[AnyRef]]
level -= 5
}
arr(i & 0x01f).asInstanceOf[T]
}
} else throw new IndexOutOfBoundsException(i.toString)
}
def update[A >: T](i: Int, obj: A): Vector[A] = {
if (i >= 0 && i < length) {
if (i >= tailOff) {
val newTail = new Array[AnyRef](tail.length)
Array.copy(tail, 0, newTail, 0, tail.length)
newTail(i & 0x01f) = obj.asInstanceOf[AnyRef]
new Vector[A](length, shift, root, newTail)
} else {
new Vector[A](length, shift, doAssoc(shift, root, i, obj), tail)
}
} else if (i == length) {
this + obj
} else throw new IndexOutOfBoundsException(i.toString)
}
private def doAssoc[A >: T](level: Int, arr: Array[AnyRef], i: Int, obj: A): Array[AnyRef] = {
val ret = new Array[AnyRef](arr.length)
Array.copy(arr, 0, ret, 0, arr.length)
if (level == 0) {
ret(i & 0x01f) = obj.asInstanceOf[AnyRef]
} else {
val subidx = (i >>> level) & 0x01f
ret(subidx) = doAssoc(level - 5, arr(subidx).asInstanceOf[Array[AnyRef]], i, obj)
}
ret
}
override def ++[A >: T](other: Iterable[A]) = other.foldLeft(this:Vector[A]) { _ + _ }
def +[A >: T](obj: A): Vector[A] = {
if (tail.length < 32) {
val newTail = new Array[AnyRef](tail.length + 1)
Array.copy(tail, 0, newTail, 0, tail.length)
newTail(tail.length) = obj.asInstanceOf[AnyRef]
new Vector[A](length + 1, shift, root, newTail)
} else {
var (newRoot, expansion) = pushTail(shift - 5, root, tail, null)
var newShift = shift
if (expansion != null) {
newRoot = array(newRoot, expansion)
newShift += 5
}
new Vector[A](length + 1, newShift, newRoot, array(obj.asInstanceOf[AnyRef]))
}
}
private def pushTail(level: Int, arr: Array[AnyRef], tailNode: Array[AnyRef], expansion: AnyRef): (Array[AnyRef], AnyRef) = {
val newChild = if (level == 0) tailNode else {
val (newChild, subExpansion) = pushTail(level - 5, arr(arr.length - 1).asInstanceOf[Array[AnyRef]], tailNode, expansion)
if (subExpansion == null) {
val ret = new Array[AnyRef](arr.length)
Array.copy(arr, 0, ret, 0, arr.length)
ret(arr.length - 1) = newChild
return (ret, null)
} else subExpansion
}
// expansion
if (arr.length == 32) {
(arr, array(newChild))
} else {
val ret = new Array[AnyRef](arr.length + 1)
Array.copy(arr, 0, ret, 0, arr.length)
ret(arr.length) = newChild
(ret, null)
}
}
/**
* Removes the <i>tail</i> element of this vector.
*/
def pop: Vector[T] = {
if (length == 0) {
throw new IllegalStateException("Can't pop empty vector")
} else if (length == 1) {
EmptyVector
} else if (tail.length > 1) {
val newTail = new Array[AnyRef](tail.length - 1)
Array.copy(tail, 0, newTail, 0, newTail.length)
new Vector[T](length - 1, shift, root, newTail)
} else {
var (newRoot, pTail) = popTail(shift - 5, root, null)
var newShift = shift
if (newRoot == null) {
newRoot = EmptyArray
}
if (shift > 5 && newRoot.length == 1) {
newRoot = newRoot(0).asInstanceOf[Array[AnyRef]]
newShift -= 5
}
new Vector[T](length - 1, newShift, newRoot, pTail.asInstanceOf[Array[AnyRef]])
}
}
private def popTail(shift: Int, arr: Array[AnyRef], pTail: AnyRef): (Array[AnyRef], AnyRef) = {
val newPTail = if (shift > 0) {
val (newChild, subPTail) = popTail(shift - 5, arr(arr.length - 1).asInstanceOf[Array[AnyRef]], pTail)
if (newChild != null) {
val ret = new Array[AnyRef](arr.length)
Array.copy(arr, 0, ret, 0, arr.length)
ret(arr.length - 1) = newChild
return (ret, subPTail)
}
subPTail
} else if (shift == 0) {
arr(arr.length - 1)
} else pTail
// contraction
if (arr.length == 1) {
(null, newPTail)
} else {
val ret = new Array[AnyRef](arr.length - 1)
Array.copy(arr, 0, ret, 0, ret.length)
(ret, newPTail)
}
}
override def filter(p: (T)=>Boolean) = {
var back = new Vector[T]
var i = 0
while (i < length) {
val e = apply(i)
if (p(e)) back += e
i += 1
}
back
}
override def flatMap[A](f: (T)=>Iterable[A]) = {
var back = new Vector[A]
var i = 0
while (i < length) {
f(apply(i)) foreach { back += _ }
i += 1
}
back
}
override def map[A](f: (T)=>A) = {
var back = new Vector[A]
var i = 0
while (i < length) {
back += f(apply(i))
i += 1
}
back
}
override def reverse: Vector[T] = new VectorProjection[T] {
override val length = outer.length
override def apply(i: Int) = outer.apply(length - i - 1)
}
override def subseq(from: Int, end: Int) = subVector(from, end)
def subVector(from: Int, end: Int): Vector[T] = {
if (from < 0) {
throw new IndexOutOfBoundsException(from.toString)
} else if (end >= length) {
throw new IndexOutOfBoundsException(end.toString)
} else if (end <= from) {
throw new IllegalArgumentException("Invalid range: " + from + ".." + end)
} else {
new VectorProjection[T] {
override val length = end - from
override def apply(i: Int) = outer.apply(i + from)
}
}
}
def zip[A](that: Vector[A]) = {
var back = new Vector[(T, A)]
var i = 0
val limit = Math.min(length, that.length)
while (i < limit) {
back += (apply(i), that(i))
i += 1
}
back
}
def zipWithIndex = {
var back = new Vector[(T, Int)]
var i = 0
while (i < length) {
back += (apply(i), i)
i += 1
}
back
}
override def equals(other: Any) = other match {
case vec:Vector[T] => {
var back = length == vec.length
var i = 0
while (i < length) {
back &&= apply(i) == vec.apply(i)
i += 1
}
back
}
case _ => false
}
override def hashCode = foldLeft(0) { _ ^ _.hashCode }
}
object Vector {
private[collection] val EmptyArray = new Array[AnyRef](0)
def apply[T](elems: T*) = elems.foldLeft(EmptyVector:Vector[T]) { _ + _ }
def unapplySeq[T](vec: Vector[T]): Option[Seq[T]] = Some(vec)
@inline
private[collection] def array(elems: AnyRef*) = {
val back = new Array[AnyRef](elems.length)
Array.copy(elems, 0, back, 0, back.length)
back
}
}
object EmptyVector extends Vector[Nothing]
private[collection] abstract class VectorProjection[+T] extends Vector[T] {
override val length: Int
override def apply(i: Int): T
override def +[A >: T](e: A) = innerCopy + e
override def update[A >: T](i: Int, e: A) = {
if (i < 0) {
throw new IndexOutOfBoundsException(i.toString)
} else if (i > length) {
throw new IndexOutOfBoundsException(i.toString)
} else innerCopy(i) = e
}
private lazy val innerCopy = foldLeft(EmptyVector:Vector[T]) { _ + _ }
}
|
djspiewak/scala-collections
|
3d7c489f1647673461ede4441ff5bbb8ed22a531
|
Changed to reflect release of Specs 1.4.0
|
diff --git a/build.yaml b/build.yaml
index 758f83b..a00f79f 100644
--- a/build.yaml
+++ b/build.yaml
@@ -1,2 +1,2 @@
scala.check: 1.4-scSNAPSHOT
-scala.specs: 1.3.2-SNAPSHOT
+scala.specs: 1.4.0
|
djspiewak/scala-collections
|
8483498551d86868132529ebd0ad6b495c21c635
|
Added foreach benchmarks
|
diff --git a/src/test/scala/HashPerf.scala b/src/test/scala/HashPerf.scala
index 8c8fd6a..b12eefa 100644
--- a/src/test/scala/HashPerf.scala
+++ b/src/test/scala/HashPerf.scala
@@ -1,166 +1,246 @@
import com.codecommit.collection.HashTrie
import scala.collection.immutable.TreeHashMap
object HashPerf {
import PerfLib._
def main(args: Array[String]) {
println()
val data = "The quick brown fox jumped over the lazy red dog"
//==========================================================================
{
title("Fill 100000 Random Keys")
val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
indexes(i) = Math.random.toString
}
val hashMapOp = "HashTrie" -> time {
var map = HashTrie[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
val mapOp = "Map" -> time {
var map = Map[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
hashMapOp compare mapOp
val intMapOp = "TreeHashMap" -> time {
var map = TreeHashMap[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
hashMapOp compare intMapOp
val mutableMapOp = "mutable.Map" -> time {
val map = scala.collection.mutable.Map[String, String]()
var i = 0
while (i < indexes.length) {
map(indexes(i)) = data
i += 1
}
}
hashMapOp compare mutableMapOp
div('=')
}
println()
//==========================================================================
{
title("Read 100000 Random Keys")
val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
indexes(i) = Math.random.toString
}
var hashMap = HashTrie[String, String]()
{
var i = 0
while (i < indexes.length) {
hashMap = hashMap(indexes(i)) = data
i += 1
}
}
var immutableMap = Map[String, String]()
{
var i = 0
while (i < indexes.length) {
immutableMap = immutableMap(indexes(i)) = data
i += 1
}
}
val hashMapOp = "HashTrie" -> time {
var i = 0
while (i < indexes.length) {
hashMap(indexes(i))
i += 1
}
}
val mapOp = "Map" -> time {
var i = 0
while (i < indexes.length) {
immutableMap(indexes(i))
i += 1
}
}
hashMapOp compare mapOp
var intMap = TreeHashMap[String, String]()
{
var i = 0
while (i < indexes.length) {
intMap = intMap(indexes(i)) = data
i += 1
}
}
val intMapOp = "TreeHashMap" -> time {
var i = 0
while (i < indexes.length) {
intMap(indexes(i))
i += 1
}
}
hashMapOp compare intMapOp
val mutableMap = scala.collection.mutable.Map[String, String]()
{
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i)) = data
i += 1
}
}
val mutableMapOp = "mutable.Map" -> time {
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i))
i += 1
}
}
hashMapOp compare mutableMapOp
div('=')
}
+
+ println()
+
+ //==========================================================================
+ {
+ title("Loop Over 100000 Random Keys (#foreach)")
+
+ val indexes = new Array[String](100000)
+ for (i <- 0 until indexes.length) {
+ indexes(i) = Math.random.toString
+ }
+
+ var hashMap = HashTrie[String, String]()
+
+ {
+ var i = 0
+
+ while (i < indexes.length) {
+ hashMap = hashMap(indexes(i)) = data
+ i += 1
+ }
+ }
+
+ var immutableMap = Map[String, String]()
+
+ {
+ var i = 0
+
+ while (i < indexes.length) {
+ immutableMap = immutableMap(indexes(i)) = data
+ i += 1
+ }
+ }
+
+
+ val hashMapOp = "HashTrie" -> time {
+ hashMap foreach { case (k, v) => () }
+ }
+
+ val mapOp = "Map" -> time {
+ immutableMap foreach { case (k, v) => () }
+ }
+
+ hashMapOp compare mapOp
+
+ var intMap = TreeHashMap[String, String]()
+
+ {
+ var i = 0
+
+ while (i < indexes.length) {
+ intMap = intMap(indexes(i)) = data
+ i += 1
+ }
+ }
+
+ val intMapOp = "TreeHashMap" -> time {
+ intMap foreach { case (k, v) => () }
+ }
+
+ hashMapOp compare intMapOp
+
+ val mutableMap = scala.collection.mutable.Map[String, String]()
+
+ {
+ var i = 0
+
+ while (i < indexes.length) {
+ mutableMap(indexes(i)) = data
+ i += 1
+ }
+ }
+
+ val mutableMapOp = "mutable.Map" -> time {
+ mutableMap foreach { case (k, v) => () }
+ }
+
+ hashMapOp compare mutableMapOp
+ div('=')
+ }
}
}
|
djspiewak/scala-collections
|
73ef058bc268dd2bbda86cbd0cd2d91845ed6944
|
Corrected deconstructor
|
diff --git a/src/main/scala/com/codecommit/collection/HashTrie.scala b/src/main/scala/com/codecommit/collection/HashTrie.scala
index 994443e..9cf586a 100644
--- a/src/main/scala/com/codecommit/collection/HashTrie.scala
+++ b/src/main/scala/com/codecommit/collection/HashTrie.scala
@@ -1,320 +1,320 @@
package com.codecommit.collection
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
*/
final class HashTrie[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashTrie(root(0, key, key.hashCode) = value)
def -(key: K) = new HashTrie(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashTrie[K, A] = new HashTrie(new EmptyNode[K])
def diagnose = root.toString
}
object HashTrie {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashTrie[K, V]) { _ + _ }
- def unapply[K, V](map: HashTrie[K, V]) = map.toSeq
+ def unapplySeq[K, V](map: HashTrie[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](shift: Int, key: K, hash: Int, value: V) = new LeafNode(key, hash, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] class LeafNode[K, +V](key: K, hash: Int, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](shift: Int, key: K, hash: Int, value: A) = {
if (this.key == key) {
if (this.value == value) this else new LeafNode(key, hash, value)
} else if (this.hash == hash) {
new CollisionNode(hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
def this(hash: Int, pairs: (K, V)*) = this(hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for ((k, v) <- bucket) yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == bucket.length) this else {
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(key, hash, value)
} else new CollisionNode(hash, newBucket)
}
}
def elements = bucket.elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else {
val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = new LeafNode(key, hash, value)
val newBits = bits | mask
if (newBits == ~0) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node == table(i)) {
this
} else if (node.isInstanceOf[EmptyNode[_]]) {
if (size == 1) new EmptyNode[K] else {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](if (i + 1 == table.length) table.length - 1 else table.length)
Array.copy(table, 0, newTable, 0, newTable.length)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
}
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
val iters = table flatMap { n =>
if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
}
iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
val table = new Array[Node[K, V]](pairs.foldLeft(0) { (x, pair) =>
val (_, hash, _) = pair
Math.max(x, (hash >>> shift) & 0x01f)
} + 1)
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
table(i) = (table(i)(shift + 5, key, hash) = value)
} else {
table(i) = new LeafNode(key, hash, value)
}
bits | mask
}
new BitmappedNode(shift)(table, bits)
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = table((hash >>> shift) & 0x01f)(key, hash)
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val node = (table(i)(shift + 5, key, hash) = value)
if (node == table(i)) this else {
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val node = table(i).remove(key, hash)
if (node == table(i)) this else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, ~0 ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
}
def elements = {
val iters = table map { _.elements }
iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
}
override def toString = "FullNode(" + table.foldLeft("") { _.toString + ", " + _.toString } + ")"
}
|
djspiewak/scala-collections
|
f8f6f7c9f50faf2567a5261a4013d38a5accde6a
|
Some optimizations and common-case short-circuits
|
diff --git a/src/main/scala/com/codecommit/collection/HashTrie.scala b/src/main/scala/com/codecommit/collection/HashTrie.scala
index 6c797cc..994443e 100644
--- a/src/main/scala/com/codecommit/collection/HashTrie.scala
+++ b/src/main/scala/com/codecommit/collection/HashTrie.scala
@@ -1,302 +1,320 @@
package com.codecommit.collection
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
*/
final class HashTrie[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashTrie(root(0, key, key.hashCode) = value)
def -(key: K) = new HashTrie(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashTrie[K, A] = new HashTrie(new EmptyNode[K])
def diagnose = root.toString
}
object HashTrie {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashTrie[K, V]) { _ + _ }
def unapply[K, V](map: HashTrie[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](shift: Int, key: K, hash: Int, value: V) = new LeafNode(key, hash, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] class LeafNode[K, +V](key: K, hash: Int, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](shift: Int, key: K, hash: Int, value: A) = {
if (this.key == key) {
- new LeafNode(key, hash, value)
+ if (this.value == value) this else new LeafNode(key, hash, value)
} else if (this.hash == hash) {
new CollisionNode(hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
def this(hash: Int, pairs: (K, V)*) = this(hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
- val newBucket = for {
- (k, v) <- bucket
- } yield {
+ val newBucket = for ((k, v) <- bucket) yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
- if (newBucket.length == 1) {
- val (key, value) = newBucket.head
- new LeafNode(key, hash, value)
- } else new CollisionNode(hash, newBucket)
+ if (newBucket.length == bucket.length) this else {
+ if (newBucket.length == 1) {
+ val (key, value) = newBucket.head
+ new LeafNode(key, hash, value)
+ } else new CollisionNode(hash, newBucket)
+ }
}
- def elements = (bucket map { case (k, v) => (k, v) }).elements
+ def elements = bucket.elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
- import BitmappedNode._
-
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
- // TODO
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
- val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
- Array.copy(table, 0, newTable, 0, table.length)
-
- val newBits = addToTable(shift)(newTable, bits)(key, hash, value)
-
- if (newBits == ~0) {
- new FullNode(shift)(newTable)
+ if ((bits & mask) == mask) {
+ val node = (table(i)(shift + 5, key, hash) = value)
+
+ if (node == table(i)) this else {
+ val newTable = new Array[Node[K, A]](table.length)
+ Array.copy(table, 0, newTable, 0, table.length)
+
+ newTable(i) = node
+
+ new BitmappedNode(shift)(newTable, bits)
+ }
} else {
- new BitmappedNode(shift)(newTable, newBits)
+ val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
+ Array.copy(table, 0, newTable, 0, table.length)
+
+ newTable(i) = new LeafNode(key, hash, value)
+
+ val newBits = bits | mask
+ if (newBits == ~0) {
+ new FullNode(shift)(newTable)
+ } else {
+ new BitmappedNode(shift)(newTable, newBits)
+ }
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
- if (node.isInstanceOf[EmptyNode[_]]) {
- val adjustedBits = bits ^ mask
- val log = Math.log(adjustedBits) / Math.log(2)
-
- if (log.toInt.toDouble == log) { // last one
- table(log.toInt)
- } else {
- val newTable = new Array[Node[K, V]](if (i + 1 == table.length) table.length - 1 else table.length)
- Array.copy(table, 0, newTable, 0, newTable.length)
-
- newTable(i) = null
+ if (node == table(i)) {
+ this
+ } else if (node.isInstanceOf[EmptyNode[_]]) {
+ if (size == 1) new EmptyNode[K] else {
+ val adjustedBits = bits ^ mask
+ val log = Math.log(adjustedBits) / Math.log(2)
- new BitmappedNode(shift)(newTable, adjustedBits)
+ if (log.toInt.toDouble == log) { // last one
+ table(log.toInt)
+ } else {
+ val newTable = new Array[Node[K, V]](if (i + 1 == table.length) table.length - 1 else table.length)
+ Array.copy(table, 0, newTable, 0, newTable.length)
+
+ newTable(i) = null
+
+ new BitmappedNode(shift)(newTable, adjustedBits)
+ }
}
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
+
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
val iters = table flatMap { n =>
if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
}
iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
val table = new Array[Node[K, V]](pairs.foldLeft(0) { (x, pair) =>
val (_, hash, _) = pair
Math.max(x, (hash >>> shift) & 0x01f)
} + 1)
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
- addToTable(shift)(table, bits)(key, hash, value)
- }
-
- new BitmappedNode(shift)(table, bits)
- }
-
- private def addToTable[K, V](shift: Int)(table: Array[Node[K, V]], bits: Int)(key: K, hash: Int, value: V) = {
- val i = (hash >>> shift) & 0x01f
- val mask = 1 << i
+ val i = (hash >>> shift) & 0x01f
+ val mask = 1 << i
+
+ if ((bits & mask) == mask) {
+ table(i) = (table(i)(shift + 5, key, hash) = value)
+ } else {
+ table(i) = new LeafNode(key, hash, value)
+ }
- if ((bits & mask) == mask) {
- table(i) = (table(i)(shift + 5, key, hash) = value)
- } else {
- table(i) = new LeafNode(key, hash, value)
+ bits | mask
}
- bits | mask
+ new BitmappedNode(shift)(table, bits)
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = table((hash >>> shift) & 0x01f)(key, hash)
def update[A >: V](levelShift: Int, key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
- val newTable = new Array[Node[K, A]](32)
- Array.copy(table, 0, newTable, 0, 32)
-
- newTable(i) = newTable(i)(shift + 5, key, hash) = value
+ val node = (table(i)(shift + 5, key, hash) = value)
- new FullNode(shift)(newTable)
+ if (node == table(i)) this else {
+ val newTable = new Array[Node[K, A]](32)
+ Array.copy(table, 0, newTable, 0, 32)
+
+ newTable(i) = node
+
+ new FullNode(shift)(newTable)
+ }
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
- val newTable = new Array[Node[K, V]](32)
- Array.copy(table, 0, newTable, 0, 32)
+ val node = table(i).remove(key, hash)
- val node = newTable(i).remove(key, hash)
-
- if (node.isInstanceOf[EmptyNode[_]]) {
- newTable(i) = null
- new BitmappedNode(shift)(newTable, Math.MAX_INT ^ mask)
- } else {
- newTable(i) = node
- new FullNode(shift)(newTable)
+ if (node == table(i)) this else {
+ val newTable = new Array[Node[K, V]](32)
+ Array.copy(table, 0, newTable, 0, 32)
+
+ if (node.isInstanceOf[EmptyNode[_]]) {
+ newTable(i) = null
+ new BitmappedNode(shift)(newTable, ~0 ^ mask)
+ } else {
+ newTable(i) = node
+ new FullNode(shift)(newTable)
+ }
}
}
def elements = {
val iters = table map { _.elements }
iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
}
override def toString = "FullNode(" + table.foldLeft("") { _.toString + ", " + _.toString } + ")"
}
|
djspiewak/scala-collections
|
95f4c3a43b7db4bb181cc4deb55c6ce25261236c
|
Moderate improvement in trie balance
|
diff --git a/src/main/scala/com/codecommit/collection/HashTrie.scala b/src/main/scala/com/codecommit/collection/HashTrie.scala
index 4160ad9..6c797cc 100644
--- a/src/main/scala/com/codecommit/collection/HashTrie.scala
+++ b/src/main/scala/com/codecommit/collection/HashTrie.scala
@@ -1,301 +1,302 @@
package com.codecommit.collection
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
*/
final class HashTrie[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
- def update[A >: V](key: K, value: A) = new HashTrie(root(key, key.hashCode) = value)
+ def update[A >: V](key: K, value: A) = new HashTrie(root(0, key, key.hashCode) = value)
def -(key: K) = new HashTrie(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashTrie[K, A] = new HashTrie(new EmptyNode[K])
def diagnose = root.toString
}
object HashTrie {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashTrie[K, V]) { _ + _ }
def unapply[K, V](map: HashTrie[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
- def update[A >: V](key: K, hash: Int, value: A): Node[K, A]
+ def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
- def update[V](key: K, hash: Int, value: V) = new LeafNode(0, hash)(key, value)
+ def update[V](shift: Int, key: K, hash: Int, value: V) = new LeafNode(key, hash, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
-private[collection] class LeafNode[K, +V](shift: Int, hash: Int)(key: K, value: V) extends Node[K, V] {
+private[collection] class LeafNode[K, +V](key: K, hash: Int, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
- def update[A >: V](key: K, hash: Int, value: A) = {
+ def update[A >: V](shift: Int, key: K, hash: Int, value: A) = {
if (this.key == key) {
- new LeafNode(shift, hash)(key, value)
+ new LeafNode(key, hash, value)
} else if (this.hash == hash) {
- new CollisionNode(shift, hash, this.key -> this.value, key -> value)
+ new CollisionNode(hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
-private[collection] class CollisionNode[K, +V](shift: Int, hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
+private[collection] class CollisionNode[K, +V](hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
- def this(shift: Int, hash: Int, pairs: (K, V)*) = this(shift, hash, pairs.toList)
+ def this(hash: Int, pairs: (K, V)*) = this(hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
- def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
+ def update[A >: V](shift: Int, key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for {
(k, v) <- bucket
} yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
- new CollisionNode(shift, hash, if (found) newBucket else (key, value) :: bucket)
+ new CollisionNode(hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == 1) {
val (key, value) = newBucket.head
- new LeafNode(shift, hash)(key, value)
- } else new CollisionNode(shift, hash, newBucket)
+ new LeafNode(key, hash, value)
+ } else new CollisionNode(hash, newBucket)
}
def elements = (bucket map { case (k, v) => (k, v) }).elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
import BitmappedNode._
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
- def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
+ // TODO
+ def update[A >: V](levelShift: Int, key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
Array.copy(table, 0, newTable, 0, table.length)
val newBits = addToTable(shift)(newTable, bits)(key, hash, value)
if (newBits == ~0) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](if (i + 1 == table.length) table.length - 1 else table.length)
Array.copy(table, 0, newTable, 0, newTable.length)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
val iters = table flatMap { n =>
if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
}
iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
val table = new Array[Node[K, V]](pairs.foldLeft(0) { (x, pair) =>
val (_, hash, _) = pair
Math.max(x, (hash >>> shift) & 0x01f)
} + 1)
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
addToTable(shift)(table, bits)(key, hash, value)
}
new BitmappedNode(shift)(table, bits)
}
private def addToTable[K, V](shift: Int)(table: Array[Node[K, V]], bits: Int)(key: K, hash: Int, value: V) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
- table(i) = (table(i)(key, hash) = value)
+ table(i) = (table(i)(shift + 5, key, hash) = value)
} else {
- table(i) = new LeafNode(shift + 5, hash)(key, value)
+ table(i) = new LeafNode(key, hash, value)
}
bits | mask
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = table((hash >>> shift) & 0x01f)(key, hash)
- def update[A >: V](key: K, hash: Int, value: A) = {
+ def update[A >: V](levelShift: Int, key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
- newTable(i) = newTable(i)(key, hash) = value
+ newTable(i) = newTable(i)(shift + 5, key, hash) = value
new FullNode(shift)(newTable)
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
val node = newTable(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, Math.MAX_INT ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def elements = {
val iters = table map { _.elements }
iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
}
override def toString = "FullNode(" + table.foldLeft("") { _.toString + ", " + _.toString } + ")"
}
|
djspiewak/scala-collections
|
71f8638c270f8c0eac8babdfbe348426fc42a1ca
|
Renamed HashMap => HashTrie
|
diff --git a/src/main/scala/com/codecommit/collection/HashMap.scala b/src/main/scala/com/codecommit/collection/HashTrie.scala
similarity index 94%
rename from src/main/scala/com/codecommit/collection/HashMap.scala
rename to src/main/scala/com/codecommit/collection/HashTrie.scala
index 423b51e..4160ad9 100644
--- a/src/main/scala/com/codecommit/collection/HashMap.scala
+++ b/src/main/scala/com/codecommit/collection/HashTrie.scala
@@ -1,301 +1,301 @@
package com.codecommit.collection
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
*/
-final class HashMap[K, +V] private (root: Node[K, V]) extends Map[K, V] {
+final class HashTrie[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
- def update[A >: V](key: K, value: A) = new HashMap(root(key, key.hashCode) = value)
+ def update[A >: V](key: K, value: A) = new HashTrie(root(key, key.hashCode) = value)
- def -(key: K) = new HashMap(root.remove(key, key.hashCode))
+ def -(key: K) = new HashTrie(root.remove(key, key.hashCode))
def elements = root.elements
- def empty[A]: HashMap[K, A] = new HashMap(new EmptyNode[K])
+ def empty[A]: HashTrie[K, A] = new HashTrie(new EmptyNode[K])
def diagnose = root.toString
}
-object HashMap {
- def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashMap[K, V]) { _ + _ }
+object HashTrie {
+ def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashTrie[K, V]) { _ + _ }
- def unapply[K, V](map: HashMap[K, V]) = map.toSeq
+ def unapply[K, V](map: HashTrie[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](key: K, hash: Int, value: V) = new LeafNode(0, hash)(key, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] class LeafNode[K, +V](shift: Int, hash: Int)(key: K, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](key: K, hash: Int, value: A) = {
if (this.key == key) {
new LeafNode(shift, hash)(key, value)
} else if (this.hash == hash) {
new CollisionNode(shift, hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](shift: Int, hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
def this(shift: Int, hash: Int, pairs: (K, V)*) = this(shift, hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for {
(k, v) <- bucket
} yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(shift, hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(shift, hash)(key, value)
} else new CollisionNode(shift, hash, newBucket)
}
def elements = (bucket map { case (k, v) => (k, v) }).elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
import BitmappedNode._
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
Array.copy(table, 0, newTable, 0, table.length)
val newBits = addToTable(shift)(newTable, bits)(key, hash, value)
if (newBits == ~0) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](if (i + 1 == table.length) table.length - 1 else table.length)
Array.copy(table, 0, newTable, 0, newTable.length)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
val iters = table flatMap { n =>
if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
}
iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
val table = new Array[Node[K, V]](pairs.foldLeft(0) { (x, pair) =>
val (_, hash, _) = pair
Math.max(x, (hash >>> shift) & 0x01f)
} + 1)
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
addToTable(shift)(table, bits)(key, hash, value)
}
new BitmappedNode(shift)(table, bits)
}
private def addToTable[K, V](shift: Int)(table: Array[Node[K, V]], bits: Int)(key: K, hash: Int, value: V) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
table(i) = (table(i)(key, hash) = value)
} else {
table(i) = new LeafNode(shift + 5, hash)(key, value)
}
bits | mask
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = table((hash >>> shift) & 0x01f)(key, hash)
def update[A >: V](key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = newTable(i)(key, hash) = value
new FullNode(shift)(newTable)
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
val node = newTable(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, Math.MAX_INT ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def elements = {
val iters = table map { _.elements }
iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
}
override def toString = "FullNode(" + table.foldLeft("") { _.toString + ", " + _.toString } + ")"
}
diff --git a/src/test/scala/HashPerf.scala b/src/test/scala/HashPerf.scala
index a370b44..8c8fd6a 100644
--- a/src/test/scala/HashPerf.scala
+++ b/src/test/scala/HashPerf.scala
@@ -1,166 +1,166 @@
-import com.codecommit.collection.HashMap
+import com.codecommit.collection.HashTrie
import scala.collection.immutable.TreeHashMap
object HashPerf {
import PerfLib._
def main(args: Array[String]) {
println()
val data = "The quick brown fox jumped over the lazy red dog"
//==========================================================================
{
title("Fill 100000 Random Keys")
val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
indexes(i) = Math.random.toString
}
- val hashMapOp = "HashMap" -> time {
- var map = HashMap[String, String]()
+ val hashMapOp = "HashTrie" -> time {
+ var map = HashTrie[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
val mapOp = "Map" -> time {
var map = Map[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
hashMapOp compare mapOp
val intMapOp = "TreeHashMap" -> time {
var map = TreeHashMap[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
hashMapOp compare intMapOp
val mutableMapOp = "mutable.Map" -> time {
val map = scala.collection.mutable.Map[String, String]()
var i = 0
while (i < indexes.length) {
map(indexes(i)) = data
i += 1
}
}
hashMapOp compare mutableMapOp
div('=')
}
println()
//==========================================================================
{
title("Read 100000 Random Keys")
val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
indexes(i) = Math.random.toString
}
- var hashMap = HashMap[String, String]()
+ var hashMap = HashTrie[String, String]()
{
var i = 0
while (i < indexes.length) {
hashMap = hashMap(indexes(i)) = data
i += 1
}
}
var immutableMap = Map[String, String]()
{
var i = 0
while (i < indexes.length) {
immutableMap = immutableMap(indexes(i)) = data
i += 1
}
}
- val hashMapOp = "HashMap" -> time {
+ val hashMapOp = "HashTrie" -> time {
var i = 0
while (i < indexes.length) {
hashMap(indexes(i))
i += 1
}
}
val mapOp = "Map" -> time {
var i = 0
while (i < indexes.length) {
immutableMap(indexes(i))
i += 1
}
}
hashMapOp compare mapOp
var intMap = TreeHashMap[String, String]()
{
var i = 0
while (i < indexes.length) {
intMap = intMap(indexes(i)) = data
i += 1
}
}
val intMapOp = "TreeHashMap" -> time {
var i = 0
while (i < indexes.length) {
intMap(indexes(i))
i += 1
}
}
hashMapOp compare intMapOp
val mutableMap = scala.collection.mutable.Map[String, String]()
{
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i)) = data
i += 1
}
}
val mutableMapOp = "mutable.Map" -> time {
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i))
i += 1
}
}
hashMapOp compare mutableMapOp
div('=')
}
}
}
diff --git a/src/test/scala/HashMapSpecs.scala b/src/test/scala/HashTrieSpecs.scala
similarity index 71%
rename from src/test/scala/HashMapSpecs.scala
rename to src/test/scala/HashTrieSpecs.scala
index 41fc006..cb88a02 100644
--- a/src/test/scala/HashMapSpecs.scala
+++ b/src/test/scala/HashTrieSpecs.scala
@@ -1,101 +1,101 @@
import org.specs._
import org.scalacheck._
-import com.codecommit.collection.HashMap
+import com.codecommit.collection.HashTrie
-object HashMapSpecs extends Specification with ScalaCheck {
+object HashTrieSpecs extends Specification with ScalaCheck {
import Prop._
"it" should {
"store ints" in {
val prop = property { src: List[Int] =>
- val map = src.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = -v }
+ val map = src.foldLeft(new HashTrie[Int, Int]) { (m, v) => m(v) = -v }
src forall { v => map(v) == -v }
}
prop must pass(set(maxSize -> 5000, minTestsOk -> 2000))
}
"store strings" in {
val prop = property { src: List[String] =>
- val map = src.foldLeft(new HashMap[String, Int]) { (m, v) => m(v) = v.length }
+ val map = src.foldLeft(new HashTrie[String, Int]) { (m, v) => m(v) = v.length }
src forall { v => map(v) == v.length }
}
prop must pass
}
"preserve values across changes" in {
- val prop = property { (map: HashMap[String, String], ls: List[String], f: (String)=>String) =>
+ val prop = property { (map: HashTrie[String, String], ls: List[String], f: (String)=>String) =>
val filtered = ls filter { !map.contains(_) }
filtered.length > 0 ==> {
val newMap = filtered.foldLeft(map) { (m, k) => m(k) = f(k) }
(map forall { case (k, v) => newMap(k) == v }) && (filtered forall { v => newMap(v) == f(v) })
}
}
prop must pass
}
"calculate size" in {
val prop = property { (ls: Set[Int], f: (Int)=>Int) =>
- val map = ls.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = f(v) }
+ val map = ls.foldLeft(new HashTrie[Int, Int]) { (m, v) => m(v) = f(v) }
map.size == ls.size
}
prop must pass
}
"remove ints" in {
- val prop = property { map: HashMap[Int, String] =>
+ val prop = property { map: HashTrie[Int, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next // insufficient
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
"remove strings" in {
- val prop = property { map: HashMap[String, String] =>
+ val prop = property { map: HashTrie[String, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
"define empty" in {
- val prop = property { map: HashMap[String, String] =>
+ val prop = property { map: HashTrie[String, String] =>
map.empty.size == 0
}
prop must pass
}
}
- implicit def arbHashMap[K](implicit ak: Arbitrary[List[K]]): Arbitrary[HashMap[K, String]] = {
+ implicit def arbHashTrie[K](implicit ak: Arbitrary[List[K]]): Arbitrary[HashTrie[K, String]] = {
Arbitrary(for {
keys <- ak.arbitrary
- } yield keys.foldLeft(new HashMap[K, String]) { (m, k) => m(k) = k.toString })
+ } yield keys.foldLeft(new HashTrie[K, String]) { (m, k) => m(k) = k.toString })
}
implicit def arbSet[A](implicit arb: Arbitrary[List[A]]): Arbitrary[Set[A]] = {
Arbitrary(for {
ls <- arb.arbitrary
} yield ls.foldLeft(Set[A]()) { _ + _ })
}
}
|
djspiewak/scala-collections
|
573a53fd5502515a9e560b76ed064c4a89ee54be
|
Changed to String keys; added TreeHashMap benchmark
|
diff --git a/src/test/scala/HashPerf.scala b/src/test/scala/HashPerf.scala
index 4b4de0c..a370b44 100644
--- a/src/test/scala/HashPerf.scala
+++ b/src/test/scala/HashPerf.scala
@@ -1,170 +1,166 @@
import com.codecommit.collection.HashMap
-import scala.collection.immutable.IntMap
+import scala.collection.immutable.TreeHashMap
object HashPerf {
import PerfLib._
def main(args: Array[String]) {
println()
val data = "The quick brown fox jumped over the lazy red dog"
//==========================================================================
{
title("Fill 100000 Random Keys")
- val indexes = new Array[Int](100000)
- var max = -1
+ val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
- indexes(i) = Math.round(Math.random * 40000000).toInt - 20000000
- max = Math.max(max, indexes(i))
+ indexes(i) = Math.random.toString
}
val hashMapOp = "HashMap" -> time {
- var map = HashMap[Int, String]()
+ var map = HashMap[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
val mapOp = "Map" -> time {
- var map = Map[Int, String]()
+ var map = Map[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
hashMapOp compare mapOp
- val intMapOp = "IntMap" -> time {
- var map = IntMap[String]()
+ val intMapOp = "TreeHashMap" -> time {
+ var map = TreeHashMap[String, String]()
var i = 0
while (i < indexes.length) {
map = map(indexes(i)) = data
i += 1
}
}
hashMapOp compare intMapOp
val mutableMapOp = "mutable.Map" -> time {
- val map = scala.collection.mutable.Map[Int, String]()
+ val map = scala.collection.mutable.Map[String, String]()
var i = 0
while (i < indexes.length) {
map(indexes(i)) = data
i += 1
}
}
hashMapOp compare mutableMapOp
div('=')
}
println()
//==========================================================================
{
title("Read 100000 Random Keys")
- val indexes = new Array[Int](100000)
- var max = -1
+ val indexes = new Array[String](100000)
for (i <- 0 until indexes.length) {
- indexes(i) = Math.round(Math.random * 40000000).toInt - 20000000
- max = Math.max(max, indexes(i))
+ indexes(i) = Math.random.toString
}
- var hashMap = HashMap[Int, String]()
+ var hashMap = HashMap[String, String]()
{
var i = 0
while (i < indexes.length) {
hashMap = hashMap(indexes(i)) = data
i += 1
}
}
- var immutableMap = Map[Int, String]()
+ var immutableMap = Map[String, String]()
{
var i = 0
while (i < indexes.length) {
immutableMap = immutableMap(indexes(i)) = data
i += 1
}
}
val hashMapOp = "HashMap" -> time {
var i = 0
while (i < indexes.length) {
hashMap(indexes(i))
i += 1
}
}
val mapOp = "Map" -> time {
var i = 0
while (i < indexes.length) {
immutableMap(indexes(i))
i += 1
}
}
hashMapOp compare mapOp
- var intMap = IntMap[String]()
+ var intMap = TreeHashMap[String, String]()
{
var i = 0
while (i < indexes.length) {
intMap = intMap(indexes(i)) = data
i += 1
}
}
- val intMapOp = "IntMap" -> time {
+ val intMapOp = "TreeHashMap" -> time {
var i = 0
while (i < indexes.length) {
intMap(indexes(i))
i += 1
}
}
hashMapOp compare intMapOp
- val mutableMap = scala.collection.mutable.Map[Int, String]()
+ val mutableMap = scala.collection.mutable.Map[String, String]()
{
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i)) = data
i += 1
}
}
val mutableMapOp = "mutable.Map" -> time {
var i = 0
while (i < indexes.length) {
mutableMap(indexes(i))
i += 1
}
}
hashMapOp compare mutableMapOp
div('=')
}
}
}
|
djspiewak/scala-collections
|
3318a8957f257919bafd7ae920f65bf0ea07c67d
|
Ported forward to Specs 1.3.2 / ScalaCheck 1.4 (compatible Scala 2.7.2)
|
diff --git a/build.yaml b/build.yaml
new file mode 100644
index 0000000..758f83b
--- /dev/null
+++ b/build.yaml
@@ -0,0 +1,2 @@
+scala.check: 1.4-scSNAPSHOT
+scala.specs: 1.3.2-SNAPSHOT
diff --git a/buildfile b/buildfile
index 649a03b..2a9c92a 100644
--- a/buildfile
+++ b/buildfile
@@ -1,12 +1,15 @@
require 'buildr/scala'
+#require 'buildr/cobertura'
repositories.remote << 'http://www.ibiblio.org/maven2'
repositories.remote << 'http://scala-tools.org/repo-releases'
desc 'A few collections classes for fun and profit'
define 'collection' do
project.version = '0.1.0'
project.group = 'com.codecommit'
+ test.using :specs=>true
+
package :jar
end
diff --git a/src/test/scala/BloomSpecs.scala b/src/test/scala/BloomSpecs.scala
index d4bac42..f4a2d32 100644
--- a/src/test/scala/BloomSpecs.scala
+++ b/src/test/scala/BloomSpecs.scala
@@ -1,134 +1,134 @@
import org.specs._
import org.scalacheck._
import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
import com.codecommit.collection.BloomSet
-object BloomSpecs extends Specification with Scalacheck {
+object BloomSpecs extends Specification with ScalaCheck {
import Prop._
"bloom set" should {
"store single element once" in {
(BloomSet[String]() + "test") contains "test" mustEqual true
}
"store single element n times" in {
val prop = property { ls: List[String] =>
val set = ls.foldLeft(BloomSet[String]()) { _ + _ }
ls.foldLeft(true) { _ && set(_) }
}
prop must pass
}
"store duplicate elements n times" in {
val prop = property { ls: List[String] =>
var set = ls.foldLeft(BloomSet[String]()) { _ + _ }
set = ls.foldLeft(set) { _ + _ }
ls.foldLeft(true) { _ && set(_) }
}
prop must pass
}
"handle ++ Iterable" in {
val prop = property { (first: List[String], last: List[String]) =>
var set = first.foldLeft(BloomSet[String]()) { _ + _ }
set ++= last
first.foldLeft(true) { _ && set(_) } && last.foldLeft(true) { _ && set(_) }
}
prop must pass
}
"handle ++ BloomSet" in {
val prop = property { (first: List[String], last: List[String]) =>
var set = first.foldLeft(BloomSet[String]()) { _ + _ }
set ++= last.foldLeft(BloomSet[String]()) { _ + _ }
first.foldLeft(true) { _ && set(_) } && last.foldLeft(true) { _ && set(_) }
}
prop must pass
}
"be immutable" in {
val prop = property { (ls: List[String], item: String) =>
val set = ls.foldLeft(new BloomSet[String](10000, 5)) { _ + _ }
// might fail, but it is doubtful
(set.accuracy > 0.999 && !ls.contains(item)) ==> {
val newSet = set + item
ls.foldLeft(true) { _ && set(_) } &&
!set.contains(item) &&
ls.foldLeft(true) { _ && newSet(_) } &&
newSet.contains(item)
}
}
prop must pass(set(minTestsOk -> 100, maxDiscarded -> 5000, minSize -> 0, maxSize -> 100))
}
"construct using companion" in {
val set = BloomSet("daniel", "chris", "joseph", "renee")
set contains "daniel" mustEqual true
set contains "chris" mustEqual true
set contains "joseph" mustEqual true
set contains "renee" mustEqual true
}
"implement equivalency" in {
val prop = property { nums: List[Int] =>
val set1 = nums.foldLeft(BloomSet[Int]()) { _ + _}
val set2 = nums.foldLeft(BloomSet[Int]()) { _ + _}
set1 == set2
}
prop must pass
}
"implement hashing" in {
val prop = property { nums: List[Int] =>
val set1 = nums.foldLeft(BloomSet[Int]()) { _ + _}
val set2 = nums.foldLeft(BloomSet[Int]()) { _ + _}
set1.hashCode == set2.hashCode
}
prop must pass
}
"persist properly" in {
val prop = property { (width: Int, k: Int, ls: List[Int]) => (width > 0 && k > 0) ==> {
val set = ls.foldLeft(new BloomSet[Int](width, k)) { _ + _ }
val os = new ByteArrayOutputStream
set.store(os)
val is = new ByteArrayInputStream(os.toByteArray)
val newSet = BloomSet.load[Int](is)
ls.foldLeft(true) { _ && newSet(_) } &&
newSet.width == set.width &&
newSet.k == set.k &&
newSet.size == set.size
}
}
prop must pass
}
"calculate accuracy" in {
BloomSet[Int]().accuracy mustEqual 1d
val set = (0 until 1000).foldLeft(BloomSet[Int]()) { _ + _ }
set.accuracy must beCloseTo(0d, 0.0000001d)
}
}
}
diff --git a/src/test/scala/HashMapSpecs.scala b/src/test/scala/HashMapSpecs.scala
index 5553624..41fc006 100644
--- a/src/test/scala/HashMapSpecs.scala
+++ b/src/test/scala/HashMapSpecs.scala
@@ -1,101 +1,101 @@
import org.specs._
import org.scalacheck._
import com.codecommit.collection.HashMap
-object HashMapSpecs extends Specification with Scalacheck {
+object HashMapSpecs extends Specification with ScalaCheck {
import Prop._
"it" should {
"store ints" in {
val prop = property { src: List[Int] =>
val map = src.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = -v }
src forall { v => map(v) == -v }
}
prop must pass(set(maxSize -> 5000, minTestsOk -> 2000))
}
"store strings" in {
val prop = property { src: List[String] =>
val map = src.foldLeft(new HashMap[String, Int]) { (m, v) => m(v) = v.length }
src forall { v => map(v) == v.length }
}
prop must pass
}
"preserve values across changes" in {
val prop = property { (map: HashMap[String, String], ls: List[String], f: (String)=>String) =>
val filtered = ls filter { !map.contains(_) }
filtered.length > 0 ==> {
val newMap = filtered.foldLeft(map) { (m, k) => m(k) = f(k) }
(map forall { case (k, v) => newMap(k) == v }) && (filtered forall { v => newMap(v) == f(v) })
}
}
prop must pass
}
"calculate size" in {
val prop = property { (ls: Set[Int], f: (Int)=>Int) =>
val map = ls.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = f(v) }
map.size == ls.size
}
prop must pass
}
"remove ints" in {
val prop = property { map: HashMap[Int, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next // insufficient
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
"remove strings" in {
val prop = property { map: HashMap[String, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
"define empty" in {
val prop = property { map: HashMap[String, String] =>
map.empty.size == 0
}
prop must pass
}
}
implicit def arbHashMap[K](implicit ak: Arbitrary[List[K]]): Arbitrary[HashMap[K, String]] = {
Arbitrary(for {
keys <- ak.arbitrary
} yield keys.foldLeft(new HashMap[K, String]) { (m, k) => m(k) = k.toString })
}
implicit def arbSet[A](implicit arb: Arbitrary[List[A]]): Arbitrary[Set[A]] = {
Arbitrary(for {
ls <- arb.arbitrary
} yield ls.foldLeft(Set[A]()) { _ + _ })
}
}
diff --git a/src/test/scala/PathVectorSpecs.scala b/src/test/scala/PathVectorSpecs.scala
index e4f2574..390405a 100644
--- a/src/test/scala/PathVectorSpecs.scala
+++ b/src/test/scala/PathVectorSpecs.scala
@@ -1,299 +1,299 @@
import org.specs._
import org.scalacheck._
import com.codecommit.collection.PathVector
-object PathVectorSpecs extends Specification with Scalacheck {
+object PathVectorSpecs extends Specification with ScalaCheck {
import Prop._
val vector = PathVector[Int]()
implicit def arbitraryPathVector[A](implicit arb: Arbitrary[A]): Arbitrary[PathVector[A]] = {
Arbitrary(for {
data <- Arbitrary.arbitrary[List[A]]
indexes <- Gen.containerOfN[List, Int](data.length, Gen.choose(0, Math.MAX_INT - 1))
} yield {
var vec = new PathVector[A]
var i = 0
for (d <- data) {
vec(indexes(i)) = d
i += 1
}
vec
})
}
"path vector" should {
"have infinite bounds" in {
vector.length mustEqual 0 // finite length
val prop = property { i: Int => // infinite bounds
i >= 0 ==> (vector(i) == 0)
}
prop must pass
}
"store a single element" in {
val prop = property { (i: Int, e: Int) =>
i >= 0 ==> ((vector(0) = e)(0) == e)
}
prop must pass
}
"replace single element" in {
val prop = property { (vec: PathVector[String], i: Int) =>
i >= 0 ==> {
val newPathVector = (vec(i) = "test")(i) = "newTest"
newPathVector(i) == "newTest"
}
}
prop must pass
}
"store multiple elements in order" in {
val prop = property { list: List[Int] =>
val newPathVector = list.foldLeft(vector) { _ + _ }
val res = for (i <- 0 until list.length) yield newPathVector(i) == list(i)
res forall { _ == true }
}
prop must pass
}
"store lots of elements" in {
val LENGTH = 100000
val vector = (0 until LENGTH).foldLeft(PathVector[Int]()) { _ + _ }
vector.length mustEqual LENGTH
for (i <- 0 until LENGTH) {
vector(i) mustEqual i
}
}
"store at arbitrary points" in {
val vector = PathVector(1, 2, 3, 4, 5)
val prop = property { others: List[(Int, Int)] =>
val (newPathVector, resMap) = others.foldLeft(vector, Map[Int, Int]()) { (inTuple, tuple) =>
val (i, value) = tuple
val (vec, map) = inTuple
if (i < 0) (vec, map) else (vec(i) = value, map + (i -> value))
}
val res = for {
(i, _) <- others
} yield if (i < 0) true else newPathVector(i) == resMap(i)
res forall { _ == true }
}
prop must pass
}
"implement filter" in {
val prop = property { (vec: PathVector[Int], f: (Int)=>Boolean) =>
val filtered = vec filter f
var back = filtered forall f
for (e <- vec) {
if (f(e)) {
back &&= filtered.contains(e)
}
}
back
}
prop must pass
}
"implement foldLeft" in {
val prop = property { list: List[Int] =>
val vec = list.foldLeft(new PathVector[Int]) { _ + _ }
vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ }
}
prop must pass
}
"implement forall" in {
val prop = property { (vec: PathVector[Int], f: (Int)=>Boolean) =>
val bool = vec forall f
var back = true
for (e <- vec) {
back &&= f(e)
}
(back && bool) || (!back && !bool)
}
prop must pass
}
"implement map" in {
val prop = property { (vec: PathVector[Int], f: (Int)=>Int) =>
val mapped = vec map f
var back = vec.length == mapped.length
for (i <- 0 until vec.length) {
back &&= mapped(i) == f(vec(i))
}
back
}
prop must pass
}
"implement reverse" in {
val prop = property { v: PathVector[Int] =>
val reversed = v.reverse
var back = v.length == reversed.length
for (i <- 0 until v.length) {
back &&= reversed(i) == v(v.length - i - 1)
}
back
}
prop must pass
}
"append to reverse" in {
val prop = property { (v: PathVector[Int], n: Int) =>
val rev = v.reverse
val add = rev + n
var back = add.length == rev.length + 1
for (i <- 0 until rev.length) {
back &&= add(i) == rev(i)
}
back && add(rev.length) == n
}
prop must pass
}
"map on reverse" in {
val prop = property { (v: PathVector[Int], f: (Int)=>Int) =>
val rev = v.reverse
val mapped = rev map f
var back = mapped.length == rev.length
for (i <- 0 until rev.length) {
back &&= mapped(i) == f(rev(i))
}
back
}
prop must pass
}
"implement subseq" in {
val prop = property { (v: PathVector[Int], from: Int, end: Int) =>
try {
val sub = v.subseq(from, end)
var back = sub.length == end - from
for (i <- 0 until sub.length) {
back &&= sub(i) == v(i + from)
}
back
} catch {
case _:IndexOutOfBoundsException => from < 0
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"append to subseq" in {
val prop = property { (v: PathVector[Int], from: Int, end: Int, n: Int) =>
try {
val sub = v.subseq(from, end)
val add = sub + n
var back = add.length == sub.length + 1
for (i <- 0 until sub.length) {
back &&= add(i) == sub(i)
}
back && add(sub.length) == n
} catch {
case _:IndexOutOfBoundsException => from < 0
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"map on subseq" in {
val prop = property { (v: PathVector[Int], from: Int, end: Int, f: (Int)=>Int) =>
try {
val sub = v.subseq(from, end)
val mapped = sub map f
var back = mapped.length == sub.length
for (i <- 0 until sub.length) {
back &&= mapped(i) == f(sub(i))
}
back
} catch {
case _:IndexOutOfBoundsException => from < 0
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"implement zip" in {
val prop = property { (first: PathVector[Int], second: PathVector[Double]) =>
val zip = first zip second
var back = zip.length == Math.max(first.length, second.length)
for (i <- 0 until zip.length) {
var (left, right) = zip(i)
back &&= (left == first(i) && right == second(i))
}
back
}
prop must pass
}
"implement zipWithIndex" in {
val prop = property { vec: PathVector[Int] =>
val zip = vec.zipWithIndex
var back = zip.length == vec.length
for (i <- 0 until zip.length) {
val (elem, index) = zip(i)
back &&= (index == i && elem == vec(i))
}
back
}
prop must pass
}
"implement equals" in {
val prop = property { list: List[Int] =>
val vecA = list.foldLeft(new PathVector[Int]) { _ + _ }
val vecB = list.foldLeft(new PathVector[Int]) { _ + _ }
vecA == vecB
}
prop must pass
}
}
}
diff --git a/src/test/scala/VectorSpecs.scala b/src/test/scala/VectorSpecs.scala
index f71fe87..d59bb0b 100644
--- a/src/test/scala/VectorSpecs.scala
+++ b/src/test/scala/VectorSpecs.scala
@@ -1,332 +1,332 @@
import org.specs._
import org.scalacheck._
import com.codecommit.collection.Vector
-object VectorSpecs extends Specification with Scalacheck {
+object VectorSpecs extends Specification with ScalaCheck {
import Prop._
val vector = Vector[Int]()
implicit def arbitraryVector[A](implicit arb: Arbitrary[A]): Arbitrary[Vector[A]] = {
Arbitrary(for {
data <- Arbitrary.arbitrary[List[A]]
} yield data.foldLeft(Vector[A]()) { _ + _ })
}
"vector" should {
"store a single element" in {
val prop = property { (i: Int, e: Int) =>
i >= 0 ==> ((vector(0) = e)(0) == e)
}
prop must pass
}
"replace single element" in {
val prop = property { (vec: Vector[Int], i: Int) =>
((0 to vec.length) contains i) ==> {
val newVector = (vec(i) = "test")(i) = "newTest"
newVector(i) == "newTest"
}
}
prop must pass
}
"pop elements" in {
val prop = property { vec: Vector[Int] =>
vec.length > 0 ==> {
val popped = vec.pop
var back = popped.length == vec.length - 1
var i = 0
while (i < popped.length) {
back &&= popped(i) == vec(i)
i += 1
}
back
}
}
prop must pass
}
"store multiple elements in order" in {
val prop = property { list: List[Int] =>
val newVector = list.foldLeft(vector) { _ + _ }
val res = for (i <- 0 until list.length) yield newVector(i) == list(i)
res forall { _ == true }
}
prop must pass
}
"store lots of elements" in {
val LENGTH = 100000
val vector = (0 until LENGTH).foldLeft(Vector[Int]()) { _ + _ }
vector.length mustEqual LENGTH
for (i <- 0 until LENGTH) {
vector(i) mustEqual i
}
}
"implement filter" in {
val prop = property { (vec: Vector[Int], f: (Int)=>Boolean) =>
val filtered = vec filter f
var back = filtered forall f
for (e <- vec) {
if (f(e)) {
back &&= filtered.contains(e)
}
}
back
}
prop must pass
}
"implement foldLeft" in {
val prop = property { list: List[Int] =>
val vec = list.foldLeft(Vector[Int]()) { _ + _ }
vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ }
}
prop must pass
}
"implement forall" in {
val prop = property { (vec: Vector[Int], f: (Int)=>Boolean) =>
val bool = vec forall f
var back = true
for (e <- vec) {
back &&= f(e)
}
(back && bool) || (!back && !bool)
}
prop must pass
}
"implement flatMap" in {
val prop = property { (vec: Vector[Int], f: (Int)=>Vector[Int]) =>
val mapped = vec flatMap f
var back = true
var i = 0
var n = 0
while (i < vec.length) {
val res = f(vec(i))
var inner = 0
while (inner < res.length) {
back &&= mapped(n) == res(inner)
inner += 1
n += 1
}
i += 1
}
back
}
prop must pass
}
"implement map" in {
val prop = property { (vec: Vector[Int], f: (Int)=>Int) =>
val mapped = vec map f
var back = vec.length == mapped.length
for (i <- 0 until vec.length) {
back &&= mapped(i) == f(vec(i))
}
back
}
prop must pass
}
"implement reverse" in {
val prop = property { v: Vector[Int] =>
val reversed = v.reverse
var back = v.length == reversed.length
for (i <- 0 until v.length) {
back &&= reversed(i) == v(v.length - i - 1)
}
back
}
prop must pass
}
"append to reverse" in {
val prop = property { (v: Vector[Int], n: Int) =>
val rev = v.reverse
val add = rev + n
var back = add.length == rev.length + 1
for (i <- 0 until rev.length) {
back &&= add(i) == rev(i)
}
back && add(rev.length) == n
}
prop must pass
}
"map on reverse" in {
val prop = property { (v: Vector[Int], f: (Int)=>Int) =>
val rev = v.reverse
val mapped = rev map f
var back = mapped.length == rev.length
for (i <- 0 until rev.length) {
back &&= mapped(i) == f(rev(i))
}
back
}
prop must pass
}
"implement subseq" in {
val prop = property { (v: Vector[Int], from: Int, end: Int) =>
try {
val sub = v.subseq(from, end)
var back = sub.length == end - from
for (i <- 0 until sub.length) {
back &&= sub(i) == v(i + from)
}
back
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"append to subseq" in {
val prop = property { (v: Vector[Int], from: Int, end: Int, n: Int) =>
try {
val sub = v.subseq(from, end)
val add = sub + n
var back = add.length == sub.length + 1
for (i <- 0 until sub.length) {
back &&= add(i) == sub(i)
}
back && add(sub.length) == n
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"map on subseq" in {
val prop = property { (v: Vector[Int], from: Int, end: Int, f: (Int)=>Int) =>
try {
val sub = v.subseq(from, end)
val mapped = sub map f
var back = mapped.length == sub.length
for (i <- 0 until sub.length) {
back &&= mapped(i) == f(sub(i))
}
back
} catch {
case _:IndexOutOfBoundsException => from < 0 || end >= v.length
case _:IllegalArgumentException => end <= from
}
}
prop must pass
}
"implement zip" in {
val prop = property { (first: Vector[Int], second: Vector[Double]) =>
val zip = first zip second
var back = zip.length == Math.min(first.length, second.length)
for (i <- 0 until zip.length) {
var (left, right) = zip(i)
back &&= (left == first(i) && right == second(i))
}
back
}
prop must pass
}
"implement zipWithIndex" in {
val prop = property { vec: Vector[Int] =>
val zip = vec.zipWithIndex
var back = zip.length == vec.length
for (i <- 0 until zip.length) {
val (elem, index) = zip(i)
back &&= (index == i && elem == vec(i))
}
back
}
prop must pass
}
"implement equals" in {
val prop = property { list: List[Int] =>
val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
vecA == vecB
}
prop must pass
}
"implement hashCode" in {
val prop = property { list: List[Int] =>
val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
vecA.hashCode == vecB.hashCode
}
prop must pass
}
"implement extractor" in {
val vec1 = Vector(1, 2, 3)
vec1 must beLike {
case Vector(a, b, c) => (a, b, c) == (1, 2, 3)
}
val vec2 = Vector("daniel", "chris", "joseph")
vec2 must beLike {
case Vector(a, b, c) => (a, b, c) == ("daniel", "chris", "joseph")
}
}
}
}
|
djspiewak/scala-collections
|
b220734243ff165962f82bf98851359c2c0a2852
|
Removed pointless test
|
diff --git a/src/test/scala/HashMapSpecs.scala b/src/test/scala/HashMapSpecs.scala
index ad91893..5553624 100644
--- a/src/test/scala/HashMapSpecs.scala
+++ b/src/test/scala/HashMapSpecs.scala
@@ -1,108 +1,101 @@
import org.specs._
import org.scalacheck._
import com.codecommit.collection.HashMap
object HashMapSpecs extends Specification with Scalacheck {
import Prop._
"it" should {
- "not die" in {
- val map = HashMap(-1 -> -1, 0 -> 0)
-
- map(-1) mustEqual -1
- map(0) mustEqual 0
- }
-
"store ints" in {
val prop = property { src: List[Int] =>
val map = src.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = -v }
src forall { v => map(v) == -v }
}
prop must pass(set(maxSize -> 5000, minTestsOk -> 2000))
}
"store strings" in {
val prop = property { src: List[String] =>
val map = src.foldLeft(new HashMap[String, Int]) { (m, v) => m(v) = v.length }
src forall { v => map(v) == v.length }
}
prop must pass
}
"preserve values across changes" in {
val prop = property { (map: HashMap[String, String], ls: List[String], f: (String)=>String) =>
val filtered = ls filter { !map.contains(_) }
filtered.length > 0 ==> {
val newMap = filtered.foldLeft(map) { (m, k) => m(k) = f(k) }
(map forall { case (k, v) => newMap(k) == v }) && (filtered forall { v => newMap(v) == f(v) })
}
}
prop must pass
}
"calculate size" in {
val prop = property { (ls: Set[Int], f: (Int)=>Int) =>
val map = ls.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = f(v) }
map.size == ls.size
}
prop must pass
}
"remove ints" in {
val prop = property { map: HashMap[Int, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next // insufficient
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
"remove strings" in {
val prop = property { map: HashMap[String, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
"define empty" in {
val prop = property { map: HashMap[String, String] =>
map.empty.size == 0
}
prop must pass
}
}
implicit def arbHashMap[K](implicit ak: Arbitrary[List[K]]): Arbitrary[HashMap[K, String]] = {
Arbitrary(for {
keys <- ak.arbitrary
} yield keys.foldLeft(new HashMap[K, String]) { (m, k) => m(k) = k.toString })
}
implicit def arbSet[A](implicit arb: Arbitrary[List[A]]): Arbitrary[Set[A]] = {
Arbitrary(for {
ls <- arb.arbitrary
} yield ls.foldLeft(Set[A]()) { _ + _ })
}
}
|
djspiewak/scala-collections
|
06c64716ffec9788162fe1f46072494b4a8c3e79
|
Added lookup benchmarks
|
diff --git a/src/test/scala/HashPerf.scala b/src/test/scala/HashPerf.scala
index ae0295c..3a18be5 100644
--- a/src/test/scala/HashPerf.scala
+++ b/src/test/scala/HashPerf.scala
@@ -1,57 +1,168 @@
import com.codecommit.collection.HashMap
object HashPerf {
import PerfLib._
def main(args: Array[String]) {
println()
+ val data = "The quick brown fox jumped over the lazy red dog"
+
//==========================================================================
{
title("Fill 100000 Random Keys")
val indexes = new Array[Int](100000)
var max = -1
for (i <- 0 until indexes.length) {
- indexes(i) = Math.round(Math.random * 40000000).toInt
+ indexes(i) = Math.round(Math.random * 40000000).toInt - 20000000
max = Math.max(max, indexes(i))
}
- val data = "The quick brown fox jumped over the lazy red dog"
-
val hashMapOp = "HashMap" -> time {
var map = HashMap[Int, String]()
var i = 0
while (i < indexes.length) {
- map = map + (i -> data)
+ map = map(indexes(i)) = data
i += 1
}
}
val mapOp = "Map" -> time {
var map = Map[Int, String]()
var i = 0
while (i < indexes.length) {
- map = map + (i -> data)
+ map = map(indexes(i)) = data
i += 1
}
}
hashMapOp compare mapOp
- val intMapOp = "Map" -> time {
+ val intMapOp = "IntMap" -> time {
var map = test.IntMap[String]()
var i = 0
while (i < indexes.length) {
- map = map(i) = data
+ map = map(indexes(i)) = data
+ i += 1
+ }
+ }
+
+ hashMapOp compare intMapOp
+
+ val mutableMapOp = "mutable.Map" -> time {
+ val map = scala.collection.mutable.Map[Int, String]()
+ var i = 0
+
+ while (i < indexes.length) {
+ map(indexes(i)) = data
+ i += 1
+ }
+ }
+
+ hashMapOp compare mutableMapOp
+ div('=')
+ }
+
+ println()
+
+ //==========================================================================
+ {
+ title("Read 100000 Random Keys")
+
+ val indexes = new Array[Int](100000)
+ var max = -1
+ for (i <- 0 until indexes.length) {
+ indexes(i) = Math.round(Math.random * 40000000).toInt - 20000000
+ max = Math.max(max, indexes(i))
+ }
+
+ var hashMap = HashMap[Int, String]()
+
+ {
+ var i = 0
+
+ while (i < indexes.length) {
+ hashMap = hashMap(indexes(i)) = data
+ i += 1
+ }
+ }
+
+ var immutableMap = Map[Int, String]()
+
+ {
+ var i = 0
+
+ while (i < indexes.length) {
+ immutableMap = immutableMap(indexes(i)) = data
+ i += 1
+ }
+ }
+
+
+ val hashMapOp = "HashMap" -> time {
+ var i = 0
+ while (i < indexes.length) {
+ hashMap(indexes(i))
+ i += 1
+ }
+ }
+
+ val mapOp = "Map" -> time {
+ var i = 0
+ while (i < indexes.length) {
+ immutableMap(indexes(i))
+ i += 1
+ }
+ }
+
+ hashMapOp compare mapOp
+
+ var intMap = test.IntMap[String]()
+
+ {
+ var i = 0
+
+ while (i < indexes.length) {
+ intMap = intMap(indexes(i)) = data
+ i += 1
+ }
+ }
+
+ val intMapOp = "IntMap" -> time {
+ var i = 0
+ while (i < indexes.length) {
+ intMap(indexes(i))
i += 1
}
}
hashMapOp compare intMapOp
+
+ val mutableMap = scala.collection.mutable.Map[Int, String]()
+
+ {
+ var i = 0
+
+ while (i < indexes.length) {
+ mutableMap(indexes(i)) = data
+ i += 1
+ }
+ }
+
+ val mutableMapOp = "mutable.Map" -> time {
+ var i = 0
+ while (i < indexes.length) {
+ mutableMap(indexes(i))
+ i += 1
+ }
+ }
+
+ hashMapOp compare mutableMapOp
+ div('=')
}
}
}
|
djspiewak/scala-collections
|
6d1a1e6ddd5a636098b03d154c62dfa87bda230d
|
Improved tests to catch more problems with lookup
|
diff --git a/src/test/scala/HashMapSpecs.scala b/src/test/scala/HashMapSpecs.scala
index 76cc7ef..ad91893 100644
--- a/src/test/scala/HashMapSpecs.scala
+++ b/src/test/scala/HashMapSpecs.scala
@@ -1,108 +1,108 @@
import org.specs._
import org.scalacheck._
import com.codecommit.collection.HashMap
object HashMapSpecs extends Specification with Scalacheck {
import Prop._
"it" should {
"not die" in {
val map = HashMap(-1 -> -1, 0 -> 0)
map(-1) mustEqual -1
map(0) mustEqual 0
}
"store ints" in {
val prop = property { src: List[Int] =>
val map = src.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = -v }
src forall { v => map(v) == -v }
}
- prop must pass
+ prop must pass(set(maxSize -> 5000, minTestsOk -> 2000))
}
"store strings" in {
val prop = property { src: List[String] =>
val map = src.foldLeft(new HashMap[String, Int]) { (m, v) => m(v) = v.length }
src forall { v => map(v) == v.length }
}
prop must pass
}
"preserve values across changes" in {
val prop = property { (map: HashMap[String, String], ls: List[String], f: (String)=>String) =>
val filtered = ls filter { !map.contains(_) }
filtered.length > 0 ==> {
val newMap = filtered.foldLeft(map) { (m, k) => m(k) = f(k) }
(map forall { case (k, v) => newMap(k) == v }) && (filtered forall { v => newMap(v) == f(v) })
}
}
prop must pass
}
"calculate size" in {
val prop = property { (ls: Set[Int], f: (Int)=>Int) =>
val map = ls.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = f(v) }
map.size == ls.size
}
prop must pass
}
"remove ints" in {
val prop = property { map: HashMap[Int, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next // insufficient
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
"remove strings" in {
val prop = property { map: HashMap[String, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
"define empty" in {
val prop = property { map: HashMap[String, String] =>
map.empty.size == 0
}
prop must pass
}
}
implicit def arbHashMap[K](implicit ak: Arbitrary[List[K]]): Arbitrary[HashMap[K, String]] = {
Arbitrary(for {
keys <- ak.arbitrary
} yield keys.foldLeft(new HashMap[K, String]) { (m, k) => m(k) = k.toString })
}
implicit def arbSet[A](implicit arb: Arbitrary[List[A]]): Arbitrary[Set[A]] = {
Arbitrary(for {
ls <- arb.arbitrary
} yield ls.foldLeft(Set[A]()) { _ + _ })
}
}
|
djspiewak/scala-collections
|
dd923391adf1b7d5ec66553953f1103ecca030c2
|
FullNode fix
|
diff --git a/src/main/scala/com/codecommit/collection/HashMap.scala b/src/main/scala/com/codecommit/collection/HashMap.scala
index 08bce7c..423b51e 100644
--- a/src/main/scala/com/codecommit/collection/HashMap.scala
+++ b/src/main/scala/com/codecommit/collection/HashMap.scala
@@ -1,305 +1,301 @@
package com.codecommit.collection
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
*/
final class HashMap[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashMap(root(key, key.hashCode) = value)
def -(key: K) = new HashMap(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashMap[K, A] = new HashMap(new EmptyNode[K])
def diagnose = root.toString
}
object HashMap {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashMap[K, V]) { _ + _ }
def unapply[K, V](map: HashMap[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](key: K, hash: Int, value: V) = new LeafNode(0, hash)(key, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] class LeafNode[K, +V](shift: Int, hash: Int)(key: K, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](key: K, hash: Int, value: A) = {
if (this.key == key) {
new LeafNode(shift, hash)(key, value)
} else if (this.hash == hash) {
new CollisionNode(shift, hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](shift: Int, hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
def this(shift: Int, hash: Int, pairs: (K, V)*) = this(shift, hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for {
(k, v) <- bucket
} yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(shift, hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(shift, hash)(key, value)
} else new CollisionNode(shift, hash, newBucket)
}
def elements = (bucket map { case (k, v) => (k, v) }).elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
import BitmappedNode._
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
Array.copy(table, 0, newTable, 0, table.length)
val newBits = addToTable(shift)(newTable, bits)(key, hash, value)
if (newBits == ~0) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](if (i + 1 == table.length) table.length - 1 else table.length)
Array.copy(table, 0, newTable, 0, newTable.length)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
} else {
val newTable = new Array[Node[K, V]](table.length)
Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
val iters = table flatMap { n =>
if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
}
iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
val table = new Array[Node[K, V]](pairs.foldLeft(0) { (x, pair) =>
val (_, hash, _) = pair
Math.max(x, (hash >>> shift) & 0x01f)
} + 1)
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
addToTable(shift)(table, bits)(key, hash, value)
}
new BitmappedNode(shift)(table, bits)
}
private def addToTable[K, V](shift: Int)(table: Array[Node[K, V]], bits: Int)(key: K, hash: Int, value: V) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
table(i) = (table(i)(key, hash) = value)
} else {
table(i) = new LeafNode(shift + 5, hash)(key, value)
}
bits | mask
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
- def apply(key: K, hash: Int) = {
- val i = (hash >>> shift) & 0x01f
-
- table(i)(key, hash)
- }
+ def apply(key: K, hash: Int) = table((hash >>> shift) & 0x01f)(key, hash)
def update[A >: V](key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = newTable(i)(key, hash) = value
new FullNode(shift)(newTable)
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
val node = newTable(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, Math.MAX_INT ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def elements = {
val iters = table map { _.elements }
iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
}
- override def toString = "FullNode"
+ override def toString = "FullNode(" + table.foldLeft("") { _.toString + ", " + _.toString } + ")"
}
|
djspiewak/scala-collections
|
51d7f4396f90a78d1cfc7ba6a45665d7259a7512
|
Optimized the "half-full bitmap" case
|
diff --git a/do_hash_perf b/do_hash_perf
index bfe4b02..be06cc6 100755
--- a/do_hash_perf
+++ b/do_hash_perf
@@ -1,8 +1,8 @@
#!/bin/sh
buildr test:compile
-if [ "$?" ]; then
+if [ $? -eq 0 ]; then
echo ===============================================================================
exec java -Xmx2048m -Xms512m -server -cp "${SCALA_HOME}/lib/scala-library.jar:target/classes:target/test/classes" HashPerf
fi
diff --git a/src/main/scala/com/codecommit/collection/HashMap.scala b/src/main/scala/com/codecommit/collection/HashMap.scala
index fa6c8da..08bce7c 100644
--- a/src/main/scala/com/codecommit/collection/HashMap.scala
+++ b/src/main/scala/com/codecommit/collection/HashMap.scala
@@ -1,301 +1,305 @@
package com.codecommit.collection
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
*/
final class HashMap[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashMap(root(key, key.hashCode) = value)
def -(key: K) = new HashMap(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashMap[K, A] = new HashMap(new EmptyNode[K])
def diagnose = root.toString
}
object HashMap {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashMap[K, V]) { _ + _ }
def unapply[K, V](map: HashMap[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](key: K, hash: Int, value: V) = new LeafNode(0, hash)(key, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] class LeafNode[K, +V](shift: Int, hash: Int)(key: K, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](key: K, hash: Int, value: A) = {
if (this.key == key) {
new LeafNode(shift, hash)(key, value)
} else if (this.hash == hash) {
new CollisionNode(shift, hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](shift: Int, hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
def this(shift: Int, hash: Int, pairs: (K, V)*) = this(shift, hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for {
(k, v) <- bucket
} yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(shift, hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(shift, hash)(key, value)
} else new CollisionNode(shift, hash, newBucket)
}
def elements = (bucket map { case (k, v) => (k, v) }).elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
import BitmappedNode._
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
- val newTable = new Array[Node[K, A]](32)
- Array.copy(table, 0, newTable, 0, 32)
+ val newTable = new Array[Node[K, A]](Math.max(table.length, i + 1))
+ Array.copy(table, 0, newTable, 0, table.length)
val newBits = addToTable(shift)(newTable, bits)(key, hash, value)
- if (newBits == Math.MIN_INT) {
+ if (newBits == ~0) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
- val newTable = new Array[Node[K, V]](32)
- Array.copy(table, 0, newTable, 0, 32)
+ val newTable = new Array[Node[K, V]](if (i + 1 == table.length) table.length - 1 else table.length)
+ Array.copy(table, 0, newTable, 0, newTable.length)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
} else {
- val newTable = new Array[Node[K, V]](32)
- Array.copy(table, 0, newTable, 0, 32)
+ val newTable = new Array[Node[K, V]](table.length)
+ Array.copy(table, 0, newTable, 0, table.length)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
val iters = table flatMap { n =>
if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
}
iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
- val table = new Array[Node[K, V]](32)
+ val table = new Array[Node[K, V]](pairs.foldLeft(0) { (x, pair) =>
+ val (_, hash, _) = pair
+ Math.max(x, (hash >>> shift) & 0x01f)
+ } + 1)
+
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
addToTable(shift)(table, bits)(key, hash, value)
}
new BitmappedNode(shift)(table, bits)
}
private def addToTable[K, V](shift: Int)(table: Array[Node[K, V]], bits: Int)(key: K, hash: Int, value: V) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
table(i) = (table(i)(key, hash) = value)
} else {
table(i) = new LeafNode(shift + 5, hash)(key, value)
}
bits | mask
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
table(i)(key, hash)
}
def update[A >: V](key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = newTable(i)(key, hash) = value
new FullNode(shift)(newTable)
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
val node = newTable(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, Math.MAX_INT ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def elements = {
val iters = table map { _.elements }
iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
}
override def toString = "FullNode"
}
diff --git a/src/test/scala/HashMapSpecs.scala b/src/test/scala/HashMapSpecs.scala
index cf8742a..76cc7ef 100644
--- a/src/test/scala/HashMapSpecs.scala
+++ b/src/test/scala/HashMapSpecs.scala
@@ -1,101 +1,108 @@
import org.specs._
import org.scalacheck._
import com.codecommit.collection.HashMap
object HashMapSpecs extends Specification with Scalacheck {
import Prop._
"it" should {
+ "not die" in {
+ val map = HashMap(-1 -> -1, 0 -> 0)
+
+ map(-1) mustEqual -1
+ map(0) mustEqual 0
+ }
+
"store ints" in {
val prop = property { src: List[Int] =>
val map = src.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = -v }
src forall { v => map(v) == -v }
}
prop must pass
}
"store strings" in {
val prop = property { src: List[String] =>
val map = src.foldLeft(new HashMap[String, Int]) { (m, v) => m(v) = v.length }
src forall { v => map(v) == v.length }
}
prop must pass
}
"preserve values across changes" in {
val prop = property { (map: HashMap[String, String], ls: List[String], f: (String)=>String) =>
val filtered = ls filter { !map.contains(_) }
filtered.length > 0 ==> {
val newMap = filtered.foldLeft(map) { (m, k) => m(k) = f(k) }
(map forall { case (k, v) => newMap(k) == v }) && (filtered forall { v => newMap(v) == f(v) })
}
}
prop must pass
}
"calculate size" in {
val prop = property { (ls: Set[Int], f: (Int)=>Int) =>
val map = ls.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = f(v) }
map.size == ls.size
}
prop must pass
}
"remove ints" in {
val prop = property { map: HashMap[Int, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next // insufficient
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
"remove strings" in {
val prop = property { map: HashMap[String, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
"define empty" in {
val prop = property { map: HashMap[String, String] =>
map.empty.size == 0
}
prop must pass
}
}
implicit def arbHashMap[K](implicit ak: Arbitrary[List[K]]): Arbitrary[HashMap[K, String]] = {
Arbitrary(for {
keys <- ak.arbitrary
} yield keys.foldLeft(new HashMap[K, String]) { (m, k) => m(k) = k.toString })
}
implicit def arbSet[A](implicit arb: Arbitrary[List[A]]): Arbitrary[Set[A]] = {
Arbitrary(for {
ls <- arb.arbitrary
} yield ls.foldLeft(Set[A]()) { _ + _ })
}
}
|
djspiewak/scala-collections
|
d1f4e5d8e2abd8afc67700295b8101d62a48e7e7
|
Hopefully fixed odd bash error
|
diff --git a/do_perf b/do_perf
index cf9d23c..c50b49f 100755
--- a/do_perf
+++ b/do_perf
@@ -1,8 +1,8 @@
#!/bin/sh
buildr test:compile
-if [$? -eq 0]; then
+if [ "$?" ]; then
echo ===============================================================================
exec java -Xmx2048m -Xms512m -server -cp "${SCALA_HOME}/lib/scala-library.jar:target/classes:target/test/classes" VectorPerf
fi
|
djspiewak/scala-collections
|
9aaf7dacef1dc2951c12b48ebe7d7efb939568c2
|
Added HashPerf
|
diff --git a/do_hash_perf b/do_hash_perf
new file mode 100755
index 0000000..bfe4b02
--- /dev/null
+++ b/do_hash_perf
@@ -0,0 +1,8 @@
+#!/bin/sh
+
+buildr test:compile
+
+if [ "$?" ]; then
+ echo ===============================================================================
+ exec java -Xmx2048m -Xms512m -server -cp "${SCALA_HOME}/lib/scala-library.jar:target/classes:target/test/classes" HashPerf
+fi
diff --git a/src/test/scala/HashPerf.scala b/src/test/scala/HashPerf.scala
new file mode 100644
index 0000000..ae0295c
--- /dev/null
+++ b/src/test/scala/HashPerf.scala
@@ -0,0 +1,57 @@
+import com.codecommit.collection.HashMap
+
+object HashPerf {
+ import PerfLib._
+
+ def main(args: Array[String]) {
+ println()
+
+ //==========================================================================
+ {
+ title("Fill 100000 Random Keys")
+
+ val indexes = new Array[Int](100000)
+ var max = -1
+ for (i <- 0 until indexes.length) {
+ indexes(i) = Math.round(Math.random * 40000000).toInt
+ max = Math.max(max, indexes(i))
+ }
+
+ val data = "The quick brown fox jumped over the lazy red dog"
+
+ val hashMapOp = "HashMap" -> time {
+ var map = HashMap[Int, String]()
+ var i = 0
+
+ while (i < indexes.length) {
+ map = map + (i -> data)
+ i += 1
+ }
+ }
+
+ val mapOp = "Map" -> time {
+ var map = Map[Int, String]()
+ var i = 0
+
+ while (i < indexes.length) {
+ map = map + (i -> data)
+ i += 1
+ }
+ }
+
+ hashMapOp compare mapOp
+
+ val intMapOp = "Map" -> time {
+ var map = test.IntMap[String]()
+ var i = 0
+
+ while (i < indexes.length) {
+ map = map(i) = data
+ i += 1
+ }
+ }
+
+ hashMapOp compare intMapOp
+ }
+ }
+}
diff --git a/src/test/scala/PerfLib.scala b/src/test/scala/PerfLib.scala
new file mode 100644
index 0000000..15fe663
--- /dev/null
+++ b/src/test/scala/PerfLib.scala
@@ -0,0 +1,117 @@
+object PerfLib {
+ @inline
+ def time(op: =>Unit) = {
+ var data = new Array[Test](12)
+
+ var minTime = Math.MAX_LONG
+ var minMem = Math.MAX_LONG
+ var minTimeI = 0
+ var minMemI = 0
+
+ var maxTime = Math.MIN_LONG
+ var maxMem = Math.MIN_LONG
+ var maxTimeI = 1
+ var maxMemI = 1
+
+ for (i <- 0 until data.length) {
+ val mem = Runtime.getRuntime.freeMemory
+ val start = System.nanoTime
+ op
+ data(i) = Test(System.nanoTime - start, mem - Runtime.getRuntime.freeMemory)
+
+ if (data(i).nanos < minTime) {
+ minTime = data(i).nanos
+ minTimeI = i
+ }
+ if (data(i).bytes < minMem) {
+ minMem = data(i).bytes
+ minMemI = i
+ }
+
+ if (data(i).nanos > maxTime) {
+ maxTime = data(i).nanos
+ maxTimeI = i
+ }
+ if (data(i).bytes > maxMem) {
+ maxMem = data(i).bytes
+ maxMemI = i
+ }
+
+ Runtime.getRuntime.gc()
+ }
+
+ var sumTime: BigInt = 0
+ var sumMem: BigInt = 0
+ for (i <- 0 until data.length) {
+ if (i != minTimeI && i != maxTimeI) {
+ sumTime += data(i).nanos
+ }
+
+ if (i != minMemI && i != maxMemI) {
+ sumMem += data(i).bytes
+ }
+ }
+
+ Test((sumTime / (data.length - 2)).longValue, (sumMem / (data.length - 2)).longValue)
+ }
+
+ def title(str: String) {
+ div('=')
+ println(" " + str)
+ }
+
+ def div(c: Char) = {
+ for (i <- 0 until 80) print(c)
+ println()
+ }
+
+ implicit def opToComparison(op1: (String, Test)) = new ComparisonClass(op1)
+
+ class ComparisonClass(op1: (String, Test)) {
+ private val timeTemplate = "%%%ds Time: %%fms%n"
+ private val memoryTemplate = "%%%ds Memory: %%f KB%n"
+
+ private val diff = "Time Difference"
+ private val memDiff = "Memory Difference"
+ private val diffTemplate = "%%%ds: %%%%f%%s%n"
+
+ private val percent = "Percentage Difference"
+ private val percentTemplate = "%%%ds: %%%%f%%%%%%%%%n"
+
+ def compare(op2: (String, Test)) {
+ import Math.max
+
+ val (op1Name, Test(op1Time, op1Mem)) = op1
+ val (op2Name, Test(op2Time, op2Mem)) = op2
+
+ val widthTotal = max(op1Name.length + 7, max(op2Name.length + 7, max(diff.length, max(memDiff.length, percent.length)))) + 2
+
+ val width:java.lang.Integer = widthTotal
+ val timeWidth:java.lang.Integer = widthTotal - 5
+ val memWidth:java.lang.Integer = widthTotal - 7
+
+ val timeFormat = String.format(timeTemplate, Array(timeWidth))
+ val memoryFormat = String.format(memoryTemplate, Array(memWidth))
+ val diffFormat = String.format(String.format(diffTemplate, Array(width)), Array(diff, "ms"))
+ val memDiffFormat = String.format(String.format(diffTemplate, Array(width)), Array(memDiff, " KB"))
+ val percentFormat = String.format(String.format(percentTemplate, Array(width)), Array(percent))
+
+ div('-')
+
+ printf(timeFormat, op1Name, (op1Time:Double) / 1000000)
+ printf(timeFormat, op2Name, (op2Time:Double) / 1000000)
+
+ printf(memoryFormat, op1Name, (op1Mem:Double) / 1024)
+ printf(memoryFormat, op2Name, (op2Mem:Double) / 1024)
+
+ println()
+ printf(diffFormat, ((op1Time - op2Time):Double) / 1000000)
+ printf(percentFormat, (((op1Time:Double) / (op2Time:Double)) - 1) * 100)
+
+ println()
+ printf(memDiffFormat, ((op1Mem - op2Mem):Double) / 1024)
+ }
+ }
+
+ case class Test(nanos: Long, bytes: Long)
+}
diff --git a/src/test/scala/VectorPerf.scala b/src/test/scala/VectorPerf.scala
index 676256d..3a93bd4 100644
--- a/src/test/scala/VectorPerf.scala
+++ b/src/test/scala/VectorPerf.scala
@@ -1,433 +1,319 @@
import com.codecommit.collection.Vector
import scala.collection.mutable.ArrayBuffer
object VectorPerf {
+ import PerfLib._
+
def main(args: Array[String]) {
println()
//==========================================================================
{
title("Fill 100000 Sequential Indexes")
val vectorOp = "Vector" -> time {
var vec = Vector[Int]()
var i = 0
while (i < 100000) {
vec += i
i += 1
}
}
val arrayOp = "ArrayBuffer" -> time {
var arr = new ArrayBuffer[Int]
var i = 0
while (i < 100000) {
arr += i
i += 1
}
}
vectorOp compare arrayOp
val intMapOp = "IntMap" -> time {
var map = test.IntMap[Int]()
var i = 0
while (i < 100000) {
map = map(i) = i
i += 1
}
}
vectorOp compare intMapOp
val oldIntMapOp = "Map[Int, _]" -> time {
var map = Map[Int, Int]()
var i = 0
while (i < 100000) {
map = map(i) = i
i += 1
}
}
vectorOp compare oldIntMapOp
div('=')
println()
}
//==========================================================================
{
title("Read 100000 Sequential Indexes")
var vec = Vector[Int]()
for (i <- 0 until 100000) {
vec += i
}
var arr = new ArrayBuffer[Int]
for (i <- 0 until 100000) {
arr += i
}
var bitVec = Vector[Int]()
for (i <- 0 until 100000) {
bitVec += i
}
var map = test.IntMap[Int]()
for (i <- 0 until 100000) {
map = map(i) = i
}
var oldMap = Map[Int, Int]()
for (i <- 0 until 100000) {
oldMap = oldMap(i) = i
}
val vectorOp = "Vector" -> time {
var i = 0
while (i < vec.length) {
vec(i)
i += 1
}
}
val arrayOp = "ArrayBuffer" -> time {
var i = 0
while (i < arr.size) {
arr(i)
i += 1
}
}
vectorOp compare arrayOp
val intMapOp = "IntMap" -> time {
var i = 0
while (i < vec.length) { // map.size is unsuitable
map(i)
i += 1
}
}
vectorOp compare intMapOp
val oldIntMapOp = "Map[Int, _]" -> time {
var i = 0
while (i < vec.length) { // map.size is unsuitable
oldMap(i)
i += 1
}
}
vectorOp compare oldIntMapOp
div('=')
println()
}
//==========================================================================
{
title("Read 100000 Random Indexes")
val indexes = new Array[Int](100000)
var max = -1
for (i <- 0 until indexes.length) {
indexes(i) = Math.round(Math.random * 40000000).toInt
max = Math.max(max, indexes(i))
}
var vec = Vector[Int]()
for (i <- 0 to max) { // unplesant hack
vec += 0
}
for (i <- 0 until indexes.length) {
vec = vec(indexes(i)) = i
}
val arr = new ArrayBuffer[Int]
for (i <- 0 to max) { // unplesant hack
arr += 0
}
for (i <- 0 until indexes.length) {
arr(indexes(i)) = i
}
var bitVec = Vector[Int]()
for (i <- 0 to max) { // unplesant hack
bitVec += 0
}
for (i <- 0 until indexes.length) {
bitVec(indexes(i)) = i
}
var map = test.IntMap[Int]()
for (i <- 0 until indexes.length) {
map = map(indexes(i)) = i
}
var oldMap = Map[Int, Int]()
for (i <- 0 until indexes.length) {
oldMap = map(indexes(i)) = i
}
val vectorOp = "Vector" -> time {
var i = 0
while (i < indexes.length) {
vec(indexes(i))
i += 1
}
}
val arrayOp = "ArrayBuffer" -> time {
var i = 0
while (i < indexes.length) {
arr(indexes(i))
i += 1
}
}
vectorOp compare arrayOp
val intMapOp = "IntMap" -> time {
var i = 0
while (i < indexes.length) {
map(indexes(i))
i += 1
}
}
vectorOp compare intMapOp
val oldIntMapOp = "Map[Int, _]" -> time {
var i = 0
while (i < indexes.length) {
oldMap(indexes(i))
i += 1
}
}
vectorOp compare oldIntMapOp
div('=')
println()
}
//==========================================================================
{
title("Reverse of Length 100000")
var vec = Vector[Int]()
for (i <- 0 until 100000) {
vec += i
}
var arr = new ArrayBuffer[Int]
for (i <- 0 until 100000) {
arr += i
}
var bitVec = Vector[Int]()
for (i <- 0 until 100000) {
bitVec += i
}
var map = test.IntMap[Int]()
for (i <- 0 until 100000) {
map = map(i) = i
}
val vectorOp = "Vector" -> time {
vec.reverse
}
val arrayOp = "ArrayBuffer" -> time {
arr.reverse
}
vectorOp compare arrayOp
div('=')
println()
}
//==========================================================================
{
title("Compute Length (100000)")
var vec = Vector[Int]()
for (i <- 0 until 100000) {
vec += i
}
var arr = new ArrayBuffer[Int]
for (i <- 0 until 100000) {
arr += i
}
var bitVec = Vector[Int]()
for (i <- 0 until 100000) {
bitVec += i
}
var map = test.IntMap[Int]()
for (i <- 0 until 100000) {
map = map(i) = i
}
var oldMap = Map[Int, Int]()
for (i <- 0 until 100000) {
oldMap = oldMap(i) = i
}
val vectorOp = "Vector" -> time {
vec.length
}
val arrayOp = "ArrayBuffer" -> time {
arr.length
}
vectorOp compare arrayOp
val intMapOp = "IntMap" -> time {
map.size
}
vectorOp compare intMapOp
val oldIntMapOp = "Map[Int, _]" -> time {
oldMap.size
}
vectorOp compare oldIntMapOp
div('=')
println()
}
}
-
- @inline
- def time(op: =>Unit) = {
- var data = new Array[Test](12)
-
- var minTime = Math.MAX_LONG
- var minMem = Math.MAX_LONG
- var minTimeI = 0
- var minMemI = 0
-
- var maxTime = Math.MIN_LONG
- var maxMem = Math.MIN_LONG
- var maxTimeI = 1
- var maxMemI = 1
-
- for (i <- 0 until data.length) {
- val mem = Runtime.getRuntime.freeMemory
- val start = System.nanoTime
- op
- data(i) = Test(System.nanoTime - start, mem - Runtime.getRuntime.freeMemory)
-
- if (data(i).nanos < minTime) {
- minTime = data(i).nanos
- minTimeI = i
- }
- if (data(i).bytes < minMem) {
- minMem = data(i).bytes
- minMemI = i
- }
-
- if (data(i).nanos > maxTime) {
- maxTime = data(i).nanos
- maxTimeI = i
- }
- if (data(i).bytes > maxMem) {
- maxMem = data(i).bytes
- maxMemI = i
- }
-
- Runtime.getRuntime.gc()
- }
-
- var sumTime: BigInt = 0
- var sumMem: BigInt = 0
- for (i <- 0 until data.length) {
- if (i != minTimeI && i != maxTimeI) {
- sumTime += data(i).nanos
- }
-
- if (i != minMemI && i != maxMemI) {
- sumMem += data(i).bytes
- }
- }
-
- Test((sumTime / (data.length - 2)).longValue, (sumMem / (data.length - 2)).longValue)
- }
-
- private def title(str: String) {
- div('=')
- println(" " + str)
- }
-
- private def div(c: Char) = {
- for (i <- 0 until 80) print(c)
- println()
- }
-
- private implicit def opToComparison(op1: (String, Test)) = new ComparisonClass(op1)
-
- private class ComparisonClass(op1: (String, Test)) {
- private val timeTemplate = "%%%ds Time: %%fms%n"
- private val memoryTemplate = "%%%ds Memory: %%f KB%n"
-
- private val diff = "Time Difference"
- private val memDiff = "Memory Difference"
- private val diffTemplate = "%%%ds: %%%%f%%s%n"
-
- private val percent = "Percentage Difference"
- private val percentTemplate = "%%%ds: %%%%f%%%%%%%%%n"
-
- def compare(op2: (String, Test)) {
- import Math.max
-
- val (op1Name, Test(op1Time, op1Mem)) = op1
- val (op2Name, Test(op2Time, op2Mem)) = op2
-
- val widthTotal = max(op1Name.length + 7, max(op2Name.length + 7, max(diff.length, max(memDiff.length, percent.length)))) + 2
-
- val width:java.lang.Integer = widthTotal
- val timeWidth:java.lang.Integer = widthTotal - 5
- val memWidth:java.lang.Integer = widthTotal - 7
-
- val timeFormat = String.format(timeTemplate, Array(timeWidth))
- val memoryFormat = String.format(memoryTemplate, Array(memWidth))
- val diffFormat = String.format(String.format(diffTemplate, Array(width)), Array(diff, "ms"))
- val memDiffFormat = String.format(String.format(diffTemplate, Array(width)), Array(memDiff, " KB"))
- val percentFormat = String.format(String.format(percentTemplate, Array(width)), Array(percent))
-
- div('-')
-
- printf(timeFormat, op1Name, (op1Time:Double) / 1000000)
- printf(timeFormat, op2Name, (op2Time:Double) / 1000000)
-
- printf(memoryFormat, op1Name, (op1Mem:Double) / 1024)
- printf(memoryFormat, op2Name, (op2Mem:Double) / 1024)
-
- println()
- printf(diffFormat, ((op1Time - op2Time):Double) / 1000000)
- printf(percentFormat, (((op1Time:Double) / (op2Time:Double)) - 1) * 100)
-
- println()
- printf(memDiffFormat, ((op1Mem - op2Mem):Double) / 1024)
- }
- }
-
- case class Test(nanos: Long, bytes: Long)
}
|
djspiewak/scala-collections
|
f36ca226e440c030e53a9f5655de82890ce4ea86
|
Added check to ensure that compilation succedes
|
diff --git a/do_perf b/do_perf
index a816cb9..cf9d23c 100755
--- a/do_perf
+++ b/do_perf
@@ -1,6 +1,8 @@
#!/bin/sh
buildr test:compile
-echo ===============================================================================
-exec java -Xmx2048m -Xms512m -server -cp "${SCALA_HOME}/lib/scala-library.jar:target/classes:target/test/classes" VectorPerf
+if [$? -eq 0]; then
+ echo ===============================================================================
+ exec java -Xmx2048m -Xms512m -server -cp "${SCALA_HOME}/lib/scala-library.jar:target/classes:target/test/classes" VectorPerf
+fi
|
djspiewak/scala-collections
|
274b15615e78c8a73b625ad31286eec23825ec99
|
Removed unnecessary import
|
diff --git a/src/main/scala/com/codecommit/collection/HashMap.scala b/src/main/scala/com/codecommit/collection/HashMap.scala
index 4c455e5..fa6c8da 100644
--- a/src/main/scala/com/codecommit/collection/HashMap.scala
+++ b/src/main/scala/com/codecommit/collection/HashMap.scala
@@ -1,303 +1,301 @@
package com.codecommit.collection
-import HashMap._
-
/**
* A clean-room port of Rich Hickey's persistent hash trie implementation from
* Clojure (http://clojure.org). Originally presented as a mutable structure in
* a paper by Phil Bagwell.
*
* @author Daniel Spiewak
*/
final class HashMap[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashMap(root(key, key.hashCode) = value)
def -(key: K) = new HashMap(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashMap[K, A] = new HashMap(new EmptyNode[K])
def diagnose = root.toString
}
object HashMap {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashMap[K, V]) { _ + _ }
def unapply[K, V](map: HashMap[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](key: K, hash: Int, value: V) = new LeafNode(0, hash)(key, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] class LeafNode[K, +V](shift: Int, hash: Int)(key: K, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](key: K, hash: Int, value: A) = {
if (this.key == key) {
new LeafNode(shift, hash)(key, value)
} else if (this.hash == hash) {
new CollisionNode(shift, hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](shift: Int, hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
def this(shift: Int, hash: Int, pairs: (K, V)*) = this(shift, hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for {
(k, v) <- bucket
} yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(shift, hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(shift, hash)(key, value)
} else new CollisionNode(shift, hash, newBucket)
}
def elements = (bucket map { case (k, v) => (k, v) }).elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
import BitmappedNode._
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
val newBits = addToTable(shift)(newTable, bits)(key, hash, value)
if (newBits == Math.MIN_INT) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
} else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
val iters = table flatMap { n =>
if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
}
iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
val table = new Array[Node[K, V]](32)
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
addToTable(shift)(table, bits)(key, hash, value)
}
new BitmappedNode(shift)(table, bits)
}
private def addToTable[K, V](shift: Int)(table: Array[Node[K, V]], bits: Int)(key: K, hash: Int, value: V) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
table(i) = (table(i)(key, hash) = value)
} else {
table(i) = new LeafNode(shift + 5, hash)(key, value)
}
bits | mask
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
table(i)(key, hash)
}
def update[A >: V](key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = newTable(i)(key, hash) = value
new FullNode(shift)(newTable)
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
val node = newTable(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, Math.MAX_INT ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def elements = {
val iters = table map { _.elements }
iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
}
override def toString = "FullNode"
}
|
djspiewak/scala-collections
|
e2d3f924c459b51cef39d45a8d4f25c5406532eb
|
Fixed classname to comply with filename
|
diff --git a/src/test/scala/VectorPerf.scala b/src/test/scala/VectorPerf.scala
index 078deee..676256d 100644
--- a/src/test/scala/VectorPerf.scala
+++ b/src/test/scala/VectorPerf.scala
@@ -1,433 +1,433 @@
import com.codecommit.collection.Vector
import scala.collection.mutable.ArrayBuffer
-object VectorPerfTest {
+object VectorPerf {
def main(args: Array[String]) {
println()
//==========================================================================
{
title("Fill 100000 Sequential Indexes")
val vectorOp = "Vector" -> time {
var vec = Vector[Int]()
var i = 0
while (i < 100000) {
vec += i
i += 1
}
}
val arrayOp = "ArrayBuffer" -> time {
var arr = new ArrayBuffer[Int]
var i = 0
while (i < 100000) {
arr += i
i += 1
}
}
vectorOp compare arrayOp
val intMapOp = "IntMap" -> time {
var map = test.IntMap[Int]()
var i = 0
while (i < 100000) {
map = map(i) = i
i += 1
}
}
vectorOp compare intMapOp
val oldIntMapOp = "Map[Int, _]" -> time {
var map = Map[Int, Int]()
var i = 0
while (i < 100000) {
map = map(i) = i
i += 1
}
}
vectorOp compare oldIntMapOp
div('=')
println()
}
//==========================================================================
{
title("Read 100000 Sequential Indexes")
var vec = Vector[Int]()
for (i <- 0 until 100000) {
vec += i
}
var arr = new ArrayBuffer[Int]
for (i <- 0 until 100000) {
arr += i
}
var bitVec = Vector[Int]()
for (i <- 0 until 100000) {
bitVec += i
}
var map = test.IntMap[Int]()
for (i <- 0 until 100000) {
map = map(i) = i
}
var oldMap = Map[Int, Int]()
for (i <- 0 until 100000) {
oldMap = oldMap(i) = i
}
val vectorOp = "Vector" -> time {
var i = 0
while (i < vec.length) {
vec(i)
i += 1
}
}
val arrayOp = "ArrayBuffer" -> time {
var i = 0
while (i < arr.size) {
arr(i)
i += 1
}
}
vectorOp compare arrayOp
val intMapOp = "IntMap" -> time {
var i = 0
while (i < vec.length) { // map.size is unsuitable
map(i)
i += 1
}
}
vectorOp compare intMapOp
val oldIntMapOp = "Map[Int, _]" -> time {
var i = 0
while (i < vec.length) { // map.size is unsuitable
oldMap(i)
i += 1
}
}
vectorOp compare oldIntMapOp
div('=')
println()
}
//==========================================================================
{
title("Read 100000 Random Indexes")
val indexes = new Array[Int](100000)
var max = -1
for (i <- 0 until indexes.length) {
indexes(i) = Math.round(Math.random * 40000000).toInt
max = Math.max(max, indexes(i))
}
var vec = Vector[Int]()
for (i <- 0 to max) { // unplesant hack
vec += 0
}
for (i <- 0 until indexes.length) {
vec = vec(indexes(i)) = i
}
val arr = new ArrayBuffer[Int]
for (i <- 0 to max) { // unplesant hack
arr += 0
}
for (i <- 0 until indexes.length) {
arr(indexes(i)) = i
}
var bitVec = Vector[Int]()
for (i <- 0 to max) { // unplesant hack
bitVec += 0
}
for (i <- 0 until indexes.length) {
bitVec(indexes(i)) = i
}
var map = test.IntMap[Int]()
for (i <- 0 until indexes.length) {
map = map(indexes(i)) = i
}
var oldMap = Map[Int, Int]()
for (i <- 0 until indexes.length) {
oldMap = map(indexes(i)) = i
}
val vectorOp = "Vector" -> time {
var i = 0
while (i < indexes.length) {
vec(indexes(i))
i += 1
}
}
val arrayOp = "ArrayBuffer" -> time {
var i = 0
while (i < indexes.length) {
arr(indexes(i))
i += 1
}
}
vectorOp compare arrayOp
val intMapOp = "IntMap" -> time {
var i = 0
while (i < indexes.length) {
map(indexes(i))
i += 1
}
}
vectorOp compare intMapOp
val oldIntMapOp = "Map[Int, _]" -> time {
var i = 0
while (i < indexes.length) {
oldMap(indexes(i))
i += 1
}
}
vectorOp compare oldIntMapOp
div('=')
println()
}
//==========================================================================
{
title("Reverse of Length 100000")
var vec = Vector[Int]()
for (i <- 0 until 100000) {
vec += i
}
var arr = new ArrayBuffer[Int]
for (i <- 0 until 100000) {
arr += i
}
var bitVec = Vector[Int]()
for (i <- 0 until 100000) {
bitVec += i
}
var map = test.IntMap[Int]()
for (i <- 0 until 100000) {
map = map(i) = i
}
val vectorOp = "Vector" -> time {
vec.reverse
}
val arrayOp = "ArrayBuffer" -> time {
arr.reverse
}
vectorOp compare arrayOp
div('=')
println()
}
//==========================================================================
{
title("Compute Length (100000)")
var vec = Vector[Int]()
for (i <- 0 until 100000) {
vec += i
}
var arr = new ArrayBuffer[Int]
for (i <- 0 until 100000) {
arr += i
}
var bitVec = Vector[Int]()
for (i <- 0 until 100000) {
bitVec += i
}
var map = test.IntMap[Int]()
for (i <- 0 until 100000) {
map = map(i) = i
}
var oldMap = Map[Int, Int]()
for (i <- 0 until 100000) {
oldMap = oldMap(i) = i
}
val vectorOp = "Vector" -> time {
vec.length
}
val arrayOp = "ArrayBuffer" -> time {
arr.length
}
vectorOp compare arrayOp
val intMapOp = "IntMap" -> time {
map.size
}
vectorOp compare intMapOp
val oldIntMapOp = "Map[Int, _]" -> time {
oldMap.size
}
vectorOp compare oldIntMapOp
div('=')
println()
}
}
@inline
def time(op: =>Unit) = {
var data = new Array[Test](12)
var minTime = Math.MAX_LONG
var minMem = Math.MAX_LONG
var minTimeI = 0
var minMemI = 0
var maxTime = Math.MIN_LONG
var maxMem = Math.MIN_LONG
var maxTimeI = 1
var maxMemI = 1
for (i <- 0 until data.length) {
val mem = Runtime.getRuntime.freeMemory
val start = System.nanoTime
op
data(i) = Test(System.nanoTime - start, mem - Runtime.getRuntime.freeMemory)
if (data(i).nanos < minTime) {
minTime = data(i).nanos
minTimeI = i
}
if (data(i).bytes < minMem) {
minMem = data(i).bytes
minMemI = i
}
if (data(i).nanos > maxTime) {
maxTime = data(i).nanos
maxTimeI = i
}
if (data(i).bytes > maxMem) {
maxMem = data(i).bytes
maxMemI = i
}
Runtime.getRuntime.gc()
}
var sumTime: BigInt = 0
var sumMem: BigInt = 0
for (i <- 0 until data.length) {
if (i != minTimeI && i != maxTimeI) {
sumTime += data(i).nanos
}
if (i != minMemI && i != maxMemI) {
sumMem += data(i).bytes
}
}
Test((sumTime / (data.length - 2)).longValue, (sumMem / (data.length - 2)).longValue)
}
private def title(str: String) {
div('=')
println(" " + str)
}
private def div(c: Char) = {
for (i <- 0 until 80) print(c)
println()
}
private implicit def opToComparison(op1: (String, Test)) = new ComparisonClass(op1)
private class ComparisonClass(op1: (String, Test)) {
private val timeTemplate = "%%%ds Time: %%fms%n"
private val memoryTemplate = "%%%ds Memory: %%f KB%n"
private val diff = "Time Difference"
private val memDiff = "Memory Difference"
private val diffTemplate = "%%%ds: %%%%f%%s%n"
private val percent = "Percentage Difference"
private val percentTemplate = "%%%ds: %%%%f%%%%%%%%%n"
def compare(op2: (String, Test)) {
import Math.max
val (op1Name, Test(op1Time, op1Mem)) = op1
val (op2Name, Test(op2Time, op2Mem)) = op2
val widthTotal = max(op1Name.length + 7, max(op2Name.length + 7, max(diff.length, max(memDiff.length, percent.length)))) + 2
val width:java.lang.Integer = widthTotal
val timeWidth:java.lang.Integer = widthTotal - 5
val memWidth:java.lang.Integer = widthTotal - 7
val timeFormat = String.format(timeTemplate, Array(timeWidth))
val memoryFormat = String.format(memoryTemplate, Array(memWidth))
val diffFormat = String.format(String.format(diffTemplate, Array(width)), Array(diff, "ms"))
val memDiffFormat = String.format(String.format(diffTemplate, Array(width)), Array(memDiff, " KB"))
val percentFormat = String.format(String.format(percentTemplate, Array(width)), Array(percent))
div('-')
printf(timeFormat, op1Name, (op1Time:Double) / 1000000)
printf(timeFormat, op2Name, (op2Time:Double) / 1000000)
printf(memoryFormat, op1Name, (op1Mem:Double) / 1024)
printf(memoryFormat, op2Name, (op2Mem:Double) / 1024)
println()
printf(diffFormat, ((op1Time - op2Time):Double) / 1000000)
printf(percentFormat, (((op1Time:Double) / (op2Time:Double)) - 1) * 100)
println()
printf(memDiffFormat, ((op1Mem - op2Mem):Double) / 1024)
}
}
case class Test(nanos: Long, bytes: Long)
}
|
djspiewak/scala-collections
|
b8b32aa3c5d90cbb85e4cb07728fc217e4898fc2
|
Modified do_perf script to account for new changes
|
diff --git a/do_perf b/do_perf
index 3e5482d..e7e57ce 100755
--- a/do_perf
+++ b/do_perf
@@ -1,4 +1,6 @@
#!/bin/sh
-buildr compile
-exec java -Xmx1024m -Xms256m -server -cp "${SCALA_HOME}/lib/scala-library.jar:target/classes" VectorPerfTest
+buildr test:compile
+
+echo ===============================================================================
+exec java -Xmx1024m -Xms256m -server -cp "${SCALA_HOME}/lib/scala-library.jar:target/test/classes" VectorPerf
diff --git a/do_perf.bat b/do_perf.bat
deleted file mode 100644
index 8c78644..0000000
--- a/do_perf.bat
+++ /dev/null
@@ -1,3 +0,0 @@
-@echo off
-
-buildr compile && "C:\Program Files\Java\jdk1.6.0_10\bin\java" -Xmx1024m -Xms256m -server -cp "C:\Program Files\Scala\lib\scala-library.jar;target\classes" VectorPerfTest
|
djspiewak/scala-collections
|
08da68eb150a18891dbf55d6c38befb6f984c9de
|
Added quick comment
|
diff --git a/src/main/scala/com/codecommit/collection/HashMap.scala b/src/main/scala/com/codecommit/collection/HashMap.scala
index 6ccf4fb..4c455e5 100644
--- a/src/main/scala/com/codecommit/collection/HashMap.scala
+++ b/src/main/scala/com/codecommit/collection/HashMap.scala
@@ -1,296 +1,303 @@
package com.codecommit.collection
import HashMap._
-class HashMap[K, +V] private (root: Node[K, V]) extends Map[K, V] {
+/**
+ * A clean-room port of Rich Hickey's persistent hash trie implementation from
+ * Clojure (http://clojure.org). Originally presented as a mutable structure in
+ * a paper by Phil Bagwell.
+ *
+ * @author Daniel Spiewak
+ */
+final class HashMap[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashMap(root(key, key.hashCode) = value)
def -(key: K) = new HashMap(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashMap[K, A] = new HashMap(new EmptyNode[K])
def diagnose = root.toString
}
object HashMap {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashMap[K, V]) { _ + _ }
def unapply[K, V](map: HashMap[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](key: K, hash: Int, value: V) = new LeafNode(0, hash)(key, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] class LeafNode[K, +V](shift: Int, hash: Int)(key: K, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](key: K, hash: Int, value: A) = {
if (this.key == key) {
new LeafNode(shift, hash)(key, value)
} else if (this.hash == hash) {
new CollisionNode(shift, hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](shift: Int, hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
def this(shift: Int, hash: Int, pairs: (K, V)*) = this(shift, hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for {
(k, v) <- bucket
} yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(shift, hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(shift, hash)(key, value)
} else new CollisionNode(shift, hash, newBucket)
}
def elements = (bucket map { case (k, v) => (k, v) }).elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
import BitmappedNode._
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
val newBits = addToTable(shift)(newTable, bits)(key, hash, value)
if (newBits == Math.MIN_INT) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
} else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
val iters = table flatMap { n =>
if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
}
iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
val table = new Array[Node[K, V]](32)
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
addToTable(shift)(table, bits)(key, hash, value)
}
new BitmappedNode(shift)(table, bits)
}
private def addToTable[K, V](shift: Int)(table: Array[Node[K, V]], bits: Int)(key: K, hash: Int, value: V) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
table(i) = (table(i)(key, hash) = value)
} else {
table(i) = new LeafNode(shift + 5, hash)(key, value)
}
bits | mask
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
table(i)(key, hash)
}
def update[A >: V](key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = newTable(i)(key, hash) = value
new FullNode(shift)(newTable)
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
val node = newTable(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, Math.MAX_INT ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def elements = {
val iters = table map { _.elements }
iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
}
override def toString = "FullNode"
}
|
djspiewak/scala-collections
|
b891b9332f1c3db42aabf0dd33072cb2805194e9
|
Added empty spec
|
diff --git a/src/test/scala/HashMapSpecs.scala b/src/test/scala/HashMapSpecs.scala
index 63a7abe..cf8742a 100644
--- a/src/test/scala/HashMapSpecs.scala
+++ b/src/test/scala/HashMapSpecs.scala
@@ -1,93 +1,101 @@
import org.specs._
import org.scalacheck._
import com.codecommit.collection.HashMap
object HashMapSpecs extends Specification with Scalacheck {
import Prop._
"it" should {
"store ints" in {
val prop = property { src: List[Int] =>
val map = src.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = -v }
src forall { v => map(v) == -v }
}
prop must pass
}
"store strings" in {
val prop = property { src: List[String] =>
val map = src.foldLeft(new HashMap[String, Int]) { (m, v) => m(v) = v.length }
src forall { v => map(v) == v.length }
}
prop must pass
}
"preserve values across changes" in {
val prop = property { (map: HashMap[String, String], ls: List[String], f: (String)=>String) =>
val filtered = ls filter { !map.contains(_) }
filtered.length > 0 ==> {
val newMap = filtered.foldLeft(map) { (m, k) => m(k) = f(k) }
(map forall { case (k, v) => newMap(k) == v }) && (filtered forall { v => newMap(v) == f(v) })
}
}
prop must pass
}
"calculate size" in {
val prop = property { (ls: Set[Int], f: (Int)=>Int) =>
val map = ls.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = f(v) }
map.size == ls.size
}
prop must pass
}
"remove ints" in {
val prop = property { map: HashMap[Int, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next // insufficient
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
"remove strings" in {
val prop = property { map: HashMap[String, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
+
+ "define empty" in {
+ val prop = property { map: HashMap[String, String] =>
+ map.empty.size == 0
+ }
+
+ prop must pass
+ }
}
implicit def arbHashMap[K](implicit ak: Arbitrary[List[K]]): Arbitrary[HashMap[K, String]] = {
Arbitrary(for {
keys <- ak.arbitrary
} yield keys.foldLeft(new HashMap[K, String]) { (m, k) => m(k) = k.toString })
}
implicit def arbSet[A](implicit arb: Arbitrary[List[A]]): Arbitrary[Set[A]] = {
Arbitrary(for {
ls <- arb.arbitrary
} yield ls.foldLeft(Set[A]()) { _ + _ })
}
}
|
djspiewak/scala-collections
|
35079a13c8d1ad01a1b803bc13594c61ab5b46c8
|
Removed unnecessary collisions
|
diff --git a/src/main/scala/com/codecommit/collection/HashMap.scala b/src/main/scala/com/codecommit/collection/HashMap.scala
index 8ed463c..6ccf4fb 100644
--- a/src/main/scala/com/codecommit/collection/HashMap.scala
+++ b/src/main/scala/com/codecommit/collection/HashMap.scala
@@ -1,296 +1,296 @@
package com.codecommit.collection
import HashMap._
class HashMap[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashMap(root(key, key.hashCode) = value)
def -(key: K) = new HashMap(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashMap[K, A] = new HashMap(new EmptyNode[K])
def diagnose = root.toString
}
object HashMap {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashMap[K, V]) { _ + _ }
def unapply[K, V](map: HashMap[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](key: K, hash: Int, value: V) = new LeafNode(0, hash)(key, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] class LeafNode[K, +V](shift: Int, hash: Int)(key: K, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](key: K, hash: Int, value: A) = {
if (this.key == key) {
new LeafNode(shift, hash)(key, value)
- } else if (this.hash == hash || hash == 0) { // if we're bottoming out, just collide
+ } else if (this.hash == hash) {
new CollisionNode(shift, hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](shift: Int, hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
def this(shift: Int, hash: Int, pairs: (K, V)*) = this(shift, hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for {
(k, v) <- bucket
} yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(shift, hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(shift, hash)(key, value)
} else new CollisionNode(shift, hash, newBucket)
}
def elements = (bucket map { case (k, v) => (k, v) }).elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
import BitmappedNode._
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
val newBits = addToTable(shift)(newTable, bits)(key, hash, value)
if (newBits == Math.MIN_INT) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
} else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
val iters = table flatMap { n =>
if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
}
iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
val table = new Array[Node[K, V]](32)
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
addToTable(shift)(table, bits)(key, hash, value)
}
new BitmappedNode(shift)(table, bits)
}
private def addToTable[K, V](shift: Int)(table: Array[Node[K, V]], bits: Int)(key: K, hash: Int, value: V) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
table(i) = (table(i)(key, hash) = value)
} else {
table(i) = new LeafNode(shift + 5, hash)(key, value)
}
bits | mask
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
table(i)(key, hash)
}
def update[A >: V](key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = newTable(i)(key, hash) = value
new FullNode(shift)(newTable)
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
val node = newTable(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, Math.MAX_INT ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def elements = {
val iters = table map { _.elements }
iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
}
override def toString = "FullNode"
}
|
djspiewak/scala-collections
|
7975de313ed5fc4d6de326ecaf2ba0c1349fd701
|
Removed printlns
|
diff --git a/src/main/scala/com/codecommit/collection/HashMap.scala b/src/main/scala/com/codecommit/collection/HashMap.scala
index 4abc60e..8ed463c 100644
--- a/src/main/scala/com/codecommit/collection/HashMap.scala
+++ b/src/main/scala/com/codecommit/collection/HashMap.scala
@@ -1,297 +1,296 @@
package com.codecommit.collection
import HashMap._
class HashMap[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashMap(root(key, key.hashCode) = value)
def -(key: K) = new HashMap(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashMap[K, A] = new HashMap(new EmptyNode[K])
def diagnose = root.toString
}
object HashMap {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashMap[K, V]) { _ + _ }
def unapply[K, V](map: HashMap[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](key: K, hash: Int, value: V) = new LeafNode(0, hash)(key, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] class LeafNode[K, +V](shift: Int, hash: Int)(key: K, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](key: K, hash: Int, value: A) = {
if (this.key == key) {
new LeafNode(shift, hash)(key, value)
} else if (this.hash == hash || hash == 0) { // if we're bottoming out, just collide
new CollisionNode(shift, hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](shift: Int, hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
def this(shift: Int, hash: Int, pairs: (K, V)*) = this(shift, hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for {
(k, v) <- bucket
} yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(shift, hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
val newBucket = bucket filter { case (k, _) => k != key }
if (newBucket.length == 1) {
val (key, value) = newBucket.head
new LeafNode(shift, hash)(key, value)
} else new CollisionNode(shift, hash, newBucket)
}
def elements = (bucket map { case (k, v) => (k, v) }).elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
import BitmappedNode._
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
val newBits = addToTable(shift)(newTable, bits)(key, hash, value)
if (newBits == Math.MIN_INT) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
- println(log)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
} else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
val iters = table flatMap { n =>
if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
}
iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
val table = new Array[Node[K, V]](32)
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
addToTable(shift)(table, bits)(key, hash, value)
}
new BitmappedNode(shift)(table, bits)
}
private def addToTable[K, V](shift: Int)(table: Array[Node[K, V]], bits: Int)(key: K, hash: Int, value: V) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
table(i) = (table(i)(key, hash) = value)
} else {
table(i) = new LeafNode(shift + 5, hash)(key, value)
}
bits | mask
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
table(i)(key, hash)
}
def update[A >: V](key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = newTable(i)(key, hash) = value
new FullNode(shift)(newTable)
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
val node = newTable(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, Math.MAX_INT ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def elements = {
val iters = table map { _.elements }
iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
}
override def toString = "FullNode"
}
|
djspiewak/scala-collections
|
6995129a71deb79e1227a614c1559b6e15448428
|
Fixed removal from CollisionNode(s)
|
diff --git a/src/main/scala/com/codecommit/collection/HashMap.scala b/src/main/scala/com/codecommit/collection/HashMap.scala
index b17cfb3..4abc60e 100644
--- a/src/main/scala/com/codecommit/collection/HashMap.scala
+++ b/src/main/scala/com/codecommit/collection/HashMap.scala
@@ -1,298 +1,297 @@
package com.codecommit.collection
import HashMap._
class HashMap[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashMap(root(key, key.hashCode) = value)
def -(key: K) = new HashMap(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashMap[K, A] = new HashMap(new EmptyNode[K])
+
+ def diagnose = root.toString
}
object HashMap {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashMap[K, V]) { _ + _ }
def unapply[K, V](map: HashMap[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](key: K, hash: Int, value: V) = new LeafNode(0, hash)(key, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] class LeafNode[K, +V](shift: Int, hash: Int)(key: K, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](key: K, hash: Int, value: A) = {
if (this.key == key) {
new LeafNode(shift, hash)(key, value)
} else if (this.hash == hash || hash == 0) { // if we're bottoming out, just collide
new CollisionNode(shift, hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](shift: Int, hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
def this(shift: Int, hash: Int, pairs: (K, V)*) = this(shift, hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for {
(k, v) <- bucket
} yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(shift, hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
- if (bucket.exists({ case (k, _) => k == key }) && size == 2) {
- var pair: (K, V) = null
-
- for {
- (k, v) <- bucket
- if k == key
- } pair = (k, v)
-
- new LeafNode(shift, hash)(pair._1, pair._2)
- } else new CollisionNode(shift, hash, bucket.dropWhile({ case (k, _) => k == key }))
+ val newBucket = bucket filter { case (k, _) => k != key }
+
+ if (newBucket.length == 1) {
+ val (key, value) = newBucket.head
+ new LeafNode(shift, hash)(key, value)
+ } else new CollisionNode(shift, hash, newBucket)
}
def elements = (bucket map { case (k, v) => (k, v) }).elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
import BitmappedNode._
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
val newBits = addToTable(shift)(newTable, bits)(key, hash, value)
if (newBits == Math.MIN_INT) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
val node = table(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
val adjustedBits = bits ^ mask
val log = Math.log(adjustedBits) / Math.log(2)
+ println(log)
if (log.toInt.toDouble == log) { // last one
table(log.toInt)
} else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = null
new BitmappedNode(shift)(newTable, adjustedBits)
}
} else {
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = node
new BitmappedNode(shift)(newTable, bits)
}
} else this
}
def elements = {
val iters = table flatMap { n =>
if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
}
iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
val table = new Array[Node[K, V]](32)
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
addToTable(shift)(table, bits)(key, hash, value)
}
new BitmappedNode(shift)(table, bits)
}
private def addToTable[K, V](shift: Int)(table: Array[Node[K, V]], bits: Int)(key: K, hash: Int, value: V) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
table(i) = (table(i)(key, hash) = value)
} else {
table(i) = new LeafNode(shift + 5, hash)(key, value)
}
bits | mask
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
table(i)(key, hash)
}
def update[A >: V](key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = newTable(i)(key, hash) = value
new FullNode(shift)(newTable)
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
val node = newTable(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, Math.MAX_INT ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def elements = {
val iters = table map { _.elements }
iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
}
override def toString = "FullNode"
}
diff --git a/src/test/scala/HashMapSpecs.scala b/src/test/scala/HashMapSpecs.scala
index 5f57ce0..63a7abe 100644
--- a/src/test/scala/HashMapSpecs.scala
+++ b/src/test/scala/HashMapSpecs.scala
@@ -1,93 +1,93 @@
import org.specs._
import org.scalacheck._
import com.codecommit.collection.HashMap
object HashMapSpecs extends Specification with Scalacheck {
import Prop._
"it" should {
"store ints" in {
val prop = property { src: List[Int] =>
val map = src.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = -v }
src forall { v => map(v) == -v }
}
prop must pass
}
"store strings" in {
val prop = property { src: List[String] =>
val map = src.foldLeft(new HashMap[String, Int]) { (m, v) => m(v) = v.length }
src forall { v => map(v) == v.length }
}
prop must pass
}
"preserve values across changes" in {
val prop = property { (map: HashMap[String, String], ls: List[String], f: (String)=>String) =>
val filtered = ls filter { !map.contains(_) }
filtered.length > 0 ==> {
val newMap = filtered.foldLeft(map) { (m, k) => m(k) = f(k) }
(map forall { case (k, v) => newMap(k) == v }) && (filtered forall { v => newMap(v) == f(v) })
}
}
prop must pass
}
"calculate size" in {
val prop = property { (ls: Set[Int], f: (Int)=>Int) =>
val map = ls.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = f(v) }
map.size == ls.size
}
prop must pass
}
"remove ints" in {
val prop = property { map: HashMap[Int, String] =>
map.size > 0 ==> {
- val (rm, _) = map.elements.next
+ val (rm, _) = map.elements.next // insufficient
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
"remove strings" in {
val prop = property { map: HashMap[String, String] =>
map.size > 0 ==> {
val (rm, _) = map.elements.next
val newMap = map - rm
!newMap.contains(rm) &&
(newMap forall { case (k, v) => map(k) == v }) &&
newMap.size == map.size - 1
}
}
prop must pass
}
}
implicit def arbHashMap[K](implicit ak: Arbitrary[List[K]]): Arbitrary[HashMap[K, String]] = {
Arbitrary(for {
keys <- ak.arbitrary
} yield keys.foldLeft(new HashMap[K, String]) { (m, k) => m(k) = k.toString })
}
implicit def arbSet[A](implicit arb: Arbitrary[List[A]]): Arbitrary[Set[A]] = {
Arbitrary(for {
ls <- arb.arbitrary
} yield ls.foldLeft(Set[A]()) { _ + _ })
}
}
|
djspiewak/scala-collections
|
72d85b97870a6fe4b1e7354b219778fb5ccdfb23
|
Toward optimized bitmapped removal
|
diff --git a/src/main/scala/com/codecommit/collection/HashMap.scala b/src/main/scala/com/codecommit/collection/HashMap.scala
index 224c6ba..b17cfb3 100644
--- a/src/main/scala/com/codecommit/collection/HashMap.scala
+++ b/src/main/scala/com/codecommit/collection/HashMap.scala
@@ -1,288 +1,298 @@
package com.codecommit.collection
import HashMap._
class HashMap[K, +V] private (root: Node[K, V]) extends Map[K, V] {
lazy val size = root.size
def this() = this(new EmptyNode[K])
def get(key: K) = root(key, key.hashCode)
override def +[A >: V](pair: (K, A)) = pair match {
case (k, v) => update(k, v)
}
def update[A >: V](key: K, value: A) = new HashMap(root(key, key.hashCode) = value)
def -(key: K) = new HashMap(root.remove(key, key.hashCode))
def elements = root.elements
def empty[A]: HashMap[K, A] = new HashMap(new EmptyNode[K])
}
object HashMap {
def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashMap[K, V]) { _ + _ }
def unapply[K, V](map: HashMap[K, V]) = map.toSeq
}
// ============================================================================
// nodes
private[collection] sealed trait Node[K, +V] {
val size: Int
def apply(key: K, hash: Int): Option[V]
def update[A >: V](key: K, hash: Int, value: A): Node[K, A]
def remove(key: K, hash: Int): Node[K, V]
def elements: Iterator[(K, V)]
}
private[collection] class EmptyNode[K] extends Node[K, Nothing] {
val size = 0
def apply(key: K, hash: Int) = None
def update[V](key: K, hash: Int, value: V) = new LeafNode(0, hash)(key, value)
def remove(key: K, hash: Int) = this
lazy val elements = new Iterator[(K, Nothing)] {
val hasNext = false
val next = null
}
}
private[collection] class LeafNode[K, +V](shift: Int, hash: Int)(key: K, value: V) extends Node[K, V] {
val size = 1
def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
def update[A >: V](key: K, hash: Int, value: A) = {
if (this.key == key) {
new LeafNode(shift, hash)(key, value)
} else if (this.hash == hash || hash == 0) { // if we're bottoming out, just collide
new CollisionNode(shift, hash, this.key -> this.value, key -> value)
} else {
BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
}
}
def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
def elements = new Iterator[(K, V)] {
var hasNext = true
def next = {
hasNext = false
(key, value)
}
}
override def toString = "LeafNode(" + key + " -> " + value + ")"
}
private[collection] class CollisionNode[K, +V](shift: Int, hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
lazy val size = bucket.length
def this(shift: Int, hash: Int, pairs: (K, V)*) = this(shift, hash, pairs.toList)
def apply(key: K, hash: Int) = {
for {
(_, v) <- bucket find { case (k, _) => k == key }
} yield v
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
if (this.hash == hash) {
var found = false
val newBucket = for {
(k, v) <- bucket
} yield {
if (k == key) {
found = true
(key, value)
} else (k, v)
}
new CollisionNode(shift, hash, if (found) newBucket else (key, value) :: bucket)
} else {
val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
}
}
def remove(key: K, hash: Int) = {
if (bucket.exists({ case (k, _) => k == key }) && size == 2) {
var pair: (K, V) = null
for {
(k, v) <- bucket
if k == key
} pair = (k, v)
new LeafNode(shift, hash)(pair._1, pair._2)
} else new CollisionNode(shift, hash, bucket.dropWhile({ case (k, _) => k == key }))
}
def elements = (bucket map { case (k, v) => (k, v) }).elements
override def toString = "CollisionNode(" + bucket.toString + ")"
}
private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
import BitmappedNode._
lazy val size = {
val sizes = for {
n <- table
if n != null
} yield n.size
sizes.foldLeft(0) { _ + _ }
}
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) table(i)(key, hash) else None
}
def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
val newBits = addToTable(shift)(newTable, bits)(key, hash, value)
if (newBits == Math.MIN_INT) {
new FullNode(shift)(newTable)
} else {
new BitmappedNode(shift)(newTable, newBits)
}
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
- val newTable = new Array[Node[K, V]](32)
- Array.copy(table, 0, newTable, 0, 32)
+ val node = table(i).remove(key, hash)
- val node = newTable(i).remove(key, hash)
- val newBits = if (node.isInstanceOf[EmptyNode[_]]) {
- newTable(i) = null
- bits ^ mask
+ if (node.isInstanceOf[EmptyNode[_]]) {
+ val adjustedBits = bits ^ mask
+ val log = Math.log(adjustedBits) / Math.log(2)
+
+ if (log.toInt.toDouble == log) { // last one
+ table(log.toInt)
+ } else {
+ val newTable = new Array[Node[K, V]](32)
+ Array.copy(table, 0, newTable, 0, 32)
+
+ newTable(i) = null
+
+ new BitmappedNode(shift)(newTable, adjustedBits)
+ }
} else {
+ val newTable = new Array[Node[K, V]](32)
+ Array.copy(table, 0, newTable, 0, 32)
+
newTable(i) = node
- bits
+ new BitmappedNode(shift)(newTable, bits)
}
-
- new BitmappedNode(shift)(newTable, newBits)
} else this
}
def elements = {
val iters = table flatMap { n =>
if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
}
iters.foldLeft(emptyElements) { _ ++ _ }
}
override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
val hasNext = false
val next = null
}
}
private[collection] object BitmappedNode {
def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
val table = new Array[Node[K, V]](32)
val bits = pairs.foldLeft(0) { (bits, pair) =>
val (key, hash, value) = pair
addToTable(shift)(table, bits)(key, hash, value)
}
new BitmappedNode(shift)(table, bits)
}
private def addToTable[K, V](shift: Int)(table: Array[Node[K, V]], bits: Int)(key: K, hash: Int, value: V) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
if ((bits & mask) == mask) {
table(i) = (table(i)(key, hash) = value)
} else {
table(i) = new LeafNode(shift + 5, hash)(key, value)
}
bits | mask
}
}
private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
lazy val size = table.foldLeft(0) { _ + _.size }
def apply(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
table(i)(key, hash)
}
def update[A >: V](key: K, hash: Int, value: A) = {
val i = (hash >>> shift) & 0x01f
val newTable = new Array[Node[K, A]](32)
Array.copy(table, 0, newTable, 0, 32)
newTable(i) = newTable(i)(key, hash) = value
new FullNode(shift)(newTable)
}
def remove(key: K, hash: Int) = {
val i = (hash >>> shift) & 0x01f
val mask = 1 << i
val newTable = new Array[Node[K, V]](32)
Array.copy(table, 0, newTable, 0, 32)
val node = newTable(i).remove(key, hash)
if (node.isInstanceOf[EmptyNode[_]]) {
newTable(i) = null
new BitmappedNode(shift)(newTable, Math.MAX_INT ^ mask)
} else {
newTable(i) = node
new FullNode(shift)(newTable)
}
}
def elements = {
val iters = table map { _.elements }
iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
}
override def toString = "FullNode"
}
|
djspiewak/scala-collections
|
1c27169755daa9975b26d44290fc2f547bc80bb1
|
Added String removal spec and refined slightly
|
diff --git a/buildfile b/buildfile
new file mode 100644
index 0000000..649a03b
--- /dev/null
+++ b/buildfile
@@ -0,0 +1,12 @@
+require 'buildr/scala'
+
+repositories.remote << 'http://www.ibiblio.org/maven2'
+repositories.remote << 'http://scala-tools.org/repo-releases'
+
+desc 'A few collections classes for fun and profit'
+define 'collection' do
+ project.version = '0.1.0'
+ project.group = 'com.codecommit'
+
+ package :jar
+end
diff --git a/do_perf b/do_perf
new file mode 100755
index 0000000..3e5482d
--- /dev/null
+++ b/do_perf
@@ -0,0 +1,4 @@
+#!/bin/sh
+
+buildr compile
+exec java -Xmx1024m -Xms256m -server -cp "${SCALA_HOME}/lib/scala-library.jar:target/classes" VectorPerfTest
diff --git a/do_perf.bat b/do_perf.bat
new file mode 100644
index 0000000..8c78644
--- /dev/null
+++ b/do_perf.bat
@@ -0,0 +1,3 @@
+@echo off
+
+buildr compile && "C:\Program Files\Java\jdk1.6.0_10\bin\java" -Xmx1024m -Xms256m -server -cp "C:\Program Files\Scala\lib\scala-library.jar;target\classes" VectorPerfTest
diff --git a/src/main/scala/IntMap.scala b/src/main/scala/IntMap.scala
new file mode 100644
index 0000000..5d29602
--- /dev/null
+++ b/src/main/scala/IntMap.scala
@@ -0,0 +1,373 @@
+package test
+
+/**
+ * @author David MacIver
+ */
+private[test] object IntMapUtils{
+ def zero(i : Int, mask : Int) = (i & mask) == 0;
+ def mask(i : Int, mask : Int) = i & (complement(mask - 1) ^ mask)
+ def hasMatch(key : Int, prefix : Int, m : Int) = mask(key, m) == prefix;
+ def unsignedCompare(i : Int, j : Int) = (i < j) ^ (i < 0) ^ (j < 0)
+ def shorter(m1 : Int, m2 : Int) = unsignedCompare(m2, m1)
+ def complement(i : Int) = (-1) ^ i;
+ def highestOneBit(j : Int) = {
+ var i = j;
+ i |= (i >> 1);
+ i |= (i >> 2);
+ i |= (i >> 4);
+ i |= (i >> 8);
+ i |= (i >> 16);
+ i - (i >>> 1);
+ }
+
+ def branchMask(i : Int, j : Int) = highestOneBit(i ^ j);
+
+ def join[T](p1 : Int, t1 : IntMap[T], p2 : Int, t2 : IntMap[T]) : IntMap[T] = {
+ val m = branchMask(p1, p2);
+ val p = mask(p1, m);
+ if (zero(p1, m)) IntMap.Bin(p, m, t1, t2)
+ else IntMap.Bin(p, m, t2, t1);
+ }
+
+ def bin[T](prefix : Int, mask : Int, left : IntMap[T], right : IntMap[T]) : IntMap[T] = (left, right) match {
+ case (left, IntMap.Nil) => left;
+ case (IntMap.Nil, right) => right;
+ case (left, right) => IntMap.Bin(prefix, mask, left, right);
+ }
+}
+
+import IntMapUtils._
+
+object IntMap{
+ def empty[T] : IntMap[T] = IntMap.Nil;
+ def singleton[T](key : Int, value : T) : IntMap[T] = IntMap.Tip(key, value);
+ def apply[T](elems : (Int, T)*) : IntMap[T] =
+ elems.foldLeft(empty[T])((x, y) => x.update(y._1, y._2));
+
+
+ private[test] case object Nil extends IntMap[Nothing]{
+ override def equals(that : Any) = this eq that.asInstanceOf[AnyRef]
+ };
+ private[test] case class Tip[+T](key : Int, value : T) extends IntMap[T]{
+ def withValue[S](s : S) =
+ if (s.asInstanceOf[AnyRef] eq value.asInstanceOf[AnyRef]) this.asInstanceOf[IntMap.Tip[S]];
+ else IntMap.Tip(key, s);
+ }
+ private[test] case class Bin[+T](prefix : Int, mask : Int, left : IntMap[T], right : IntMap[T]) extends IntMap[T]{
+ def bin[S](left : IntMap[S], right : IntMap[S]) : IntMap[S] = {
+ if ((this.left eq left) && (this.right eq right)) this.asInstanceOf[IntMap.Bin[S]];
+ else IntMap.Bin[S](prefix, mask, left, right);
+ }
+ }
+
+}
+
+import IntMap._
+
+// Iterator over a non-empty IntMap.
+private[test] abstract class IntMapIterator[V, T](it : IntMap[V]) extends Iterator[T]{
+
+ // Basically this uses a simple stack to emulate conversion over the tree. However
+ // because we know that Ints are at least 32 bits we can have at most 32 IntMap.Bins and
+ // one IntMap.Tip sitting on the tree at any point. Therefore we know the maximum stack
+ // depth is 33 and
+ var index = 0;
+ var buffer = new Array[AnyRef](33);
+
+ def pop = {
+ index -= 1;
+ buffer(index).asInstanceOf[IntMap[V]];
+ }
+
+ def push(x : IntMap[V]) {
+ buffer(index) = x.asInstanceOf[AnyRef];
+ index += 1;
+ }
+ push(it);
+
+ /**
+ * What value do we assign to a tip?
+ */
+ def valueOf(tip : IntMap.Tip[V]) : T;
+
+ def hasNext = index != 0;
+ final def next : T =
+ pop match {
+ case IntMap.Bin(_,_, [email protected](_, _), right) => {
+ push(right);
+ valueOf(t);
+ }
+ case IntMap.Bin(_, _, left, right) => {
+ push(right);
+ push(left);
+ next;
+ }
+ case [email protected](_, _) => valueOf(t);
+ // This should never happen. We don't allow IntMap.Nil in subtrees of the IntMap
+ // and don't return an IntMapIterator for IntMap.Nil.
+ case IntMap.Nil => error("Empty maps not allowed as subtrees");
+ }
+}
+
+private[test] class IntMapEntryIterator[V](it : IntMap[V]) extends IntMapIterator[V, (Int, V)](it){
+ def valueOf(tip : IntMap.Tip[V]) = (tip.key, tip.value);
+}
+
+private[test] class IntMapValueIterator[V](it : IntMap[V]) extends IntMapIterator[V, V](it){
+ def valueOf(tip : IntMap.Tip[V]) = tip.value;
+}
+
+private[test] class IntMapKeyIterator[V](it : IntMap[V]) extends IntMapIterator[V, Int](it){
+ def valueOf(tip : IntMap.Tip[V]) = tip.key;
+}
+
+import IntMap._;
+
+/**
+ * Specialised immutable map structure for integer keys, based on
+ * <a href="http://citeseer.ist.psu.edu/okasaki98fast.html">Fast Mergeable Integer Maps</a>
+ * by Okasaki and Gill. Essentially a trie based on binary digits of the the integers.
+ */
+sealed abstract class IntMap[+T] extends scala.collection.immutable.Map[Int, T]{
+ def empty[S] : IntMap[S] = IntMap.Nil;
+
+ override def toList = {
+ val buffer = new scala.collection.mutable.ListBuffer[(Int, T)];
+ foreach(buffer += _);
+ buffer.toList;
+ }
+
+ /**
+ * Iterator over key, value pairs of the map in unsigned order of the keys.
+ */
+ def elements : Iterator[(Int, T)] = this match {
+ case IntMap.Nil => Iterator.empty;
+ case _ => new IntMapEntryIterator(this);
+ }
+
+ /**
+ * Loops over the key, value pairs of the map in unsigned order of the keys.
+ */
+ override final def foreach(f : ((Int, T)) => Unit) : Unit = this match {
+ case IntMap.Bin(_, _, left, right) => {left.foreach(f); right.foreach(f); }
+ case IntMap.Tip(key, value) => f((key, value));
+ case IntMap.Nil => {};
+ }
+
+ override def keys : Iterator[Int] = this match {
+ case IntMap.Nil => Iterator.empty;
+ case _ => new IntMapKeyIterator(this);
+ }
+
+ /**
+ * Loop over the keys of the map. The same as keys.foreach(f), but may
+ * be more efficient.
+ *
+ * @param f The loop body
+ */
+ final def foreachKey(f : Int => Unit) : Unit = this match {
+ case IntMap.Bin(_, _, left, right) => {left.foreachKey(f); right.foreachKey(f); }
+ case IntMap.Tip(key, _) => f(key);
+ case IntMap.Nil => {}
+ }
+
+ override def values : Iterator[T] = this match {
+ case IntMap.Nil => Iterator.empty;
+ case _ => new IntMapValueIterator(this);
+ }
+
+ /**
+ * Loop over the keys of the map. The same as keys.foreach(f), but may
+ * be more efficient.
+ *
+ * @param f The loop body
+ */
+ final def foreachValue(f : T => Unit) : Unit = this match {
+ case IntMap.Bin(_, _, left, right) => {left.foreachValue(f); right.foreachValue(f); }
+ case IntMap.Tip(_, value) => f(value);
+ case IntMap.Nil => {};
+ }
+
+ override def stringPrefix = "IntMap"
+
+ override def isEmpty = this == IntMap.Nil;
+
+ override def filter(f : ((Int, T)) => Boolean) : IntMap[T] = this match {
+ case IntMap.Bin(prefix, mask, left, right) => {
+ val (newleft, newright) = (left.filter(f), right.filter(f));
+ if ((left eq newleft) && (right eq newright)) this;
+ else bin(prefix, mask, newleft, newright);
+ }
+ case IntMap.Tip(key, value) =>
+ if (f((key, value))) this
+ else IntMap.Nil;
+ case IntMap.Nil => IntMap.Nil;
+ }
+
+ override def transform[S](f : (Int, T) => S) : IntMap[S] = this match {
+ case [email protected](prefix, mask, left, right) => b.bin(left.transform(f), right.transform(f));
+ case [email protected](key, value) => t.withValue(f(key, value));
+ case IntMap.Nil => IntMap.Nil;
+ }
+
+ final def size : Int = this match {
+ case IntMap.Nil => 0;
+ case IntMap.Tip(_, _) => 1;
+ case IntMap.Bin(_, _, left, right) => left.size + right.size;
+ }
+
+ final def get(key : Int) : Option[T] = this match {
+ case IntMap.Bin(prefix, mask, left, right) => if (zero(key, mask)) left.get(key) else right.get(key);
+ case IntMap.Tip(key2, value) => if (key == key2) Some(value) else None;
+ case IntMap.Nil => None;
+ }
+
+ final override def getOrElse[S >: T](key : Int, default : =>S) : S = this match {
+ case IntMap.Nil => default;
+ case IntMap.Tip(key2, value) => if (key == key2) value else default;
+ case IntMap.Bin(prefix, mask, left, right) => if (zero(key, mask)) left(key) else right(key);
+ }
+
+ final override def apply(key : Int) : T = this match {
+ case IntMap.Bin(prefix, mask, left, right) => if (zero(key, mask)) left(key) else right(key);
+ case IntMap.Tip(key2, value) => if (key == key2) value else error("Key not found");
+ case IntMap.Nil => error("key not found");
+ }
+
+ def update[S >: T](key : Int, value : S) : IntMap[S] = this match {
+ case IntMap.Bin(prefix, mask, left, right) => if (!hasMatch(key, prefix, mask)) join(key, IntMap.Tip(key, value), prefix, this);
+ else if (zero(key, mask)) IntMap.Bin(prefix, mask, left.update(key, value), right)
+ else IntMap.Bin(prefix, mask, left, right.update(key, value));
+ case IntMap.Tip(key2, value2) => if (key == key2) IntMap.Tip(key, value);
+ else join(key, IntMap.Tip(key, value), key2, this);
+ case IntMap.Nil => IntMap.Tip(key, value);
+ }
+
+ /**
+ * Updates the map, using the provided function to resolve conflicts if the key is already present.
+ * Equivalent to
+ * <pre>this.get(key) match {
+ * case None => this.update(key, value);
+ * case Some(oldvalue) => this.update(key, f(oldvalue, value) }
+ * </pre>
+ *
+ * @param key The key to update
+ * @param value The value to use if there is no conflict
+ * @param f The function used to resolve conflicts.
+ */
+ def updateWith[S >: T](key : Int, value : S, f : (T, S) => S) : IntMap[S] = this match {
+ case IntMap.Bin(prefix, mask, left, right) => if (!hasMatch(key, prefix, mask)) join(key, IntMap.Tip(key, value), prefix, this);
+ else if (zero(key, mask)) IntMap.Bin(prefix, mask, left.updateWith(key, value, f), right)
+ else IntMap.Bin(prefix, mask, left, right.updateWith(key, value, f));
+ case IntMap.Tip(key2, value2) => if (key == key2) IntMap.Tip(key, f(value2, value));
+ else join(key, IntMap.Tip(key, value), key2, this);
+ case IntMap.Nil => IntMap.Tip(key, value);
+ }
+
+ def -(key : Int) : IntMap[T] = this match {
+ case IntMap.Bin(prefix, mask, left, right) =>
+ if (!hasMatch(key, prefix, mask)) this;
+ else if (zero(key, mask)) bin(prefix, mask, left - key, right);
+ else bin(prefix, mask, left, right - key);
+ case IntMap.Tip(key2, _) =>
+ if (key == key2) IntMap.Nil;
+ else this;
+ case IntMap.Nil => IntMap.Nil;
+ }
+
+ /**
+ * A combined transform and filter function. Returns an IntMap such that for each (key, value) mapping
+ * in this map, if f(key, value) == None the map contains no mapping for key, and if <code>f(key, value)
+ *
+ * @param f The transforming function.
+ */
+ def modifyOrRemove[S](f : (Int, T) => Option[S]) : IntMap[S] = this match {
+ case IntMap.Bin(prefix, mask, left, right) => {
+ val newleft = left.modifyOrRemove(f);
+ val newright = right.modifyOrRemove(f);
+ if ((left eq newleft) && (right eq newright)) this.asInstanceOf[IntMap[S]];
+ else bin(prefix, mask, newleft, newright)
+ }
+ case IntMap.Tip(key, value) => f(key, value) match {
+ case None => IntMap.Nil;
+ case Some(value2) =>
+ //hack to preserve sharing
+ if (value.asInstanceOf[AnyRef] eq value2.asInstanceOf[AnyRef]) this.asInstanceOf[IntMap[S]]
+ else IntMap.Tip(key, value2);
+ }
+ case IntMap.Nil => IntMap.Nil;
+ }
+
+
+ /**
+ * Forms a union map with that map, using the combining function to resolve conflicts.
+ *
+ * @param that the map to form a union with.
+ * @param f the function used to resolve conflicts between two mappings.
+ */
+ def unionWith[S >: T](that : IntMap[S], f : (Int, S, S) => S) : IntMap[S] = (this, that) match{
+ case (IntMap.Bin(p1, m1, l1, r1), that@(IntMap.Bin(p2, m2, l2, r2))) =>
+ if (shorter(m1, m2)) {
+ if (!hasMatch(p2, p1, m1)) join(p1, this, p2, that);
+ else if (zero(p2, m1)) IntMap.Bin(p1, m1, l1.unionWith(that, f), r1);
+ else IntMap.Bin(p1, m1, l1, r1.unionWith(that, f));
+ } else if (shorter(m2, m1)){
+ if (!hasMatch(p1, p2, m2)) join(p1, this, p2, that);
+ else if (zero(p1, m2)) IntMap.Bin(p2, m2, this.unionWith(l2, f), r2);
+ else IntMap.Bin(p2, m2, l2, this.unionWith(r2, f));
+ }
+ else {
+ if (p1 == p2) IntMap.Bin(p1, m1, l1.unionWith(l2,f), r1.unionWith(r2, f));
+ else join(p1, this, p2, that);
+ }
+ case (IntMap.Tip(key, value), x) => x.updateWith(key, value, (x, y) => f(key, y, x));
+ case (x, IntMap.Tip(key, value)) => x.updateWith[S](key, value, (x, y) => f(key, x, y));
+ case (IntMap.Nil, x) => x;
+ case (x, IntMap.Nil) => x;
+ }
+
+ /**
+ * Forms the intersection of these two maps with a combinining function. The resulting map is
+ * a map that has only keys present in both maps and has values produced from the original mappings
+ * by combining them with f.
+ *
+ * @param that The map to intersect with.
+ * @param f The combining function.
+ */
+ def intersectionWith[S, R](that : IntMap[S], f : (Int, T, S) => R) : IntMap[R] = (this, that) match {
+ case (IntMap.Bin(p1, m1, l1, r1), [email protected](p2, m2, l2, r2)) =>
+ if (shorter(m1, m2)) {
+ if (!hasMatch(p2, p1, m1)) IntMap.Nil;
+ else if (zero(p2, m1)) l1.intersectionWith(that, f);
+ else r1.intersectionWith(that, f);
+ } else if (m1 == m2) bin(p1, m1, l1.intersectionWith(l2, f), r1.intersectionWith(r2, f));
+ else {
+ if (!hasMatch(p1, p2, m2)) IntMap.Nil;
+ else if (zero(p1, m2)) this.intersectionWith(l2, f);
+ else this.intersectionWith(r2, f);
+ }
+ case (IntMap.Tip(key, value), that) => that.get(key) match {
+ case None => IntMap.Nil;
+ case Some(value2) => IntMap.Tip(key, f(key, value, value2));
+ }
+ case (_, IntMap.Tip(key, value)) => this.get(key) match {
+ case None => IntMap.Nil;
+ case Some(value2) => IntMap.Tip(key, f(key, value2, value));
+ }
+ case (_, _) => IntMap.Nil;
+ }
+
+ /**
+ * Left biased intersection. Returns the map that has all the same mappings as this but only for keys
+ * which are present in the other map.
+ *
+ * @param that The map to intersect with.
+ */
+ def intersection[R](that : IntMap[R]) : IntMap[T] = this.intersectionWith(that, (key : Int, value : T, value2 : R) => value);
+
+ override def ++[S >: T](that : Iterable[(Int, S)]) = that match {
+ case (that : IntMap[_]) => this.unionWith[S](that.asInstanceOf[IntMap[S]], (key, x, y) => y);
+ case that => that.foldLeft(this : IntMap[S])({case (m, (x, y)) => m.update(x, y)});
+ }
+}
+
diff --git a/src/main/scala/VectorPerfTest.scala b/src/main/scala/VectorPerfTest.scala
new file mode 100644
index 0000000..078deee
--- /dev/null
+++ b/src/main/scala/VectorPerfTest.scala
@@ -0,0 +1,433 @@
+import com.codecommit.collection.Vector
+
+import scala.collection.mutable.ArrayBuffer
+
+object VectorPerfTest {
+ def main(args: Array[String]) {
+ println()
+
+ //==========================================================================
+ {
+ title("Fill 100000 Sequential Indexes")
+
+ val vectorOp = "Vector" -> time {
+ var vec = Vector[Int]()
+ var i = 0
+
+ while (i < 100000) {
+ vec += i
+ i += 1
+ }
+ }
+
+ val arrayOp = "ArrayBuffer" -> time {
+ var arr = new ArrayBuffer[Int]
+ var i = 0
+
+ while (i < 100000) {
+ arr += i
+ i += 1
+ }
+ }
+
+ vectorOp compare arrayOp
+
+ val intMapOp = "IntMap" -> time {
+ var map = test.IntMap[Int]()
+ var i = 0
+
+ while (i < 100000) {
+ map = map(i) = i
+ i += 1
+ }
+ }
+
+ vectorOp compare intMapOp
+
+ val oldIntMapOp = "Map[Int, _]" -> time {
+ var map = Map[Int, Int]()
+ var i = 0
+
+ while (i < 100000) {
+ map = map(i) = i
+ i += 1
+ }
+ }
+
+ vectorOp compare oldIntMapOp
+
+ div('=')
+ println()
+ }
+
+ //==========================================================================
+ {
+ title("Read 100000 Sequential Indexes")
+
+ var vec = Vector[Int]()
+ for (i <- 0 until 100000) {
+ vec += i
+ }
+
+ var arr = new ArrayBuffer[Int]
+ for (i <- 0 until 100000) {
+ arr += i
+ }
+
+ var bitVec = Vector[Int]()
+ for (i <- 0 until 100000) {
+ bitVec += i
+ }
+
+ var map = test.IntMap[Int]()
+ for (i <- 0 until 100000) {
+ map = map(i) = i
+ }
+
+ var oldMap = Map[Int, Int]()
+ for (i <- 0 until 100000) {
+ oldMap = oldMap(i) = i
+ }
+
+ val vectorOp = "Vector" -> time {
+ var i = 0
+ while (i < vec.length) {
+ vec(i)
+ i += 1
+ }
+ }
+
+ val arrayOp = "ArrayBuffer" -> time {
+ var i = 0
+ while (i < arr.size) {
+ arr(i)
+ i += 1
+ }
+ }
+
+ vectorOp compare arrayOp
+
+ val intMapOp = "IntMap" -> time {
+ var i = 0
+ while (i < vec.length) { // map.size is unsuitable
+ map(i)
+ i += 1
+ }
+ }
+
+ vectorOp compare intMapOp
+
+ val oldIntMapOp = "Map[Int, _]" -> time {
+ var i = 0
+ while (i < vec.length) { // map.size is unsuitable
+ oldMap(i)
+ i += 1
+ }
+ }
+
+ vectorOp compare oldIntMapOp
+
+ div('=')
+ println()
+ }
+
+ //==========================================================================
+ {
+ title("Read 100000 Random Indexes")
+
+ val indexes = new Array[Int](100000)
+ var max = -1
+ for (i <- 0 until indexes.length) {
+ indexes(i) = Math.round(Math.random * 40000000).toInt
+ max = Math.max(max, indexes(i))
+ }
+
+ var vec = Vector[Int]()
+ for (i <- 0 to max) { // unplesant hack
+ vec += 0
+ }
+
+ for (i <- 0 until indexes.length) {
+ vec = vec(indexes(i)) = i
+ }
+
+ val arr = new ArrayBuffer[Int]
+ for (i <- 0 to max) { // unplesant hack
+ arr += 0
+ }
+
+ for (i <- 0 until indexes.length) {
+ arr(indexes(i)) = i
+ }
+
+ var bitVec = Vector[Int]()
+ for (i <- 0 to max) { // unplesant hack
+ bitVec += 0
+ }
+
+ for (i <- 0 until indexes.length) {
+ bitVec(indexes(i)) = i
+ }
+
+ var map = test.IntMap[Int]()
+ for (i <- 0 until indexes.length) {
+ map = map(indexes(i)) = i
+ }
+
+ var oldMap = Map[Int, Int]()
+ for (i <- 0 until indexes.length) {
+ oldMap = map(indexes(i)) = i
+ }
+
+ val vectorOp = "Vector" -> time {
+ var i = 0
+ while (i < indexes.length) {
+ vec(indexes(i))
+ i += 1
+ }
+ }
+
+ val arrayOp = "ArrayBuffer" -> time {
+ var i = 0
+ while (i < indexes.length) {
+ arr(indexes(i))
+ i += 1
+ }
+ }
+
+ vectorOp compare arrayOp
+
+ val intMapOp = "IntMap" -> time {
+ var i = 0
+ while (i < indexes.length) {
+ map(indexes(i))
+ i += 1
+ }
+ }
+
+ vectorOp compare intMapOp
+
+ val oldIntMapOp = "Map[Int, _]" -> time {
+ var i = 0
+ while (i < indexes.length) {
+ oldMap(indexes(i))
+ i += 1
+ }
+ }
+
+ vectorOp compare oldIntMapOp
+
+ div('=')
+ println()
+ }
+
+ //==========================================================================
+ {
+ title("Reverse of Length 100000")
+
+ var vec = Vector[Int]()
+ for (i <- 0 until 100000) {
+ vec += i
+ }
+
+ var arr = new ArrayBuffer[Int]
+ for (i <- 0 until 100000) {
+ arr += i
+ }
+
+ var bitVec = Vector[Int]()
+ for (i <- 0 until 100000) {
+ bitVec += i
+ }
+
+ var map = test.IntMap[Int]()
+ for (i <- 0 until 100000) {
+ map = map(i) = i
+ }
+
+ val vectorOp = "Vector" -> time {
+ vec.reverse
+ }
+
+ val arrayOp = "ArrayBuffer" -> time {
+ arr.reverse
+ }
+
+ vectorOp compare arrayOp
+
+ div('=')
+ println()
+ }
+
+ //==========================================================================
+ {
+ title("Compute Length (100000)")
+
+ var vec = Vector[Int]()
+ for (i <- 0 until 100000) {
+ vec += i
+ }
+
+ var arr = new ArrayBuffer[Int]
+ for (i <- 0 until 100000) {
+ arr += i
+ }
+
+ var bitVec = Vector[Int]()
+ for (i <- 0 until 100000) {
+ bitVec += i
+ }
+
+ var map = test.IntMap[Int]()
+ for (i <- 0 until 100000) {
+ map = map(i) = i
+ }
+
+ var oldMap = Map[Int, Int]()
+ for (i <- 0 until 100000) {
+ oldMap = oldMap(i) = i
+ }
+
+ val vectorOp = "Vector" -> time {
+ vec.length
+ }
+
+ val arrayOp = "ArrayBuffer" -> time {
+ arr.length
+ }
+
+ vectorOp compare arrayOp
+
+ val intMapOp = "IntMap" -> time {
+ map.size
+ }
+
+ vectorOp compare intMapOp
+
+ val oldIntMapOp = "Map[Int, _]" -> time {
+ oldMap.size
+ }
+
+ vectorOp compare oldIntMapOp
+
+ div('=')
+ println()
+ }
+ }
+
+ @inline
+ def time(op: =>Unit) = {
+ var data = new Array[Test](12)
+
+ var minTime = Math.MAX_LONG
+ var minMem = Math.MAX_LONG
+ var minTimeI = 0
+ var minMemI = 0
+
+ var maxTime = Math.MIN_LONG
+ var maxMem = Math.MIN_LONG
+ var maxTimeI = 1
+ var maxMemI = 1
+
+ for (i <- 0 until data.length) {
+ val mem = Runtime.getRuntime.freeMemory
+ val start = System.nanoTime
+ op
+ data(i) = Test(System.nanoTime - start, mem - Runtime.getRuntime.freeMemory)
+
+ if (data(i).nanos < minTime) {
+ minTime = data(i).nanos
+ minTimeI = i
+ }
+ if (data(i).bytes < minMem) {
+ minMem = data(i).bytes
+ minMemI = i
+ }
+
+ if (data(i).nanos > maxTime) {
+ maxTime = data(i).nanos
+ maxTimeI = i
+ }
+ if (data(i).bytes > maxMem) {
+ maxMem = data(i).bytes
+ maxMemI = i
+ }
+
+ Runtime.getRuntime.gc()
+ }
+
+ var sumTime: BigInt = 0
+ var sumMem: BigInt = 0
+ for (i <- 0 until data.length) {
+ if (i != minTimeI && i != maxTimeI) {
+ sumTime += data(i).nanos
+ }
+
+ if (i != minMemI && i != maxMemI) {
+ sumMem += data(i).bytes
+ }
+ }
+
+ Test((sumTime / (data.length - 2)).longValue, (sumMem / (data.length - 2)).longValue)
+ }
+
+ private def title(str: String) {
+ div('=')
+ println(" " + str)
+ }
+
+ private def div(c: Char) = {
+ for (i <- 0 until 80) print(c)
+ println()
+ }
+
+ private implicit def opToComparison(op1: (String, Test)) = new ComparisonClass(op1)
+
+ private class ComparisonClass(op1: (String, Test)) {
+ private val timeTemplate = "%%%ds Time: %%fms%n"
+ private val memoryTemplate = "%%%ds Memory: %%f KB%n"
+
+ private val diff = "Time Difference"
+ private val memDiff = "Memory Difference"
+ private val diffTemplate = "%%%ds: %%%%f%%s%n"
+
+ private val percent = "Percentage Difference"
+ private val percentTemplate = "%%%ds: %%%%f%%%%%%%%%n"
+
+ def compare(op2: (String, Test)) {
+ import Math.max
+
+ val (op1Name, Test(op1Time, op1Mem)) = op1
+ val (op2Name, Test(op2Time, op2Mem)) = op2
+
+ val widthTotal = max(op1Name.length + 7, max(op2Name.length + 7, max(diff.length, max(memDiff.length, percent.length)))) + 2
+
+ val width:java.lang.Integer = widthTotal
+ val timeWidth:java.lang.Integer = widthTotal - 5
+ val memWidth:java.lang.Integer = widthTotal - 7
+
+ val timeFormat = String.format(timeTemplate, Array(timeWidth))
+ val memoryFormat = String.format(memoryTemplate, Array(memWidth))
+ val diffFormat = String.format(String.format(diffTemplate, Array(width)), Array(diff, "ms"))
+ val memDiffFormat = String.format(String.format(diffTemplate, Array(width)), Array(memDiff, " KB"))
+ val percentFormat = String.format(String.format(percentTemplate, Array(width)), Array(percent))
+
+ div('-')
+
+ printf(timeFormat, op1Name, (op1Time:Double) / 1000000)
+ printf(timeFormat, op2Name, (op2Time:Double) / 1000000)
+
+ printf(memoryFormat, op1Name, (op1Mem:Double) / 1024)
+ printf(memoryFormat, op2Name, (op2Mem:Double) / 1024)
+
+ println()
+ printf(diffFormat, ((op1Time - op2Time):Double) / 1000000)
+ printf(percentFormat, (((op1Time:Double) / (op2Time:Double)) - 1) * 100)
+
+ println()
+ printf(memDiffFormat, ((op1Mem - op2Mem):Double) / 1024)
+ }
+ }
+
+ case class Test(nanos: Long, bytes: Long)
+}
diff --git a/src/main/scala/com/codecommit/collection/BloomSet.scala b/src/main/scala/com/codecommit/collection/BloomSet.scala
new file mode 100644
index 0000000..2586d4f
--- /dev/null
+++ b/src/main/scala/com/codecommit/collection/BloomSet.scala
@@ -0,0 +1,212 @@
+package com.codecommit.collection
+
+import java.io.{InputStream, OutputStream}
+
+import BloomSet._
+
+class BloomSet[A] private (val size: Int, val k: Int, private val contents: Vector[Boolean]) extends ((A)=>Boolean) {
+ val width = contents.length
+
+ /**
+ * <p>A value between 0 and 1 which estimates the accuracy of the bloom filter.
+ * This estimate is precisely the inverse of the probability function for
+ * a bloom filter of a given size, width and number of hash functions. The
+ * probability function given by the following expression in LaTeX math syntax:</p>
+ *
+ * <p><code>(1 - e^{-kn/m})^k</code> where <i>k</i> is the number of hash functions,
+ * <i>n</i> is the number of elements in the bloom filter and <i>m</i> is the
+ * width.</p>
+ *
+ * <p>It is important to remember that this is only an estimate of the accuracy.
+ * Likewise, it assumes perfectly ideal hash functions, thus it is somewhat
+ * more optimistic than the reality of the implementation.</p>
+ */
+ lazy val accuracy = {
+ val exp = ((k:Double) * size) / width
+ val probability = Math.pow(1 - Math.exp(-exp), k)
+
+ 1d - probability
+ }
+
+ /**
+ * Returns the optimal value of <i>k</i> for a bloom filter with the current
+ * properties (width and size). Useful in reducing false-positives on sets
+ * with a limited range in size.
+ */
+ lazy val optimalK = {
+ val num = (9:Double) * width
+ val dem = (13:Double) * size
+ Math.max((num / dem).intValue, 1)
+ }
+
+ def this(width: Int, k: Int) = this(0, k, alloc(width))
+
+ def +(e: A) = new BloomSet[A](size + 1, k, add(contents)(e))
+
+ def ++(col: Iterable[A]) = {
+ var length = 0
+ val newContents = col.foldLeft(contents) { (c, e) =>
+ length += 1
+ add(c)(e)
+ }
+
+ new BloomSet[A](size + length, k, newContents)
+ }
+
+ /**
+ * Computes the union of two bloom filters and returns the result. Note that
+ * this operation is only defined for filters of the same width. Filters which
+ * have a different value of <i>k</i> (different number of hash functions) can
+ * be unioned, but the result will have a higher probability of false positives
+ * than either of the operands. The <i>k</i> value of the resulting filter is
+ * computed to be the minimum <i>k</i> of the two operands. The <i>size</i> of
+ * the resulting filter is precisely the combined size of the operands. This
+ * of course means that for sets with intersecting items the size will be
+ * slightly large.
+ */
+ def ++(set: BloomSet[A]) = {
+ if (set.width != width) {
+ throw new IllegalArgumentException("Bloom filter union is only defined for " +
+ "sets of the same width (" + set.width + " != " + width + ")")
+ }
+
+ val newContents = (0 until width).foldLeft(contents) { (c, i) =>
+ c(i) ||= set.contents(i)
+ }
+
+ new BloomSet[A](size + set.size, Math.min(set.k, k), newContents) // min guarantees no false negatives
+ }
+
+ def contains(e: A) = {
+ (0 until k).foldLeft(true) { (acc, i) =>
+ acc && contents(hash(e, i, contents.length))
+ }
+ }
+
+ def apply(e: A) = contains(e)
+
+ def store(os: OutputStream) {
+ os.write(convertToBytes(size))
+ os.write(convertToBytes(k))
+ os.write(convertToBytes(contents.length))
+
+ var num = 0
+ var card = 0
+ for (b <- contents) {
+ num = (num << 1) | (if (b) 1 else 0) // construct mask
+ card += 1
+
+ if (card == 8) {
+ os.write(num)
+
+ num = 0
+ card = 0
+ }
+ }
+
+ if (card != 0) {
+ os.write(num)
+ }
+ }
+
+ override def equals(other: Any) = other match {
+ case set: BloomSet[A] => {
+ val back = (size == set.size) &&
+ (k == set.k) &&
+ (contents.length == set.contents.length)
+
+ (0 until contents.length).foldLeft(back) { (acc, i) =>
+ acc && (contents(i) == set.contents(i))
+ }
+ }
+
+ case _ => false
+ }
+
+ override def hashCode = {
+ (0 until width).foldLeft(size ^ k ^ width) { (acc, i) =>
+ acc ^ (if (contents(i)) i else 0)
+ }
+ }
+
+ protected def add(contents: Vector[Boolean])(e: Any) = {
+ var back = contents
+
+ for (i <- 0 until k) {
+ back = back(hash(e, i, back.length)) = true
+ }
+
+ back
+ }
+}
+
+object BloomSet {
+ def apply[A](e: A*) = e.foldLeft(new BloomSet[A](200, 4)) { _ + _ }
+
+ def load[A](is: InputStream) = {
+ val buf = new Array[Byte](4)
+
+ is.read(buf)
+ val size = convertToInt(buf)
+
+ is.read(buf)
+ val k = convertToInt(buf)
+
+ is.read(buf)
+ val width = convertToInt(buf)
+
+ var contents = Vector[Boolean]()
+ for (_ <- 0 until (width / 8)) {
+ var num = is.read()
+ var buf: List[Boolean] = Nil
+
+ for (_ <- 0 until 8) {
+ buf = ((num & 1) == 1) :: buf
+ num >>= 1
+ }
+
+ contents = contents ++ buf
+ }
+
+ if (width % 8 != 0) {
+ var buf: List[Boolean] = Nil
+ var num = is.read()
+
+ for (_ <- 0 until (width % 8)) {
+ buf = ((num & 1) == 1) :: buf
+ num >>= 1
+ }
+
+ contents = contents ++ buf
+ }
+
+ new BloomSet[A](size, k, contents)
+ }
+
+ private[collection] def convertToBytes(i: Int) = {
+ val buf = new Array[Byte](4)
+
+ buf(0) = ((i & 0xff000000) >>> 24).byteValue
+ buf(1) = ((i & 0x00ff0000) >>> 16).byteValue
+ buf(2) = ((i & 0x0000ff00) >>> 8).byteValue
+ buf(3) = ((i & 0x000000ff)).byteValue
+
+ buf
+ }
+
+ private[collection] def convertToInt(buf: Array[Byte]) = {
+ ((buf(0) & 0xFF) << 24) |
+ ((buf(1) & 0xFF) << 16) |
+ ((buf(2) & 0xFF) << 8) |
+ (buf(3) & 0xFF)
+ }
+
+ private[collection] def alloc(size: Int) = {
+ (0 until size).foldLeft(Vector[Boolean]()) { (c, i) => c + false }
+ }
+
+ private[collection] def hash(e: Any, iters: Int, bounds: Int): Int = {
+ val rand = new Random(e.hashCode)
+ (0 until iters).foldLeft(rand.nextInt(bounds)) { (x, y) => rand.nextInt(bounds) }
+ }
+}
diff --git a/src/main/scala/com/codecommit/collection/BloomSetArray.scala b/src/main/scala/com/codecommit/collection/BloomSetArray.scala
new file mode 100644
index 0000000..e0bdcf8
--- /dev/null
+++ b/src/main/scala/com/codecommit/collection/BloomSetArray.scala
@@ -0,0 +1,74 @@
+package com.codecommit.collection
+
+import java.io.{InputStream, OutputStream}
+import java.util.Random
+
+class BloomSetArray[+T] private (k: Int, contents: Array[Int]) {
+
+ def this(width: Int, k: Int) = this(k, new Array[Int](width))
+
+ def +[A >: T](e: A) = {
+ val newContents = cloneArray(contents)
+ add(newContents)(e)
+
+ new BloomSetArray[A](k, newContents)
+ }
+
+ def ++[A >: T](col: Iterable[A]) = {
+ val newContents = cloneArray(contents)
+ val addNew = add(newContents) _
+
+ col foreach addNew
+
+ new BloomSetArray[A](k, newContents)
+ }
+
+ def contains[A >: T](e: A) = {
+ val total = (0 until k).foldLeft(0) { (acc, i) => acc + contents(hash(e, i, contents.length)) }
+ total == k
+ }
+
+ def store(os: OutputStream) {
+ os.write(k)
+ os.write(contents.length)
+ contents foreach { os.write(_) }
+ }
+
+ private def add(contents: Array[Int])(e: Any) = {
+ for (i <- 0 until k) {
+ contents(hash(e, i, contents.length)) = 1
+ }
+ }
+
+ private def hash(e: Any, iters: Int, bounds: Int): Int = if (iters == 0) 0 else {
+ Math.abs(twist(e.hashCode + iters + hash(e, iters - 1, bounds)) % bounds)
+ }
+
+ private def twist(i: Int) = new Random(i).nextInt()
+
+ private def cloneArray[A](a: Array[A]) = {
+ val back = new Array[A](a.length)
+ Array.copy(a, 0, back, 0, a.length)
+ back
+ }
+}
+
+object BloomSetArray {
+ val DEFAULT_WIDTH = 200
+ val DEFAULT_K = 4
+
+ def apply[T](elems: T*) = {
+ new BloomSetArray[T](DEFAULT_WIDTH, DEFAULT_K) ++ elems
+ }
+
+ def load[T](is: InputStream) = {
+ val k = is.read()
+ val contents = new Array[Int](is.read())
+
+ for (i <- 0 until contents.length) {
+ contents(i) = is.read()
+ }
+
+ new BloomSetArray[T](k, contents)
+ }
+}
diff --git a/src/main/scala/com/codecommit/collection/HashMap.scala b/src/main/scala/com/codecommit/collection/HashMap.scala
new file mode 100644
index 0000000..224c6ba
--- /dev/null
+++ b/src/main/scala/com/codecommit/collection/HashMap.scala
@@ -0,0 +1,288 @@
+package com.codecommit.collection
+
+import HashMap._
+
+class HashMap[K, +V] private (root: Node[K, V]) extends Map[K, V] {
+ lazy val size = root.size
+
+ def this() = this(new EmptyNode[K])
+
+ def get(key: K) = root(key, key.hashCode)
+
+ override def +[A >: V](pair: (K, A)) = pair match {
+ case (k, v) => update(k, v)
+ }
+
+ def update[A >: V](key: K, value: A) = new HashMap(root(key, key.hashCode) = value)
+
+ def -(key: K) = new HashMap(root.remove(key, key.hashCode))
+
+ def elements = root.elements
+
+ def empty[A]: HashMap[K, A] = new HashMap(new EmptyNode[K])
+}
+
+object HashMap {
+ def apply[K, V](pairs: (K, V)*) = pairs.foldLeft(new HashMap[K, V]) { _ + _ }
+
+ def unapply[K, V](map: HashMap[K, V]) = map.toSeq
+}
+
+// ============================================================================
+// nodes
+
+private[collection] sealed trait Node[K, +V] {
+ val size: Int
+
+ def apply(key: K, hash: Int): Option[V]
+
+ def update[A >: V](key: K, hash: Int, value: A): Node[K, A]
+
+ def remove(key: K, hash: Int): Node[K, V]
+
+ def elements: Iterator[(K, V)]
+}
+
+
+private[collection] class EmptyNode[K] extends Node[K, Nothing] {
+ val size = 0
+
+ def apply(key: K, hash: Int) = None
+
+ def update[V](key: K, hash: Int, value: V) = new LeafNode(0, hash)(key, value)
+
+ def remove(key: K, hash: Int) = this
+
+ lazy val elements = new Iterator[(K, Nothing)] {
+ val hasNext = false
+
+ val next = null
+ }
+}
+
+
+private[collection] class LeafNode[K, +V](shift: Int, hash: Int)(key: K, value: V) extends Node[K, V] {
+ val size = 1
+
+ def apply(key: K, hash: Int) = if (this.key == key) Some(value) else None
+
+ def update[A >: V](key: K, hash: Int, value: A) = {
+ if (this.key == key) {
+ new LeafNode(shift, hash)(key, value)
+ } else if (this.hash == hash || hash == 0) { // if we're bottoming out, just collide
+ new CollisionNode(shift, hash, this.key -> this.value, key -> value)
+ } else {
+ BitmappedNode(shift)(Array((this.key, this.hash, this.value), (key, hash, value)))
+ }
+ }
+
+ def remove(key: K, hash: Int) = if (this.key == key) new EmptyNode[K] else this
+
+ def elements = new Iterator[(K, V)] {
+ var hasNext = true
+
+ def next = {
+ hasNext = false
+ (key, value)
+ }
+ }
+
+ override def toString = "LeafNode(" + key + " -> " + value + ")"
+}
+
+
+private[collection] class CollisionNode[K, +V](shift: Int, hash: Int, bucket: List[(K, V)]) extends Node[K, V] {
+ lazy val size = bucket.length
+
+ def this(shift: Int, hash: Int, pairs: (K, V)*) = this(shift, hash, pairs.toList)
+
+ def apply(key: K, hash: Int) = {
+ for {
+ (_, v) <- bucket find { case (k, _) => k == key }
+ } yield v
+ }
+
+ def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
+ if (this.hash == hash) {
+ var found = false
+
+ val newBucket = for {
+ (k, v) <- bucket
+ } yield {
+ if (k == key) {
+ found = true
+ (key, value)
+ } else (k, v)
+ }
+
+ new CollisionNode(shift, hash, if (found) newBucket else (key, value) :: bucket)
+ } else {
+ val tempBucket = ((key, value) :: bucket).map({ case (k, v) => (k, k.hashCode, v) })
+ BitmappedNode(shift)(tempBucket.toArray) // not the most efficient, but not too bad
+ }
+ }
+
+ def remove(key: K, hash: Int) = {
+ if (bucket.exists({ case (k, _) => k == key }) && size == 2) {
+ var pair: (K, V) = null
+
+ for {
+ (k, v) <- bucket
+ if k == key
+ } pair = (k, v)
+
+ new LeafNode(shift, hash)(pair._1, pair._2)
+ } else new CollisionNode(shift, hash, bucket.dropWhile({ case (k, _) => k == key }))
+ }
+
+ def elements = (bucket map { case (k, v) => (k, v) }).elements
+
+ override def toString = "CollisionNode(" + bucket.toString + ")"
+}
+
+
+private[collection] class BitmappedNode[K, +V](shift: Int)(table: Array[Node[K, V]], bits: Int) extends Node[K, V] {
+ import BitmappedNode._
+
+ lazy val size = {
+ val sizes = for {
+ n <- table
+ if n != null
+ } yield n.size
+
+ sizes.foldLeft(0) { _ + _ }
+ }
+
+ def apply(key: K, hash: Int) = {
+ val i = (hash >>> shift) & 0x01f
+ val mask = 1 << i
+
+ if ((bits & mask) == mask) table(i)(key, hash) else None
+ }
+
+ def update[A >: V](key: K, hash: Int, value: A): Node[K, A] = {
+ val i = (hash >>> shift) & 0x01f
+ val mask = 1 << i
+
+ val newTable = new Array[Node[K, A]](32)
+ Array.copy(table, 0, newTable, 0, 32)
+
+ val newBits = addToTable(shift)(newTable, bits)(key, hash, value)
+
+ if (newBits == Math.MIN_INT) {
+ new FullNode(shift)(newTable)
+ } else {
+ new BitmappedNode(shift)(newTable, newBits)
+ }
+ }
+
+ def remove(key: K, hash: Int) = {
+ val i = (hash >>> shift) & 0x01f
+ val mask = 1 << i
+
+ if ((bits & mask) == mask) {
+ val newTable = new Array[Node[K, V]](32)
+ Array.copy(table, 0, newTable, 0, 32)
+
+ val node = newTable(i).remove(key, hash)
+ val newBits = if (node.isInstanceOf[EmptyNode[_]]) {
+ newTable(i) = null
+ bits ^ mask
+ } else {
+ newTable(i) = node
+ bits
+ }
+
+ new BitmappedNode(shift)(newTable, newBits)
+ } else this
+ }
+
+ def elements = {
+ val iters = table flatMap { n =>
+ if (n == null) Array[Iterator[(K, V)]]() else Array(n.elements)
+ }
+
+ iters.foldLeft(emptyElements) { _ ++ _ }
+ }
+
+ override def toString = "BitmappedNode(" + size + "," + table.filter(_ != null).toList.toString + ")"
+
+ private lazy val emptyElements: Iterator[(K, V)] = new Iterator[(K, V)] {
+ val hasNext = false
+
+ val next = null
+ }
+}
+
+
+private[collection] object BitmappedNode {
+ def apply[K, V](shift: Int)(pairs: Array[(K, Int, V)]) = {
+ val table = new Array[Node[K, V]](32)
+ val bits = pairs.foldLeft(0) { (bits, pair) =>
+ val (key, hash, value) = pair
+ addToTable(shift)(table, bits)(key, hash, value)
+ }
+
+ new BitmappedNode(shift)(table, bits)
+ }
+
+ private def addToTable[K, V](shift: Int)(table: Array[Node[K, V]], bits: Int)(key: K, hash: Int, value: V) = {
+ val i = (hash >>> shift) & 0x01f
+ val mask = 1 << i
+
+ if ((bits & mask) == mask) {
+ table(i) = (table(i)(key, hash) = value)
+ } else {
+ table(i) = new LeafNode(shift + 5, hash)(key, value)
+ }
+
+ bits | mask
+ }
+}
+
+
+private[collection] class FullNode[K, +V](shift: Int)(table: Array[Node[K, V]]) extends Node[K, V] {
+ lazy val size = table.foldLeft(0) { _ + _.size }
+
+ def apply(key: K, hash: Int) = {
+ val i = (hash >>> shift) & 0x01f
+
+ table(i)(key, hash)
+ }
+
+ def update[A >: V](key: K, hash: Int, value: A) = {
+ val i = (hash >>> shift) & 0x01f
+
+ val newTable = new Array[Node[K, A]](32)
+ Array.copy(table, 0, newTable, 0, 32)
+
+ newTable(i) = newTable(i)(key, hash) = value
+
+ new FullNode(shift)(newTable)
+ }
+
+ def remove(key: K, hash: Int) = {
+ val i = (hash >>> shift) & 0x01f
+ val mask = 1 << i
+
+ val newTable = new Array[Node[K, V]](32)
+ Array.copy(table, 0, newTable, 0, 32)
+
+ val node = newTable(i).remove(key, hash)
+
+ if (node.isInstanceOf[EmptyNode[_]]) {
+ newTable(i) = null
+ new BitmappedNode(shift)(newTable, Math.MAX_INT ^ mask)
+ } else {
+ newTable(i) = node
+ new FullNode(shift)(newTable)
+ }
+ }
+
+ def elements = {
+ val iters = table map { _.elements }
+ iters.reduceLeft[Iterator[(K, V)]] { _ ++ _ }
+ }
+
+ override def toString = "FullNode"
+}
diff --git a/src/main/scala/com/codecommit/collection/PathVector.scala b/src/main/scala/com/codecommit/collection/PathVector.scala
new file mode 100644
index 0000000..4b44a07
--- /dev/null
+++ b/src/main/scala/com/codecommit/collection/PathVector.scala
@@ -0,0 +1,290 @@
+package com.codecommit.collection
+
+import Math.max
+import PathVector._
+
+/**
+ * <p>An immutable implementation of the {@link Seq} interface with an array
+ * backend. Effectively, this class is an immutable vector. The only wrinkle
+ * in this design is the ability to store elements in <i>completely</i> arbitrary
+ * indexes (to enable use as a random-access array). Thus, the length of this
+ * data structure is effectively infinite. The {@link #length} field is defined
+ * to return the maximum index of the elements in the vector.</p>
+ *
+ * <p>The underlying data structure for the persistent vector is a trie with an
+ * extremely high branching factor (by default: 32). Each trie node contains
+ * an array representing each branch. This implementation allows almost-constant
+ * time access coupled with minimal data-copying on insert. The ratio between
+ * these two is controlled by the branching factor. A higher branching factor
+ * will lead to a better worst-case access time (asymtotically more constant)
+ * while a lower branching factor will result in asymtotically less data
+ * copying on insert.</p>
+ *
+ * <p>As is natural for an immutable data structure, this vector is parameterized
+ * covariantly. This poses a few minor difficulties in implementation, due to
+ * the fact that arrays, as mutable containers, are parameterized
+ * <i>invariantly</i>. To get around this, some up-casting is utilized durring
+ * insertion. This is considered to be sound due to the fact that the type
+ * system will ensure that the casting is always upwards, rather than down (which
+ * is where the mutability concerns come into play).</p>
+ *
+ * <p>The underlying determinant for the trie structure in this implementation is
+ * the big-endian component value of the index in question, converted into a path
+ * to the final trie node. This still yields a maximum depth of 7 (when dealing
+ * with 32-bit integer indexes and a branching factor of 32), but the average
+ * depth of the trie is higher and its width is proportionately lower. This
+ * yields far more efficient write operations than a bit-partitioned trie, as well
+ * as a tremendously reduced memory footprint. Additionally, this implementation
+ * allows a configurable branching factor, whereas the branching factor of a
+ * bit-partitioned implemnetation must always be a factor of 2.</p>
+ *
+ * @author Daniel Spiewak
+ */
+class PathVector[+T] private (private val data: Option[T], val length: Int, val branchingFactor: Int,
+ private val left: Seq[PathVector[T]], private val right: Seq[PathVector[T]]) extends RandomAccessSeq[T] { outer =>
+
+ def this(branchingFactor: Int) = this(None, 0, branchingFactor, EmptyArray, EmptyArray)
+
+ def this() = this(32)
+
+ def apply(i: Int) = getOrElse(i, null.asInstanceOf[T])
+
+ def get(i: Int) = locate(computePath(i, branchingFactor))
+
+ def getOrElse[A >: T](i: Int, default: A) = get(i) match {
+ case Some(x) => x
+ case None => default
+ }
+
+ private def locate(path: List[Int]): Option[T] = path match {
+ case hd :: tail => {
+ val branches = if (hd < (branchingFactor / 2)) left else right
+ val node = if (hd < branches.length) branches(hd) else null.asInstanceOf[PathVector[T]]
+
+ if (node == null) None else node.locate(tail)
+ }
+
+ case Nil => data
+ }
+
+ // somewhat less efficient than it could be
+ override def ++[A >: T](other: Iterable[A]) = other.foldLeft(this:PathVector[A]) { _ + _ }
+
+ def +[A >: T](e: A) = update(length, e)
+
+ def update[A >: T](i: Int, e: A) = store(computePath(i, branchingFactor), e)
+
+ private def store[A >: T](path: List[Int], e: A): PathVector[A] = path match {
+ case hd :: tail => {
+ val branches = if (hd < (branchingFactor / 2)) left else right
+ val node = if (hd < branches.length) branches(hd) else null.asInstanceOf[PathVector[T]]
+ val vector = if (node == null) EmptyPathVector(branchingFactor) else node
+
+ val newBranches = new Array[PathVector[A]](max(branches.length, hd + 1))
+ Array.copy(branches, 0, newBranches, 0, branches.length)
+
+ newBranches(hd) = vector.store(tail, e)
+
+ val newLeft = if (hd < (branchingFactor / 2)) newBranches else left
+ val newRight = if (hd < (branchingFactor / 2)) right else newBranches
+
+ new PathVector(data, max(length, flattenPath(path, branchingFactor) + 1), branchingFactor, newLeft, newRight)
+ }
+
+ case Nil => new PathVector(Some(e), max(length, flattenPath(path, branchingFactor) + 1), branchingFactor, left, right)
+ }
+
+ override def filter(p: (T)=>Boolean) = {
+ var back = new PathVector[T]
+ var i = 0
+
+ while (i < length) {
+ val e = apply(i)
+ if (p(e)) back += e
+
+ i += 1
+ }
+
+ back
+ }
+
+ override def flatMap[A](f: (T)=>Iterable[A]) = {
+ var back = new PathVector[A]
+ var i = 0
+
+ while (i < length) {
+ f(apply(i)) foreach { back += _ }
+ i += 1
+ }
+
+ back
+ }
+
+ override def map[A](f: (T)=>A): PathVector[A] = {
+ var back = new PathVector[A]
+ var i = 0
+
+ while (i < length) {
+ back += f(apply(i))
+ i += 1
+ }
+
+ back
+ }
+
+ override def reverse = new PathVector[T](branchingFactor) {
+ override val length = outer.length
+
+ override def get(i: Int) = outer.get(length - i - 1)
+
+ override def update[A >: T](i: Int, e: A) = {
+ var back = new PathVector[A]
+
+ foreachOption { (c, x) =>
+ back = back(c) = if (c == i) e else x
+ }
+
+ if (i < 0) {
+ throw new IndexOutOfBoundsException(i.toString)
+ } else if (i >= length) {
+ back(i) = e
+ } else {
+ back
+ }
+ }
+ }
+
+ override def subseq(from: Int, end: Int) = subPathVector(from, end)
+
+ def subPathVector(from: Int, end: Int) = {
+ if (from < 0) {
+ throw new IndexOutOfBoundsException(from.toString)
+ } else if (end <= from) {
+ throw new IllegalArgumentException("Invalid range: " + from + ".." + end)
+ } else {
+ new PathVector[T](branchingFactor) {
+ override val length = end - from
+
+ override def get(i: Int) = outer.get(i + from)
+
+ override def update[A >: T](i: Int, e: A) = {
+ var back = new PathVector[A]
+
+ foreachOption { (c, x) =>
+ back = back(c) = if (c == i) e else x
+ }
+
+ if (i < 0) {
+ throw new IndexOutOfBoundsException(i.toString)
+ } else if (i >= length) {
+ back(i) = e
+ } else {
+ back
+ }
+ }
+ }
+ }
+ }
+
+ def zip[A](that: PathVector[A]) = {
+ var back = new PathVector[(T, A)]
+ var i = 0
+
+ val limit = max(length, that.length)
+ while (i < limit) {
+ back += (apply(i), that(i))
+ i += 1
+ }
+
+ back
+ }
+
+ def zipWithIndex = {
+ var back = new PathVector[(T, Int)]
+ var i = 0
+
+ while (i < length) {
+ back += (apply(i), i)
+ i += 1
+ }
+
+ back
+ }
+
+ override def equals(other: Any) = other match {
+ case vec:PathVector[T] => {
+ var back = length == vec.length
+ var i = 0
+
+ while (i < length) {
+ back &&= get(i) == vec.get(i)
+ i += 1
+ }
+
+ back
+ }
+
+ case _ => false
+ }
+
+ @inline
+ private def foreachOption(f: (Int, T)=>Unit) = {
+ var i = 0
+ while (i < length) {
+ get(i) match {
+ case Some(x) => f(i, x)
+ case None => ()
+ }
+
+ i += 1
+ }
+ }
+}
+
+object PathVector {
+ private[collection] val EmptyArray = new Array[PathVector[Nothing]](0)
+
+ def apply[T](elems: T*) = {
+ var vector = new PathVector[T]
+ var i = 0
+
+ for (e <- elems) {
+ vector = vector(i) = e
+ i += 1
+ }
+ vector
+ }
+
+ @inline
+ private[collection] def computePath(total: Int, base: Int) = {
+ if (total < 0) {
+ throw new IndexOutOfBoundsException(total.toString)
+ } else {
+ var back: List[Int] = Nil
+ var num = total
+
+ do {
+ back = (num % base) :: back
+ num /= base
+ } while (num > 0)
+
+ back
+ }
+ }
+
+ @inline
+ private[collection] def flattenPath(path: List[Int], base: Int) = path.foldLeft(0) { _ * base + _ }
+}
+
+object EmptyPathVector {
+ private var cache = Map[Int, PathVector[Nothing]]()
+
+ def apply(branchingFactor: Int) = {
+ if (cache contains branchingFactor) cache(branchingFactor) else {
+ val back = new PathVector[Nothing](branchingFactor)
+ cache += (branchingFactor -> back)
+
+ back
+ }
+ }
+}
diff --git a/src/main/scala/com/codecommit/collection/Vector.scala b/src/main/scala/com/codecommit/collection/Vector.scala
new file mode 100644
index 0000000..dba0355
--- /dev/null
+++ b/src/main/scala/com/codecommit/collection/Vector.scala
@@ -0,0 +1,327 @@
+/*
+ * Copyright (c) Rich Hickey. All rights reserved.
+ * The use and distribution terms for this software are covered by the
+ * Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
+ * which can be found in the file CPL.TXT at the root of this distribution.
+ * By using this software in any fashion, you are agreeing to be bound by
+ * the terms of this license.
+ * You must not remove this notice, or any other, from this software.
+ */
+
+package com.codecommit.collection
+
+import Vector._
+
+/**
+ * A straight port of Clojure's <code>PersistentVector</code> class.
+ *
+ * @author Daniel Spiewak
+ * @author Rich Hickey
+ */
+class Vector[+T] private (val length: Int, shift: Int, root: Array[AnyRef], tail: Array[AnyRef]) extends RandomAccessSeq[T] { outer =>
+ private val tailOff = length - tail.length
+
+ /*
+ * The design of this data structure inherantly requires heterogenous arrays.
+ * It is *possible* to design around this, but the result is comparatively
+ * quite inefficient. With respect to this fact, I have left the original
+ * (somewhat dynamically-typed) implementation in place.
+ */
+
+ private[collection] def this() = this(0, 5, EmptyArray, EmptyArray)
+
+ def apply(i: Int): T = {
+ if (i >= 0 && i < length) {
+ if (i >= tailOff) {
+ tail(i & 0x01f).asInstanceOf[T]
+ } else {
+ var arr = root
+ var level = shift
+
+ while (level > 0) {
+ arr = arr((i >>> level) & 0x01f).asInstanceOf[Array[AnyRef]]
+ level -= 5
+ }
+
+ arr(i & 0x01f).asInstanceOf[T]
+ }
+ } else throw new IndexOutOfBoundsException(i.toString)
+ }
+
+ def update[A >: T](i: Int, obj: A): Vector[A] = {
+ if (i >= 0 && i < length) {
+ if (i >= tailOff) {
+ val newTail = new Array[AnyRef](tail.length)
+ Array.copy(tail, 0, newTail, 0, tail.length)
+ newTail(i & 0x01f) = obj.asInstanceOf[AnyRef]
+
+ new Vector[A](length, shift, root, newTail)
+ } else {
+ new Vector[A](length, shift, doAssoc(shift, root, i, obj), tail)
+ }
+ } else if (i == length) {
+ this + obj
+ } else throw new IndexOutOfBoundsException(i.toString)
+ }
+
+ private def doAssoc[A >: T](level: Int, arr: Array[AnyRef], i: Int, obj: A): Array[AnyRef] = {
+ val ret = new Array[AnyRef](arr.length)
+ Array.copy(arr, 0, ret, 0, arr.length)
+
+ if (level == 0) {
+ ret(i & 0x01f) = obj.asInstanceOf[AnyRef]
+ } else {
+ val subidx = (i >>> level) & 0x01f
+ ret(subidx) = doAssoc(level - 5, arr(subidx).asInstanceOf[Array[AnyRef]], i, obj)
+ }
+
+ ret
+ }
+
+ override def ++[A >: T](other: Iterable[A]) = other.foldLeft(this:Vector[A]) { _ + _ }
+
+ def +[A >: T](obj: A): Vector[A] = {
+ if (tail.length < 32) {
+ val newTail = new Array[AnyRef](tail.length + 1)
+ Array.copy(tail, 0, newTail, 0, tail.length)
+ newTail(tail.length) = obj.asInstanceOf[AnyRef]
+
+ new Vector[A](length + 1, shift, root, newTail)
+ } else {
+ var (newRoot, expansion) = pushTail(shift - 5, root, tail, null)
+ var newShift = shift
+
+ if (expansion != null) {
+ newRoot = array(newRoot, expansion)
+ newShift += 5
+ }
+
+ new Vector[A](length + 1, newShift, newRoot, array(obj.asInstanceOf[AnyRef]))
+ }
+ }
+
+ private def pushTail(level: Int, arr: Array[AnyRef], tailNode: Array[AnyRef], expansion: AnyRef): (Array[AnyRef], AnyRef) = {
+ val newChild = if (level == 0) tailNode else {
+ val (newChild, subExpansion) = pushTail(level - 5, arr(arr.length - 1).asInstanceOf[Array[AnyRef]], tailNode, expansion)
+
+ if (subExpansion == null) {
+ val ret = new Array[AnyRef](arr.length)
+ Array.copy(arr, 0, ret, 0, arr.length)
+
+ ret(arr.length - 1) = newChild
+
+ return (ret, null)
+ } else subExpansion
+ }
+
+ // expansion
+ if (arr.length == 32) {
+ (arr, array(newChild))
+ } else {
+ val ret = new Array[AnyRef](arr.length + 1)
+ Array.copy(arr, 0, ret, 0, arr.length)
+ ret(arr.length) = newChild
+
+ (ret, null)
+ }
+ }
+
+ /**
+ * Removes the <i>tail</i> element of this vector.
+ */
+ def pop: Vector[T] = {
+ if (length == 0) {
+ throw new IllegalStateException("Can't pop empty vector")
+ } else if (length == 1) {
+ EmptyVector
+ } else if (tail.length > 1) {
+ val newTail = new Array[AnyRef](tail.length - 1)
+ Array.copy(tail, 0, newTail, 0, newTail.length)
+
+ new Vector[T](length - 1, shift, root, newTail)
+ } else {
+ var (newRoot, pTail) = popTail(shift - 5, root, null)
+ var newShift = shift
+
+ if (newRoot == null) {
+ newRoot = EmptyArray
+ }
+
+ if (shift > 5 && newRoot.length == 1) {
+ newRoot = newRoot(0).asInstanceOf[Array[AnyRef]]
+ newShift -= 5
+ }
+
+ new Vector[T](length - 1, newShift, newRoot, pTail.asInstanceOf[Array[AnyRef]])
+ }
+ }
+
+ private def popTail(shift: Int, arr: Array[AnyRef], pTail: AnyRef): (Array[AnyRef], AnyRef) = {
+ val newPTail = if (shift > 0) {
+ val (newChild, subPTail) = popTail(shift - 5, arr(arr.length - 1).asInstanceOf[Array[AnyRef]], pTail)
+
+ if (newChild != null) {
+ val ret = new Array[AnyRef](arr.length)
+ Array.copy(arr, 0, ret, 0, arr.length)
+
+ ret(arr.length - 1) = newChild
+
+ return (ret, subPTail)
+ }
+ subPTail
+ } else if (shift == 0) {
+ arr(arr.length - 1)
+ } else pTail
+
+ // contraction
+ if (arr.length == 1) {
+ (null, newPTail)
+ } else {
+ val ret = new Array[AnyRef](arr.length - 1)
+ Array.copy(arr, 0, ret, 0, ret.length)
+
+ (ret, newPTail)
+ }
+ }
+
+ override def filter(p: (T)=>Boolean) = {
+ var back = new Vector[T]
+ var i = 0
+
+ while (i < length) {
+ val e = apply(i)
+ if (p(e)) back += e
+
+ i += 1
+ }
+
+ back
+ }
+
+ override def flatMap[A](f: (T)=>Iterable[A]) = {
+ var back = new Vector[A]
+ var i = 0
+
+ while (i < length) {
+ f(apply(i)) foreach { back += _ }
+ i += 1
+ }
+
+ back
+ }
+
+ override def map[A](f: (T)=>A) = {
+ var back = new Vector[A]
+ var i = 0
+
+ while (i < length) {
+ back += f(apply(i))
+ i += 1
+ }
+
+ back
+ }
+
+ override def reverse: Vector[T] = new VectorProjection[T] {
+ override val length = outer.length
+
+ override def apply(i: Int) = outer.apply(length - i - 1)
+ }
+
+ override def subseq(from: Int, end: Int) = subVector(from, end)
+
+ def subVector(from: Int, end: Int): Vector[T] = {
+ if (from < 0) {
+ throw new IndexOutOfBoundsException(from.toString)
+ } else if (end >= length) {
+ throw new IndexOutOfBoundsException(end.toString)
+ } else if (end <= from) {
+ throw new IllegalArgumentException("Invalid range: " + from + ".." + end)
+ } else {
+ new VectorProjection[T] {
+ override val length = end - from
+
+ override def apply(i: Int) = outer.apply(i + from)
+ }
+ }
+ }
+
+ def zip[A](that: Vector[A]) = {
+ var back = new Vector[(T, A)]
+ var i = 0
+
+ val limit = Math.min(length, that.length)
+ while (i < limit) {
+ back += (apply(i), that(i))
+ i += 1
+ }
+
+ back
+ }
+
+ def zipWithIndex = {
+ var back = new Vector[(T, Int)]
+ var i = 0
+
+ while (i < length) {
+ back += (apply(i), i)
+ i += 1
+ }
+
+ back
+ }
+
+ override def equals(other: Any) = other match {
+ case vec:Vector[T] => {
+ var back = length == vec.length
+ var i = 0
+
+ while (i < length) {
+ back &&= apply(i) == vec.apply(i)
+ i += 1
+ }
+
+ back
+ }
+
+ case _ => false
+ }
+
+ override def hashCode = foldLeft(0) { _ ^ _.hashCode }
+}
+
+object Vector {
+ private[collection] val EmptyArray = new Array[AnyRef](0)
+
+ def apply[T](elems: T*) = elems.foldLeft(EmptyVector:Vector[T]) { _ + _ }
+
+ def unapplySeq[T](vec: Vector[T]): Option[Seq[T]] = Some(vec)
+
+ @inline
+ private[collection] def array(elems: AnyRef*) = {
+ val back = new Array[AnyRef](elems.length)
+ Array.copy(elems, 0, back, 0, back.length)
+
+ back
+ }
+}
+
+object EmptyVector extends Vector[Nothing]
+
+private[collection] abstract class VectorProjection[+T] extends Vector[T] {
+ override val length: Int
+ override def apply(i: Int): T
+
+ override def +[A >: T](e: A) = innerCopy + e
+
+ override def update[A >: T](i: Int, e: A) = {
+ if (i < 0) {
+ throw new IndexOutOfBoundsException(i.toString)
+ } else if (i > length) {
+ throw new IndexOutOfBoundsException(i.toString)
+ } else innerCopy(i) = e
+ }
+
+ private lazy val innerCopy = foldLeft(EmptyVector:Vector[T]) { _ + _ }
+}
+
diff --git a/src/test/scala/BloomSpecs.scala b/src/test/scala/BloomSpecs.scala
new file mode 100644
index 0000000..d4bac42
--- /dev/null
+++ b/src/test/scala/BloomSpecs.scala
@@ -0,0 +1,134 @@
+import org.specs._
+import org.scalacheck._
+
+import java.io.{ByteArrayInputStream, ByteArrayOutputStream}
+import com.codecommit.collection.BloomSet
+
+object BloomSpecs extends Specification with Scalacheck {
+ import Prop._
+
+ "bloom set" should {
+ "store single element once" in {
+ (BloomSet[String]() + "test") contains "test" mustEqual true
+ }
+
+ "store single element n times" in {
+ val prop = property { ls: List[String] =>
+ val set = ls.foldLeft(BloomSet[String]()) { _ + _ }
+
+ ls.foldLeft(true) { _ && set(_) }
+ }
+
+ prop must pass
+ }
+
+ "store duplicate elements n times" in {
+ val prop = property { ls: List[String] =>
+ var set = ls.foldLeft(BloomSet[String]()) { _ + _ }
+ set = ls.foldLeft(set) { _ + _ }
+
+ ls.foldLeft(true) { _ && set(_) }
+ }
+
+ prop must pass
+ }
+
+ "handle ++ Iterable" in {
+ val prop = property { (first: List[String], last: List[String]) =>
+ var set = first.foldLeft(BloomSet[String]()) { _ + _ }
+ set ++= last
+
+ first.foldLeft(true) { _ && set(_) } && last.foldLeft(true) { _ && set(_) }
+ }
+
+ prop must pass
+ }
+
+ "handle ++ BloomSet" in {
+ val prop = property { (first: List[String], last: List[String]) =>
+ var set = first.foldLeft(BloomSet[String]()) { _ + _ }
+ set ++= last.foldLeft(BloomSet[String]()) { _ + _ }
+
+ first.foldLeft(true) { _ && set(_) } && last.foldLeft(true) { _ && set(_) }
+ }
+
+ prop must pass
+ }
+
+ "be immutable" in {
+ val prop = property { (ls: List[String], item: String) =>
+ val set = ls.foldLeft(new BloomSet[String](10000, 5)) { _ + _ }
+
+ // might fail, but it is doubtful
+ (set.accuracy > 0.999 && !ls.contains(item)) ==> {
+ val newSet = set + item
+
+ ls.foldLeft(true) { _ && set(_) } &&
+ !set.contains(item) &&
+ ls.foldLeft(true) { _ && newSet(_) } &&
+ newSet.contains(item)
+ }
+ }
+
+ prop must pass(set(minTestsOk -> 100, maxDiscarded -> 5000, minSize -> 0, maxSize -> 100))
+ }
+
+ "construct using companion" in {
+ val set = BloomSet("daniel", "chris", "joseph", "renee")
+
+ set contains "daniel" mustEqual true
+ set contains "chris" mustEqual true
+ set contains "joseph" mustEqual true
+ set contains "renee" mustEqual true
+ }
+
+ "implement equivalency" in {
+ val prop = property { nums: List[Int] =>
+ val set1 = nums.foldLeft(BloomSet[Int]()) { _ + _}
+ val set2 = nums.foldLeft(BloomSet[Int]()) { _ + _}
+
+ set1 == set2
+ }
+
+ prop must pass
+ }
+
+ "implement hashing" in {
+ val prop = property { nums: List[Int] =>
+ val set1 = nums.foldLeft(BloomSet[Int]()) { _ + _}
+ val set2 = nums.foldLeft(BloomSet[Int]()) { _ + _}
+
+ set1.hashCode == set2.hashCode
+ }
+
+ prop must pass
+ }
+
+ "persist properly" in {
+ val prop = property { (width: Int, k: Int, ls: List[Int]) => (width > 0 && k > 0) ==> {
+ val set = ls.foldLeft(new BloomSet[Int](width, k)) { _ + _ }
+ val os = new ByteArrayOutputStream
+
+ set.store(os)
+ val is = new ByteArrayInputStream(os.toByteArray)
+
+ val newSet = BloomSet.load[Int](is)
+
+ ls.foldLeft(true) { _ && newSet(_) } &&
+ newSet.width == set.width &&
+ newSet.k == set.k &&
+ newSet.size == set.size
+ }
+ }
+
+ prop must pass
+ }
+
+ "calculate accuracy" in {
+ BloomSet[Int]().accuracy mustEqual 1d
+
+ val set = (0 until 1000).foldLeft(BloomSet[Int]()) { _ + _ }
+ set.accuracy must beCloseTo(0d, 0.0000001d)
+ }
+ }
+}
diff --git a/src/test/scala/HashMapSpecs.scala b/src/test/scala/HashMapSpecs.scala
new file mode 100644
index 0000000..5f57ce0
--- /dev/null
+++ b/src/test/scala/HashMapSpecs.scala
@@ -0,0 +1,93 @@
+import org.specs._
+import org.scalacheck._
+
+import com.codecommit.collection.HashMap
+
+object HashMapSpecs extends Specification with Scalacheck {
+ import Prop._
+
+ "it" should {
+ "store ints" in {
+ val prop = property { src: List[Int] =>
+ val map = src.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = -v }
+ src forall { v => map(v) == -v }
+ }
+
+ prop must pass
+ }
+
+ "store strings" in {
+ val prop = property { src: List[String] =>
+ val map = src.foldLeft(new HashMap[String, Int]) { (m, v) => m(v) = v.length }
+ src forall { v => map(v) == v.length }
+ }
+
+ prop must pass
+ }
+
+ "preserve values across changes" in {
+ val prop = property { (map: HashMap[String, String], ls: List[String], f: (String)=>String) =>
+ val filtered = ls filter { !map.contains(_) }
+
+ filtered.length > 0 ==> {
+ val newMap = filtered.foldLeft(map) { (m, k) => m(k) = f(k) }
+
+ (map forall { case (k, v) => newMap(k) == v }) && (filtered forall { v => newMap(v) == f(v) })
+ }
+ }
+
+ prop must pass
+ }
+
+ "calculate size" in {
+ val prop = property { (ls: Set[Int], f: (Int)=>Int) =>
+ val map = ls.foldLeft(new HashMap[Int, Int]) { (m, v) => m(v) = f(v) }
+ map.size == ls.size
+ }
+
+ prop must pass
+ }
+
+ "remove ints" in {
+ val prop = property { map: HashMap[Int, String] =>
+ map.size > 0 ==> {
+ val (rm, _) = map.elements.next
+ val newMap = map - rm
+
+ !newMap.contains(rm) &&
+ (newMap forall { case (k, v) => map(k) == v }) &&
+ newMap.size == map.size - 1
+ }
+ }
+
+ prop must pass
+ }
+
+ "remove strings" in {
+ val prop = property { map: HashMap[String, String] =>
+ map.size > 0 ==> {
+ val (rm, _) = map.elements.next
+ val newMap = map - rm
+
+ !newMap.contains(rm) &&
+ (newMap forall { case (k, v) => map(k) == v }) &&
+ newMap.size == map.size - 1
+ }
+ }
+
+ prop must pass
+ }
+ }
+
+ implicit def arbHashMap[K](implicit ak: Arbitrary[List[K]]): Arbitrary[HashMap[K, String]] = {
+ Arbitrary(for {
+ keys <- ak.arbitrary
+ } yield keys.foldLeft(new HashMap[K, String]) { (m, k) => m(k) = k.toString })
+ }
+
+ implicit def arbSet[A](implicit arb: Arbitrary[List[A]]): Arbitrary[Set[A]] = {
+ Arbitrary(for {
+ ls <- arb.arbitrary
+ } yield ls.foldLeft(Set[A]()) { _ + _ })
+ }
+}
diff --git a/src/test/scala/PathVectorSpecs.scala b/src/test/scala/PathVectorSpecs.scala
new file mode 100644
index 0000000..e4f2574
--- /dev/null
+++ b/src/test/scala/PathVectorSpecs.scala
@@ -0,0 +1,299 @@
+import org.specs._
+import org.scalacheck._
+
+import com.codecommit.collection.PathVector
+
+object PathVectorSpecs extends Specification with Scalacheck {
+ import Prop._
+
+ val vector = PathVector[Int]()
+
+ implicit def arbitraryPathVector[A](implicit arb: Arbitrary[A]): Arbitrary[PathVector[A]] = {
+ Arbitrary(for {
+ data <- Arbitrary.arbitrary[List[A]]
+ indexes <- Gen.containerOfN[List, Int](data.length, Gen.choose(0, Math.MAX_INT - 1))
+ } yield {
+ var vec = new PathVector[A]
+
+ var i = 0
+ for (d <- data) {
+ vec(indexes(i)) = d
+ i += 1
+ }
+
+ vec
+ })
+ }
+
+
+ "path vector" should {
+ "have infinite bounds" in {
+ vector.length mustEqual 0 // finite length
+
+ val prop = property { i: Int => // infinite bounds
+ i >= 0 ==> (vector(i) == 0)
+ }
+
+ prop must pass
+ }
+
+ "store a single element" in {
+ val prop = property { (i: Int, e: Int) =>
+ i >= 0 ==> ((vector(0) = e)(0) == e)
+ }
+
+ prop must pass
+ }
+
+ "replace single element" in {
+ val prop = property { (vec: PathVector[String], i: Int) =>
+ i >= 0 ==> {
+ val newPathVector = (vec(i) = "test")(i) = "newTest"
+ newPathVector(i) == "newTest"
+ }
+ }
+
+ prop must pass
+ }
+
+ "store multiple elements in order" in {
+ val prop = property { list: List[Int] =>
+ val newPathVector = list.foldLeft(vector) { _ + _ }
+ val res = for (i <- 0 until list.length) yield newPathVector(i) == list(i)
+
+ res forall { _ == true }
+ }
+
+ prop must pass
+ }
+
+ "store lots of elements" in {
+ val LENGTH = 100000
+ val vector = (0 until LENGTH).foldLeft(PathVector[Int]()) { _ + _ }
+
+ vector.length mustEqual LENGTH
+ for (i <- 0 until LENGTH) {
+ vector(i) mustEqual i
+ }
+ }
+
+ "store at arbitrary points" in {
+ val vector = PathVector(1, 2, 3, 4, 5)
+ val prop = property { others: List[(Int, Int)] =>
+ val (newPathVector, resMap) = others.foldLeft(vector, Map[Int, Int]()) { (inTuple, tuple) =>
+ val (i, value) = tuple
+ val (vec, map) = inTuple
+
+ if (i < 0) (vec, map) else (vec(i) = value, map + (i -> value))
+ }
+
+ val res = for {
+ (i, _) <- others
+ } yield if (i < 0) true else newPathVector(i) == resMap(i)
+
+ res forall { _ == true }
+ }
+
+ prop must pass
+ }
+
+ "implement filter" in {
+ val prop = property { (vec: PathVector[Int], f: (Int)=>Boolean) =>
+ val filtered = vec filter f
+
+ var back = filtered forall f
+ for (e <- vec) {
+ if (f(e)) {
+ back &&= filtered.contains(e)
+ }
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement foldLeft" in {
+ val prop = property { list: List[Int] =>
+ val vec = list.foldLeft(new PathVector[Int]) { _ + _ }
+ vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ }
+ }
+
+ prop must pass
+ }
+
+ "implement forall" in {
+ val prop = property { (vec: PathVector[Int], f: (Int)=>Boolean) =>
+ val bool = vec forall f
+
+ var back = true
+ for (e <- vec) {
+ back &&= f(e)
+ }
+
+ (back && bool) || (!back && !bool)
+ }
+
+ prop must pass
+ }
+
+ "implement map" in {
+ val prop = property { (vec: PathVector[Int], f: (Int)=>Int) =>
+ val mapped = vec map f
+
+ var back = vec.length == mapped.length
+ for (i <- 0 until vec.length) {
+ back &&= mapped(i) == f(vec(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement reverse" in {
+ val prop = property { v: PathVector[Int] =>
+ val reversed = v.reverse
+
+ var back = v.length == reversed.length
+ for (i <- 0 until v.length) {
+ back &&= reversed(i) == v(v.length - i - 1)
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "append to reverse" in {
+ val prop = property { (v: PathVector[Int], n: Int) =>
+ val rev = v.reverse
+ val add = rev + n
+
+ var back = add.length == rev.length + 1
+ for (i <- 0 until rev.length) {
+ back &&= add(i) == rev(i)
+ }
+ back && add(rev.length) == n
+ }
+
+ prop must pass
+ }
+
+ "map on reverse" in {
+ val prop = property { (v: PathVector[Int], f: (Int)=>Int) =>
+ val rev = v.reverse
+ val mapped = rev map f
+
+ var back = mapped.length == rev.length
+ for (i <- 0 until rev.length) {
+ back &&= mapped(i) == f(rev(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement subseq" in {
+ val prop = property { (v: PathVector[Int], from: Int, end: Int) =>
+ try {
+ val sub = v.subseq(from, end)
+
+ var back = sub.length == end - from
+ for (i <- 0 until sub.length) {
+ back &&= sub(i) == v(i + from)
+ }
+ back
+ } catch {
+ case _:IndexOutOfBoundsException => from < 0
+ case _:IllegalArgumentException => end <= from
+ }
+ }
+
+ prop must pass
+ }
+
+ "append to subseq" in {
+ val prop = property { (v: PathVector[Int], from: Int, end: Int, n: Int) =>
+ try {
+ val sub = v.subseq(from, end)
+ val add = sub + n
+
+ var back = add.length == sub.length + 1
+ for (i <- 0 until sub.length) {
+ back &&= add(i) == sub(i)
+ }
+ back && add(sub.length) == n
+ } catch {
+ case _:IndexOutOfBoundsException => from < 0
+ case _:IllegalArgumentException => end <= from
+ }
+ }
+
+ prop must pass
+ }
+
+ "map on subseq" in {
+ val prop = property { (v: PathVector[Int], from: Int, end: Int, f: (Int)=>Int) =>
+ try {
+ val sub = v.subseq(from, end)
+ val mapped = sub map f
+
+ var back = mapped.length == sub.length
+ for (i <- 0 until sub.length) {
+ back &&= mapped(i) == f(sub(i))
+ }
+ back
+ } catch {
+ case _:IndexOutOfBoundsException => from < 0
+ case _:IllegalArgumentException => end <= from
+ }
+ }
+
+ prop must pass
+ }
+
+ "implement zip" in {
+ val prop = property { (first: PathVector[Int], second: PathVector[Double]) =>
+ val zip = first zip second
+
+ var back = zip.length == Math.max(first.length, second.length)
+ for (i <- 0 until zip.length) {
+ var (left, right) = zip(i)
+ back &&= (left == first(i) && right == second(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement zipWithIndex" in {
+ val prop = property { vec: PathVector[Int] =>
+ val zip = vec.zipWithIndex
+
+ var back = zip.length == vec.length
+ for (i <- 0 until zip.length) {
+ val (elem, index) = zip(i)
+
+ back &&= (index == i && elem == vec(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement equals" in {
+ val prop = property { list: List[Int] =>
+ val vecA = list.foldLeft(new PathVector[Int]) { _ + _ }
+ val vecB = list.foldLeft(new PathVector[Int]) { _ + _ }
+
+ vecA == vecB
+ }
+
+ prop must pass
+ }
+ }
+}
diff --git a/src/test/scala/VectorSpecs.scala b/src/test/scala/VectorSpecs.scala
new file mode 100644
index 0000000..f71fe87
--- /dev/null
+++ b/src/test/scala/VectorSpecs.scala
@@ -0,0 +1,332 @@
+import org.specs._
+import org.scalacheck._
+
+import com.codecommit.collection.Vector
+
+object VectorSpecs extends Specification with Scalacheck {
+ import Prop._
+
+ val vector = Vector[Int]()
+
+ implicit def arbitraryVector[A](implicit arb: Arbitrary[A]): Arbitrary[Vector[A]] = {
+ Arbitrary(for {
+ data <- Arbitrary.arbitrary[List[A]]
+ } yield data.foldLeft(Vector[A]()) { _ + _ })
+ }
+
+ "vector" should {
+ "store a single element" in {
+ val prop = property { (i: Int, e: Int) =>
+ i >= 0 ==> ((vector(0) = e)(0) == e)
+ }
+
+ prop must pass
+ }
+
+ "replace single element" in {
+ val prop = property { (vec: Vector[Int], i: Int) =>
+ ((0 to vec.length) contains i) ==> {
+ val newVector = (vec(i) = "test")(i) = "newTest"
+ newVector(i) == "newTest"
+ }
+ }
+
+ prop must pass
+ }
+
+ "pop elements" in {
+ val prop = property { vec: Vector[Int] =>
+ vec.length > 0 ==> {
+ val popped = vec.pop
+
+ var back = popped.length == vec.length - 1
+ var i = 0
+
+ while (i < popped.length) {
+ back &&= popped(i) == vec(i)
+ i += 1
+ }
+
+ back
+ }
+ }
+
+ prop must pass
+ }
+
+ "store multiple elements in order" in {
+ val prop = property { list: List[Int] =>
+ val newVector = list.foldLeft(vector) { _ + _ }
+ val res = for (i <- 0 until list.length) yield newVector(i) == list(i)
+
+ res forall { _ == true }
+ }
+
+ prop must pass
+ }
+
+ "store lots of elements" in {
+ val LENGTH = 100000
+ val vector = (0 until LENGTH).foldLeft(Vector[Int]()) { _ + _ }
+
+ vector.length mustEqual LENGTH
+ for (i <- 0 until LENGTH) {
+ vector(i) mustEqual i
+ }
+ }
+
+ "implement filter" in {
+ val prop = property { (vec: Vector[Int], f: (Int)=>Boolean) =>
+ val filtered = vec filter f
+
+ var back = filtered forall f
+ for (e <- vec) {
+ if (f(e)) {
+ back &&= filtered.contains(e)
+ }
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement foldLeft" in {
+ val prop = property { list: List[Int] =>
+ val vec = list.foldLeft(Vector[Int]()) { _ + _ }
+ vec.foldLeft(0) { _ + _ } == list.foldLeft(0) { _ + _ }
+ }
+
+ prop must pass
+ }
+
+ "implement forall" in {
+ val prop = property { (vec: Vector[Int], f: (Int)=>Boolean) =>
+ val bool = vec forall f
+
+ var back = true
+ for (e <- vec) {
+ back &&= f(e)
+ }
+
+ (back && bool) || (!back && !bool)
+ }
+
+ prop must pass
+ }
+
+ "implement flatMap" in {
+ val prop = property { (vec: Vector[Int], f: (Int)=>Vector[Int]) =>
+ val mapped = vec flatMap f
+
+ var back = true
+
+ var i = 0
+ var n = 0
+
+ while (i < vec.length) {
+ val res = f(vec(i))
+
+ var inner = 0
+ while (inner < res.length) {
+ back &&= mapped(n) == res(inner)
+
+ inner += 1
+ n += 1
+ }
+
+ i += 1
+ }
+
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement map" in {
+ val prop = property { (vec: Vector[Int], f: (Int)=>Int) =>
+ val mapped = vec map f
+
+ var back = vec.length == mapped.length
+ for (i <- 0 until vec.length) {
+ back &&= mapped(i) == f(vec(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement reverse" in {
+ val prop = property { v: Vector[Int] =>
+ val reversed = v.reverse
+
+ var back = v.length == reversed.length
+ for (i <- 0 until v.length) {
+ back &&= reversed(i) == v(v.length - i - 1)
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "append to reverse" in {
+ val prop = property { (v: Vector[Int], n: Int) =>
+ val rev = v.reverse
+ val add = rev + n
+
+ var back = add.length == rev.length + 1
+ for (i <- 0 until rev.length) {
+ back &&= add(i) == rev(i)
+ }
+ back && add(rev.length) == n
+ }
+
+ prop must pass
+ }
+
+ "map on reverse" in {
+ val prop = property { (v: Vector[Int], f: (Int)=>Int) =>
+ val rev = v.reverse
+ val mapped = rev map f
+
+ var back = mapped.length == rev.length
+ for (i <- 0 until rev.length) {
+ back &&= mapped(i) == f(rev(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement subseq" in {
+ val prop = property { (v: Vector[Int], from: Int, end: Int) =>
+ try {
+ val sub = v.subseq(from, end)
+
+ var back = sub.length == end - from
+
+ for (i <- 0 until sub.length) {
+ back &&= sub(i) == v(i + from)
+ }
+
+ back
+ } catch {
+ case _:IndexOutOfBoundsException => from < 0 || end >= v.length
+ case _:IllegalArgumentException => end <= from
+ }
+ }
+
+ prop must pass
+ }
+
+ "append to subseq" in {
+ val prop = property { (v: Vector[Int], from: Int, end: Int, n: Int) =>
+ try {
+ val sub = v.subseq(from, end)
+ val add = sub + n
+
+ var back = add.length == sub.length + 1
+ for (i <- 0 until sub.length) {
+ back &&= add(i) == sub(i)
+ }
+ back && add(sub.length) == n
+ } catch {
+ case _:IndexOutOfBoundsException => from < 0 || end >= v.length
+ case _:IllegalArgumentException => end <= from
+ }
+ }
+
+ prop must pass
+ }
+
+ "map on subseq" in {
+ val prop = property { (v: Vector[Int], from: Int, end: Int, f: (Int)=>Int) =>
+ try {
+ val sub = v.subseq(from, end)
+ val mapped = sub map f
+
+ var back = mapped.length == sub.length
+ for (i <- 0 until sub.length) {
+ back &&= mapped(i) == f(sub(i))
+ }
+ back
+ } catch {
+ case _:IndexOutOfBoundsException => from < 0 || end >= v.length
+ case _:IllegalArgumentException => end <= from
+ }
+ }
+
+ prop must pass
+ }
+
+ "implement zip" in {
+ val prop = property { (first: Vector[Int], second: Vector[Double]) =>
+ val zip = first zip second
+
+ var back = zip.length == Math.min(first.length, second.length)
+ for (i <- 0 until zip.length) {
+ var (left, right) = zip(i)
+ back &&= (left == first(i) && right == second(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement zipWithIndex" in {
+ val prop = property { vec: Vector[Int] =>
+ val zip = vec.zipWithIndex
+
+ var back = zip.length == vec.length
+ for (i <- 0 until zip.length) {
+ val (elem, index) = zip(i)
+
+ back &&= (index == i && elem == vec(i))
+ }
+ back
+ }
+
+ prop must pass
+ }
+
+ "implement equals" in {
+ val prop = property { list: List[Int] =>
+ val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
+ val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
+
+ vecA == vecB
+ }
+
+ prop must pass
+ }
+
+ "implement hashCode" in {
+ val prop = property { list: List[Int] =>
+ val vecA = list.foldLeft(Vector[Int]()) { _ + _ }
+ val vecB = list.foldLeft(Vector[Int]()) { _ + _ }
+
+ vecA.hashCode == vecB.hashCode
+ }
+
+ prop must pass
+ }
+
+ "implement extractor" in {
+ val vec1 = Vector(1, 2, 3)
+ vec1 must beLike {
+ case Vector(a, b, c) => (a, b, c) == (1, 2, 3)
+ }
+
+ val vec2 = Vector("daniel", "chris", "joseph")
+ vec2 must beLike {
+ case Vector(a, b, c) => (a, b, c) == ("daniel", "chris", "joseph")
+ }
+ }
+ }
+}
+
|
anerian/rack-analytics
|
ba1ad1ae37712750ba53f72cc8fd5f0319ee5117
|
add in mutex support
|
diff --git a/lib/rack-analytics.rb b/lib/rack-analytics.rb
index 337cbba..12dd03c 100644
--- a/lib/rack-analytics.rb
+++ b/lib/rack-analytics.rb
@@ -1,127 +1,134 @@
require 'ruby-prof'
require 'ruby-debug'
+$reporter = nil
+$mutex = Mutex.new
module Rack
+ class Reporter
+ attr_accessor :logfile
+ def initialize(logfile=nil)
+ @logfile = logfile
+ end
+ end
# Set the profile=process_time query parameter to download a
# calltree profile of the request.
#
# Pass the :printer option to pick a different result format.
class Analytics
- BUFFER_SIZE = 5
LOG_DIR = '.'
- LOGFILE_MAX_SIZE = 30 # in Kilobytes, ie 1 mb
- LOGFILE_MAX_AGE = 1000 # in seconds, ie 1 hour
+ LOGFILE_MAX_SIZE = 1024 * 500# in bytes, ie 1 mb
+ LOGFILE_MAX_AGE = 3 # in seconds, ie 1 hour
MODES = %w(
process_time
wall_time
cpu_time
)
def initialize(app, options = {})
+ $reporter ||= Reporter.new
@app = app
@profile_type = :time
@write_type = :file
end
def call(env)
case @profile_type
when :prof
profile(env, mode)
when :time
start_time = Time.now
app_response = @app.call(env)
end_time = Time.now
time_taken = end_time - start_time
# dup, otherwise we screw up the env hash for rack
# also merge with an empty new Hash to create a real Hash and not a Mongrel::HttpParams 'hash'
@rack_env = Hash.new.merge(env.dup)
# a mix of IO and Action::* classes that rails can't to_yaml
@rack_env.delete('rack.errors')
@rack_env.delete('rack.input')
@rack_env.delete('action_controller.rescue.request')
@rack_env.delete('action_controller.rescue.response')
@rack_env.delete('rack.session')
data = {:time_taken => time_taken, :created_at => Time.now.to_i, :rack_env => @rack_env}
if @write_type == :file
- filename = get_logfile_name
- if logfile_needs_rotating?(filename)
- filename = rotate_logfile(filename)
+ $mutex.synchronize do
+ set_new_logfile unless $reporter.logfile
+ filename = $reporter.logfile
+ if logfile_needs_rotating?(filename)
+ filename = rotate_logfile(filename)
+ end
+ file_write(filename, data.to_yaml)
end
- file_write(filename, data.to_yaml)
elsif @write_type == :db
ActiveRecord::Base.connection.insert("insert into log_entries (time_taken, details, created_at) values (#{time_taken}, #{ActiveRecord::Base.connection.quote(@rack_env)}, #{Time.now.to_i})")
end
app_response
else
@app.call(env)
end
end
def rotate_logfile(filename)
- puts "rotating logfile"
+ debug "rotating logfile"
`mv #{filename} archived.#{filename}`
- get_new_logfile_name
+ set_new_logfile
end
def logfile_needs_rotating?(filename)
# this assumes an analysis.port_number.timestamp.log layout
created_at = filename.split('.')[2].to_i
(Time.now.to_i - created_at) > LOGFILE_MAX_AGE or (::File.exists?(filename) and ::File.size(filename) > LOGFILE_MAX_SIZE)
end
- def get_logfile_name
- unless filename = logfile_exists?
- filename = get_new_logfile_name
- end
- filename
+ def set_new_logfile
+ $reporter.logfile = get_new_logfile_name
end
def get_new_logfile_name
"analysis.#{@rack_env['SERVER_PORT']}.#{Time.now.to_i}.log"
end
- def logfile_exists?
- # this assumes an analysis.port_number.timestamp.log layout
- Dir.entries(LOG_DIR).find {|filename| filename =~ /analysis\.\d+\.\d+\.log/}
- end
-
def profile(env, mode)
RubyProf.measure_mode = RubyProf.const_get(mode.upcase)
rails_response = []
result = RubyProf.profile do
rails_response = @app.call(env)
end
store_in_filesystem(result, env)
[200, {'Content-Type' => 'text/html'}, rails_response[2]]
end
def file_write(filename, data)
- puts "writing out file #{filename}"
+ debug "writing out file #{filename}"
::File.open(filename, 'a') {|file| file.write data}
end
def store_in_filesystem(result, env)
filename = "public/analytics.profile.#{timestamp}.txt"
string = StringIO.new
RubyProf::FlatPrinter.new(result).print(string, :min_percent => 0.01)
string.rewind
file_write(filename, string)
filename = "public/analytics.rack_env.#{timestamp}.txt"
file_write(filename, env.to_hash.to_yaml)
end
def timestamp
"%10.6f" % Time.now.to_f
end
+
+ def debug(text)
+ puts text if $DEBUG
+ end
end
end
|
anerian/rack-analytics
|
ec2f651d86b7dbaf171a14ef7bcbc660897260fd
|
cleanup some unused vars
|
diff --git a/lib/rack-analytics.rb b/lib/rack-analytics.rb
index 79f510f..337cbba 100644
--- a/lib/rack-analytics.rb
+++ b/lib/rack-analytics.rb
@@ -1,131 +1,127 @@
require 'ruby-prof'
require 'ruby-debug'
module Rack
# Set the profile=process_time query parameter to download a
# calltree profile of the request.
#
# Pass the :printer option to pick a different result format.
class Analytics
BUFFER_SIZE = 5
LOG_DIR = '.'
LOGFILE_MAX_SIZE = 30 # in Kilobytes, ie 1 mb
LOGFILE_MAX_AGE = 1000 # in seconds, ie 1 hour
MODES = %w(
process_time
wall_time
cpu_time
)
def initialize(app, options = {})
@app = app
@profile_type = :time
@write_type = :file
end
def call(env)
case @profile_type
when :prof
profile(env, mode)
when :time
start_time = Time.now
app_response = @app.call(env)
end_time = Time.now
time_taken = end_time - start_time
# dup, otherwise we screw up the env hash for rack
# also merge with an empty new Hash to create a real Hash and not a Mongrel::HttpParams 'hash'
@rack_env = Hash.new.merge(env.dup)
# a mix of IO and Action::* classes that rails can't to_yaml
@rack_env.delete('rack.errors')
@rack_env.delete('rack.input')
@rack_env.delete('action_controller.rescue.request')
@rack_env.delete('action_controller.rescue.response')
@rack_env.delete('rack.session')
data = {:time_taken => time_taken, :created_at => Time.now.to_i, :rack_env => @rack_env}
if @write_type == :file
filename = get_logfile_name
if logfile_needs_rotating?(filename)
filename = rotate_logfile(filename)
end
- file_write(filename, @analytics_data.to_yaml)
+ file_write(filename, data.to_yaml)
elsif @write_type == :db
ActiveRecord::Base.connection.insert("insert into log_entries (time_taken, details, created_at) values (#{time_taken}, #{ActiveRecord::Base.connection.quote(@rack_env)}, #{Time.now.to_i})")
end
app_response
else
@app.call(env)
end
end
def rotate_logfile(filename)
puts "rotating logfile"
`mv #{filename} archived.#{filename}`
get_new_logfile_name
end
def logfile_needs_rotating?(filename)
# this assumes an analysis.port_number.timestamp.log layout
created_at = filename.split('.')[2].to_i
(Time.now.to_i - created_at) > LOGFILE_MAX_AGE or (::File.exists?(filename) and ::File.size(filename) > LOGFILE_MAX_SIZE)
end
def get_logfile_name
unless filename = logfile_exists?
filename = get_new_logfile_name
end
filename
end
def get_new_logfile_name
"analysis.#{@rack_env['SERVER_PORT']}.#{Time.now.to_i}.log"
end
def logfile_exists?
# this assumes an analysis.port_number.timestamp.log layout
Dir.entries(LOG_DIR).find {|filename| filename =~ /analysis\.\d+\.\d+\.log/}
end
- def should_writeout_data
- @analytics_data.size >= BUFFER_SIZE
- end
-
def profile(env, mode)
RubyProf.measure_mode = RubyProf.const_get(mode.upcase)
rails_response = []
result = RubyProf.profile do
rails_response = @app.call(env)
end
store_in_filesystem(result, env)
[200, {'Content-Type' => 'text/html'}, rails_response[2]]
end
def file_write(filename, data)
puts "writing out file #{filename}"
::File.open(filename, 'a') {|file| file.write data}
end
def store_in_filesystem(result, env)
filename = "public/analytics.profile.#{timestamp}.txt"
string = StringIO.new
RubyProf::FlatPrinter.new(result).print(string, :min_percent => 0.01)
string.rewind
file_write(filename, string)
filename = "public/analytics.rack_env.#{timestamp}.txt"
file_write(filename, env.to_hash.to_yaml)
end
def timestamp
"%10.6f" % Time.now.to_f
end
end
end
|
anerian/rack-analytics
|
540da863bfc1f8bb6f62574f9cf16585be69e13d
|
flesh out file writing/archiving functionality
|
diff --git a/lib/rack-analytics.rb b/lib/rack-analytics.rb
index 85edffa..79f510f 100644
--- a/lib/rack-analytics.rb
+++ b/lib/rack-analytics.rb
@@ -1,100 +1,131 @@
require 'ruby-prof'
require 'ruby-debug'
module Rack
# Set the profile=process_time query parameter to download a
# calltree profile of the request.
#
# Pass the :printer option to pick a different result format.
class Analytics
BUFFER_SIZE = 5
+ LOG_DIR = '.'
+ LOGFILE_MAX_SIZE = 30 # in Kilobytes, ie 1 mb
+ LOGFILE_MAX_AGE = 1000 # in seconds, ie 1 hour
+
MODES = %w(
process_time
wall_time
cpu_time
)
def initialize(app, options = {})
@app = app
@profile_type = :time
@write_type = :file
- if @write_type == :file
- @analytics_data = []
- end
end
def call(env)
case @profile_type
when :prof
profile(env, mode)
when :time
start_time = Time.now
app_response = @app.call(env)
end_time = Time.now
time_taken = end_time - start_time
# dup, otherwise we screw up the env hash for rack
# also merge with an empty new Hash to create a real Hash and not a Mongrel::HttpParams 'hash'
- rack_env = Hash.new.merge(env.dup)
+ @rack_env = Hash.new.merge(env.dup)
# a mix of IO and Action::* classes that rails can't to_yaml
- rack_env.delete('rack.errors')
- rack_env.delete('rack.input')
- rack_env.delete('action_controller.rescue.request')
- rack_env.delete('action_controller.rescue.response')
- rack_env.delete('rack.session')
+ @rack_env.delete('rack.errors')
+ @rack_env.delete('rack.input')
+ @rack_env.delete('action_controller.rescue.request')
+ @rack_env.delete('action_controller.rescue.response')
+ @rack_env.delete('rack.session')
+
+ data = {:time_taken => time_taken, :created_at => Time.now.to_i, :rack_env => @rack_env}
if @write_type == :file
- if should_writeout_data
- file_write("analysis.current.log", @analytics_data.to_yaml)
- @analytics_data = []
- else
- @analytics_data << {:time_taken => time_taken, :created_at => Time.now.to_i, :rack_env => rack_env}
+ filename = get_logfile_name
+ if logfile_needs_rotating?(filename)
+ filename = rotate_logfile(filename)
end
+ file_write(filename, @analytics_data.to_yaml)
elsif @write_type == :db
- ActiveRecord::Base.connection.insert("insert into log_entries (time_taken, details, created_at) values (#{time_taken}, #{ActiveRecord::Base.connection.quote(rack_env)}, #{Time.now.to_i})")
+ ActiveRecord::Base.connection.insert("insert into log_entries (time_taken, details, created_at) values (#{time_taken}, #{ActiveRecord::Base.connection.quote(@rack_env)}, #{Time.now.to_i})")
end
app_response
else
@app.call(env)
end
end
+ def rotate_logfile(filename)
+ puts "rotating logfile"
+ `mv #{filename} archived.#{filename}`
+ get_new_logfile_name
+ end
+
+ def logfile_needs_rotating?(filename)
+ # this assumes an analysis.port_number.timestamp.log layout
+ created_at = filename.split('.')[2].to_i
+ (Time.now.to_i - created_at) > LOGFILE_MAX_AGE or (::File.exists?(filename) and ::File.size(filename) > LOGFILE_MAX_SIZE)
+ end
+
+ def get_logfile_name
+ unless filename = logfile_exists?
+ filename = get_new_logfile_name
+ end
+ filename
+ end
+
+ def get_new_logfile_name
+ "analysis.#{@rack_env['SERVER_PORT']}.#{Time.now.to_i}.log"
+ end
+
+ def logfile_exists?
+ # this assumes an analysis.port_number.timestamp.log layout
+ Dir.entries(LOG_DIR).find {|filename| filename =~ /analysis\.\d+\.\d+\.log/}
+ end
+
def should_writeout_data
@analytics_data.size >= BUFFER_SIZE
end
def profile(env, mode)
RubyProf.measure_mode = RubyProf.const_get(mode.upcase)
rails_response = []
result = RubyProf.profile do
rails_response = @app.call(env)
end
store_in_filesystem(result, env)
[200, {'Content-Type' => 'text/html'}, rails_response[2]]
end
def file_write(filename, data)
+ puts "writing out file #{filename}"
::File.open(filename, 'a') {|file| file.write data}
end
def store_in_filesystem(result, env)
filename = "public/analytics.profile.#{timestamp}.txt"
string = StringIO.new
RubyProf::FlatPrinter.new(result).print(string, :min_percent => 0.01)
string.rewind
file_write(filename, string)
filename = "public/analytics.rack_env.#{timestamp}.txt"
file_write(filename, env.to_hash.to_yaml)
end
def timestamp
"%10.6f" % Time.now.to_f
end
end
end
|
anerian/rack-analytics
|
9b72f4c545d9810e1e8d6dbebab8ec0aba67d791
|
remove debug
|
diff --git a/lib/rack-analytics.rb b/lib/rack-analytics.rb
index 499687c..85edffa 100644
--- a/lib/rack-analytics.rb
+++ b/lib/rack-analytics.rb
@@ -1,101 +1,100 @@
-puts "required main class here"
require 'ruby-prof'
require 'ruby-debug'
module Rack
# Set the profile=process_time query parameter to download a
# calltree profile of the request.
#
# Pass the :printer option to pick a different result format.
class Analytics
BUFFER_SIZE = 5
MODES = %w(
process_time
wall_time
cpu_time
)
def initialize(app, options = {})
@app = app
@profile_type = :time
@write_type = :file
if @write_type == :file
@analytics_data = []
end
end
def call(env)
case @profile_type
when :prof
profile(env, mode)
when :time
start_time = Time.now
app_response = @app.call(env)
end_time = Time.now
time_taken = end_time - start_time
# dup, otherwise we screw up the env hash for rack
# also merge with an empty new Hash to create a real Hash and not a Mongrel::HttpParams 'hash'
rack_env = Hash.new.merge(env.dup)
# a mix of IO and Action::* classes that rails can't to_yaml
rack_env.delete('rack.errors')
rack_env.delete('rack.input')
rack_env.delete('action_controller.rescue.request')
rack_env.delete('action_controller.rescue.response')
rack_env.delete('rack.session')
if @write_type == :file
if should_writeout_data
file_write("analysis.current.log", @analytics_data.to_yaml)
@analytics_data = []
else
@analytics_data << {:time_taken => time_taken, :created_at => Time.now.to_i, :rack_env => rack_env}
end
elsif @write_type == :db
ActiveRecord::Base.connection.insert("insert into log_entries (time_taken, details, created_at) values (#{time_taken}, #{ActiveRecord::Base.connection.quote(rack_env)}, #{Time.now.to_i})")
end
app_response
else
@app.call(env)
end
end
def should_writeout_data
@analytics_data.size >= BUFFER_SIZE
end
def profile(env, mode)
RubyProf.measure_mode = RubyProf.const_get(mode.upcase)
rails_response = []
result = RubyProf.profile do
rails_response = @app.call(env)
end
store_in_filesystem(result, env)
[200, {'Content-Type' => 'text/html'}, rails_response[2]]
end
def file_write(filename, data)
::File.open(filename, 'a') {|file| file.write data}
end
def store_in_filesystem(result, env)
filename = "public/analytics.profile.#{timestamp}.txt"
string = StringIO.new
RubyProf::FlatPrinter.new(result).print(string, :min_percent => 0.01)
string.rewind
file_write(filename, string)
filename = "public/analytics.rack_env.#{timestamp}.txt"
file_write(filename, env.to_hash.to_yaml)
end
def timestamp
"%10.6f" % Time.now.to_f
end
end
end
|
anerian/rack-analytics
|
f815563fe1dc2ba3e9cfd45c3e657a45ba7b0fe1
|
clean up license etc
|
diff --git a/LICENSE b/LICENSE
index 1bb1534..72329a0 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,20 +1,20 @@
-Copyright (c) 2009 Jack Dempsey
+Copyright (c) 2009 Anerian LLC
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.rdoc b/README.rdoc
index 1cfa5ff..225e494 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -1,7 +1,7 @@
= rack-analytics
Description goes here.
== Copyright
-Copyright (c) 2009 Jack Dempsey. See LICENSE for details.
+Copyright (c) 2009 Anerian LLC. See LICENSE for details.
diff --git a/Rakefile b/Rakefile
index 4ab8737..ff3a723 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,56 +1,56 @@
require 'rubygems'
require 'rake'
begin
require 'jeweler'
Jeweler::Tasks.new do |gem|
gem.name = "rack-analytics"
gem.summary = %Q{A gem that provides rack middleware to capture analytics}
- gem.email = "[email protected]"
- gem.homepage = "http://github.com/jackdempsey/rack-analytics"
+ gem.email = "[email protected]"
+ gem.homepage = "http://github.com/anerian/rack-analytics"
gem.authors = ["Jack Dempsey"]
# gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
end
rescue LoadError
puts "Jeweler not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com"
end
require 'rake/testtask'
Rake::TestTask.new(:test) do |test|
test.libs << 'lib' << 'test'
test.pattern = 'test/**/*_test.rb'
test.verbose = true
end
begin
require 'rcov/rcovtask'
Rcov::RcovTask.new do |test|
test.libs << 'test'
test.pattern = 'test/**/*_test.rb'
test.verbose = true
end
rescue LoadError
task :rcov do
abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
end
end
task :default => :test
require 'rake/rdoctask'
Rake::RDocTask.new do |rdoc|
if File.exist?('VERSION.yml')
config = YAML.load(File.read('VERSION.yml'))
version = "#{config[:major]}.#{config[:minor]}.#{config[:patch]}"
else
version = ""
end
rdoc.rdoc_dir = 'rdoc'
rdoc.title = "rack-analytics #{version}"
rdoc.rdoc_files.include('README*')
rdoc.rdoc_files.include('lib/**/*.rb')
end
diff --git a/rack-analytics.gemspec b/rack-analytics.gemspec
index 9f434c7..acf8d7b 100644
--- a/rack-analytics.gemspec
+++ b/rack-analytics.gemspec
@@ -1,44 +1,44 @@
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{rack-analytics}
s.version = "0.0.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Jack Dempsey"]
s.date = %q{2009-04-22}
- s.email = %q{[email protected]}
+ s.email = %q{[email protected]}
s.extra_rdoc_files = [
"LICENSE",
"README.rdoc"
]
s.files = [
"LICENSE",
"README.rdoc",
"Rakefile",
+ "VERSION.yml",
"lib/rack-analytics.rb",
- "lib/rack_analytics.rb",
"test/rack_analytics_test.rb",
"test/test_helper.rb"
]
s.has_rdoc = true
- s.homepage = %q{http://github.com/jackdempsey/rack-analytics}
+ s.homepage = %q{http://github.com/anerian/rack-analytics}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.2}
s.summary = %q{A gem that provides rack middleware to capture analytics}
s.test_files = [
"test/rack_analytics_test.rb",
"test/test_helper.rb"
]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
|
anerian/rack-analytics
|
b8dbad8630d41828c9d4f207881758e778325039
|
move over to use jeweler
|
diff --git a/LICENSE b/LICENSE
index 72329a0..1bb1534 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,20 +1,20 @@
-Copyright (c) 2009 Anerian LLC
+Copyright (c) 2009 Jack Dempsey
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README b/README
deleted file mode 100644
index e69de29..0000000
diff --git a/README.rdoc b/README.rdoc
new file mode 100644
index 0000000..1cfa5ff
--- /dev/null
+++ b/README.rdoc
@@ -0,0 +1,7 @@
+= rack-analytics
+
+Description goes here.
+
+== Copyright
+
+Copyright (c) 2009 Jack Dempsey. See LICENSE for details.
diff --git a/Rakefile b/Rakefile
index 364868c..4ab8737 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,57 +1,56 @@
require 'rubygems'
-require 'rake/gempackagetask'
-require 'rubygems/specification'
-require 'date'
-require 'spec/rake/spectask'
-
-GEM = "rack-analytics"
-GEM_VERSION = "0.0.1"
-AUTHOR = "Anerian LLC"
-EMAIL = "[email protected]"
-HOMEPAGE = "http://anerian.com"
-SUMMARY = "A gem that provides rack middlware to analyze Rails apps"
-
-spec = Gem::Specification.new do |s|
- s.name = GEM
- s.version = GEM_VERSION
- s.platform = Gem::Platform::RUBY
- s.has_rdoc = true
- s.extra_rdoc_files = ["README", "LICENSE", 'TODO']
- s.summary = SUMMARY
- s.description = s.summary
- s.author = AUTHOR
- s.email = EMAIL
- s.homepage = HOMEPAGE
-
- # Uncomment this to add a dependency
- # s.add_dependency "foo"
-
- s.require_path = 'lib'
- s.autorequire = GEM
- s.files = %w(LICENSE README Rakefile TODO) + Dir.glob("{lib,spec}/**/*")
+require 'rake'
+
+begin
+ require 'jeweler'
+ Jeweler::Tasks.new do |gem|
+ gem.name = "rack-analytics"
+ gem.summary = %Q{A gem that provides rack middleware to capture analytics}
+ gem.email = "[email protected]"
+ gem.homepage = "http://github.com/jackdempsey/rack-analytics"
+ gem.authors = ["Jack Dempsey"]
+
+ # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
+ end
+rescue LoadError
+ puts "Jeweler not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com"
end
-task :default => :spec
-
-desc "Run specs"
-Spec::Rake::SpecTask.new do |t|
- t.spec_files = FileList['spec/**/*_spec.rb']
- t.spec_opts = %w(-fs --color)
+require 'rake/testtask'
+Rake::TestTask.new(:test) do |test|
+ test.libs << 'lib' << 'test'
+ test.pattern = 'test/**/*_test.rb'
+ test.verbose = true
end
-
-Rake::GemPackageTask.new(spec) do |pkg|
- pkg.gem_spec = spec
+begin
+ require 'rcov/rcovtask'
+ Rcov::RcovTask.new do |test|
+ test.libs << 'test'
+ test.pattern = 'test/**/*_test.rb'
+ test.verbose = true
+ end
+rescue LoadError
+ task :rcov do
+ abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
+ end
end
-desc "install the gem locally"
-task :install => [:package] do
- sh %{sudo gem install pkg/#{GEM}-#{GEM_VERSION}}
-end
-desc "create a gemspec file"
-task :make_spec do
- File.open("#{GEM}.gemspec", "w") do |file|
- file.puts spec.to_ruby
+task :default => :test
+
+require 'rake/rdoctask'
+Rake::RDocTask.new do |rdoc|
+ if File.exist?('VERSION.yml')
+ config = YAML.load(File.read('VERSION.yml'))
+ version = "#{config[:major]}.#{config[:minor]}.#{config[:patch]}"
+ else
+ version = ""
end
+
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = "rack-analytics #{version}"
+ rdoc.rdoc_files.include('README*')
+ rdoc.rdoc_files.include('lib/**/*.rb')
end
+
diff --git a/TODO b/TODO
deleted file mode 100644
index 321c447..0000000
--- a/TODO
+++ /dev/null
@@ -1,4 +0,0 @@
-TODO:
-Fix LICENSE with your name
-Fix Rakefile with your name and contact info
-Add your code to lib/<%= name %>.rb
\ No newline at end of file
diff --git a/VERSION.yml b/VERSION.yml
new file mode 100644
index 0000000..aeeffca
--- /dev/null
+++ b/VERSION.yml
@@ -0,0 +1,4 @@
+---
+:major: 0
+:minor: 0
+:patch: 0
diff --git a/lib/rack-analytics.rb b/lib/rack-analytics.rb
index f4c01bb..499687c 100644
--- a/lib/rack-analytics.rb
+++ b/lib/rack-analytics.rb
@@ -1 +1,101 @@
-require 'rack/analytics'
+puts "required main class here"
+require 'ruby-prof'
+require 'ruby-debug'
+
+module Rack
+ # Set the profile=process_time query parameter to download a
+ # calltree profile of the request.
+ #
+ # Pass the :printer option to pick a different result format.
+ class Analytics
+ BUFFER_SIZE = 5
+ MODES = %w(
+ process_time
+ wall_time
+ cpu_time
+ )
+
+ def initialize(app, options = {})
+ @app = app
+ @profile_type = :time
+ @write_type = :file
+ if @write_type == :file
+ @analytics_data = []
+ end
+ end
+
+ def call(env)
+ case @profile_type
+ when :prof
+ profile(env, mode)
+ when :time
+ start_time = Time.now
+ app_response = @app.call(env)
+ end_time = Time.now
+
+ time_taken = end_time - start_time
+
+ # dup, otherwise we screw up the env hash for rack
+ # also merge with an empty new Hash to create a real Hash and not a Mongrel::HttpParams 'hash'
+ rack_env = Hash.new.merge(env.dup)
+
+ # a mix of IO and Action::* classes that rails can't to_yaml
+ rack_env.delete('rack.errors')
+ rack_env.delete('rack.input')
+ rack_env.delete('action_controller.rescue.request')
+ rack_env.delete('action_controller.rescue.response')
+ rack_env.delete('rack.session')
+
+ if @write_type == :file
+ if should_writeout_data
+ file_write("analysis.current.log", @analytics_data.to_yaml)
+ @analytics_data = []
+ else
+ @analytics_data << {:time_taken => time_taken, :created_at => Time.now.to_i, :rack_env => rack_env}
+ end
+ elsif @write_type == :db
+ ActiveRecord::Base.connection.insert("insert into log_entries (time_taken, details, created_at) values (#{time_taken}, #{ActiveRecord::Base.connection.quote(rack_env)}, #{Time.now.to_i})")
+ end
+ app_response
+ else
+ @app.call(env)
+ end
+ end
+
+ def should_writeout_data
+ @analytics_data.size >= BUFFER_SIZE
+ end
+
+ def profile(env, mode)
+ RubyProf.measure_mode = RubyProf.const_get(mode.upcase)
+
+ rails_response = []
+ result = RubyProf.profile do
+ rails_response = @app.call(env)
+ end
+
+ store_in_filesystem(result, env)
+
+ [200, {'Content-Type' => 'text/html'}, rails_response[2]]
+ end
+
+ def file_write(filename, data)
+ ::File.open(filename, 'a') {|file| file.write data}
+ end
+
+ def store_in_filesystem(result, env)
+ filename = "public/analytics.profile.#{timestamp}.txt"
+ string = StringIO.new
+ RubyProf::FlatPrinter.new(result).print(string, :min_percent => 0.01)
+ string.rewind
+ file_write(filename, string)
+
+ filename = "public/analytics.rack_env.#{timestamp}.txt"
+ file_write(filename, env.to_hash.to_yaml)
+ end
+
+ def timestamp
+ "%10.6f" % Time.now.to_f
+ end
+ end
+end
diff --git a/lib/rack-analytics/analytics.rb b/lib/rack-analytics/analytics.rb
deleted file mode 100644
index 85edffa..0000000
--- a/lib/rack-analytics/analytics.rb
+++ /dev/null
@@ -1,100 +0,0 @@
-require 'ruby-prof'
-require 'ruby-debug'
-
-module Rack
- # Set the profile=process_time query parameter to download a
- # calltree profile of the request.
- #
- # Pass the :printer option to pick a different result format.
- class Analytics
- BUFFER_SIZE = 5
- MODES = %w(
- process_time
- wall_time
- cpu_time
- )
-
- def initialize(app, options = {})
- @app = app
- @profile_type = :time
- @write_type = :file
- if @write_type == :file
- @analytics_data = []
- end
- end
-
- def call(env)
- case @profile_type
- when :prof
- profile(env, mode)
- when :time
- start_time = Time.now
- app_response = @app.call(env)
- end_time = Time.now
-
- time_taken = end_time - start_time
-
- # dup, otherwise we screw up the env hash for rack
- # also merge with an empty new Hash to create a real Hash and not a Mongrel::HttpParams 'hash'
- rack_env = Hash.new.merge(env.dup)
-
- # a mix of IO and Action::* classes that rails can't to_yaml
- rack_env.delete('rack.errors')
- rack_env.delete('rack.input')
- rack_env.delete('action_controller.rescue.request')
- rack_env.delete('action_controller.rescue.response')
- rack_env.delete('rack.session')
-
- if @write_type == :file
- if should_writeout_data
- file_write("analysis.current.log", @analytics_data.to_yaml)
- @analytics_data = []
- else
- @analytics_data << {:time_taken => time_taken, :created_at => Time.now.to_i, :rack_env => rack_env}
- end
- elsif @write_type == :db
- ActiveRecord::Base.connection.insert("insert into log_entries (time_taken, details, created_at) values (#{time_taken}, #{ActiveRecord::Base.connection.quote(rack_env)}, #{Time.now.to_i})")
- end
- app_response
- else
- @app.call(env)
- end
- end
-
- def should_writeout_data
- @analytics_data.size >= BUFFER_SIZE
- end
-
- def profile(env, mode)
- RubyProf.measure_mode = RubyProf.const_get(mode.upcase)
-
- rails_response = []
- result = RubyProf.profile do
- rails_response = @app.call(env)
- end
-
- store_in_filesystem(result, env)
-
- [200, {'Content-Type' => 'text/html'}, rails_response[2]]
- end
-
- def file_write(filename, data)
- ::File.open(filename, 'a') {|file| file.write data}
- end
-
- def store_in_filesystem(result, env)
- filename = "public/analytics.profile.#{timestamp}.txt"
- string = StringIO.new
- RubyProf::FlatPrinter.new(result).print(string, :min_percent => 0.01)
- string.rewind
- file_write(filename, string)
-
- filename = "public/analytics.rack_env.#{timestamp}.txt"
- file_write(filename, env.to_hash.to_yaml)
- end
-
- def timestamp
- "%10.6f" % Time.now.to_f
- end
- end
-end
diff --git a/rack-analytics.gemspec b/rack-analytics.gemspec
index af6f2fb..9f434c7 100644
--- a/rack-analytics.gemspec
+++ b/rack-analytics.gemspec
@@ -1,30 +1,44 @@
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{rack-analytics}
- s.version = "0.0.1"
+ s.version = "0.0.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
- s.authors = ["Anerian LLC"]
- s.autorequire = %q{rack-analytics}
+ s.authors = ["Jack Dempsey"]
s.date = %q{2009-04-22}
- s.description = %q{A gem that provides rack middlware to analyze Rails apps}
- s.email = %q{[email protected]}
- s.extra_rdoc_files = ["README", "LICENSE", "TODO"]
- s.files = ["LICENSE", "README", "Rakefile", "TODO", "lib/rack-analytics.rb", "spec/rack-analytics_spec.rb", "spec/spec_helper.rb"]
+ s.email = %q{[email protected]}
+ s.extra_rdoc_files = [
+ "LICENSE",
+ "README.rdoc"
+ ]
+ s.files = [
+ "LICENSE",
+ "README.rdoc",
+ "Rakefile",
+ "lib/rack-analytics.rb",
+ "lib/rack_analytics.rb",
+ "test/rack_analytics_test.rb",
+ "test/test_helper.rb"
+ ]
s.has_rdoc = true
- s.homepage = %q{http://anerian.com}
+ s.homepage = %q{http://github.com/jackdempsey/rack-analytics}
+ s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.2}
- s.summary = %q{A gem that provides rack middlware to analyze Rails apps}
+ s.summary = %q{A gem that provides rack middleware to capture analytics}
+ s.test_files = [
+ "test/rack_analytics_test.rb",
+ "test/test_helper.rb"
+ ]
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
else
end
else
end
end
diff --git a/script/destroy b/script/destroy
deleted file mode 100755
index 40901a8..0000000
--- a/script/destroy
+++ /dev/null
@@ -1,14 +0,0 @@
-#!/usr/bin/env ruby
-APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
-
-begin
- require 'rubigen'
-rescue LoadError
- require 'rubygems'
- require 'rubigen'
-end
-require 'rubigen/scripts/destroy'
-
-ARGV.shift if ['--help', '-h'].include?(ARGV[0])
-RubiGen::Base.use_component_sources! [:newgem_simple, :test_unit]
-RubiGen::Scripts::Destroy.new.run(ARGV)
diff --git a/script/generate b/script/generate
deleted file mode 100755
index 5c8ed01..0000000
--- a/script/generate
+++ /dev/null
@@ -1,14 +0,0 @@
-#!/usr/bin/env ruby
-APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
-
-begin
- require 'rubigen'
-rescue LoadError
- require 'rubygems'
- require 'rubigen'
-end
-require 'rubigen/scripts/generate'
-
-ARGV.shift if ['--help', '-h'].include?(ARGV[0])
-RubiGen::Base.use_component_sources! [:newgem_simple, :test_unit]
-RubiGen::Scripts::Generate.new.run(ARGV)
diff --git a/spec/rack-analytics_spec.rb b/spec/rack-analytics_spec.rb
deleted file mode 100644
index ff7712b..0000000
--- a/spec/rack-analytics_spec.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-require File.dirname(__FILE__) + '/spec_helper'
-
-describe "rack-analytics" do
- it "should do nothing" do
- true.should == true
- end
-end
\ No newline at end of file
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
deleted file mode 100644
index 8eee1f2..0000000
--- a/spec/spec_helper.rb
+++ /dev/null
@@ -1,2 +0,0 @@
-$TESTING=true
-$:.push File.join(File.dirname(__FILE__), '..', 'lib')
diff --git a/test/rack_analytics_test.rb b/test/rack_analytics_test.rb
new file mode 100644
index 0000000..286feab
--- /dev/null
+++ b/test/rack_analytics_test.rb
@@ -0,0 +1,7 @@
+require 'test_helper'
+
+class RackAnalyticsTest < Test::Unit::TestCase
+ should "probably rename this file and start testing for real" do
+ flunk "hey buddy, you should probably rename this file and start testing for real"
+ end
+end
diff --git a/test/test_helper.rb b/test/test_helper.rb
new file mode 100644
index 0000000..8c53a43
--- /dev/null
+++ b/test/test_helper.rb
@@ -0,0 +1,10 @@
+require 'rubygems'
+require 'test/unit'
+require 'shoulda'
+
+$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
+$LOAD_PATH.unshift(File.dirname(__FILE__))
+require 'rack_analytics'
+
+class Test::Unit::TestCase
+end
|
anerian/rack-analytics
|
64208fc2873596fe7d8aeba0273791ed9b3f7b76
|
add in main lib require file
|
diff --git a/lib/rack-analytics.rb b/lib/rack-analytics.rb
new file mode 100644
index 0000000..f4c01bb
--- /dev/null
+++ b/lib/rack-analytics.rb
@@ -0,0 +1 @@
+require 'rack/analytics'
|
anerian/rack-analytics
|
278ca65229e5119235caa3b77e0f709321736fdf
|
create gemspec
|
diff --git a/rack-analytics.gemspec b/rack-analytics.gemspec
new file mode 100644
index 0000000..af6f2fb
--- /dev/null
+++ b/rack-analytics.gemspec
@@ -0,0 +1,30 @@
+# -*- encoding: utf-8 -*-
+
+Gem::Specification.new do |s|
+ s.name = %q{rack-analytics}
+ s.version = "0.0.1"
+
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
+ s.authors = ["Anerian LLC"]
+ s.autorequire = %q{rack-analytics}
+ s.date = %q{2009-04-22}
+ s.description = %q{A gem that provides rack middlware to analyze Rails apps}
+ s.email = %q{[email protected]}
+ s.extra_rdoc_files = ["README", "LICENSE", "TODO"]
+ s.files = ["LICENSE", "README", "Rakefile", "TODO", "lib/rack-analytics.rb", "spec/rack-analytics_spec.rb", "spec/spec_helper.rb"]
+ s.has_rdoc = true
+ s.homepage = %q{http://anerian.com}
+ s.require_paths = ["lib"]
+ s.rubygems_version = %q{1.3.2}
+ s.summary = %q{A gem that provides rack middlware to analyze Rails apps}
+
+ if s.respond_to? :specification_version then
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
+ s.specification_version = 3
+
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
+ else
+ end
+ else
+ end
+end
|
anerian/rack-analytics
|
2975876080392a5fb8fdd8ac49dc5c2143107bf0
|
adding in gem files
|
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f8bd0f0
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2009 YOUR NAME
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/Rakefile b/Rakefile
new file mode 100644
index 0000000..c62453b
--- /dev/null
+++ b/Rakefile
@@ -0,0 +1,57 @@
+require 'rubygems'
+require 'rake/gempackagetask'
+require 'rubygems/specification'
+require 'date'
+require 'spec/rake/spectask'
+
+GEM = "rack-analytics"
+GEM_VERSION = "0.0.1"
+AUTHOR = "Your Name"
+EMAIL = "Your Email"
+HOMEPAGE = "http://example.com"
+SUMMARY = "A gem that provides..."
+
+spec = Gem::Specification.new do |s|
+ s.name = GEM
+ s.version = GEM_VERSION
+ s.platform = Gem::Platform::RUBY
+ s.has_rdoc = true
+ s.extra_rdoc_files = ["README", "LICENSE", 'TODO']
+ s.summary = SUMMARY
+ s.description = s.summary
+ s.author = AUTHOR
+ s.email = EMAIL
+ s.homepage = HOMEPAGE
+
+ # Uncomment this to add a dependency
+ # s.add_dependency "foo"
+
+ s.require_path = 'lib'
+ s.autorequire = GEM
+ s.files = %w(LICENSE README Rakefile TODO) + Dir.glob("{lib,spec}/**/*")
+end
+
+task :default => :spec
+
+desc "Run specs"
+Spec::Rake::SpecTask.new do |t|
+ t.spec_files = FileList['spec/**/*_spec.rb']
+ t.spec_opts = %w(-fs --color)
+end
+
+
+Rake::GemPackageTask.new(spec) do |pkg|
+ pkg.gem_spec = spec
+end
+
+desc "install the gem locally"
+task :install => [:package] do
+ sh %{sudo gem install pkg/#{GEM}-#{GEM_VERSION}}
+end
+
+desc "create a gemspec file"
+task :make_spec do
+ File.open("#{GEM}.gemspec", "w") do |file|
+ file.puts spec.to_ruby
+ end
+end
\ No newline at end of file
diff --git a/TODO b/TODO
new file mode 100644
index 0000000..321c447
--- /dev/null
+++ b/TODO
@@ -0,0 +1,4 @@
+TODO:
+Fix LICENSE with your name
+Fix Rakefile with your name and contact info
+Add your code to lib/<%= name %>.rb
\ No newline at end of file
diff --git a/lib/rack-analytics.rb b/lib/rack-analytics.rb
new file mode 100644
index 0000000..85edffa
--- /dev/null
+++ b/lib/rack-analytics.rb
@@ -0,0 +1,100 @@
+require 'ruby-prof'
+require 'ruby-debug'
+
+module Rack
+ # Set the profile=process_time query parameter to download a
+ # calltree profile of the request.
+ #
+ # Pass the :printer option to pick a different result format.
+ class Analytics
+ BUFFER_SIZE = 5
+ MODES = %w(
+ process_time
+ wall_time
+ cpu_time
+ )
+
+ def initialize(app, options = {})
+ @app = app
+ @profile_type = :time
+ @write_type = :file
+ if @write_type == :file
+ @analytics_data = []
+ end
+ end
+
+ def call(env)
+ case @profile_type
+ when :prof
+ profile(env, mode)
+ when :time
+ start_time = Time.now
+ app_response = @app.call(env)
+ end_time = Time.now
+
+ time_taken = end_time - start_time
+
+ # dup, otherwise we screw up the env hash for rack
+ # also merge with an empty new Hash to create a real Hash and not a Mongrel::HttpParams 'hash'
+ rack_env = Hash.new.merge(env.dup)
+
+ # a mix of IO and Action::* classes that rails can't to_yaml
+ rack_env.delete('rack.errors')
+ rack_env.delete('rack.input')
+ rack_env.delete('action_controller.rescue.request')
+ rack_env.delete('action_controller.rescue.response')
+ rack_env.delete('rack.session')
+
+ if @write_type == :file
+ if should_writeout_data
+ file_write("analysis.current.log", @analytics_data.to_yaml)
+ @analytics_data = []
+ else
+ @analytics_data << {:time_taken => time_taken, :created_at => Time.now.to_i, :rack_env => rack_env}
+ end
+ elsif @write_type == :db
+ ActiveRecord::Base.connection.insert("insert into log_entries (time_taken, details, created_at) values (#{time_taken}, #{ActiveRecord::Base.connection.quote(rack_env)}, #{Time.now.to_i})")
+ end
+ app_response
+ else
+ @app.call(env)
+ end
+ end
+
+ def should_writeout_data
+ @analytics_data.size >= BUFFER_SIZE
+ end
+
+ def profile(env, mode)
+ RubyProf.measure_mode = RubyProf.const_get(mode.upcase)
+
+ rails_response = []
+ result = RubyProf.profile do
+ rails_response = @app.call(env)
+ end
+
+ store_in_filesystem(result, env)
+
+ [200, {'Content-Type' => 'text/html'}, rails_response[2]]
+ end
+
+ def file_write(filename, data)
+ ::File.open(filename, 'a') {|file| file.write data}
+ end
+
+ def store_in_filesystem(result, env)
+ filename = "public/analytics.profile.#{timestamp}.txt"
+ string = StringIO.new
+ RubyProf::FlatPrinter.new(result).print(string, :min_percent => 0.01)
+ string.rewind
+ file_write(filename, string)
+
+ filename = "public/analytics.rack_env.#{timestamp}.txt"
+ file_write(filename, env.to_hash.to_yaml)
+ end
+
+ def timestamp
+ "%10.6f" % Time.now.to_f
+ end
+ end
+end
diff --git a/script/destroy b/script/destroy
new file mode 100755
index 0000000..40901a8
--- /dev/null
+++ b/script/destroy
@@ -0,0 +1,14 @@
+#!/usr/bin/env ruby
+APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
+
+begin
+ require 'rubigen'
+rescue LoadError
+ require 'rubygems'
+ require 'rubigen'
+end
+require 'rubigen/scripts/destroy'
+
+ARGV.shift if ['--help', '-h'].include?(ARGV[0])
+RubiGen::Base.use_component_sources! [:newgem_simple, :test_unit]
+RubiGen::Scripts::Destroy.new.run(ARGV)
diff --git a/script/generate b/script/generate
new file mode 100755
index 0000000..5c8ed01
--- /dev/null
+++ b/script/generate
@@ -0,0 +1,14 @@
+#!/usr/bin/env ruby
+APP_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
+
+begin
+ require 'rubigen'
+rescue LoadError
+ require 'rubygems'
+ require 'rubigen'
+end
+require 'rubigen/scripts/generate'
+
+ARGV.shift if ['--help', '-h'].include?(ARGV[0])
+RubiGen::Base.use_component_sources! [:newgem_simple, :test_unit]
+RubiGen::Scripts::Generate.new.run(ARGV)
diff --git a/spec/rack-analytics_spec.rb b/spec/rack-analytics_spec.rb
new file mode 100644
index 0000000..ff7712b
--- /dev/null
+++ b/spec/rack-analytics_spec.rb
@@ -0,0 +1,7 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe "rack-analytics" do
+ it "should do nothing" do
+ true.should == true
+ end
+end
\ No newline at end of file
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
new file mode 100644
index 0000000..8eee1f2
--- /dev/null
+++ b/spec/spec_helper.rb
@@ -0,0 +1,2 @@
+$TESTING=true
+$:.push File.join(File.dirname(__FILE__), '..', 'lib')
|
david-guenault/frogx_api
|
4aac4cd7b3cf2cd16f946719637f2be5d927cd50
|
live now handle overall states and partial performances informations. tac class removed
|
diff --git a/api/live.php b/api/live.php
index 77d68eb..58020a9 100644
--- a/api/live.php
+++ b/api/live.php
@@ -1,759 +1,968 @@
<?php
/**
* base class to use live status implementation in shinken and nagios
*
* @package livestatusapi
* @author David GUENAULT ([email protected])
* @copyright (c) 2010 Monitoring-fr Team / Shinken Team (http://monitoring-fr.org / http://www.shinken-monitoring.org)
* @license Afero GPL
* @version 0.1
*/
class live {
/**
*
* this is an array containing the location of each livestatus sites parameters
* @var array $sites List of sites paramaters (see sites.inc.php)
*/
protected $sites = null;
/**
* the socket used to communicate
* @var ressource
*/
protected $socket = null;
/**
* path to the livestatus unix socket
* @var string
*/
protected $socketpath = null;
/**
* host name or ip address of the host that serve livestatus queries
* @var string
*/
protected $host = null;
/**
* TCP port of the remote host that serve livestatus queries
* @var int
*/
protected $port = null;
/**
* the socket buffer read length
* @var int
*/
protected $buffer = 1024;
/**
* the cahracter used to define newlines (livestatus use double newline character end of query definition)
* @var char
*/
protected $newline = "\n";
/**
* this is the version of livestatus it is automaticaly filed by the getLivestatusVersion() method
* @var string
*/
protected $livever = null;
/**
* default headersize (in bytes) returned after a livestatus query (always 16)
* @var int
*/
protected $headersize = 16;
/**
*
* @commands array list all authorized commands
*/
protected $commands = null;
/**
* this define query options that will be added to each query (default options)
* @var array
*/
protected $resultArray = array();
public $defaults = array(
"ColumnHeaders: on",
"ResponseHeader: fixed16",
// "KeepAlive: on",
"OutputFormat: json"
);
/**
* used to make difference between pre 1.1.3 version of livestatus return code and post 1.1.3
* @var array
*/
protected $messages = array(
"versions" => array(
"1.0.19" => "old",
"1.0.20" => "old",
"1.0.21" => "old",
"1.0.22" => "old",
"1.0.23" => "old",
"1.0.24" => "old",
"1.0.25" => "old",
"1.0.26" => "old",
"1.0.27" => "old",
"1.0.28" => "old",
"1.0.29" => "old",
"1.0.30" => "old",
"1.0.31" => "old",
"1.0.32" => "old",
"1.0.33" => "old",
"1.0.34" => "old",
"1.0.35" => "old",
"1.0.36" => "old",
"1.0.37" => "old",
"1.0.38" => "old",
"1.0.39" => "old",
"1.1.0" => "old",
"1.1.1" => "old",
"1.1.2" => "old",
"1.1.3" => "new",
"1.1.4" => "new",
"1.1.5i0" => "new",
"1.1.5i1" => "new",
"1.1.5i2" => "new",
"1.1.5i3" => "new",
"1.1.6b2" => "new",
"1.1.6b3" => "new",
"1.1.6rc1" => "new",
"1.1.6rc2" => "new",
"1.1.6rc3" => "new",
"1.1.6p1" => "new",
"1.1.7i1" => "new",
"1.1.7i2" => "new"
),
"old" => array(
"200"=>"OK. Reponse contains the queried data.",
"401"=>"The request contains an invalid header.",
"402"=>"The request is completely invalid.",
"403"=>"The request is incomplete",
"404"=>"The target of the GET has not been found (e.g. the table).",
"405"=>"A non-existing column was being referred to"
),
"new" => array(
"200"=>"OK. Reponse contains the queried data.",
"400"=>"The request contains an invalid header.",
"403"=>"The user is not authorized (see AuthHeader)",
"404"=>"The target of the GET has not been found (e.g. the table).",
"450"=>"A non-existing column was being referred to",
"451"=>"The request is incomplete.",
"452"=>"The request is completely invalid."
)
);
/**
* json response of the query
* @var string
*/
public $queryresponse = null;
/**
* response code returned after query
* @var int
*/
public $responsecode = null;
/**
* response message returned after query
*/
public $responsemessage = null;
/**
* Class Constructor
* @param array params array of parameters (if socket is in the keys then the connection is UNIX SOCKET else it is TCP SOCKET)
* @param int buffer used to read query response
*/
public function __construct($params=null,$buffer=1024){
// fucking php limitation on declaring multiple constructors !
if(isset($params["socket"])){
$this->socketpath = $params["socket"];
$this->buffer = $buffer;
$this->getLivestatusVersion();
}elseif(isset($params["host"]) && isset($params["port"]) ){
$this->host = $params["host"];
$this->port = $params["port"];
$this->buffer = $buffer;
$this->getLivestatusVersion();
}elseif(isset($params["multisite"])){
// multi site rule !
array_shift($params);
$this->sites = $params;
$this->buffer = $buffer;
}else{
return false;
}
return true;
}
/**
* Class destructor
*/
public function __destruct() {
$this->disconnect();
$this->queryresponse = null;
}
/**
*
* Execute a multisite query
* @param $query the query to be executed
*/
public function execQueryMultisite($query){
// response array
$responses=array();
// reset connection data
$this->resetConnection();
//iterate through each site and execute the query
foreach (array_keys($this->sites) as $site){
// set connection data
$params = $this->sites[$site];
if(isset($params["socket"])){
$this->socketpath = $params["socket"];
$this->getLivestatusVersion();
}elseif(isset($params["host"]) && isset($params["port"]) ){
$this->host = $params["host"];
$this->port = $params["port"];
$this->getLivestatusVersion();
}
// execute query for current site;
$response = json_decode($this->execQuery($query));
// record result
if($response){
$this->agregateResult($response,$site);
}
$response = "";
$this->resetConnection();
}
return json_encode($this->resultArray);
}
/**
* This method get the overall status of all services and hosts. if $sites is an array of sites names it will only retrieve the tac for the specified sites.
* @param array sites an array off all of the monitoring hosts (see conf/sites.inc.php) if null get tac for all sites
* @return string the json encoded tac values
*/
public function getOverallStates($sites=null){
// TODO : introduce a possibility to get TAC for a filtered list .....
if(!is_null($sites)){
$this->sites = $sites;
}
// get overall services states
$queryservices = array(
"GET services",
"Filter: last_check > 0", // not pending ?
"Stats: last_hard_state = 0",
"Stats: last_hard_state = 1",
"Stats: last_hard_state = 2",
"Stats: last_hard_state = 3",
);
+ // pending services
$querypendingservices = array(
"GET services",
"Stats: last_check = 0",
);
// get overall hosts states
$queryhosts = array(
"GET hosts",
"Filter: last_check > 0", // not pending ?
"Stats: last_hard_state = 0",
"Stats: last_hard_state = 1",
"Stats: last_hard_state = 2"
);
+ // pending services
$querypendinghosts = array(
"GET hosts",
"Stats: last_check = 0",
);
$failedservices = array();
$failedhosts = array();
$hosts=array(
"UP"=>0,
"DOWN"=>0,
"UNREACHABLE"=>0,
"ALL PROBLEMS"=>0,
"ALL TYPES"=>0,
"PENDING"=>0
);
$services=array(
"OK"=>0,
"WARNING"=>0,
"CRITICAL"=>0,
"UNKNOWN"=>0,
"ALL PROBLEMS"=>0,
"ALL TYPES"=>0,
"PENDING"=>0
);
foreach($this->sites as $site){
switch ($site["type"]){
case "UNIX":
$this->socketpath = $site["socket"];
$this->host=null;
$this->port=null;
$this->getLivestatusVersion();
break;
case "TCP":
$this->socketpath = null;
$this->host=$site["host"];
$this->port=$site["port"];
$this->getLivestatusVersion();
break;
default:
return false;
}
if($this->socket) { $this->resetConnection();}
if($this->connect()){
$result=$this->execQuery($queryservices);
if($result == false){
// one ore more sites failed to execute the query
// we keep a trace
$failedservices[]=array("site"=>$site,"code"=>$this->responsecode,"message"=>$this->responsemessage);
return false;
}else{
$states=json_decode($this->queryresponse);
// query pending services
$result = $this->execQuery($querypendingservices);
$pending = json_decode($this->queryresponse);
// PENDING
$services["PENDING"] += $pending[0][0];
// OK
$services["OK"] += $states[0][0];
// WARNING
$services["WARNING"] += $states[0][1];
// CRITICAL
$services["CRITICAL"] += $states[0][2];
// UNKNOWN
$services["UNKNOWN"] += $states[0][3];
// ALL TYPES
$services["ALL TYPES"] += $services["OK"]+$services["WARNING"]+$services["CRITICAL"]+$services["UNKNOWN"]+$services["PENDING"];
// ALL PROBLEMS
$services["ALL PROBLEMS"] += $services["WARNING"]+$services["CRITICAL"]+$services["UNKNOWN"];
}
$result=$this->execQuery($queryhosts);
if(!$result){
// one ore more sites failed to execute the query
// we keep a trace
$failedhosts[]=array("site"=>$site,"code"=>$this->responsecode,"message"=>$this->responsemessage);
}else{
$states=json_decode($this->queryresponse);
// query pending hosts
$result = $this->execQuery($querypendinghosts);
$pending = json_decode($this->queryresponse);
// PENDING
$hosts["PENDING"] += $pending[0][0];
// UP
$hosts["UP"] += $states[0][0];
// DOWN
$hosts["DOWN"] += $states[0][1];
// UNREACHABLE
$hosts["UNREACHABLE"] += $states[0][2];
// ALL TYPES
$hosts["ALL TYPES"] = $hosts["UP"]+$hosts["DOWN"]+$hosts["UNREACHABLE"]+$hosts["PENDING"];
// ALL PROBLEMS
$hosts["ALL PROBLEMS"] = $hosts["DOWN"]+$hosts["UNREACHABLE"];
}
}else{
// one ore more sites failed to connect
// we keep a trace
$failedhosts[]=array("site"=>$site,"code"=>$this->responsecode,"message"=>$this->responsemessage);
}
}
return json_encode(array(
"hosts"=>(array)$hosts,
"services"=>(array)$services
));
}
/**
*
* Enter description here ...
*/
- public function getPerformances($sites){
+ public function getPerformances($sites=null){
+ if(!is_null($sites)){
+ $this->sites = $sites;
+ }
+
+ $ts = strtotime("now");
+ $ts1min = strtotime("-1 minute");
+ $ts5min = strtotime("-5 minute");
+ $ts15min = strtotime("-15 minute");
+ $ts1hour = strtotime("-1 hour");
+ // get active services stats
+ $queryactiveservicestats = array(
+ "GET services",
+ "Stats: min latency",
+ "Stats: max latency",
+ "Stats: avg latency",
+ "Stats: min execution_time",
+ "Stats: max execution_time",
+ "Stats: avg execution_time",
+ "Stats: min percent_state_change",
+ "Stats: max percent_state_change",
+ "Stats: avg percent_state_change",
+ "Stats: last_check >= ".$ts1min,
+ "Stats: last_check >= ".$ts5min,
+ "Stats: last_check >= ".$ts15min,
+ "Stats: last_check >= ".$ts1hour,
+ "Stats: last_check > 0",
+ "Filter: has_been_checked = 1",
+ "Filter: check_type = 0"
+ );
+
+ // get passive services stats
+ $querypassiveservicestats = array(
+ "GET services",
+ "Stats: min percent_state_change",
+ "Stats: max percent_state_change",
+ "Stats: avg percent_state_change",
+ "Stats: last_check >= ".$ts1min,
+ "Stats: last_check >= ".$ts5min,
+ "Stats: last_check >= ".$ts15min,
+ "Stats: last_check >= ".$ts1hour,
+ "Stats: last_check > 0",
+ "Filter: has_been_checked = 1",
+ "Filter: check_type = 1"
+ );
+
+ $queryactivehoststats = array(
+ "GET hosts",
+ "Stats: min latency",
+ "Stats: max latency",
+ "Stats: avg latency",
+ "Stats: min execution_time",
+ "Stats: max execution_time",
+ "Stats: avg execution_time",
+ "Stats: min percent_state_change",
+ "Stats: max percent_state_change",
+ "Stats: avg percent_state_change",
+ "Stats: last_check >= ".$ts1min,
+ "Stats: last_check >= ".$ts5min,
+ "Stats: last_check >= ".$ts15min,
+ "Stats: last_check >= ".$ts1hour,
+ "Stats: last_check > 0",
+ "Filter: has_been_checked = 1",
+ "Filter: check_type = 0"
+ );
+
+ // get passive hosts stats
+ $querypassivehoststats = array(
+ "GET hosts",
+ "Stats: min percent_state_change",
+ "Stats: max percent_state_change",
+ "Stats: avg percent_state_change",
+ "Stats: last_check >= ".$ts1min,
+ "Stats: last_check >= ".$ts5min,
+ "Stats: last_check >= ".$ts15min,
+ "Stats: last_check >= ".$ts1hour,
+ "Stats: last_check > 0",
+ "Filter: has_been_checked = 1",
+ "Filter: check_type = 1"
+ );
+
+ foreach(array_keys($this->sites) as $key){
+ $site = $this->sites[$key];
+ switch ($site["type"]){
+ case "UNIX":
+ $this->socketpath = $site["socket"];
+ $this->host=null;
+ $this->port=null;
+ $this->getLivestatusVersion();
+ break;
+ case "TCP":
+ $this->socketpath = null;
+ $this->host=$site["host"];
+ $this->port=$site["port"];
+ $this->getLivestatusVersion();
+ break;
+ default:
+ return false;
+ }
+ if($this->socket) { $this->resetConnection();}
+ if($this->connect()){
+
+ $this->execQuery($queryactiveservicestats );
+ $activeservicesstats = json_decode($this->queryresponse);
+ $activeservicesstats = $activeservicesstats[0];
+
+ $this->execQuery($querypassiveservicestats );
+ $passiveservicesstats = json_decode($this->queryresponse);
+ $passiveservicesstats = $passiveservicesstats[0];
+
+ $this->execQuery($queryactivehoststats );
+ $activehostsstats = json_decode($this->queryresponse);
+ $activehostsstats = $activehostsstats[0];
+
+ $this->execQuery($querypassivehoststats );
+ $passivehostsstats = json_decode($this->queryresponse);
+ $passivehostsstats = $passivehostsstats[0];
+
+ $performances[]=array(
+ "site"=>$key,
+ "services"=>array(
+ "active"=>array(
+ "execStats"=>array(
+ "lte1min"=>$activeservicesstats[9],
+ "lte5min"=>$activeservicesstats[10],
+ "lte15min"=>$activeservicesstats[11],
+ "lte1hour"=>$activeservicesstats[12],
+ "sinceStart"=>$activeservicesstats[13],
+
+ ),
+ "latency"=>array(
+ "min"=>$activeservicesstats[0],
+ "max"=>$activeservicesstats[1],
+ "average"=>$activeservicesstats[2]
+ ),
+ "executiontime"=>array(
+ "min"=>$activeservicesstats[3],
+ "max"=>$activeservicesstats[4],
+ "average"=>$activeservicesstats[5]
+ ),
+ "percentstatechange"=>array(
+ "min"=>$activeservicesstats[6],
+ "max"=>$activeservicesstats[7],
+ "average"=>$activeservicesstats[8]
+ )
+ ),
+ "passive"=>array(
+ "execStats"=>array(
+ "lte1min"=>$passiveservicesstats[3],
+ "lte5min"=>$passiveservicesstats[4],
+ "lte15min"=>$passiveservicesstats[5],
+ "lte1hour"=>$passiveservicesstats[6],
+ "sinceStart"=>$passiveservicesstats[7]
+ ),
+ "percentstatechange"=>array(
+ "min"=>$passiveservicesstats[0],
+ "max"=>$passiveservicesstats[1],
+ "average"=>$passiveservicesstats[2]
+ )
+ )
+ ),
+ "hosts"=>array(
+ "active"=>array(
+ "execStats"=>array(
+ "lte1min"=>$activehostsstats[9],
+ "lte5min"=>$activehostsstats[10],
+ "lte15min"=>$activehostsstats[11],
+ "lte1hour"=>$activehostsstats[12],
+ "sinceStart"=>$activehostsstats[13],
+
+ ),
+ "latency"=>array(
+ "min"=>$activehostsstats[0],
+ "max"=>$activehostsstats[1],
+ "average"=>$activehostsstats[2]
+ ),
+ "executiontime"=>array(
+ "min"=>$activehostsstats[3],
+ "max"=>$activehostsstats[4],
+ "average"=>$activehostsstats[5]
+ ),
+ "percentstatechange"=>array(
+ "min"=>$activehostsstats[6],
+ "max"=>$activehostsstats[7],
+ "average"=>$activehostsstats[8]
+ )
+ ),
+ "passive"=>array(
+ "execStats"=>array(
+ "lte1min"=>$passivehostsstats[3],
+ "lte5min"=>$passivehostsstats[4],
+ "lte15min"=>$passivehostsstats[5],
+ "lte1hour"=>$passivehostsstats[6],
+ "sinceStart"=>$passivehostsstats[7]
+ ),
+ "percentstatechange"=>array(
+ "min"=>$passivehostsstats[0],
+ "max"=>$passivehostsstats[1],
+ "average"=>$passivehostsstats[2]
+ )
+ )
+ )
+ );
+
+
+ }
+ }
+ return json_encode($performances);
}
public function getHealth($sites){
}
public function getFeatures($sites){
}
/**
*
* Enter description here ...
* @param unknown_type $source
* @param unknown_type $site
*/
private function agregateresult($source,$site){
$headers = array_shift($source);
$headers[]="site";
foreach($source as $row){
array_push($row,$site);
$this->resultArray[] = array_combine($headers,$row);
}
}
/**
*
* specific to multisite query (see execQueryMultisite)
*/
private function resetConnection(){
$this->socketpath = null;
$this->host = null;
$this->port = null;
if($this->socket){
$this->disconnect();
}
return true;
}
/**
* execute a livestatus query and return result as json
* @param array $query elements of the querry (ex: array("GET services","Filter: state = 1","Filter: state = 2", "Or: 2"))
* @return string the json encoded result of the query
*/
private function execQuery($query){
if($this->socket){
$this->disconnect();
}
if(!$this->connect()){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
return false;
}else{
if(!$this->query($query)){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
$this->disconnect();
return false;
}else{
if(!$this->readresponse()){
$this->disconnect();
return false;
}else{
$this->disconnect();
return $this->queryresponse;
}
}
}
}
/**
* This method submit an external command to nagios through livestatus socket.
* @param array $command an array describing the command array("COMMANDNAME",array("paramname"=>"value","paramname"=>"value",...)
* @return bool true if success false il failed
*/
public function sendExternalCommand($command){
if(!$this->parseCommand($command)){
return false;
}else{
if(!$this->submitExternalCommand($command)){
return false;
}else{
return true;
}
}
}
/**
* load commands defined in commands.inc.php
*/
public function getCommands($commands){
$this->commands = $commands;
}
/**
* PRIVATE METHODS
*/
/**
* Abstract method that choose wich connection method we should use.....
*/
protected function connect(){
if(is_null($this->socketpath)){
return $this->connectTCP();
}else{
return $this->connectUNIX();
}
}
/**
* connect to livestatus through TCP.
* @return bool true if success false if fail
*/
private function connectTCP(){
$this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if( $this->socket == false){
$this->socket = false;
return false;
}
$result = @socket_connect($this->socket, $this->host,$this->port);
if ($result == false){
$this->socket = null;
return false;
}
return true;
}
private function connectUNIX(){
$this->socket = @socket_create(AF_UNIX, SOCK_STREAM, SOL_SOCKET);
if( $this->socket == false){
$this->socket = false;
return false;
}
$result = @socket_connect($this->socket, $this->socketpath);
if ($result == false){
$this->socket = null;
return false;
}
return true;
}
private function connectSSH(){
die("Not implemented");
}
/**
*
* Enter description here ...
*/
private function disconnect(){
if ( ! is_null($this->socket)){
// disconnect gracefully
socket_shutdown($this->socket,2);
socket_close($this->socket);
$this->socket = null;
return true;
}else{
return false;
}
}
/**
* get livestatus version and put it in livever class property
*/
protected function getLivestatusVersion(){
$query = array(
"GET status",
"Columns: livestatus_version",
);
$this->execQuery($query);
$result = json_decode($this->queryresponse);
$this->livever = $result[1][0];
$this->responsecode=null;
$this->responsemessage=null;
$this->queryresponse=null;
}
/**
*
* Enter description here ...
* @param unknown_type $elements
* @param unknown_type $default
*/
private function query($elements,$default="json") {
$query = $this->preparequery($elements,$default);
foreach($query as $element){
if(($this->socketwrite($element.$this->newline)) == false){
return false;
}
}
// finalize query
if(($this->socketwrite($this->newline)) == false){
return false;
}
return true;
}
/**
*
* Enter description here ...
*/
private function readresponse(){
$this->queryresponse="";
if ( ! is_null( $this->socket ) ){
$headers = $this->getHeaders();
$code = $headers["statuscode"];
$size = $headers["contentlength"];
$this->responsecode = $code;
$this->responsemessage = $this->code2message($code);
if($code != "200"){
return false;
}
$this->queryresponse = $this->socketread($size);
return true;
}else{
return false;
}
}
/**
*
* Enter description here ...
* @param unknown_type $code
*/
private function code2message($code){
if ( ! isset($this->messages["versions"][$this->livever])){
// assume new
$type = "new";
}else{
$type = $this->messages["versions"][$this->livever];
}
$message = $this->messages[$type][$code];
return $message;
}
/**
*
* Enter description here ...
* @param unknown_type $size
*/
private function socketread($size){
if ( ! is_null( $this->socket ) ){
$buffer = $this->buffer;
$socketData = "";
if($size <= $buffer){
$socketData = @socket_read($this->socket,$size);
}else{
while($read = @socket_read($this->socket, $buffer)){
$socketData .= $read;
}
}
return $socketData;
}else{
return false;
}
}
/**
*
* Enter description here ...
* @param unknown_type $data
*/
private function socketwrite($data){
if ( ! is_null( $this->socket ) ){
if (socket_write($this->socket, $data) === false){
return false;
}else{
return true;
}
}else{
return false;
}
return true;
}
/**
*
* Enter description here ...
*/
public function getSocketError(){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
return $errormsg;
}
private function getHeaders(){
if ( ! is_null( $this->socket ) ){
$rawHeaders = @socket_read($this->socket, $this->headersize);
return array(
"statuscode" => substr($rawHeaders, 0, 3),
"contentlength" => intval(trim(substr($rawHeaders, 4, 11)))
);
}else{
return false;
}
}
private function preparequery($elements){
$query=$this->defaults;
return array_merge((array)$elements,(array)$query);
}
/**
* This function submit an external command to the livestatus enabled host
* @param array $command an array defining the command array("commandname",array("argname"=>"value","argname"=>"value",...))
* @return bool true if success, false if failed
*/
private function submitExternalCommand($command){
$arguments = "";
foreach(array_keys($command[1]) as $key){
$arguments .= $command[1][$key].";";
}
$arguments = substr($arguments, 0, strlen($arguments)-1);
$commandline = "COMMAND [".time()."] ".$command[0].";".$arguments;
if($this->socket){
$this->disconnect();
}
if(!$this->connect()){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
return false;
}else{
if(!$this->query($commandline)){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
$this->disconnect();
return false;
}else{
$this->responsecode = null;
$this->responsemessage = null;
return true;
}
}
}
/**
* This function is used to parse and validate commands before submit them.
* @param array $command an array defining the command array("commandname",array("argname"=>"value","argname"=>"value",...))
* @return bool true id ok false if not. the raison is stored in responsecode and response message class properties.
*/
private function parseCommand($command){
// check if there is 2 elements in the array
if(count($command) != 2){
$this->responsecode = "602";
$this->responsemessage = "Invalid message definition (wrong number of entries in \$command)";
}else{
// check if first element exist as a key in commands definition
if(!array_key_exists($command[0], $this->commands)){
$this->responsecode = "602";
$this->responsemessage = "Invalid message definition (command ".$command[0]." not found)";
}else{
// check number of arguments against command definition
if(count($this->commands[$command[0]]) != count($command[1])){
$this->responsecode = "602";
$this->responsemessage = "Invalid number of arguments (required : ".count($this->commands[$command[0]]).", provided : ".count($command[1]).")";
}else{
// check argument's names
$defined_keys = $this->commands[$command[0]];
$provided_keys = array_keys($command[1]);
$diff_keys = array_diff($defined_keys, $provided_keys);
if ( count($diff_keys) > 0 ){
$this->responsecode = "602";
$this->responsemessage = "The arguments provided doesn't match the required arguments (".implode(", ", $diff_keys).")";
}else{
$this->responsecode = null;
$this->responsemessage = null;
return true;
}
}
}
}
return false;
}
}
diff --git a/examples/livestatus-tac.php b/examples/livestatus-tac.php
index a91a257..a4df553 100644
--- a/examples/livestatus-tac.php
+++ b/examples/livestatus-tac.php
@@ -1,13 +1,14 @@
<?php
/**
* get overall hosts and services states (as known as tactical overview)
* this introduce the concept of multisite. Each site is an entry in the array config["sites"]
*/
require_once("/var/www/frogx/conf/sites.inc.php");
require_once("/var/www/frogx/api/live.php");
-require_once("/var/www/frogx/api/tac.php");
-
-$tac = new tac();
-print($tac->getOverallStates($config["sites"]));
+$tac = new live($config["sites"],1024);
+// get global states
+print_r(json_decode($tac->getOverallStates()));
+// get performances
+print_r(json_decode($tac->getPerformances()));
?>
|
david-guenault/frogx_api
|
fe9bb416b741cc5ff36f952cfc2b974b30c409aa
|
Added function getOverallStates allowing to get a summary of states for host and services
|
diff --git a/api/live.php b/api/live.php
index 37a6aae..77d68eb 100644
--- a/api/live.php
+++ b/api/live.php
@@ -1,498 +1,759 @@
<?php
/**
* base class to use live status implementation in shinken and nagios
*
* @package livestatusapi
* @author David GUENAULT ([email protected])
* @copyright (c) 2010 Monitoring-fr Team / Shinken Team (http://monitoring-fr.org / http://www.shinken-monitoring.org)
* @license Afero GPL
* @version 0.1
*/
class live {
- /**
- * the socket used to communicate
- * @var ressource
- */
- protected $socket = null;
- /**
- * path to the livestatus unix socket
- * @var string
- */
- protected $socketpath = null;
- /**
- * host name or ip address of the host that serve livestatus queries
- * @var string
- */
- protected $host = null;
- /**
- * TCP port of the remote host that serve livestatus queries
- * @var int
- */
- protected $port = null;
- /**
- * the socket buffer read length
- * @var int
- */
- protected $buffer = 1024;
- /**
- * the cahracter used to define newlines (livestatus use double newline character end of query definition)
- * @var char
- */
- protected $newline = "\n";
- /**
- * this is the version of livestatus it is automaticaly filed by the getLivestatusVersion() method
- * @var string
- */
- protected $livever = null;
- /**
- * default headersize (in bytes) returned after a livestatus query (always 16)
- * @var int
- */
- protected $headersize = 16;
- /**
- *
- * @commands array list all authorized commands
- */
- protected $commands = null;
- /**
- * this define query options that will be added to each query (default options)
- * @var array
- */
- public $defaults = array(
- "ColumnHeaders: on",
- "ResponseHeader: fixed16",
- // "KeepAlive: on",
- "OutputFormat: json"
- );
- /**
- * used to make difference between pre 1.1.3 version of livestatus return code and post 1.1.3
- * @var array
- */
- protected $messages = array(
- "versions" => array(
- "1.0.19" => "old",
- "1.0.20" => "old",
- "1.0.21" => "old",
- "1.0.22" => "old",
- "1.0.23" => "old",
- "1.0.24" => "old",
- "1.0.25" => "old",
- "1.0.26" => "old",
- "1.0.27" => "old",
- "1.0.28" => "old",
- "1.0.29" => "old",
- "1.0.30" => "old",
- "1.0.31" => "old",
- "1.0.32" => "old",
- "1.0.33" => "old",
- "1.0.34" => "old",
- "1.0.35" => "old",
- "1.0.36" => "old",
- "1.0.37" => "old",
- "1.0.38" => "old",
- "1.0.39" => "old",
- "1.1.0" => "old",
- "1.1.1" => "old",
- "1.1.2" => "old",
- "1.1.3" => "new",
- "1.1.4" => "new",
- "1.1.5i0" => "new",
- "1.1.5i1" => "new",
- "1.1.5i2" => "new",
- "1.1.5i3" => "new",
- "1.1.6b2" => "new",
- "1.1.6b3" => "new",
- "1.1.6rc1" => "new",
- "1.1.6rc2" => "new",
- "1.1.6rc3" => "new",
- "1.1.6p1" => "new",
- "1.1.7i1" => "new",
- "1.1.7i2" => "new"
- ),
- "old" => array(
- "200"=>"OK. Reponse contains the queried data.",
- "401"=>"The request contains an invalid header.",
- "402"=>"The request is completely invalid.",
- "403"=>"The request is incomplete",
- "404"=>"The target of the GET has not been found (e.g. the table).",
- "405"=>"A non-existing column was being referred to"
- ),
- "new" => array(
- "200"=>"OK. Reponse contains the queried data.",
- "400"=>"The request contains an invalid header.",
- "403"=>"The user is not authorized (see AuthHeader)",
- "404"=>"The target of the GET has not been found (e.g. the table).",
- "450"=>"A non-existing column was being referred to",
- "451"=>"The request is incomplete.",
- "452"=>"The request is completely invalid."
- )
- );
+ /**
+ *
+ * this is an array containing the location of each livestatus sites parameters
+ * @var array $sites List of sites paramaters (see sites.inc.php)
+ */
+ protected $sites = null;
+ /**
+ * the socket used to communicate
+ * @var ressource
+ */
+ protected $socket = null;
+ /**
+ * path to the livestatus unix socket
+ * @var string
+ */
+ protected $socketpath = null;
+ /**
+ * host name or ip address of the host that serve livestatus queries
+ * @var string
+ */
+ protected $host = null;
+ /**
+ * TCP port of the remote host that serve livestatus queries
+ * @var int
+ */
+ protected $port = null;
+ /**
+ * the socket buffer read length
+ * @var int
+ */
+ protected $buffer = 1024;
+ /**
+ * the cahracter used to define newlines (livestatus use double newline character end of query definition)
+ * @var char
+ */
+ protected $newline = "\n";
+ /**
+ * this is the version of livestatus it is automaticaly filed by the getLivestatusVersion() method
+ * @var string
+ */
+ protected $livever = null;
+ /**
+ * default headersize (in bytes) returned after a livestatus query (always 16)
+ * @var int
+ */
+ protected $headersize = 16;
+ /**
+ *
+ * @commands array list all authorized commands
+ */
+ protected $commands = null;
+ /**
+ * this define query options that will be added to each query (default options)
+ * @var array
+ */
+
+ protected $resultArray = array();
+
+ public $defaults = array(
+ "ColumnHeaders: on",
+ "ResponseHeader: fixed16",
+ // "KeepAlive: on",
+ "OutputFormat: json"
+ );
+ /**
+ * used to make difference between pre 1.1.3 version of livestatus return code and post 1.1.3
+ * @var array
+ */
+ protected $messages = array(
+ "versions" => array(
+ "1.0.19" => "old",
+ "1.0.20" => "old",
+ "1.0.21" => "old",
+ "1.0.22" => "old",
+ "1.0.23" => "old",
+ "1.0.24" => "old",
+ "1.0.25" => "old",
+ "1.0.26" => "old",
+ "1.0.27" => "old",
+ "1.0.28" => "old",
+ "1.0.29" => "old",
+ "1.0.30" => "old",
+ "1.0.31" => "old",
+ "1.0.32" => "old",
+ "1.0.33" => "old",
+ "1.0.34" => "old",
+ "1.0.35" => "old",
+ "1.0.36" => "old",
+ "1.0.37" => "old",
+ "1.0.38" => "old",
+ "1.0.39" => "old",
+ "1.1.0" => "old",
+ "1.1.1" => "old",
+ "1.1.2" => "old",
+ "1.1.3" => "new",
+ "1.1.4" => "new",
+ "1.1.5i0" => "new",
+ "1.1.5i1" => "new",
+ "1.1.5i2" => "new",
+ "1.1.5i3" => "new",
+ "1.1.6b2" => "new",
+ "1.1.6b3" => "new",
+ "1.1.6rc1" => "new",
+ "1.1.6rc2" => "new",
+ "1.1.6rc3" => "new",
+ "1.1.6p1" => "new",
+ "1.1.7i1" => "new",
+ "1.1.7i2" => "new"
+ ),
+ "old" => array(
+ "200"=>"OK. Reponse contains the queried data.",
+ "401"=>"The request contains an invalid header.",
+ "402"=>"The request is completely invalid.",
+ "403"=>"The request is incomplete",
+ "404"=>"The target of the GET has not been found (e.g. the table).",
+ "405"=>"A non-existing column was being referred to"
+ ),
+ "new" => array(
+ "200"=>"OK. Reponse contains the queried data.",
+ "400"=>"The request contains an invalid header.",
+ "403"=>"The user is not authorized (see AuthHeader)",
+ "404"=>"The target of the GET has not been found (e.g. the table).",
+ "450"=>"A non-existing column was being referred to",
+ "451"=>"The request is incomplete.",
+ "452"=>"The request is completely invalid."
+ )
+ );
+ /**
+ * json response of the query
+ * @var string
+ */
+ public $queryresponse = null;
+
+ /**
+ * response code returned after query
+ * @var int
+ */
+ public $responsecode = null;
+
+ /**
+ * response message returned after query
+ */
+ public $responsemessage = null;
- /**
- * json response of the query
- * @var string
- */
- public $queryresponse = null;
- /**
- * response code returned after query
- * @var int
- */
- public $responsecode = null;
- /**
- * response message returned after query
- */
- public $responsemessage = null;
+ /**
+ * Class Constructor
+ * @param array params array of parameters (if socket is in the keys then the connection is UNIX SOCKET else it is TCP SOCKET)
+ * @param int buffer used to read query response
+ */
+ public function __construct($params=null,$buffer=1024){
+ // fucking php limitation on declaring multiple constructors !
+ if(isset($params["socket"])){
+ $this->socketpath = $params["socket"];
+ $this->buffer = $buffer;
+ $this->getLivestatusVersion();
+ }elseif(isset($params["host"]) && isset($params["port"]) ){
+ $this->host = $params["host"];
+ $this->port = $params["port"];
+ $this->buffer = $buffer;
+ $this->getLivestatusVersion();
+ }elseif(isset($params["multisite"])){
+ // multi site rule !
+ array_shift($params);
+ $this->sites = $params;
+ $this->buffer = $buffer;
+ }else{
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Class destructor
+ */
+ public function __destruct() {
+ $this->disconnect();
+ $this->queryresponse = null;
+ }
- /**
- * Class Constructor
- * @param array params array of parameters (if socket is in the keys then the connection is UNIX SOCKET else it is TCP SOCKET)
- * @param int buffer used to read query response
- */
- public function __construct($params,$buffer=1024){
- // fucking php limitation on declaring multiple constructors !
- if(isset($params["socket"])){
- $this->socketpath = $params["socket"];
- $this->buffer = $buffer;
- $this->getLivestatusVersion();
- }elseif(isset($params["host"]) && isset($params["port"]) ){
- $this->host = $params["host"];
- $this->port = $params["port"];
- $this->buffer = $buffer;
- $this->getLivestatusVersion();
- }else{
- return false;
- }
-
+ /**
+ *
+ * Execute a multisite query
+ * @param $query the query to be executed
+ */
+ public function execQueryMultisite($query){
+ // response array
+ $responses=array();
+ // reset connection data
+ $this->resetConnection();
+ //iterate through each site and execute the query
+ foreach (array_keys($this->sites) as $site){
+ // set connection data
+ $params = $this->sites[$site];
+ if(isset($params["socket"])){
+ $this->socketpath = $params["socket"];
+ $this->getLivestatusVersion();
+ }elseif(isset($params["host"]) && isset($params["port"]) ){
+ $this->host = $params["host"];
+ $this->port = $params["port"];
+ $this->getLivestatusVersion();
}
-
- /**
- * wrapper constructor method
- * Enter description here ...
- * @param $params
- * @param $buffer
- */
- protected function constructLive($params,$buffer=1024){
- $this->__construct($params,$buffer);
+ // execute query for current site;
+ $response = json_decode($this->execQuery($query));
+ // record result
+ if($response){
+ $this->agregateResult($response,$site);
}
-
- /**
- * Class destructor
- */
- public function __destruct() {
- $this->disconnect();
- $this->queryresponse = null;
+ $response = "";
+ $this->resetConnection();
+ }
+ return json_encode($this->resultArray);
+ }
+
+ /**
+ * This method get the overall status of all services and hosts. if $sites is an array of sites names it will only retrieve the tac for the specified sites.
+ * @param array sites an array off all of the monitoring hosts (see conf/sites.inc.php) if null get tac for all sites
+ * @return string the json encoded tac values
+ */
+ public function getOverallStates($sites=null){
+ // TODO : introduce a possibility to get TAC for a filtered list .....
+
+ if(!is_null($sites)){
+ $this->sites = $sites;
+ }
+
+ // get overall services states
+ $queryservices = array(
+ "GET services",
+ "Filter: last_check > 0", // not pending ?
+ "Stats: last_hard_state = 0",
+ "Stats: last_hard_state = 1",
+ "Stats: last_hard_state = 2",
+ "Stats: last_hard_state = 3",
+ );
+
+ $querypendingservices = array(
+ "GET services",
+ "Stats: last_check = 0",
+ );
+
+ // get overall hosts states
+ $queryhosts = array(
+ "GET hosts",
+ "Filter: last_check > 0", // not pending ?
+ "Stats: last_hard_state = 0",
+ "Stats: last_hard_state = 1",
+ "Stats: last_hard_state = 2"
+ );
+
+ $querypendinghosts = array(
+ "GET hosts",
+ "Stats: last_check = 0",
+ );
+
+ $failedservices = array();
+ $failedhosts = array();
+
+ $hosts=array(
+ "UP"=>0,
+ "DOWN"=>0,
+ "UNREACHABLE"=>0,
+ "ALL PROBLEMS"=>0,
+ "ALL TYPES"=>0,
+ "PENDING"=>0
+ );
+
+ $services=array(
+ "OK"=>0,
+ "WARNING"=>0,
+ "CRITICAL"=>0,
+ "UNKNOWN"=>0,
+ "ALL PROBLEMS"=>0,
+ "ALL TYPES"=>0,
+ "PENDING"=>0
+ );
+
+ foreach($this->sites as $site){
+ switch ($site["type"]){
+ case "UNIX":
+ $this->socketpath = $site["socket"];
+ $this->host=null;
+ $this->port=null;
+ $this->getLivestatusVersion();
+ break;
+ case "TCP":
+ $this->socketpath = null;
+ $this->host=$site["host"];
+ $this->port=$site["port"];
+ $this->getLivestatusVersion();
+ break;
+ default:
+ return false;
+ }
+ if($this->socket) { $this->resetConnection();}
+ if($this->connect()){
+ $result=$this->execQuery($queryservices);
+ if($result == false){
+ // one ore more sites failed to execute the query
+ // we keep a trace
+ $failedservices[]=array("site"=>$site,"code"=>$this->responsecode,"message"=>$this->responsemessage);
+ return false;
+ }else{
+ $states=json_decode($this->queryresponse);
+
+ // query pending services
+ $result = $this->execQuery($querypendingservices);
+ $pending = json_decode($this->queryresponse);
+
+ // PENDING
+ $services["PENDING"] += $pending[0][0];
+ // OK
+ $services["OK"] += $states[0][0];
+ // WARNING
+ $services["WARNING"] += $states[0][1];
+ // CRITICAL
+ $services["CRITICAL"] += $states[0][2];
+ // UNKNOWN
+ $services["UNKNOWN"] += $states[0][3];
+ // ALL TYPES
+ $services["ALL TYPES"] += $services["OK"]+$services["WARNING"]+$services["CRITICAL"]+$services["UNKNOWN"]+$services["PENDING"];
+ // ALL PROBLEMS
+ $services["ALL PROBLEMS"] += $services["WARNING"]+$services["CRITICAL"]+$services["UNKNOWN"];
+ }
+ $result=$this->execQuery($queryhosts);
+ if(!$result){
+ // one ore more sites failed to execute the query
+ // we keep a trace
+ $failedhosts[]=array("site"=>$site,"code"=>$this->responsecode,"message"=>$this->responsemessage);
+ }else{
+ $states=json_decode($this->queryresponse);
+
+ // query pending hosts
+ $result = $this->execQuery($querypendinghosts);
+ $pending = json_decode($this->queryresponse);
+
+ // PENDING
+ $hosts["PENDING"] += $pending[0][0];
+ // UP
+ $hosts["UP"] += $states[0][0];
+ // DOWN
+ $hosts["DOWN"] += $states[0][1];
+ // UNREACHABLE
+ $hosts["UNREACHABLE"] += $states[0][2];
+ // ALL TYPES
+ $hosts["ALL TYPES"] = $hosts["UP"]+$hosts["DOWN"]+$hosts["UNREACHABLE"]+$hosts["PENDING"];
+ // ALL PROBLEMS
+ $hosts["ALL PROBLEMS"] = $hosts["DOWN"]+$hosts["UNREACHABLE"];
+ }
+ }else{
+ // one ore more sites failed to connect
+ // we keep a trace
+ $failedhosts[]=array("site"=>$site,"code"=>$this->responsecode,"message"=>$this->responsemessage);
+ }
}
-
+
+ return json_encode(array(
+ "hosts"=>(array)$hosts,
+ "services"=>(array)$services
+ ));
+ }
+
+
+ /**
+ *
+ * Enter description here ...
+ */
+ public function getPerformances($sites){
+
+ }
+
+ public function getHealth($sites){
+
+ }
+
+ public function getFeatures($sites){
+
+ }
+
+ /**
+ *
+ * Enter description here ...
+ * @param unknown_type $source
+ * @param unknown_type $site
+ */
+ private function agregateresult($source,$site){
+ $headers = array_shift($source);
+ $headers[]="site";
+ foreach($source as $row){
+ array_push($row,$site);
+ $this->resultArray[] = array_combine($headers,$row);
+ }
+ }
+
+ /**
+ *
+ * specific to multisite query (see execQueryMultisite)
+ */
+ private function resetConnection(){
+ $this->socketpath = null;
+ $this->host = null;
+ $this->port = null;
+ if($this->socket){
+ $this->disconnect();
+ }
+ return true;
+ }
/**
* execute a livestatus query and return result as json
* @param array $query elements of the querry (ex: array("GET services","Filter: state = 1","Filter: state = 2", "Or: 2"))
* @return string the json encoded result of the query
*/
- public function execQuery($query){
+ private function execQuery($query){
if($this->socket){
$this->disconnect();
}
if(!$this->connect()){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
return false;
}else{
if(!$this->query($query)){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
$this->disconnect();
return false;
}else{
if(!$this->readresponse()){
$this->disconnect();
return false;
}else{
$this->disconnect();
return $this->queryresponse;
}
}
}
}
/**
* This method submit an external command to nagios through livestatus socket.
* @param array $command an array describing the command array("COMMANDNAME",array("paramname"=>"value","paramname"=>"value",...)
* @return bool true if success false il failed
*/
public function sendExternalCommand($command){
if(!$this->parseCommand($command)){
return false;
}else{
if(!$this->submitExternalCommand($command)){
return false;
}else{
return true;
}
}
}
/**
* load commands defined in commands.inc.php
*/
public function getCommands($commands){
$this->commands = $commands;
}
/**
* PRIVATE METHODS
*/
/**
* Abstract method that choose wich connection method we should use.....
*/
protected function connect(){
if(is_null($this->socketpath)){
return $this->connectTCP();
}else{
return $this->connectUNIX();
}
}
/**
* connect to livestatus through TCP.
* @return bool true if success false if fail
*/
private function connectTCP(){
$this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if( $this->socket == false){
$this->socket = false;
return false;
}
$result = @socket_connect($this->socket, $this->host,$this->port);
if ($result == false){
$this->socket = null;
return false;
}
return true;
}
private function connectUNIX(){
$this->socket = @socket_create(AF_UNIX, SOCK_STREAM, SOL_SOCKET);
if( $this->socket == false){
$this->socket = false;
return false;
}
$result = @socket_connect($this->socket, $this->socketpath);
if ($result == false){
$this->socket = null;
return false;
}
return true;
}
private function connectSSH(){
die("Not implemented");
}
-
+ /**
+ *
+ * Enter description here ...
+ */
private function disconnect(){
- if ( ! is_null($this->socket)){
- // disconnect gracefully
- socket_shutdown($this->socket,2);
- socket_close($this->socket);
- $this->socket = null;
- return true;
- }else{
- return false;
- }
-
+ if ( ! is_null($this->socket)){
+ // disconnect gracefully
+ socket_shutdown($this->socket,2);
+ socket_close($this->socket);
+ $this->socket = null;
+ return true;
+ }else{
+ return false;
+ }
}
+
/**
* get livestatus version and put it in livever class property
*/
protected function getLivestatusVersion(){
$query = array(
"GET status",
"Columns: livestatus_version",
);
- $this->execQuery($query);
+
+ $this->execQuery($query);
$result = json_decode($this->queryresponse);
$this->livever = $result[1][0];
$this->responsecode=null;
$this->responsemessage=null;
$this->queryresponse=null;
- }
+ }
- private function query($elements,$default="json") {
- $query = $this->preparequery($elements,$default);
- foreach($query as $element){
- if(($this->socketwrite($element.$this->newline)) == false){
- return false;
- }
- }
- // finalize query
- if(($this->socketwrite($this->newline)) == false){
- return false;
- }
- return true;
+
+ /**
+ *
+ * Enter description here ...
+ * @param unknown_type $elements
+ * @param unknown_type $default
+ */
+ private function query($elements,$default="json") {
+ $query = $this->preparequery($elements,$default);
+ foreach($query as $element){
+ if(($this->socketwrite($element.$this->newline)) == false){
+ return false;
+ }
+ }
+ // finalize query
+ if(($this->socketwrite($this->newline)) == false){
+ return false;
+ }
+ return true;
}
-
+ /**
+ *
+ * Enter description here ...
+ */
private function readresponse(){
$this->queryresponse="";
if ( ! is_null( $this->socket ) ){
$headers = $this->getHeaders();
$code = $headers["statuscode"];
$size = $headers["contentlength"];
$this->responsecode = $code;
$this->responsemessage = $this->code2message($code);
if($code != "200"){
return false;
}
$this->queryresponse = $this->socketread($size);
return true;
}else{
return false;
}
}
-
+ /**
+ *
+ * Enter description here ...
+ * @param unknown_type $code
+ */
private function code2message($code){
if ( ! isset($this->messages["versions"][$this->livever])){
// assume new
$type = "new";
}else{
$type = $this->messages["versions"][$this->livever];
}
$message = $this->messages[$type][$code];
return $message;
}
+ /**
+ *
+ * Enter description here ...
+ * @param unknown_type $size
+ */
+ private function socketread($size){
+ if ( ! is_null( $this->socket ) ){
+ $buffer = $this->buffer;
+ $socketData = "";
+ if($size <= $buffer){
+ $socketData = @socket_read($this->socket,$size);
+ }else{
+ while($read = @socket_read($this->socket, $buffer)){
+ $socketData .= $read;
+ }
+ }
+ return $socketData;
+ }else{
+ return false;
+ }
+ }
-
-
- private function socketread($size){
- if ( ! is_null( $this->socket ) ){
- $buffer = $this->buffer;
- $socketData = "";
- if($size <= $buffer){
- $socketData = @socket_read($this->socket,$size);
- }else{
- while($read = @socket_read($this->socket, $buffer)){
- $socketData .= $read;
- }
- }
- return $socketData;
- }else{
- return false;
- }
- }
-
+ /**
+ *
+ * Enter description here ...
+ * @param unknown_type $data
+ */
private function socketwrite($data){
- if ( ! is_null( $this->socket ) ){
- if (socket_write($this->socket, $data) === false){
- return false;
- }else{
- return true;
- }
- }else{
- return false;
- }
- return true;
+ if ( ! is_null( $this->socket ) ){
+ if (socket_write($this->socket, $data) === false){
+ return false;
+ }else{
+ return true;
+ }
+ }else{
+ return false;
+ }
+ return true;
}
- public function getSocketError(){
- $errorcode = socket_last_error();
- $errormsg = socket_strerror($errorcode);
- return $errormsg;
- }
+ /**
+ *
+ * Enter description here ...
+ */
+ public function getSocketError(){
+ $errorcode = socket_last_error();
+ $errormsg = socket_strerror($errorcode);
+ return $errormsg;
+ }
private function getHeaders(){
if ( ! is_null( $this->socket ) ){
$rawHeaders = @socket_read($this->socket, $this->headersize);
return array(
"statuscode" => substr($rawHeaders, 0, 3),
"contentlength" => intval(trim(substr($rawHeaders, 4, 11)))
);
}else{
return false;
}
}
private function preparequery($elements){
$query=$this->defaults;
return array_merge((array)$elements,(array)$query);
}
/**
* This function submit an external command to the livestatus enabled host
* @param array $command an array defining the command array("commandname",array("argname"=>"value","argname"=>"value",...))
* @return bool true if success, false if failed
*/
private function submitExternalCommand($command){
$arguments = "";
foreach(array_keys($command[1]) as $key){
$arguments .= $command[1][$key].";";
}
$arguments = substr($arguments, 0, strlen($arguments)-1);
$commandline = "COMMAND [".time()."] ".$command[0].";".$arguments;
if($this->socket){
$this->disconnect();
}
if(!$this->connect()){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
return false;
}else{
if(!$this->query($commandline)){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
$this->disconnect();
return false;
}else{
$this->responsecode = null;
$this->responsemessage = null;
return true;
}
}
}
/**
* This function is used to parse and validate commands before submit them.
* @param array $command an array defining the command array("commandname",array("argname"=>"value","argname"=>"value",...))
* @return bool true id ok false if not. the raison is stored in responsecode and response message class properties.
*/
private function parseCommand($command){
// check if there is 2 elements in the array
if(count($command) != 2){
$this->responsecode = "602";
$this->responsemessage = "Invalid message definition (wrong number of entries in \$command)";
}else{
// check if first element exist as a key in commands definition
if(!array_key_exists($command[0], $this->commands)){
$this->responsecode = "602";
$this->responsemessage = "Invalid message definition (command ".$command[0]." not found)";
}else{
// check number of arguments against command definition
if(count($this->commands[$command[0]]) != count($command[1])){
$this->responsecode = "602";
$this->responsemessage = "Invalid number of arguments (required : ".count($this->commands[$command[0]]).", provided : ".count($command[1]).")";
}else{
// check argument's names
$defined_keys = $this->commands[$command[0]];
$provided_keys = array_keys($command[1]);
$diff_keys = array_diff($defined_keys, $provided_keys);
if ( count($diff_keys) > 0 ){
$this->responsecode = "602";
$this->responsemessage = "The arguments provided doesn't match the required arguments (".implode(", ", $diff_keys).")";
}else{
$this->responsecode = null;
$this->responsemessage = null;
return true;
}
}
}
}
return false;
}
}
|
david-guenault/frogx_api
|
55eac56799a58bccfaa333527ca22408d3ce9300
|
Fixed some typo in command example
|
diff --git a/examples/livestatus-command.php b/examples/livestatus-command.php
index 49bc3c5..6815ba8 100644
--- a/examples/livestatus-command.php
+++ b/examples/livestatus-command.php
@@ -1,30 +1,35 @@
<?php
// this script send an external command to livestatus
$base = "/var/www/frogx";
include_once ($base."/api/live.php");
include_once ($base."/conf/commands.inc.php");
-// live status query (each line is a row in the array)
+
+// command definition
$command = array(
"DISABLE_HOST_SVC_CHECKS",
array("host_name"=>"localhost")
);
-// create live object TCP with xinetd with default buffer size
-// $live = new live(array("host"=>"localhost", "port"=>"6557"));
+// this is a single site command call
// create live object with Unix Socket
$live = new live(array("socket"=>"/opt/monitor/var/rw/live"),1024);
+
//load authorised external command list
$live->getCommands($config["commands"]);
+
if(!$live){
die("Error while connecting");
}else{
//execute the command
if(!$live->sendExternalCommand($command)){
echo "[ERROR ".$live->responsecode."] ".$live->responsemessage;
}else{
echo "[SUCCESS]";
}
}
+
+//
+
?>
|
david-guenault/frogx_api
|
fdbe07ad337c492e83b909b6c0518c31b407477a
|
fixed several bugs in live and tac. Now all seems to work fine
|
diff --git a/api/live.php b/api/live.php
index 6f57291..37a6aae 100644
--- a/api/live.php
+++ b/api/live.php
@@ -1,487 +1,498 @@
<?php
/**
* base class to use live status implementation in shinken and nagios
*
* @package livestatusapi
* @author David GUENAULT ([email protected])
* @copyright (c) 2010 Monitoring-fr Team / Shinken Team (http://monitoring-fr.org / http://www.shinken-monitoring.org)
* @license Afero GPL
* @version 0.1
*/
class live {
/**
* the socket used to communicate
* @var ressource
*/
- protected $socket = null;
+ protected $socket = null;
/**
* path to the livestatus unix socket
* @var string
*/
- protected $socketpath = null;
+ protected $socketpath = null;
/**
* host name or ip address of the host that serve livestatus queries
* @var string
*/
- protected $host = null;
+ protected $host = null;
/**
* TCP port of the remote host that serve livestatus queries
* @var int
*/
- protected $port = null;
+ protected $port = null;
/**
* the socket buffer read length
* @var int
*/
- protected $buffer = null;
+ protected $buffer = 1024;
/**
* the cahracter used to define newlines (livestatus use double newline character end of query definition)
* @var char
*/
- protected $newline = "\n";
+ protected $newline = "\n";
/**
* this is the version of livestatus it is automaticaly filed by the getLivestatusVersion() method
* @var string
*/
- protected $livever = null;
+ protected $livever = null;
/**
* default headersize (in bytes) returned after a livestatus query (always 16)
* @var int
*/
- protected $headersize = 16;
+ protected $headersize = 16;
/**
*
* @commands array list all authorized commands
*/
- protected $commands = null;
+ protected $commands = null;
/**
* this define query options that will be added to each query (default options)
* @var array
*/
- public $defaults = array(
- "ColumnHeaders: on",
- "ResponseHeader: fixed16",
- // "KeepAlive: on",
- "OutputFormat: json"
- );
- /**
- * used to make difference between pre 1.1.3 version of livestatus return code and post 1.1.3
- * @var array
- */
- protected $messages = array(
- "versions" => array(
- "1.0.19" => "old",
- "1.0.20" => "old",
- "1.0.21" => "old",
- "1.0.22" => "old",
- "1.0.23" => "old",
- "1.0.24" => "old",
- "1.0.25" => "old",
- "1.0.26" => "old",
- "1.0.27" => "old",
- "1.0.28" => "old",
- "1.0.29" => "old",
- "1.0.30" => "old",
- "1.0.31" => "old",
- "1.0.32" => "old",
- "1.0.33" => "old",
- "1.0.34" => "old",
- "1.0.35" => "old",
- "1.0.36" => "old",
- "1.0.37" => "old",
- "1.0.38" => "old",
- "1.0.39" => "old",
- "1.1.0" => "old",
- "1.1.1" => "old",
- "1.1.2" => "old",
- "1.1.3" => "new",
- "1.1.4" => "new",
- "1.1.5i0" => "new",
- "1.1.5i1" => "new",
- "1.1.5i2" => "new",
- "1.1.5i3" => "new",
- "1.1.6b2" => "new",
- "1.1.6b3" => "new",
- "1.1.6rc1" => "new",
- "1.1.6rc2" => "new",
- "1.1.6rc3" => "new",
- "1.1.6p1" => "new",
- "1.1.7i1" => "new",
- "1.1.7i2" => "new"
- ),
- "old" => array(
- "200"=>"OK. Reponse contains the queried data.",
- "401"=>"The request contains an invalid header.",
- "402"=>"The request is completely invalid.",
- "403"=>"The request is incomplete",
- "404"=>"The target of the GET has not been found (e.g. the table).",
- "405"=>"A non-existing column was being referred to"
- ),
- "new" => array(
- "200"=>"OK. Reponse contains the queried data.",
- "400"=>"The request contains an invalid header.",
- "403"=>"The user is not authorized (see AuthHeader)",
- "404"=>"The target of the GET has not been found (e.g. the table).",
- "450"=>"A non-existing column was being referred to",
- "451"=>"The request is incomplete.",
- "452"=>"The request is completely invalid."
- )
- );
+ public $defaults = array(
+ "ColumnHeaders: on",
+ "ResponseHeader: fixed16",
+ // "KeepAlive: on",
+ "OutputFormat: json"
+ );
+ /**
+ * used to make difference between pre 1.1.3 version of livestatus return code and post 1.1.3
+ * @var array
+ */
+ protected $messages = array(
+ "versions" => array(
+ "1.0.19" => "old",
+ "1.0.20" => "old",
+ "1.0.21" => "old",
+ "1.0.22" => "old",
+ "1.0.23" => "old",
+ "1.0.24" => "old",
+ "1.0.25" => "old",
+ "1.0.26" => "old",
+ "1.0.27" => "old",
+ "1.0.28" => "old",
+ "1.0.29" => "old",
+ "1.0.30" => "old",
+ "1.0.31" => "old",
+ "1.0.32" => "old",
+ "1.0.33" => "old",
+ "1.0.34" => "old",
+ "1.0.35" => "old",
+ "1.0.36" => "old",
+ "1.0.37" => "old",
+ "1.0.38" => "old",
+ "1.0.39" => "old",
+ "1.1.0" => "old",
+ "1.1.1" => "old",
+ "1.1.2" => "old",
+ "1.1.3" => "new",
+ "1.1.4" => "new",
+ "1.1.5i0" => "new",
+ "1.1.5i1" => "new",
+ "1.1.5i2" => "new",
+ "1.1.5i3" => "new",
+ "1.1.6b2" => "new",
+ "1.1.6b3" => "new",
+ "1.1.6rc1" => "new",
+ "1.1.6rc2" => "new",
+ "1.1.6rc3" => "new",
+ "1.1.6p1" => "new",
+ "1.1.7i1" => "new",
+ "1.1.7i2" => "new"
+ ),
+ "old" => array(
+ "200"=>"OK. Reponse contains the queried data.",
+ "401"=>"The request contains an invalid header.",
+ "402"=>"The request is completely invalid.",
+ "403"=>"The request is incomplete",
+ "404"=>"The target of the GET has not been found (e.g. the table).",
+ "405"=>"A non-existing column was being referred to"
+ ),
+ "new" => array(
+ "200"=>"OK. Reponse contains the queried data.",
+ "400"=>"The request contains an invalid header.",
+ "403"=>"The user is not authorized (see AuthHeader)",
+ "404"=>"The target of the GET has not been found (e.g. the table).",
+ "450"=>"A non-existing column was being referred to",
+ "451"=>"The request is incomplete.",
+ "452"=>"The request is completely invalid."
+ )
+ );
/**
* json response of the query
* @var string
*/
- public $queryresponse = null;
+ public $queryresponse = null;
/**
* response code returned after query
* @var int
*/
- public $responsecode = null;
+ public $responsecode = null;
/**
* response message returned after query
*/
- public $responsemessage = null;
+ public $responsemessage = null;
/**
* Class Constructor
* @param array params array of parameters (if socket is in the keys then the connection is UNIX SOCKET else it is TCP SOCKET)
* @param int buffer used to read query response
*/
- public function __construct($params,$buffer=1024)
- {
- // fucking php limitation on declaring multiple constructors !
- if(isset($params["socket"])){
- $this->socketpath = $params["socket"];
- $this->buffer = $buffer;
- }else{
- $this->host = $params["host"];
- $this->port = $params["port"];
- $this->buffer = $buffer;
- }
- $this->getLivestatusVersion();
- }
-
+ public function __construct($params,$buffer=1024){
+ // fucking php limitation on declaring multiple constructors !
+ if(isset($params["socket"])){
+ $this->socketpath = $params["socket"];
+ $this->buffer = $buffer;
+ $this->getLivestatusVersion();
+ }elseif(isset($params["host"]) && isset($params["port"]) ){
+ $this->host = $params["host"];
+ $this->port = $params["port"];
+ $this->buffer = $buffer;
+ $this->getLivestatusVersion();
+ }else{
+ return false;
+ }
+
+ }
+
+ /**
+ * wrapper constructor method
+ * Enter description here ...
+ * @param $params
+ * @param $buffer
+ */
+ protected function constructLive($params,$buffer=1024){
+ $this->__construct($params,$buffer);
+ }
+
/**
* Class destructor
*/
public function __destruct() {
$this->disconnect();
$this->queryresponse = null;
}
/**
* execute a livestatus query and return result as json
* @param array $query elements of the querry (ex: array("GET services","Filter: state = 1","Filter: state = 2", "Or: 2"))
* @return string the json encoded result of the query
*/
public function execQuery($query){
if($this->socket){
$this->disconnect();
}
if(!$this->connect()){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
return false;
}else{
if(!$this->query($query)){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
$this->disconnect();
return false;
}else{
if(!$this->readresponse()){
$this->disconnect();
return false;
}else{
$this->disconnect();
return $this->queryresponse;
}
}
}
}
/**
* This method submit an external command to nagios through livestatus socket.
* @param array $command an array describing the command array("COMMANDNAME",array("paramname"=>"value","paramname"=>"value",...)
* @return bool true if success false il failed
*/
public function sendExternalCommand($command){
if(!$this->parseCommand($command)){
return false;
}else{
if(!$this->submitExternalCommand($command)){
return false;
}else{
return true;
}
}
}
/**
* load commands defined in commands.inc.php
*/
public function getCommands($commands){
$this->commands = $commands;
}
/**
* PRIVATE METHODS
*/
/**
* Abstract method that choose wich connection method we should use.....
*/
- private function connect(){
+ protected function connect(){
if(is_null($this->socketpath)){
return $this->connectTCP();
}else{
return $this->connectUNIX();
}
}
/**
* connect to livestatus through TCP.
* @return bool true if success false if fail
*/
private function connectTCP(){
$this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if( $this->socket == false){
$this->socket = false;
return false;
}
$result = @socket_connect($this->socket, $this->host,$this->port);
if ($result == false){
$this->socket = null;
return false;
}
return true;
}
private function connectUNIX(){
$this->socket = @socket_create(AF_UNIX, SOCK_STREAM, SOL_SOCKET);
if( $this->socket == false){
$this->socket = false;
return false;
}
$result = @socket_connect($this->socket, $this->socketpath);
if ($result == false){
$this->socket = null;
return false;
}
return true;
}
private function connectSSH(){
die("Not implemented");
}
private function disconnect(){
if ( ! is_null($this->socket)){
// disconnect gracefully
socket_shutdown($this->socket,2);
socket_close($this->socket);
$this->socket = null;
return true;
}else{
return false;
}
}
/**
* get livestatus version and put it in livever class property
*/
protected function getLivestatusVersion(){
$query = array(
"GET status",
"Columns: livestatus_version",
);
$this->execQuery($query);
$result = json_decode($this->queryresponse);
$this->livever = $result[1][0];
$this->responsecode=null;
$this->responsemessage=null;
$this->queryresponse=null;
}
private function query($elements,$default="json") {
$query = $this->preparequery($elements,$default);
foreach($query as $element){
if(($this->socketwrite($element.$this->newline)) == false){
return false;
}
}
// finalize query
if(($this->socketwrite($this->newline)) == false){
return false;
}
return true;
}
private function readresponse(){
- $this->queryresponse="";
-
- if ( ! is_null( $this->socket ) ){
- $headers = $this->getHeaders();
- $code = $headers["statuscode"];
- $size = $headers["contentlength"];
-
- $this->responsecode = $code;
- $this->responsemessage = $this->code2message($code);
- if($code != "200"){
- return false;
+ $this->queryresponse="";
+ if ( ! is_null( $this->socket ) ){
+ $headers = $this->getHeaders();
+ $code = $headers["statuscode"];
+ $size = $headers["contentlength"];
+ $this->responsecode = $code;
+ $this->responsemessage = $this->code2message($code);
+ if($code != "200"){
+ return false;
+ }
+ $this->queryresponse = $this->socketread($size);
+ return true;
+ }else{
+ return false;
}
- $this->queryresponse = $this->socketread($size);
- return true;
- }else{
- return false;
- }
- }
+ }
private function code2message($code){
if ( ! isset($this->messages["versions"][$this->livever])){
// assume new
$type = "new";
}else{
$type = $this->messages["versions"][$this->livever];
}
$message = $this->messages[$type][$code];
return $message;
}
private function socketread($size){
if ( ! is_null( $this->socket ) ){
$buffer = $this->buffer;
$socketData = "";
if($size <= $buffer){
$socketData = @socket_read($this->socket,$size);
}else{
while($read = @socket_read($this->socket, $buffer)){
$socketData .= $read;
}
}
return $socketData;
}else{
return false;
}
}
private function socketwrite($data){
if ( ! is_null( $this->socket ) ){
if (socket_write($this->socket, $data) === false){
return false;
}else{
return true;
}
}else{
return false;
}
return true;
}
public function getSocketError(){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
return $errormsg;
}
private function getHeaders(){
if ( ! is_null( $this->socket ) ){
$rawHeaders = @socket_read($this->socket, $this->headersize);
return array(
"statuscode" => substr($rawHeaders, 0, 3),
"contentlength" => intval(trim(substr($rawHeaders, 4, 11)))
);
}else{
return false;
}
}
private function preparequery($elements){
$query=$this->defaults;
return array_merge((array)$elements,(array)$query);
}
/**
* This function submit an external command to the livestatus enabled host
* @param array $command an array defining the command array("commandname",array("argname"=>"value","argname"=>"value",...))
* @return bool true if success, false if failed
*/
private function submitExternalCommand($command){
$arguments = "";
foreach(array_keys($command[1]) as $key){
$arguments .= $command[1][$key].";";
}
$arguments = substr($arguments, 0, strlen($arguments)-1);
$commandline = "COMMAND [".time()."] ".$command[0].";".$arguments;
if($this->socket){
$this->disconnect();
}
if(!$this->connect()){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
return false;
}else{
if(!$this->query($commandline)){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
$this->disconnect();
return false;
}else{
$this->responsecode = null;
$this->responsemessage = null;
return true;
}
}
}
/**
* This function is used to parse and validate commands before submit them.
* @param array $command an array defining the command array("commandname",array("argname"=>"value","argname"=>"value",...))
* @return bool true id ok false if not. the raison is stored in responsecode and response message class properties.
*/
private function parseCommand($command){
// check if there is 2 elements in the array
if(count($command) != 2){
$this->responsecode = "602";
$this->responsemessage = "Invalid message definition (wrong number of entries in \$command)";
}else{
// check if first element exist as a key in commands definition
if(!array_key_exists($command[0], $this->commands)){
$this->responsecode = "602";
$this->responsemessage = "Invalid message definition (command ".$command[0]." not found)";
}else{
// check number of arguments against command definition
if(count($this->commands[$command[0]]) != count($command[1])){
$this->responsecode = "602";
$this->responsemessage = "Invalid number of arguments (required : ".count($this->commands[$command[0]]).", provided : ".count($command[1]).")";
}else{
// check argument's names
$defined_keys = $this->commands[$command[0]];
$provided_keys = array_keys($command[1]);
$diff_keys = array_diff($defined_keys, $provided_keys);
if ( count($diff_keys) > 0 ){
$this->responsecode = "602";
$this->responsemessage = "The arguments provided doesn't match the required arguments (".implode(", ", $diff_keys).")";
}else{
$this->responsecode = null;
$this->responsemessage = null;
return true;
}
}
}
}
return false;
}
}
diff --git a/api/tac.php b/api/tac.php
index 184450d..4dfa448 100644
--- a/api/tac.php
+++ b/api/tac.php
@@ -1,152 +1,142 @@
<?php
/**
* base class to use live status implementation in shinken and nagios
*
* @package livestatusapi
* @author David GUENAULT ([email protected])
* @copyright (c) 2010 Monitoring-fr Team / Shinken Team (http://monitoring-fr.org / http://www.shinken-monitoring.org)
* @license Afero GPL
* @version 0.1
*/
class tac extends live{
public $sites = null;
-
- /**
- * Class Constructor
- * @param array params array of parameters (if socket is in the keys then the connection is UNIX SOCKET else it is TCP SOCKET)
- * @param int buffer used to read query response
- */
- public function __construct($params,$buffer=1024) {
- // fucking php limitation on declaring multiple constructors !
- if(isset($params["socket"])){
- $this->socketpath = $params["socket"];
- $this->buffer = $buffer;
- }else{
- $this->host = $params["host"];
- $this->port = $params["port"];
- $this->buffer = $buffer;
- }
- $this->getLivestatusVersion();
+
+ public function __construct(){
+
}
- /**
- * Class destructor
- */
- public function __destruc(){
-
+
+ public function __destruct(){
+
}
+
/**
* This method get the overall status of all services and hosts. if $sites is an array of sites names it will only retrieve the tac for the specified sites.
- * @param array $sites
+ * @param array sites an array off all of the monitoring hosts (see conf/sites.inc.php)
* @return string the json encoded tac values
*/
public function getOverallStates($sites){
// check sites validity
if($sites == null || count($sites) < 1){
$this->responsecode = "603";
$this->responsemessage = "[SITES] invalid sites definition";
return false;
}
// get overall services states (HARD STATES ONLY)
$queryservices = array(
- "GET services",
- "Columns: state",
- "Filter: state_type = 1"
+ "GET services",
+ "Stats: state = 0",
+ "Stats: state = 1",
+ "Stats: state = 2",
+ "Stats: state = 3",
);
// get overall hosts states (HARD STATES ONLY)
$queryhosts = array(
- "GET hosts",
- "Columns: state",
- "Filter: state_type = 1"
+ "GET hosts",
+ "Stats: state = 0",
+ "Stats: state = 1",
+ "Stats: state = 2"
);
$failedservices = array();
$failedhosts = array();
$hosts=array(
"UP"=>0,
"DOWN"=>0,
"UNREACHABLE"=>0,
"ALL PROBLEMS"=>0,
"ALL TYPES"=>0
);
$services=array(
"OK"=>0,
"WARNING"=>0,
"CRITICAL"=>0,
"UNKNOWN"=>0,
"ALL PROBLEMS"=>0,
"ALL TYPES"=>0
);
foreach($sites as $site){
- if(!$this->execQuery($queryservices)){
- // one ore more sites failed to execute the query
- // we keep a trace
- $failedservices[$site]=array("code"=>$this->responsecode,"message"=>$this->responsemessage);
- }else{
- $result=json_decode($this->queryresponse);
- foreach($result as $state){
- switch($state[0]){
- case "0":
- $services["OK"]++;
- $services["ALL TYPES"]++;
- break;
- case "1":
- $services["WARNING"]++;
- $services["ALL PROBLEMS"]++;
- $services["ALL TYPES"]++;
- break;
- case "2":
- $services["CRITICAL"]++;
- $services["ALL PROBLEMS"]++;
- $services["ALL TYPES"]++;
- break;
- case "3":
- $services["UNKNOWN"]++;
- $services["ALL PROBLEMS"]++;
- $services["ALL TYPES"]++;
- break;
- }
- }
- }
- if(!$this->execQuery($queryhosts)){
- // one ore more sites failed to execute the query
- // we keep a trace
- $failedhosts[$site]=array("code"=>$this->responsecode,"message"=>$this->responsemessage);
- }else{
- $result=json_decode($this->queryresponse);
- foreach($result as $state){
- switch($state[0]){
- case "0":
- $hosts["UP"]++;
- $hosts["ALL TYPES"]++;
- break;
- case "1":
- $hosts["DOWN"]++;
- $hosts["ALL PROBLEMS"]++;
- $hosts["ALL TYPES"]++;
- break;
- case "2":
- $hosts["UNREACHABLE"]++;
- $hosts["ALL PROBLEMS"]++;
- $hosts["ALL TYPES"]++;
- break;
- }
- }
-
- }
+ if($this->connectSite($site)){
+ $result=$this->execQuery($queryservices);
+ if($result == false){
+ // one ore more sites failed to execute the query
+ // we keep a trace
+ $failedservices[]=array("site"=>$site,"code"=>$this->responsecode,"message"=>$this->responsemessage);
+ return false;
+ }else{
+ $states=json_decode($this->queryresponse);
+ // OK
+ $services["OK"] += $states[0][0];
+ // WARNING
+ $services["WARNING"] += $states[0][1];
+ // CRITICAL
+ $services["CRITICAL"] += $states[0][2];
+ // UNKNOWN
+ $services["UNKNOWN"] += $states[0][3];
+ // ALL TYPES
+ $services["ALL TYPES"] += $services["OK"]+$services["WARNING"]+$services["CRITICAL"]+$services["UNKNOWN"];
+ // ALL PROBLEMS
+ $services["ALL PROBLEMS"] += $services["WARNING"]+$services["CRITICAL"]+$services["UNKNOWN"];
+ }
+ $result=$this->execQuery($queryhosts);
+ if(!$result){
+ // one ore more sites failed to execute the query
+ // we keep a trace
+ $failedhosts[]=array("site"=>$site,"code"=>$this->responsecode,"message"=>$this->responsemessage);
+ }else{
+ $states=json_decode($this->queryresponse);
+ // UP
+ $hosts["UP"] += $states[0][0];
+ // DOWN
+ $hosts["DOWN"] += $states[0][1];
+ // UNREACHABLE
+ $hosts["UNREACHABLE"] += $states[0][2];
+ // ALL TYPES
+ $hosts["ALL TYPES"] += $hosts["UP"]+$hosts["DOWN"]+$hosts["UNREACHABLE"];
+ // ALL PROBLEMS
+ $hosts["ALL PROBLEMS"] += $hosts["DOWN"]+$hosts["UNREACHABLE"];
+ }
+ }else{
+ // one ore more sites failed to connect
+ // we keep a trace
+ $failedhosts[]=array("site"=>$site,"code"=>$this->responsecode,"message"=>$this->responsemessage);
+ }
}
- return json_encode(array(
- "hosts"=>$hosts,
- "services"=>$services
- ));
+ return json_encode(array(
+ "hosts"=>$hosts,
+ "services"=>$services
+ ));
}
-
+ private function connectSite($site){
+ switch($site["type"]){
+ case "TCP":
+ $this->host = $site["host"];
+ $this->port = $site["port"];
+ break;
+ case "UNIX":
+ $this->socketpath = $site["socket"];
+ break;
+ default:
+ break;
+ }
+ return $this->connect();
+ }
}
diff --git a/conf/sites.inc.php b/conf/sites.inc.php
index ec73601..f0be2ba 100644
--- a/conf/sites.inc.php
+++ b/conf/sites.inc.php
@@ -1,16 +1,22 @@
<?php
/**
* This config file is used to define the nagios/shinken collectors
*
* @global array $GLOBALS['config']
* @name $config
*/
$config["sites"]=array(
- "frogx"=>array(
- "type"=>"TCP",
- "address"=>"localhost",
- "port"=>"5667"
+ "host-unix"=>array(
+ "type"=>"UNIX",
+ "socket"=>"/opt/monitor/var/rw/live"
)
+// ,
+// "host-tcp"=>array(
+// "type"=>"TCP",
+// "host"=>"localhost",
+// "port"=>"6557"
+// )
+//
);
?>
diff --git a/examples/livestatus-documentation.php b/examples/livestatus-documentation.php
index b2fbb36..82e2994 100644
--- a/examples/livestatus-documentation.php
+++ b/examples/livestatus-documentation.php
@@ -1,39 +1,39 @@
<?php
// this script execute a simple livestatus query on table columns
// columns describe all of the others tables of livestatus
require_once("/var/www/frogx/api/live.php");
// live status query (each line is a row in the array)
$query = array("GET columns");
// create live object TCP with xinetd with default buffer size
-// $live = new live(array("host"=>"localhost", "port"=>"6557"));
+$live = new live(array("host"=>"localhost", "port"=>"6557"));
// create live object with Unix Socket
-$live = new live(array("socket"=>"/opt/monitor/var/rw/live"),1024);
+//$live = new live(array("socket"=>"/opt/monitor/var/rw/live"),1024);
if(!$live){
die("Error while connecting");
}else{
//execute the query
$json = $live->execQuery($query);
if($live->responsecode != "200"){
// error
die($live->responsecode." : ".$live->responsemessage);
}
$response = json_decode($json);
echo "<table>";
foreach ($response as $line){
// line
echo "<tr>";
// header
foreach($line as $col){
echo "<td style=\"border:1px solid black\">".$col."</td>";
}
echo "</tr>";
}
echo "</table>";
}
?>
diff --git a/examples/livestatus-tac.php b/examples/livestatus-tac.php
index fafa0ca..a91a257 100644
--- a/examples/livestatus-tac.php
+++ b/examples/livestatus-tac.php
@@ -1,13 +1,13 @@
<?php
/**
* get overall hosts and services states (as known as tactical overview)
* this introduce the concept of multisite. Each site is an entry in the array config["sites"]
*/
require_once("/var/www/frogx/conf/sites.inc.php");
require_once("/var/www/frogx/api/live.php");
require_once("/var/www/frogx/api/tac.php");
-$tac = new tac(array("host"=>"localhost", "port"=>"6557"));
+$tac = new tac();
print($tac->getOverallStates($config["sites"]));
?>
|
david-guenault/frogx_api
|
f94f33397fdc78a00722bed340ec20e0181b5d86
|
Added readme file
|
diff --git a/README b/README
new file mode 100644
index 0000000..e69de29
|
david-guenault/frogx_api
|
58a5a2d22a491ee02becd85762782594c0c44c87
|
tac example print json now
|
diff --git a/examples/livestatus-tac.php b/examples/livestatus-tac.php
index 3708941..fafa0ca 100644
--- a/examples/livestatus-tac.php
+++ b/examples/livestatus-tac.php
@@ -1,13 +1,13 @@
<?php
/**
* get overall hosts and services states (as known as tactical overview)
* this introduce the concept of multisite. Each site is an entry in the array config["sites"]
*/
require_once("/var/www/frogx/conf/sites.inc.php");
require_once("/var/www/frogx/api/live.php");
require_once("/var/www/frogx/api/tac.php");
$tac = new tac(array("host"=>"localhost", "port"=>"6557"));
-print_r(json_decode($tac->getOverallStates($config["sites"])));
+print($tac->getOverallStates($config["sites"]));
?>
|
david-guenault/frogx_api
|
1ccb268a388434305d27eb9e7007800cdf69deb0
|
tac data should be returned as json
|
diff --git a/api/tac.php b/api/tac.php
index 623ec49..184450d 100644
--- a/api/tac.php
+++ b/api/tac.php
@@ -1,152 +1,152 @@
<?php
/**
* base class to use live status implementation in shinken and nagios
*
* @package livestatusapi
* @author David GUENAULT ([email protected])
* @copyright (c) 2010 Monitoring-fr Team / Shinken Team (http://monitoring-fr.org / http://www.shinken-monitoring.org)
* @license Afero GPL
* @version 0.1
*/
class tac extends live{
public $sites = null;
/**
* Class Constructor
* @param array params array of parameters (if socket is in the keys then the connection is UNIX SOCKET else it is TCP SOCKET)
* @param int buffer used to read query response
*/
public function __construct($params,$buffer=1024) {
// fucking php limitation on declaring multiple constructors !
if(isset($params["socket"])){
$this->socketpath = $params["socket"];
$this->buffer = $buffer;
}else{
$this->host = $params["host"];
$this->port = $params["port"];
$this->buffer = $buffer;
}
$this->getLivestatusVersion();
}
/**
* Class destructor
*/
public function __destruc(){
}
/**
* This method get the overall status of all services and hosts. if $sites is an array of sites names it will only retrieve the tac for the specified sites.
* @param array $sites
* @return string the json encoded tac values
*/
public function getOverallStates($sites){
// check sites validity
if($sites == null || count($sites) < 1){
$this->responsecode = "603";
$this->responsemessage = "[SITES] invalid sites definition";
return false;
}
// get overall services states (HARD STATES ONLY)
$queryservices = array(
"GET services",
"Columns: state",
"Filter: state_type = 1"
);
// get overall hosts states (HARD STATES ONLY)
$queryhosts = array(
"GET hosts",
"Columns: state",
"Filter: state_type = 1"
);
$failedservices = array();
$failedhosts = array();
$hosts=array(
"UP"=>0,
"DOWN"=>0,
"UNREACHABLE"=>0,
"ALL PROBLEMS"=>0,
"ALL TYPES"=>0
);
$services=array(
"OK"=>0,
"WARNING"=>0,
"CRITICAL"=>0,
"UNKNOWN"=>0,
"ALL PROBLEMS"=>0,
"ALL TYPES"=>0
);
foreach($sites as $site){
if(!$this->execQuery($queryservices)){
// one ore more sites failed to execute the query
// we keep a trace
$failedservices[$site]=array("code"=>$this->responsecode,"message"=>$this->responsemessage);
}else{
$result=json_decode($this->queryresponse);
foreach($result as $state){
switch($state[0]){
case "0":
$services["OK"]++;
$services["ALL TYPES"]++;
break;
case "1":
$services["WARNING"]++;
$services["ALL PROBLEMS"]++;
$services["ALL TYPES"]++;
break;
case "2":
$services["CRITICAL"]++;
$services["ALL PROBLEMS"]++;
$services["ALL TYPES"]++;
break;
case "3":
$services["UNKNOWN"]++;
$services["ALL PROBLEMS"]++;
$services["ALL TYPES"]++;
break;
}
}
}
if(!$this->execQuery($queryhosts)){
// one ore more sites failed to execute the query
// we keep a trace
$failedhosts[$site]=array("code"=>$this->responsecode,"message"=>$this->responsemessage);
}else{
$result=json_decode($this->queryresponse);
foreach($result as $state){
switch($state[0]){
case "0":
$hosts["UP"]++;
$hosts["ALL TYPES"]++;
break;
case "1":
$hosts["DOWN"]++;
$hosts["ALL PROBLEMS"]++;
$hosts["ALL TYPES"]++;
break;
case "2":
$hosts["UNREACHABLE"]++;
$hosts["ALL PROBLEMS"]++;
$hosts["ALL TYPES"]++;
break;
}
}
}
}
- return array(
+ return json_encode(array(
"hosts"=>$hosts,
"services"=>$services
- );
+ ));
}
}
diff --git a/examples/livestatus-tac.php b/examples/livestatus-tac.php
index c7dae19..3708941 100644
--- a/examples/livestatus-tac.php
+++ b/examples/livestatus-tac.php
@@ -1,13 +1,13 @@
<?php
/**
* get overall hosts and services states (as known as tactical overview)
* this introduce the concept of multisite. Each site is an entry in the array config["sites"]
*/
require_once("/var/www/frogx/conf/sites.inc.php");
require_once("/var/www/frogx/api/live.php");
require_once("/var/www/frogx/api/tac.php");
$tac = new tac(array("host"=>"localhost", "port"=>"6557"));
-print_r($tac->getOverallStates($config["sites"]));
+print_r(json_decode($tac->getOverallStates($config["sites"])));
?>
|
david-guenault/frogx_api
|
6beee293e29f6cf2d5c9f50ad483bb47d04e4e18
|
added support for tactical overview (only overall hosts and services states)
|
diff --git a/api/live.php b/api/live.php
index a429d9c..6f57291 100644
--- a/api/live.php
+++ b/api/live.php
@@ -1,485 +1,487 @@
<?php
/**
* base class to use live status implementation in shinken and nagios
*
* @package livestatusapi
* @author David GUENAULT ([email protected])
* @copyright (c) 2010 Monitoring-fr Team / Shinken Team (http://monitoring-fr.org / http://www.shinken-monitoring.org)
* @license Afero GPL
* @version 0.1
*/
class live {
/**
* the socket used to communicate
* @var ressource
*/
protected $socket = null;
/**
* path to the livestatus unix socket
* @var string
*/
protected $socketpath = null;
/**
* host name or ip address of the host that serve livestatus queries
* @var string
*/
protected $host = null;
/**
* TCP port of the remote host that serve livestatus queries
* @var int
*/
protected $port = null;
/**
* the socket buffer read length
* @var int
*/
protected $buffer = null;
/**
* the cahracter used to define newlines (livestatus use double newline character end of query definition)
* @var char
*/
protected $newline = "\n";
/**
* this is the version of livestatus it is automaticaly filed by the getLivestatusVersion() method
* @var string
*/
protected $livever = null;
/**
* default headersize (in bytes) returned after a livestatus query (always 16)
* @var int
*/
protected $headersize = 16;
/**
*
* @commands array list all authorized commands
*/
protected $commands = null;
/**
* this define query options that will be added to each query (default options)
* @var array
*/
public $defaults = array(
"ColumnHeaders: on",
"ResponseHeader: fixed16",
// "KeepAlive: on",
"OutputFormat: json"
);
/**
* used to make difference between pre 1.1.3 version of livestatus return code and post 1.1.3
* @var array
*/
protected $messages = array(
"versions" => array(
"1.0.19" => "old",
"1.0.20" => "old",
"1.0.21" => "old",
"1.0.22" => "old",
"1.0.23" => "old",
"1.0.24" => "old",
"1.0.25" => "old",
"1.0.26" => "old",
"1.0.27" => "old",
"1.0.28" => "old",
"1.0.29" => "old",
"1.0.30" => "old",
"1.0.31" => "old",
"1.0.32" => "old",
"1.0.33" => "old",
"1.0.34" => "old",
"1.0.35" => "old",
"1.0.36" => "old",
"1.0.37" => "old",
"1.0.38" => "old",
"1.0.39" => "old",
"1.1.0" => "old",
"1.1.1" => "old",
"1.1.2" => "old",
"1.1.3" => "new",
"1.1.4" => "new",
"1.1.5i0" => "new",
"1.1.5i1" => "new",
"1.1.5i2" => "new",
"1.1.5i3" => "new",
"1.1.6b2" => "new",
"1.1.6b3" => "new",
"1.1.6rc1" => "new",
"1.1.6rc2" => "new",
"1.1.6rc3" => "new",
"1.1.6p1" => "new",
"1.1.7i1" => "new",
"1.1.7i2" => "new"
),
"old" => array(
"200"=>"OK. Reponse contains the queried data.",
"401"=>"The request contains an invalid header.",
"402"=>"The request is completely invalid.",
"403"=>"The request is incomplete",
"404"=>"The target of the GET has not been found (e.g. the table).",
"405"=>"A non-existing column was being referred to"
),
"new" => array(
"200"=>"OK. Reponse contains the queried data.",
"400"=>"The request contains an invalid header.",
"403"=>"The user is not authorized (see AuthHeader)",
"404"=>"The target of the GET has not been found (e.g. the table).",
"450"=>"A non-existing column was being referred to",
"451"=>"The request is incomplete.",
"452"=>"The request is completely invalid."
)
);
/**
* json response of the query
* @var string
*/
public $queryresponse = null;
/**
* response code returned after query
* @var int
*/
public $responsecode = null;
/**
* response message returned after query
*/
public $responsemessage = null;
/**
* Class Constructor
* @param array params array of parameters (if socket is in the keys then the connection is UNIX SOCKET else it is TCP SOCKET)
* @param int buffer used to read query response
*/
public function __construct($params,$buffer=1024)
{
// fucking php limitation on declaring multiple constructors !
if(isset($params["socket"])){
$this->socketpath = $params["socket"];
$this->buffer = $buffer;
}else{
$this->host = $params["host"];
$this->port = $params["port"];
$this->buffer = $buffer;
}
$this->getLivestatusVersion();
}
/**
* Class destructor
*/
public function __destruct() {
$this->disconnect();
$this->queryresponse = null;
}
/**
* execute a livestatus query and return result as json
* @param array $query elements of the querry (ex: array("GET services","Filter: state = 1","Filter: state = 2", "Or: 2"))
* @return string the json encoded result of the query
*/
public function execQuery($query){
if($this->socket){
$this->disconnect();
}
if(!$this->connect()){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
return false;
}else{
if(!$this->query($query)){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
$this->disconnect();
return false;
}else{
if(!$this->readresponse()){
$this->disconnect();
return false;
}else{
$this->disconnect();
return $this->queryresponse;
}
}
}
}
/**
* This method submit an external command to nagios through livestatus socket.
* @param array $command an array describing the command array("COMMANDNAME",array("paramname"=>"value","paramname"=>"value",...)
* @return bool true if success false il failed
*/
public function sendExternalCommand($command){
if(!$this->parseCommand($command)){
return false;
}else{
if(!$this->submitExternalCommand($command)){
return false;
}else{
return true;
}
}
}
/**
* load commands defined in commands.inc.php
*/
public function getCommands($commands){
$this->commands = $commands;
}
/**
* PRIVATE METHODS
*/
/**
* Abstract method that choose wich connection method we should use.....
*/
private function connect(){
if(is_null($this->socketpath)){
return $this->connectTCP();
}else{
return $this->connectUNIX();
}
}
/**
* connect to livestatus through TCP.
* @return bool true if success false if fail
*/
private function connectTCP(){
$this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if( $this->socket == false){
$this->socket = false;
return false;
}
$result = @socket_connect($this->socket, $this->host,$this->port);
if ($result == false){
$this->socket = null;
return false;
}
return true;
}
private function connectUNIX(){
$this->socket = @socket_create(AF_UNIX, SOCK_STREAM, SOL_SOCKET);
if( $this->socket == false){
$this->socket = false;
return false;
}
$result = @socket_connect($this->socket, $this->socketpath);
if ($result == false){
$this->socket = null;
return false;
}
return true;
}
private function connectSSH(){
die("Not implemented");
}
private function disconnect(){
if ( ! is_null($this->socket)){
// disconnect gracefully
socket_shutdown($this->socket,2);
socket_close($this->socket);
$this->socket = null;
return true;
}else{
return false;
}
}
-
- private function getLivestatusVersion(){
+ /**
+ * get livestatus version and put it in livever class property
+ */
+ protected function getLivestatusVersion(){
$query = array(
"GET status",
"Columns: livestatus_version",
);
$this->execQuery($query);
$result = json_decode($this->queryresponse);
$this->livever = $result[1][0];
$this->responsecode=null;
$this->responsemessage=null;
$this->queryresponse=null;
}
private function query($elements,$default="json") {
$query = $this->preparequery($elements,$default);
foreach($query as $element){
if(($this->socketwrite($element.$this->newline)) == false){
return false;
}
}
// finalize query
if(($this->socketwrite($this->newline)) == false){
return false;
}
return true;
}
private function readresponse(){
$this->queryresponse="";
if ( ! is_null( $this->socket ) ){
$headers = $this->getHeaders();
$code = $headers["statuscode"];
$size = $headers["contentlength"];
$this->responsecode = $code;
$this->responsemessage = $this->code2message($code);
if($code != "200"){
return false;
}
$this->queryresponse = $this->socketread($size);
return true;
}else{
return false;
}
}
private function code2message($code){
if ( ! isset($this->messages["versions"][$this->livever])){
// assume new
$type = "new";
}else{
$type = $this->messages["versions"][$this->livever];
}
$message = $this->messages[$type][$code];
return $message;
}
private function socketread($size){
if ( ! is_null( $this->socket ) ){
$buffer = $this->buffer;
$socketData = "";
if($size <= $buffer){
$socketData = @socket_read($this->socket,$size);
}else{
while($read = @socket_read($this->socket, $buffer)){
$socketData .= $read;
}
}
return $socketData;
}else{
return false;
}
}
private function socketwrite($data){
if ( ! is_null( $this->socket ) ){
if (socket_write($this->socket, $data) === false){
return false;
}else{
return true;
}
}else{
return false;
}
return true;
}
public function getSocketError(){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
return $errormsg;
}
private function getHeaders(){
if ( ! is_null( $this->socket ) ){
$rawHeaders = @socket_read($this->socket, $this->headersize);
return array(
"statuscode" => substr($rawHeaders, 0, 3),
"contentlength" => intval(trim(substr($rawHeaders, 4, 11)))
);
}else{
return false;
}
}
private function preparequery($elements){
$query=$this->defaults;
return array_merge((array)$elements,(array)$query);
}
/**
* This function submit an external command to the livestatus enabled host
* @param array $command an array defining the command array("commandname",array("argname"=>"value","argname"=>"value",...))
* @return bool true if success, false if failed
*/
private function submitExternalCommand($command){
$arguments = "";
foreach(array_keys($command[1]) as $key){
$arguments .= $command[1][$key].";";
}
$arguments = substr($arguments, 0, strlen($arguments)-1);
$commandline = "COMMAND [".time()."] ".$command[0].";".$arguments;
if($this->socket){
$this->disconnect();
}
if(!$this->connect()){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
return false;
}else{
if(!$this->query($commandline)){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
$this->disconnect();
return false;
}else{
$this->responsecode = null;
$this->responsemessage = null;
return true;
}
}
}
/**
* This function is used to parse and validate commands before submit them.
* @param array $command an array defining the command array("commandname",array("argname"=>"value","argname"=>"value",...))
* @return bool true id ok false if not. the raison is stored in responsecode and response message class properties.
*/
private function parseCommand($command){
// check if there is 2 elements in the array
if(count($command) != 2){
$this->responsecode = "602";
$this->responsemessage = "Invalid message definition (wrong number of entries in \$command)";
}else{
// check if first element exist as a key in commands definition
if(!array_key_exists($command[0], $this->commands)){
$this->responsecode = "602";
$this->responsemessage = "Invalid message definition (command ".$command[0]." not found)";
}else{
// check number of arguments against command definition
if(count($this->commands[$command[0]]) != count($command[1])){
$this->responsecode = "602";
$this->responsemessage = "Invalid number of arguments (required : ".count($this->commands[$command[0]]).", provided : ".count($command[1]).")";
}else{
// check argument's names
$defined_keys = $this->commands[$command[0]];
$provided_keys = array_keys($command[1]);
$diff_keys = array_diff($defined_keys, $provided_keys);
if ( count($diff_keys) > 0 ){
$this->responsecode = "602";
$this->responsemessage = "The arguments provided doesn't match the required arguments (".implode(", ", $diff_keys).")";
}else{
$this->responsecode = null;
$this->responsemessage = null;
return true;
}
}
}
}
return false;
}
}
diff --git a/api/tac.php b/api/tac.php
index 9c699c1..623ec49 100644
--- a/api/tac.php
+++ b/api/tac.php
@@ -1,47 +1,152 @@
<?php
/**
* base class to use live status implementation in shinken and nagios
*
* @package livestatusapi
* @author David GUENAULT ([email protected])
* @copyright (c) 2010 Monitoring-fr Team / Shinken Team (http://monitoring-fr.org / http://www.shinken-monitoring.org)
* @license Afero GPL
* @version 0.1
*/
-require_once './live.php';
class tac extends live{
+
+ public $sites = null;
+
/**
* Class Constructor
* @param array params array of parameters (if socket is in the keys then the connection is UNIX SOCKET else it is TCP SOCKET)
* @param int buffer used to read query response
*/
public function __construct($params,$buffer=1024) {
// fucking php limitation on declaring multiple constructors !
if(isset($params["socket"])){
$this->socketpath = $params["socket"];
$this->buffer = $buffer;
}else{
$this->host = $params["host"];
$this->port = $params["port"];
$this->buffer = $buffer;
}
$this->getLivestatusVersion();
}
/**
* Class destructor
*/
public function __destruc(){
}
/**
* This method get the overall status of all services and hosts. if $sites is an array of sites names it will only retrieve the tac for the specified sites.
* @param array $sites
* @return string the json encoded tac values
*/
- public function getTac($sites=null){
+ public function getOverallStates($sites){
+ // check sites validity
+ if($sites == null || count($sites) < 1){
+ $this->responsecode = "603";
+ $this->responsemessage = "[SITES] invalid sites definition";
+ return false;
+ }
+
+ // get overall services states (HARD STATES ONLY)
+ $queryservices = array(
+ "GET services",
+ "Columns: state",
+ "Filter: state_type = 1"
+ );
- return true;
+ // get overall hosts states (HARD STATES ONLY)
+ $queryhosts = array(
+ "GET hosts",
+ "Columns: state",
+ "Filter: state_type = 1"
+ );
+
+ $failedservices = array();
+ $failedhosts = array();
+
+ $hosts=array(
+ "UP"=>0,
+ "DOWN"=>0,
+ "UNREACHABLE"=>0,
+ "ALL PROBLEMS"=>0,
+ "ALL TYPES"=>0
+ );
+
+ $services=array(
+ "OK"=>0,
+ "WARNING"=>0,
+ "CRITICAL"=>0,
+ "UNKNOWN"=>0,
+ "ALL PROBLEMS"=>0,
+ "ALL TYPES"=>0
+ );
+
+ foreach($sites as $site){
+ if(!$this->execQuery($queryservices)){
+ // one ore more sites failed to execute the query
+ // we keep a trace
+ $failedservices[$site]=array("code"=>$this->responsecode,"message"=>$this->responsemessage);
+ }else{
+ $result=json_decode($this->queryresponse);
+ foreach($result as $state){
+ switch($state[0]){
+ case "0":
+ $services["OK"]++;
+ $services["ALL TYPES"]++;
+ break;
+ case "1":
+ $services["WARNING"]++;
+ $services["ALL PROBLEMS"]++;
+ $services["ALL TYPES"]++;
+ break;
+ case "2":
+ $services["CRITICAL"]++;
+ $services["ALL PROBLEMS"]++;
+ $services["ALL TYPES"]++;
+ break;
+ case "3":
+ $services["UNKNOWN"]++;
+ $services["ALL PROBLEMS"]++;
+ $services["ALL TYPES"]++;
+ break;
+ }
+ }
+ }
+ if(!$this->execQuery($queryhosts)){
+ // one ore more sites failed to execute the query
+ // we keep a trace
+ $failedhosts[$site]=array("code"=>$this->responsecode,"message"=>$this->responsemessage);
+ }else{
+ $result=json_decode($this->queryresponse);
+ foreach($result as $state){
+ switch($state[0]){
+ case "0":
+ $hosts["UP"]++;
+ $hosts["ALL TYPES"]++;
+ break;
+ case "1":
+ $hosts["DOWN"]++;
+ $hosts["ALL PROBLEMS"]++;
+ $hosts["ALL TYPES"]++;
+ break;
+ case "2":
+ $hosts["UNREACHABLE"]++;
+ $hosts["ALL PROBLEMS"]++;
+ $hosts["ALL TYPES"]++;
+ break;
+ }
+ }
+
+ }
+ }
+ return array(
+ "hosts"=>$hosts,
+ "services"=>$services
+ );
}
+
+
}
diff --git a/examples/livestatus-documentation.php b/examples/livestatus-documentation.php
index 41e9cba..b2fbb36 100644
--- a/examples/livestatus-documentation.php
+++ b/examples/livestatus-documentation.php
@@ -1,39 +1,39 @@
<?php
// this script execute a simple livestatus query on table columns
// columns describe all of the others tables of livestatus
-require("../api/live.php");
+require_once("/var/www/frogx/api/live.php");
// live status query (each line is a row in the array)
$query = array("GET columns");
// create live object TCP with xinetd with default buffer size
// $live = new live(array("host"=>"localhost", "port"=>"6557"));
// create live object with Unix Socket
$live = new live(array("socket"=>"/opt/monitor/var/rw/live"),1024);
if(!$live){
die("Error while connecting");
}else{
//execute the query
$json = $live->execQuery($query);
if($live->responsecode != "200"){
// error
die($live->responsecode." : ".$live->responsemessage);
}
$response = json_decode($json);
echo "<table>";
foreach ($response as $line){
// line
echo "<tr>";
// header
foreach($line as $col){
echo "<td style=\"border:1px solid black\">".$col."</td>";
}
echo "</tr>";
}
echo "</table>";
}
?>
diff --git a/examples/livestatus-tac.php b/examples/livestatus-tac.php
index f3c95d9..c7dae19 100644
--- a/examples/livestatus-tac.php
+++ b/examples/livestatus-tac.php
@@ -1,7 +1,13 @@
<?php
/**
+ * get overall hosts and services states (as known as tactical overview)
* this introduce the concept of multisite. Each site is an entry in the array config["sites"]
*/
-require_once '../conf/sites.inc.php';
+require_once("/var/www/frogx/conf/sites.inc.php");
+require_once("/var/www/frogx/api/live.php");
+require_once("/var/www/frogx/api/tac.php");
+
+$tac = new tac(array("host"=>"localhost", "port"=>"6557"));
+print_r($tac->getOverallStates($config["sites"]));
?>
|
david-guenault/frogx_api
|
a35ff137bbb212687446e6acb1ffc3e0ccc7f111
|
added configuration files
|
diff --git a/conf/commands.inc.php b/conf/commands.inc.php
new file mode 100644
index 0000000..9de8894
--- /dev/null
+++ b/conf/commands.inc.php
@@ -0,0 +1,33 @@
+<?php
+$config["commands"]=array(
+ "ACKNOWLEDGE_HOST_PROBLEM"=>array("host_name","sticky","notify","persistent","author","comment"),
+ "ACKNOWLEDGE_SVC_PROBLEM"=>array("host_name","service_description","sticky","notify","persistent","author","comment"),
+ "SCHEDULE_HOST_DOWNTIME"=>array("host_name","start_time","end_time","fixed","trigger_id","duration","author","comment"),
+ "SCHEDULE_SVC_DOWNTIME"=>array("host_name","service_description","start_time","end_time","fixed","trigger_id","duration","author","comment"),
+ "SCHEDULE_HOST_SVC_DOWNTIME"=>array("host_name","start_time","end_time","fixed","trigger_id","duration","author","comment"),
+
+ "DEL_HOST_DOWNTIME"=>array("downtime_id"),
+ "DEL_SVC_DOWNTIME"=>array("downtime_id"),
+
+ "DISABLE_HOST_SVC_CHECKS"=>array("host_name"),
+
+ "DISABLE_HOST_CHECK"=>array("host_name"),
+ "ENABLE_HOST_CHECK"=>array("host_name"),
+ "DISABLE_PASSIVE_HOST_CHECKS"=>array("host_name"),
+ "ENABLE_PASSIVE_HOST_CHECKS"=>array("host_name"),
+
+ "DISABLE_SVC_CHECK"=>array("host_name","service_description"),
+ "ENABLE_SVC_CHECK"=>array("host_name","service_description"),
+ "DISABLE_PASSIVE_SVC_CHECKS"=>array("host_name","service_description"),
+ "ENABLE_PASSIVE_SVC_CHECKS"=>array("host_name","service_description"),
+
+ "ADD_HOST_COMMENT"=>array("host_name","persistent","author","comment"),
+ "ADD_SVC_COMMENT"=>array("host_name","service_description","persistent","author","comment"),
+
+ "SCHEDULE_SVC_CHECK"=>array("host_name","service_description","check_time"),
+ "SCHEDULE_FORCED_SVC_CHECK"=>array("host_name","service_description","check_time"),
+ "REMOVE_SVC_ACKNOWLEDGEMENT"=>array("host_name","service_description"),
+ "DISABLE_SVC_NOTIFICATIONS"=>array("host_name","service_description"),
+ "ENABLE_SVC_NOTIFICATIONS"=>array("host_name","service_description")
+);
+?>
diff --git a/conf/sites.inc.php b/conf/sites.inc.php
new file mode 100644
index 0000000..ec73601
--- /dev/null
+++ b/conf/sites.inc.php
@@ -0,0 +1,16 @@
+<?php
+/**
+ * This config file is used to define the nagios/shinken collectors
+ *
+ * @global array $GLOBALS['config']
+ * @name $config
+ */
+$config["sites"]=array(
+ "frogx"=>array(
+ "type"=>"TCP",
+ "address"=>"localhost",
+ "port"=>"5667"
+ )
+);
+
+?>
|
david-guenault/frogx_api
|
3c3610ae8c7ff30a019c002df4192f6cad5bc3c3
|
added working version of tac management
|
diff --git a/api/tac.php b/api/tac.php
new file mode 100644
index 0000000..9c699c1
--- /dev/null
+++ b/api/tac.php
@@ -0,0 +1,47 @@
+<?php
+/**
+ * base class to use live status implementation in shinken and nagios
+ *
+ * @package livestatusapi
+ * @author David GUENAULT ([email protected])
+ * @copyright (c) 2010 Monitoring-fr Team / Shinken Team (http://monitoring-fr.org / http://www.shinken-monitoring.org)
+ * @license Afero GPL
+ * @version 0.1
+ */
+require_once './live.php';
+
+class tac extends live{
+ /**
+ * Class Constructor
+ * @param array params array of parameters (if socket is in the keys then the connection is UNIX SOCKET else it is TCP SOCKET)
+ * @param int buffer used to read query response
+ */
+ public function __construct($params,$buffer=1024) {
+ // fucking php limitation on declaring multiple constructors !
+ if(isset($params["socket"])){
+ $this->socketpath = $params["socket"];
+ $this->buffer = $buffer;
+ }else{
+ $this->host = $params["host"];
+ $this->port = $params["port"];
+ $this->buffer = $buffer;
+ }
+ $this->getLivestatusVersion();
+ }
+ /**
+ * Class destructor
+ */
+ public function __destruc(){
+
+ }
+ /**
+ * This method get the overall status of all services and hosts. if $sites is an array of sites names it will only retrieve the tac for the specified sites.
+ * @param array $sites
+ * @return string the json encoded tac values
+ */
+ public function getTac($sites=null){
+
+ return true;
+ }
+
+}
diff --git a/examples/livestatus-tac.php b/examples/livestatus-tac.php
new file mode 100644
index 0000000..f3c95d9
--- /dev/null
+++ b/examples/livestatus-tac.php
@@ -0,0 +1,7 @@
+<?php
+/**
+ * this introduce the concept of multisite. Each site is an entry in the array config["sites"]
+ */
+require_once '../conf/sites.inc.php';
+
+?>
|
david-guenault/frogx_api
|
3aee8c358e6fc95277970e31e502aaa88cc4e73f
|
Added support for external commands, support for unix and tcp socket, fixed several bugs, added an external command example
|
diff --git a/api/live.php b/api/live.php
index 92a6789..a429d9c 100644
--- a/api/live.php
+++ b/api/live.php
@@ -1,379 +1,485 @@
<?php
/**
* base class to use live status implementation in shinken and nagios
*
* @package livestatusapi
* @author David GUENAULT ([email protected])
* @copyright (c) 2010 Monitoring-fr Team / Shinken Team (http://monitoring-fr.org / http://www.shinken-monitoring.org)
* @license Afero GPL
* @version 0.1
*/
class live {
/**
* the socket used to communicate
* @var ressource
*/
protected $socket = null;
/**
* path to the livestatus unix socket
* @var string
*/
protected $socketpath = null;
/**
* host name or ip address of the host that serve livestatus queries
* @var string
*/
protected $host = null;
/**
* TCP port of the remote host that serve livestatus queries
* @var int
*/
protected $port = null;
/**
* the socket buffer read length
* @var int
*/
protected $buffer = null;
/**
* the cahracter used to define newlines (livestatus use double newline character end of query definition)
* @var char
*/
protected $newline = "\n";
/**
* this is the version of livestatus it is automaticaly filed by the getLivestatusVersion() method
* @var string
*/
protected $livever = null;
/**
* default headersize (in bytes) returned after a livestatus query (always 16)
* @var int
*/
protected $headersize = 16;
+ /**
+ *
+ * @commands array list all authorized commands
+ */
+ protected $commands = null;
/**
* this define query options that will be added to each query (default options)
* @var array
*/
public $defaults = array(
"ColumnHeaders: on",
"ResponseHeader: fixed16",
// "KeepAlive: on",
"OutputFormat: json"
);
/**
* used to make difference between pre 1.1.3 version of livestatus return code and post 1.1.3
* @var array
*/
protected $messages = array(
"versions" => array(
"1.0.19" => "old",
"1.0.20" => "old",
"1.0.21" => "old",
"1.0.22" => "old",
"1.0.23" => "old",
"1.0.24" => "old",
"1.0.25" => "old",
"1.0.26" => "old",
"1.0.27" => "old",
"1.0.28" => "old",
"1.0.29" => "old",
"1.0.30" => "old",
"1.0.31" => "old",
"1.0.32" => "old",
"1.0.33" => "old",
"1.0.34" => "old",
"1.0.35" => "old",
"1.0.36" => "old",
"1.0.37" => "old",
"1.0.38" => "old",
"1.0.39" => "old",
"1.1.0" => "old",
"1.1.1" => "old",
"1.1.2" => "old",
"1.1.3" => "new",
"1.1.4" => "new",
"1.1.5i0" => "new",
"1.1.5i1" => "new",
"1.1.5i2" => "new",
"1.1.5i3" => "new",
"1.1.6b2" => "new",
"1.1.6b3" => "new",
"1.1.6rc1" => "new",
"1.1.6rc2" => "new",
"1.1.6rc3" => "new",
"1.1.6p1" => "new",
"1.1.7i1" => "new",
"1.1.7i2" => "new"
),
"old" => array(
"200"=>"OK. Reponse contains the queried data.",
"401"=>"The request contains an invalid header.",
"402"=>"The request is completely invalid.",
"403"=>"The request is incomplete",
"404"=>"The target of the GET has not been found (e.g. the table).",
"405"=>"A non-existing column was being referred to"
),
"new" => array(
"200"=>"OK. Reponse contains the queried data.",
"400"=>"The request contains an invalid header.",
"403"=>"The user is not authorized (see AuthHeader)",
"404"=>"The target of the GET has not been found (e.g. the table).",
"450"=>"A non-existing column was being referred to",
"451"=>"The request is incomplete.",
"452"=>"The request is completely invalid."
)
);
/**
* json response of the query
* @var string
*/
public $queryresponse = null;
/**
* response code returned after query
* @var int
*/
public $responsecode = null;
/**
* response message returned after query
*/
-
public $responsemessage = null;
/**
- * Constructor
- * @params array array of parameters
- * @buffer int buffer used to read query response
+ * Class Constructor
+ * @param array params array of parameters (if socket is in the keys then the connection is UNIX SOCKET else it is TCP SOCKET)
+ * @param int buffer used to read query response
*/
public function __construct($params,$buffer=1024)
{
+ // fucking php limitation on declaring multiple constructors !
if(isset($params["socket"])){
$this->socketpath = $params["socket"];
$this->buffer = $buffer;
}else{
$this->host = $params["host"];
$this->port = $params["port"];
$this->buffer = $buffer;
}
$this->getLivestatusVersion();
}
+ /**
+ * Class destructor
+ */
public function __destruct() {
$this->disconnect();
$this->queryresponse = null;
}
/**
* execute a livestatus query and return result as json
- * @param array query elements
- * @return string
+ * @param array $query elements of the querry (ex: array("GET services","Filter: state = 1","Filter: state = 2", "Or: 2"))
+ * @return string the json encoded result of the query
*/
public function execQuery($query){
if($this->socket){
$this->disconnect();
+ }
+ if(!$this->connect()){
+ $this->responsecode = "501";
+ $this->responsemessage="[SOCKET] ".$this->getSocketError();
+ return false;
}else{
- if(!$this->connect()){
+ if(!$this->query($query)){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
+ $this->disconnect();
return false;
}else{
- if(!$this->query($query)){
- $this->responsecode = "501";
- $this->responsemessage="[SOCKET] ".$this->getSocketError();
+ if(!$this->readresponse()){
$this->disconnect();
return false;
}else{
- if(!$this->readresponse()){
- $this->disconnect();
- return false;
- }else{
- $this->disconnect();
- return $this->queryresponse;
- }
+ $this->disconnect();
+ return $this->queryresponse;
}
}
}
}
+ /**
+ * This method submit an external command to nagios through livestatus socket.
+ * @param array $command an array describing the command array("COMMANDNAME",array("paramname"=>"value","paramname"=>"value",...)
+ * @return bool true if success false il failed
+ */
+ public function sendExternalCommand($command){
+ if(!$this->parseCommand($command)){
+ return false;
+ }else{
+ if(!$this->submitExternalCommand($command)){
+ return false;
+ }else{
+ return true;
+ }
+ }
+ }
+
+ /**
+ * load commands defined in commands.inc.php
+ */
+ public function getCommands($commands){
+ $this->commands = $commands;
+ }
+
+
/**
* PRIVATE METHODS
*/
/**
* Abstract method that choose wich connection method we should use.....
*/
private function connect(){
if(is_null($this->socketpath)){
return $this->connectTCP();
}else{
return $this->connectUNIX();
}
}
/**
* connect to livestatus through TCP.
* @return bool true if success false if fail
*/
private function connectTCP(){
$this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if( $this->socket == false){
$this->socket = false;
return false;
}
$result = @socket_connect($this->socket, $this->host,$this->port);
if ($result == false){
$this->socket = null;
return false;
}
return true;
}
private function connectUNIX(){
$this->socket = @socket_create(AF_UNIX, SOCK_STREAM, SOL_SOCKET);
if( $this->socket == false){
$this->socket = false;
return false;
}
$result = @socket_connect($this->socket, $this->socketpath);
if ($result == false){
$this->socket = null;
return false;
}
return true;
}
private function connectSSH(){
die("Not implemented");
}
private function disconnect(){
if ( ! is_null($this->socket)){
// disconnect gracefully
socket_shutdown($this->socket,2);
socket_close($this->socket);
$this->socket = null;
return true;
}else{
return false;
}
}
private function getLivestatusVersion(){
$query = array(
"GET status",
"Columns: livestatus_version",
);
$this->execQuery($query);
$result = json_decode($this->queryresponse);
$this->livever = $result[1][0];
$this->responsecode=null;
$this->responsemessage=null;
$this->queryresponse=null;
}
private function query($elements,$default="json") {
$query = $this->preparequery($elements,$default);
foreach($query as $element){
if(($this->socketwrite($element.$this->newline)) == false){
return false;
}
}
// finalize query
if(($this->socketwrite($this->newline)) == false){
return false;
}
return true;
}
private function readresponse(){
$this->queryresponse="";
if ( ! is_null( $this->socket ) ){
$headers = $this->getHeaders();
$code = $headers["statuscode"];
$size = $headers["contentlength"];
$this->responsecode = $code;
$this->responsemessage = $this->code2message($code);
if($code != "200"){
return false;
}
$this->queryresponse = $this->socketread($size);
return true;
}else{
return false;
}
}
private function code2message($code){
if ( ! isset($this->messages["versions"][$this->livever])){
// assume new
$type = "new";
}else{
$type = $this->messages["versions"][$this->livever];
}
$message = $this->messages[$type][$code];
return $message;
}
private function socketread($size){
if ( ! is_null( $this->socket ) ){
$buffer = $this->buffer;
$socketData = "";
if($size <= $buffer){
$socketData = @socket_read($this->socket,$size);
}else{
while($read = @socket_read($this->socket, $buffer)){
$socketData .= $read;
}
}
return $socketData;
}else{
return false;
}
}
private function socketwrite($data){
if ( ! is_null( $this->socket ) ){
if (socket_write($this->socket, $data) === false){
return false;
}else{
return true;
}
}else{
return false;
}
return true;
}
public function getSocketError(){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
return $errormsg;
}
private function getHeaders(){
if ( ! is_null( $this->socket ) ){
$rawHeaders = @socket_read($this->socket, $this->headersize);
return array(
"statuscode" => substr($rawHeaders, 0, 3),
"contentlength" => intval(trim(substr($rawHeaders, 4, 11)))
);
}else{
return false;
}
}
private function preparequery($elements){
$query=$this->defaults;
return array_merge((array)$elements,(array)$query);
}
+
+
+ /**
+ * This function submit an external command to the livestatus enabled host
+ * @param array $command an array defining the command array("commandname",array("argname"=>"value","argname"=>"value",...))
+ * @return bool true if success, false if failed
+ */
+ private function submitExternalCommand($command){
+ $arguments = "";
+ foreach(array_keys($command[1]) as $key){
+
+ $arguments .= $command[1][$key].";";
+ }
+ $arguments = substr($arguments, 0, strlen($arguments)-1);
+ $commandline = "COMMAND [".time()."] ".$command[0].";".$arguments;
+ if($this->socket){
+ $this->disconnect();
+ }
+ if(!$this->connect()){
+ $this->responsecode = "501";
+ $this->responsemessage="[SOCKET] ".$this->getSocketError();
+ return false;
+ }else{
+ if(!$this->query($commandline)){
+ $this->responsecode = "501";
+ $this->responsemessage="[SOCKET] ".$this->getSocketError();
+ $this->disconnect();
+ return false;
+ }else{
+ $this->responsecode = null;
+ $this->responsemessage = null;
+ return true;
+ }
+ }
+ }
+ /**
+ * This function is used to parse and validate commands before submit them.
+ * @param array $command an array defining the command array("commandname",array("argname"=>"value","argname"=>"value",...))
+ * @return bool true id ok false if not. the raison is stored in responsecode and response message class properties.
+ */
+ private function parseCommand($command){
+
+ // check if there is 2 elements in the array
+ if(count($command) != 2){
+ $this->responsecode = "602";
+ $this->responsemessage = "Invalid message definition (wrong number of entries in \$command)";
+ }else{
+ // check if first element exist as a key in commands definition
+ if(!array_key_exists($command[0], $this->commands)){
+ $this->responsecode = "602";
+ $this->responsemessage = "Invalid message definition (command ".$command[0]." not found)";
+ }else{
+ // check number of arguments against command definition
+ if(count($this->commands[$command[0]]) != count($command[1])){
+ $this->responsecode = "602";
+ $this->responsemessage = "Invalid number of arguments (required : ".count($this->commands[$command[0]]).", provided : ".count($command[1]).")";
+ }else{
+ // check argument's names
+ $defined_keys = $this->commands[$command[0]];
+ $provided_keys = array_keys($command[1]);
+ $diff_keys = array_diff($defined_keys, $provided_keys);
+ if ( count($diff_keys) > 0 ){
+ $this->responsecode = "602";
+ $this->responsemessage = "The arguments provided doesn't match the required arguments (".implode(", ", $diff_keys).")";
+ }else{
+ $this->responsecode = null;
+ $this->responsemessage = null;
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
}
diff --git a/examples/livestatus-command.php b/examples/livestatus-command.php
new file mode 100644
index 0000000..49bc3c5
--- /dev/null
+++ b/examples/livestatus-command.php
@@ -0,0 +1,30 @@
+<?php
+
+// this script send an external command to livestatus
+$base = "/var/www/frogx";
+include_once ($base."/api/live.php");
+include_once ($base."/conf/commands.inc.php");
+// live status query (each line is a row in the array)
+$command = array(
+ "DISABLE_HOST_SVC_CHECKS",
+ array("host_name"=>"localhost")
+);
+
+// create live object TCP with xinetd with default buffer size
+// $live = new live(array("host"=>"localhost", "port"=>"6557"));
+
+// create live object with Unix Socket
+$live = new live(array("socket"=>"/opt/monitor/var/rw/live"),1024);
+//load authorised external command list
+$live->getCommands($config["commands"]);
+if(!$live){
+ die("Error while connecting");
+}else{
+ //execute the command
+ if(!$live->sendExternalCommand($command)){
+ echo "[ERROR ".$live->responsecode."] ".$live->responsemessage;
+ }else{
+ echo "[SUCCESS]";
+ }
+}
+?>
|
david-guenault/frogx_api
|
4e78e1ce3d4df67e6f15d61349ba0a9a65f2436c
|
fix typo
|
diff --git a/api/live.php b/api/live.php
index 325fad9..92a6789 100644
--- a/api/live.php
+++ b/api/live.php
@@ -1,379 +1,379 @@
<?php
/**
- * base class to use live status implementation in shinken
+ * base class to use live status implementation in shinken and nagios
*
- * @package shinkenapi
+ * @package livestatusapi
* @author David GUENAULT ([email protected])
* @copyright (c) 2010 Monitoring-fr Team / Shinken Team (http://monitoring-fr.org / http://www.shinken-monitoring.org)
- * @license Affero GPL
+ * @license Afero GPL
* @version 0.1
*/
class live {
/**
* the socket used to communicate
* @var ressource
*/
protected $socket = null;
/**
* path to the livestatus unix socket
* @var string
*/
protected $socketpath = null;
/**
* host name or ip address of the host that serve livestatus queries
* @var string
*/
protected $host = null;
/**
* TCP port of the remote host that serve livestatus queries
* @var int
*/
protected $port = null;
/**
* the socket buffer read length
* @var int
*/
protected $buffer = null;
/**
* the cahracter used to define newlines (livestatus use double newline character end of query definition)
* @var char
*/
protected $newline = "\n";
/**
* this is the version of livestatus it is automaticaly filed by the getLivestatusVersion() method
* @var string
*/
protected $livever = null;
/**
* default headersize (in bytes) returned after a livestatus query (always 16)
* @var int
*/
protected $headersize = 16;
/**
* this define query options that will be added to each query (default options)
* @var array
*/
public $defaults = array(
"ColumnHeaders: on",
"ResponseHeader: fixed16",
// "KeepAlive: on",
"OutputFormat: json"
);
/**
* used to make difference between pre 1.1.3 version of livestatus return code and post 1.1.3
* @var array
*/
protected $messages = array(
"versions" => array(
"1.0.19" => "old",
"1.0.20" => "old",
"1.0.21" => "old",
"1.0.22" => "old",
"1.0.23" => "old",
"1.0.24" => "old",
"1.0.25" => "old",
"1.0.26" => "old",
"1.0.27" => "old",
"1.0.28" => "old",
"1.0.29" => "old",
"1.0.30" => "old",
"1.0.31" => "old",
"1.0.32" => "old",
"1.0.33" => "old",
"1.0.34" => "old",
"1.0.35" => "old",
"1.0.36" => "old",
"1.0.37" => "old",
"1.0.38" => "old",
"1.0.39" => "old",
"1.1.0" => "old",
"1.1.1" => "old",
"1.1.2" => "old",
"1.1.3" => "new",
"1.1.4" => "new",
"1.1.5i0" => "new",
"1.1.5i1" => "new",
"1.1.5i2" => "new",
"1.1.5i3" => "new",
"1.1.6b2" => "new",
"1.1.6b3" => "new",
"1.1.6rc1" => "new",
"1.1.6rc2" => "new",
"1.1.6rc3" => "new",
"1.1.6p1" => "new",
"1.1.7i1" => "new",
"1.1.7i2" => "new"
),
"old" => array(
"200"=>"OK. Reponse contains the queried data.",
"401"=>"The request contains an invalid header.",
"402"=>"The request is completely invalid.",
"403"=>"The request is incomplete",
"404"=>"The target of the GET has not been found (e.g. the table).",
"405"=>"A non-existing column was being referred to"
),
"new" => array(
"200"=>"OK. Reponse contains the queried data.",
"400"=>"The request contains an invalid header.",
"403"=>"The user is not authorized (see AuthHeader)",
"404"=>"The target of the GET has not been found (e.g. the table).",
"450"=>"A non-existing column was being referred to",
"451"=>"The request is incomplete.",
"452"=>"The request is completely invalid."
)
);
/**
* json response of the query
* @var string
*/
public $queryresponse = null;
/**
* response code returned after query
* @var int
*/
public $responsecode = null;
/**
* response message returned after query
*/
public $responsemessage = null;
/**
* Constructor
* @params array array of parameters
* @buffer int buffer used to read query response
*/
public function __construct($params,$buffer=1024)
{
if(isset($params["socket"])){
$this->socketpath = $params["socket"];
$this->buffer = $buffer;
}else{
$this->host = $params["host"];
$this->port = $params["port"];
$this->buffer = $buffer;
}
$this->getLivestatusVersion();
}
public function __destruct() {
$this->disconnect();
$this->queryresponse = null;
}
/**
* execute a livestatus query and return result as json
* @param array query elements
* @return string
*/
public function execQuery($query){
if($this->socket){
$this->disconnect();
}else{
if(!$this->connect()){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
return false;
}else{
if(!$this->query($query)){
$this->responsecode = "501";
$this->responsemessage="[SOCKET] ".$this->getSocketError();
$this->disconnect();
return false;
}else{
if(!$this->readresponse()){
$this->disconnect();
return false;
}else{
$this->disconnect();
return $this->queryresponse;
}
}
}
}
}
/**
* PRIVATE METHODS
*/
/**
* Abstract method that choose wich connection method we should use.....
*/
private function connect(){
if(is_null($this->socketpath)){
return $this->connectTCP();
}else{
return $this->connectUNIX();
}
}
/**
* connect to livestatus through TCP.
* @return bool true if success false if fail
*/
private function connectTCP(){
$this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if( $this->socket == false){
$this->socket = false;
return false;
}
$result = @socket_connect($this->socket, $this->host,$this->port);
if ($result == false){
$this->socket = null;
return false;
}
return true;
}
private function connectUNIX(){
$this->socket = @socket_create(AF_UNIX, SOCK_STREAM, SOL_SOCKET);
if( $this->socket == false){
$this->socket = false;
return false;
}
$result = @socket_connect($this->socket, $this->socketpath);
if ($result == false){
$this->socket = null;
return false;
}
return true;
}
private function connectSSH(){
die("Not implemented");
}
private function disconnect(){
if ( ! is_null($this->socket)){
// disconnect gracefully
socket_shutdown($this->socket,2);
socket_close($this->socket);
$this->socket = null;
return true;
}else{
return false;
}
}
private function getLivestatusVersion(){
$query = array(
"GET status",
"Columns: livestatus_version",
);
$this->execQuery($query);
$result = json_decode($this->queryresponse);
$this->livever = $result[1][0];
$this->responsecode=null;
$this->responsemessage=null;
$this->queryresponse=null;
}
private function query($elements,$default="json") {
$query = $this->preparequery($elements,$default);
foreach($query as $element){
if(($this->socketwrite($element.$this->newline)) == false){
return false;
}
}
// finalize query
if(($this->socketwrite($this->newline)) == false){
return false;
}
return true;
}
private function readresponse(){
$this->queryresponse="";
if ( ! is_null( $this->socket ) ){
$headers = $this->getHeaders();
$code = $headers["statuscode"];
$size = $headers["contentlength"];
$this->responsecode = $code;
$this->responsemessage = $this->code2message($code);
if($code != "200"){
return false;
}
$this->queryresponse = $this->socketread($size);
return true;
}else{
return false;
}
}
private function code2message($code){
if ( ! isset($this->messages["versions"][$this->livever])){
// assume new
$type = "new";
}else{
$type = $this->messages["versions"][$this->livever];
}
$message = $this->messages[$type][$code];
return $message;
}
private function socketread($size){
if ( ! is_null( $this->socket ) ){
$buffer = $this->buffer;
$socketData = "";
if($size <= $buffer){
$socketData = @socket_read($this->socket,$size);
}else{
while($read = @socket_read($this->socket, $buffer)){
$socketData .= $read;
}
}
return $socketData;
}else{
return false;
}
}
private function socketwrite($data){
if ( ! is_null( $this->socket ) ){
if (socket_write($this->socket, $data) === false){
return false;
}else{
return true;
}
}else{
return false;
}
return true;
}
public function getSocketError(){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
return $errormsg;
}
private function getHeaders(){
if ( ! is_null( $this->socket ) ){
$rawHeaders = @socket_read($this->socket, $this->headersize);
return array(
"statuscode" => substr($rawHeaders, 0, 3),
"contentlength" => intval(trim(substr($rawHeaders, 4, 11)))
);
}else{
return false;
}
}
private function preparequery($elements){
$query=$this->defaults;
return array_merge((array)$elements,(array)$query);
}
}
diff --git a/examples/livestatus-documentation.php b/examples/livestatus-documentation.php
index 283010f..41e9cba 100644
--- a/examples/livestatus-documentation.php
+++ b/examples/livestatus-documentation.php
@@ -1,37 +1,39 @@
<?php
// this script execute a simple livestatus query on table columns
// columns describe all of the others tables of livestatus
require("../api/live.php");
+// live status query (each line is a row in the array)
$query = array("GET columns");
// create live object TCP with xinetd with default buffer size
// $live = new live(array("host"=>"localhost", "port"=>"6557"));
-// create live object Unix Socket
+// create live object with Unix Socket
$live = new live(array("socket"=>"/opt/monitor/var/rw/live"),1024);
if(!$live){
die("Error while connecting");
}else{
+ //execute the query
$json = $live->execQuery($query);
if($live->responsecode != "200"){
// error
die($live->responsecode." : ".$live->responsemessage);
}
$response = json_decode($json);
echo "<table>";
foreach ($response as $line){
// line
echo "<tr>";
// header
foreach($line as $col){
echo "<td style=\"border:1px solid black\">".$col."</td>";
}
echo "</tr>";
}
echo "</table>";
}
?>
|
david-guenault/frogx_api
|
68ef6a8a132011ae86cd2de3e8db6bebe15a3d8a
|
First working version (but without commands)
|
diff --git a/api/live.php b/api/live.php
index a0f175e..325fad9 100644
--- a/api/live.php
+++ b/api/live.php
@@ -1,257 +1,379 @@
<?php
/**
* base class to use live status implementation in shinken
*
* @package shinkenapi
* @author David GUENAULT ([email protected])
* @copyright (c) 2010 Monitoring-fr Team / Shinken Team (http://monitoring-fr.org / http://www.shinken-monitoring.org)
* @license Affero GPL
* @version 0.1
*/
class live {
-
+ /**
+ * the socket used to communicate
+ * @var ressource
+ */
protected $socket = null;
+ /**
+ * path to the livestatus unix socket
+ * @var string
+ */
+ protected $socketpath = null;
+ /**
+ * host name or ip address of the host that serve livestatus queries
+ * @var string
+ */
protected $host = null;
+ /**
+ * TCP port of the remote host that serve livestatus queries
+ * @var int
+ */
protected $port = null;
+ /**
+ * the socket buffer read length
+ * @var int
+ */
protected $buffer = null;
+ /**
+ * the cahracter used to define newlines (livestatus use double newline character end of query definition)
+ * @var char
+ */
protected $newline = "\n";
+ /**
+ * this is the version of livestatus it is automaticaly filed by the getLivestatusVersion() method
+ * @var string
+ */
protected $livever = null;
+ /**
+ * default headersize (in bytes) returned after a livestatus query (always 16)
+ * @var int
+ */
protected $headersize = 16;
- // this define query options that will be added to each query (default options)
+ /**
+ * this define query options that will be added to each query (default options)
+ * @var array
+ */
public $defaults = array(
"ColumnHeaders: on",
"ResponseHeader: fixed16",
+ // "KeepAlive: on",
"OutputFormat: json"
);
- // this is used to define which error code are used
+ /**
+ * used to make difference between pre 1.1.3 version of livestatus return code and post 1.1.3
+ * @var array
+ */
protected $messages = array(
"versions" => array(
"1.0.19" => "old",
"1.0.20" => "old",
"1.0.21" => "old",
"1.0.22" => "old",
"1.0.23" => "old",
"1.0.24" => "old",
"1.0.25" => "old",
"1.0.26" => "old",
"1.0.27" => "old",
"1.0.28" => "old",
"1.0.29" => "old",
"1.0.30" => "old",
"1.0.31" => "old",
"1.0.32" => "old",
"1.0.33" => "old",
"1.0.34" => "old",
"1.0.35" => "old",
"1.0.36" => "old",
"1.0.37" => "old",
"1.0.38" => "old",
"1.0.39" => "old",
"1.1.0" => "old",
"1.1.1" => "old",
"1.1.2" => "old",
"1.1.3" => "new",
"1.1.4" => "new",
"1.1.5i0" => "new",
"1.1.5i1" => "new",
"1.1.5i2" => "new",
"1.1.5i3" => "new",
"1.1.6b2" => "new",
"1.1.6b3" => "new",
"1.1.6rc1" => "new",
"1.1.6rc2" => "new",
"1.1.6rc3" => "new",
"1.1.6p1" => "new",
"1.1.7i1" => "new",
"1.1.7i2" => "new"
),
"old" => array(
"200"=>"OK. Reponse contains the queried data.",
"401"=>"The request contains an invalid header.",
"402"=>"The request is completely invalid.",
"403"=>"The request is incomplete",
"404"=>"The target of the GET has not been found (e.g. the table).",
"405"=>"A non-existing column was being referred to"
),
"new" => array(
"200"=>"OK. Reponse contains the queried data.",
"400"=>"The request contains an invalid header.",
"403"=>"The user is not authorized (see AuthHeader)",
"404"=>"The target of the GET has not been found (e.g. the table).",
"450"=>"A non-existing column was being referred to",
"451"=>"The request is incomplete.",
"452"=>"The request is completely invalid."
)
);
+ /**
+ * json response of the query
+ * @var string
+ */
public $queryresponse = null;
- public $responsecode = null;
- public $responsemessage = null;
-
-
+ /**
+ * response code returned after query
+ * @var int
+ */
+ public $responsecode = null;
+ /**
+ * response message returned after query
+ */
+ public $responsemessage = null;
- public function __construct($host,$port,$buffer=1024)
+ /**
+ * Constructor
+ * @params array array of parameters
+ * @buffer int buffer used to read query response
+ */
+ public function __construct($params,$buffer=1024)
{
- $this->host = $host;
- $this->port = $port;
+ if(isset($params["socket"])){
+ $this->socketpath = $params["socket"];
+ $this->buffer = $buffer;
+ }else{
+ $this->host = $params["host"];
+ $this->port = $params["port"];
$this->buffer = $buffer;
- $this->getLivestatusVersion();
+ }
+ $this->getLivestatusVersion();
}
public function __destruct() {
$this->disconnect();
$this->queryresponse = null;
}
- public function connect(){
+
+ /**
+ * execute a livestatus query and return result as json
+ * @param array query elements
+ * @return string
+ */
+ public function execQuery($query){
+ if($this->socket){
+ $this->disconnect();
+ }else{
+ if(!$this->connect()){
+ $this->responsecode = "501";
+ $this->responsemessage="[SOCKET] ".$this->getSocketError();
+ return false;
+ }else{
+ if(!$this->query($query)){
+ $this->responsecode = "501";
+ $this->responsemessage="[SOCKET] ".$this->getSocketError();
+ $this->disconnect();
+ return false;
+ }else{
+ if(!$this->readresponse()){
+ $this->disconnect();
+ return false;
+ }else{
+ $this->disconnect();
+ return $this->queryresponse;
+ }
+ }
+ }
+ }
+ }
+
+/**
+ * PRIVATE METHODS
+ */
+
+ /**
+ * Abstract method that choose wich connection method we should use.....
+ */
+ private function connect(){
+ if(is_null($this->socketpath)){
+ return $this->connectTCP();
+ }else{
+ return $this->connectUNIX();
+ }
+ }
+ /**
+ * connect to livestatus through TCP.
+ * @return bool true if success false if fail
+ */
+ private function connectTCP(){
$this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if( $this->socket == false){
$this->socket = false;
return false;
}
$result = @socket_connect($this->socket, $this->host,$this->port);
if ($result == false){
$this->socket = null;
return false;
}
return true;
- }
+ }
- public function disconnect(){
+ private function connectUNIX(){
+ $this->socket = @socket_create(AF_UNIX, SOCK_STREAM, SOL_SOCKET);
+ if( $this->socket == false){
+ $this->socket = false;
+ return false;
+ }
+ $result = @socket_connect($this->socket, $this->socketpath);
+ if ($result == false){
+ $this->socket = null;
+ return false;
+ }
+ return true;
+ }
+
+ private function connectSSH(){
+ die("Not implemented");
+ }
+
+
+ private function disconnect(){
if ( ! is_null($this->socket)){
// disconnect gracefully
socket_shutdown($this->socket,2);
socket_close($this->socket);
$this->socket = null;
return true;
}else{
return false;
}
}
- public function query($elements,$default="json") {
+ private function getLivestatusVersion(){
+ $query = array(
+ "GET status",
+ "Columns: livestatus_version",
+ );
+ $this->execQuery($query);
+ $result = json_decode($this->queryresponse);
+
+ $this->livever = $result[1][0];
+ $this->responsecode=null;
+ $this->responsemessage=null;
+ $this->queryresponse=null;
+ }
+
+ private function query($elements,$default="json") {
$query = $this->preparequery($elements,$default);
foreach($query as $element){
if(($this->socketwrite($element.$this->newline)) == false){
return false;
}
}
// finalize query
if(($this->socketwrite($this->newline)) == false){
return false;
}
return true;
}
- public function readresponse(){
+ private function readresponse(){
$this->queryresponse="";
if ( ! is_null( $this->socket ) ){
$headers = $this->getHeaders();
$code = $headers["statuscode"];
$size = $headers["contentlength"];
$this->responsecode = $code;
$this->responsemessage = $this->code2message($code);
- if($code != "200"){
- return false;
+ if($code != "200"){
+ return false;
}
$this->queryresponse = $this->socketread($size);
return true;
}else{
return false;
}
}
-/**
- * PRIVATE METHODS
- */
-
- private function getLivestatusVersion(){
- $query = array(
- "GET status",
- "Columns: livestatus_version",
- );
- $this->connect();
- $this->query($query);
- $this->readresponse();
- $this->disconnect();
- $result = json_decode($this->queryresponse);
- $this->livever = $result[1][0];
- }
-
private function code2message($code){
if ( ! isset($this->messages["versions"][$this->livever])){
// assume new
$type = "new";
}else{
$type = $this->messages["versions"][$this->livever];
}
$message = $this->messages[$type][$code];
return $message;
}
private function socketread($size){
if ( ! is_null( $this->socket ) ){
$buffer = $this->buffer;
$socketData = "";
if($size <= $buffer){
$socketData = @socket_read($this->socket,$size);
}else{
while($read = @socket_read($this->socket, $buffer)){
$socketData .= $read;
}
}
return $socketData;
}else{
return false;
}
}
private function socketwrite($data){
if ( ! is_null( $this->socket ) ){
if (socket_write($this->socket, $data) === false){
return false;
}else{
return true;
}
}else{
return false;
}
return true;
}
public function getSocketError(){
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
- return array(
- "code"=>$errorcode,
- "message"=>$errormsg
- );
+ return $errormsg;
}
private function getHeaders(){
if ( ! is_null( $this->socket ) ){
$rawHeaders = @socket_read($this->socket, $this->headersize);
return array(
"statuscode" => substr($rawHeaders, 0, 3),
"contentlength" => intval(trim(substr($rawHeaders, 4, 11)))
);
}else{
return false;
}
}
private function preparequery($elements){
$query=$this->defaults;
return array_merge((array)$elements,(array)$query);
}
}
diff --git a/examples/livestatus-documentation.php b/examples/livestatus-documentation.php
index d07e478..283010f 100644
--- a/examples/livestatus-documentation.php
+++ b/examples/livestatus-documentation.php
@@ -1,46 +1,37 @@
<?php
// this script execute a simple livestatus query on table columns
// columns describe all of the others tables of livestatus
require("../api/live.php");
-$query = array("GET colmmumns");
+$query = array("GET columns");
-// create live object
-$live = new live("localhost", "6557");
-// connect
-if ( ! $live->connect() ){
- die("Unable to connect");
+// create live object TCP with xinetd with default buffer size
+// $live = new live(array("host"=>"localhost", "port"=>"6557"));
+
+// create live object Unix Socket
+$live = new live(array("socket"=>"/opt/monitor/var/rw/live"),1024);
+
+if(!$live){
+ die("Error while connecting");
}else{
- // query nagios/shinken data
- if (!$live->query($query)){
- die("Query Error");
- }else{
- if($live->responsecode != "200"){
- die("QUERY : ".$live->responsemessage." (".$live->responsecode.")");
- }else{
- // read response after query
- if (!$live->readresponse()){
- die("Response Error");
- }else{
- // disconnect from livestatus socket
- $live->disconnect();
- // use data
- $response = json_decode($live->queryresponse);
- echo "<table>";
- foreach ($response as $line){
- // line
- echo "<tr>";
- // header
- foreach($line as $col){
- echo "<td style=\"border:1px solid black\">".$col."</td>";
- }
- echo "</tr>";
- }
- echo "</table>";
- }
- }
- }
+ $json = $live->execQuery($query);
+ if($live->responsecode != "200"){
+ // error
+ die($live->responsecode." : ".$live->responsemessage);
+ }
+ $response = json_decode($json);
+ echo "<table>";
+ foreach ($response as $line){
+ // line
+ echo "<tr>";
+ // header
+ foreach($line as $col){
+ echo "<td style=\"border:1px solid black\">".$col."</td>";
+ }
+ echo "</tr>";
+ }
+ echo "</table>";
}
?>
|
david-guenault/frogx_api
|
26d66ee7ae1e51fc40b1e788df99b349640608ff
|
First import
|
diff --git a/api/live.php b/api/live.php
new file mode 100644
index 0000000..a0f175e
--- /dev/null
+++ b/api/live.php
@@ -0,0 +1,257 @@
+<?php
+/**
+ * base class to use live status implementation in shinken
+ *
+ * @package shinkenapi
+ * @author David GUENAULT ([email protected])
+ * @copyright (c) 2010 Monitoring-fr Team / Shinken Team (http://monitoring-fr.org / http://www.shinken-monitoring.org)
+ * @license Affero GPL
+ * @version 0.1
+ */
+class live {
+
+ protected $socket = null;
+ protected $host = null;
+ protected $port = null;
+ protected $buffer = null;
+ protected $newline = "\n";
+ protected $livever = null;
+ protected $headersize = 16;
+ // this define query options that will be added to each query (default options)
+ public $defaults = array(
+ "ColumnHeaders: on",
+ "ResponseHeader: fixed16",
+ "OutputFormat: json"
+ );
+ // this is used to define which error code are used
+ protected $messages = array(
+ "versions" => array(
+ "1.0.19" => "old",
+ "1.0.20" => "old",
+ "1.0.21" => "old",
+ "1.0.22" => "old",
+ "1.0.23" => "old",
+ "1.0.24" => "old",
+ "1.0.25" => "old",
+ "1.0.26" => "old",
+ "1.0.27" => "old",
+ "1.0.28" => "old",
+ "1.0.29" => "old",
+ "1.0.30" => "old",
+ "1.0.31" => "old",
+ "1.0.32" => "old",
+ "1.0.33" => "old",
+ "1.0.34" => "old",
+ "1.0.35" => "old",
+ "1.0.36" => "old",
+ "1.0.37" => "old",
+ "1.0.38" => "old",
+ "1.0.39" => "old",
+ "1.1.0" => "old",
+ "1.1.1" => "old",
+ "1.1.2" => "old",
+ "1.1.3" => "new",
+ "1.1.4" => "new",
+ "1.1.5i0" => "new",
+ "1.1.5i1" => "new",
+ "1.1.5i2" => "new",
+ "1.1.5i3" => "new",
+ "1.1.6b2" => "new",
+ "1.1.6b3" => "new",
+ "1.1.6rc1" => "new",
+ "1.1.6rc2" => "new",
+ "1.1.6rc3" => "new",
+ "1.1.6p1" => "new",
+ "1.1.7i1" => "new",
+ "1.1.7i2" => "new"
+ ),
+ "old" => array(
+ "200"=>"OK. Reponse contains the queried data.",
+ "401"=>"The request contains an invalid header.",
+ "402"=>"The request is completely invalid.",
+ "403"=>"The request is incomplete",
+ "404"=>"The target of the GET has not been found (e.g. the table).",
+ "405"=>"A non-existing column was being referred to"
+ ),
+ "new" => array(
+ "200"=>"OK. Reponse contains the queried data.",
+ "400"=>"The request contains an invalid header.",
+ "403"=>"The user is not authorized (see AuthHeader)",
+ "404"=>"The target of the GET has not been found (e.g. the table).",
+ "450"=>"A non-existing column was being referred to",
+ "451"=>"The request is incomplete.",
+ "452"=>"The request is completely invalid."
+ )
+ );
+
+
+ public $queryresponse = null;
+ public $responsecode = null;
+ public $responsemessage = null;
+
+
+
+
+ public function __construct($host,$port,$buffer=1024)
+ {
+ $this->host = $host;
+ $this->port = $port;
+ $this->buffer = $buffer;
+ $this->getLivestatusVersion();
+ }
+
+ public function __destruct() {
+ $this->disconnect();
+ $this->queryresponse = null;
+ }
+
+ public function connect(){
+ $this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
+ if( $this->socket == false){
+ $this->socket = false;
+ return false;
+ }
+ $result = @socket_connect($this->socket, $this->host,$this->port);
+ if ($result == false){
+ $this->socket = null;
+ return false;
+ }
+ return true;
+ }
+
+ public function disconnect(){
+ if ( ! is_null($this->socket)){
+ // disconnect gracefully
+ socket_shutdown($this->socket,2);
+ socket_close($this->socket);
+ $this->socket = null;
+ return true;
+ }else{
+ return false;
+ }
+
+ }
+
+ public function query($elements,$default="json") {
+ $query = $this->preparequery($elements,$default);
+ foreach($query as $element){
+ if(($this->socketwrite($element.$this->newline)) == false){
+ return false;
+ }
+ }
+ // finalize query
+ if(($this->socketwrite($this->newline)) == false){
+ return false;
+ }
+ return true;
+ }
+
+
+ public function readresponse(){
+ $this->queryresponse="";
+
+ if ( ! is_null( $this->socket ) ){
+ $headers = $this->getHeaders();
+ $code = $headers["statuscode"];
+ $size = $headers["contentlength"];
+
+ $this->responsecode = $code;
+ $this->responsemessage = $this->code2message($code);
+ if($code != "200"){
+ return false;
+ }
+ $this->queryresponse = $this->socketread($size);
+ return true;
+ }else{
+ return false;
+ }
+ }
+
+
+/**
+ * PRIVATE METHODS
+ */
+
+ private function getLivestatusVersion(){
+ $query = array(
+ "GET status",
+ "Columns: livestatus_version",
+ );
+ $this->connect();
+ $this->query($query);
+ $this->readresponse();
+ $this->disconnect();
+ $result = json_decode($this->queryresponse);
+ $this->livever = $result[1][0];
+ }
+
+ private function code2message($code){
+ if ( ! isset($this->messages["versions"][$this->livever])){
+ // assume new
+ $type = "new";
+ }else{
+ $type = $this->messages["versions"][$this->livever];
+ }
+ $message = $this->messages[$type][$code];
+ return $message;
+ }
+
+
+
+
+ private function socketread($size){
+ if ( ! is_null( $this->socket ) ){
+ $buffer = $this->buffer;
+ $socketData = "";
+ if($size <= $buffer){
+ $socketData = @socket_read($this->socket,$size);
+ }else{
+ while($read = @socket_read($this->socket, $buffer)){
+ $socketData .= $read;
+ }
+ }
+ return $socketData;
+ }else{
+ return false;
+ }
+ }
+
+ private function socketwrite($data){
+ if ( ! is_null( $this->socket ) ){
+ if (socket_write($this->socket, $data) === false){
+ return false;
+ }else{
+ return true;
+ }
+ }else{
+ return false;
+ }
+ return true;
+ }
+
+ public function getSocketError(){
+ $errorcode = socket_last_error();
+ $errormsg = socket_strerror($errorcode);
+ return array(
+ "code"=>$errorcode,
+ "message"=>$errormsg
+ );
+ }
+
+ private function getHeaders(){
+ if ( ! is_null( $this->socket ) ){
+ $rawHeaders = @socket_read($this->socket, $this->headersize);
+ return array(
+ "statuscode" => substr($rawHeaders, 0, 3),
+ "contentlength" => intval(trim(substr($rawHeaders, 4, 11)))
+ );
+ }else{
+ return false;
+ }
+ }
+
+ private function preparequery($elements){
+ $query=$this->defaults;
+ return array_merge((array)$elements,(array)$query);
+ }
+}
diff --git a/examples/livestatus-documentation.php b/examples/livestatus-documentation.php
new file mode 100644
index 0000000..d07e478
--- /dev/null
+++ b/examples/livestatus-documentation.php
@@ -0,0 +1,46 @@
+<?php
+
+// this script execute a simple livestatus query on table columns
+// columns describe all of the others tables of livestatus
+
+require("../api/live.php");
+
+$query = array("GET colmmumns");
+
+// create live object
+$live = new live("localhost", "6557");
+// connect
+if ( ! $live->connect() ){
+ die("Unable to connect");
+}else{
+ // query nagios/shinken data
+ if (!$live->query($query)){
+ die("Query Error");
+ }else{
+ if($live->responsecode != "200"){
+ die("QUERY : ".$live->responsemessage." (".$live->responsecode.")");
+ }else{
+ // read response after query
+ if (!$live->readresponse()){
+ die("Response Error");
+ }else{
+ // disconnect from livestatus socket
+ $live->disconnect();
+ // use data
+ $response = json_decode($live->queryresponse);
+ echo "<table>";
+ foreach ($response as $line){
+ // line
+ echo "<tr>";
+ // header
+ foreach($line as $col){
+ echo "<td style=\"border:1px solid black\">".$col."</td>";
+ }
+ echo "</tr>";
+ }
+ echo "</table>";
+ }
+ }
+ }
+}
+?>
|
rngtng/nups
|
463ba6f2244806670079057693a3e27d8b00910e
|
clean queue before each spec
|
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 3df96f5..a3714eb 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,56 +1,57 @@
require 'simplecov'
SimpleCov.start 'rails' if ENV["COV"]
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
# https://github.com/jnicklas/capybara
# http://jumpstartlab.com/resources/testing-ruby/integration-testing-with-rspec-capybara-and-selenium/
# http://opinionatedprogrammer.com/2011/02/capybara-and-selenium-with-rspec-and-rails-3/
# http://railscasts.com/episodes/257-request-specs-and-capybara?view=asciicast
# http://jfire.posterous.com/selenium-on-ruby
# http://seleniumhq.wordpress.com/
# Load Capybara integration
require 'capybara/rspec'
require 'capybara/rails'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.include Delorean
config.include FactoryGirl::Syntax::Methods
# == Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
config.mock_with :rspec
# Remove this line if you're not using Active Record or Active Record fixtures
config.fixture_path = "#{::Rails.root.to_s}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = false #true
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
#DatabaseCleaner.clean_with(:truncation)
end
config.before :each do
+ ResqueSpec.reset!
DatabaseCleaner.start
end
config.after :each do
DatabaseCleaner.clean
end
end
|
rngtng/nups
|
e852813c77cb9403790cca6b4d59843ad7d15886
|
rails upgrade, gem update, fixed deprecation warnings
|
diff --git a/Gemfile b/Gemfile
index 4e0cfc2..aa6f093 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,81 +1,81 @@
source 'http://rubygems.org'
-gem 'rails', '~> 3.2.3'
+gem 'rails', '~> 3.2.5'
gem 'mysql2'
gem 'jquery-rails'
gem 'haml'
#Authorization
gem "devise"
# Use resque for async jobs
gem 'resque'
gem 'resque-scheduler', '~> 2.0.0.h'
gem 'resque-jobs-per-fork'
#For handling File uploads
gem 'paperclip'
#For proper pagination
gem 'kaminari'
# For excel export
gem 'ekuseru'
# parsing bounce emails
gem 'bounce_email'
gem 'state_machine'
gem 'nokogiri'
gem 'premailer'
gem 'rpm_contrib'
gem 'newrelic_rpm'
gem 'airbrake'
# auto_link replacement
gem 'rinku'
gem 'annotate', :git => 'git://github.com/ctran/annotate_models.git'
gem 'rspec-rails', :group => [:development, :test]
gem 'spin', :group => [:development, :test]
group :development do
gem 'capistrano'
gem 'mailcatcher'
gem 'ruby-graphviz', :require => 'graphviz'
end
# http://metaskills.net/2011/07/29/use-compass-sass-framework-files-with-the-rails-3.1.0.rc5-asset-pipeline/
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails'
# gem 'compass', :git => 'git://github.com/chriseppstein/compass.git', :branch => 'rails31'
end
group :test do
gem 'json' #needed for resque to run on travis-ci
gem 'resque_spec'
gem 'delorean'
#selenium
gem 'capybara'
gem 'database_cleaner'
#fixtures
gem 'faker'
gem 'factory_girl_rails'
gem 'watchr'
gem 'simplecov'
end
diff --git a/Gemfile.lock b/Gemfile.lock
index 49e866c..6f4b88b 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,304 +1,305 @@
GIT
remote: git://github.com/ctran/annotate_models.git
- revision: ff1131daee8c03dbcc4966b7914b77a7e3a62f02
+ revision: 9ed9a56d72d4bbc49667688c485cc2d034976710
specs:
- annotate (2.4.1.beta1)
+ annotate (2.5.0.pre1)
+ rake
GEM
remote: http://rubygems.org/
specs:
- actionmailer (3.2.3)
- actionpack (= 3.2.3)
+ actionmailer (3.2.5)
+ actionpack (= 3.2.5)
mail (~> 2.4.4)
- actionpack (3.2.3)
- activemodel (= 3.2.3)
- activesupport (= 3.2.3)
+ actionpack (3.2.5)
+ activemodel (= 3.2.5)
+ activesupport (= 3.2.5)
builder (~> 3.0.0)
erubis (~> 2.7.0)
journey (~> 1.0.1)
rack (~> 1.4.0)
rack-cache (~> 1.2)
rack-test (~> 0.6.1)
- sprockets (~> 2.1.2)
- activemodel (3.2.3)
- activesupport (= 3.2.3)
+ sprockets (~> 2.1.3)
+ activemodel (3.2.5)
+ activesupport (= 3.2.5)
builder (~> 3.0.0)
- activerecord (3.2.3)
- activemodel (= 3.2.3)
- activesupport (= 3.2.3)
+ activerecord (3.2.5)
+ activemodel (= 3.2.5)
+ activesupport (= 3.2.5)
arel (~> 3.0.2)
tzinfo (~> 0.3.29)
- activeresource (3.2.3)
- activemodel (= 3.2.3)
- activesupport (= 3.2.3)
- activesupport (3.2.3)
+ activeresource (3.2.5)
+ activemodel (= 3.2.5)
+ activesupport (= 3.2.5)
+ activesupport (3.2.5)
i18n (~> 0.6)
multi_json (~> 1.0)
- addressable (2.2.7)
- airbrake (3.0.9)
+ addressable (2.2.8)
+ airbrake (3.1.1)
activesupport
builder
arel (3.0.2)
bcrypt-ruby (3.0.1)
bounce_email (0.2.2)
mail
builder (3.0.0)
capistrano (2.12.0)
highline
net-scp (>= 1.0.0)
net-sftp (>= 2.0.0)
net-ssh (>= 2.0.14)
net-ssh-gateway (>= 1.1.0)
capybara (1.1.2)
mime-types (>= 1.16)
nokogiri (>= 1.3.3)
rack (>= 1.0.0)
rack-test (>= 0.5.4)
selenium-webdriver (~> 2.0)
xpath (~> 0.1.4)
childprocess (0.3.2)
ffi (~> 1.0.6)
chronic (0.6.7)
cocaine (0.2.1)
coffee-rails (3.2.2)
coffee-script (>= 2.2.0)
railties (~> 3.2.0)
coffee-script (2.2.0)
coffee-script-source
execjs
- coffee-script-source (1.3.1)
+ coffee-script-source (1.3.3)
css_parser (1.2.6)
addressable
rdoc
daemons (1.1.8)
- database_cleaner (0.7.2)
+ database_cleaner (0.8.0)
delorean (1.2.0)
chronic
- devise (2.0.4)
+ devise (2.1.0)
bcrypt-ruby (~> 3.0)
- orm_adapter (~> 0.0.3)
+ orm_adapter (~> 0.0.7)
railties (~> 3.1)
warden (~> 1.1.1)
diff-lcs (1.1.3)
ekuseru (0.3.10)
rails (>= 3.0)
spreadsheet (>= 0.6)
erubis (2.7.0)
eventmachine (0.12.10)
- execjs (1.3.0)
+ execjs (1.4.0)
multi_json (~> 1.0)
- factory_girl (3.1.1)
+ factory_girl (3.3.0)
activesupport (>= 3.0.0)
- factory_girl_rails (3.1.0)
- factory_girl (~> 3.1.0)
+ factory_girl_rails (3.3.0)
+ factory_girl (~> 3.3.0)
railties (>= 3.0.0)
faker (1.0.1)
i18n (~> 0.4)
ffi (1.0.11)
- haml (3.1.4)
- highline (1.6.11)
+ haml (3.1.6)
+ highline (1.6.12)
hike (1.2.1)
htmlentities (4.3.1)
i18n (0.6.0)
journey (1.0.3)
jquery-rails (2.0.2)
railties (>= 3.2.0, < 5.0)
thor (~> 0.14)
- json (1.6.6)
+ json (1.7.3)
kaminari (0.13.0)
actionpack (>= 3.0.0)
activesupport (>= 3.0.0)
railties (>= 3.0.0)
libwebsocket (0.1.3)
addressable
mail (2.4.4)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
mailcatcher (0.5.6)
activesupport (~> 3.0)
eventmachine (~> 0.12)
haml (~> 3.1)
mail (~> 2.3)
sinatra (~> 1.2)
skinny (~> 0.2)
sqlite3 (~> 1.3)
thin (~> 1.2)
mime-types (1.18)
- multi_json (1.3.2)
+ multi_json (1.3.6)
mysql2 (0.3.11)
net-scp (1.0.4)
net-ssh (>= 1.99.1)
net-sftp (2.0.5)
net-ssh (>= 2.0.9)
- net-ssh (2.3.0)
+ net-ssh (2.5.2)
net-ssh-gateway (1.1.0)
net-ssh (>= 1.99.1)
- newrelic_rpm (3.3.4)
- nokogiri (1.5.2)
+ newrelic_rpm (3.3.5)
+ nokogiri (1.5.3)
orm_adapter (0.0.7)
- paperclip (3.0.2)
+ paperclip (3.0.4)
activemodel (>= 3.0.0)
activerecord (>= 3.0.0)
activesupport (>= 3.0.0)
cocaine (>= 0.0.2)
mime-types
polyglot (0.3.3)
premailer (1.7.3)
css_parser (>= 1.1.9)
htmlentities (>= 4.0.0)
rack (1.4.1)
rack-cache (1.2)
rack (>= 0.4)
rack-protection (1.2.0)
rack
rack-ssl (1.3.2)
rack
rack-test (0.6.1)
rack (>= 1.0)
- rails (3.2.3)
- actionmailer (= 3.2.3)
- actionpack (= 3.2.3)
- activerecord (= 3.2.3)
- activeresource (= 3.2.3)
- activesupport (= 3.2.3)
+ rails (3.2.5)
+ actionmailer (= 3.2.5)
+ actionpack (= 3.2.5)
+ activerecord (= 3.2.5)
+ activeresource (= 3.2.5)
+ activesupport (= 3.2.5)
bundler (~> 1.0)
- railties (= 3.2.3)
- railties (3.2.3)
- actionpack (= 3.2.3)
- activesupport (= 3.2.3)
+ railties (= 3.2.5)
+ railties (3.2.5)
+ actionpack (= 3.2.5)
+ activesupport (= 3.2.5)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
- thor (~> 0.14.6)
+ thor (>= 0.14.6, < 2.0)
rake (0.9.2.2)
rdoc (3.12)
json (~> 1.4)
redis (2.2.2)
redis-namespace (1.0.3)
redis (< 3.0.0)
resque (1.20.0)
multi_json (~> 1.0)
redis-namespace (~> 1.0.2)
sinatra (>= 0.9.2)
vegas (~> 0.1.2)
resque-jobs-per-fork (1.15.1)
resque (~> 1.15)
resque-scheduler (2.0.0.h)
redis (>= 2.0.1)
resque (>= 1.19.0)
rufus-scheduler
- resque_spec (0.10.0)
+ resque_spec (0.12.1)
resque (>= 1.19.0)
rspec (>= 2.5.0)
rinku (1.5.1)
- rpm_contrib (2.1.8)
+ rpm_contrib (2.1.11)
newrelic_rpm (>= 3.1.1)
newrelic_rpm (>= 3.1.1)
- rspec (2.9.0)
- rspec-core (~> 2.9.0)
- rspec-expectations (~> 2.9.0)
- rspec-mocks (~> 2.9.0)
- rspec-core (2.9.0)
- rspec-expectations (2.9.1)
+ rspec (2.10.0)
+ rspec-core (~> 2.10.0)
+ rspec-expectations (~> 2.10.0)
+ rspec-mocks (~> 2.10.0)
+ rspec-core (2.10.1)
+ rspec-expectations (2.10.0)
diff-lcs (~> 1.1.3)
- rspec-mocks (2.9.0)
- rspec-rails (2.9.0)
+ rspec-mocks (2.10.1)
+ rspec-rails (2.10.1)
actionpack (>= 3.0)
activesupport (>= 3.0)
railties (>= 3.0)
- rspec (~> 2.9.0)
+ rspec (~> 2.10.0)
ruby-graphviz (1.0.5)
ruby-ole (1.2.11.3)
- rubyzip (0.9.7)
+ rubyzip (0.9.8)
rufus-scheduler (2.0.16)
tzinfo (>= 0.3.23)
- sass (3.1.16)
+ sass (3.1.19)
sass-rails (3.2.5)
railties (~> 3.2.0)
sass (>= 3.1.10)
tilt (~> 1.3)
- selenium-webdriver (2.21.2)
+ selenium-webdriver (2.22.2)
childprocess (>= 0.2.5)
ffi (~> 1.0)
libwebsocket (~> 0.1.3)
multi_json (~> 1.0)
rubyzip
- simplecov (0.6.2)
- multi_json (~> 1.3)
+ simplecov (0.6.4)
+ multi_json (~> 1.0)
simplecov-html (~> 0.5.3)
simplecov-html (0.5.3)
sinatra (1.3.2)
rack (~> 1.3, >= 1.3.6)
rack-protection (~> 1.2)
tilt (~> 1.3, >= 1.3.3)
skinny (0.2.0)
eventmachine (~> 0.12)
thin (~> 1.2)
- spin (0.4.5)
- spreadsheet (0.6.8)
+ spin (0.4.6)
+ spreadsheet (0.7.1)
ruby-ole (>= 1.0)
- sprockets (2.1.2)
+ sprockets (2.1.3)
hike (~> 1.2)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sqlite3 (1.3.6)
state_machine (1.1.2)
thin (1.3.1)
daemons (>= 1.0.9)
eventmachine (>= 0.12.6)
rack (>= 1.0.0)
- thor (0.14.6)
+ thor (0.15.2)
tilt (1.3.3)
treetop (1.4.10)
polyglot
polyglot (>= 0.3.1)
tzinfo (0.3.33)
vegas (0.1.11)
rack (>= 1.0.0)
warden (1.1.1)
rack (>= 1.0)
watchr (0.7)
xpath (0.1.4)
nokogiri (~> 1.3)
PLATFORMS
ruby
DEPENDENCIES
airbrake
annotate!
bounce_email
capistrano
capybara
coffee-rails
database_cleaner
delorean
devise
ekuseru
factory_girl_rails
faker
haml
jquery-rails
json
kaminari
mailcatcher
mysql2
newrelic_rpm
nokogiri
paperclip
premailer
- rails (~> 3.2.3)
+ rails (~> 3.2.5)
resque
resque-jobs-per-fork
resque-scheduler (~> 2.0.0.h)
resque_spec
rinku
rpm_contrib
rspec-rails
ruby-graphviz
sass-rails (~> 3.2.3)
simplecov
spin
state_machine
watchr
diff --git a/app/models/live_send_out.rb b/app/models/live_send_out.rb
index 0ba945c..de30afc 100644
--- a/app/models/live_send_out.rb
+++ b/app/models/live_send_out.rb
@@ -1,62 +1,64 @@
class LiveSendOut < SendOut
+ attr_accessible :recipient
+
validates :recipient_id, :presence => true, :uniqueness => {:scope => [:newsletter_id, :type]}, :on => :create
before_validation :set_email, :on => :create
state_machine :initial => :sheduled do
before_transition :delivering => :finished do |me|
me.finished_at = Time.now
me.recipient.update_attribute(:deliveries_count, me.recipient.deliveries_count + 1)
end
before_transition :delivering => :failed do |me, transition|
me.error_message = transition.args[0].message
me.recipient.update_attribute(:fails_count, me.recipient.fails_count + 1)
end
after_transition :delivering => :failed do |me, transition|
# a bit dirty hack: force to end transition successfull but still
# propagade execption
me.connection.execute("COMMIT") #prevent rollback
Airbrake.notify(transition.args[0], :params => { :id => self.id })
raise transition.args[0]
end
before_transition :finished => :read do |me|
me.recipient.update_attribute(:reads_count, me.recipient.reads_count + 1)
end
before_transition :finished => :bounced do |me, transition|
me.error_message = transition.args[0]
me.recipient.update_attribute(:bounces_count, me.recipient.bounces_count + 1)
end
end
def issue_id
["ma", self.id, self.recipient_id].join('-')
end
private
def set_email
self.email = recipient.email
end
end
# == Schema Information
#
# Table name: send_outs
#
# id :integer(4) not null, primary key
# recipient_id :integer(4)
# newsletter_id :integer(4)
# type :string(255)
# state :string(255)
# email :string(255)
# error_message :text
# created_at :datetime
# updated_at :datetime
# finished_at :datetime
#
# updated_at :datetime
diff --git a/app/models/newsletter.rb b/app/models/newsletter.rb
index af85154..3579f6d 100644
--- a/app/models/newsletter.rb
+++ b/app/models/newsletter.rb
@@ -1,215 +1,220 @@
class Newsletter < ActiveRecord::Base
QUEUE = :nups_newsletter
HEADER_ID = "X-MA-Id"
belongs_to :account
has_many :recipients, :through => :account, :conditions => { 'recipients.state' => :confirmed }
has_many :attachments, :class_name => 'Asset'
# http://stackoverflow.com/questions/738906/rails-dependent-and-delete
has_many :send_outs, :dependent => :delete_all #send_out has no dependency, speed it up
has_many :live_send_outs
has_many :test_send_outs
scope :with_account, lambda { |account| account ? where(:account_id => account.id) : {} }
+ attr_accessible :draft, :account, :subject, :content, :mode, :status, :last_sent_id, :recipients_count
+ attr_accessible :deliveries_count, :fails_count, :deliver_at, :delivery_started_at, :delivery_ended_at
+ attr_accessible :account_id, :created_at, :updated_at, :state, :bounces_count, :reads_count
+ attr_accessible :attachment_ids, :recipient
+
validates :account_id, :presence => true
validates :subject, :presence => true
before_create :set_recipients_count
########################################################################################################################
state_machine :initial => :new do
event :send_test do
transition :new => :pre_testing
transition :tested => :pre_testing
end
event :send_live do
transition :tested => :pre_sending
transition :stopped => :pre_sending
end
event :process do
transition :pre_testing => :testing
transition :pre_sending => :sending
end
event :stop do
transition :sending => :stopping
transition :testing => :new
end
event :finish do
transition :sending => :finished
transition :testing => :tested
transition :stopping => :stopped
end
after_transition all => :pre_testing do |me, transition|
Resque.enqueue(me.class, me.id, "_send_test!", transition.args[0])
end
after_transition :tested => :pre_sending do |me|
if me.deliver_at && me.deliver_at > Time.now
Resque.enqueue_at(me.deliver_at, me.class, me.id, "_send_live!")
else
Resque.enqueue(me.class, me.id, "_send_live!")
end
end
after_transition :stopped => :pre_sending do |me|
Resque.enqueue(me.class, me.id, "_resume_live!")
end
before_transition :pre_sending => :sending do |me|
me.recipients_count = me.live_send_outs.count #TODO what if stopped??
end
before_transition :sending => :finished do |me|
me.delivery_ended_at = me.live_send_outs.first(:select => "finished_at", :order => "finished_at DESC").try(:finished_at)
end
after_transition all => :stopping do |me|
Resque.enqueue(me.class, me.id, "_stop!")
end
end
########################################################################################################################
def self.queue
QUEUE
end
def self.perform(id, action, email = nil)
# self.connection.verify! # ActiveRecord::Base.verify_active_connections!
self.find(id).send(action, email)
end
########################################################################################################################
def route
[self.account, self]
end
def attachment_ids=(attachment_ids)
self.attachments.clear
attachment_ids.each do |attachment_id|
if attachment_id.present? && (asset = account.assets.find_by_id(attachment_id))
self.attachments << asset
end
end
end
def draft=(draft)
return unless draft
%w(subject content).each do |method|
self.send("#{method}=", draft.send(method))
end
end
########################################################################################################################
def progress_percent
return 0 if self.recipients_count.to_i < 1
(100 * count / self.recipients_count).round
end
#How long did it take to send newsletter
def sending_time
((self.delivery_ended_at || Time.now) - (self.delivery_started_at || Time.now)).to_f.round(2)
end
def count
self.deliveries_count.to_i + self.fails_count.to_i
end
def finishs_count
self.deliveries_count.to_i - self.bounces_count.to_i - self.reads_count.to_i
end
def sendings_per_second
(sending_time > 0) ? (count.to_f / sending_time).round(2) : 0
end
def update_stats!
if pre_sending? || sending?
self.delivery_started_at ||= self.live_send_outs.first(:order => "created_at ASC").try(:created_at)
self.deliveries_count = self.live_send_outs.where("finished_at IS NOT NULL").count
self.fails_count = self.live_send_outs.with_state(:failed).count
end
if done?
self.finish!
end
if finished?
self.bounces_count = live_send_outs.with_state(:bounced).count
self.reads_count = live_send_outs.with_state(:read).count
end
self.save!
end
def done?
(sending? && self.live_send_outs.with_state(:sheduled).count == 0) ||
(testing? && self.test_send_outs.with_state(:sheduled).count == 0)
end
#-------------------------------------------------------------------------------------------------------------------------
private
def set_recipients_count
self.recipients_count = recipients.count
end
def _send_test!(email = nil)
account.test_recipient_emails_array(email).each do |test_recipient_email|
self.test_send_outs.create!(:email => test_recipient_email.strip)
end
process!
end
def _send_live!(*args)
self.recipients.each do |live_recipient|
self.live_send_outs.create!(:recipient => live_recipient)
end
process!
end
def _resume_live!(*args)
#self.update_attributes(:delivery_started_at => Time.now)
self.live_send_outs.with_state(:stopped).map(&:resume!)
process!
end
def _stop!(*args)
self.live_send_outs.with_state(:sheduled).update_all(:state => 'stopped')
finish!
end
end
# == Schema Information
#
# Table name: newsletters
#
# id :integer(4) not null, primary key
# subject :string(255)
# content :text
# mode :integer(4) default(0), not null
# status :integer(4) default(0), not null
# last_sent_id :integer(4)
# recipients_count :integer(4) default(0), not null
# deliveries_count :integer(4) default(0), not null
# fails_count :integer(4) default(0), not null
# deliver_at :datetime
# delivery_started_at :datetime
# delivery_ended_at :datetime
# account_id :integer(4)
# created_at :datetime
# updated_at :datetime
# state :string(255) default("finished")
# bounces_count :integer(4) default(0), not null
# reads_count :integer(4) default(0), not null
#
# updated_at :datetime
diff --git a/app/models/send_out.rb b/app/models/send_out.rb
index e55d3cd..e360d4e 100644
--- a/app/models/send_out.rb
+++ b/app/models/send_out.rb
@@ -1,96 +1,98 @@
class SendOut < ActiveRecord::Base
QUEUE = :nups_send_outs
belongs_to :newsletter
belongs_to :recipient
+ attr_accessible :newsletter, :state, :finished_at, :created_at, :updated_at
+
validates :newsletter_id, :presence => true
after_save :async_deliver!
state_machine :initial => :sheduled do
event :deliver do
transition :sheduled => :delivering
end
event :resume do
transition :stopped => :sheduled
end
event :stop do
transition :sheduled => :stopped
end
event :finish do
transition :delivering => :finished
end
event :failure do
transition :delivering => :failed
end
event :read do
transition :finished => :read
transition :read => :read
end
event :bounce do
transition :finished => :bounced
transition :bounced => :bounced
end
after_transition :sheduled => :delivering do |me|
begin
me.issue.deliver
me.finish!
rescue Exception => e
me.failure!(e)
end
end
end
########################################################################################################################
def self.queue
QUEUE
end
def self.perform(id)
with_state(:sheduled).find_by_id(id, :include => [:newsletter, :recipient]).try(:deliver!)
end
def issue
@issue ||= NewsletterMailer.issue(self.newsletter, self.recipient, self.id).tap do |issue|
issue.header[Newsletter::HEADER_ID] = issue_id
end
end
def issue_id #likely overwritten by subclasses
["ma", self.id].join('-')
end
private
def async_deliver!
if sheduled?
Resque.enqueue(self.class, self.id)
end
end
end
# == Schema Information
#
# Table name: send_outs
#
# id :integer(4) not null, primary key
# recipient_id :integer(4)
# newsletter_id :integer(4)
# type :string(255)
# state :string(255)
# email :string(255)
# error_message :text
# created_at :datetime
# updated_at :datetime
# finished_at :datetime
#
# updated_at :datetime
diff --git a/app/models/test_send_out.rb b/app/models/test_send_out.rb
index cbe9334..5a20178 100644
--- a/app/models/test_send_out.rb
+++ b/app/models/test_send_out.rb
@@ -1,44 +1,46 @@
class TestSendOut < SendOut
+ attr_accessible :email
+
state_machine :initial => :sheduled do
before_transition :delivering => :finished do |me|
me.finished_at = Time.now
end
before_transition :delivering => :failed do |me, transition|
me.error_message = transition.args[0]
end
end
def recipient
@recipient ||= Recipient.new(:email => email)
end
def issue_id
["ma", self.id, "test"].join('-')
end
def issue
super.tap do |issue|
issue.subject = "TEST: #{issue.subject}"
end
end
end
# == Schema Information
#
# Table name: send_outs
#
# id :integer(4) not null, primary key
# recipient_id :integer(4)
# newsletter_id :integer(4)
# type :string(255)
# state :string(255)
# email :string(255)
# error_message :text
# created_at :datetime
# updated_at :datetime
# finished_at :datetime
#
# updated_at :datetime
diff --git a/config/application.rb b/config/application.rb
index 5bf2d92..c3e64c0 100644
--- a/config/application.rb
+++ b/config/application.rb
@@ -1,63 +1,66 @@
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module Nups
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W( #{config.root}/lib )
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'Berlin'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]
config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
+ # Enable escaping HTML in JSON.
+ config.active_support.escape_html_entities_in_json = true
+
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
- # config.active_record.whitelist_attributes = true
+ config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.generators do |g|
g.fixture_replacement :factory_girl
end
end
end
diff --git a/config/environments/production.rb b/config/environments/production.rb
index bac4221..fc7280b 100644
--- a/config/environments/production.rb
+++ b/config/environments/production.rb
@@ -1,67 +1,67 @@
Nups::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = false
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
- # Defaults to Rails.root.join("public/assets")
+ # Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w(frame.js frame.css public.js public.css)
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb
index 7652cd0..9daad16 100644
--- a/config/initializers/devise.rb
+++ b/config/initializers/devise.rb
@@ -1,223 +1,216 @@
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class with default "from" parameter.
config.mailer_sender = "[email protected]"
# Configure the class responsible to send e-mails.
# config.mailer = "Devise::Mailer"
- # Automatically apply schema changes in tableless databases
- config.apply_schema = false
-
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
config.authentication_keys = [ :username ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Basic Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:token]` will
# enable it only for token authentication.
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. "Application" by default.
# config.http_authentication_realm = "Application"
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# :http_auth and :token_auth by adding those symbols to the array below.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing :skip => :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments.
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
config.pepper = "740321a81a1c84cd0fa393ca564f0321461efa1fa47767b29ca02fe9e43b94ed52f6920c081c5373961b967f8e3dd32a5c603397aebd8163e45eed745c11b44e"
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming his account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming his account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming his account.
# config.allow_unconfirmed_access_for = 2.days
# If true, requires any email changes to be confirmed (exctly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed new email is stored in
# unconfirmed email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
- # If true, uses the password salt as remember token. This should be turned
- # to false if you are not using database authenticatable.
- config.use_salt_as_remember_token = true
-
# Options to be passed to the created cookie. For instance, you can set
# :secure => true in order to force SSL only cookies.
# config.cookie_options = {}
# ==> Configuration for :validatable
# Range for password length. Default is 6..128.
config.password_length = 4..20
# Email regex used to validate email formats. It simply asserts that
# an one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper)
# config.encryptor = :sha512
# ==> Configuration for :token_authenticatable
# Defines name of the authentication token params key
# config.token_authentication_key = :auth_token
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Configure sign_out behavior.
# Sign_out action can be scoped (i.e. /users/sign_out affects only :user scope).
# The default is true, which means any logout action will sign out all active scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ["*/*", :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(:scope => :user).unshift :some_external_strategy
# end
end
diff --git a/spec/controllers/newsletters_controller_spec.rb b/spec/controllers/newsletters_controller_spec.rb
index 9053be8..f49ece9 100644
--- a/spec/controllers/newsletters_controller_spec.rb
+++ b/spec/controllers/newsletters_controller_spec.rb
@@ -1,214 +1,214 @@
require 'spec_helper'
describe NewslettersController do
include Devise::TestHelpers
fixtures :accounts, :users, :newsletters
let(:admin) { users(:admin) }
let(:user) { users(:biff) }
let(:newsletter) { newsletters(:biff_newsletter) }
let(:account) { newsletter.account }
context "logged out" do
it "should not get index" do
get :index, :account_id => account.to_param
response.status.should == 302
end
it "should not get new" do
get :new, :account_id => account.to_param
response.status.should == 302
end
it "should not get show" do
get :show, :account_id => account.to_param, :id => newsletter.id
response.status.should == 302
end
end
context "logged in" do
render_views
before do
sign_in user
end
describe "index" do
it "is success" do
get :index, :account_id => account.to_param
response.status.should == 200 #:success
end
it "assigns newsletters" do
get :index, :account_id => account.to_param
assigns(:newsletters).should =~ account.newsletters
end
it "gets not index for other user account" do
get :index, :account_id => accounts(:admin_account).to_param
response.status.should == 404
end
it "sees all own newsletters" do
get :index
assigns(:newsletters).should =~ user.newsletters
end
context "as admin" do
before do
sign_in admin
end
it "sees all newsletter for other user" do
get :index, :user_id => user.id
assigns(:newsletters).should =~ user.newsletters
end
it "gets index for other user account" do
get :index, :account_id => account.to_param
assigns(:newsletters).should =~ account.newsletters
end
end
end
describe "stats" do
it "should get stats" do
get :stats, :account_id => account.to_param, :format => :js
response.status.should == 200 #:success
assigns(:newsletters).should_not be_nil
end
end
describe "new" do
it "should get new" do
get :index, :account_id => account.to_param
response.status.should == 200 #:success
end
it "doesn't get new if wrong account" do
account = accounts(:admin_account)
get :new, :account_id => account.to_param
response.status.should == 404 #:not_found
end
it "gets new if wrong account but admin" do
sign_in admin
get :new, :account_id => account.to_param
assigns(:newsletter).subject.should == account.subject
response.status.should == 200 #:success
end
end
describe "show" do
context "html" do
before do
xhr :get, :show, :account_id => account.to_param, :id => newsletter.to_param
end
it "assigns newsletter" do
assigns(:newsletter).id.should == newsletter.id
end
it "response valid" do
response.status.should == 200 #:success
end
end
it "returns newletter html content" do
xhr :get, :show, :account_id => account.to_param, :id => newsletter.to_param
response.body.should include(newsletter.content)
end
end
- describe "create" do
+ describe "#create" do
it "creates newsletter" do
expect do
post :create, :account_id => account.to_param, :newsletter => newsletter.attributes
- end.to change(Newsletter, :count)
+ end.to change { Newsletter.count }
end
it "creates newsletter with empty attachment_ids" do
expect do
post :create, :account_id => account.to_param, :newsletter => {:subject => "blabla", :attachment_ids => ["1"]}
- end.to change(Newsletter, :count)
+ end.to change { Newsletter.count }
end
it "redirects to newsletters form account" do
post :create, :account_id => account.to_param, :newsletter => newsletter.attributes
response.should redirect_to(account_newsletters_path(account))
end
context "as admin" do
before do
sign_in admin
end
it "creates newsletter for other user" do
expect do
post :create, :account_id => account.to_param, :newsletter => newsletter.attributes, :preview => true
end.to change { account.newsletters.count }
end
end
end
- describe "edit" do
+ describe "#edit" do
it "does success" do
get :edit, :account_id => account.to_param, :id => newsletter.to_param
response.status.should == 200 #:success
end
end
describe "update" do
it "should update newsletter" do
put :update, :account_id => account.to_param, :id => newsletter.to_param, :newsletter => newsletter.attributes
response.should redirect_to(account_newsletters_path(account))
end
end
describe "destroy" do
it "should destroy newsletter" do
expect do
delete :destroy, :account_id => account.to_param, :id => newsletter.to_param
end.to change(Newsletter, :count).by(-1)
end
it "should redirect to newsletters from account" do
delete :destroy, :account_id => account.to_param, :id => newsletter.to_param
response.should redirect_to(account_newsletters_path(account))
end
end
describe "schedule" do
context "test" do
it "changes newsletter state" do
get :start, :account_id => account.to_param, :id => newsletter.to_param
newsletter.reload.pre_testing?.should be_true
end
it "queues test newsletter" do
get :start, :account_id => account.to_param, :id => newsletter.to_param
Newsletter.should have_queued(newsletter.id, "_send_test!", user.email)
end
it "redirects to newsletters from account" do
get :start, :account_id => account.to_param, :id => newsletter.to_param
response.should redirect_to(account_newsletters_path(account))
end
end
context "live" do
it "changes newsletter state" do
get :start, :account_id => account.to_param, :id => newsletter.to_param, :mode => 'live'
newsletter.reload.pre_sending?.should be_true
end
it "queues live newsletter" do
get :start, :account_id => account.to_param, :id => newsletter.to_param, :mode => 'live'
Newsletter.should have_queued(newsletter.id, "_send_live!")
end
end
end
end
end
diff --git a/spec/factories/all.rb b/spec/factories/all.rb
index 61e4fe6..fd366d8 100644
--- a/spec/factories/all.rb
+++ b/spec/factories/all.rb
@@ -1,88 +1,87 @@
# Read about factories at http://github.com/thoughtbot/factory_girl
require 'factory_girl/syntax/blueprint'
-require 'factory_girl/syntax/make'
FactoryGirl.define do
sequence :email do |n|
"#{n}-#{Faker::Internet.email}"
end
factory :user do
username Faker::Internet.user_name
email
password 'admin'
password_confirmation { password }
factory :admin do
username "admin"
admin true
confirmed_at Time.now
end
end
factory :account do
user
from Faker::Internet.email
name Faker::Name.name
test_recipient_emails %w([email protected] [email protected])
factory :biff_account do
end
end
factory :recipient do
account
email
first_name Faker::Name.first_name
last_name Faker::Name.last_name
state 'confirmed'
# factory :josh, :class => :recipient do
# association :biff_account
# end
#
# factory :wonne, :class => :recipient do
# account #biff
# end
#
# factory :raziel, :class => :recipient do
# account #biff
# state 'pending'
# end
#
# factory :admin_r, :class => :recipient do
# account #admin
# end
end
factory :newsletter do
account
subject Faker::Lorem.words
end
factory :bounce do
raw File.read(Rails.root.join('spec', 'fixtures', 'mail.txt').to_s)
end
factory :live_send_out do |me|
state 'finished'
recipient
#both share same account
newsletter { FactoryGirl.create(:newsletter, :account => recipient.account) }
end
factory :asset do
account
user { account.user }
factory :asset2 do
attachment_file_name "picture_two.jpg"
end
factory :asset3 do
attachment_file_name "picture_three.jpg"
end
end
end
diff --git a/spec/helpers/charts_helper_spec.rb b/spec/helpers/charts_helper_spec.rb
index a188546..c89b1cb 100644
--- a/spec/helpers/charts_helper_spec.rb
+++ b/spec/helpers/charts_helper_spec.rb
@@ -1,79 +1,79 @@
require 'spec_helper'
describe ChartsHelper do
- let(:account) { Account.make! }
+ let(:account) { create(:account) }
describe "newsletters_chart" do
let(:newsletter_attrs) do
[
{:created_at => ago_4, :deliveries_count => 10, :bounces_count => 10},
{:created_at => ago_3 + 3.hours},
{:created_at => ago_3, :updated_at => ago_2 + 2.hours},
{:created_at => ago_3},
{:created_at => ago_3, :updated_at => ago_2},
{:created_at => ago_2, :updated_at => ago_1},
{:created_at => ago_2, :updated_at => ago_2},
{:created_at => ago_2, :updated_at => ago_1},
]
end
it "works" do
#puts helper.newsletters_chart(account.newsletters)
end
end
describe "recipients_chart" do
let(:time_group) { 1.day }
let(:date) { Time.parse("2011-12-10 12:34:00 UTC") }
let(:ago_4) { date - 4 * time_group }
let(:ago_3) { date - 3 * time_group }
let(:ago_2) { date - 2 * time_group }
let(:ago_1) { date - 1 * time_group }
let(:now_d) { Time.parse("2011-12-10 00:00:00 UTC") }
let(:ago_4_d) { (now_d - 4 * time_group).to_i }
let(:ago_3_d) { (now_d - 3 * time_group).to_i }
let(:ago_2_d) { (now_d - 2 * time_group).to_i }
let(:ago_1_d) { (now_d - 1 * time_group).to_i }
let(:recipient_attrs) do
[
{:state => 'pending', :created_at => ago_4},
{:state => 'pending', :created_at => ago_3 + 3.hours},
{:state => 'pending', :created_at => ago_3, :updated_at => ago_2 + 2.hours},
{:state => 'confirmed', :created_at => ago_3},
{:state => 'confirmed', :created_at => ago_3, :updated_at => ago_2},
{:state => 'confirmed', :created_at => ago_2, :updated_at => ago_1},
{:state => 'deleted', :created_at => ago_2, :updated_at => ago_2},
{:state => 'deleted', :created_at => ago_2, :updated_at => ago_1},
]
end
let(:actual_result) { helper.recipients_chart(account) }
let(:expected_result) do
{
:pending => { ago_4_d => 1, ago_3_d => 2 },
:confirmed => { ago_3_d => 2, ago_2_d => 2, ago_1_d => -1 },
:deleted => { ago_2_d => 1, ago_1_d => 1 },
}
end
before do
recipient_attrs.each do |recipient_attr|
- Recipient.make!(recipient_attr.merge(:account => account))
+ create(:recipient, recipient_attr.merge(:account => account))
end
end
it "works for pending" do
actual_result[:pending].to_a.should =~ expected_result[:pending].to_a
end
it "works for confirmed" do
actual_result[:confirmed].to_a.should =~ expected_result[:confirmed].to_a
end
it "works for deleted" do
actual_result[:deleted].to_a.should =~ expected_result[:deleted].to_a
end
end
end
diff --git a/spec/models/account_spec.rb b/spec/models/account_spec.rb
index 326c614..53fc179 100644
--- a/spec/models/account_spec.rb
+++ b/spec/models/account_spec.rb
@@ -1,108 +1,108 @@
require 'spec_helper'
describe Account do
- let(:account) { Account.make }
+ let(:account) { build(:account) }
describe "#validation" do
context "#create" do
context "permalink" do
it "generates random string for code" do
Account.create.permalink.should_not nil
end
it "does not mass assign code" do
expect do
Account.create(:permalink => 'custom')
end.to raise_error
end
it "does not overwrite manual set permalink" do
- Account.make.tap do |account|
+ build(:account).tap do |account|
account.permalink = 'custom'
account.save!
account.permalink.should == 'custom'
end
end
it "generates uniqe one" do
- Account.make.tap do |account|
- account.permalink = Account.make!.permalink
+ build(:account).tap do |account|
+ account.permalink = create(:account).permalink
account.save!
end
end
end
end
end
describe "#test_recipient_emails_array" do
{
:by_comma => "[email protected],[email protected],[email protected]",
:by_spec_char => "[email protected];[email protected]|[email protected]",
:uniq => "[email protected],[email protected]\r,[email protected],[email protected]",
:remove_empty => "[email protected],,[email protected],[email protected],",
:and_strip => "[email protected] ;[email protected]\n| [email protected] "
}.each do |name, value|
it "splits recipients #{name}" do
account.test_recipient_emails = value
account.test_recipient_emails_array.should =~ %w([email protected] [email protected] [email protected])
end
end
it "includes extra test_emails" do
account.test_recipient_emails_array("[email protected]").should =~ %w([email protected] [email protected] [email protected])
end
it "uniques extra test_emails" do
account.test_recipient_emails_array("[email protected]").should =~ %w([email protected] [email protected])
end
end
describe "#process_bounces" do
it "doesn't fail" do
account.should_receive(:mail_config).and_return(nil)
account.process_bounces.should be_nil
end
end
describe "#mail_config" do
it "fals back to global when empty" do
account.mail_config.should == $mail_config
end
it "fals back to global when not parsable" do
account.mail_config_raw = "["
account.mail_config.should == $mail_config
end
it "fals back to global when not parsable" do
account.mail_config_raw = "method: smtp"
account.mail_config.should == {"method"=>"smtp"}
end
end
end
# == Schema Information
#
# Table name: accounts
#
# id :integer(4) not null, primary key
# name :string(255)
# from :string(255)
# user_id :integer(4)
# subject :string(255)
# template_html :text
# template_text :text
# test_recipient_emails :text
# created_at :datetime
# updated_at :datetime
# color :string(255) default("#FFF")
# has_html :boolean(1) default(TRUE)
# has_text :boolean(1) default(TRUE)
# has_attachments :boolean(1)
# has_scheduling :boolean(1)
# mail_config_raw :text
# permalink :string(255)
#
# updated_at :datetime
diff --git a/spec/models/bounce_spec.rb b/spec/models/bounce_spec.rb
index bbc7916..b754844 100644
--- a/spec/models/bounce_spec.rb
+++ b/spec/models/bounce_spec.rb
@@ -1,101 +1,101 @@
require 'spec_helper'
describe Bounce do
- let(:bounce) { Bounce.make }
+ let(:bounce) { build(:bounce) }
context "create" do
it "gets enqueued" do
- new_bounce = Bounce.create!(:raw => "example Email")
+ new_bounce = create(:bounce, :raw => "example Email")
Bounce.should have_queued(new_bounce.id)
end
end
it "find mail id" do
bounce.mail_id.should == "ma-14-87"
end
it "bounced" do
bounce.mail.should be_bounced
end
describe "#process!" do
before do
bounce.process!
end
it "sets subject" do
bounce.subject.should == 'Notificacion del estado del envio'
end
it "sets from" do
bounce.from.should == '[email protected]'
end
it "sets error_status" do
bounce.error_status.should == '5.1.1'
end
it "sets send_out_id" do
bounce.send_out_id.should == 14
end
it "sets recipient_id" do
bounce.recipient_id.should == 87
end
end
context "send_out" do
- let(:send_out) { LiveSendOut.make! }
+ let(:send_out) { create(:live_send_out) }
let(:newsletter) { send_out.newsletter }
let(:recipient) { send_out.recipient }
before do
bounce.stub(:mail_id).and_return "ma-#{send_out.id}-#{recipient.id}"
bounce.stub(:error_message).and_return "error"
end
it "changes send_out state" do
expect do
bounce.process!
end.to change { send_out.reload.state }.from('finished').to('bounced')
end
it "adds error_message to send_out" do
expect do
bounce.process!
end.to change { send_out.reload.error_message }.from(nil).to("error")
end
it "increases recipient bounces_count" do
expect do
bounce.process!
end.to change { recipient.reload.bounces_count }.by(1)
end
# #dummy test to make sure fixture is right
it "send_out has same account" do
recipient.account.id.should == newsletter.account.id
end
end
end
# == Schema Information
#
# Table name: bounces
#
# id :integer(4) not null, primary key
# account_id :integer(4)
# recipient_id :integer(4)
# from :string(255)
# subject :string(255)
# send_at :datetime
# header :text
# body :text
# raw :text
# created_at :datetime
# updated_at :datetime
# error_status :string(255)
# send_out_id :integer(4)
#
# updated_at :datetime
|
rngtng/nups
|
fe21140552467bf2373a65ed0d5f6d69acbea5e3
|
gem updates
|
diff --git a/Gemfile b/Gemfile
index 58c077a..4e0cfc2 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,81 +1,81 @@
source 'http://rubygems.org'
-gem 'rails', '~> 3.2.1'
+gem 'rails', '~> 3.2.3'
gem 'mysql2'
gem 'jquery-rails'
gem 'haml'
#Authorization
gem "devise"
# Use resque for async jobs
gem 'resque'
-gem 'resque-scheduler', '~> 2.0.0.e'
+gem 'resque-scheduler', '~> 2.0.0.h'
gem 'resque-jobs-per-fork'
#For handling File uploads
gem 'paperclip'
#For proper pagination
gem 'kaminari'
# For excel export
gem 'ekuseru'
# parsing bounce emails
gem 'bounce_email'
gem 'state_machine'
gem 'nokogiri'
gem 'premailer'
gem 'rpm_contrib'
gem 'newrelic_rpm'
gem 'airbrake'
# auto_link replacement
gem 'rinku'
gem 'annotate', :git => 'git://github.com/ctran/annotate_models.git'
gem 'rspec-rails', :group => [:development, :test]
gem 'spin', :group => [:development, :test]
group :development do
gem 'capistrano'
gem 'mailcatcher'
gem 'ruby-graphviz', :require => 'graphviz'
end
# http://metaskills.net/2011/07/29/use-compass-sass-framework-files-with-the-rails-3.1.0.rc5-asset-pipeline/
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails'
# gem 'compass', :git => 'git://github.com/chriseppstein/compass.git', :branch => 'rails31'
end
group :test do
gem 'json' #needed for resque to run on travis-ci
gem 'resque_spec'
gem 'delorean'
#selenium
gem 'capybara'
gem 'database_cleaner'
#fixtures
gem 'faker'
gem 'factory_girl_rails'
gem 'watchr'
gem 'simplecov'
end
diff --git a/Gemfile.lock b/Gemfile.lock
index 7251067..b5d5d7f 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,300 +1,304 @@
GIT
remote: git://github.com/ctran/annotate_models.git
- revision: a43c08f0eb4d69a48c6830630ebb60e35ccb2d2d
+ revision: ff1131daee8c03dbcc4966b7914b77a7e3a62f02
specs:
annotate (2.4.1.beta1)
GEM
remote: http://rubygems.org/
specs:
- actionmailer (3.2.1)
- actionpack (= 3.2.1)
- mail (~> 2.4.0)
- actionpack (3.2.1)
- activemodel (= 3.2.1)
- activesupport (= 3.2.1)
+ actionmailer (3.2.3)
+ actionpack (= 3.2.3)
+ mail (~> 2.4.4)
+ actionpack (3.2.3)
+ activemodel (= 3.2.3)
+ activesupport (= 3.2.3)
builder (~> 3.0.0)
erubis (~> 2.7.0)
journey (~> 1.0.1)
rack (~> 1.4.0)
- rack-cache (~> 1.1)
+ rack-cache (~> 1.2)
rack-test (~> 0.6.1)
sprockets (~> 2.1.2)
- activemodel (3.2.1)
- activesupport (= 3.2.1)
+ activemodel (3.2.3)
+ activesupport (= 3.2.3)
builder (~> 3.0.0)
- activerecord (3.2.1)
- activemodel (= 3.2.1)
- activesupport (= 3.2.1)
- arel (~> 3.0.0)
+ activerecord (3.2.3)
+ activemodel (= 3.2.3)
+ activesupport (= 3.2.3)
+ arel (~> 3.0.2)
tzinfo (~> 0.3.29)
- activeresource (3.2.1)
- activemodel (= 3.2.1)
- activesupport (= 3.2.1)
- activesupport (3.2.1)
+ activeresource (3.2.3)
+ activemodel (= 3.2.3)
+ activesupport (= 3.2.3)
+ activesupport (3.2.3)
i18n (~> 0.6)
multi_json (~> 1.0)
- addressable (2.2.6)
+ addressable (2.2.7)
airbrake (3.0.9)
activesupport
builder
- arel (3.0.0)
+ arel (3.0.2)
bcrypt-ruby (3.0.1)
bounce_email (0.2.2)
mail
builder (3.0.0)
- capistrano (2.9.0)
+ capistrano (2.12.0)
highline
net-scp (>= 1.0.0)
net-sftp (>= 2.0.0)
net-ssh (>= 2.0.14)
net-ssh-gateway (>= 1.1.0)
capybara (1.1.2)
mime-types (>= 1.16)
nokogiri (>= 1.3.3)
rack (>= 1.0.0)
rack-test (>= 0.5.4)
selenium-webdriver (~> 2.0)
xpath (~> 0.1.4)
childprocess (0.3.1)
ffi (~> 1.0.6)
chronic (0.6.7)
cocaine (0.2.1)
coffee-rails (3.2.2)
coffee-script (>= 2.2.0)
railties (~> 3.2.0)
coffee-script (2.2.0)
coffee-script-source
execjs
- coffee-script-source (1.2.0)
+ coffee-script-source (1.3.1)
css_parser (1.2.6)
addressable
rdoc
- daemons (1.1.6)
- database_cleaner (0.7.1)
+ daemons (1.1.8)
+ database_cleaner (0.7.2)
delorean (1.2.0)
chronic
- devise (2.0.0)
+ devise (2.0.4)
bcrypt-ruby (~> 3.0)
orm_adapter (~> 0.0.3)
railties (~> 3.1)
- warden (~> 1.1)
+ warden (~> 1.1.1)
diff-lcs (1.1.3)
ekuseru (0.3.10)
rails (>= 3.0)
spreadsheet (>= 0.6)
erubis (2.7.0)
eventmachine (0.12.10)
execjs (1.3.0)
multi_json (~> 1.0)
- factory_girl (2.5.1)
- activesupport
- factory_girl_rails (1.6.0)
- factory_girl (~> 2.5.0)
+ factory_girl (3.1.1)
+ activesupport (>= 3.0.0)
+ factory_girl_rails (3.1.0)
+ factory_girl (~> 3.1.0)
railties (>= 3.0.0)
faker (1.0.1)
i18n (~> 0.4)
ffi (1.0.11)
haml (3.1.4)
highline (1.6.11)
hike (1.2.1)
htmlentities (4.3.1)
i18n (0.6.0)
- journey (1.0.1)
- jquery-rails (2.0.0)
- railties (>= 3.2.0.beta, < 5.0)
+ journey (1.0.3)
+ jquery-rails (2.0.2)
+ railties (>= 3.2.0, < 5.0)
thor (~> 0.14)
- json (1.6.5)
+ json (1.6.6)
kaminari (0.13.0)
actionpack (>= 3.0.0)
activesupport (>= 3.0.0)
railties (>= 3.0.0)
- mail (2.4.1)
+ libwebsocket (0.1.3)
+ addressable
+ mail (2.4.4)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
- mailcatcher (0.5.5)
+ mailcatcher (0.5.6)
activesupport (~> 3.0)
eventmachine (~> 0.12)
haml (~> 3.1)
mail (~> 2.3)
sinatra (~> 1.2)
skinny (~> 0.2)
sqlite3 (~> 1.3)
thin (~> 1.2)
- mime-types (1.17.2)
- multi_json (1.0.4)
+ mime-types (1.18)
+ multi_json (1.3.2)
mysql2 (0.3.11)
net-scp (1.0.4)
net-ssh (>= 1.99.1)
net-sftp (2.0.5)
net-ssh (>= 2.0.9)
net-ssh (2.3.0)
net-ssh-gateway (1.1.0)
net-ssh (>= 1.99.1)
- newrelic_rpm (3.3.1)
- nokogiri (1.5.0)
- orm_adapter (0.0.6)
- paperclip (2.5.2)
- activerecord (>= 2.3.0)
- activesupport (>= 2.3.2)
+ newrelic_rpm (3.3.3)
+ nokogiri (1.5.2)
+ orm_adapter (0.0.7)
+ paperclip (3.0.2)
+ activemodel (>= 3.0.0)
+ activerecord (>= 3.0.0)
+ activesupport (>= 3.0.0)
cocaine (>= 0.0.2)
mime-types
polyglot (0.3.3)
premailer (1.7.3)
css_parser (>= 1.1.9)
htmlentities (>= 4.0.0)
rack (1.4.1)
- rack-cache (1.1)
+ rack-cache (1.2)
rack (>= 0.4)
rack-protection (1.2.0)
rack
rack-ssl (1.3.2)
rack
rack-test (0.6.1)
rack (>= 1.0)
- rails (3.2.1)
- actionmailer (= 3.2.1)
- actionpack (= 3.2.1)
- activerecord (= 3.2.1)
- activeresource (= 3.2.1)
- activesupport (= 3.2.1)
+ rails (3.2.3)
+ actionmailer (= 3.2.3)
+ actionpack (= 3.2.3)
+ activerecord (= 3.2.3)
+ activeresource (= 3.2.3)
+ activesupport (= 3.2.3)
bundler (~> 1.0)
- railties (= 3.2.1)
- railties (3.2.1)
- actionpack (= 3.2.1)
- activesupport (= 3.2.1)
+ railties (= 3.2.3)
+ railties (3.2.3)
+ actionpack (= 3.2.3)
+ activesupport (= 3.2.3)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (~> 0.14.6)
rake (0.9.2.2)
rdoc (3.12)
json (~> 1.4)
redis (2.2.2)
redis-namespace (1.0.3)
redis (< 3.0.0)
- resque (1.19.0)
+ resque (1.20.0)
multi_json (~> 1.0)
redis-namespace (~> 1.0.2)
sinatra (>= 0.9.2)
vegas (~> 0.1.2)
resque-jobs-per-fork (1.15.1)
resque (~> 1.15)
- resque-scheduler (2.0.0.g)
+ resque-scheduler (2.0.0.h)
redis (>= 2.0.1)
resque (>= 1.19.0)
rufus-scheduler
- resque_spec (0.9.0)
+ resque_spec (0.10.0)
resque (>= 1.19.0)
rspec (>= 2.5.0)
- rinku (1.5.0)
- rpm_contrib (2.1.7)
+ rinku (1.5.1)
+ rpm_contrib (2.1.8)
newrelic_rpm (>= 3.1.1)
newrelic_rpm (>= 3.1.1)
- rspec (2.8.0)
- rspec-core (~> 2.8.0)
- rspec-expectations (~> 2.8.0)
- rspec-mocks (~> 2.8.0)
- rspec-core (2.8.0)
- rspec-expectations (2.8.0)
- diff-lcs (~> 1.1.2)
- rspec-mocks (2.8.0)
- rspec-rails (2.8.1)
+ rspec (2.9.0)
+ rspec-core (~> 2.9.0)
+ rspec-expectations (~> 2.9.0)
+ rspec-mocks (~> 2.9.0)
+ rspec-core (2.9.0)
+ rspec-expectations (2.9.1)
+ diff-lcs (~> 1.1.3)
+ rspec-mocks (2.9.0)
+ rspec-rails (2.9.0)
actionpack (>= 3.0)
activesupport (>= 3.0)
railties (>= 3.0)
- rspec (~> 2.8.0)
+ rspec (~> 2.9.0)
ruby-graphviz (1.0.5)
- ruby-ole (1.2.11.2)
- rubyzip (0.9.5)
+ ruby-ole (1.2.11.3)
+ rubyzip (0.9.7)
rufus-scheduler (2.0.16)
tzinfo (>= 0.3.23)
- sass (3.1.14)
- sass-rails (3.2.4)
+ sass (3.1.15)
+ sass-rails (3.2.5)
railties (~> 3.2.0)
sass (>= 3.1.10)
tilt (~> 1.3)
- selenium-webdriver (2.18.0)
+ selenium-webdriver (2.21.0)
childprocess (>= 0.2.5)
- ffi (~> 1.0.9)
- multi_json (~> 1.0.4)
+ ffi (~> 1.0)
+ libwebsocket (~> 0.1.3)
+ multi_json (~> 1.0)
rubyzip
- simplecov (0.5.4)
- multi_json (~> 1.0.3)
+ simplecov (0.6.1)
+ multi_json (~> 1.0)
simplecov-html (~> 0.5.3)
simplecov-html (0.5.3)
sinatra (1.3.2)
rack (~> 1.3, >= 1.3.6)
rack-protection (~> 1.2)
tilt (~> 1.3, >= 1.3.3)
skinny (0.2.0)
eventmachine (~> 0.12)
thin (~> 1.2)
- spin (0.4.3)
+ spin (0.4.5)
spreadsheet (0.6.8)
ruby-ole (>= 1.0)
sprockets (2.1.2)
hike (~> 1.2)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
- sqlite3 (1.3.5)
+ sqlite3 (1.3.6)
state_machine (1.1.2)
thin (1.3.1)
daemons (>= 1.0.9)
eventmachine (>= 0.12.6)
rack (>= 1.0.0)
thor (0.14.6)
tilt (1.3.3)
treetop (1.4.10)
polyglot
polyglot (>= 0.3.1)
- tzinfo (0.3.31)
+ tzinfo (0.3.33)
vegas (0.1.11)
rack (>= 1.0.0)
- warden (1.1.0)
+ warden (1.1.1)
rack (>= 1.0)
watchr (0.7)
xpath (0.1.4)
nokogiri (~> 1.3)
PLATFORMS
ruby
DEPENDENCIES
airbrake
annotate!
bounce_email
capistrano
capybara
coffee-rails
database_cleaner
delorean
devise
ekuseru
factory_girl_rails
faker
haml
jquery-rails
json
kaminari
mailcatcher
mysql2
newrelic_rpm
nokogiri
paperclip
premailer
- rails (~> 3.2.1)
+ rails (~> 3.2.3)
resque
resque-jobs-per-fork
- resque-scheduler (~> 2.0.0.e)
+ resque-scheduler (~> 2.0.0.h)
resque_spec
rinku
rpm_contrib
rspec-rails
ruby-graphviz
sass-rails (~> 3.2.3)
simplecov
spin
state_machine
watchr
diff --git a/config/boot.rb b/config/boot.rb
index e03d404..4489e58 100644
--- a/config/boot.rb
+++ b/config/boot.rb
@@ -1,9 +1,6 @@
require 'rubygems'
-require 'yaml' #for travis
-YAML::ENGINE.yamler= 'syck' #for travis
-
# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb
index deadc5e..5d8d9be 100644
--- a/config/initializers/inflections.rb
+++ b/config/initializers/inflections.rb
@@ -1,15 +1,15 @@
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
#
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.acronym 'RESTful'
-# end
\ No newline at end of file
+# end
|
rngtng/nups
|
8b2e4035933515899be1b2f0d693066f14829e45
|
force reconnect when mysql gone away, send send_out errors to air brake
|
diff --git a/README.md b/README.md
index aaae714..d249a79 100644
--- a/README.md
+++ b/README.md
@@ -1,92 +1,92 @@
# Welcome to NUPS
## resources
* Overview of best plugins: http://ruby-toolbox.com/
* [Devise](http://github.com/plataformatec/devise) -> `rails generate devise_install`
* Test SMTP lockally: http://mocksmtpapp.com/
* Spinners:
http://www.andrewdavidson.com/articles/spinning-wait-icons/
http://mentalized.net/activity-indicators/
## TODO
* try send grids:
http://stackoverflow.com/questions/4798141/sendgrid-vs-postmark-vs-amazon-ses-and-other-email-smtp-api-providers
* check: stop while in pre_sending??
* check: error when creating send_outs
* chart when people read
* remove mode/status/last_send_id from newsletter
* order DESC
- * heighlight reciever with bounce count, set option to disable
+ * highlight reciever with bounce count, set option to disable
* translation (gender)
* add better migration
* test coffeescript
* animate sendout & test gif icons
* check: http://isnotspam.com
* test premailer
* add index to recipients
* bounce only when 5.X code
* bounce cleanup
* mv send_out textfield into string? (speed up)
## DONE
* check what happens if a single sendout fails within a batch
* add better fixtures: factory_girl
* newsletter stats: total/percent send/fail/bounces/read count
-> * add infos to newsletter to see total read/bounces
* history stats
recipient growth
newsletter read/bounce growth
sending time/speed
* remove error_message recipeint -> move to send_out
* change update_newsletter to json
* reactivate deleted users
* send test email to current_user.email
* newsletter unsubscribe by email
* autodetect URLS
* unsubscribe ->
header: http://www.list-unsubscribe.com/
* recipients: overflow for user name + email
* remove error_code from send_out
* errors_count + errors message
* hidden image to register if nl was read *test*
* read NL on website *test*
* read count to recipient *update when read* *test*
* update bounce counters:
-> only counter bounces younger than last update time -> bounces_count_updated_at
-> resque task?
-> on bounce create? if user available?
* update deliver counters:
-> after send?
* fix receiver edit
* recipients overlay with list of sendouts (details -> when which newsletter was send)
* hide deleted receiver
* sort receiver column, indicate sorting *test*
* receiver paginate ajax
* pretty time span
* add user total count on top
* update deliverd_startet_at_ from youngest sendout
* scheduling
* recipients import/export
* Newsletter delete ajax
* search pagination, show total amount
* attachment upload
* new newsletter scroll
* reload after recp import
* open new newsletter in window
* recipients
* in place editing (improvement see rails cast)
* fix travis setup: http://about.travis-ci.org/docs/user/build-configuration/
* progress bar update time
* resque status: http://github.com/quirkey/resque-status
## Resque Startup:
* rake resque:workers:start
## Mail
http://www.techsoup.org/learningcenter/internet/page5052.cfm
http://www.sitepoint.com/forums/showthread.php?571536-Building-a-newsletter-not-getting-listed-as-spam
http://gettingattention.org/articles/160/email-enewsletters/nonprofit-email-newsletter-success.html
## Builder
[](http://travis-ci.org/rngtng/nups)
diff --git a/app/models/account.rb b/app/models/account.rb
index e4c0cd8..712d4c9 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -1,124 +1,125 @@
require 'net/imap'
class Account < ActiveRecord::Base
belongs_to :user
attr_protected :permalink
has_many :assets, :dependent => :destroy
has_many :newsletters, :dependent => :destroy
has_many :recipients, :dependent => :destroy
validates :from, :presence => true
validates :name, :presence => true
validates :user_id, :presence => true
validates :permalink, :presence => true, :uniqueness => true, :on => :create
scope :with_mail_config, :conditions => "mail_config_raw != ''"
def self.queue
Bounce::QUEUE
end
def self.perform(id = nil)
+ ActiveRecord::Base.verify_active_connections!
if id
self.find(id).process_bounces
else
Account.all.each do |account|
Resque.enqueue(Account, account.id)
end
end
end
def test_recipient_emails_array(extra_email = nil)
tester = [test_recipient_emails, extra_email].join(' ')
tester.split(/,| |\||;|\r|\n|\t/).select do |email|
email.include?('@')
end.compact.uniq
end
def mail_config
@mail_config ||= YAML::load(self.mail_config_raw) || $mail_config
rescue
$mail_config
end
def from_email
email_exp = Regexp.new(/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/)
self.from.scan(email_exp).first
end
def sender
@sender ||= (self.mail_config && self.mail_config['sender']) || self.from_email
end
def reply_to
@reply_to ||= (self.mail_config && self.mail_config['reply_to']) || self.from_email
end
def process_bounces(mbox = 'INBOX', encoding = 'RFC822')
if mail_config && (mail_settings = mail_config['smtp_settings'])
Net::IMAP.new(mail_settings[:address].gsub('smtp', 'imap')).tap do |imap|
imap.authenticate('LOGIN', mail_settings[:user_name], mail_settings[:password])
imap.select(mbox) #use examaine for read only
# all msgs
if imap.status(mbox, ["MESSAGES"])["MESSAGES"] > 0
imap.uid_search(["SINCE", "1-Jan-1969", "NOT", "DELETED"]).each do |uid|
begin
Bounce.create!(:raw => imap.uid_fetch(uid, [encoding]).first.attr[encoding])
imap.uid_store(uid, "+FLAGS", [:Deleted])
rescue ArgumentError => e
imap.uid_store(uid, "+FLAGS", [:Deleted])
rescue => e
Airbrake.notify(
:error_class => e.class,
:error_message => e.message,
:parameters => {:account_id => self.id, :uid => uid}
)
end
end
end
imap.expunge
imap.close
end
end
end
protected
# in case we generate a duplicate confirm_code, regenerate a new one
def run_validations!
super.tap do
if errors[:permalink].present?
self.permalink = SecureRandom.hex(8)
return valid? #re-run validation
end
end
end
end
# == Schema Information
#
# Table name: accounts
#
# id :integer(4) not null, primary key
# name :string(255)
# from :string(255)
# user_id :integer(4)
# subject :string(255)
# template_html :text
# template_text :text
# test_recipient_emails :text
# created_at :datetime
# updated_at :datetime
# color :string(255) default("#FFF")
# has_html :boolean(1) default(TRUE)
# has_text :boolean(1) default(TRUE)
# has_attachments :boolean(1)
# has_scheduling :boolean(1)
# mail_config_raw :text
# permalink :string(255)
#
# updated_at :datetime
diff --git a/app/models/live_send_out.rb b/app/models/live_send_out.rb
index 5a5dccb..74da391 100644
--- a/app/models/live_send_out.rb
+++ b/app/models/live_send_out.rb
@@ -1,66 +1,67 @@
class LiveSendOut < SendOut
validates :recipient_id, :presence => true, :uniqueness => {:scope => [:newsletter_id, :type]}, :on => :create
before_validation :set_email, :on => :create
state_machine :initial => :sheduled do
before_transition :delivering => :finished do |me|
me.finished_at = Time.now
me.recipient.update_attribute(:deliveries_count, me.recipient.deliveries_count + 1)
end
before_transition :delivering => :failed do |me, transition|
me.error_message = transition.args[0].message
me.recipient.update_attribute(:fails_count, me.recipient.fails_count + 1)
end
after_transition :delivering => :failed do |me, transition|
# a bit dirty hack: force to end transition successfull but still
# propagade execption
me.connection.execute("COMMIT") #prevent rollback
+ Airbrake.notify(transition.args[0], :params => { :id => self.id })
raise transition.args[0]
end
before_transition :finished => :read do |me|
me.recipient.update_attribute(:reads_count, me.recipient.reads_count + 1)
end
before_transition :finished => :bounced do |me, transition|
me.error_message = transition.args[0]
me.recipient.update_attribute(:bounces_count, me.recipient.bounces_count + 1)
end
end
def issue_id
["ma", self.id, self.recipient_id].join('-')
end
private
def set_email
self.email = recipient.email
end
end
# == Schema Information
#
# Table name: send_outs
#
# id :integer(4) not null, primary key
# recipient_id :integer(4)
# newsletter_id :integer(4)
# type :string(255)
# state :string(255)
# email :string(255)
# error_message :text
# created_at :datetime
# updated_at :datetime
# finished_at :datetime
#
# Indexes
#
# index_send_outs_on_newsletter_id_and_type (newsletter_id,type)
# index_send_outs_on_newsletter_id_and_type_and_recipient_id (newsletter_id,type,recipient_id)
#
# updated_at :datetime
diff --git a/app/models/newsletter.rb b/app/models/newsletter.rb
index bc1a847..8364aa0 100644
--- a/app/models/newsletter.rb
+++ b/app/models/newsletter.rb
@@ -1,218 +1,219 @@
class Newsletter < ActiveRecord::Base
QUEUE = :nups_newsletter
HEADER_ID = "X-MA-Id"
belongs_to :account
has_many :recipients, :through => :account, :conditions => { 'recipients.state' => :confirmed }
has_many :attachments, :class_name => 'Asset'
# http://stackoverflow.com/questions/738906/rails-dependent-and-delete
has_many :send_outs, :dependent => :delete_all #send_out has no dependency, speed it up
has_many :live_send_outs
has_many :test_send_outs
scope :with_account, lambda { |account| account ? where(:account_id => account.id) : {} }
validates :account_id, :presence => true
validates :subject, :presence => true
before_create :set_recipients_count
########################################################################################################################
state_machine :initial => :new do
event :send_test do
transition :new => :pre_testing
transition :tested => :pre_testing
end
event :send_live do
transition :tested => :pre_sending
transition :stopped => :pre_sending
end
event :process do
transition :pre_testing => :testing
transition :pre_sending => :sending
end
event :stop do
transition :sending => :stopping
transition :testing => :new
end
event :finish do
transition :sending => :finished
transition :testing => :tested
transition :stopping => :stopped
end
after_transition all => :pre_testing do |me, transition|
Resque.enqueue(me.class, me.id, "_send_test!", transition.args[0])
end
after_transition :tested => :pre_sending do |me|
if me.deliver_at && me.deliver_at > Time.now
Resque.enqueue_at(me.deliver_at, me.class, me.id, "_send_live!")
else
Resque.enqueue(me.class, me.id, "_send_live!")
end
end
after_transition :stopped => :pre_sending do |me|
Resque.enqueue(me.class, me.id, "_resume_live!")
end
before_transition :pre_sending => :sending do |me|
me.recipients_count = me.live_send_outs.count #TODO what if stopped??
end
before_transition :sending => :finished do |me|
me.delivery_ended_at = me.live_send_outs.first(:select => "finished_at", :order => "finished_at DESC").try(:finished_at)
end
after_transition all => :stopping do |me|
Resque.enqueue(me.class, me.id, "_stop!")
end
end
########################################################################################################################
def self.queue
QUEUE
end
def self.perform(id, action, email = nil)
+ self.connection.verify! # ActiveRecord::Base.verify_active_connections!
self.find(id).send(action, email)
end
########################################################################################################################
def route
[self.account, self]
end
def attachment_ids=(attachment_ids)
self.attachments.clear
attachment_ids.each do |attachment_id|
if attachment_id.present? && (asset = account.assets.find_by_id(attachment_id))
self.attachments << asset
end
end
end
def draft=(draft)
return unless draft
%w(subject content).each do |method|
self.send("#{method}=", draft.send(method))
end
end
########################################################################################################################
def progress_percent
return 0 if self.recipients_count.to_i < 1
(100 * count / self.recipients_count).round
end
#How long did it take to send newsletter
def sending_time
((self.delivery_ended_at || Time.now) - (self.delivery_started_at || Time.now)).to_f.round(2)
end
def count
self.deliveries_count.to_i + self.fails_count.to_i
end
def finishs_count
self.deliveries_count.to_i - self.bounces_count.to_i - self.reads_count.to_i
end
def sendings_per_second
(sending_time > 0) ? (count.to_f / sending_time).round(2) : 0
end
def update_stats!
if pre_sending? || sending?
self.delivery_started_at ||= self.live_send_outs.first(:order => "created_at ASC").try(:created_at)
self.deliveries_count = self.live_send_outs.where("finished_at IS NOT NULL").count
self.fails_count = self.live_send_outs.with_state(:failed).count
end
if done?
self.finish!
end
if finished?
self.bounces_count = live_send_outs.with_state(:bounced).count
self.reads_count = live_send_outs.with_state(:read).count
end
self.save!
end
def done?
(sending? && self.live_send_outs.with_state(:sheduled).count == 0) ||
(testing? && self.test_send_outs.with_state(:sheduled).count == 0)
end
#-------------------------------------------------------------------------------------------------------------------------
private
def set_recipients_count
self.recipients_count = recipients.count
end
def _send_test!(email = nil)
account.test_recipient_emails_array(email).each do |test_recipient_email|
self.test_send_outs.create!(:email => test_recipient_email.strip)
end
process!
end
def _send_live!(*args)
self.recipients.each do |live_recipient|
self.live_send_outs.create!(:recipient => live_recipient)
end
process!
end
def _resume_live!(*args)
#self.update_attributes(:delivery_started_at => Time.now)
self.live_send_outs.with_state(:stopped).map(&:resume!)
process!
end
def _stop!(*args)
self.live_send_outs.with_state(:sheduled).update_all(:state => 'stopped')
finish!
end
end
# == Schema Information
#
# Table name: newsletters
#
# id :integer(4) not null, primary key
# subject :string(255)
# content :text
# mode :integer(4) default(0), not null
# status :integer(4) default(0), not null
# last_sent_id :integer(4)
# recipients_count :integer(4) default(0), not null
# deliveries_count :integer(4) default(0), not null
# fails_count :integer(4) default(0), not null
# deliver_at :datetime
# delivery_started_at :datetime
# delivery_ended_at :datetime
# account_id :integer(4)
# created_at :datetime
# updated_at :datetime
# state :string(255) default("finished")
# bounces_count :integer(4) default(0), not null
# reads_count :integer(4) default(0), not null
#
# Indexes
#
# index_newsletters_on_account_id (account_id)
#
# updated_at :datetime
|
rngtng/nups
|
aad0f655f9fa7075558dcac7812e2a8ffccca4e0
|
replaced annotate plugin by gem, updated annotations
|
diff --git a/Gemfile b/Gemfile
index 454877f..f05a544 100644
--- a/Gemfile
+++ b/Gemfile
@@ -1,79 +1,81 @@
source 'http://rubygems.org'
gem 'rails', '~> 3.2.0.rc2'
gem 'mysql2'
gem 'jquery-rails'
gem 'haml'
#Authorization
gem "devise"
# Use resque for async jobs
gem 'resque'
gem 'resque-scheduler', '~> 2.0.0.e'
gem 'resque-jobs-per-fork'
#For handling File uploads
gem 'paperclip'
#For proper pagination
gem 'kaminari'
# For excel export
gem 'ekuseru'
# parsing bounce emails
gem 'bounce_email'
gem 'state_machine', :git => 'git://github.com/pluginaweek/state_machine.git'
gem 'nokogiri'
gem 'premailer'
gem 'rpm_contrib'
gem 'newrelic_rpm'
gem 'airbrake'
# auto_link replacement
gem 'rinku'
+gem 'annotate', :git => 'git://github.com/ctran/annotate_models.git'
+
gem 'rspec-rails', :group => [:development, :test]
gem 'spin', :group => [:development, :test]
group :development do
gem 'capistrano'
gem 'mailcatcher'
gem 'ruby-graphviz', :require => 'graphviz'
end
# http://metaskills.net/2011/07/29/use-compass-sass-framework-files-with-the-rails-3.1.0.rc5-asset-pipeline/
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails'
# gem 'compass', :git => 'git://github.com/chriseppstein/compass.git', :branch => 'rails31'
end
group :test do
gem 'json' #needed for resque to run on travis-ci
gem 'resque_spec'
gem 'delorean'
#selenium
gem 'capybara'
gem 'database_cleaner', :git => 'git://github.com/bmabey/database_cleaner.git'
#fixtures
gem 'faker'
gem 'factory_girl_rails'
gem 'watchr'
gem 'simplecov'
end
diff --git a/Gemfile.lock b/Gemfile.lock
index 23f77a1..5dd94cb 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -1,301 +1,308 @@
GIT
remote: git://github.com/bmabey/database_cleaner.git
revision: 98675ee71d7af1514192eef11ab5db487a656e2f
specs:
database_cleaner (0.7.0)
+GIT
+ remote: git://github.com/ctran/annotate_models.git
+ revision: 032565653b98e0790ddd8a070579566eb60a850c
+ specs:
+ annotate (2.4.1.beta1)
+
GIT
remote: git://github.com/pluginaweek/state_machine.git
revision: de425325959303bda6edfdc6b2a4ae89b19c23cc
specs:
state_machine (1.1.1)
GEM
remote: http://rubygems.org/
specs:
actionmailer (3.2.0.rc2)
actionpack (= 3.2.0.rc2)
mail (~> 2.3.0)
actionpack (3.2.0.rc2)
activemodel (= 3.2.0.rc2)
activesupport (= 3.2.0.rc2)
builder (~> 3.0.0)
erubis (~> 2.7.0)
journey (~> 1.0.0.rc1)
rack (~> 1.4.0)
rack-cache (~> 1.1)
rack-test (~> 0.6.1)
sprockets (~> 2.1.2)
activemodel (3.2.0.rc2)
activesupport (= 3.2.0.rc2)
builder (~> 3.0.0)
activerecord (3.2.0.rc2)
activemodel (= 3.2.0.rc2)
activesupport (= 3.2.0.rc2)
arel (~> 3.0.0.rc1)
tzinfo (~> 0.3.29)
activeresource (3.2.0.rc2)
activemodel (= 3.2.0.rc2)
activesupport (= 3.2.0.rc2)
activesupport (3.2.0.rc2)
i18n (~> 0.6)
multi_json (~> 1.0)
addressable (2.2.6)
airbrake (3.0.9)
activesupport
builder
arel (3.0.0.rc1)
bcrypt-ruby (3.0.1)
bounce_email (0.2.2)
mail
builder (3.0.0)
capistrano (2.9.0)
highline
net-scp (>= 1.0.0)
net-sftp (>= 2.0.0)
net-ssh (>= 2.0.14)
net-ssh-gateway (>= 1.1.0)
capybara (1.1.2)
mime-types (>= 1.16)
nokogiri (>= 1.3.3)
rack (>= 1.0.0)
rack-test (>= 0.5.4)
selenium-webdriver (~> 2.0)
xpath (~> 0.1.4)
childprocess (0.2.8)
ffi (~> 1.0.6)
chronic (0.6.6)
cocaine (0.2.1)
coffee-rails (3.2.1)
coffee-script (>= 2.2.0)
railties (~> 3.2.0.beta)
coffee-script (2.2.0)
coffee-script-source
execjs
coffee-script-source (1.2.0)
css_parser (1.2.5)
addressable
daemons (1.1.5)
delorean (1.2.0)
chronic
devise (1.5.3)
bcrypt-ruby (~> 3.0)
orm_adapter (~> 0.0.3)
warden (~> 1.1)
diff-lcs (1.1.3)
ekuseru (0.3.10)
rails (>= 3.0)
spreadsheet (>= 0.6)
erubis (2.7.0)
eventmachine (0.12.10)
execjs (1.2.13)
multi_json (~> 1.0)
factory_girl (2.3.2)
activesupport
factory_girl_rails (1.4.0)
factory_girl (~> 2.3.0)
railties (>= 3.0.0)
faker (1.0.1)
i18n (~> 0.4)
ffi (1.0.11)
haml (3.1.4)
highline (1.6.9)
hike (1.2.1)
htmlentities (4.3.1)
i18n (0.6.0)
journey (1.0.0.rc4)
jquery-rails (2.0.0)
railties (>= 3.2.0.beta, < 5.0)
thor (~> 0.14)
json (1.6.4)
kaminari (0.13.0)
actionpack (>= 3.0.0)
activesupport (>= 3.0.0)
railties (>= 3.0.0)
mail (2.3.0)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
mailcatcher (0.5.5)
activesupport (~> 3.0)
eventmachine (~> 0.12)
haml (~> 3.1)
mail (~> 2.3)
sinatra (~> 1.2)
skinny (~> 0.2)
sqlite3 (~> 1.3)
thin (~> 1.2)
mime-types (1.17.2)
multi_json (1.0.4)
mysql2 (0.3.11)
net-scp (1.0.4)
net-ssh (>= 1.99.1)
net-sftp (2.0.5)
net-ssh (>= 2.0.9)
net-ssh (2.2.2)
net-ssh-gateway (1.1.0)
net-ssh (>= 1.99.1)
newrelic_rpm (3.3.1)
nokogiri (1.5.0)
orm_adapter (0.0.6)
paperclip (2.4.5)
activerecord (>= 2.3.0)
activesupport (>= 2.3.2)
cocaine (>= 0.0.2)
mime-types
polyglot (0.3.3)
premailer (1.7.3)
css_parser (>= 1.1.9)
htmlentities (>= 4.0.0)
rack (1.4.0)
rack-cache (1.1)
rack (>= 0.4)
rack-protection (1.2.0)
rack
rack-ssl (1.3.2)
rack
rack-test (0.6.1)
rack (>= 1.0)
rails (3.2.0.rc2)
actionmailer (= 3.2.0.rc2)
actionpack (= 3.2.0.rc2)
activerecord (= 3.2.0.rc2)
activeresource (= 3.2.0.rc2)
activesupport (= 3.2.0.rc2)
bundler (~> 1.0)
railties (= 3.2.0.rc2)
railties (3.2.0.rc2)
actionpack (= 3.2.0.rc2)
activesupport (= 3.2.0.rc2)
rack-ssl (~> 1.3.2)
rake (>= 0.8.7)
rdoc (~> 3.4)
thor (~> 0.14.6)
rake (0.9.2.2)
rdoc (3.12)
json (~> 1.4)
redis (2.2.2)
redis-namespace (1.0.3)
redis (< 3.0.0)
resque (1.19.0)
multi_json (~> 1.0)
redis-namespace (~> 1.0.2)
sinatra (>= 0.9.2)
vegas (~> 0.1.2)
resque-jobs-per-fork (1.15.1)
resque (~> 1.15)
resque-scheduler (2.0.0.e)
redis (>= 2.0.1)
resque (>= 1.15.0)
rufus-scheduler
resque_spec (0.8.1)
resque (>= 1.19.0)
rspec (>= 2.5.0)
rinku (1.5.0)
rpm_contrib (2.1.7)
newrelic_rpm (>= 3.1.1)
newrelic_rpm (>= 3.1.1)
rspec (2.8.0)
rspec-core (~> 2.8.0)
rspec-expectations (~> 2.8.0)
rspec-mocks (~> 2.8.0)
rspec-core (2.8.0)
rspec-expectations (2.8.0)
diff-lcs (~> 1.1.2)
rspec-mocks (2.8.0)
rspec-rails (2.8.1)
actionpack (>= 3.0)
activesupport (>= 3.0)
railties (>= 3.0)
rspec (~> 2.8.0)
ruby-graphviz (1.0.3)
ruby-ole (1.2.11.2)
rubyzip (0.9.5)
rufus-scheduler (2.0.16)
tzinfo (>= 0.3.23)
sass (3.1.12)
sass-rails (3.2.3)
railties (~> 3.2.0.beta)
sass (>= 3.1.10)
tilt (~> 1.3)
selenium-webdriver (2.16.0)
childprocess (>= 0.2.5)
ffi (~> 1.0.9)
multi_json (~> 1.0.4)
rubyzip
simplecov (0.5.4)
multi_json (~> 1.0.3)
simplecov-html (~> 0.5.3)
simplecov-html (0.5.3)
sinatra (1.3.2)
rack (~> 1.3, >= 1.3.6)
rack-protection (~> 1.2)
tilt (~> 1.3, >= 1.3.3)
skinny (0.2.0)
eventmachine (~> 0.12)
thin (~> 1.2)
spin (0.4.2)
spreadsheet (0.6.5.9)
ruby-ole (>= 1.0)
sprockets (2.1.2)
hike (~> 1.2)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sqlite3 (1.3.5)
thin (1.3.1)
daemons (>= 1.0.9)
eventmachine (>= 0.12.6)
rack (>= 1.0.0)
thor (0.14.6)
tilt (1.3.3)
treetop (1.4.10)
polyglot
polyglot (>= 0.3.1)
tzinfo (0.3.31)
vegas (0.1.8)
rack (>= 1.0.0)
warden (1.1.0)
rack (>= 1.0)
watchr (0.7)
xpath (0.1.4)
nokogiri (~> 1.3)
PLATFORMS
ruby
DEPENDENCIES
airbrake
+ annotate!
bounce_email
capistrano
capybara
coffee-rails
database_cleaner!
delorean
devise
ekuseru
factory_girl_rails
faker
haml
jquery-rails
json
kaminari
mailcatcher
mysql2
newrelic_rpm
nokogiri
paperclip
premailer
rails (~> 3.2.0.rc2)
resque
resque-jobs-per-fork
resque-scheduler (~> 2.0.0.e)
resque_spec
rinku
rpm_contrib
rspec-rails
ruby-graphviz
sass-rails (~> 3.2.3)
simplecov
spin
state_machine!
watchr
diff --git a/Rakefile b/Rakefile
index 2ec38e0..fc8cc9b 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,17 +1,18 @@
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
require 'rake'
require 'rdoc/task'
+require 'annotate/tasks'
Nups::Application.load_tasks
task :travis do
["rake db:schema:load", "rake spec"].each do |cmd|
puts "Starting to run #{cmd}..."
system("export DISPLAY=:99.0 && bundle exec #{cmd}")
raise "#{cmd} failed!" unless $?.exitstatus == 0
end
end
diff --git a/app/models/account.rb b/app/models/account.rb
index ae897bf..e4c0cd8 100644
--- a/app/models/account.rb
+++ b/app/models/account.rb
@@ -1,121 +1,124 @@
require 'net/imap'
class Account < ActiveRecord::Base
belongs_to :user
attr_protected :permalink
has_many :assets, :dependent => :destroy
has_many :newsletters, :dependent => :destroy
has_many :recipients, :dependent => :destroy
validates :from, :presence => true
validates :name, :presence => true
validates :user_id, :presence => true
validates :permalink, :presence => true, :uniqueness => true, :on => :create
scope :with_mail_config, :conditions => "mail_config_raw != ''"
def self.queue
Bounce::QUEUE
end
def self.perform(id = nil)
if id
self.find(id).process_bounces
else
Account.all.each do |account|
Resque.enqueue(Account, account.id)
end
end
end
def test_recipient_emails_array(extra_email = nil)
tester = [test_recipient_emails, extra_email].join(' ')
tester.split(/,| |\||;|\r|\n|\t/).select do |email|
email.include?('@')
end.compact.uniq
end
def mail_config
@mail_config ||= YAML::load(self.mail_config_raw) || $mail_config
rescue
$mail_config
end
def from_email
email_exp = Regexp.new(/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/)
self.from.scan(email_exp).first
end
def sender
@sender ||= (self.mail_config && self.mail_config['sender']) || self.from_email
end
def reply_to
@reply_to ||= (self.mail_config && self.mail_config['reply_to']) || self.from_email
end
def process_bounces(mbox = 'INBOX', encoding = 'RFC822')
if mail_config && (mail_settings = mail_config['smtp_settings'])
Net::IMAP.new(mail_settings[:address].gsub('smtp', 'imap')).tap do |imap|
imap.authenticate('LOGIN', mail_settings[:user_name], mail_settings[:password])
imap.select(mbox) #use examaine for read only
# all msgs
if imap.status(mbox, ["MESSAGES"])["MESSAGES"] > 0
imap.uid_search(["SINCE", "1-Jan-1969", "NOT", "DELETED"]).each do |uid|
begin
Bounce.create!(:raw => imap.uid_fetch(uid, [encoding]).first.attr[encoding])
imap.uid_store(uid, "+FLAGS", [:Deleted])
rescue ArgumentError => e
imap.uid_store(uid, "+FLAGS", [:Deleted])
rescue => e
Airbrake.notify(
:error_class => e.class,
:error_message => e.message,
:parameters => {:account_id => self.id, :uid => uid}
)
end
end
end
imap.expunge
imap.close
end
end
end
protected
# in case we generate a duplicate confirm_code, regenerate a new one
def run_validations!
super.tap do
if errors[:permalink].present?
self.permalink = SecureRandom.hex(8)
return valid? #re-run validation
end
end
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: accounts
#
# id :integer(4) not null, primary key
-# user_id :integer(4)
-# color :string(255) default("#FFF")
-# from :string(255)
-# has_attachments :boolean(1)
-# has_html :boolean(1) default(TRUE)
-# has_scheduling :boolean(1)
-# has_text :boolean(1) default(TRUE)
-# mail_config_raw :text
# name :string(255)
-# permalink :string(255)
+# from :string(255)
+# user_id :integer(4)
# subject :string(255)
# template_html :text
# template_text :text
# test_recipient_emails :text
# created_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# updated_at :datetime
+# color :string(255) default("#FFF")
+# has_html :boolean(1) default(TRUE)
+# has_text :boolean(1) default(TRUE)
+# has_attachments :boolean(1)
+# has_scheduling :boolean(1)
+# mail_config_raw :text
+# permalink :string(255)
+#
+
+# updated_at :datetime
diff --git a/app/models/asset.rb b/app/models/asset.rb
index fe5e88a..5bd6536 100644
--- a/app/models/asset.rb
+++ b/app/models/asset.rb
@@ -1,43 +1,46 @@
class Asset < ActiveRecord::Base
belongs_to :user
belongs_to :account
belongs_to :newsletter
has_attached_file :attachment
validates_attachment_presence :attachment
validates :user_id, :presence => true
validates :account_id, :presence => true
def name
attachment_file_name
end
def size
attachment_file_size
end
def path
attachment.path
end
def content_type
attachment.content_type
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: assets
#
# id :integer(4) not null, primary key
-# account_id :integer(4)
-# newsletter_id :integer(4)
-# user_id :integer(4)
-# attachment_content_type :string(255)
# attachment_file_name :string(255)
+# attachment_content_type :string(255)
# attachment_file_size :string(255)
+# user_id :integer(4)
+# account_id :integer(4)
+# newsletter_id :integer(4)
# created_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# updated_at :datetime
+#
+
+# updated_at :datetime
diff --git a/app/models/bounce.rb b/app/models/bounce.rb
index a013779..1be0d25 100644
--- a/app/models/bounce.rb
+++ b/app/models/bounce.rb
@@ -1,74 +1,77 @@
require 'bounce_email'
class Bounce < ActiveRecord::Base
QUEUE = :nups_bounces
belongs_to :send_out
belongs_to :recipient
validates :raw, :presence => true
after_create :schedule_for_processing
after_save :update_send_out
def self.queue
Bounce::QUEUE
end
def self.perform(id)
self.find(id).process!
end
def mail
@mail ||= ::BounceEmail::Mail.new(self.raw)
end
def mail_id
@mail_id ||= Array(mail.body.to_s.match(/#{Newsletter::HEADER_ID}:? ?([^\r\n ]+)/))[1]
end
def process!
if mail.bounced? && mail_id
_, self.send_out_id, self.recipient_id = mail_id.split('-')
self.send_at = mail.date
self.subject = mail.subject
self.from = Array(mail.from).join(';')
self.header = mail.header.to_s
self.body = mail.body.decoded
self.error_status = mail.error_status
self.save!
end
end
def schedule_for_processing
Resque.enqueue(Bounce, self.id)
end
def error_message
"#{mail.diagnostic_code} #{mail.error_status}"
end
def update_send_out
send_out.bounce!(self.error_message) if send_out
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: bounces
#
# id :integer(4) not null, primary key
# account_id :integer(4)
# recipient_id :integer(4)
-# send_out_id :integer(4)
-# body :text
-# error_status :string(255)
# from :string(255)
+# subject :string(255)
+# send_at :datetime
# header :text
+# body :text
# raw :text
-# subject :string(255)
# created_at :datetime
-# send_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# updated_at :datetime
+# error_status :string(255)
+# send_out_id :integer(4)
+#
+
+# updated_at :datetime
diff --git a/app/models/domain.rb b/app/models/domain.rb
index e6eed09..2b7364c 100644
--- a/app/models/domain.rb
+++ b/app/models/domain.rb
@@ -1,25 +1,28 @@
class Domain < ActiveRecord::Base
belongs_to :user
def main_url
"https://sslsites.de/kundenmenue/uebersicht.php?rekm_login=#{username}&rekm_password=#{password}"
end
def ftp_url
"https://sslsites.de/kundenmenue/ftp.php?rekm_login=#{username}&rekm_password=#{password}"
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: domains
#
# id :integer(4) not null, primary key
# user_id :integer(4)
# name :string(255)
# number :string(255)
-# password :string(255)
# username :string(255)
+# password :string(255)
# created_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# updated_at :datetime
+#
+
+# updated_at :datetime
diff --git a/app/models/live_send_out.rb b/app/models/live_send_out.rb
index efcc7a6..5a5dccb 100644
--- a/app/models/live_send_out.rb
+++ b/app/models/live_send_out.rb
@@ -1,58 +1,66 @@
class LiveSendOut < SendOut
validates :recipient_id, :presence => true, :uniqueness => {:scope => [:newsletter_id, :type]}, :on => :create
before_validation :set_email, :on => :create
state_machine :initial => :sheduled do
before_transition :delivering => :finished do |me|
me.finished_at = Time.now
me.recipient.update_attribute(:deliveries_count, me.recipient.deliveries_count + 1)
end
before_transition :delivering => :failed do |me, transition|
me.error_message = transition.args[0].message
me.recipient.update_attribute(:fails_count, me.recipient.fails_count + 1)
end
after_transition :delivering => :failed do |me, transition|
# a bit dirty hack: force to end transition successfull but still
# propagade execption
me.connection.execute("COMMIT") #prevent rollback
raise transition.args[0]
end
before_transition :finished => :read do |me|
me.recipient.update_attribute(:reads_count, me.recipient.reads_count + 1)
end
before_transition :finished => :bounced do |me, transition|
me.error_message = transition.args[0]
me.recipient.update_attribute(:bounces_count, me.recipient.bounces_count + 1)
end
end
def issue_id
["ma", self.id, self.recipient_id].join('-')
end
private
def set_email
self.email = recipient.email
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: send_outs
#
# id :integer(4) not null, primary key
-# newsletter_id :integer(4)
# recipient_id :integer(4)
+# newsletter_id :integer(4)
+# type :string(255)
+# state :string(255)
# email :string(255)
# error_message :text
-# state :string(255)
-# type :string(255)
# created_at :datetime
+# updated_at :datetime
# finished_at :datetime
-# updated_at :datetime
\ No newline at end of file
+#
+# Indexes
+#
+# index_send_outs_on_newsletter_id_and_type (newsletter_id,type)
+# index_send_outs_on_newsletter_id_and_type_and_recipient_id (newsletter_id,type,recipient_id)
+#
+
+# updated_at :datetime
diff --git a/app/models/newsletter.rb b/app/models/newsletter.rb
index db366d4..bc1a847 100644
--- a/app/models/newsletter.rb
+++ b/app/models/newsletter.rb
@@ -1,209 +1,218 @@
class Newsletter < ActiveRecord::Base
QUEUE = :nups_newsletter
HEADER_ID = "X-MA-Id"
belongs_to :account
has_many :recipients, :through => :account, :conditions => { 'recipients.state' => :confirmed }
has_many :attachments, :class_name => 'Asset'
# http://stackoverflow.com/questions/738906/rails-dependent-and-delete
has_many :send_outs, :dependent => :delete_all #send_out has no dependency, speed it up
has_many :live_send_outs
has_many :test_send_outs
scope :with_account, lambda { |account| account ? where(:account_id => account.id) : {} }
validates :account_id, :presence => true
validates :subject, :presence => true
before_create :set_recipients_count
########################################################################################################################
state_machine :initial => :new do
event :send_test do
transition :new => :pre_testing
transition :tested => :pre_testing
end
event :send_live do
transition :tested => :pre_sending
transition :stopped => :pre_sending
end
event :process do
transition :pre_testing => :testing
transition :pre_sending => :sending
end
event :stop do
transition :sending => :stopping
transition :testing => :new
end
event :finish do
transition :sending => :finished
transition :testing => :tested
transition :stopping => :stopped
end
after_transition all => :pre_testing do |me, transition|
Resque.enqueue(me.class, me.id, "_send_test!", transition.args[0])
end
after_transition :tested => :pre_sending do |me|
if me.deliver_at && me.deliver_at > Time.now
Resque.enqueue_at(me.deliver_at, me.class, me.id, "_send_live!")
else
Resque.enqueue(me.class, me.id, "_send_live!")
end
end
after_transition :stopped => :pre_sending do |me|
Resque.enqueue(me.class, me.id, "_resume_live!")
end
before_transition :pre_sending => :sending do |me|
me.recipients_count = me.live_send_outs.count #TODO what if stopped??
end
before_transition :sending => :finished do |me|
me.delivery_ended_at = me.live_send_outs.first(:select => "finished_at", :order => "finished_at DESC").try(:finished_at)
end
after_transition all => :stopping do |me|
Resque.enqueue(me.class, me.id, "_stop!")
end
end
########################################################################################################################
def self.queue
QUEUE
end
def self.perform(id, action, email = nil)
self.find(id).send(action, email)
end
########################################################################################################################
def route
[self.account, self]
end
def attachment_ids=(attachment_ids)
self.attachments.clear
attachment_ids.each do |attachment_id|
if attachment_id.present? && (asset = account.assets.find_by_id(attachment_id))
self.attachments << asset
end
end
end
def draft=(draft)
return unless draft
%w(subject content).each do |method|
self.send("#{method}=", draft.send(method))
end
end
########################################################################################################################
def progress_percent
return 0 if self.recipients_count.to_i < 1
(100 * count / self.recipients_count).round
end
#How long did it take to send newsletter
def sending_time
((self.delivery_ended_at || Time.now) - (self.delivery_started_at || Time.now)).to_f.round(2)
end
def count
self.deliveries_count.to_i + self.fails_count.to_i
end
def finishs_count
self.deliveries_count.to_i - self.bounces_count.to_i - self.reads_count.to_i
end
def sendings_per_second
(sending_time > 0) ? (count.to_f / sending_time).round(2) : 0
end
def update_stats!
if pre_sending? || sending?
self.delivery_started_at ||= self.live_send_outs.first(:order => "created_at ASC").try(:created_at)
self.deliveries_count = self.live_send_outs.where("finished_at IS NOT NULL").count
self.fails_count = self.live_send_outs.with_state(:failed).count
end
if done?
self.finish!
end
if finished?
self.bounces_count = live_send_outs.with_state(:bounced).count
self.reads_count = live_send_outs.with_state(:read).count
end
self.save!
end
def done?
(sending? && self.live_send_outs.with_state(:sheduled).count == 0) ||
(testing? && self.test_send_outs.with_state(:sheduled).count == 0)
end
#-------------------------------------------------------------------------------------------------------------------------
private
def set_recipients_count
self.recipients_count = recipients.count
end
def _send_test!(email = nil)
account.test_recipient_emails_array(email).each do |test_recipient_email|
self.test_send_outs.create!(:email => test_recipient_email.strip)
end
process!
end
def _send_live!(*args)
self.recipients.each do |live_recipient|
self.live_send_outs.create!(:recipient => live_recipient)
end
process!
end
def _resume_live!(*args)
#self.update_attributes(:delivery_started_at => Time.now)
self.live_send_outs.with_state(:stopped).map(&:resume!)
process!
end
def _stop!(*args)
self.live_send_outs.with_state(:sheduled).update_all(:state => 'stopped')
finish!
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: newsletters
#
# id :integer(4) not null, primary key
-# account_id :integer(4)
-# last_sent_id :integer(4)
-# content :text
-# deliveries_count :integer(4) not null, default(0)
-# errors_count :integer(4) not null, default(0)
-# mode :integer(4) not null, default(0)
-# recipients_count :integer(4) not null, default(0)
-# state :string(255) default("finished")
-# status :integer(4) not null, default(0)
# subject :string(255)
-# created_at :datetime
+# content :text
+# mode :integer(4) default(0), not null
+# status :integer(4) default(0), not null
+# last_sent_id :integer(4)
+# recipients_count :integer(4) default(0), not null
+# deliveries_count :integer(4) default(0), not null
+# fails_count :integer(4) default(0), not null
# deliver_at :datetime
-# delivery_ended_at :datetime
# delivery_started_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# delivery_ended_at :datetime
+# account_id :integer(4)
+# created_at :datetime
+# updated_at :datetime
+# state :string(255) default("finished")
+# bounces_count :integer(4) default(0), not null
+# reads_count :integer(4) default(0), not null
+#
+# Indexes
+#
+# index_newsletters_on_account_id (account_id)
+#
+
+# updated_at :datetime
diff --git a/app/models/recipient.rb b/app/models/recipient.rb
index c1e2d81..5e3d2d4 100644
--- a/app/models/recipient.rb
+++ b/app/models/recipient.rb
@@ -1,105 +1,113 @@
class Recipient < ActiveRecord::Base
SEARCH_COLUMNS = %w(email first_name last_name)
belongs_to :account
attr_accessible :gender, :first_name, :last_name, :email
attr_accessible :account, :state, :gender, :first_name, :last_name, :email, :as => :test
has_many :newsletters, :through => :account
has_many :live_send_outs
scope :greater_than, lambda { |recipient_id| {:conditions => [ "recipients.id > ?", recipient_id ] } }
scope :search, lambda { |search| search.blank? ? {} : {:conditions => SEARCH_COLUMNS.map { |column| "#{column} LIKE '%#{search}%'" }.join(' OR ') } }
scope :confirmed, :conditions => { :state => :confirmed}
validates :account_id, :presence => true
validates :email, :presence => true, :uniqueness => {:scope => :account_id}, :email_format => true
validates :confirm_code, :presence => true, :uniqueness => true, :on => :create
StateMachine::Machine.ignore_method_conflicts = true #to enable #delete
state_machine :initial => :pending do
event :pending do
transition :pending => :pending
transition :deleted => :pending
end
event :confirm do
transition :pending => :confirmed
transition :confirmed => :confirmed
transition :deleted => :confirmed
end
event :disable do
transition any => :disabled
end
event :delete do
transition any => :deleted
end
end
def self.find_or_build_by(attrs)
where(attrs).first || new(attrs)
end
alias_method :force_destroy, :destroy
def destroy
self.delete!
self
end
def update_stats!
self.deliveries_count = live_send_outs.with_states(:finished, :failed, :bounced, :read).count
self.bounces_count = live_send_outs.with_state(:bounced).count
self.fails_count = live_send_outs.with_state(:failed).count
self.reads_count = live_send_outs.with_state(:read).count
self.save!
end
protected
# in case we generate a duplicate confirm_code, reset code and regenerate a new one
def run_validations!
super.tap do
if errors[:confirm_code].present?
self.confirm_code = SecureRandom.hex(8)
return valid? #re-run validation
end
end
end
#temporary will soon be gone
def move_bounce_to_send_outs
self.bounces.split("\n").each do |bounce|
begin
if ids = bounce.scan(/ma-(\d+)-(\d+)/).first
account_id, newsletter_id = ids
LiveSendOut.create!(:newsletter_id => newsletter_id, :state => 'bounced', :error_message => bounce, :recipient_id => self.id, :email => self.email)
end
rescue => e
puts e.message
end
end
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: recipients
#
# id :integer(4) not null, primary key
-# account_id :integer(4)
-# bounces :text
-# bounces_count :integer(4) not null, default(0)
-# confirm_code :string(255)
-# deliveries_count :integer(4) not null, default(0)
-# email :string(255)
-# failed_count :integer(4) not null, default(0)
-# first_name :string(255)
# gender :string(255)
+# first_name :string(255)
# last_name :string(255)
-# reads_count :integer(4) not null, default(0)
-# state :string(255) default("pending")
+# email :string(255)
+# deliveries_count :integer(4) default(0), not null
+# bounces_count :integer(4) default(0), not null
+# account_id :integer(4)
# created_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# updated_at :datetime
+# fails_count :integer(4) default(0), not null
+# confirm_code :string(255)
+# state :string(255) default("pending")
+# reads_count :integer(4) default(0), not null
+#
+# Indexes
+#
+# index_recipients_on_id_and_account_id (id,account_id) UNIQUE
+# index_recipients_on_email (email)
+# index_recipients_on_account_id (account_id)
+#
+
+# updated_at :datetime
diff --git a/app/models/send_out.rb b/app/models/send_out.rb
index a39bb9e..cf4697c 100644
--- a/app/models/send_out.rb
+++ b/app/models/send_out.rb
@@ -1,93 +1,101 @@
class SendOut < ActiveRecord::Base
QUEUE = :nups_send_outs
belongs_to :newsletter
belongs_to :recipient
validates :newsletter_id, :presence => true
after_save :async_deliver!
state_machine :initial => :sheduled do
event :deliver do
transition :sheduled => :delivering
end
event :resume do
transition :stopped => :sheduled
end
event :stop do
transition :sheduled => :stopped
end
event :finish do
transition :delivering => :finished
end
event :failure do
transition :delivering => :failed
end
event :read do
transition :finished => :read
transition :read => :read
end
event :bounce do
transition :finished => :bounced
transition :bounced => :bounced
end
after_transition :sheduled => :delivering do |me|
begin
me.issue.deliver
me.finish!
rescue Exception => e
me.failure!(e)
end
end
end
########################################################################################################################
def self.queue
QUEUE
end
def self.perform(id)
with_state(:sheduled).find_by_id(id, :include => [:newsletter, :recipient]).try(:deliver!)
end
def issue
@issue ||= NewsletterMailer.issue(self.newsletter, self.recipient, self.id).tap do |issue|
issue.header[Newsletter::HEADER_ID] = issue_id
end
end
def issue_id #likely overwritten by subclasses
["ma", self.id].join('-')
end
private
def async_deliver!
if sheduled?
Resque.enqueue(self.class, self.id)
end
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: send_outs
#
# id :integer(4) not null, primary key
-# newsletter_id :integer(4)
# recipient_id :integer(4)
+# newsletter_id :integer(4)
+# type :string(255)
+# state :string(255)
# email :string(255)
# error_message :text
-# state :string(255)
-# type :string(255)
# created_at :datetime
+# updated_at :datetime
# finished_at :datetime
-# updated_at :datetime
\ No newline at end of file
+#
+# Indexes
+#
+# index_send_outs_on_newsletter_id_and_type (newsletter_id,type)
+# index_send_outs_on_newsletter_id_and_type_and_recipient_id (newsletter_id,type,recipient_id)
+#
+
+# updated_at :datetime
diff --git a/app/models/test_send_out.rb b/app/models/test_send_out.rb
index a67c25d..aff9184 100644
--- a/app/models/test_send_out.rb
+++ b/app/models/test_send_out.rb
@@ -1,41 +1,49 @@
class TestSendOut < SendOut
state_machine :initial => :sheduled do
before_transition :delivering => :finished do |me|
me.finished_at = Time.now
end
before_transition :delivering => :failed do |me, transition|
me.error_message = transition.args[0]
end
end
def recipient
@recipient ||= Recipient.new(:email => email)
end
def issue_id
["ma", self.id, "test"].join('-')
end
def issue
super.tap do |issue|
issue.subject = "TEST: #{issue.subject}"
end
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: send_outs
#
# id :integer(4) not null, primary key
-# newsletter_id :integer(4)
# recipient_id :integer(4)
+# newsletter_id :integer(4)
+# type :string(255)
+# state :string(255)
# email :string(255)
# error_message :text
-# state :string(255)
-# type :string(255)
# created_at :datetime
+# updated_at :datetime
# finished_at :datetime
-# updated_at :datetime
\ No newline at end of file
+#
+# Indexes
+#
+# index_send_outs_on_newsletter_id_and_type (newsletter_id,type)
+# index_send_outs_on_newsletter_id_and_type_and_recipient_id (newsletter_id,type,recipient_id)
+#
+
+# updated_at :datetime
diff --git a/app/models/user.rb b/app/models/user.rb
index 9d56410..1bbd807 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1,48 +1,57 @@
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :lockable and :timeoutable, :confirmable,
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
devise :database_authenticatable, :authentication_keys => [:username]
# Setup accessible (or protected) attributes for your model
attr_accessible :username, :email, :admin, :password, :password_confirmation
validate :username, :presence => true, :uniqueness => true
has_many :accounts
has_many :newsletters, :through => :accounts
has_many :domains
#https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign_in-using-their-username-or-email-address
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
username = conditions.delete(:username)
where(conditions).where(["username = :value OR email = :value", { :value => username }]).first
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: users
#
# id :integer(4) not null, primary key
-# admin :boolean(1)
+# email :string(255) default(""), not null
+# encrypted_password :string(128) default(""), not null
# confirmation_token :string(255)
-# current_sign_in_ip :string(255)
-# email :string(255) not null, default("")
-# encrypted_password :string(128) not null, default("")
-# last_sign_in_ip :string(255)
-# remember_token :string(255)
+# confirmed_at :datetime
+# confirmation_sent_at :datetime
# reset_password_token :string(255)
+# remember_token :string(255)
+# remember_created_at :datetime
# sign_in_count :integer(4) default(0)
-# username :string(255)
-# confirmation_sent_at :datetime
-# confirmed_at :datetime
-# created_at :datetime
# current_sign_in_at :datetime
# last_sign_in_at :datetime
-# remember_created_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# current_sign_in_ip :string(255)
+# last_sign_in_ip :string(255)
+# created_at :datetime
+# updated_at :datetime
+# username :string(255)
+# admin :boolean(1)
+#
+# Indexes
+#
+# index_users_on_email (email) UNIQUE
+# index_users_on_confirmation_token (confirmation_token) UNIQUE
+# index_users_on_reset_password_token (reset_password_token) UNIQUE
+#
+
+# updated_at :datetime
diff --git a/config/routes.rb b/config/routes.rb
index d1eb597..13c8dd7 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,51 +1,121 @@
Nups::Application.routes.draw do
mount Resque::Server.new => "/resque"
# first created -> highest priority.
root :to => "frame#index"
devise_for :users
match 'newsletters' => 'newsletters#index', :as => :all_newsletters
match 'newsletters/stats' => 'newsletters#stats', :as => :all_newsletter_stats
namespace :admin do
resources :users
resources :accounts
end
namespace :public do
resources :recipients, :only => [:index, :show, :destroy]
end
# resource route with sub-resources:
resources :accounts, :only => [:index] do
resources :newsletters do
member do
get :start
get :stop
end
end
resources :recipients do
collection do
get :delete
delete :multiple_destroy
end
resources :send_outs
end
resources :assets, :only => :create
resources :charts, :only => :index
end
match 'subscribe/:account_permalink' => 'public/recipients#create', :via => 'post', :as => :subscribe
match 'confirm/:recipient_confirm_code' => 'public/recipients#confirm', :via => 'get', :as => :confirm #put
match 'unsubscribe/:recipient_confirm_code' => 'public/recipients#destroy_confirm', :via => 'get', :as => :unsubscribe
match 'unsubscribe/:recipient_confirm_code' => 'public/recipients#destroy', :via => 'delete'
match 'remove/:account_permalink' => 'public/recipients#destroy_by_email', :via => 'delete'
match ':recipient_id/:send_out_id(/:image)' => 'public/newsletters#show', :via => 'get', :as => :newsletter
end
+#== Route Map
+# Generated on 10 Jan 2012 19:05
+#
+# root / frame#index
+# new_user_session GET /users/sign_in(.:format) devise/sessions#new
+# user_session POST /users/sign_in(.:format) devise/sessions#create
+# destroy_user_session GET /users/sign_out(.:format) devise/sessions#destroy
+# user_password POST /users/password(.:format) devise/passwords#create
+# new_user_password GET /users/password/new(.:format) devise/passwords#new
+# edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
+# PUT /users/password(.:format) devise/passwords#update
+# cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel
+# user_registration POST /users(.:format) devise/registrations#create
+# new_user_registration GET /users/sign_up(.:format) devise/registrations#new
+# edit_user_registration GET /users/edit(.:format) devise/registrations#edit
+# PUT /users(.:format) devise/registrations#update
+# DELETE /users(.:format) devise/registrations#destroy
+# all_newsletters /newsletters(.:format) newsletters#index
+# all_newsletter_stats /newsletters/stats(.:format) newsletters#stats
+# admin_users GET /admin/users(.:format) admin/users#index
+# POST /admin/users(.:format) admin/users#create
+# new_admin_user GET /admin/users/new(.:format) admin/users#new
+# edit_admin_user GET /admin/users/:id/edit(.:format) admin/users#edit
+# admin_user GET /admin/users/:id(.:format) admin/users#show
+# PUT /admin/users/:id(.:format) admin/users#update
+# DELETE /admin/users/:id(.:format) admin/users#destroy
+# admin_accounts GET /admin/accounts(.:format) admin/accounts#index
+# POST /admin/accounts(.:format) admin/accounts#create
+# new_admin_account GET /admin/accounts/new(.:format) admin/accounts#new
+# edit_admin_account GET /admin/accounts/:id/edit(.:format) admin/accounts#edit
+# admin_account GET /admin/accounts/:id(.:format) admin/accounts#show
+# PUT /admin/accounts/:id(.:format) admin/accounts#update
+# DELETE /admin/accounts/:id(.:format) admin/accounts#destroy
+# public_recipients GET /public/recipients(.:format) public/recipients#index
+# public_recipient GET /public/recipients/:id(.:format) public/recipients#show
+# DELETE /public/recipients/:id(.:format) public/recipients#destroy
+# start_account_newsletter GET /accounts/:account_id/newsletters/:id/start(.:format) newsletters#start
+# stop_account_newsletter GET /accounts/:account_id/newsletters/:id/stop(.:format) newsletters#stop
+# account_newsletters GET /accounts/:account_id/newsletters(.:format) newsletters#index
+# POST /accounts/:account_id/newsletters(.:format) newsletters#create
+# new_account_newsletter GET /accounts/:account_id/newsletters/new(.:format) newsletters#new
+# edit_account_newsletter GET /accounts/:account_id/newsletters/:id/edit(.:format) newsletters#edit
+# account_newsletter GET /accounts/:account_id/newsletters/:id(.:format) newsletters#show
+# PUT /accounts/:account_id/newsletters/:id(.:format) newsletters#update
+# DELETE /accounts/:account_id/newsletters/:id(.:format) newsletters#destroy
+# delete_account_recipients GET /accounts/:account_id/recipients/delete(.:format) recipients#delete
+# multiple_destroy_account_recipients DELETE /accounts/:account_id/recipients/multiple_destroy(.:format) recipients#multiple_destroy
+# account_recipient_send_outs GET /accounts/:account_id/recipients/:recipient_id/send_outs(.:format) send_outs#index
+# POST /accounts/:account_id/recipients/:recipient_id/send_outs(.:format) send_outs#create
+# new_account_recipient_send_out GET /accounts/:account_id/recipients/:recipient_id/send_outs/new(.:format) send_outs#new
+# edit_account_recipient_send_out GET /accounts/:account_id/recipients/:recipient_id/send_outs/:id/edit(.:format) send_outs#edit
+# account_recipient_send_out GET /accounts/:account_id/recipients/:recipient_id/send_outs/:id(.:format) send_outs#show
+# PUT /accounts/:account_id/recipients/:recipient_id/send_outs/:id(.:format) send_outs#update
+# DELETE /accounts/:account_id/recipients/:recipient_id/send_outs/:id(.:format) send_outs#destroy
+# account_recipients GET /accounts/:account_id/recipients(.:format) recipients#index
+# POST /accounts/:account_id/recipients(.:format) recipients#create
+# new_account_recipient GET /accounts/:account_id/recipients/new(.:format) recipients#new
+# edit_account_recipient GET /accounts/:account_id/recipients/:id/edit(.:format) recipients#edit
+# account_recipient GET /accounts/:account_id/recipients/:id(.:format) recipients#show
+# PUT /accounts/:account_id/recipients/:id(.:format) recipients#update
+# DELETE /accounts/:account_id/recipients/:id(.:format) recipients#destroy
+# account_assets POST /accounts/:account_id/assets(.:format) assets#create
+# account_charts GET /accounts/:account_id/charts(.:format) charts#index
+# accounts GET /accounts(.:format) accounts#index
+# subscribe POST /subscribe/:account_permalink(.:format) public/recipients#create
+# confirm GET /confirm/:recipient_confirm_code(.:format) public/recipients#confirm
+# unsubscribe GET /unsubscribe/:recipient_confirm_code(.:format) public/recipients#destroy_confirm
+# DELETE /unsubscribe/:recipient_confirm_code(.:format) public/recipients#destroy
+# DELETE /remove/:account_permalink(.:format) public/recipients#destroy_by_email
+# newsletter GET /:recipient_id/:send_out_id(/:image)(.:format) public/newsletters#show
diff --git a/spec/fixtures/accounts.yml b/spec/fixtures/accounts.yml
index e1db38d..b62cbaa 100644
--- a/spec/fixtures/accounts.yml
+++ b/spec/fixtures/accounts.yml
@@ -1,49 +1,52 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
admin_account:
name: First
user: admin
subject: example subject1
from: [email protected]
has_html: true
has_text: true
permalink: ffc62a2778b59be5
biff_account:
name: Second
user: biff
subject: example subject2
from: Biff <[email protected]>
has_html: true
has_text: true
permalink: ffc62a2778b59be6
test_recipient_emails: |-
[email protected]
[email protected]
-# == Schema Info
+# == Schema Information
#
# Table name: accounts
#
# id :integer(4) not null, primary key
-# user_id :integer(4)
-# color :string(255) default("#FFF")
-# from :string(255)
-# has_attachments :boolean(1)
-# has_html :boolean(1) default(TRUE)
-# has_scheduling :boolean(1)
-# has_text :boolean(1) default(TRUE)
-# mail_config_raw :text
# name :string(255)
-# permalink :string(255)
+# from :string(255)
+# user_id :integer(4)
# subject :string(255)
# template_html :text
# template_text :text
# test_recipient_emails :text
# created_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# updated_at :datetime
+# color :string(255) default("#FFF")
+# has_html :boolean(1) default(TRUE)
+# has_text :boolean(1) default(TRUE)
+# has_attachments :boolean(1)
+# has_scheduling :boolean(1)
+# mail_config_raw :text
+# permalink :string(255)
+#
+
+# updated_at :datetime
diff --git a/spec/fixtures/assets.yml b/spec/fixtures/assets.yml
index 23f42fb..7308b39 100644
--- a/spec/fixtures/assets.yml
+++ b/spec/fixtures/assets.yml
@@ -1,31 +1,34 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
one:
account: biff_account
newsletter: biff_newsletter
attachment_file_name: picture_one.jpg
user: admin
two:
account: biff_account
attachment_file_name: picture_two.jpg
user: admin
three:
account: biff_account
attachment_file_name: picture_three.jpg
user: admin
-# == Schema Info
+# == Schema Information
#
# Table name: assets
#
# id :integer(4) not null, primary key
-# account_id :integer(4)
-# newsletter_id :integer(4)
-# user_id :integer(4)
-# attachment_content_type :string(255)
# attachment_file_name :string(255)
+# attachment_content_type :string(255)
# attachment_file_size :string(255)
+# user_id :integer(4)
+# account_id :integer(4)
+# newsletter_id :integer(4)
# created_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# updated_at :datetime
+#
+
+# updated_at :datetime
diff --git a/spec/fixtures/newsletters.yml b/spec/fixtures/newsletters.yml
index 82def5c..90d5850 100644
--- a/spec/fixtures/newsletters.yml
+++ b/spec/fixtures/newsletters.yml
@@ -1,38 +1,47 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
biff_newsletter:
account: biff_account
subject: First Newsletter Tested
state: tested
content: "Monthly Newsletter"
biff_newsletter_two:
account: biff_account
subject: Second Newsletter New
state: new
-# == Schema Info
+# == Schema Information
#
# Table name: newsletters
#
# id :integer(4) not null, primary key
-# account_id :integer(4)
-# last_sent_id :integer(4)
-# content :text
-# deliveries_count :integer(4) not null, default(0)
-# errors_count :integer(4) not null, default(0)
-# mode :integer(4) not null, default(0)
-# recipients_count :integer(4) not null, default(0)
-# state :string(255) default("finished")
-# status :integer(4) not null, default(0)
# subject :string(255)
-# created_at :datetime
+# content :text
+# mode :integer(4) default(0), not null
+# status :integer(4) default(0), not null
+# last_sent_id :integer(4)
+# recipients_count :integer(4) default(0), not null
+# deliveries_count :integer(4) default(0), not null
+# fails_count :integer(4) default(0), not null
# deliver_at :datetime
-# delivery_ended_at :datetime
# delivery_started_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# delivery_ended_at :datetime
+# account_id :integer(4)
+# created_at :datetime
+# updated_at :datetime
+# state :string(255) default("finished")
+# bounces_count :integer(4) default(0), not null
+# reads_count :integer(4) default(0), not null
+#
+# Indexes
+#
+# index_newsletters_on_account_id (account_id)
+#
+
+# updated_at :datetime
diff --git a/spec/fixtures/recipients.yml b/spec/fixtures/recipients.yml
index cc3197a..8a0c725 100644
--- a/spec/fixtures/recipients.yml
+++ b/spec/fixtures/recipients.yml
@@ -1,58 +1,66 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
josh:
account: biff_account
email: [email protected]
first_name: josh
last_name: joshua
state: confirmed
confirm_code: josh
wonne:
account: biff_account
email: [email protected]
first_name: wonne
last_name: sonne
state: confirmed
confirm_code: wonne
raziel:
account: biff_account
email: [email protected]
first_name: raziel
last_name: razza
state: pending
confirm_code: raziel
admin:
account: admin_account
email: [email protected]
first_name: admin
last_name: admin
state: confirmed
confirm_code: admin
-# == Schema Info
+# == Schema Information
#
# Table name: recipients
#
# id :integer(4) not null, primary key
-# account_id :integer(4)
-# bounces :text
-# bounces_count :integer(4) not null, default(0)
-# confirm_code :string(255)
-# deliveries_count :integer(4) not null, default(0)
-# email :string(255)
-# failed_count :integer(4) not null, default(0)
-# first_name :string(255)
# gender :string(255)
+# first_name :string(255)
# last_name :string(255)
-# reads_count :integer(4) not null, default(0)
-# state :string(255) default("pending")
+# email :string(255)
+# deliveries_count :integer(4) default(0), not null
+# bounces_count :integer(4) default(0), not null
+# account_id :integer(4)
# created_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# updated_at :datetime
+# fails_count :integer(4) default(0), not null
+# confirm_code :string(255)
+# state :string(255) default("pending")
+# reads_count :integer(4) default(0), not null
+#
+# Indexes
+#
+# index_recipients_on_id_and_account_id (id,account_id) UNIQUE
+# index_recipients_on_email (email)
+# index_recipients_on_account_id (account_id)
+#
+
+# updated_at :datetime
diff --git a/spec/fixtures/users.yml b/spec/fixtures/users.yml
index 1471994..dcc9d86 100644
--- a/spec/fixtures/users.yml
+++ b/spec/fixtures/users.yml
@@ -1,44 +1,53 @@
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
# This model initially had no columns defined. If you add columns to the
# model remove the '{}' from the fixture names and add the columns immediately
# below each fixture, per the syntax in the comments below
#
admin:
username: admin
email: [email protected]
admin: true
encrypted_password: $2a$10$1UMyzDm2SEsGBhFblkiCdelY2s4D48iL7fuEw.rMlxa7/eWUqixdW
confirmed_at: <%= Time.now %>
biff:
username: biff
email: [email protected]
admin: false
encrypted_password: $2a$10$1UMyzDm2SEsGBhFblkiCdelY2s4D48iL7fuEw.rMlxa7/eWUqixdW
confirmed_at: <%= Time.now %>
-# == Schema Info
+# == Schema Information
#
# Table name: users
#
# id :integer(4) not null, primary key
-# admin :boolean(1)
+# email :string(255) default(""), not null
+# encrypted_password :string(128) default(""), not null
# confirmation_token :string(255)
-# current_sign_in_ip :string(255)
-# email :string(255) not null, default("")
-# encrypted_password :string(128) not null, default("")
-# last_sign_in_ip :string(255)
-# remember_token :string(255)
+# confirmed_at :datetime
+# confirmation_sent_at :datetime
# reset_password_token :string(255)
+# remember_token :string(255)
+# remember_created_at :datetime
# sign_in_count :integer(4) default(0)
-# username :string(255)
-# confirmation_sent_at :datetime
-# confirmed_at :datetime
-# created_at :datetime
# current_sign_in_at :datetime
# last_sign_in_at :datetime
-# remember_created_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# current_sign_in_ip :string(255)
+# last_sign_in_ip :string(255)
+# created_at :datetime
+# updated_at :datetime
+# username :string(255)
+# admin :boolean(1)
+#
+# Indexes
+#
+# index_users_on_email (email) UNIQUE
+# index_users_on_confirmation_token (confirmation_token) UNIQUE
+# index_users_on_reset_password_token (reset_password_token) UNIQUE
+#
+
+# updated_at :datetime
diff --git a/spec/models/account_spec.rb b/spec/models/account_spec.rb
index faf1c9a..326c614 100644
--- a/spec/models/account_spec.rb
+++ b/spec/models/account_spec.rb
@@ -1,105 +1,108 @@
require 'spec_helper'
describe Account do
let(:account) { Account.make }
describe "#validation" do
context "#create" do
context "permalink" do
it "generates random string for code" do
Account.create.permalink.should_not nil
end
it "does not mass assign code" do
expect do
Account.create(:permalink => 'custom')
end.to raise_error
end
it "does not overwrite manual set permalink" do
Account.make.tap do |account|
account.permalink = 'custom'
account.save!
account.permalink.should == 'custom'
end
end
it "generates uniqe one" do
Account.make.tap do |account|
account.permalink = Account.make!.permalink
account.save!
end
end
end
end
end
describe "#test_recipient_emails_array" do
{
:by_comma => "[email protected],[email protected],[email protected]",
:by_spec_char => "[email protected];[email protected]|[email protected]",
:uniq => "[email protected],[email protected]\r,[email protected],[email protected]",
:remove_empty => "[email protected],,[email protected],[email protected],",
:and_strip => "[email protected] ;[email protected]\n| [email protected] "
}.each do |name, value|
it "splits recipients #{name}" do
account.test_recipient_emails = value
account.test_recipient_emails_array.should =~ %w([email protected] [email protected] [email protected])
end
end
it "includes extra test_emails" do
account.test_recipient_emails_array("[email protected]").should =~ %w([email protected] [email protected] [email protected])
end
it "uniques extra test_emails" do
account.test_recipient_emails_array("[email protected]").should =~ %w([email protected] [email protected])
end
end
describe "#process_bounces" do
it "doesn't fail" do
account.should_receive(:mail_config).and_return(nil)
account.process_bounces.should be_nil
end
end
describe "#mail_config" do
it "fals back to global when empty" do
account.mail_config.should == $mail_config
end
it "fals back to global when not parsable" do
account.mail_config_raw = "["
account.mail_config.should == $mail_config
end
it "fals back to global when not parsable" do
account.mail_config_raw = "method: smtp"
account.mail_config.should == {"method"=>"smtp"}
end
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: accounts
#
# id :integer(4) not null, primary key
-# user_id :integer(4)
-# color :string(255) default("#FFF")
-# from :string(255)
-# has_attachments :boolean(1)
-# has_html :boolean(1) default(TRUE)
-# has_scheduling :boolean(1)
-# has_text :boolean(1) default(TRUE)
-# mail_config_raw :text
# name :string(255)
-# permalink :string(255)
+# from :string(255)
+# user_id :integer(4)
# subject :string(255)
# template_html :text
# template_text :text
# test_recipient_emails :text
# created_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# updated_at :datetime
+# color :string(255) default("#FFF")
+# has_html :boolean(1) default(TRUE)
+# has_text :boolean(1) default(TRUE)
+# has_attachments :boolean(1)
+# has_scheduling :boolean(1)
+# mail_config_raw :text
+# permalink :string(255)
+#
+
+# updated_at :datetime
diff --git a/spec/models/bounce_spec.rb b/spec/models/bounce_spec.rb
index 777ffa0..bbc7916 100644
--- a/spec/models/bounce_spec.rb
+++ b/spec/models/bounce_spec.rb
@@ -1,98 +1,101 @@
require 'spec_helper'
describe Bounce do
let(:bounce) { Bounce.make }
context "create" do
it "gets enqueued" do
new_bounce = Bounce.create!(:raw => "example Email")
Bounce.should have_queued(new_bounce.id)
end
end
it "find mail id" do
bounce.mail_id.should == "ma-14-87"
end
it "bounced" do
bounce.mail.should be_bounced
end
describe "#process!" do
before do
bounce.process!
end
it "sets subject" do
bounce.subject.should == 'Notificacion del estado del envio'
end
it "sets from" do
bounce.from.should == '[email protected]'
end
it "sets error_status" do
bounce.error_status.should == '5.1.1'
end
it "sets send_out_id" do
bounce.send_out_id.should == 14
end
it "sets recipient_id" do
bounce.recipient_id.should == 87
end
end
context "send_out" do
let(:send_out) { LiveSendOut.make! }
let(:newsletter) { send_out.newsletter }
let(:recipient) { send_out.recipient }
before do
bounce.stub(:mail_id).and_return "ma-#{send_out.id}-#{recipient.id}"
bounce.stub(:error_message).and_return "error"
end
it "changes send_out state" do
expect do
bounce.process!
end.to change { send_out.reload.state }.from('finished').to('bounced')
end
it "adds error_message to send_out" do
expect do
bounce.process!
end.to change { send_out.reload.error_message }.from(nil).to("error")
end
it "increases recipient bounces_count" do
expect do
bounce.process!
end.to change { recipient.reload.bounces_count }.by(1)
end
# #dummy test to make sure fixture is right
it "send_out has same account" do
recipient.account.id.should == newsletter.account.id
end
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: bounces
#
# id :integer(4) not null, primary key
# account_id :integer(4)
# recipient_id :integer(4)
-# send_out_id :integer(4)
-# body :text
-# error_status :string(255)
# from :string(255)
+# subject :string(255)
+# send_at :datetime
# header :text
+# body :text
# raw :text
-# subject :string(255)
# created_at :datetime
-# send_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# updated_at :datetime
+# error_status :string(255)
+# send_out_id :integer(4)
+#
+
+# updated_at :datetime
diff --git a/spec/models/newsletter_spec.rb b/spec/models/newsletter_spec.rb
index da13e25..aa7789a 100644
--- a/spec/models/newsletter_spec.rb
+++ b/spec/models/newsletter_spec.rb
@@ -1,348 +1,357 @@
require 'spec_helper'
describe Newsletter do
fixtures :all
let(:newsletter) { newsletters(:biff_newsletter) }
let(:account) { newsletter.account }
describe "#with_account" do
it "should find right newsletter" do
Newsletter.with_account(account).first.should == newsletter
end
end
describe "#new" do
context "created from draft" do
subject { account.newsletters.create(:draft => newsletter) }
%w(subject content).each do |method|
it "copies #{method}" do
subject.send(method).should == newsletter.send(method)
end
end
end
end
describe "#draft" do
let(:new_newsletter) { Newsletter.new(:draft => newsletter) }
it "copies subject" do
new_newsletter.subject.should == newsletter.subject
end
it "copies content" do
new_newsletter.content.should == newsletter.content
end
end
describe "#recipients_count" do
let(:new_newsletter) { account.newsletters.create!(:subject => "Test") }
it "should be set on create" do
new_newsletter.recipients_count.should == new_newsletter.recipients.count
end
end
context "without StateMachine" do
describe "#_send_test!" do
before do
newsletter.update_attribute("state", "pre_testing")
end
it "creates TestSendOuts" do
expect do
newsletter.send("_send_test!")
end.to change(TestSendOut, :count).by(2)
end
it "uniq test" do
expect do
newsletter.send("_send_test!", newsletter.account.test_recipient_emails_array.first)
end.to change(TestSendOut, :count).by(2)
end
it "calls process!" do
newsletter.should_receive(:process!)
newsletter.send("_send_test!")
end
it "calls process!" do
expect do
newsletter.send("_send_test!")
end.to change { newsletter.state }.from("pre_testing").to("testing")
end
it "creates TestSendOuts for extra email" do
newsletter.send("_send_test!", "[email protected]")
newsletter.test_send_outs.map(&:email).should include("[email protected]")
end
end
describe "#_send_live!" do
before do
newsletter.update_attribute("state", "pre_sending")
end
it "creates LiveSendOuts" do
expect do
newsletter.send("_send_live!")
end.to change(LiveSendOut, :count).by(2)
end
it "updates recipient count" do
expect do
newsletter.send("_send_live!")
end.to change { newsletter.recipients_count }.from(0).to(2)
end
it "calls process!" do
newsletter.should_receive(:process!)
newsletter.send("_send_live!")
end
it "calls process!" do
expect do
newsletter.send("_send_live!")
end.to change { newsletter.state }.from("pre_sending").to("sending")
end
end
describe "#_stop!" do
before do
newsletter.update_attribute("state", "pre_sending")
newsletter.send("_send_live!")
end
it "stopps" do
expect do
expect do
newsletter.send("_stop!")
end.to change(LiveSendOut.with_state(:sheduled), :count).by(-2)
end.to change(LiveSendOut.with_state(:stopped), :count).by(2)
end
it "resumes" do
newsletter.update_attribute("state", "stopping")
newsletter.send("_stop!")
newsletter.update_attribute("state", "pre_sending")
expect do
expect do
newsletter.send("_resume_live!")
end.to change(LiveSendOut.with_state(:sheduled), :count).by(2)
end.to change(LiveSendOut.with_state(:stopped), :count).by(-2)
end
end
end
describe "#send" do
shared_examples_for "sending to recipients" do
let(:klass){ TestSendOut }
let(:method){ :send_test }
it "sends mail" do
expect do
with_resque do
newsletter.fire_state_event(method)
end
end.to change(ActionMailer::Base.deliveries, :size).by(2)
end
it "creates sendouts" do
expect do
with_resque do
newsletter.fire_state_event(method)
end
end.to change(klass.with_state(:finished), :count).by(2)
end
end
context "test" do
it "should have users" do
newsletter.account.test_recipient_emails_array.count.should == 2
end
it_should_behave_like "sending to recipients"
it "sends mail to custom email" do
expect do
with_resque do
newsletter.send_test!("[email protected]")
end
end.to change(ActionMailer::Base.deliveries, :size).by(3)
end
end
context "live" do
it "should have users" do
newsletter.recipients.count.should == 2
end
it_should_behave_like "sending to recipients" do
let(:klass){ LiveSendOut }
let(:method){ :send_live }
end
end
context "state machine" do
it "should not scheduled twice" do
newsletter.send_live!
expect do
newsletter.send_live!
end.to raise_error
end
end
end
describe "#attachments" do
let(:newsletter) { newsletters(:biff_newsletter) }
before do
newsletter.attachment_ids = [assets(:two), assets(:three)].map(&:id)
newsletter.save!
#@newsletter.reload
end
it "updates attachments :one" do
assets(:one).reload.newsletter_id.should be_nil
end
it "updates attachments :two" do
assets(:two).reload.newsletter_id.should == newsletter.id
end
it "updates attachments :two" do
assets(:three).reload.newsletter_id.should == newsletter.id
end
it "updates attachments" do
newsletter.attachments.size.should == 2
end
it "doesn't assign empty blank ids" do
account.should_not_receive(:assets)
newsletter.update_attributes(:attachment_ids => [""])
end
end
describe "#done?" do
it "" do
#sending", one schedule, one done -> not done
#sending", no scheduled, two done -> done
#newsletter.
#newsletter.should be_done
end
end
describe "#update_stats!" do
context "test newsletter" do
before do
newsletter.update_attribute('state', 'testing')
end
it "calls finish" do
expect do
newsletter.update_stats!
end.to change { newsletter.reload.state }.from('testing').to('tested')
end
end
context "live newsletter" do
before do
newsletter.update_attributes(:state => 'sending')
@send_out_first = newsletter.live_send_outs.create!(:recipient => newsletter.recipients.first)
@send_out_last = newsletter.live_send_outs.create!(:recipient => newsletter.recipients.last)
end
context "sending" do
let(:created_at) { 5.days.ago }
it "updates delivery_started_at" do
@send_out_first.update_attributes(:created_at => created_at)
expect do
newsletter.update_stats!
end.to change { newsletter.delivery_started_at.to_i }.to(created_at.to_i)
end
it "doesn't change state" do
expect do
newsletter.update_stats!
end.to_not change { newsletter.reload.state }.from('sending')
end
end
context "finished" do
let(:finished_at) { 2.days.ago }
before do
newsletter.update_attributes(:state => 'sending')
@send_out_first.update_attributes(:state => 'finished', :finished_at => 3.days.ago)
@send_out_last.update_attributes(:state => 'read', :finished_at => finished_at)
end
it "does not update delivery_started_at" do
newsletter.update_attributes(:delivery_started_at => Time.now)
expect do
newsletter.update_stats!
end.to_not change { newsletter.delivery_started_at }
end
it "finishes newsletter" do
expect do
newsletter.update_stats!
end.to change { newsletter.reload.state }.from('sending').to('finished')
end
it "updates delivery_ended_at" do
expect do
newsletter.update_stats!
end.to change { newsletter.reload.delivery_ended_at.to_i }.to(finished_at.to_i)
end
it "updates errors_count" do
@send_out_last.update_attributes(:state => 'failed', :updated_at => finished_at)
expect do
newsletter.update_stats!
end.to change { newsletter.fails_count }.by(1)
end
it "updates reads_count" do
expect do
newsletter.update_stats!
end.to change { newsletter.reads_count }.by(1)
end
it "updates deliveries_count" do
expect do
newsletter.update_stats!
end.to change { newsletter.deliveries_count }.by(2)
end
end
end
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: newsletters
#
# id :integer(4) not null, primary key
-# account_id :integer(4)
-# last_sent_id :integer(4)
-# content :text
-# deliveries_count :integer(4) not null, default(0)
-# errors_count :integer(4) not null, default(0)
-# mode :integer(4) not null, default(0)
-# recipients_count :integer(4) not null, default(0)
-# state :string(255) default("finished")
-# status :integer(4) not null, default(0)
# subject :string(255)
-# created_at :datetime
+# content :text
+# mode :integer(4) default(0), not null
+# status :integer(4) default(0), not null
+# last_sent_id :integer(4)
+# recipients_count :integer(4) default(0), not null
+# deliveries_count :integer(4) default(0), not null
+# fails_count :integer(4) default(0), not null
# deliver_at :datetime
-# delivery_ended_at :datetime
# delivery_started_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# delivery_ended_at :datetime
+# account_id :integer(4)
+# created_at :datetime
+# updated_at :datetime
+# state :string(255) default("finished")
+# bounces_count :integer(4) default(0), not null
+# reads_count :integer(4) default(0), not null
+#
+# Indexes
+#
+# index_newsletters_on_account_id (account_id)
+#
+
+# updated_at :datetime
diff --git a/spec/models/recipient_spec.rb b/spec/models/recipient_spec.rb
index 85cb247..9191332 100644
--- a/spec/models/recipient_spec.rb
+++ b/spec/models/recipient_spec.rb
@@ -1,127 +1,135 @@
require 'spec_helper'
describe Recipient do
fixtures :all
let(:recipient) { recipients(:josh) }
context "#create" do
context "state" do
it "inits state with pending" do
Recipient.create.state.should == 'pending'
end
end
context "confirm code" do
it "generates random string for code" do
Recipient.create.confirm_code.should_not nil
end
it "does not mass assign code" do
expect do
Recipient.create(:confirm_code => 'custom')
end.to raise_error
end
it "does not overwirte manual set confirm_code" do
Recipient.new({:account => Account.first, :email => "[email protected]"}, :as => :test).tap do |recipient|
recipient.confirm_code = 'custom'
recipient.save!
recipient.confirm_code.should == 'custom'
end
end
it "generates uniqe one" do
Recipient.new({:account => Account.first, :email => "[email protected]"}, :as => :test).tap do |recipient|
recipient.confirm_code = Recipient.last.confirm_code
recipient.save!
end
end
end
it "inital state is pending" do
Recipient.create.state.should == 'pending'
end
it "inital state is pending" do
expect do
recipient.update_attributes( :first_name => 'wonne')
end.to_not change { recipient.reload.confirm_code }.from(recipient.confirm_code)
end
end
context "#uniq" do
it "has unique email per account" do
recipient.account.recipients.new(:email => "[email protected]").should be_valid
end
it "has unique email per account" do
recipient.account.recipients.new(:email => recipient.email).should_not be_valid
end
it "has unique email per account" do
accounts(:admin_account).recipients.new(:email => recipient.email).should be_valid
end
end
context "#search" do
let(:account) { accounts(:biff_account) }
let(:recipient) { account.recipients.first }
it "finds exactly one" do
account.recipients.size.should > 1 #make sure we have more than one, otherwise rest of test is senseless ;-)
Recipient::SEARCH_COLUMNS.each do |column|
search_token = recipient.send(column)
account.recipients.search(search_token).size.should == 1
account.recipients.search(search_token[0..-2]).size.should == 1 #remove last char
account.recipients.search(search_token[1..-1]).size.should == 1 #remove first char
end
end
end
context "#delete" do
%w(delete destroy delete!).each do |method|
it "#{method} doesn't remove entry from DB" do
expect do
recipient.send(method)
end.to_not change { Recipient.count }
end
end
end
describe "force_remove" do
it "does remove entry from DB" do
expect do
recipient.force_destroy
end.to change { Recipient.count }
end
it "does not remoce any send_outs" do
recipient.live_send_outs.create(:newsletter => Newsletter.last)
expect do
recipient.force_destroy
end.to_not change { SendOut.count }.from(1)
end
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: recipients
#
# id :integer(4) not null, primary key
-# account_id :integer(4)
-# bounces :text
-# bounces_count :integer(4) not null, default(0)
-# confirm_code :string(255)
-# deliveries_count :integer(4) not null, default(0)
-# email :string(255)
-# failed_count :integer(4) not null, default(0)
-# first_name :string(255)
# gender :string(255)
+# first_name :string(255)
# last_name :string(255)
-# reads_count :integer(4) not null, default(0)
-# state :string(255) default("pending")
+# email :string(255)
+# deliveries_count :integer(4) default(0), not null
+# bounces_count :integer(4) default(0), not null
+# account_id :integer(4)
# created_at :datetime
-# updated_at :datetime
\ No newline at end of file
+# updated_at :datetime
+# fails_count :integer(4) default(0), not null
+# confirm_code :string(255)
+# state :string(255) default("pending")
+# reads_count :integer(4) default(0), not null
+#
+# Indexes
+#
+# index_recipients_on_id_and_account_id (id,account_id) UNIQUE
+# index_recipients_on_email (email)
+# index_recipients_on_account_id (account_id)
+#
+
+# updated_at :datetime
diff --git a/spec/models/send_out_spec.rb b/spec/models/send_out_spec.rb
index e00eda0..da4cda3 100644
--- a/spec/models/send_out_spec.rb
+++ b/spec/models/send_out_spec.rb
@@ -1,175 +1,183 @@
require 'spec_helper'
describe SendOut do
fixtures :all
let(:recipient) { newsletter.recipients.first }
let(:newsletter) { newsletters(:biff_newsletter) }
let(:live_send_out) { LiveSendOut.create!(:newsletter => newsletter, :recipient => recipient) }
let(:test_send_out) { TestSendOut.create!(:newsletter => newsletter, :email => "[email protected]") }
context "#create" do
describe LiveSendOut do
it "should set email" do
live_send_out.email.should == recipient.email
end
it "should not allow multiple instances" do
live_send_out
expect do
LiveSendOut.create!(:newsletter => newsletter, :recipient => recipient)
end.to raise_error
end
end
it "should allow multiple instances of TestSendOut" do
live_send_out
expect do
TestSendOut.create!(:newsletter => newsletter, :email => "[email protected]")
end.to_not raise_error
end
end
context "#async_deliver!" do
before do
ResqueSpec.reset!
end
it "live should be scheduled after create" do
LiveSendOut.should have_queued(live_send_out.id)
TestSendOut.should_not have_queued(live_send_out.id)
end
it "test should be scheduled after create" do
TestSendOut.should have_queued(test_send_out.id)
LiveSendOut.should_not have_queued(test_send_out.id)
end
end
describe "#deliver!" do
before do
ActionMailer::Base.deliveries.clear
end
context "TestSendOut" do
it "should send out test sending" do
expect do
test_send_out.deliver!
end.to change(ActionMailer::Base.deliveries, :size).by(1)
end
it "changes state to finished on success" do
expect do
test_send_out.deliver!
end.not_to change { Recipient.count }
end
end
context "LiveSendOut" do
it "should send out live sending" do
expect do
live_send_out.deliver!
end.to change(ActionMailer::Base.deliveries, :size).by(1)
end
it "changes state to finished on success" do
expect do
live_send_out.deliver!
end.to change { live_send_out.reload.state }.from('sheduled').to('finished')
end
it "set finished_at" do
expect do
live_send_out.deliver!
end.to change { live_send_out.reload.finished_at }.from(nil)
end
it "increases recipients deliveries_count" do
expect do
live_send_out.deliver!
end.to change { recipient.reload.deliveries_count }.by(1)
end
it "should change state to failed on failure" do
live_send_out.issue.should_receive(:deliver).and_raise
expect do
expect do
live_send_out.deliver!
end.to raise_error
end.to change { live_send_out.reload.state }.from('sheduled').to('failed')
end
it "increases recipients fails_count" do
live_send_out.issue.should_receive(:deliver).and_raise
expect do
expect do
live_send_out.deliver!
end.to raise_error
end.to change { recipient.reload.fails_count }.by(1)
end
end
end
describe "#read!" do
it "changes from finished to read" do
live_send_out.update_attributes(:state => 'finished')
expect do
live_send_out.read!
end.to change { live_send_out.reload.state }.from('finished').to('read')
end
it "does not change from read to read" do
live_send_out.update_attributes(:state => 'read')
expect do
live_send_out.read!
end.to_not change { live_send_out.reload.state }.from('read')
end
it "increases recipients reads_count" do
live_send_out.update_attributes(:state => 'finished')
expect do
live_send_out.read!
end.to change { recipient.reload.reads_count }.by(1)
end
end
describe "#bounce!" do
it "changes from finished to read" do
live_send_out.update_attributes(:state => 'finished')
expect do
live_send_out.bounce!
end.to change { live_send_out.reload.state }.from('finished').to('bounced')
end
it "does not change from read to read" do
live_send_out.update_attributes(:state => 'bounced')
expect do
live_send_out.bounce!
end.to_not change { live_send_out.reload.state }.from('bounced')
end
it "increases recipients bounces_count" do
live_send_out.update_attributes(:state => 'finished')
expect do
live_send_out.bounce!
end.to change { recipient.reload.bounces_count }.by(1)
end
end
end
-# == Schema Info
+# == Schema Information
#
# Table name: send_outs
#
# id :integer(4) not null, primary key
-# newsletter_id :integer(4)
# recipient_id :integer(4)
+# newsletter_id :integer(4)
+# type :string(255)
+# state :string(255)
# email :string(255)
# error_message :text
-# state :string(255)
-# type :string(255)
# created_at :datetime
+# updated_at :datetime
# finished_at :datetime
-# updated_at :datetime
\ No newline at end of file
+#
+# Indexes
+#
+# index_send_outs_on_newsletter_id_and_type (newsletter_id,type)
+# index_send_outs_on_newsletter_id_and_type_and_recipient_id (newsletter_id,type,recipient_id)
+#
+
+# updated_at :datetime
diff --git a/vendor/plugins/.gitkeep b/vendor/plugins/.gitkeep
deleted file mode 100644
index e69de29..0000000
diff --git a/vendor/plugins/annotate_models/ChangeLog b/vendor/plugins/annotate_models/ChangeLog
deleted file mode 100644
index 884fe90..0000000
--- a/vendor/plugins/annotate_models/ChangeLog
+++ /dev/null
@@ -1,49 +0,0 @@
-2008-10-02 Marcos Piccinini <[email protected]>
- * annotates object daddy exemplar files.
-
-2008-10-01 Marcos Piccinini <[email protected]>
- * annotates factory file.
-
-2007-03-05 Dave Thomas <[email protected]>
- * Forgot to call the quote method
-
-2007-03-02 Dave Thomas <[email protected]>
- * Allow non-printing characters in column defaults (suggested by Ben Booth)
-
-2007-02-28 Dave Thomas <[email protected]>
- * Report errors loading model classes better. Change suggested by Niels Knacke
-
-2007-02-22 Dave Thomas <[email protected]>
- * Ignore models with no underlying database table (based on patch from Jamie van Dyke)
- * Handle case where database has no session_info table (patch by David Vrensk)
-
-2006-07-13 Dave Thomas <[email protected]>
- * Support :scale for decimal columns
-
-2006-07-10 Wes Gamble <no@mail>
- * Don't annotate abstract models
-
-2006-06-13 Dave Thomas <[email protected]>
- * Fix bug where we corrupted the PREFIX string and therefore duplicated
- the header
- * No longer include the datetime, so we don't trigger a commit
- back into repos
-
- -- NOTE -- just this once, you'll get a duplicate header after you run
- a_m on an already-annotated model. Sorry.... Dave
-
-2006-06-11 Dave Thomas <[email protected]>
- * lib/annotate_models.rb: At Kian Wright's suggestion, document the table
- name and primary key. Also make the timestamp prettier
-
-2006-04-17 Dave Thomas <[email protected]>
-
- * lib/annnotate_models.rb: Include Bruce William's patch to allow
- models in subdirectories
-
-2006-03-11 Dave Thomas <[email protected]>
-
- * lib/annotate_models.rb: Use camelize, not classify, to construct
- class names (Grant Hollingworth)
-
-3/3/06 Now annotates fixture files too (thanks to Josha Susser)
diff --git a/vendor/plugins/annotate_models/LICENSE.txt b/vendor/plugins/annotate_models/LICENSE.txt
deleted file mode 100644
index 37e5ae0..0000000
--- a/vendor/plugins/annotate_models/LICENSE.txt
+++ /dev/null
@@ -1,60 +0,0 @@
-Ruby License
-http://www.ruby-lang.org/en/LICENSE.txt
-
-Ruby is copyrighted free software by Yukihiro Matsumoto <[email protected]>.
-You can redistribute it and/or modify it under either the terms of the GPL
-(see COPYING.txt file), or the conditions below:
-
- 1. You may make and give away verbatim copies of the source form of the
- software without restriction, provided that you duplicate all of the
- original copyright notices and associated disclaimers.
-
- 2. You may modify your copy of the software in any way, provided that
- you do at least ONE of the following:
-
- a) place your modifications in the Public Domain or otherwise
- make them Freely Available, such as by posting said
- modifications to Usenet or an equivalent medium, or by allowing
- the author to include your modifications in the software.
-
- b) use the modified software only within your corporation or
- organization.
-
- c) rename any non-standard executables so the names do not conflict
- with standard executables, which must also be provided.
-
- d) make other distribution arrangements with the author.
-
- 3. You may distribute the software in object code or executable
- form, provided that you do at least ONE of the following:
-
- a) distribute the executables and library files of the software,
- together with instructions (in the manual page or equivalent)
- on where to get the original distribution.
-
- b) accompany the distribution with the machine-readable source of
- the software.
-
- c) give non-standard executables non-standard names, with
- instructions on where to get the original software distribution.
-
- d) make other distribution arrangements with the author.
-
- 4. You may modify and include the part of the software into any other
- software (possibly commercial). But some files in the distribution
- are not written by the author, so that they are not under this terms.
-
- They are gc.c(partly), utils.c(partly), regex.[ch], st.[ch] and some
- files under the ./missing directory. See each file for the copying
- condition.
-
- 5. The scripts and library files supplied as input to or produced as
- output from the software do not automatically fall under the
- copyright of the software, but belong to whomever generated them,
- and may be sold commercially, and may be aggregated with this
- software.
-
- 6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
- IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- PURPOSE.
diff --git a/vendor/plugins/annotate_models/README.txt b/vendor/plugins/annotate_models/README.txt
deleted file mode 100644
index 714ba4a..0000000
--- a/vendor/plugins/annotate_models/README.txt
+++ /dev/null
@@ -1,71 +0,0 @@
- _
- /_| _/__/_ /|/| _/_ / _
-( |/)/)()/(//(- / |()(/(-(_)
-________________________________
-
-Add a comment summarizing the current schema to the
-bottom of each ActiveRecord model, Test File,
-Exemplar, Fixture and Factory source file:
-
- # == Schema Info
- # Schema version: 20081001061831
- #
- # Table name: line_item
- #
- # id :integer(11) not null, primary key
- # order_id :integer(11)
- # product_id :integer(11) not null
- # quantity :integer(11) not null
- # unit_price :float
-
- class LineItem < ActiveRecord::Base
- belongs_to :product
- . . .
-
-Note that this code will blow away the initial/final comment
-block in your models if it looks like it was previously added
-by annotate models, so you don't want to add additional text
-to an automatically created comment block.
-
- * * Back up your model files before using... * *
-
-== HOW TO USE:
-
-To annotate all your models:
-
- rake db:annotate
-
-To migrate & annotate:
-
- rake db:update
-
-
-Options:
-
-Annotate on the head of the file:
-
- rake db:annotate POSITION='top'
-
-Include schema version:
- rake db:annotate SHOW_SCHEMA_VERSION='true'
-
-
-Set Options Permanently:
-
-If using bash, you can put these lines in your .bashrc file to set more permanently:
- export POSITION='top'
- export SHOW_SCHEMA_VERSION='true'
-
-
-== LICENSE:
-
-Original code by:
- Dave Thomas
- Pragmatic Programmers, LLC
-
-Refactored, improved by
- Alexander Semyonov (http://github.com/rotuka/annotate_models)
- Marcos Piccinini (http://github.com/nofxx/annotate_models)
- Stephen Anderson (http://github.com/bendycode/annotate_models)
-
-Released under the same license as Ruby. No Support. No Warranty.
diff --git a/vendor/plugins/annotate_models/lib/annotate_models.rb b/vendor/plugins/annotate_models/lib/annotate_models.rb
deleted file mode 100755
index 9e3a7db..0000000
--- a/vendor/plugins/annotate_models/lib/annotate_models.rb
+++ /dev/null
@@ -1,158 +0,0 @@
-require Rails.root.join("config","environment")
-
-MODEL_DIR = (Rails.root + "app/models").to_s
-UNIT_TEST_DIR = (Rails.root + "test/unit").to_s
-SPEC_MODEL_DIR = (Rails.root + "spec/models").to_s
-FIXTURES_DIR = (Rails.root + "test/fixtures").to_s
-SPEC_FIXTURES_DIR = (Rails.root + "spec/fixtures").to_s
-SORT_COLUMNS = ENV['SORT'] != 'no'
-
-module AnnotateModels
-
- PREFIX = "== Schema Info"
- SEP_LINES = "\n\n"
-
- # Simple quoting for the default column value
- def self.quote(value)
- case value
- when NilClass then "NULL"
- when TrueClass then "TRUE"
- when FalseClass then "FALSE"
- when Float, Fixnum, Bignum then value.to_s
- # BigDecimals need to be output in a non-normalized form and quoted.
- when BigDecimal then value.to_s('F')
- else
- value.inspect
- end
- end
-
- # Use the column information in an ActiveRecord class
- # to create a comment block containing a line for
- # each column. The line contains the column name,
- # the type (and length), and any optional attributes
- def self.get_schema_info(klass, header)
- table_info = "# Table name: #{klass.table_name}\n#\n"
- max_size = klass.column_names.collect{|name| name.size}.max + 1
-
- cols = if SORT_COLUMNS
- pk = klass.columns.find_all { |col| col.name == klass.primary_key }.flatten
- assoc = klass.columns.find_all { |col| col.name.match(/_id$/) }.sort_by(&:name)
- dates = klass.columns.find_all { |col| col.name.match(/_on$/) }.sort_by(&:name)
- times = klass.columns.find_all { |col| col.name.match(/_at$/) }.sort_by(&:name)
-
- pk + assoc + (klass.columns - pk - assoc - times - dates).compact.sort_by(&:name) + dates + times
- else
- klass.columns
- end
-
- cols_text = cols.map{|col| annotate_column(col, klass, max_size)}.join("\n")
-
- "# #{header}\n#\n" + table_info + cols_text
- end
-
- def self.annotate_column(col, klass, max_size)
- attrs = []
- attrs << "not null" unless col.null
- attrs << "default(#{quote(col.default)})" if col.default
- attrs << "primary key" if col.name == klass.primary_key
-
- col_type = col.type.to_s
- if col_type == "decimal"
- col_type << "(#{col.precision}, #{col.scale})"
- else
- col_type << "(#{col.limit})" if col.limit
- end
- sprintf("# %-#{max_size}.#{max_size}s:%-15.15s %s", col.name, col_type, attrs.join(", ")).rstrip
- end
-
- # Add a schema block to a file. If the file already contains
- # a schema info block (a comment starting
- # with "Schema as of ..."), remove it first.
- # Mod to write to the end of the file
-
- def self.annotate_one_file(file_name, info_block)
- if File.exist?(file_name)
- content = File.read(file_name)
-
- # Remove old schema info
- content.sub!(/(\n)*^# #{PREFIX}.*?\n(#.*\n)*#.*(\n)*/, '')
-
- # Write it back
- File.open(file_name, "w") do |f|
- if ENV['POSITION'] == 'top'
- f.print info_block + SEP_LINES + content
- else
- f.print content + SEP_LINES + info_block
- end
- end
- end
- end
-
- # Given the name of an ActiveRecord class, create a schema
- # info block (basically a comment containing information
- # on the columns and their types) and put it at the front
- # of the model and fixture source files.
-
- def self.annotate(klass, header)
- info = get_schema_info(klass, header)
- model_name = klass.name.underscore
- fixtures_name = "#{klass.table_name}.yml"
-
- [
- File.join(MODEL_DIR, "#{model_name}.rb"), # model
- File.join(UNIT_TEST_DIR, "#{model_name}_test.rb"), # test
- File.join(FIXTURES_DIR, fixtures_name), # fixture
- File.join(SPEC_MODEL_DIR, "#{model_name}_spec.rb"), # spec
- File.join(SPEC_FIXTURES_DIR, fixtures_name), # spec fixture
- File.join(Rails.root.to_s, 'test', 'factories.rb'), # factories file
- File.join(Rails.root.to_s, 'spec', 'factories.rb'), # factories file
- ].each { |file| annotate_one_file(file, info) }
- end
-
- # Return a list of the model files to annotate. If we have
- # command line arguments, they're assumed to be either
- # the underscore or CamelCase versions of model names.
- # Otherwise we take all the model files in the
- # app/models directory.
- def self.get_model_names
- models = ENV['MODELS'] ? ENV['MODELS'].split(',') : []
-
- if models.empty?
- Dir.chdir(MODEL_DIR) do
- models = Dir["**/*.rb"]
- end
- end
- models
- end
-
- # We're passed a name of things that might be
- # ActiveRecord models. If we can find the class, and
- # if its a subclass of ActiveRecord::Base,
- # then pas it to the associated block
- def self.do_annotations
- header = PREFIX.dup
-
- # Don't show the schema version every time by default
- header << get_schema_version if ENV['SHOW_SCHEMA_VERSION'] == 'true'
-
- annotated = self.get_model_names.inject([]) do |list, m|
- class_name = m.sub(/\.rb$/, '').camelize
- begin
- klass = class_name.split('::').inject(Object){ |klass,part| klass.const_get(part) }
- if klass < ActiveRecord::Base && !klass.abstract_class?
- list << class_name
- self.annotate(klass, header)
- end
- rescue Exception => e
- puts "Unable to annotate #{class_name}: #{e.message}"
- end
- list
- end
- puts "Annotated #{annotated.join(', ')}"
- end
-
- def self.get_schema_version
- version = ActiveRecord::Migrator.current_version rescue 0
- version > 0 ? "\n# Schema version: #{version}" : ''
- end
-end
diff --git a/vendor/plugins/annotate_models/lib/tasks/annotate_models_tasks.rake b/vendor/plugins/annotate_models/lib/tasks/annotate_models_tasks.rake
deleted file mode 100755
index 0bc33f9..0000000
--- a/vendor/plugins/annotate_models/lib/tasks/annotate_models_tasks.rake
+++ /dev/null
@@ -1,30 +0,0 @@
-# old task :annotate_models removed
-
-namespace :db do
- desc "Add schema information (as comments) to model files"
- task :annotate do
- require File.join(File.dirname(__FILE__), "../annotate_models.rb")
- AnnotateModels.do_annotations
- end
-
- desc "Updates database (migrate and annotate models)"
- task :update do
- Rake::Task['db:migrate'].invoke
- Rake::Task['db:annotate'].invoke
- Rake::Task['db:test:prepare'].invoke
- end
- # namespace :migrate do
- # task :down do
- # Rake::Task['db:annotate'].invoke
- # Rake::Task['db:test:prepare'].invoke
- # end
- # task :up do
- # Rake::Task['db:annotate'].invoke
- # Rake::Task['db:test:prepare'].invoke
- # end
- # task :rollback do
- # Rake::Task['db:annotate'].invoke
- # Rake::Task['db:test:prepare'].invoke
- # end
- # end
-end
|
rngtng/nups
|
daed26c1e69c9af750344790b9a1f10ba4bb3253
|
fixed JS date bug, added send grid todo
|
diff --git a/README.md b/README.md
index b446998..aaae714 100644
--- a/README.md
+++ b/README.md
@@ -1,90 +1,92 @@
# Welcome to NUPS
## resources
* Overview of best plugins: http://ruby-toolbox.com/
* [Devise](http://github.com/plataformatec/devise) -> `rails generate devise_install`
* Test SMTP lockally: http://mocksmtpapp.com/
* Spinners:
http://www.andrewdavidson.com/articles/spinning-wait-icons/
http://mentalized.net/activity-indicators/
## TODO
+ * try send grids:
+ http://stackoverflow.com/questions/4798141/sendgrid-vs-postmark-vs-amazon-ses-and-other-email-smtp-api-providers
* check: stop while in pre_sending??
* check: error when creating send_outs
* chart when people read
* remove mode/status/last_send_id from newsletter
* order DESC
* heighlight reciever with bounce count, set option to disable
* translation (gender)
* add better migration
* test coffeescript
* animate sendout & test gif icons
* check: http://isnotspam.com
* test premailer
* add index to recipients
* bounce only when 5.X code
* bounce cleanup
* mv send_out textfield into string? (speed up)
## DONE
* check what happens if a single sendout fails within a batch
* add better fixtures: factory_girl
* newsletter stats: total/percent send/fail/bounces/read count
-> * add infos to newsletter to see total read/bounces
* history stats
recipient growth
newsletter read/bounce growth
sending time/speed
* remove error_message recipeint -> move to send_out
* change update_newsletter to json
* reactivate deleted users
* send test email to current_user.email
* newsletter unsubscribe by email
* autodetect URLS
* unsubscribe ->
header: http://www.list-unsubscribe.com/
* recipients: overflow for user name + email
* remove error_code from send_out
* errors_count + errors message
* hidden image to register if nl was read *test*
* read NL on website *test*
* read count to recipient *update when read* *test*
* update bounce counters:
-> only counter bounces younger than last update time -> bounces_count_updated_at
-> resque task?
-> on bounce create? if user available?
* update deliver counters:
-> after send?
* fix receiver edit
* recipients overlay with list of sendouts (details -> when which newsletter was send)
* hide deleted receiver
* sort receiver column, indicate sorting *test*
* receiver paginate ajax
* pretty time span
* add user total count on top
* update deliverd_startet_at_ from youngest sendout
* scheduling
* recipients import/export
* Newsletter delete ajax
* search pagination, show total amount
* attachment upload
* new newsletter scroll
* reload after recp import
* open new newsletter in window
* recipients
* in place editing (improvement see rails cast)
* fix travis setup: http://about.travis-ci.org/docs/user/build-configuration/
* progress bar update time
* resque status: http://github.com/quirkey/resque-status
## Resque Startup:
* rake resque:workers:start
## Mail
http://www.techsoup.org/learningcenter/internet/page5052.cfm
http://www.sitepoint.com/forums/showthread.php?571536-Building-a-newsletter-not-getting-listed-as-spam
http://gettingattention.org/articles/160/email-enewsletters/nonprofit-email-newsletter-success.html
## Builder
[](http://travis-ci.org/rngtng/nups)
diff --git a/app/assets/javascripts/application.js b/app/assets/javascripts/application.js
index eb165e3..22bca2d 100644
--- a/app/assets/javascripts/application.js
+++ b/app/assets/javascripts/application.js
@@ -1,51 +1,51 @@
// This is a manifest file that'll be compiled into including all the files listed below.
// Add new JavaScript/Coffee code in separate files in this directory and they'll automatically
// be included in the compiled file accessible from http://example.com/assets/application.js
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//= require jquery
//= require jquery_ujs
//= require jquery.tools.min
//= require jquery.progress
//= require plupload/jquery.plupload.queue.min
//= require plupload/plupload.full.min
//= require cleditor/jquery.cleditor
//= require cleditor
//= require highcharts
//= require newsletters
//= require recipients
//= require send_outs
//= require tools
window.distance_of_time = function(from_time, to_time, include_seconds){
var out = '',
s = {},
- diff = Math.abs(new Date(to_time) - new Date(from_time)) / 1000;
+ diff = Math.abs(new Date(to_time || $.now()) - new Date(from_time)) / 1000;
var day_diff = diff % (7 * 24 * 60 * 60);
s.weeks = (diff - day_diff) / (7 * 24 * 60 * 60);
var hour_diff = day_diff % (24 * 60 * 60);
s.days = (day_diff - hour_diff) / (24 * 60 * 60);
var minute_diff = hour_diff % (60 * 60);
s.hours = (hour_diff - minute_diff) / (60 * 60);
var second_diff = minute_diff % 60;
s.minutes = (minute_diff - second_diff) / 60;
var fractions = second_diff % 1;
s.seconds = second_diff - fractions;
if (s.weeks > 0) {
out += s.weeks + 'w';
}
if (s.days > 0) {
out += ' ' + s.days + 'd';
}
if (s.hours > 0) {
out += ' ' + s.hours + 'h';
}
if (!include_seconds || s.minutes > 0) {
out += ' ' + s.minutes + 'm';
}
if (include_seconds) {
out += ' ' + s.seconds + 's';
}
return out;
}
|
rngtng/nups
|
4a83dbbfcf7545e075f1b0ba1ec863e1196ba774
|
added chart to analyze read behavior
|
diff --git a/app/assets/stylesheets/frame.css.scss b/app/assets/stylesheets/frame.css.scss
index c9f3340..9059451 100644
--- a/app/assets/stylesheets/frame.css.scss
+++ b/app/assets/stylesheets/frame.css.scss
@@ -1,88 +1,92 @@
//
// This is a manifest file that'll automatically include all the stylesheets available in this directory
// and any sub-directories. You're free to add application-wide styles to this file and they'll appear at
// the top of the compiled file, but it's generally better to create a new file per style scope.
//= require_self
html, body, table, iframe {
margin: 0;
padding: 0;
border: 0;
height: 100%;
width: 100%;
overflow: auto;
font-family: Helvetica;
font-size: 13px;
font-weight: normal; }
* html table#frame {
height: 100%; }
body {
overflow: hidden;
background-color: #6699CC; }
.hidden {
display: none; }
a {
color: #000;
text-decoration: none;
&:hover {
text-decoration: underline; } }
/* specific rules */
#top {
height: 20px;
#menu {
width: 145px;
padding-left: 5px;
#logo {
margin: 5px 0; }
#admin {
margin-bottom: 10px;
a {
font-weight: bold; } }
.item ul {
list-style-type: none;
padding: 10px 3px 0px 0px;
margin: 0px;
margin-bottom: 15px;
a {
font-weight: bold; }
ul {
list-style-type: disc;
padding: 0px 0px 0px 20px;
a {
font-weight: normal; } } } }
#new-relic, #airbrake {
margin: 3px 4px 0 4px; }
#travis{
margin: 4px 4px 0 4px; }
#resque, #travis, #new-relic, #airbrake {
float: left;
display: none;
.admin & {
display: inline ;}}
#logout {
float: right;
img {
border: 0;
margin: 2px 0px 0; } } }
iframe {
width: 100%;
border-left: 1px solid;
border-top: 1px solid;
padding: 0px;
background-color: #FFF; }
.admin #admin {
display: block; }
+
+.user .charts{
+ display: none; }
+
diff --git a/app/helpers/charts_helper.rb b/app/helpers/charts_helper.rb
index 210e4a1..81b6273 100644
--- a/app/helpers/charts_helper.rb
+++ b/app/helpers/charts_helper.rb
@@ -1,66 +1,113 @@
module ChartsHelper
NL_FIELDS = %w(finishs_count reads_count fails_count bounces_count sendings_per_second)
def newsletters_chart(newsletters)
{}.tap do |data|
NL_FIELDS.each do |method|
data[method] = []
end
newsletters.each do |newsletter|
date = newsletter.delivery_started_at.to_i * 1000
NL_FIELDS.each do |method|
data[method] << [date, newsletter.send(method)]
end
end
end
end
def recipients_chart(account)
{
:pending => get_recipients(account.id, 'pending', 'created_at'),
:confirmed => get_recipients_all(account.id, ['confirmed', 'deleted']),
:deleted => get_recipients(account.id, 'deleted', 'updated_at'),
}
end
#private
def get_recipients(account_id, state, field = 'created_at')
Recipient.connection.execute("Set time_zone = '+0:00'")
Recipient.connection.select_rows <<-SQL
SELECT
UNIX_TIMESTAMP(DATE_FORMAT(#{field}, '%Y-%m-%d')) AS `date`,
COUNT(*) AS cnt
FROM recipients
WHERE state = '#{state}'
GROUP BY `date`
ORDER BY `date` ASC
SQL
end
def get_recipients_all(account_id, states = [])
Recipient.connection.execute("Set time_zone = '+0:00'")
Recipient.connection.select_rows <<-SQL
SELECT
UNIX_TIMESTAMP(`date`) AS `date`,
MAX(IF(cnt > 0,cnt,0)) + Min(IF(cnt < 0,cnt,0)) AS cnt
FROM
(SELECT
DATE_FORMAT(created_at, '%Y-%m-%d') AS `date`,
COUNT(*) AS cnt
FROM recipients
WHERE account_id = #{account_id} AND state IN('#{states.join("','")}')
GROUP BY `date`
UNION
SELECT
DATE_FORMAT(updated_at, '%Y-%m-%d') AS `date`,
-1 * COUNT(*) AS cnt
FROM recipients
WHERE account_id = #{account_id} AND state = '#{states.last}'
GROUP BY `date`) AS u
GROUP BY `date`
ORDER BY `date`
SQL
end
+
+ def send_outs_chart(account)
+ opts = {
+ 15.minutes => "< 15min",
+ 1.hour => "15min - 1h",
+ 3.hours => "1h - 3h",
+ 12.hours => "3h - 12h",
+ 1.day => "12h - 24h",
+ 2.day => "24h - 48h",
+ 100.days => "> 48h"
+ }
+ newsletter_ids = account.newsletters.map(&:id)
+ {
+ :read_diff => {
+ :opts => opts,
+ :data => get_read_diff(newsletter_ids, opts),
+ },
+ :read_span => get_read_span(newsletter_ids),
+ }
+ end
+
+ def get_read_diff(newsletter_ids, opts)
+ return [] unless newsletter_ids.any?
+ min = opts.keys.min
+ Recipient.connection.select_rows <<-SQL
+ SELECT TIME_TO_SEC(TIMEDIFF(updated_at, IFNULL(finished_at, created_at))) DIV #{min} * #{min} AS `date`,
+ COUNT(*)
+ FROM send_outs
+ WHERE state = 'read'
+ AND newsletter_id IN(#{newsletter_ids.join(',')})
+ GROUP BY `date`
+ SQL
+ end
+
+ def get_read_span(newsletter_ids, span = 10.minutes)
+ return [] unless newsletter_ids.any?
+ Recipient.connection.execute("Set time_zone = '+0:00'")
+ Recipient.connection.select_rows <<-SQL
+ SELECT
+ UNIX_TIMESTAMP(DATE_FORMAT(updated_at, "2011-01-01 %H:%i")) DIV #{span} AS `date`,
+ COUNT(*)
+ FROM send_outs
+ WHERE state = 'read'
+ AND newsletter_id IN(#{newsletter_ids.join(',')})
+ GROUP BY `date`
+ SQL
+ end
end
diff --git a/app/views/charts/_send_outs.html.haml b/app/views/charts/_send_outs.html.haml
new file mode 100644
index 0000000..5ff3c4e
--- /dev/null
+++ b/app/views/charts/_send_outs.html.haml
@@ -0,0 +1,90 @@
+#send-outs
+
+:javascript
+ var data = #{send_outs_chart(@account).to_json},
+ process = function(d) {
+ var out = $.map(d, function(values, index) {
+ return [[(values[0] * 600 + 60 * 60) * 1000, values[1]]];
+ });
+ return out;
+ },
+ processPie = function(d) {
+ var i = 0,
+ out = $.map(d.opts, function(name, index) {
+ var sum = 0;
+ while((a = d.data[i]) && a[0] < index) {
+ sum += a[1];
+ i += 1;
+ }
+ return [{ name: name, y: sum }];
+ });
+ return out;
+ },
+ chart = new Highcharts.Chart({
+ chart: {
+ renderTo: 'send-outs',
+ },
+
+ title: {
+ text: "Lese Verhalten"
+ },
+
+ tooltip: {
+ formatter: function() {
+ if(this.series.index == 0) {
+ var d = new Date(this.x),
+ m = (d.getUTCMinutes() < 1) ? '00' : d.getUTCMinutes(),
+ s = '<b>' + d.getUTCHours() + ':' + m + ' Uhr</b><br/>';
+ s += '<span style="fill:#4572A7">'+ this.series.name +':</span> '+ this.y;
+ return s;
+ } else {
+ var s = '<b>' + this.point.name + '</b><br/>';
+ s += '<span style="fill:#4572A7">'+ this.series.name +':</span> '+ Math.round(this.percentage * 100) / 100 + '%';
+ return s;
+ }
+ },
+ crosshairs: true
+ },
+
+ xAxis: {
+ type: 'datetime',
+ tickWidth: 0,
+ tickLength: 10,
+ gridLineWidth: 1,
+ },
+
+ yAxis: [{
+ title: {
+ text: "Anzahl"
+ }
+ }],
+
+ plotOptions: {
+ series: {
+ connectNulls: true
+ },
+ area: {
+ stacking: 'normal'
+ }
+ },
+
+ series: [{
+ type: 'area',
+ name: 'Lese Zeitpunkt',
+ yAxis: 0,
+ pointWidth: 4,
+ data: process(data.read_span),
+ stack: 0
+ },
+ {
+ type: 'pie',
+ name: 'Read Point',
+ data: processPie(data.read_diff),
+ center: [160, 100],
+ size: 180,
+ showInLegend: false,
+ dataLabels: {
+ enabled: true
+ }
+ }]
+ });
\ No newline at end of file
diff --git a/app/views/charts/index.html.haml b/app/views/charts/index.html.haml
index 9e4f2dc..225d988 100644
--- a/app/views/charts/index.html.haml
+++ b/app/views/charts/index.html.haml
@@ -1,7 +1,11 @@
#charts.index
%h2= t 'charts.title', :account_name => @account.name
= render :partial => 'charts/newsletters'
+ %br
- = render :partial => 'charts/recipients'
+ = render :partial => 'charts/send_outs'
+ %br
+ = render :partial => 'charts/recipients'
+ %br
diff --git a/app/views/layouts/frame.html.haml b/app/views/layouts/frame.html.haml
index e8552fe..3366f9b 100644
--- a/app/views/layouts/frame.html.haml
+++ b/app/views/layouts/frame.html.haml
@@ -1,58 +1,59 @@
!!!
%html
%head
%title= t('application.title')
= stylesheet_link_tag 'frame'
= javascript_include_tag 'frame'
= csrf_meta_tag
%base{:target => "application"}
= render :partial => "layouts/tracking"
:javascript
$(document).ready(function() {
showMenu(#{@user.id});
//console.log('#frame loaded');
});
%body{:class => current_user.admin? ? 'admin' : 'user'}
%table{:cellspacing => "0", :cellpadding => "0"}
%tr#top
%td#menu{:rowspan => 2, :valign => "top"}
= image_tag 'logo.jpg', :id => 'logo'
#admin.hidden
= link_to t('menu.accounts'), admin_accounts_path
•
= link_to t('menu.users'), admin_users_path
- opts = options_from_collection_for_select(@users, :id, :username)
%br
%label= t('menu.user')
= select_tag 'user_menu', opts, :onChange => "showMenu(this.options[this.selectedIndex].value)"
- @users.each do |user|
.item.hidden{:id => "user-menu-#{user.id}"}
- user.domains.each do |domain|
%strong= link_to t('menu.domains'), domain.main_url
%br
%br
-# %strong= link_to t('menu.ftp'), domain.ftp_url
%strong= link_to t('menu.newsletters'), all_newsletters_path(:user_id => user)
%ul
- user.accounts.each do |account|
%li
= link_to account.name, account_newsletters_path(account)
%ul
%li= link_to t('menu.new'), new_account_newsletter_path(account)
%li= link_to t('menu.recipients'), account_recipients_path(account)
+ %li.charts= link_to t('menu.charts'), account_charts_path(account)
%td
= render :partial => "layouts/admin_panel"
= link_to image_tag('buttons/logout.gif'), destroy_user_session_path, :id => 'logout', :target => "_self"
%tr
%td{:bgcolor => "#ddd", :height => "100%"}
= yield
diff --git a/config/locales/de.yml b/config/locales/de.yml
index c3c27d3..6859304 100644
--- a/config/locales/de.yml
+++ b/config/locales/de.yml
@@ -1,102 +1,103 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
de:
application:
title: MultiAdmin - Nups
login:
forgot: "Passwort vergessen?"
signin: "Einloggen"
send_password: "Passwort reset Email senden"
menu:
users: Users
user: User
accounts: Accounts
newsletters: Ãbersicht Newsletter
new: Neuer Newsletter
recipients: Empfänger
+ charts: Statistik
domains: Domain Verwaltung
ftp: FTP
views:
pagination:
previous: "« Zurück"
next: "Vor »"
truncate: "..."
last: "»|"
first: "|«"
ctrl:
back: zurück
cancel: abbrechen
confirm: Sicher?
delete: löschen
edit: ändern
new: neu
preview: vorschau
search: suchen
show: details
save: speichern
newsletters:
title: Newsletter
new: Neuer Newsletter
all: "Ãbersicht"
user: User
users: Users
account: Newsletter
action: Aktion
confirm:
delete: "Newsletter löschen?"
resume: "Versand fortführen?"
send_live: "Versand starten?"
stop: "Versand stoppen?"
ctrl:
add_files: "Datei(en) hinzufügen"
resume: versenden
send_live: versenden
send_test: testen
stop: stoppen
clone: duplizieren
form:
add_attachment: "Anhang hinzufügen"
current_time: "aktuelle Zeit"
title: "Newsletter erstellen"
menu: Menu
new: "Neuer Newsletter"
title: Newsletter
uploading: wird hochgeladen
nothing: Keine Einträge vorhanden
recipients:
confirm:
delete: Empfänger löschen?
edit:
title: "Empfänger editieren"
new:
ctrl:
check: "Emailadresse(n) überprüfen"
valid_import: "Valide Empfänger importieren"
explanation: "Emailadresse(n) pro Zeile oder durch Komma (,) bzw. Semikolon (;) getrennt eingeben:"
invalid_recipients: "Folgende Empfänger sind ungültig"
title: "Empfänger importieren"
valid_recipients: "Folgende valide Empfänger wurden hinzugefügt"
menu:
export_xls: "Export Exceldatei"
import: Eintragen
delete: Austragen
title: Empfänger
delete:
ctrl:
check: "Emailadresse(n) überprüfen"
confirm_delete: Sicher?
valid_delete: "Empfänger löschen"
explanation: "Emailadresse(n) pro Zeile oder durch Komma (,) bzw. Semikolon (;) getrennt eingeben:"
invalid_recipients: "Folgende Empfänger wurden nicht gefunden"
title: "Mehrere Empfänger löschen"
valid_recipients: "Folgende Empfänger werden gelöscht"
title: "%{account_name} - Empfänger (%{count})"
nothing: Keine Einträge vorhanden
charts:
title: "%{account_name} - Statistik"
|
rngtng/nups
|
e9b198ac11417564b39b54e9f495816509aeab1a
|
speed up NL destroy, fix chart date
|
diff --git a/app/helpers/charts_helper.rb b/app/helpers/charts_helper.rb
index 225bfb3..210e4a1 100644
--- a/app/helpers/charts_helper.rb
+++ b/app/helpers/charts_helper.rb
@@ -1,66 +1,66 @@
module ChartsHelper
NL_FIELDS = %w(finishs_count reads_count fails_count bounces_count sendings_per_second)
def newsletters_chart(newsletters)
{}.tap do |data|
NL_FIELDS.each do |method|
data[method] = []
end
newsletters.each do |newsletter|
- date = newsletter.delivery_started_at.to_i
+ date = newsletter.delivery_started_at.to_i * 1000
NL_FIELDS.each do |method|
data[method] << [date, newsletter.send(method)]
end
end
end
end
def recipients_chart(account)
{
:pending => get_recipients(account.id, 'pending', 'created_at'),
:confirmed => get_recipients_all(account.id, ['confirmed', 'deleted']),
:deleted => get_recipients(account.id, 'deleted', 'updated_at'),
}
end
#private
def get_recipients(account_id, state, field = 'created_at')
Recipient.connection.execute("Set time_zone = '+0:00'")
Recipient.connection.select_rows <<-SQL
SELECT
UNIX_TIMESTAMP(DATE_FORMAT(#{field}, '%Y-%m-%d')) AS `date`,
COUNT(*) AS cnt
FROM recipients
WHERE state = '#{state}'
GROUP BY `date`
ORDER BY `date` ASC
SQL
end
def get_recipients_all(account_id, states = [])
Recipient.connection.execute("Set time_zone = '+0:00'")
Recipient.connection.select_rows <<-SQL
SELECT
UNIX_TIMESTAMP(`date`) AS `date`,
MAX(IF(cnt > 0,cnt,0)) + Min(IF(cnt < 0,cnt,0)) AS cnt
FROM
(SELECT
DATE_FORMAT(created_at, '%Y-%m-%d') AS `date`,
COUNT(*) AS cnt
FROM recipients
WHERE account_id = #{account_id} AND state IN('#{states.join("','")}')
GROUP BY `date`
UNION
SELECT
DATE_FORMAT(updated_at, '%Y-%m-%d') AS `date`,
-1 * COUNT(*) AS cnt
FROM recipients
WHERE account_id = #{account_id} AND state = '#{states.last}'
GROUP BY `date`) AS u
GROUP BY `date`
ORDER BY `date`
SQL
end
end
diff --git a/app/models/newsletter.rb b/app/models/newsletter.rb
index 4398580..220c740 100644
--- a/app/models/newsletter.rb
+++ b/app/models/newsletter.rb
@@ -1,208 +1,209 @@
class Newsletter < ActiveRecord::Base
QUEUE = :nups_newsletter
HEADER_ID = "X-MA-Id"
belongs_to :account
has_many :recipients, :through => :account, :conditions => { 'recipients.state' => :confirmed }
has_many :attachments, :class_name => 'Asset'
- has_many :send_outs, :dependent => :destroy
+ # http://stackoverflow.com/questions/738906/rails-dependent-and-delete
+ has_many :send_outs, :dependent => :delete_all #send_out has no dependency, speed it up
has_many :live_send_outs
has_many :test_send_outs
scope :with_account, lambda { |account| account ? where(:account_id => account.id) : {} }
validates :account_id, :presence => true
validates :subject, :presence => true
before_create :set_recipients_count
########################################################################################################################
state_machine :initial => :new do
event :send_test do
transition :new => :pre_testing
transition :tested => :pre_testing
end
event :send_live do
transition :tested => :pre_sending
transition :stopped => :pre_sending
end
event :process do
transition :pre_testing => :testing
transition :pre_sending => :sending
end
event :stop do
transition :sending => :stopping
transition :testing => :new
end
event :finish do
transition :sending => :finished
transition :testing => :tested
transition :stopping => :stopped
end
after_transition all => :pre_testing do |me, transition|
Resque.enqueue(me.class, me.id, "_send_test!", transition.args[0])
end
after_transition :tested => :pre_sending do |me|
if me.deliver_at && me.deliver_at > Time.now
Resque.enqueue_at(me.deliver_at, me.class, me.id, "_send_live!")
else
Resque.enqueue(me.class, me.id, "_send_live!")
end
end
after_transition :stopped => :pre_sending do |me|
Resque.enqueue(me.class, me.id, "_resume_live!")
end
before_transition :pre_sending => :sending do |me|
me.recipients_count = me.live_send_outs.count #TODO what if stopped??
end
before_transition :sending => :finished do |me|
me.delivery_ended_at = me.live_send_outs.first(:select => "finished_at", :order => "finished_at DESC").try(:finished_at)
end
after_transition all => :stopping do |me|
Resque.enqueue(me.class, me.id, "_stop!")
end
end
########################################################################################################################
def self.queue
QUEUE
end
def self.perform(id, action, email = nil)
self.find(id).send(action, email)
end
########################################################################################################################
def route
[self.account, self]
end
def attachment_ids=(attachment_ids)
self.attachments.clear
attachment_ids.each do |attachment_id|
if attachment_id.present? && (asset = account.assets.find_by_id(attachment_id))
self.attachments << asset
end
end
end
def draft=(draft)
return unless draft
%w(subject content).each do |method|
self.send("#{method}=", draft.send(method))
end
end
########################################################################################################################
def progress_percent
return 0 if self.recipients_count.to_i < 1
(100 * count / self.recipients_count).round
end
#How long did it take to send newsletter
def sending_time
((self.delivery_ended_at || Time.now) - (self.delivery_started_at || Time.now)).to_f.round(2)
end
def count
self.deliveries_count.to_i + self.fails_count.to_i
end
def finishs_count
self.deliveries_count.to_i - self.bounces_count.to_i - self.reads_count.to_i
end
def sendings_per_second
(sending_time > 0) ? (count.to_f / sending_time).round(2) : 0
end
def update_stats!
if sending?
self.delivery_started_at ||= live_send_outs.first(:order => "created_at ASC").try(:created_at)
self.deliveries_count = live_send_outs.where("finished_at IS NOT NULL").count
self.fails_count = live_send_outs.with_state(:failed).count
end
if done?
self.finish!
end
if finished?
self.bounces_count = live_send_outs.with_state(:bounced).count
self.reads_count = live_send_outs.with_state(:read).count
end
self.save!
end
def done?
(sending? && self.live_send_outs.with_state(:sheduled).count == 0) ||
(testing? && self.test_send_outs.with_state(:sheduled).count == 0)
end
#-------------------------------------------------------------------------------------------------------------------------
private
def set_recipients_count
self.recipients_count = recipients.count
end
def _send_test!(email = nil)
account.test_recipient_emails_array(email).each do |test_recipient_email|
self.test_send_outs.create!(:email => test_recipient_email.strip)
end
process!
end
def _send_live!(*args)
self.recipients.each do |live_recipient|
self.live_send_outs.create!(:recipient => live_recipient)
end
process!
end
def _resume_live!(*args)
#self.update_attributes(:delivery_started_at => Time.now)
self.live_send_outs.with_state(:stopped).map(&:resume!)
process!
end
def _stop!(*args)
self.live_send_outs.with_state(:sheduled).update_all(:state => 'stopped')
finish!
end
end
# == Schema Info
#
# Table name: newsletters
#
# id :integer(4) not null, primary key
# account_id :integer(4)
# last_sent_id :integer(4)
# content :text
# deliveries_count :integer(4) not null, default(0)
# errors_count :integer(4) not null, default(0)
# mode :integer(4) not null, default(0)
# recipients_count :integer(4) not null, default(0)
# state :string(255) default("finished")
# status :integer(4) not null, default(0)
# subject :string(255)
# created_at :datetime
# deliver_at :datetime
# delivery_ended_at :datetime
# delivery_started_at :datetime
# updated_at :datetime
\ No newline at end of file
|
rngtng/nups
|
4676b6825b9353ead0b5484d5b710f8077e345e2
|
moved enquque actions back in after transition
|
diff --git a/app/models/newsletter.rb b/app/models/newsletter.rb
index c19f426..4398580 100644
--- a/app/models/newsletter.rb
+++ b/app/models/newsletter.rb
@@ -1,208 +1,208 @@
class Newsletter < ActiveRecord::Base
QUEUE = :nups_newsletter
HEADER_ID = "X-MA-Id"
belongs_to :account
has_many :recipients, :through => :account, :conditions => { 'recipients.state' => :confirmed }
has_many :attachments, :class_name => 'Asset'
has_many :send_outs, :dependent => :destroy
has_many :live_send_outs
has_many :test_send_outs
scope :with_account, lambda { |account| account ? where(:account_id => account.id) : {} }
validates :account_id, :presence => true
validates :subject, :presence => true
before_create :set_recipients_count
########################################################################################################################
state_machine :initial => :new do
event :send_test do
transition :new => :pre_testing
transition :tested => :pre_testing
end
event :send_live do
transition :tested => :pre_sending
transition :stopped => :pre_sending
end
event :process do
transition :pre_testing => :testing
transition :pre_sending => :sending
end
event :stop do
transition :sending => :stopping
transition :testing => :new
end
event :finish do
transition :sending => :finished
transition :testing => :tested
transition :stopping => :stopped
end
- before_transition all => :pre_testing do |me, transition|
+ after_transition all => :pre_testing do |me, transition|
Resque.enqueue(me.class, me.id, "_send_test!", transition.args[0])
end
- before_transition :tested => :pre_sending do |me|
+ after_transition :tested => :pre_sending do |me|
if me.deliver_at && me.deliver_at > Time.now
Resque.enqueue_at(me.deliver_at, me.class, me.id, "_send_live!")
else
Resque.enqueue(me.class, me.id, "_send_live!")
end
end
- before_transition :stopped => :pre_sending do |me|
+ after_transition :stopped => :pre_sending do |me|
Resque.enqueue(me.class, me.id, "_resume_live!")
end
before_transition :pre_sending => :sending do |me|
me.recipients_count = me.live_send_outs.count #TODO what if stopped??
end
before_transition :sending => :finished do |me|
me.delivery_ended_at = me.live_send_outs.first(:select => "finished_at", :order => "finished_at DESC").try(:finished_at)
end
- before_transition all => :stopping do |me|
+ after_transition all => :stopping do |me|
Resque.enqueue(me.class, me.id, "_stop!")
end
end
########################################################################################################################
def self.queue
QUEUE
end
def self.perform(id, action, email = nil)
self.find(id).send(action, email)
end
########################################################################################################################
def route
[self.account, self]
end
def attachment_ids=(attachment_ids)
self.attachments.clear
attachment_ids.each do |attachment_id|
if attachment_id.present? && (asset = account.assets.find_by_id(attachment_id))
self.attachments << asset
end
end
end
def draft=(draft)
return unless draft
%w(subject content).each do |method|
self.send("#{method}=", draft.send(method))
end
end
########################################################################################################################
def progress_percent
return 0 if self.recipients_count.to_i < 1
(100 * count / self.recipients_count).round
end
#How long did it take to send newsletter
def sending_time
((self.delivery_ended_at || Time.now) - (self.delivery_started_at || Time.now)).to_f.round(2)
end
def count
self.deliveries_count.to_i + self.fails_count.to_i
end
def finishs_count
self.deliveries_count.to_i - self.bounces_count.to_i - self.reads_count.to_i
end
def sendings_per_second
(sending_time > 0) ? (count.to_f / sending_time).round(2) : 0
end
def update_stats!
if sending?
self.delivery_started_at ||= live_send_outs.first(:order => "created_at ASC").try(:created_at)
self.deliveries_count = live_send_outs.where("finished_at IS NOT NULL").count
self.fails_count = live_send_outs.with_state(:failed).count
end
if done?
self.finish!
end
if finished?
self.bounces_count = live_send_outs.with_state(:bounced).count
self.reads_count = live_send_outs.with_state(:read).count
end
self.save!
end
def done?
(sending? && self.live_send_outs.with_state(:sheduled).count == 0) ||
(testing? && self.test_send_outs.with_state(:sheduled).count == 0)
end
#-------------------------------------------------------------------------------------------------------------------------
private
def set_recipients_count
self.recipients_count = recipients.count
end
def _send_test!(email = nil)
account.test_recipient_emails_array(email).each do |test_recipient_email|
self.test_send_outs.create!(:email => test_recipient_email.strip)
end
process!
end
def _send_live!(*args)
self.recipients.each do |live_recipient|
self.live_send_outs.create!(:recipient => live_recipient)
end
process!
end
def _resume_live!(*args)
#self.update_attributes(:delivery_started_at => Time.now)
self.live_send_outs.with_state(:stopped).map(&:resume!)
process!
end
def _stop!(*args)
self.live_send_outs.with_state(:sheduled).update_all(:state => 'stopped')
finish!
end
end
# == Schema Info
#
# Table name: newsletters
#
# id :integer(4) not null, primary key
# account_id :integer(4)
# last_sent_id :integer(4)
# content :text
# deliveries_count :integer(4) not null, default(0)
# errors_count :integer(4) not null, default(0)
# mode :integer(4) not null, default(0)
# recipients_count :integer(4) not null, default(0)
# state :string(255) default("finished")
# status :integer(4) not null, default(0)
# subject :string(255)
# created_at :datetime
# deliver_at :datetime
# delivery_ended_at :datetime
# delivery_started_at :datetime
# updated_at :datetime
\ No newline at end of file
|
rngtng/nups
|
f9b54173ea9c569d0507506f6920296456c97175
|
move scheduler deploy task to rake
|
diff --git a/.gitignore b/.gitignore
index 32bf618..c04514a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,19 +1,20 @@
.rvmrc
.bundle
db/*.sqlite3
db/schema.rb
log/*.log
tmp/
.DS_Store
config/database.yml
config/mail.yml
public/system
dump.rdb
Newsletter_state.png
Sending_state.png
.tmtags
config/setup_load_paths.rb
.sass-cache
log/resque_err
log/resque_stdout
coverage
+log/resque_scheduler
\ No newline at end of file
diff --git a/config/deploy.rb b/config/deploy.rb
index 2b62f8b..1aa4c2b 100644
--- a/config/deploy.rb
+++ b/config/deploy.rb
@@ -1,139 +1,102 @@
$:.unshift(File.expand_path('./lib', ENV['rvm_path']))
require 'rvm/capistrano'
require 'bundler/capistrano'
require 'new_relic/recipes'
set :application, "nups"
set :host, "www2.multiadmin.de"
set :use_sudo, false
set :user, 'ssh-21560'
set :rvm_type, :user
set :rvm_ruby_string, "ruby-1.9.2-p290"
set :keep_releases, 3
set :default_environment, {
'LANG' => 'en_US.UTF-8'
}
# If you aren't deploying to /u/apps/#{application} on the target
# servers (which is the default), you can specify the actual location
# via the :deploy_to variable:
set :deploy_to, "/kunden/warteschlange.de/produktiv/rails/#{application}"
# If you aren't using Subversion to manage your source code, specify
# your SCM below:
set :scm, :git
set :repository, "git://github.com/rngtng/#{application}.git"
set :branch, "master"
set :normalize_asset_timestamps, false
set :deploy_via, :remote_cache
set :ssh_options, :forward_agent => true
role :app, host
role :web, host
role :db, host, :primary => true
role :job, host
##
# Rake helper task.
# http://pastie.org/255489
# http://geminstallthat.wordpress.com/2008/01/27/rake-tasks-through-capistrano/
# http://ananelson.com/said/on/2007/12/30/remote-rake-tasks-with-capistrano/
def run_remote_rake(rake_cmd)
rake_args = ENV['RAKE_ARGS'].to_s.split(',')
cmd = "cd #{fetch(:latest_release)} && #{fetch(:rake, "rake")} RAILS_ENV=#{fetch(:rails_env, "production")} #{rake_cmd}"
cmd += "['#{rake_args.join("','")}']" unless rake_args.empty?
run cmd
set :rakefile, nil if exists?(:rakefile)
end
namespace :deploy do
desc "Restarting mod_rails with restart.txt"
task :restart, :roles => :app, :except => { :no_release => true } do
run "touch #{current_path}/tmp/restart.txt"
end
desc "Link in the production database.yml"
task :link_configs do
run "ln -nfs #{deploy_to}/#{shared_dir}/database.yml #{release_path}/config/database.yml"
run "ln -nfs #{deploy_to}/#{shared_dir}/mail.yml #{release_path}/config/mail.yml"
run "ln -nfs #{deploy_to}/#{shared_dir}/uploads #{release_path}/public/system"
end
[:start, :stop].each do |t|
desc "#{t} task is a no-op with mod_rails"
task t, :roles => :app do ; end
end
desc "Restart Resque Workers"
task :restart_workers, :roles => :job do
run_remote_rake "resque:workers:restart"
- resque.scheduler.stop
- resque.scheduler.start
end
desc "precompile the assets"
task :precompile_assets, :roles => :web, :except => { :no_release => true } do
run_remote_rake "assets:precompile"
end
end
def remote_file_exists?(full_path)
'true' == capture("if [ -e #{full_path} ]; then echo 'true'; fi").strip
end
-namespace :resque do
- namespace :scheduler do
- def scheduler_pid
- File.join(current_release, "tmp/pids/resque_scheduler.pid")
- end
-
- def scheduler_log
- File.join(current_release, "log/resque_scheduler.log")
- end
-
- desc "start scheduler"
- task :start, :roles => :job do
- unless remote_file_exists?(scheduler_pid)
- # INITIALIZER_PATH=#{current_release}/
- run "cd #{current_release}; RAILS_ENV=production PIDFILE=#{scheduler_pid} nohup bundle exec rake resque:scheduler &> #{scheduler_log}& 2> /dev/null"
- else
- puts "PID File exits!!"
- end
- end
-
- desc "stop scheduler"
- task :stop, :roles => :job do
- if remote_file_exists?(scheduler_pid)
- begin
- run "kill -s QUIT `cat #{scheduler_pid}`"
- rescue
- end
- run "rm -f #{scheduler_pid}"
- else
- puts "No PID File found"
- end
- end
- end
-end
-
after "deploy:update_code" do
deploy.link_configs
deploy.precompile_assets
end
after "deploy:symlink", "deploy:restart_workers"
after "deploy:symlink", "deploy:cleanup"
after "deploy:update", "newrelic:notice_deployment"
# require './config/boot'
# require 'airbrake/capistrano'
diff --git a/lib/tasks/resque.rake b/lib/tasks/resque.rake
index 642ff87..2ce7d54 100644
--- a/lib/tasks/resque.rake
+++ b/lib/tasks/resque.rake
@@ -1,85 +1,121 @@
## TAKEN from: https://gist.github.com/797301
require 'resque/tasks'
require 'resque_scheduler/tasks'
namespace :resque do
task :setup => :environment do
require 'resque'
require 'resque_scheduler'
require 'resque/scheduler'
resque_config = YAML.load_file (Rails.root + 'config/resque.yml').to_s
# you probably already have this somewhere
Resque.redis = resque_config[Rails.env]
# The schedule doesn't need to be stored in a YAML, it just needs to
# be a hash. YAML is usually the easiest.
Resque.schedule = YAML.load_file (Rails.root + 'config/resque_schedule.yml').to_s
# If your schedule already has +queue+ set for each job, you don't
# need to require your jobs. This can be an advantage since it's
# less code that resque-scheduler needs to know about. But in a small
# project, it's usually easier to just include you job classes here.
# So, someting like this:
#require 'jobs'
# If you want to be able to dynamically change the schedule,
# uncomment this line. A dynamic schedule can be updated via the
# Resque::Scheduler.set_schedule (and remove_schedule) methods.
# When dynamic is set to true, the scheduler process looks for
# schedule changes and applies them on the fly.
# Note: This feature is only available in >=2.0.0.
Resque::Scheduler.dynamic = true
end
namespace :workers do
desc "Restart running workers"
task :restart => :environment do
Rake::Task['resque:workers:stop'].invoke
Rake::Task['resque:workers:start'].invoke
end
desc "Quit running workers"
task :stop => :environment do
+ Rake::Task['resque:scheduler:stop'].invoke
pids = Resque.workers.select do |worker|
worker.to_s.include?('nups_')
end.map(&:worker_pids).flatten.uniq
if pids.any?
syscmd = "kill -s QUIT #{pids.join(' ')}"
puts "Running syscmd: #{syscmd}"
system(syscmd)
else
puts "No workers to kill"
end
end
# http://stackoverflow.com/questions/2532427/why-is-rake-not-able-to-invoke-multiple-tasks-consecutively
desc "Start workers"
task :start => :environment do
+ Rake::Task['resque:scheduler:start'].invoke
Rake::Task['resque:worker:start'].execute(:queue => Bounce, :count => 1, :jobs => 100)
Rake::Task['resque:worker:start'].execute(:queue => Newsletter)
Rake::Task['resque:worker:start'].execute(:queue => SendOut, :count => 5, :jobs => 100)
end
end
namespace :worker do
# http://nhw.pl/wp/2008/10/11/rake-and-arguments-for-tasks
desc "Start a worker with proper env vars and output redirection"
task :start, [:queue, :count, :jobs] => :environment do |t, args|
args = args.to_hash.reverse_merge(:count => 1, :jobs => 1)
queue = args[:queue].to_s.underscore.classify.constantize::QUEUE
puts "Starting #{args[:count]} worker(s) with #{args[:jobs]} Jobs for QUEUE: #{queue}"
ops = {:pgroup => true, :err => [(Rails.root + "log/resque_err").to_s, "a"],
:out => [(Rails.root + "log/resque_stdout").to_s, "a"]}
env_vars = {"QUEUE" => queue.to_s, "JOBS_PER_FORK" => args[:jobs].to_s}
args[:count].times {
## Using Kernel.spawn and Process.detach because regular system() call would
## cause the processes to quit when capistrano finishes
pid = spawn(env_vars, "rake resque:work", ops)
Process.detach(pid)
}
end
end
+
+ namespace :scheduler do
+ def scheduler_pid
+ (Rails.root + "tmp/pids/resque_scheduler.pid").to_s
+ end
+
+ def scheduler_log
+ (Rails.root + "log/resque_scheduler").to_s
+ end
+
+ desc "Start Resque Scheduler"
+ task :start => :setup do
+ ops = {:pgroup => true, :err => [scheduler_log, "a"], :out => [scheduler_log, "a"]}
+ env_vars = {"PIDFILE" => scheduler_pid, "DYNAMIC_SCHEDULE" => true.to_s} #"VERBOSE" => true,
+ pid = spawn(env_vars, "rake resque:scheduler", ops)
+ Process.detach(pid)
+ end
+
+ desc "Stop Resque Scheduler"
+ task :stop do
+ if File.exists?(scheduler_pid)
+ begin
+ syscmd = "kill -s QUIT `cat #{scheduler_pid}`"
+ puts "Running syscmd: #{syscmd}"
+ system(syscmd)
+ rescue
+ end
+ system("rm -f #{scheduler_pid}")
+ else
+ puts "No PID File found"
+ end
+ end
+ end
+
end
\ No newline at end of file
|
rngtng/nups
|
34e20d5d6b0505f6c7438627d1869b91a7712bd9
|
propagate sending exception to top
|
diff --git a/README.md b/README.md
index 906bfcb..b446998 100644
--- a/README.md
+++ b/README.md
@@ -1,92 +1,90 @@
# Welcome to NUPS
## resources
* Overview of best plugins: http://ruby-toolbox.com/
* [Devise](http://github.com/plataformatec/devise) -> `rails generate devise_install`
* Test SMTP lockally: http://mocksmtpapp.com/
* Spinners:
http://www.andrewdavidson.com/articles/spinning-wait-icons/
http://mentalized.net/activity-indicators/
## TODO
- * stop while in pre_sending??
+ * check: stop while in pre_sending??
+ * check: error when creating send_outs
* chart when people read
- * introduce foreign key for send_outs? -> auto delete test sendouts
* remove mode/status/last_send_id from newsletter
* order DESC
* heighlight reciever with bounce count, set option to disable
* translation (gender)
* add better migration
* test coffeescript
* animate sendout & test gif icons
* check: http://isnotspam.com
* test premailer
* add index to recipients
* bounce only when 5.X code
* bounce cleanup
- * check what happens if a single sendout fails within a batch
* mv send_out textfield into string? (speed up)
## DONE
+ * check what happens if a single sendout fails within a batch
* add better fixtures: factory_girl
* newsletter stats: total/percent send/fail/bounces/read count
-> * add infos to newsletter to see total read/bounces
* history stats
recipient growth
newsletter read/bounce growth
sending time/speed
* remove error_message recipeint -> move to send_out
* change update_newsletter to json
* reactivate deleted users
* send test email to current_user.email
* newsletter unsubscribe by email
* autodetect URLS
* unsubscribe ->
header: http://www.list-unsubscribe.com/
* recipients: overflow for user name + email
* remove error_code from send_out
* errors_count + errors message
* hidden image to register if nl was read *test*
* read NL on website *test*
* read count to recipient *update when read* *test*
* update bounce counters:
-> only counter bounces younger than last update time -> bounces_count_updated_at
-> resque task?
-> on bounce create? if user available?
* update deliver counters:
-> after send?
* fix receiver edit
* recipients overlay with list of sendouts (details -> when which newsletter was send)
* hide deleted receiver
* sort receiver column, indicate sorting *test*
* receiver paginate ajax
* pretty time span
* add user total count on top
* update deliverd_startet_at_ from youngest sendout
* scheduling
* recipients import/export
* Newsletter delete ajax
* search pagination, show total amount
* attachment upload
* new newsletter scroll
* reload after recp import
* open new newsletter in window
* recipients
* in place editing (improvement see rails cast)
* fix travis setup: http://about.travis-ci.org/docs/user/build-configuration/
* progress bar update time
* resque status: http://github.com/quirkey/resque-status
## Resque Startup:
-
- 1. redis-server
- 2. COUNT=1 QUEUE=* rake resque:workers
+ * rake resque:workers:start
## Mail
http://www.techsoup.org/learningcenter/internet/page5052.cfm
http://www.sitepoint.com/forums/showthread.php?571536-Building-a-newsletter-not-getting-listed-as-spam
http://gettingattention.org/articles/160/email-enewsletters/nonprofit-email-newsletter-success.html
## Builder
[](http://travis-ci.org/rngtng/nups)
diff --git a/app/assets/javascripts/newsletters.js b/app/assets/javascripts/newsletters.js
index f354591..24191c6 100644
--- a/app/assets/javascripts/newsletters.js
+++ b/app/assets/javascripts/newsletters.js
@@ -1,113 +1,116 @@
var request = function(newsletterPath){
$.ajax({
url: newsletterPath,
data: {
ids: $.makeArray($('.newsletter').map(function(){
return this.id.replace('newsletter-', '');
}))
},
dataType: 'json',
success: function (data, status, xhr) {
$('#newsletters').removeClass('scheduled');
$.each(data, function(index, newsletter){
updateNewsletter(newsletter);
});
+ schedule();
},
error: function (jqXHR, textStatus, errorThrown) {
- alert("Error in request: " + jqXHR + " - "+ textStatus + " - " + errorThrown);
+ console.log(jqXHR);
+ console.log("Error in request:" + textStatus + " - " + errorThrown);
+ schedule();
}
});
},
schedule = function(){
$('#newsletters:not(.scheduled) .newsletter:not(.finished):first').each(function(){
var newsletterPath = $(this).data('newsletter-path'),
pullTime = $(this).data('pull-time');
$('#newsletters').addClass('scheduled');
window.setTimeout(function(){
request(newsletterPath);
}, window.parseInt(pullTime));
})
},
updateNewsletter = function(nl){
$('#newsletter-' + nl.id)
.attr('class', 'newsletter ' + nl.state)
.find('.progress')
.width(nl.progress_percent + '%')
.show()
.find('label')
.text(nl.progress_percent + '%')
.end()
.end()
.find('.stats')
.find('.progress-percent').html(nl.progress_percent + '%').end()
.find('.sending-time').html(distance_of_time(nl.delivery_started_at, nl.delivery_ended_at, true)).end()
.find('.sendings-per-sec').html(nl.sendings_per_second + '/sec.').end()
.find('.finishs span').html(nl.finishs_count).end()
.find('.reads span').html(nl.reads_count).end()
.find('.bounces span').html(nl.bounces_count).end()
.find('.fails span').html(nl.fails_count).end();
- schedule();
};
$('#newsletters a.delete').live('ajax:success', function(e, data, status, xhr) {
$('#newsletter-' + data.id).remove();
});
$('#newsletters').find('.send-live,.send-test,.stop').live('ajax:success', function(e, data, status, xhr) {
updateNewsletter(data);
+ schedule();
}).live('ajax:error', function(e, xhr, status, error){
alert("Please try again!" + e + " " +error);
});
$.tools.tabs.addEffect("ajaxOverlay", function(tabIndex, done) {
this.getPanes().eq(0).html("").load(this.getTabs().eq(tabIndex).attr("href"), function() {
$(newsletterNavElements).attr('data-type', 'html');
$("tbody a[rel=#overlay]").attachOverlay();
$("table.content").showNothingFound();
if( (url = $("a.current").data("new-url")) ){
$("a.new").show().attr("href", url);
}
else {
$("a.new").hide();
}
});
done.call();
});
var newsletterNavElements = "#newsletters table .paginate a";
$("#newsletters table .paginate a")
.live('ajax:success', function(e, data, status, xhr){
$("#newsletters table tbody").html(data);
$(newsletterNavElements).attr('data-type', 'html');
$("tbody a.preview[rel=#overlay]").attachOverlay();
$("table.content").showNothingFound();
})
.live('ajax:error', function(e, xhr, status, error){
alert("Please try again!");
});
$(document).keypress(function(e){
if( (e.keyCode || e.which) == 113 ){
$("body").removeClass("default");
}
})
$(document).ready(function (){
$("#newsletters").each(function(){
schedule();
$("ul.tabs").tabs("table > tbody", {
effect: 'ajaxOverlay',
initialIndex: -1
});
$(newsletterNavElements).attr('data-type', 'html');
$("a[rel=#overlay]").attachOverlay();
$("table.content").showNothingFound();
//console.log('#newsletters loaded');
});
});
diff --git a/app/helpers/newsletters_helper.rb b/app/helpers/newsletters_helper.rb
index 21f5126..c5d12d9 100644
--- a/app/helpers/newsletters_helper.rb
+++ b/app/helpers/newsletters_helper.rb
@@ -1,7 +1,7 @@
module NewslettersHelper
def pull_time
- Rails.env.test? ? 400 : 2000
+ Rails.env.test? ? 250 : 2000
end
end
diff --git a/app/models/live_send_out.rb b/app/models/live_send_out.rb
index 6d8ad34..efcc7a6 100644
--- a/app/models/live_send_out.rb
+++ b/app/models/live_send_out.rb
@@ -1,51 +1,58 @@
class LiveSendOut < SendOut
validates :recipient_id, :presence => true, :uniqueness => {:scope => [:newsletter_id, :type]}, :on => :create
before_validation :set_email, :on => :create
state_machine :initial => :sheduled do
before_transition :delivering => :finished do |me|
me.finished_at = Time.now
me.recipient.update_attribute(:deliveries_count, me.recipient.deliveries_count + 1)
end
before_transition :delivering => :failed do |me, transition|
- me.error_message = transition.args[0]
+ me.error_message = transition.args[0].message
me.recipient.update_attribute(:fails_count, me.recipient.fails_count + 1)
end
+ after_transition :delivering => :failed do |me, transition|
+ # a bit dirty hack: force to end transition successfull but still
+ # propagade execption
+ me.connection.execute("COMMIT") #prevent rollback
+ raise transition.args[0]
+ end
+
before_transition :finished => :read do |me|
me.recipient.update_attribute(:reads_count, me.recipient.reads_count + 1)
end
before_transition :finished => :bounced do |me, transition|
me.error_message = transition.args[0]
me.recipient.update_attribute(:bounces_count, me.recipient.bounces_count + 1)
end
end
def issue_id
["ma", self.id, self.recipient_id].join('-')
end
private
def set_email
self.email = recipient.email
end
end
# == Schema Info
#
# Table name: send_outs
#
# id :integer(4) not null, primary key
# newsletter_id :integer(4)
# recipient_id :integer(4)
# email :string(255)
# error_message :text
# state :string(255)
# type :string(255)
# created_at :datetime
# finished_at :datetime
# updated_at :datetime
\ No newline at end of file
diff --git a/app/models/newsletter.rb b/app/models/newsletter.rb
index b6bc58a..c19f426 100644
--- a/app/models/newsletter.rb
+++ b/app/models/newsletter.rb
@@ -1,208 +1,208 @@
class Newsletter < ActiveRecord::Base
QUEUE = :nups_newsletter
HEADER_ID = "X-MA-Id"
belongs_to :account
has_many :recipients, :through => :account, :conditions => { 'recipients.state' => :confirmed }
has_many :attachments, :class_name => 'Asset'
has_many :send_outs, :dependent => :destroy
has_many :live_send_outs
has_many :test_send_outs
scope :with_account, lambda { |account| account ? where(:account_id => account.id) : {} }
validates :account_id, :presence => true
validates :subject, :presence => true
before_create :set_recipients_count
########################################################################################################################
state_machine :initial => :new do
event :send_test do
transition :new => :pre_testing
transition :tested => :pre_testing
end
event :send_live do
transition :tested => :pre_sending
transition :stopped => :pre_sending
end
event :process do
transition :pre_testing => :testing
transition :pre_sending => :sending
end
event :stop do
transition :sending => :stopping
transition :testing => :new
end
event :finish do
transition :sending => :finished
transition :testing => :tested
transition :stopping => :stopped
end
- after_transition all => :pre_testing do |me, transition|
+ before_transition all => :pre_testing do |me, transition|
Resque.enqueue(me.class, me.id, "_send_test!", transition.args[0])
end
- after_transition :tested => :pre_sending do |me|
- if me.deliver_at
+ before_transition :tested => :pre_sending do |me|
+ if me.deliver_at && me.deliver_at > Time.now
Resque.enqueue_at(me.deliver_at, me.class, me.id, "_send_live!")
else
Resque.enqueue(me.class, me.id, "_send_live!")
end
end
- after_transition :stopped => :pre_sending do |me|
+ before_transition :stopped => :pre_sending do |me|
Resque.enqueue(me.class, me.id, "_resume_live!")
end
before_transition :pre_sending => :sending do |me|
me.recipients_count = me.live_send_outs.count #TODO what if stopped??
end
before_transition :sending => :finished do |me|
me.delivery_ended_at = me.live_send_outs.first(:select => "finished_at", :order => "finished_at DESC").try(:finished_at)
end
- after_transition all => :stopping do |me|
+ before_transition all => :stopping do |me|
Resque.enqueue(me.class, me.id, "_stop!")
end
end
########################################################################################################################
def self.queue
QUEUE
end
def self.perform(id, action, email = nil)
self.find(id).send(action, email)
end
########################################################################################################################
def route
[self.account, self]
end
def attachment_ids=(attachment_ids)
self.attachments.clear
attachment_ids.each do |attachment_id|
if attachment_id.present? && (asset = account.assets.find_by_id(attachment_id))
self.attachments << asset
end
end
end
def draft=(draft)
return unless draft
%w(subject content).each do |method|
self.send("#{method}=", draft.send(method))
end
end
########################################################################################################################
def progress_percent
return 0 if self.recipients_count.to_i < 1
(100 * count / self.recipients_count).round
end
#How long did it take to send newsletter
def sending_time
((self.delivery_ended_at || Time.now) - (self.delivery_started_at || Time.now)).to_f.round(2)
end
def count
self.deliveries_count.to_i + self.fails_count.to_i
end
def finishs_count
self.deliveries_count.to_i - self.bounces_count.to_i - self.reads_count.to_i
end
def sendings_per_second
(sending_time > 0) ? (count.to_f / sending_time).round(2) : 0
end
def update_stats!
if sending?
self.delivery_started_at ||= live_send_outs.first(:order => "created_at ASC").try(:created_at)
self.deliveries_count = live_send_outs.where("finished_at IS NOT NULL").count
self.fails_count = live_send_outs.with_state(:failed).count
end
if done?
self.finish!
end
if finished?
self.bounces_count = live_send_outs.with_state(:bounced).count
self.reads_count = live_send_outs.with_state(:read).count
end
self.save!
end
def done?
(sending? && self.live_send_outs.with_state(:sheduled).count == 0) ||
(testing? && self.test_send_outs.with_state(:sheduled).count == 0)
end
#-------------------------------------------------------------------------------------------------------------------------
private
def set_recipients_count
self.recipients_count = recipients.count
end
def _send_test!(email = nil)
account.test_recipient_emails_array(email).each do |test_recipient_email|
self.test_send_outs.create!(:email => test_recipient_email.strip)
end
process!
end
def _send_live!(*args)
self.recipients.each do |live_recipient|
self.live_send_outs.create!(:recipient => live_recipient)
end
process!
end
def _resume_live!(*args)
#self.update_attributes(:delivery_started_at => Time.now)
self.live_send_outs.with_state(:stopped).map(&:resume!)
process!
end
def _stop!(*args)
self.live_send_outs.with_state(:sheduled).update_all(:state => 'stopped')
- self.finish!
+ finish!
end
end
# == Schema Info
#
# Table name: newsletters
#
# id :integer(4) not null, primary key
# account_id :integer(4)
# last_sent_id :integer(4)
# content :text
# deliveries_count :integer(4) not null, default(0)
# errors_count :integer(4) not null, default(0)
# mode :integer(4) not null, default(0)
# recipients_count :integer(4) not null, default(0)
# state :string(255) default("finished")
# status :integer(4) not null, default(0)
# subject :string(255)
# created_at :datetime
# deliver_at :datetime
# delivery_ended_at :datetime
# delivery_started_at :datetime
# updated_at :datetime
\ No newline at end of file
diff --git a/app/models/send_out.rb b/app/models/send_out.rb
index 2649233..a39bb9e 100644
--- a/app/models/send_out.rb
+++ b/app/models/send_out.rb
@@ -1,97 +1,93 @@
class SendOut < ActiveRecord::Base
QUEUE = :nups_send_outs
belongs_to :newsletter
belongs_to :recipient
validates :newsletter_id, :presence => true
- validates :email, :presence => true
after_save :async_deliver!
- # Add this to remove it from transition
- # alias_method :save_state, :save
- #, :use_transactions => false, :action => :save_state do
state_machine :initial => :sheduled do
event :deliver do
transition :sheduled => :delivering
end
event :resume do
transition :stopped => :sheduled
end
event :stop do
transition :sheduled => :stopped
end
event :finish do
transition :delivering => :finished
end
event :failure do
transition :delivering => :failed
end
event :read do
transition :finished => :read
transition :read => :read
end
event :bounce do
transition :finished => :bounced
transition :bounced => :bounced
end
after_transition :sheduled => :delivering do |me|
begin
me.issue.deliver
me.finish!
rescue Exception => e
- me.failure!(e.message)
+ me.failure!(e)
end
end
end
########################################################################################################################
def self.queue
QUEUE
end
def self.perform(id)
with_state(:sheduled).find_by_id(id, :include => [:newsletter, :recipient]).try(:deliver!)
end
def issue
@issue ||= NewsletterMailer.issue(self.newsletter, self.recipient, self.id).tap do |issue|
issue.header[Newsletter::HEADER_ID] = issue_id
end
end
def issue_id #likely overwritten by subclasses
["ma", self.id].join('-')
end
private
def async_deliver!
if sheduled?
Resque.enqueue(self.class, self.id)
end
end
end
# == Schema Info
#
# Table name: send_outs
#
# id :integer(4) not null, primary key
# newsletter_id :integer(4)
# recipient_id :integer(4)
# email :string(255)
# error_message :text
# state :string(255)
# type :string(255)
# created_at :datetime
# finished_at :datetime
# updated_at :datetime
\ No newline at end of file
diff --git a/spec/controllers/newsletters_controller_spec.rb b/spec/controllers/newsletters_controller_spec.rb
index a372b2c..9053be8 100644
--- a/spec/controllers/newsletters_controller_spec.rb
+++ b/spec/controllers/newsletters_controller_spec.rb
@@ -1,205 +1,214 @@
require 'spec_helper'
describe NewslettersController do
include Devise::TestHelpers
fixtures :accounts, :users, :newsletters
let(:admin) { users(:admin) }
let(:user) { users(:biff) }
let(:newsletter) { newsletters(:biff_newsletter) }
let(:account) { newsletter.account }
context "logged out" do
it "should not get index" do
get :index, :account_id => account.to_param
response.status.should == 302
end
it "should not get new" do
get :new, :account_id => account.to_param
response.status.should == 302
end
it "should not get show" do
get :show, :account_id => account.to_param, :id => newsletter.id
response.status.should == 302
end
end
context "logged in" do
render_views
before do
sign_in user
end
describe "index" do
it "is success" do
get :index, :account_id => account.to_param
response.status.should == 200 #:success
end
it "assigns newsletters" do
get :index, :account_id => account.to_param
assigns(:newsletters).should =~ account.newsletters
end
it "gets not index for other user account" do
get :index, :account_id => accounts(:admin_account).to_param
response.status.should == 404
end
it "sees all own newsletters" do
get :index
assigns(:newsletters).should =~ user.newsletters
end
context "as admin" do
before do
sign_in admin
end
it "sees all newsletter for other user" do
get :index, :user_id => user.id
assigns(:newsletters).should =~ user.newsletters
end
it "gets index for other user account" do
get :index, :account_id => account.to_param
assigns(:newsletters).should =~ account.newsletters
end
end
end
describe "stats" do
it "should get stats" do
get :stats, :account_id => account.to_param, :format => :js
response.status.should == 200 #:success
assigns(:newsletters).should_not be_nil
end
end
describe "new" do
it "should get new" do
get :index, :account_id => account.to_param
response.status.should == 200 #:success
end
it "doesn't get new if wrong account" do
account = accounts(:admin_account)
get :new, :account_id => account.to_param
response.status.should == 404 #:not_found
end
it "gets new if wrong account but admin" do
sign_in admin
get :new, :account_id => account.to_param
assigns(:newsletter).subject.should == account.subject
response.status.should == 200 #:success
end
end
describe "show" do
context "html" do
before do
xhr :get, :show, :account_id => account.to_param, :id => newsletter.to_param
end
it "assigns newsletter" do
assigns(:newsletter).id.should == newsletter.id
end
it "response valid" do
response.status.should == 200 #:success
end
end
it "returns newletter html content" do
xhr :get, :show, :account_id => account.to_param, :id => newsletter.to_param
response.body.should include(newsletter.content)
end
end
describe "create" do
it "creates newsletter" do
expect do
post :create, :account_id => account.to_param, :newsletter => newsletter.attributes
end.to change(Newsletter, :count)
end
it "creates newsletter with empty attachment_ids" do
expect do
post :create, :account_id => account.to_param, :newsletter => {:subject => "blabla", :attachment_ids => ["1"]}
end.to change(Newsletter, :count)
end
it "redirects to newsletters form account" do
post :create, :account_id => account.to_param, :newsletter => newsletter.attributes
response.should redirect_to(account_newsletters_path(account))
end
context "as admin" do
before do
sign_in admin
end
it "creates newsletter for other user" do
expect do
post :create, :account_id => account.to_param, :newsletter => newsletter.attributes, :preview => true
end.to change { account.newsletters.count }
end
end
end
describe "edit" do
it "does success" do
get :edit, :account_id => account.to_param, :id => newsletter.to_param
response.status.should == 200 #:success
end
end
describe "update" do
it "should update newsletter" do
put :update, :account_id => account.to_param, :id => newsletter.to_param, :newsletter => newsletter.attributes
response.should redirect_to(account_newsletters_path(account))
end
end
describe "destroy" do
it "should destroy newsletter" do
expect do
delete :destroy, :account_id => account.to_param, :id => newsletter.to_param
end.to change(Newsletter, :count).by(-1)
end
it "should redirect to newsletters from account" do
delete :destroy, :account_id => account.to_param, :id => newsletter.to_param
response.should redirect_to(account_newsletters_path(account))
end
end
describe "schedule" do
- it "changes newsletter state" do
- get :start, :account_id => account.to_param, :id => newsletter.to_param
- newsletter.reload.testing?.should be_true
- end
+ context "test" do
+ it "changes newsletter state" do
+ get :start, :account_id => account.to_param, :id => newsletter.to_param
+ newsletter.reload.pre_testing?.should be_true
+ end
- it "queues test newsletter" do
- get :start, :account_id => account.to_param, :id => newsletter.to_param
- Newsletter.should have_queued(newsletter.id, "_send_test!", user.email)
- end
+ it "queues test newsletter" do
+ get :start, :account_id => account.to_param, :id => newsletter.to_param
+ Newsletter.should have_queued(newsletter.id, "_send_test!", user.email)
+ end
- it "queues live newsletter" do
- get :start, :account_id => account.to_param, :id => newsletter.to_param, :mode => 'live'
- Newsletter.should have_queued(newsletter.id, "_send_live!")
+ it "redirects to newsletters from account" do
+ get :start, :account_id => account.to_param, :id => newsletter.to_param
+ response.should redirect_to(account_newsletters_path(account))
+ end
end
- it "redirects to newsletters from account" do
- get :start, :account_id => account.to_param, :id => newsletter.to_param
- response.should redirect_to(account_newsletters_path(account))
+ context "live" do
+ it "changes newsletter state" do
+ get :start, :account_id => account.to_param, :id => newsletter.to_param, :mode => 'live'
+ newsletter.reload.pre_sending?.should be_true
+ end
+
+ it "queues live newsletter" do
+ get :start, :account_id => account.to_param, :id => newsletter.to_param, :mode => 'live'
+ Newsletter.should have_queued(newsletter.id, "_send_live!")
+ end
end
end
end
end
diff --git a/spec/integration/newsletters_page_spec.rb b/spec/integration/newsletters_page_spec.rb
index 1f153c0..fc99c8e 100644
--- a/spec/integration/newsletters_page_spec.rb
+++ b/spec/integration/newsletters_page_spec.rb
@@ -1,158 +1,158 @@
# encoding: UTF-8
require 'spec_helper'
describe 'recipients page' do
fixtures :users, :accounts, :recipients, :newsletters
let(:user) { users(:biff) }
let(:account) { accounts(:biff_account) }
let(:newsletter) { newsletters(:biff_newsletter) }
let(:newsletter2) { newsletters(:biff_newsletter_two) }
before do
visit '/'
fill_in 'user_username', :with => user.email
fill_in 'user_password', :with => 'admin'
click_on 'Login'
end
it 'show newsletters, preview, delete and edit', :js => true do
visit all_newsletters_path
within("#newsletter-#{newsletter.id}") do
find(".info").should have_content(newsletter.subject)
find(".send-test").should be_visible
find(".send-live").should be_visible
find(".stop").should_not be_visible
find("a.preview").click
sleep 1
end
page.should have_content(newsletter.content)
find("a.close").click
# delete
within("#newsletter-#{newsletter.id}") do
find("a.delete").click
page.driver.browser.switch_to.alert.accept
sleep 1
end
page.should have_no_selector("#newsletter-#{newsletter.id}")
#edit
within("#newsletter-#{newsletter2.id}") do
find("td.info").should have_content(newsletter2.subject)
find(".send-test").should be_visible
find(".send-live").should_not be_visible
find("a.edit").click
end
#redirected
page.should have_content('Absender')
page.should have_selector("textarea.cleditor")
end
context "sending" do
before do
visit account_newsletters_path(account)
end
it 'sends test newsletter', :js => true do
selector = "#newsletter-#{newsletter2.id}"
page.should have_no_selector("#{selector}.tested")
expect do
find("#{selector} a.send-test").click
sleep 1
page.should have_selector("#newsletter-#{newsletter2.id}.pre_testing")
find("#{selector} .progress-bar").should be_visible
ResqueSpec.perform_next(Newsletter::QUEUE)
sleep 1
page.should have_selector("#{selector}.testing")
ResqueSpec.perform_all(SendOut::QUEUE)
end.to change(ActionMailer::Base.deliveries, :size).by(3)
- sleep 5
+ sleep 1
page.should have_selector("#{selector}.tested")
end
it 'sends live newsletter', :js => true do
selector = "#newsletter-#{newsletter.id}"
expect do
find("#{selector} a.send-live").click
page.driver.browser.switch_to.alert.accept
sleep 1
page.should have_selector("#{selector}.pre_sending")
find("#{selector} .progress-bar").should be_visible
ResqueSpec.perform_next(Newsletter::QUEUE)
sleep 1
page.should have_selector("#{selector}.sending")
ResqueSpec.perform_next(SendOut::QUEUE)
sleep 1
page.should have_content('50%')
ResqueSpec.perform_next(SendOut::QUEUE)
sleep 1
page.should have_content('100%')
end.to change(ActionMailer::Base.deliveries, :size).by(2)
page.should have_selector("#{selector}.finished")
end
it 'stops and resume live newsletter', :js => true do
selector = "#newsletter-#{newsletter.id}"
expect do
find("#{selector} a.send-live").click
page.driver.browser.switch_to.alert.accept
sleep 1
page.should have_selector("#{selector}.pre_sending")
find("#{selector} .progress-bar").should be_visible
ResqueSpec.perform_next(Newsletter::QUEUE)
ResqueSpec.perform_next(SendOut::QUEUE)
sleep 1
page.should have_content('50%')
end.to change(ActionMailer::Base.deliveries, :size).by(1)
find("#{selector} a.stop").click
page.driver.browser.switch_to.alert.accept
sleep 1
page.should have_selector("#{selector}.stopping")
ResqueSpec.perform_next(Newsletter::QUEUE)
ResqueSpec.perform_all(SendOut::QUEUE)
sleep 1
page.should have_content('50%')
page.should have_selector("#{selector}.stopped")
# sleep 100
newsletter.live_send_outs.with_state(:stopped).count.should == 1
expect do
find("#{selector} a.resume").click
page.driver.browser.switch_to.alert.accept
sleep 1
page.should have_selector("#{selector}.pre_sending")
ResqueSpec.perform_next(Newsletter::QUEUE)
sleep 1
page.should have_selector("#{selector}.sending")
ResqueSpec.perform_next(SendOut::QUEUE)
sleep 1
page.should have_content('100%')
page.should have_selector("#{selector}.finished")
end.to change(ActionMailer::Base.deliveries, :size).by(1)
end
end
end
diff --git a/spec/models/newsletter_spec.rb b/spec/models/newsletter_spec.rb
index 267aafd..da13e25 100644
--- a/spec/models/newsletter_spec.rb
+++ b/spec/models/newsletter_spec.rb
@@ -1,347 +1,348 @@
require 'spec_helper'
describe Newsletter do
fixtures :all
let(:newsletter) { newsletters(:biff_newsletter) }
let(:account) { newsletter.account }
describe "#with_account" do
it "should find right newsletter" do
Newsletter.with_account(account).first.should == newsletter
end
end
describe "#new" do
context "created from draft" do
subject { account.newsletters.create(:draft => newsletter) }
%w(subject content).each do |method|
it "copies #{method}" do
subject.send(method).should == newsletter.send(method)
end
end
end
end
describe "#draft" do
let(:new_newsletter) { Newsletter.new(:draft => newsletter) }
it "copies subject" do
new_newsletter.subject.should == newsletter.subject
end
it "copies content" do
new_newsletter.content.should == newsletter.content
end
end
describe "#recipients_count" do
let(:new_newsletter) { account.newsletters.create!(:subject => "Test") }
it "should be set on create" do
new_newsletter.recipients_count.should == new_newsletter.recipients.count
end
end
context "without StateMachine" do
describe "#_send_test!" do
before do
newsletter.update_attribute("state", "pre_testing")
end
it "creates TestSendOuts" do
expect do
newsletter.send("_send_test!")
end.to change(TestSendOut, :count).by(2)
end
it "uniq test" do
expect do
newsletter.send("_send_test!", newsletter.account.test_recipient_emails_array.first)
end.to change(TestSendOut, :count).by(2)
end
it "calls process!" do
newsletter.should_receive(:process!)
newsletter.send("_send_test!")
end
it "calls process!" do
expect do
newsletter.send("_send_test!")
end.to change { newsletter.state }.from("pre_testing").to("testing")
end
it "creates TestSendOuts for extra email" do
newsletter.send("_send_test!", "[email protected]")
newsletter.test_send_outs.map(&:email).should include("[email protected]")
end
end
describe "#_send_live!" do
before do
newsletter.update_attribute("state", "pre_sending")
end
it "creates LiveSendOuts" do
expect do
newsletter.send("_send_live!")
end.to change(LiveSendOut, :count).by(2)
end
it "updates recipient count" do
expect do
newsletter.send("_send_live!")
end.to change { newsletter.recipients_count }.from(0).to(2)
end
it "calls process!" do
newsletter.should_receive(:process!)
newsletter.send("_send_live!")
end
it "calls process!" do
expect do
newsletter.send("_send_live!")
end.to change { newsletter.state }.from("pre_sending").to("sending")
end
end
describe "#_stop!" do
before do
- #newsletter.stub('finish!').and_return(true)
newsletter.update_attribute("state", "pre_sending")
newsletter.send("_send_live!")
end
it "stopps" do
expect do
expect do
newsletter.send("_stop!")
end.to change(LiveSendOut.with_state(:sheduled), :count).by(-2)
end.to change(LiveSendOut.with_state(:stopped), :count).by(2)
end
it "resumes" do
+ newsletter.update_attribute("state", "stopping")
newsletter.send("_stop!")
+ newsletter.update_attribute("state", "pre_sending")
expect do
expect do
newsletter.send("_resume_live!")
end.to change(LiveSendOut.with_state(:sheduled), :count).by(2)
end.to change(LiveSendOut.with_state(:stopped), :count).by(-2)
end
end
end
describe "#send" do
shared_examples_for "sending to recipients" do
let(:klass){ TestSendOut }
- let(:method){ "send_test!" }
+ let(:method){ :send_test }
it "sends mail" do
expect do
with_resque do
- newsletter.send(method)
+ newsletter.fire_state_event(method)
end
end.to change(ActionMailer::Base.deliveries, :size).by(2)
end
it "creates sendouts" do
expect do
with_resque do
- newsletter.send(method)
+ newsletter.fire_state_event(method)
end
end.to change(klass.with_state(:finished), :count).by(2)
end
end
context "test" do
it "should have users" do
newsletter.account.test_recipient_emails_array.count.should == 2
end
it_should_behave_like "sending to recipients"
it "sends mail to custom email" do
expect do
with_resque do
newsletter.send_test!("[email protected]")
end
end.to change(ActionMailer::Base.deliveries, :size).by(3)
end
end
context "live" do
it "should have users" do
newsletter.recipients.count.should == 2
end
it_should_behave_like "sending to recipients" do
let(:klass){ LiveSendOut }
- let(:method){ "send_live!" }
+ let(:method){ :send_live }
end
end
context "state machine" do
it "should not scheduled twice" do
newsletter.send_live!
- lambda do
+ expect do
newsletter.send_live!
- end.should raise_error
+ end.to raise_error
end
end
end
describe "#attachments" do
let(:newsletter) { newsletters(:biff_newsletter) }
before do
newsletter.attachment_ids = [assets(:two), assets(:three)].map(&:id)
newsletter.save!
#@newsletter.reload
end
it "updates attachments :one" do
assets(:one).reload.newsletter_id.should be_nil
end
it "updates attachments :two" do
assets(:two).reload.newsletter_id.should == newsletter.id
end
it "updates attachments :two" do
assets(:three).reload.newsletter_id.should == newsletter.id
end
it "updates attachments" do
newsletter.attachments.size.should == 2
end
it "doesn't assign empty blank ids" do
account.should_not_receive(:assets)
newsletter.update_attributes(:attachment_ids => [""])
end
end
describe "#done?" do
it "" do
#sending", one schedule, one done -> not done
#sending", no scheduled, two done -> done
#newsletter.
#newsletter.should be_done
end
end
describe "#update_stats!" do
context "test newsletter" do
before do
newsletter.update_attribute('state', 'testing')
end
it "calls finish" do
expect do
newsletter.update_stats!
end.to change { newsletter.reload.state }.from('testing').to('tested')
end
end
context "live newsletter" do
before do
newsletter.update_attributes(:state => 'sending')
@send_out_first = newsletter.live_send_outs.create!(:recipient => newsletter.recipients.first)
@send_out_last = newsletter.live_send_outs.create!(:recipient => newsletter.recipients.last)
end
context "sending" do
let(:created_at) { 5.days.ago }
it "updates delivery_started_at" do
@send_out_first.update_attributes(:created_at => created_at)
expect do
newsletter.update_stats!
end.to change { newsletter.delivery_started_at.to_i }.to(created_at.to_i)
end
it "doesn't change state" do
expect do
newsletter.update_stats!
end.to_not change { newsletter.reload.state }.from('sending')
end
end
context "finished" do
let(:finished_at) { 2.days.ago }
before do
newsletter.update_attributes(:state => 'sending')
@send_out_first.update_attributes(:state => 'finished', :finished_at => 3.days.ago)
@send_out_last.update_attributes(:state => 'read', :finished_at => finished_at)
end
it "does not update delivery_started_at" do
newsletter.update_attributes(:delivery_started_at => Time.now)
expect do
newsletter.update_stats!
end.to_not change { newsletter.delivery_started_at }
end
it "finishes newsletter" do
expect do
newsletter.update_stats!
end.to change { newsletter.reload.state }.from('sending').to('finished')
end
it "updates delivery_ended_at" do
expect do
newsletter.update_stats!
end.to change { newsletter.reload.delivery_ended_at.to_i }.to(finished_at.to_i)
end
it "updates errors_count" do
@send_out_last.update_attributes(:state => 'failed', :updated_at => finished_at)
expect do
newsletter.update_stats!
end.to change { newsletter.fails_count }.by(1)
end
it "updates reads_count" do
expect do
newsletter.update_stats!
end.to change { newsletter.reads_count }.by(1)
end
it "updates deliveries_count" do
expect do
newsletter.update_stats!
end.to change { newsletter.deliveries_count }.by(2)
end
end
end
end
end
# == Schema Info
#
# Table name: newsletters
#
# id :integer(4) not null, primary key
# account_id :integer(4)
# last_sent_id :integer(4)
# content :text
# deliveries_count :integer(4) not null, default(0)
# errors_count :integer(4) not null, default(0)
# mode :integer(4) not null, default(0)
# recipients_count :integer(4) not null, default(0)
# state :string(255) default("finished")
# status :integer(4) not null, default(0)
# subject :string(255)
# created_at :datetime
# deliver_at :datetime
# delivery_ended_at :datetime
# delivery_started_at :datetime
# updated_at :datetime
\ No newline at end of file
diff --git a/spec/models/send_out_spec.rb b/spec/models/send_out_spec.rb
index 23fbc29..e00eda0 100644
--- a/spec/models/send_out_spec.rb
+++ b/spec/models/send_out_spec.rb
@@ -1,171 +1,175 @@
require 'spec_helper'
describe SendOut do
fixtures :all
let(:recipient) { newsletter.recipients.first }
let(:newsletter) { newsletters(:biff_newsletter) }
let(:live_send_out) { LiveSendOut.create!(:newsletter => newsletter, :recipient => recipient) }
let(:test_send_out) { TestSendOut.create!(:newsletter => newsletter, :email => "[email protected]") }
context "#create" do
describe LiveSendOut do
it "should set email" do
live_send_out.email.should == recipient.email
end
it "should not allow multiple instances" do
live_send_out
- lambda do
+ expect do
LiveSendOut.create!(:newsletter => newsletter, :recipient => recipient)
- end.should raise_error
+ end.to raise_error
end
end
it "should allow multiple instances of TestSendOut" do
live_send_out
- lambda do
+ expect do
TestSendOut.create!(:newsletter => newsletter, :email => "[email protected]")
- end.should_not raise_error
+ end.to_not raise_error
end
end
context "#async_deliver!" do
before do
ResqueSpec.reset!
end
it "live should be scheduled after create" do
LiveSendOut.should have_queued(live_send_out.id)
TestSendOut.should_not have_queued(live_send_out.id)
end
it "test should be scheduled after create" do
TestSendOut.should have_queued(test_send_out.id)
LiveSendOut.should_not have_queued(test_send_out.id)
end
end
describe "#deliver!" do
before do
ActionMailer::Base.deliveries.clear
end
context "TestSendOut" do
it "should send out test sending" do
expect do
test_send_out.deliver!
end.to change(ActionMailer::Base.deliveries, :size).by(1)
end
it "changes state to finished on success" do
expect do
test_send_out.deliver!
end.not_to change { Recipient.count }
end
end
context "LiveSendOut" do
it "should send out live sending" do
expect do
live_send_out.deliver!
end.to change(ActionMailer::Base.deliveries, :size).by(1)
end
it "changes state to finished on success" do
expect do
live_send_out.deliver!
end.to change { live_send_out.reload.state }.from('sheduled').to('finished')
end
it "set finished_at" do
expect do
live_send_out.deliver!
end.to change { live_send_out.reload.finished_at }.from(nil)
end
it "increases recipients deliveries_count" do
expect do
live_send_out.deliver!
end.to change { recipient.reload.deliveries_count }.by(1)
end
it "should change state to failed on failure" do
- live_send_out.issue.stub(:deliver).and_raise
+ live_send_out.issue.should_receive(:deliver).and_raise
expect do
- live_send_out.deliver!
+ expect do
+ live_send_out.deliver!
+ end.to raise_error
end.to change { live_send_out.reload.state }.from('sheduled').to('failed')
end
it "increases recipients fails_count" do
- live_send_out.issue.stub(:deliver).and_raise
+ live_send_out.issue.should_receive(:deliver).and_raise
expect do
- live_send_out.deliver!
+ expect do
+ live_send_out.deliver!
+ end.to raise_error
end.to change { recipient.reload.fails_count }.by(1)
end
end
end
describe "#read!" do
it "changes from finished to read" do
live_send_out.update_attributes(:state => 'finished')
expect do
live_send_out.read!
end.to change { live_send_out.reload.state }.from('finished').to('read')
end
it "does not change from read to read" do
live_send_out.update_attributes(:state => 'read')
expect do
live_send_out.read!
end.to_not change { live_send_out.reload.state }.from('read')
end
it "increases recipients reads_count" do
live_send_out.update_attributes(:state => 'finished')
expect do
live_send_out.read!
end.to change { recipient.reload.reads_count }.by(1)
end
end
describe "#bounce!" do
it "changes from finished to read" do
live_send_out.update_attributes(:state => 'finished')
expect do
live_send_out.bounce!
end.to change { live_send_out.reload.state }.from('finished').to('bounced')
end
it "does not change from read to read" do
live_send_out.update_attributes(:state => 'bounced')
expect do
live_send_out.bounce!
end.to_not change { live_send_out.reload.state }.from('bounced')
end
it "increases recipients bounces_count" do
live_send_out.update_attributes(:state => 'finished')
expect do
live_send_out.bounce!
end.to change { recipient.reload.bounces_count }.by(1)
end
end
end
# == Schema Info
#
# Table name: send_outs
#
# id :integer(4) not null, primary key
# newsletter_id :integer(4)
# recipient_id :integer(4)
# email :string(255)
# error_message :text
# state :string(255)
# type :string(255)
# created_at :datetime
# finished_at :datetime
# updated_at :datetime
\ No newline at end of file
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.