scala.collection.IterableLike Scala Examples

The following examples show how to use scala.collection.IterableLike. 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: LawlessTraversals.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// 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 2
Source File: ColLayout.scala    From bonsai   with MIT License 5 votes vote down vote up
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 3
Source File: CollectionUtils.scala    From spark-redis   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 4
Source File: package.scala    From guardrail   with MIT License 5 votes vote down vote up
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 5
Source File: IncrementalMap.scala    From inox   with Apache License 2.0 5 votes vote down vote up
package inox.utils

import scala.collection.mutable.{Map => MMap, Builder}
import scala.collection.generic.Shrinkable
import scala.collection.IterableLike

class IncrementalMap[A, B] private(dflt: Option[B])
  extends IncrementalState
     with Iterable[(A,B)]
     with IterableLike[(A,B), Map[A,B]]
     with Builder[(A,B), IncrementalMap[A, B]]
     with Shrinkable[A]
     with (A => B) {

  def this() = this(None)

  private var stack: List[MMap[A, B]] = List(MMap())

  override def clear(): Unit = {
    stack = List(MMap())
  }

  def reset(): Unit = {
    clear()
  }

  def push(): Unit = {
    val last = MMap[A,B]() ++ stack.head

    val withDefault = dflt match {
      case Some(value) => last.withDefaultValue(value)
      case None => last
    }

    stack ::= withDefault
  }

  def pop(): Unit = {
    stack = stack.tail
  }

  def withDefaultValue[B1 >: B](dflt: B1) = {
    val map = new IncrementalMap[A, B1](Some(dflt))
    map.stack = map.stack.tail
    for (s <- stack) map.stack ::= MMap[A,B1]().withDefaultValue(dflt) ++ s
    map
  }

  def get(k: A) = stack.head.get(k)
  def apply(k: A) = stack.head.apply(k)
  def contains(k: A) = stack.head.contains(k)
  def isDefinedAt(k: A) = stack.head.isDefinedAt(k)
  def getOrElse[B1 >: B](k: A, e: => B1) = stack.head.getOrElse(k, e)
  def values = stack.head.values

  def cached(k: A)(b: => B): B = getOrElse(k, {
    val ev = b
    this += k -> ev
    ev
  })

  def iterator = stack.head.iterator
  def +=(kv: (A, B)) = { stack.head += kv; this }
  def -=(k: A) = { stack.head -= k; this }

  override def seq = stack.head.seq
  override def newBuilder = new scala.collection.mutable.MapBuilder(Map.empty[A,B])
  def result = this
} 
Example 6
Source File: IncrementalSeq.scala    From inox   with Apache License 2.0 5 votes vote down vote up
package inox.utils

import scala.collection.mutable.Builder
import scala.collection.mutable.ArrayBuffer
import scala.collection.{Iterable, IterableLike}

class IncrementalSeq[A] extends IncrementalState
                        with Iterable[A]
                        with IterableLike[A, Seq[A]]
                        with Builder[A, IncrementalSeq[A]] {

  private[this] var stack: List[ArrayBuffer[A]] = List(new ArrayBuffer())

  def clear() : Unit = {
    stack = List(new ArrayBuffer())
  }

  def reset(): Unit = {
    clear()
  }

  def push(): Unit = {
    stack ::= stack.head.clone
  }

  def pop(): Unit = {
    stack = stack.tail
  }

  def iterator = stack.head.toList.iterator
  def +=(e: A) = { stack.head += e; this }
  def -=(e: A) = { stack.head -= e; this }

  override def newBuilder = new scala.collection.mutable.ArrayBuffer()
  def result = this
}