From 42850f901dc145bf75c12a0c59045f32b8ee2d14 Mon Sep 17 00:00:00 2001 From: David Strawn Date: Thu, 3 Nov 2022 07:43:39 -0600 Subject: [PATCH] Add Cogen instances for SortedSet and SortedMap This commit also updates the Map and Set instances to proxy to the SortedMap and SortedSet instances as they already required sorting the Map/Set in order to yield a consistent iteration of the underlying structure. --- .../org/scalacheck/CogenSpecification.scala | 7 +++++-- .../src/main/scala/org/scalacheck/Cogen.scala | 16 ++++++++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/core/jvm/src/test/scala/org/scalacheck/CogenSpecification.scala b/core/jvm/src/test/scala/org/scalacheck/CogenSpecification.scala index 000f8b62e..e9d810839 100644 --- a/core/jvm/src/test/scala/org/scalacheck/CogenSpecification.scala +++ b/core/jvm/src/test/scala/org/scalacheck/CogenSpecification.scala @@ -16,9 +16,10 @@ import org.scalacheck.Prop.forAll import org.scalacheck.rng.Seed import ScalaVersionSpecific._ - -import scala.util.Try +import scala.collection.immutable.SortedMap +import scala.collection.immutable.SortedSet import scala.concurrent.duration.{Duration, FiniteDuration} +import scala.util.Try import java.time._ import java.util.UUID @@ -181,4 +182,6 @@ object CogenSpecification extends Properties("Cogen") { include(cogenLaws[ZonedDateTime], "cogenZonedDateTime.") include(cogenLaws[ZoneId], "cogenZoneId.") include(cogenLaws[Period], "cogenPeriod.") + include(cogenLaws[SortedSet[Int]], "cogenSortedSet.") + include(cogenLaws[SortedMap[Int, Int]], "cogenSortedSet.") } diff --git a/core/shared/src/main/scala/org/scalacheck/Cogen.scala b/core/shared/src/main/scala/org/scalacheck/Cogen.scala index 7a31d532e..cad5c0f46 100644 --- a/core/shared/src/main/scala/org/scalacheck/Cogen.scala +++ b/core/shared/src/main/scala/org/scalacheck/Cogen.scala @@ -17,6 +17,8 @@ import scala.concurrent.duration.{Duration, FiniteDuration} import java.math.BigInteger import java.util.UUID import rng.Seed +import scala.collection.immutable.SortedMap +import scala.collection.immutable.SortedSet sealed trait Cogen[T] extends Serializable { @@ -124,10 +126,20 @@ object Cogen extends CogenArities with CogenLowPriority with CogenVersionSpecifi Cogen.it(_.iterator) implicit def cogenSet[A: Cogen: Ordering]: Cogen[Set[A]] = - Cogen.it(_.toVector.sorted.iterator) + Cogen[SortedSet[A]].contramap(value => + value.foldLeft(SortedSet.empty[A])(_ + _) + ) + + implicit def cogenSortedSet[A: Cogen]: Cogen[SortedSet[A]] = + Cogen.it(_.iterator) implicit def cogenMap[K: Cogen: Ordering, V: Cogen]: Cogen[Map[K, V]] = - Cogen.it(_.toVector.sortBy(_._1).iterator) + Cogen[SortedMap[K, V]].contramap(value => + value.foldLeft(SortedMap.empty[K, V])(_ + _) + ) + + implicit def cogenSortedMap[K: Cogen, V: Cogen]: Cogen[SortedMap[K, V]] = + Cogen.it(_.iterator) implicit def cogenFunction0[Z: Cogen]: Cogen[() => Z] = Cogen[Z].contramap(f => f())