Skip to content

Commit

Permalink
Preserve order of iterable in viaSeq
Browse files Browse the repository at this point in the history
Add a general property to assert this behaviour.

Fixes #329
  • Loading branch information
swsnr committed May 11, 2020
1 parent 76fcf7f commit 0c93e45
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/main/scala/spray/json/CollectionFormats.scala
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ trait CollectionFormats {
* List => I.
*/
def viaSeq[I <: Iterable[T], T :JsonFormat](f: imm.Seq[T] => I): RootJsonFormat[I] = new RootJsonFormat[I] {
def write(iterable: I) = JsArray(iterable.map(_.toJson).toVector)
def write(iterable: I) = JsArray(iterable.iterator.map(_.toJson).toVector)
def read(value: JsValue) = value match {
case JsArray(elements) => f(elements.map(_.convertTo[T]))
case x => deserializationError("Expected Collection as JsArray, but got " + x)
Expand Down
15 changes: 12 additions & 3 deletions src/test/scala/spray/json/CollectionFormatsSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ package spray.json
import org.specs2.mutable._
import java.util.Arrays

class CollectionFormatsSpec extends Specification with DefaultJsonProtocol {
import org.specs2.ScalaCheck

import scala.collection.immutable.TreeSet

class CollectionFormatsSpec extends Specification with DefaultJsonProtocol with ScalaCheck {

"The listFormat" should {
val list = List(1, 2, 3)
Expand Down Expand Up @@ -78,5 +82,10 @@ class CollectionFormatsSpec extends Specification with DefaultJsonProtocol {
json.convertTo[collection.IndexedSeq[Int]] mustEqual seq
}
}

}

"viaSeq" should {
"maintain order" in prop { s: TreeSet[Long] =>
viaSeq[TreeSet[Long], Long](TreeSet(_: _*)).write(s) must_== s.toList.toJson
}
}
}

0 comments on commit 0c93e45

Please sign in to comment.