scala.collection.generic.CanBuildFrom Scala Examples
The following examples show how to use scala.collection.generic.CanBuildFrom.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: TransmittableIterableCollections.scala From scala-loci with Apache License 2.0 | 5 votes |
package loci package transmitter import scala.collection.TraversableLike import scala.collection.generic.CanBuildFrom import scala.language.higherKinds trait TransmittableGeneralIterableCollections extends TransmittableDummy { this: Transmittable.type => final implicit def traversable[B, I, R, V[T] >: Null <: TraversableLike[T, V[T]]] (implicit transmittable: Transmittable[B, I, R], cbfI: CanBuildFrom[V[B], I, V[I]], cbfR: CanBuildFrom[V[I], R, V[R]]) : DelegatingTransmittable[V[B], V[I], V[R]] { type Delegates = transmittable.Type } = DelegatingTransmittable( provide = (value, context) => if (value == null) null else value map { context delegate _ }, receive = (value, context) => if (value == null) null else value map { context delegate _ }) } trait TransmittableIterableCollections extends TransmittableGeneralCollections { this: Transmittable.type => final implicit def identicalTraversable [T: IdenticallyTransmittable, V[T] <: TraversableLike[T, V[T]]] : IdenticallyTransmittable[V[T]] = IdenticallyTransmittable() }
Example 2
Source File: package.scala From CM-Well with Apache License 2.0 | 5 votes |
package cmwell.util import scala.language.higherKinds import scala.collection.generic.CanBuildFrom import scala.collection.mutable import scala.util.{Success, Try} package object exceptions { def trySequence[A, M[X] <: TraversableOnce[X]]( in: M[Try[A]] )(implicit cbf: CanBuildFrom[M[Try[A]], A, M[A]]): Try[M[A]] = { in.foldLeft(Success(cbf(in)): Try[mutable.Builder[A, M[A]]]) { (tr, ta) => { for { r <- tr a <- ta } yield r += a } } .map(_.result()) } def stackTraceToString(t: Throwable): String = { val w = new java.io.StringWriter() val pw = new java.io.PrintWriter(w) t.printStackTrace(pw) val resp = w.toString w.close() pw.close() resp } }
Example 3
Source File: RandomNumberGenerator.scala From fotm-info with MIT License | 5 votes |
package info.fotm.util import scala.collection.generic.CanBuildFrom trait RandomNumberGenerator { def nextInt(): Int def nextInt(max: Int): Int def nextDouble(): Double def shuffle[T, CC[X] <: TraversableOnce[X]](xs: CC[T])(implicit bf: CanBuildFrom[CC[T], T, CC[T]]): CC[T] } class Rng(rng: scala.util.Random) extends RandomNumberGenerator { def this() = this(new scala.util.Random) override def nextInt(): Int = rng.nextInt() override def nextInt(max: Int): Int = rng.nextInt(max) override def nextDouble(): Double = rng.nextDouble() override def shuffle[T, CC[X] <: TraversableOnce[X]](xs: CC[T])(implicit bf: CanBuildFrom[CC[T], T, CC[T]]): CC[T] = rng.shuffle(xs)(bf) } class NullRng extends RandomNumberGenerator { override def nextInt(): Int = 0 override def nextInt(max: Int): Int = 0 override def nextDouble(): Double = 0 override def shuffle[T, CC[X] <: TraversableOnce[X]](xs: CC[T])(implicit bf: CanBuildFrom[CC[T], T, CC[T]]): CC[T] = xs }
Example 4
Source File: package.scala From diffx with Apache License 2.0 | 5 votes |
package com.softwaremill import acyclic.skipped import scala.annotation.compileTimeOnly import scala.collection.TraversableLike import scala.collection.generic.CanBuildFrom import scala.language.experimental.macros import scala.language.higherKinds import com.softwaremill.diffx.DiffxSupport._ package object diffx extends DiffxSupport { implicit def traversableDiffxFunctor[F[_], A](implicit cbf: CanBuildFrom[F[A], A, F[A]], ev: F[A] => TraversableLike[A, F[A]] ): DiffxFunctor[F, A] = new DiffxFunctor[F, A] {} trait DiffxMapAtFunctor[F[_, _], K, T] { @compileTimeOnly(canOnlyBeUsedInsideIgnore("each")) def each(fa: F[K, T])(f: T => T): F[K, T] = sys.error("") } implicit def mapDiffxFunctor[M[KT, TT] <: Map[KT, TT], K, T](implicit cbf: CanBuildFrom[M[K, T], (K, T), M[K, T]] ): DiffxMapAtFunctor[M, K, T] = new DiffxMapAtFunctor[M, K, T] {} implicit class DiffxEachMap[F[_, _], K, T](t: F[K, T])(implicit f: DiffxMapAtFunctor[F, K, T]) { @compileTimeOnly(canOnlyBeUsedInsideIgnore("each")) def each: T = sys.error("") } }
Example 5
Source File: package.scala From guardrail with MIT License | 5 votes |
package com.twilio.guardrail.generators import cats.data.NonEmptyList import java.util.Locale import java.util.regex.Matcher.quoteReplacement import io.swagger.v3.oas.models.{ Operation, PathItem } import io.swagger.v3.oas.models.media.Schema import io.swagger.v3.oas.models.parameters.Parameter import scala.collection.IterableLike import scala.collection.generic.CanBuildFrom import scala.language.implicitConversions package syntax { class RichNotNullShower[A](value: A) { def showNotNull: String = showNotNullIndented(0) def showNotNullIndented(indent: Int): String = (" " * indent) + value.toString().linesIterator.filterNot(_.contains(": null")).mkString("\n" + (" " * indent)) } class RichCollection[A, Repr](xs: IterableLike[A, Repr]) { def distinctBy[B, That](f: A => B)(implicit cbf: CanBuildFrom[Repr, A, That]): That = { val builder = cbf(xs.repr) val i = xs.iterator var set = Set[B]() while (i.hasNext) { val o = i.next val b = f(o) if (!set(b)) { set += b builder += o } } builder.result } } } package object syntax { val GENERATED_CODE_COMMENT_LINES: List[String] = List( "This file was generated by Guardrail (https://github.com/twilio/guardrail).", "Modifications will be overwritten; instead edit the OpenAPI/Swagger spec file." ) private val SPLIT_DELIMITERS = "[-_\\s\\.]+".r private val BOUNDARY_SPLITTERS = List( "([^A-Z])([A-Z])".r, "([A-Z]+)([A-Z][a-z]+)".r ) implicit class RichString(private val s: String) extends AnyVal { private def splitParts(s: String): List[String] = BOUNDARY_SPLITTERS .foldLeft(SPLIT_DELIMITERS.split(s))( (last, splitter) => last.flatMap(part => splitter.replaceAllIn(part, m => quoteReplacement(m.group(1) + "-" + m.group(2))).split("-")) ) .map(_.toLowerCase(Locale.US)) .toList def toPascalCase: String = splitParts(s).map(_.capitalize).mkString def toCamelCase: String = NonEmptyList .fromList(splitParts(s)) .fold("")( parts => parts.head + parts.tail.map(_.capitalize).mkString ) def toSnakeCase: String = splitParts(s).mkString("_") def toDashedCase: String = splitParts(s).mkString("-") def uncapitalized: String = if (s.nonEmpty) { val inUnPacked = s.toCharArray val lowercaseFirstCharacter = Character.toLowerCase(inUnPacked(0)) new String(lowercaseFirstCharacter +: inUnPacked.tail) } else s } implicit def RichSchema: Schema[_] => RichNotNullShower[Schema[_]] = new RichNotNullShower[Schema[_]](_) implicit def RichOperation: Operation => RichNotNullShower[Operation] = new RichNotNullShower[Operation](_) implicit def RichPathItem: PathItem => RichNotNullShower[PathItem] = new RichNotNullShower[PathItem](_) implicit def RichParameter: Parameter => RichNotNullShower[Parameter] = new RichNotNullShower[Parameter](_) implicit def toRichCollection[A, Repr](xs: IterableLike[A, Repr]): RichCollection[A, Repr] = new RichCollection(xs) }
Example 6
Source File: Sequencing.scala From futiles with Apache License 2.0 | 5 votes |
package markatta.futiles import scala.collection.generic.CanBuildFrom import scala.concurrent.{ExecutionContext, Future} import scala.language.higherKinds import scala.util.Try def sequenceTries[A, M[X] <: TraversableOnce[X]]( fas: M[Future[A]] )( implicit ec: ExecutionContext, cbf: CanBuildFrom[M[Future[A]], Try[A], M[Try[A]]] ): Future[M[Try[A]]] = { val fts = fas.foldLeft(Future.successful(cbf())) { (facc, fa) => for { acc <- facc ta <- Lifting.liftTry(fa) } yield acc += ta } fts.map(_.result()) } }
Example 7
Source File: XCompat.scala From boopickle with Apache License 2.0 | 5 votes |
package boopickle import boopickle.Constants.NullRef import collection.generic.CanBuildFrom import scala.collection.generic.CanBuildFrom import scala.language.higherKinds trait XCompatImplicitPicklers { this: PicklerHelper => implicit def mapPickler[T: P, S: P, V[_, _] <: scala.collection.Map[_, _]]( implicit cbf: CanBuildFrom[Nothing, (T, S), V[T, S]]): P[V[T, S]] = BasicPicklers.MapPickler[T, S, V] implicit def iterablePickler[T: P, V[_] <: Iterable[_]](implicit cbf: CanBuildFrom[Nothing, T, V[T]]): P[V[T]] = BasicPicklers.IterablePickler[T, V] } trait XCompatPicklers { this: PicklerHelper => def MapPickler[T: P, S: P, V[_, _] <: scala.collection.Map[_, _]]( implicit cbf: CanBuildFrom[Nothing, (T, S), V[T, S]]): P[V[T, S]] = new P[V[T, S]] { override def pickle(map: V[T, S])(implicit state: PickleState): Unit = { if (map == null) { state.enc.writeInt(NullRef) } else { // encode length state.enc.writeInt(map.size) // encode contents as a sequence val kPickler = implicitly[P[T]] val vPickler = implicitly[P[S]] map.asInstanceOf[scala.collection.Map[T, S]].foreach { kv => kPickler.pickle(kv._1)(state) vPickler.pickle(kv._2)(state) } } } override def unpickle(implicit state: UnpickleState): V[T, S] = { state.dec.readInt match { case NullRef => null.asInstanceOf[V[T, S]] case 0 => // empty map val res = cbf().result() res case idx if idx < 0 => state.identityFor[V[T, S]](-idx) case len => val b = cbf() b.sizeHint(len) val kPickler = implicitly[P[T]] val vPickler = implicitly[P[S]] var i = 0 while (i < len) { b += kPickler.unpickle(state) -> vPickler.unpickle(state) i += 1 } val res = b.result() res } } } }
Example 8
Source File: RichSeq.scala From swave with Mozilla Public License 2.0 | 5 votes |
package swave.core.util import scala.annotation.tailrec import scala.collection.LinearSeq import scala.collection.generic.CanBuildFrom import swave.core.macros._ final class RichSeq[A](val underlying: Seq[A]) extends AnyVal { def mapFind[B](f: A ⇒ Option[B]): Option[B] = { @tailrec def linearRec(seq: LinearSeq[A]): Option[B] = if (seq.nonEmpty) { val x = f(seq.head) if (x.isEmpty) linearRec(seq.tail) else x } else None @tailrec def indexedRec(ix: Int): Option[B] = if (ix < underlying.length) { val x = f(underlying(ix)) if (x.isEmpty) indexedRec(ix + 1) else x } else None underlying match { case x: LinearSeq[A] ⇒ linearRec(x) case _ ⇒ indexedRec(0) } } def foreachWithIndex(f: (A, Int) ⇒ Unit): Unit = { requireState(underlying.isInstanceOf[IndexedSeq[A]]) @tailrec def rec(ix: Int): Unit = if (ix < underlying.size) { f(underlying(ix), ix) rec(ix + 1) } rec(0) } def mapWithIndex[B, That](f: (A, Int) ⇒ B)(implicit bf: CanBuildFrom[Seq[A], B, That]): That = { requireState(underlying.isInstanceOf[IndexedSeq[A]]) val b = bf(underlying) b.sizeHint(underlying) @tailrec def rec(ix: Int): Unit = if (ix < underlying.size) { b += f(underlying(ix), ix) rec(ix + 1) } rec(0) b.result() } }
Example 9
Source File: TransmittableIterableCollections.scala From scala-loci with Apache License 2.0 | 5 votes |
package loci package transmitter import scala.collection.TraversableLike import scala.collection.generic.CanBuildFrom import scala.language.higherKinds trait TransmittableGeneralIterableCollections extends TransmittableDummy { this: Transmittable.type => final implicit def traversable[B, I, R, V[T] >: Null <: TraversableLike[T, V[T]]] (implicit transmittable: Transmittable[B, I, R], cbfI: CanBuildFrom[V[B], I, V[I]], cbfR: CanBuildFrom[V[I], R, V[R]]) : DelegatingTransmittable[V[B], V[I], V[R]] { type Delegates = transmittable.Type } = DelegatingTransmittable( provide = (value, context) => if (value == null) null else value map { context delegate _ }, receive = (value, context) => if (value == null) null else value map { context delegate _ }) } trait TransmittableIterableCollections extends TransmittableGeneralCollections { this: Transmittable.type => final implicit def identicalTraversable [T: IdenticallyTransmittable, V[T] <: TraversableLike[T, V[T]]] : IdenticallyTransmittable[V[T]] = IdenticallyTransmittable() }
Example 10
Source File: Arbitrary.scala From hail with MIT License | 5 votes |
package is.hail.check import scala.collection.generic.CanBuildFrom import scala.language.higherKinds object Arbitrary { def apply[T](arbitrary: Gen[T]): Arbitrary[T] = new Arbitrary(arbitrary) implicit def arbBoolean: Arbitrary[Boolean] = new Arbitrary( Gen.oneOf(true, false)) implicit def arbByte: Arbitrary[Byte] = new Arbitrary(Gen.oneOfGen(Gen.oneOf(Byte.MinValue, -1, 0, 1, Byte.MaxValue), Gen { p => p.rng.getRandomGenerator.nextInt().toByte })) implicit def arbInt: Arbitrary[Int] = new Arbitrary( Gen.oneOfGen(Gen.oneOf(Int.MinValue, -1, 0, 1, Int.MaxValue), Gen.choose(-100, 100), Gen { p => p.rng.getRandomGenerator.nextInt() })) implicit def arbLong: Arbitrary[Long] = new Arbitrary( Gen.oneOfGen(Gen.oneOf(Long.MinValue, -1L, 0L, 1L, Long.MaxValue), Gen.choose(-100, 100), Gen { p => p.rng.getRandomGenerator.nextLong() })) implicit def arbFloat: Arbitrary[Float] = new Arbitrary( Gen.oneOfGen(Gen.oneOf(Float.MinValue, -1.0f, -Float.MinPositiveValue, 0.0f, Float.MinPositiveValue, 1.0f, Float.MaxValue), Gen.choose(-100.0f, 100.0f), Gen { p => p.rng.nextUniform(Float.MinValue, Float.MaxValue, true).toFloat })) implicit def arbDouble: Arbitrary[Double] = new Arbitrary( Gen.oneOfGen(Gen.oneOf(Double.MinValue, -1.0, -Double.MinPositiveValue, 0.0, Double.MinPositiveValue, 1.0, Double.MaxValue), Gen.choose(-100.0, 100.0), Gen { p => p.rng.nextUniform(Double.MinValue, Double.MaxValue, true) })) implicit def arbString: Arbitrary[String] = new Arbitrary(Gen.frequency((1, Gen.const("")), (10, Gen { (p: Parameters) => val s = p.rng.getRandomGenerator.nextInt(12) val b = new StringBuilder() for (i <- 0 until s) b += Gen.randomOneOf(p.rng, Gen.printableChars) b.result() }))) implicit def arbBuildableOf[C[_], T](implicit a: Arbitrary[T], cbf: CanBuildFrom[Nothing, T, C[T]]): Arbitrary[C[T]] = Arbitrary(Gen.buildableOf(a.arbitrary)) def arbitrary[T](implicit arb: Arbitrary[T]): Gen[T] = arb.arbitrary } class Arbitrary[T](val arbitrary: Gen[T])
Example 11
Source File: IdentityHashMap.scala From sql-differential-privacy with MIT License | 5 votes |
package com.uber.engsec.dp.util import scala.collection.generic.CanBuildFrom import scala.collection.mutable final class IdentityHashMap[A <: AnyRef, B]() extends mutable.HashMap[A, B] with mutable.MapLike[A, B, IdentityHashMap[A, B]] { override protected def elemEquals(key1: A, key2: A): Boolean = key1 eq key2 override protected def elemHashCode(key: A) = System.identityHashCode(key) override def empty: IdentityHashMap[A, B] = IdentityHashMap.empty } object IdentityHashMap { type Coll = IdentityHashMap[_, _] implicit def canBuildFrom[A <: AnyRef, B] = new CanBuildFrom[Coll, (A, B), IdentityHashMap[A, B]] { def apply() = newBuilder[A, B] def apply(from: Coll) = { val builder = newBuilder[A, B] builder.sizeHint(from.size) builder } } def empty[A <: AnyRef, B]: IdentityHashMap[A, B] = new IdentityHashMap[A, B] def newBuilder[A <: AnyRef, B] = new mutable.MapBuilder[A, B, IdentityHashMap[A, B]](empty[A, B]) { override def +=(x: (A, B)): this.type = { elems += x this } override def sizeHint(size: Int): Unit = elems.sizeHint(size) } def apply[A <: AnyRef, B](elems: (A, B)*) = (newBuilder[A, B] ++= elems).result() }
Example 12
Source File: JTraversableSerializer.scala From scio with Apache License 2.0 | 5 votes |
package com.spotify.scio.coders.instances.kryo import com.esotericsoftware.kryo.Kryo import com.esotericsoftware.kryo.io.{Input, InputChunked, Output, OutputChunked} import com.twitter.chill.KSerializer import scala.jdk.CollectionConverters._ import scala.collection.generic.CanBuildFrom import scala.collection.mutable private[coders] class JTraversableSerializer[T, C <: Traversable[T]]( val bufferSize: Int = 64 * 1024 )(implicit cbf: CanBuildFrom[C, T, C]) extends KSerializer[C] { override def write(kser: Kryo, out: Output, obj: C): Unit = { val i = obj.toIterator val chunked = new OutputChunked(out, bufferSize) while (i.hasNext) { chunked.writeBoolean(true) kser.writeClassAndObject(chunked, i.next()) } chunked.writeBoolean(false) chunked.endChunks() chunked.flush() } override def read(kser: Kryo, in: Input, cls: Class[C]): C = { val b = cbf() val chunked = new InputChunked(in, bufferSize) while (chunked.readBoolean()) { b += kser.readClassAndObject(chunked).asInstanceOf[T] } b.result() } } // workaround for Java Iterable/Collection missing proper equality check abstract private[coders] class JWrapperCBF[T] extends CanBuildFrom[Iterable[T], T, Iterable[T]] { override def apply(from: Iterable[T]): mutable.Builder[T, Iterable[T]] = { val b = new JIterableWrapperBuilder from.foreach(b += _) b } override def apply(): mutable.Builder[T, Iterable[T]] = new JIterableWrapperBuilder def asScala(xs: java.util.List[T]): Iterable[T] class JIterableWrapperBuilder extends mutable.Builder[T, Iterable[T]] { private val xs = new java.util.ArrayList[T]() override def +=(elem: T): this.type = { xs.add(elem) this } override def clear(): Unit = xs.clear() override def result(): Iterable[T] = asScala(xs) } } private[coders] class JIterableWrapperCBF[T] extends JWrapperCBF[T] { override def asScala(xs: java.util.List[T]): Iterable[T] = xs.asInstanceOf[java.lang.Iterable[T]].asScala } private[coders] class JCollectionWrapperCBF[T] extends JWrapperCBF[T] { override def asScala(xs: java.util.List[T]): Iterable[T] = xs.asInstanceOf[java.util.Collection[T]].asScala }
Example 13
Source File: ModifyMacroSupport.scala From tapir with Apache License 2.0 | 5 votes |
package sttp.tapir.internal import scala.annotation.compileTimeOnly import scala.collection.TraversableLike import scala.collection.generic.CanBuildFrom trait ModifyMacroSupport extends ModifyMacroFunctorSupport { implicit def traversableModifyFunctor[F[_], A](implicit cbf: CanBuildFrom[F[A], A, F[A]], ev: F[A] => TraversableLike[A, F[A]] ): ModifyFunctor[F, A] = new ModifyFunctor[F, A] {} trait ModifyMapAtFunctor[F[_, _], K, T] { @compileTimeOnly(canOnlyBeUsedInsideModify("each")) def each(fa: F[K, T])(f: T => T): F[K, T] = sys.error("") } implicit def mapModifyFunctor[M[KT, TT] <: Map[KT, TT], K, T](implicit cbf: CanBuildFrom[M[K, T], (K, T), M[K, T]] ): ModifyMapAtFunctor[M, K, T] = new ModifyMapAtFunctor[M, K, T] {} implicit class ModifyEachMap[F[_, _], K, T](t: F[K, T])(implicit f: ModifyMapAtFunctor[F, K, T]) { @compileTimeOnly(canOnlyBeUsedInsideModify("each")) def each: T = sys.error("") } }
Example 14
Source File: UniqueList.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.utils.collection.immutable import scala.collection.generic.{CanBuildFrom, SeqForwarder} import scala.collection.mutable.{Builder, ListBuffer} import scala.collection.{SeqLike, mutable} class UniqueList[T] private ( list: List[T], set: Set[T] ) extends Seq[T] with SeqForwarder[T] with SeqLike[T, UniqueList[T]] { override def newBuilder: Builder[T, UniqueList[T]] = UniqueList.canBuildFrom() override def underlying: Seq[T] = list override def toString(): String = s"UniqueList(${list.mkString(", ")})" } object UniqueList { def newBuilder[T](): Builder[T, UniqueList[T]] = { new Builder[T, UniqueList[T]]() { val listBuffer = new ListBuffer[T]() val setBuffer = new mutable.HashSet[T]() override def +=(elem: T): this.type = { if(setBuffer.contains(elem)){ throw new UnicityViolationException(elem) } else { listBuffer += elem setBuffer += elem } this } override def clear(): Unit = { listBuffer.clear() setBuffer.clear() } override def result(): UniqueList[T] = { new UniqueList(listBuffer.toList, setBuffer.toSet) } } } implicit def canBuildFrom[In, Out]: CanBuildFrom[UniqueList[In], Out, UniqueList[Out]] = { new CanBuildFrom[UniqueList[In], Out, UniqueList[Out]]() { override def apply(from: UniqueList[In]): Builder[Out, UniqueList[Out]] = newBuilder() override def apply(): Builder[Out, UniqueList[Out]] = newBuilder() } } def apply[T](elems: T*): UniqueList[T] = { (newBuilder() ++= elems).result() } def apply[T](elems: Iterable[T]): UniqueList[T] = { (newBuilder() ++= elems).result() } }
Example 15
Source File: NamedCollection.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.utils.collection.mutable import com.flaminem.flamy.utils.Named import scala.collection.generic.CanBuildFrom import scala.collection.mutable.{Builder, ListBuffer} import scala.collection.{TraversableLike, mutable} import scala.language.implicitConversions class NamedCollection[V <: Named] extends IndexedCollection[String, V] with TraversableLike[V, NamedCollection[V]] { override def newBuilder: mutable.Builder[V, NamedCollection[V]] = { new ListBuffer[V] mapResult{x => new NamedCollection(x)} } def this(namedItems: Traversable[V]) = { this this++=namedItems } def getIndexOf(value: V): String = value.getName.toLowerCase } object NamedCollection { def newBuilder[V <: Named](): Builder[V, NamedCollection[V]] = { new Builder[V, NamedCollection[V]]() { val buffer = new NamedCollection[V]() override def +=(elem: V): this.type = { buffer += elem this } override def clear(): Unit = { buffer.clear() } override def result(): NamedCollection[V] = { buffer } } } implicit def canBuildFrom[In <: Named, Out <: Named]: CanBuildFrom[NamedCollection[In], Out, NamedCollection[Out]] = { new CanBuildFrom[NamedCollection[In], Out, NamedCollection[Out]]() { override def apply(from: NamedCollection[In]): Builder[Out, NamedCollection[Out]] = newBuilder() override def apply(): Builder[Out, NamedCollection[Out]] = newBuilder() } } }
Example 16
Source File: TraversableLikeExtension.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.utils.collection import scala.collection.TraversableLike import scala.collection.generic.CanBuildFrom import scala.collection.mutable.ListBuffer import scala.language.higherKinds def splitBy[B](fun: A => B)(implicit bf: CanBuildFrom[T[A], A, T[A]]): Iterable[(B, T[A])] = { if(t.isEmpty){ Nil } else { val buffer = new ListBuffer[(B, T[A])]() var groupBuilder = bf(t) var prevB: Option[B] = None t.foreach{ a => val b = Some(fun(a)) if(prevB != b){ if(prevB.isDefined){ buffer += prevB.get -> groupBuilder.result() } prevB = b groupBuilder = bf(t) } groupBuilder += a } buffer += prevB.get -> groupBuilder.result() buffer.result() } } }
Example 17
Source File: ItemName.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.model.names import com.flaminem.flamy.model.exceptions.FlamyException import org.rogach.scallop.ValueConverter import scala.collection.TraversableLike import scala.collection.generic.CanBuildFrom import scala.language.{higherKinds, implicitConversions} import scala.reflect.runtime.universe._ import scala.util.{Failure, Success, Try} def tryParse(s: String): Try[ItemName] = { Try{ SchemaName.parse(s) .orElse{ TableName.parse(s) } .orElse{ TablePartitionName.parse(s) } .getOrElse { throw new IllegalArgumentException("Wrong item name : " + s) } } } def tryParse(s: String, allowedTypes: Set[Class[_]]): Try[ItemName] = { tryParse(s).flatMap { case item if allowedTypes.contains(item.getClass) => Success(item) case item => Failure( new IllegalArgumentException( s"Item $item is a ${item.getClass.getSimpleName}, " + s"but only the following item types are allowed: ${allowedTypes.map{_.getSimpleName}.mkString("[", ", ", "]")}" ) ) } } implicit def fromStringTraversableLike[T[Z] <: TraversableLike[Z, T[Z]]] (l: T[String])(implicit bf: CanBuildFrom[T[String], ItemName, T[ItemName]]) : T[ItemName] = { l.map{tryParse(_).get} } private def fromArgs(args: Seq[String]): Either[String, Option[List[ItemName]]] = { val tries: Seq[Try[ItemName]] = args.map{tryParse} if(tries.forall{_.isSuccess}){ Right(Some(tries.map{_.get}.toList)) } else { val firstFailureIndex = tries.indexWhere(_.isFailure) Left(s"Could not parse the item name ${args(firstFailureIndex)}") } } implicit val scallopConverterList: ValueConverter[List[ItemName]] = { new ValueConverter[List[ItemName]] { override def parse(s: List[(String, List[String])]): Either[String, Option[List[ItemName]]] = { s match { case l if l.nonEmpty => fromArgs(l.flatMap{_._2}) case Nil => Right(None) } } override val tag: TypeTag[List[ItemName]] = typeTag[List[ItemName]] override val argType = org.rogach.scallop.ArgType.LIST } } }
Example 18
Source File: TableDependencyCollection.scala From flamy with Apache License 2.0 | 5 votes |
package com.flaminem.flamy.parsing.model import com.flaminem.flamy.model.names.TableName import com.flaminem.flamy.utils.collection.mutable.IndexedCollection import scala.collection.generic.CanBuildFrom import scala.collection.mutable.ListBuffer import scala.collection.{TraversableLike, mutable} def copy(): TableDependencyCollection = { val res = new TableDependencyCollection res ++= this res } def getTables: Iterable[TableDependency] = { super.getAllValues } override def getIndexOf(value: TableDependency): TableName = { value.fullName } } object TableDependencyCollection { implicit val canBuildFrom = new CanBuildFrom[TableDependencyCollection, TableDependency, TableDependencyCollection] { override def apply(from: TableDependencyCollection): mutable.Builder[TableDependency, TableDependencyCollection] = { apply() } override def apply(): mutable.Builder[TableDependency, TableDependencyCollection] = { new ListBuffer[TableDependency] mapResult{x => new TableDependencyCollection(x)} } } implicit class TableDependencyCollectionConvertible(s: Seq[TableDependency]) { def toTableDependencyCollection: TableDependencyCollection = { new TableDependencyCollection(s) } } }
Example 19
Source File: sizedbuilder.scala From perf_tester with Apache License 2.0 | 5 votes |
package shapeless class SizedBuilder[CC[_]] { import scala.collection.generic.CanBuildFrom import nat._ import Sized.wrap def apply[T](a:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _1]((cbf() += (a)).result) def apply[T](a:T, b:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _2]((cbf() += (a, b)).result) def apply[T](a:T, b:T, c:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _3]((cbf() += (a, b, c)).result) def apply[T](a:T, b:T, c:T, d:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _4]((cbf() += (a, b, c, d)).result) def apply[T](a:T, b:T, c:T, d:T, e:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _5]((cbf() += (a, b, c, d, e)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _6]((cbf() += (a, b, c, d, e, f)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _7]((cbf() += (a, b, c, d, e, f, g)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _8]((cbf() += (a, b, c, d, e, f, g, h)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T, i:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _9]((cbf() += (a, b, c, d, e, f, g, h, i)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T, i:T, j:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _10]((cbf() += (a, b, c, d, e, f, g, h, i, j)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T, i:T, j:T, k:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _11]((cbf() += (a, b, c, d, e, f, g, h, i, j, k)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T, i:T, j:T, k:T, l:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _12]((cbf() += (a, b, c, d, e, f, g, h, i, j, k, l)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T, i:T, j:T, k:T, l:T, m:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _13]((cbf() += (a, b, c, d, e, f, g, h, i, j, k, l, m)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T, i:T, j:T, k:T, l:T, m:T, n:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _14]((cbf() += (a, b, c, d, e, f, g, h, i, j, k, l, m, n)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T, i:T, j:T, k:T, l:T, m:T, n:T, o:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _15]((cbf() += (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T, i:T, j:T, k:T, l:T, m:T, n:T, o:T, p:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _16]((cbf() += (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T, i:T, j:T, k:T, l:T, m:T, n:T, o:T, p:T, q:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _17]((cbf() += (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T, i:T, j:T, k:T, l:T, m:T, n:T, o:T, p:T, q:T, r:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _18]((cbf() += (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T, i:T, j:T, k:T, l:T, m:T, n:T, o:T, p:T, q:T, r:T, s:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _19]((cbf() += (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T, i:T, j:T, k:T, l:T, m:T, n:T, o:T, p:T, q:T, r:T, s:T, t:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _20]((cbf() += (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T, i:T, j:T, k:T, l:T, m:T, n:T, o:T, p:T, q:T, r:T, s:T, t:T, u:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _21]((cbf() += (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u)).result) def apply[T](a:T, b:T, c:T, d:T, e:T, f:T, g:T, h:T, i:T, j:T, k:T, l:T, m:T, n:T, o:T, p:T, q:T, r:T, s:T, t:T, u:T, v:T) (implicit cbf : CanBuildFrom[Nothing, T, CC[T]], ev : AdditiveCollection[CC[T]]) = wrap[CC[T], _22]((cbf() += (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v)).result) }
Example 20
Source File: InsertDeleteStep.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.http package util import com.daml.http.dbbackend.Queries.DBContract import com.daml.ledger.api.v1.{event => evv1} import scalaz.{Monoid, \/, \/-} import scalaz.syntax.tag._ import scala.collection.generic.CanBuildFrom import scala.runtime.AbstractFunction1 import scala.language.higherKinds private[http] final case class InsertDeleteStep[+D, +C]( inserts: InsertDeleteStep.Inserts[C], deletes: Map[String, D]) { import InsertDeleteStep._ def append[DD >: D, CC >: C: Cid](o: InsertDeleteStep[DD, CC]): InsertDeleteStep[DD, CC] = InsertDeleteStep( appendForgettingDeletes(inserts, o), deletes ++ o.deletes, ) def nonEmpty: Boolean = inserts.nonEmpty || deletes.nonEmpty def leftMap[DD](f: D => DD): InsertDeleteStep[DD, C] = copy(deletes = deletes transform ((_, d) => f(d))) def partitionBimap[LD, DD, LC, CC, LDS](f: D => (LD \/ DD), g: C => (LC \/ CC))( implicit LDS: CanBuildFrom[Map[String, D], LD, LDS], ): (LDS, Inserts[LC], InsertDeleteStep[DD, CC]) = { import Collections._ import scalaz.std.tuple._, scalaz.syntax.traverse._ val (lcs, ins) = inserts partitionMap g val (lds, del) = deletes partitionMap (_ traverse f) (lds, lcs, copy(inserts = ins, deletes = del)) } } private[http] object InsertDeleteStep extends WithLAV1[InsertDeleteStep] { type Inserts[+C] = Vector[C] val Inserts: Vector.type = Vector val Empty: InsertDeleteStep[Nothing, Nothing] = apply(Vector.empty, Map.empty) abstract class Cid[-C] extends (C AbstractFunction1 String) @SuppressWarnings(Array("org.wartremover.warts.Any")) object Cid { implicit val ofDBC: Cid[DBContract[Any, Any, Any, Any]] = _.contractId implicit val ofAC: Cid[domain.ActiveContract[Any]] = _.contractId.unwrap implicit def ofFst[L](implicit L: Cid[L]): Cid[(L, Any)] = la => L(la._1) // ofFst and ofSnd should *not* both be defined, being incoherent together } // we always use the Last semigroup for D implicit def `IDS monoid`[D, C: Cid]: Monoid[InsertDeleteStep[D, C]] = Monoid instance (_ append _, Empty) def appendForgettingDeletes[D, C](leftInserts: Inserts[C], right: InsertDeleteStep[Any, C])( implicit cid: Cid[C], ): Inserts[C] = (if (right.deletes.isEmpty) leftInserts else leftInserts.filter(c => !right.deletes.isDefinedAt(cid(c)))) ++ right.inserts } private[http] trait WithLAV1[F[_, _]] { type LAV1 = F[evv1.ArchivedEvent, evv1.CreatedEvent] }
Example 21
Source File: ContractStreamStep.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.http package util import Collections._ import InsertDeleteStep.{Cid, Inserts} import scalaz.{Semigroup, \/} import scalaz.std.tuple._ import scalaz.syntax.functor._ import scala.collection.generic.CanBuildFrom private[http] sealed abstract class ContractStreamStep[+D, +C] extends Product with Serializable { import ContractStreamStep._ def toInsertDelete: InsertDeleteStep[D, C] = this match { case Acs(inserts) => InsertDeleteStep(inserts, Map.empty) case LiveBegin(_) => InsertDeleteStep.Empty case Txn(step, _) => step } def append[DD >: D, CC >: C: Cid](o: ContractStreamStep[DD, CC]): ContractStreamStep[DD, CC] = (this, o) match { case (Acs(inserts), Acs(oinserts)) => Acs(inserts ++ oinserts) case (Acs(_), LiveBegin(AbsoluteBookmark(off))) => Txn(toInsertDelete, off) case (Acs(_) | Txn(_, _), Txn(ostep, off)) => Txn(toInsertDelete append ostep, off) case (LiveBegin(_), Txn(_, _)) => o // the following cases should never happen in a real stream; we attempt to // provide definitions that make `append` totally associative, anyway case (Acs(_) | LiveBegin(_), LiveBegin(LedgerBegin)) => this case (LiveBegin(LedgerBegin), Acs(_) | LiveBegin(_)) | (LiveBegin(AbsoluteBookmark(_)), LiveBegin(AbsoluteBookmark(_))) => o case (LiveBegin(AbsoluteBookmark(off)), Acs(_)) => Txn(o.toInsertDelete, off) case (Txn(step, off), Acs(_) | LiveBegin(LedgerBegin)) => Txn(step append o.toInsertDelete, off) case (Txn(step, _), LiveBegin(AbsoluteBookmark(off))) => Txn(step, off) } def mapPreservingIds[CC](f: C => CC): ContractStreamStep[D, CC] = mapInserts(_ map f) def partitionBimap[LD, DD, LC, CC, LDS](f: D => (LD \/ DD), g: C => (LC \/ CC))( implicit LDS: CanBuildFrom[Map[String, D], LD, LDS], ): (LDS, Inserts[LC], ContractStreamStep[DD, CC]) = this match { case Acs(inserts) => val (lcs, ins) = inserts partitionMap g (LDS().result(), lcs, Acs(ins)) case lb @ LiveBegin(_) => (LDS().result(), Inserts.empty, lb) case Txn(step, off) => step partitionBimap (f, g) map (Txn(_, off)) } def mapInserts[CC](f: Inserts[C] => Inserts[CC]): ContractStreamStep[D, CC] = this match { case Acs(inserts) => Acs(f(inserts)) case lb @ LiveBegin(_) => lb case Txn(step, off) => Txn(step copy (inserts = f(step.inserts)), off) } def mapDeletes[DD](f: Map[String, D] => Map[String, DD]): ContractStreamStep[DD, C] = this match { case acs @ Acs(_) => acs case lb @ LiveBegin(_) => lb case Txn(step, off) => Txn(step copy (deletes = f(step.deletes)), off) } def nonEmpty: Boolean = this match { case Acs(inserts) => inserts.nonEmpty case LiveBegin(_) => true // unnatural wrt `toInsertDelete`, but what nonEmpty is used for here case Txn(step, _) => step.nonEmpty } def bookmark: Option[BeginBookmark[domain.Offset]] = this match { case Acs(_) => Option.empty case LiveBegin(bookmark) => Some(bookmark) case Txn(_, offset) => Some(AbsoluteBookmark(offset)) } } private[http] object ContractStreamStep extends WithLAV1[ContractStreamStep] { final case class Acs[+C](inserts: Inserts[C]) extends ContractStreamStep[Nothing, C] final case class LiveBegin(offset: BeginBookmark[domain.Offset]) extends ContractStreamStep[Nothing, Nothing] final case class Txn[+D, +C](step: InsertDeleteStep[D, C], offsetAfter: domain.Offset) extends ContractStreamStep[D, C] object Txn extends WithLAV1[Txn] implicit def `CSS semigroup`[D, C: Cid]: Semigroup[ContractStreamStep[D, C]] = Semigroup instance (_ append _) }
Example 22
Source File: package.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.lf import scala.collection.TraversableLike import scala.collection.generic.CanBuildFrom package object transaction { private[transaction] def sequence[A, B, This, That]( seq: TraversableLike[Either[A, B], This], )(implicit cbf: CanBuildFrom[This, B, That]): Either[A, That] = seq collectFirst { case Left(e) => Left(e) } getOrElse { val b = cbf.apply() seq.foreach { case Right(a) => b += a case e @ Left(_) => sys.error(s"impossible $e") } Right(b.result()) } }
Example 23
Source File: LawlessTraversals.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.lf.data import scala.collection.IterableLike import scala.collection.generic.CanBuildFrom import scala.annotation.tailrec private[daml] object LawlessTraversals { implicit final class `Lawless iterable traversal`[A, This](private val seq: IterableLike[A, This]) extends AnyVal { def traverseEitherStrictly[E, B, That](f: A => Either[E, B])( implicit cbf: CanBuildFrom[This, B, That]): Either[E, That] = { val that = cbf(seq.repr) that.sizeHint(seq) val i = seq.iterator @tailrec def lp(): Either[E, That] = if (i.hasNext) f(i.next) match { case Left(b) => Left(b) case Right(c) => that += c lp() } else Right(that.result) lp() } } }
Example 24
Source File: LowPriorityAccessors.scala From scala-json with Apache License 2.0 | 5 votes |
package json.internal import json._ import json.exceptions.{InputTypeException, InputFormatsException, InputFormatException} import scala.collection.generic.CanBuildFrom import scala.reflect.ClassTag case JArray(vals) => var exceptions = List[InputFormatException]() val builder = cbf() for((x, idx) <- vals.iterator.zipWithIndex) { try { val value = x.to[T] builder += value } catch { case e: InputFormatException => exceptions ::= e.prependFieldName(idx.toString) } } if (!exceptions.isEmpty) throw InputFormatsException(exceptions.flatMap(_.getExceptions).toSet) builder.result() case x => throw InputTypeException("", "array", x.getClass.getName, x) } } }
Example 25
Source File: ColLayout.scala From bonsai with MIT License | 5 votes |
package com.stripe.bonsai package layout import java.io.{ DataOutput, DataInput } import scala.collection.IterableLike import scala.collection.generic.{ CanBuildFrom, IsTraversableLike } case class ColLayout[A, Repr <: IterableLike[A, Repr]]( layout: Layout[A], offsetsLayout: Layout[Int] )(implicit cbf: CanBuildFrom[Nothing, A, Repr] ) extends Layout[Repr] { def newBuilder: VecBuilder[Repr] = new DenseBuilder(Vector.newBuilder[Repr], Vec.fromVector) def isSafeToCast(vec: Vec[_]): Boolean = false def write(vec: Vec[Repr], out: DataOutput): Unit = { out.writeByte(ColLayout.OffsetEncoding) val offsetsBldr = offsetsLayout.newBuilder val bldr = layout.newBuilder var offset = 0 vec.foreach { values => offsetsBldr += offset offset += values.size bldr ++= values } offsetsLayout.write(offsetsBldr.result(), out) layout.write(bldr.result(), out) } def read(in: DataInput): Vec[Repr] = in.readByte() match { case ColLayout.OffsetEncoding => val offsets = offsetsLayout.read(in) val values = layout.read(in) ColVec(offsets, values)(cbf) case e => throw new java.io.IOException(s"unsupported encoding for ColLayout: $e") } } object ColLayout { final val OffsetEncoding = 1.toByte }
Example 26
Source File: package.scala From magnolify with Apache License 2.0 | 5 votes |
package magnolify import scala.collection.generic.CanBuildFrom import scala.collection.mutable import scala.language.higherKinds import scala.reflect.ClassTag import scala.util.hashing.MurmurHash3 package object shims { trait Monadic[F[_]] extends mercator.Monadic[F] { def flatMapS[A, B](from: F[A])(fn: A => F[B]): F[B] def mapS[A, B](from: F[A])(fn: A => B): F[B] override def flatMap[A, B](from: F[A])(fn: A => F[B]): F[B] = flatMapS(from)(fn) override def map[A, B](from: F[A])(fn: A => B): F[B] = mapS(from)(fn) } trait FactoryCompat[-A, +C] extends Serializable { def newBuilder: mutable.Builder[A, C] def build(xs: TraversableOnce[A]): C = (newBuilder ++= xs).result() } object FactoryCompat extends LowPriorityFactoryCompat1 { private type FC[A, C] = FactoryCompat[A, C] def apply[A, C](f: () => mutable.Builder[A, C]): FC[A, C] = new FactoryCompat[A, C] { override def newBuilder: mutable.Builder[A, C] = f() } implicit def arrayFC[A: ClassTag] = FactoryCompat(() => Array.newBuilder[A]) // Deprecated in 2.13 // implicit def traversableFC[A] = FactoryCompat(() => Traversable.newBuilder[A]) // List <: Iterable // implicit def iterableFC[A] = FactoryCompat(() => Iterable.newBuilder[A]) // List <: Seq // implicit def seqFC[A] = FactoryCompat(() => Seq.newBuilder[A]) // Vector <: IndexedSeq // implicit def indexedSeqFC[A] = FactoryCompat(() => IndexedSeq.newBuilder[A]) } trait LowPriorityFactoryCompat1 extends LowPriorityFactoryCompat2 { implicit def listFC[A] = FactoryCompat(() => List.newBuilder[A]) } trait LowPriorityFactoryCompat2 { implicit def vectorFC[A] = FactoryCompat(() => Vector.newBuilder[A]) // Deprecated in 2.13 // implicit def streamFC[A] = FactoryCompat(() => Stream.newBuilder[A]) } object SerializableCanBuildFroms { private def cbf[A, C](f: () => mutable.Builder[A, C]): CanBuildFrom[C, A, C] = new CanBuildFrom[C, A, C] with Serializable { override def apply(from: C): mutable.Builder[A, C] = f() override def apply(): mutable.Builder[A, C] = f() } implicit def arrayCBF[A: ClassTag] = cbf(() => Array.newBuilder[A]) implicit def traversableCBF[A] = cbf(() => Traversable.newBuilder[A]) implicit def iterableCBF[A] = cbf(() => Iterable.newBuilder[A]) implicit def seqCBF[A] = cbf(() => Seq.newBuilder[A]) implicit def indexedSeqCBF[A] = cbf(() => IndexedSeq.newBuilder[A]) implicit def listCBF[A] = cbf(() => List.newBuilder[A]) implicit def vectorCBF[A] = cbf(() => Vector.newBuilder[A]) implicit def streamCBF[A] = cbf(() => Stream.newBuilder[A]) } val JavaConverters = scala.collection.JavaConverters object MurmurHash3Compat { def seed(data: Int): Int = MurmurHash3.productSeed } }
Example 27
Source File: CollectionUtils.scala From spark-redis with BSD 3-Clause "New" or "Revised" License | 5 votes |
package com.redislabs.provider.redis.util import scala.collection.IterableLike import scala.collection.generic.CanBuildFrom object CollectionUtils { implicit class RichCollection[A, Repr](val xs: IterableLike[A, Repr]) extends AnyVal { def distinctBy[B, That](f: A => B)(implicit cbf: CanBuildFrom[Repr, A, That]): That = { val builder = cbf(xs.repr) val iterator = xs.iterator var set = Set[B]() while (iterator.hasNext) { val element = iterator.next val distinctField = f(element) if (!set(distinctField)) { set += distinctField builder += element } } builder.result } } }
Example 28
Source File: CustomScoptReaders.scala From daml with Apache License 2.0 | 5 votes |
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package com.daml.extractor.config import com.daml.lf.data.Ref.Party import scalaz.OneAnd import scopt.Read import scopt.Read.reads import scala.language.higherKinds import scala.collection.breakOut import scala.collection.generic.CanBuildFrom private[extractor] object CustomScoptReaders { implicit val partyRead: Read[Party] = reads { s => Party fromString s fold (e => throw new IllegalArgumentException(e), identity) } implicit val templateConfigRead: Read[TemplateConfig] = reads { s => s.split(':') match { case Array(moduleName, entityName) => TemplateConfig(moduleName, entityName) case _ => throw new IllegalArgumentException( s"Expected TemplateConfig string: '<moduleName>:<entityName>', got: '$s'") } } implicit def nonEmptySeqRead[F[_], A]( implicit ev: Read[A], target: CanBuildFrom[Nothing, A, F[A]]): Read[OneAnd[F, A]] = reads { s => val Array(hd, tl @ _*) = s split Read.sep OneAnd(ev reads hd, tl.map(ev.reads)(breakOut)) } }
Example 29
Source File: mercator.scala From mercator with Apache License 2.0 | 5 votes |
package mercator import scala.language.higherKinds import scala.reflect.macros._ import scala.collection.generic.CanBuildFrom import language.experimental.macros import language.reflectiveCalls object `package` { implicit def monadic[F[_]]: Monadic[F] = macro Mercator.instantiate.monadic[F[Nothing]] final implicit class Ops[M[_], A](val value: M[A]) extends AnyVal { @inline def flatMap[B](fn: A => M[B])(implicit monadic: Monadic[M]): M[B] = monadic.flatMap[A, B](value)(fn) @inline def map[B](fn: A => B)(implicit functor: Functor[M]): M[B] = functor.map[A, B](value)(fn) @inline def filter(fn: A => Boolean)(implicit filterable: Filterable[M]): M[A] = filterable.filter[A](value)(fn) } implicit def functor[F[_]]: Functor[F] = macro Mercator.instantiate.functor[F[Nothing]] implicit def filterable[F[_]]: Filterable[F] = macro Mercator.instantiate.filterable[F[Nothing]] } object Mercator { object instantiate { def functor[F: c.WeakTypeTag](c: whitebox.Context): c.Tree = common(c).functor def monadic[F: c.WeakTypeTag](c: whitebox.Context): c.Tree = common(c).monadic def filterable[F: c.WeakTypeTag](c: whitebox.Context): c.Tree = common(c).filterable } def common[F: c.WeakTypeTag](c: whitebox.Context) = new { import c.universe._ private val typeConstructor = weakTypeOf[F].typeConstructor private val mockType = appliedType(typeConstructor, typeOf[Mercator.type]) private val companion = typeConstructor.dealias.typeSymbol.companion private val returnType = scala.util.Try(c.typecheck(q"$companion.apply(_root_.mercator.Mercator)").tpe) private def pointAp = if(returnType.map(_ <:< mockType).getOrElse(false)) q"${companion.asModule}(value)" else { val subtypes = typeConstructor.typeSymbol.asClass.knownDirectSubclasses.filter { sub => c.typecheck(q"${sub.companion}.apply(_root_.mercator.Mercator)").tpe <:< mockType }.map { sub => q"${sub.companion}.apply(value)" } if(subtypes.size == 1) subtypes.head else c.abort(c.enclosingPosition, s"mercator: unable to derive Monadic instance for type constructor $typeConstructor") } def monadic: c.Tree = q""" new _root_.mercator.Monadic[$typeConstructor] { def point[A](value: A): Apply[A] = ${pointAp} def map[A, B](from: Apply[A])(fn: A => B): Apply[B] = from.map(fn) def flatMap[A, B](from: Apply[A])(fn: A => Apply[B]): Apply[B] = from.flatMap(fn) } """ def functor: c.Tree = q""" new _root_.mercator.Functor[$typeConstructor] { def point[A](value: A): Apply[A] = ${pointAp} def map[A, B](from: Apply[A])(fn: A => B): Apply[B] = from.map(fn) } """ def filterable: c.Tree = q""" new _root_.mercator.Filterable[$typeConstructor] { def filter[A](value: Apply[A])(fn: A => Boolean): Apply[A] = value.filter(fn) } """ } } trait Functor[F[_]] { type Apply[X] = F[X] def point[A](value: A): F[A] def map[A, B](from: F[A])(fn: A => B): F[B] } trait Monadic[F[_]] extends Functor[F] { def flatMap[A, B](from: F[A])(fn: A => F[B]): F[B] } trait Filterable[F[_]] { type Apply[X] = F[X] def filter[A](value: F[A])(fn: A => Boolean): F[A] }
Example 30
Source File: compat.scala From mercator with Apache License 2.0 | 5 votes |
package mercator import scala.collection.generic.CanBuildFrom import language.higherKinds final class CollOps[M[_], Coll[T] <: Traversable[T], A](val value: Coll[M[A]]) extends AnyVal { @inline def sequence(implicit monadic: Monadic[M], cbf: CanBuildFrom[Nothing, A, Coll[A]]): M[Coll[A]] = value.foldLeft(monadic.point(List[A]()): M[List[A]]) { (acc, next) => acc.flatMap { xs => next.map(_ :: xs) } }.map { xs => xs.reverseIterator.to[Coll] } } final class TraversableOps[Coll[T] <: Traversable[T], A](val value: Coll[A]) extends AnyVal { @inline def traverse[B, M[_]](fn: A => M[B])(implicit monadic: Monadic[M], cbf: CanBuildFrom[Nothing, B, Coll[B]]): M[Coll[B]] = value.foldLeft(monadic.point(List[B]())) { (acc, next) => acc.flatMap { xs => fn(next).map(_ :: xs) } }.map { xs => xs.reverseIterator.to[Coll] } }
Example 31
Source File: CompatImpl.scala From scala-library-compat with Apache License 2.0 | 5 votes |
package scala.collection.compat import scala.reflect.ClassTag import scala.collection.generic.CanBuildFrom import scala.collection.{immutable => i, mutable => m} private final class IdentityPreservingBuilder[A, CC[X] <: TraversableOnce[X]]( that: m.Builder[A, CC[A]])(implicit ct: ClassTag[CC[A]]) extends m.Builder[A, CC[A]] { //invariant: ruined => (collection == null) var collection: CC[A] = null.asInstanceOf[CC[A]] var ruined = false private[this] def ruin(): Unit = { if (collection != null) that ++= collection collection = null.asInstanceOf[CC[A]] ruined = true } override def ++=(elems: TraversableOnce[A]): this.type = elems match { case ct(ca) if collection == null && !ruined => { collection = ca this } case _ => { ruin() that ++= elems this } } def +=(elem: A): this.type = { ruin() that += elem this } def clear(): Unit = { collection = null.asInstanceOf[CC[A]] if (ruined) that.clear() ruined = false } def result(): CC[A] = if (collection == null) that.result() else collection } private[compat] object CompatImpl { def simpleCBF[A, C](f: => m.Builder[A, C]): CanBuildFrom[Any, A, C] = new CanBuildFrom[Any, A, C] { def apply(from: Any): m.Builder[A, C] = apply() def apply(): m.Builder[A, C] = f } type ImmutableBitSetCC[X] = ({ type L[_] = i.BitSet })#L[X] type MutableBitSetCC[X] = ({ type L[_] = m.BitSet })#L[X] }
Example 32
Source File: BuildFrom.scala From scala-library-compat with Apache License 2.0 | 5 votes |
package scala.collection.compat import scala.collection.generic.CanBuildFrom import scala.collection.mutable def newBuilder(from: From): mutable.Builder[A, C] @deprecated("Use newBuilder() instead of apply()", "2.13.0") @`inline` def apply(from: From): mutable.Builder[A, C] = newBuilder(from) } object BuildFrom { // Implicit instance derived from an implicit CanBuildFrom instance implicit def fromCanBuildFrom[From, A, C]( implicit cbf: CanBuildFrom[From, A, C]): BuildFrom[From, A, C] = new BuildFrom[From, A, C] { def fromSpecific(from: From)(it: IterableOnce[A]): C = (cbf(from) ++= it).result() def newBuilder(from: From): mutable.Builder[A, C] = cbf(from) } // Implicit conversion derived from an implicit conversion to CanBuildFrom implicit def fromCanBuildFromConversion[X, From, A, C](x: X)( implicit toCanBuildFrom: X => CanBuildFrom[From, A, C]): BuildFrom[From, A, C] = fromCanBuildFrom(toCanBuildFrom(x)) }
Example 33
Source File: package.scala From scala-library-compat with Apache License 2.0 | 5 votes |
package scala.collection import scala.collection.generic.{CanBuildFrom, GenericOrderedCompanion, IsTraversableLike} import scala.{collection => c} import scala.collection.{mutable => m} import scala.runtime.Tuple2Zipped import scala.collection.{immutable => i, mutable => m} package object compat extends compat.PackageShared { implicit class MutableTreeMapExtensions2(private val fact: m.TreeMap.type) extends AnyVal { def from[K: Ordering, V](source: TraversableOnce[(K, V)]): m.TreeMap[K, V] = build(m.TreeMap.newBuilder[K, V], source) } implicit class MutableSortedMapExtensions(private val fact: m.SortedMap.type) extends AnyVal { def from[K: Ordering, V](source: TraversableOnce[(K, V)]): m.SortedMap[K, V] = build(m.SortedMap.newBuilder[K, V], source) } implicit def genericOrderedCompanionToCBF[A, CC[X] <: Traversable[X]]( fact: GenericOrderedCompanion[CC])( implicit ordering: Ordering[A]): CanBuildFrom[Any, A, CC[A]] = CompatImpl.simpleCBF(fact.newBuilder[A]) // CanBuildFrom instances for `IterableView[(K, V), Map[K, V]]` that preserve // the strict type of the view to be `Map` instead of `Iterable` // Instances produced by this method are used to chain `filterKeys` after `mapValues` implicit def canBuildFromIterableViewMapLike[K, V, L, W, CC[X, Y] <: Map[X, Y]] : CanBuildFrom[IterableView[(K, V), CC[K, V]], (L, W), IterableView[(L, W), CC[L, W]]] = new CanBuildFrom[IterableView[(K, V), CC[K, V]], (L, W), IterableView[(L, W), CC[L, W]]] { // `CanBuildFrom` parameters are used as type constraints, they are not used // at run-time, hence the dummy builder implementations def apply(from: IterableView[(K, V), CC[K, V]]) = new TraversableView.NoBuilder def apply() = new TraversableView.NoBuilder } implicit def toTraversableLikeExtensionMethods[Repr](self: Repr)( implicit traversable: IsTraversableLike[Repr]) : TraversableLikeExtensionMethods[traversable.A, Repr] = new TraversableLikeExtensionMethods[traversable.A, Repr](traversable.conversion(self)) implicit def toSeqExtensionMethods[A](self: c.Seq[A]): SeqExtensionMethods[A] = new SeqExtensionMethods[A](self) implicit def toTrulyTraversableLikeExtensionMethods[T1, El1, Repr1](self: T1)( implicit w1: T1 => TraversableLike[El1, Repr1] ): TrulyTraversableLikeExtensionMethods[El1, Repr1] = new TrulyTraversableLikeExtensionMethods[El1, Repr1](w1(self)) implicit def toTuple2ZippedExtensionMethods[El1, Repr1, El2, Repr2]( self: Tuple2Zipped[El1, Repr1, El2, Repr2]) : Tuple2ZippedExtensionMethods[El1, Repr1, El2, Repr2] = new Tuple2ZippedExtensionMethods[El1, Repr1, El2, Repr2](self) implicit def toImmutableQueueExtensionMethods[A]( self: i.Queue[A]): ImmutableQueueExtensionMethods[A] = new ImmutableQueueExtensionMethods[A](self) }
Example 34
Source File: package.scala From scala-library-compat with Apache License 2.0 | 5 votes |
package scala.collection import scala.collection.generic.{CanBuildFrom, GenericOrderedCompanion, IsTraversableLike} import scala.runtime.Tuple2Zipped import scala.collection.{immutable => i} import scala.{collection => c} package object compat extends compat.PackageShared { implicit def genericOrderedCompanionToCBF[A, CC[X] <: Traversable[X]]( fact: GenericOrderedCompanion[CC])( implicit ordering: Ordering[A]): CanBuildFrom[Any, A, CC[A]] = CompatImpl.simpleCBF(fact.newBuilder[A]) // CanBuildFrom instances for `IterableView[(K, V), Map[K, V]]` that preserve // the strict type of the view to be `Map` instead of `Iterable` // Instances produced by this method are used to chain `filterKeys` after `mapValues` implicit def canBuildFromIterableViewMapLike[K, V, L, W, CC[X, Y] <: Map[X, Y]] : CanBuildFrom[IterableView[(K, V), CC[K, V]], (L, W), IterableView[(L, W), CC[L, W]]] = new CanBuildFrom[IterableView[(K, V), CC[K, V]], (L, W), IterableView[(L, W), CC[L, W]]] { // `CanBuildFrom` parameters are used as type constraints, they are not used // at run-time, hence the dummy builder implementations def apply(from: IterableView[(K, V), CC[K, V]]) = new TraversableView.NoBuilder def apply() = new TraversableView.NoBuilder } implicit def toTraversableLikeExtensionMethods[Repr](self: Repr)( implicit traversable: IsTraversableLike[Repr]) : TraversableLikeExtensionMethods[traversable.A, Repr] = new TraversableLikeExtensionMethods[traversable.A, Repr](traversable.conversion(self)) implicit def toSeqExtensionMethods[A](self: c.Seq[A]): SeqExtensionMethods[A] = new SeqExtensionMethods[A](self) implicit def toTrulyTraversableLikeExtensionMethods[T1, El1, Repr1](self: T1)( implicit w1: T1 => TraversableLike[El1, Repr1] ): TrulyTraversableLikeExtensionMethods[El1, Repr1] = new TrulyTraversableLikeExtensionMethods[El1, Repr1](w1(self)) implicit def toTuple2ZippedExtensionMethods[El1, Repr1, El2, Repr2]( self: Tuple2Zipped[El1, Repr1, El2, Repr2] ): Tuple2ZippedExtensionMethods[El1, Repr1, El2, Repr2] = new Tuple2ZippedExtensionMethods[El1, Repr1, El2, Repr2](self) implicit def toImmutableQueueExtensionMethods[A]( self: i.Queue[A]): ImmutableQueueExtensionMethods[A] = new ImmutableQueueExtensionMethods[A](self) }
Example 35
Source File: PubSubRequests.scala From scredis with Apache License 2.0 | 5 votes |
package scredis.protocol.requests import scredis.protocol._ import scredis.serialization.Writer import scala.collection.generic.CanBuildFrom import scala.language.higherKinds object PubSubRequests { import scredis.serialization.Implicits.{intReader, stringReader} object PSubscribe extends Command("PSUBSCRIBE") object Publish extends Command("PUBLISH") with WriteCommand object PubSubChannels extends Command("PUBSUB", "CHANNELS") object PubSubNumSub extends Command("PUBSUB", "NUMSUB") object PubSubNumPat extends ZeroArgCommand("PUBSUB", "NUMPAT") object PUnsubscribe extends Command("PUNSUBSCRIBE") object Subscribe extends Command("SUBSCRIBE") object Unsubscribe extends Command("UNSUBSCRIBE") case class PSubscribe(patterns: String*) extends Request[Int]( PSubscribe, patterns: _* ) { override def decode = ??? } case class Publish[W: Writer](channel: String, message: W) extends Request[Long]( Publish, channel, implicitly[Writer[W]].write(message) ) { override def decode = { case IntegerResponse(value) => value } } case class PubSubChannels(patternOpt: Option[String]) extends Request[List[String]](PubSubChannels, patternOpt.toSeq: _*) { override def decode = { case a: ArrayResponse => a.parsed[String, List] { case b: BulkStringResponse => b.flattened[String] } } } case class PubSubNumSub(channels: String*) extends Request[Map[String, Long]](PubSubNumSub, channels: _*) { override def decode = { case a: ArrayResponse => a.parsedAsPairsMap[String, Long, Map] { case b: BulkStringResponse => b.flattened[String] } { case IntegerResponse(value) => value } } } case class PubSubNumPat() extends Request[Long](PubSubNumPat) { override def decode = { case IntegerResponse(value) => value } } case class PUnsubscribe(patterns: String*) extends Request[Int]( PUnsubscribe, patterns: _* ) { override def decode = ??? } case class Subscribe(channels: String*) extends Request[Int]( Subscribe, channels: _* ) { override def decode = ??? } case class Unsubscribe(channels: String*) extends Request[Int]( Unsubscribe, channels: _* ) { override def decode = ??? } }
Example 36
Source File: CollectionBuilder.scala From tethys with Apache License 2.0 | 5 votes |
package tethys.compat import scala.collection.generic.CanBuildFrom import scala.collection.mutable import scala.language.higherKinds trait CollectionBuilder[A, C] { def newBuilder: mutable.Builder[A, C] } object CollectionBuilder { implicit def seqCBFBuilder[A, C[_]](implicit cbf: CanBuildFrom[Nothing, A, C[A]]): CollectionBuilder[A, C[A]] = new CollectionBuilder[A, C[A]] { override def newBuilder: mutable.Builder[A, C[A]] = cbf() } implicit def mapCBFBuilder[K, V, M[_, _]](implicit cbf: CanBuildFrom[Nothing, (K, V), M[K, V]]): CollectionBuilder[(K, V), M[K, V]] = new CollectionBuilder[(K, V), M[K, V]] { override def newBuilder: mutable.Builder[(K, V), M[K, V]] = cbf() } }