scala.collection.mutable.Builder Scala Examples

The following examples show how to use scala.collection.mutable.Builder. 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: MultiSet.scala    From scala-collection-contrib   with Apache License 2.0 5 votes vote down vote up
package scala
package collection
package immutable

import scala.collection.mutable.{Builder, ImmutableBuilder}


  def excl(elem: A): MultiSet[A] =
    new MultiSetImpl(elems.updatedWith(elem) {
      case Some(n) => if (n > 1) Some(n - 1) else None
      case None => None
    })

}

object MultiSet extends IterableFactory[MultiSet] {

  def from[A](source: IterableOnce[A]): MultiSet[A] =
    source match {
      case ms: MultiSet[A] => ms
      case _ => (newBuilder[A] ++= source).result()
    }

  def empty[A] = new MultiSetImpl[A](Map.empty)

  def newBuilder[A]: Builder[A, MultiSet[A]] =
    new ImmutableBuilder[A, MultiSet[A]](empty[A]) {
      def addOne(elem: A): this.type = { elems = elems + elem; this }
    }

} 
Example 2
Source File: SortedMultiSet.scala    From scala-collection-contrib   with Apache License 2.0 5 votes vote down vote up
package scala
package collection
package immutable

import scala.collection.mutable.{Builder, ImmutableBuilder}


  def excl(elem: A): SortedMultiSet[A] =
    new SortedMultiSet(elems.updatedWith(elem) {
      case Some(n) => if (n > 1) Some(n - 1) else None
      case None => None
    })
}

object SortedMultiSet extends SortedIterableFactory[SortedMultiSet] {

  def from[A: Ordering](source: IterableOnce[A]): SortedMultiSet[A] =
    source match {
      case sms: SortedMultiSet[A] => sms
      case _ => (newBuilder[A] ++= source).result()
    }

  def empty[A: Ordering]: SortedMultiSet[A] = new SortedMultiSet[A](TreeMap.empty)

  def newBuilder[A: Ordering]: Builder[A, SortedMultiSet[A]] =
    new ImmutableBuilder[A, SortedMultiSet[A]](empty) {
      def addOne(elem: A): this.type = { elems = elems + elem; this }
    }

} 
Example 3
Source File: ValidationError.scala    From circe-json-schema   with Apache License 2.0 5 votes vote down vote up
package io.circe.schema

import cats.data.NonEmptyList
import org.everit.json.schema.ValidationException
import scala.collection.mutable.Builder

sealed abstract class ValidationError(
  val keyword: String,
  val location: String,
  val schemaLocation: Option[String]
) extends Exception {
  final override def fillInStackTrace(): Throwable = this
}

object ValidationError {
  def apply(
    keyword: String,
    message: String,
    location: String,
    schemaLocation: Option[String] = None
  ): ValidationError =
    new ValidationError(keyword, location, schemaLocation) {
      final override def getMessage: String = message
    }

  private[this] def fromEveritOne(e: ValidationException): ValidationError =
    apply(e.getKeyword, e.getMessage, e.getPointerToViolation, Option(e.getSchemaLocation))

  private[this] def fromEveritRecursive(
    e: ValidationException,
    builder: Builder[ValidationError, List[ValidationError]]
  ): Unit = {
    val nested = e.getCausingExceptions
    val iter = nested.iterator

    while (iter.hasNext) {
      builder += fromEveritOne(iter.next)
    }

    val iterRecursive = nested.iterator

    while (iterRecursive.hasNext) {
      fromEveritRecursive(iterRecursive.next, builder)
    }
  }

  private[schema] def fromEverit(e: ValidationException): NonEmptyList[ValidationError] = {
    val builder = List.newBuilder[ValidationError]
    fromEveritRecursive(e, builder)
    NonEmptyList(fromEveritOne(e), builder.result)
  }
} 
Example 4
Source File: Code.scala    From jgo   with GNU General Public License v3.0 5 votes vote down vote up
package jgo.tools.compiler
package interm
package codeseq

import instr._

import scala.collection.LinearSeqOptimized
import scala.collection.immutable._
import scala.collection.generic._
import scala.collection.mutable.Builder

object Code {
  def apply(elems: Instr*) = {
    val cb = new CodeBuilder
    for (elem <- elems)
      cb += elem
    cb.result
  }
}


  
  override def equals(that: Any) = this eq that.asInstanceOf[AnyRef]
  
  override def canEqual(o: Any) = o == CodeNil
} 
Example 5
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
} 
Example 6
Source File: traverse.scala    From neotypes   with MIT License 5 votes vote down vote up
package neotypes
package internal.utils

import scala.collection.compat._
import scala.collection.mutable.Builder

private[neotypes] object traverse {
  final def traverseAs[A, B, C](factory: Factory[B, C])
                               (iter: Iterator[A])
                               (f: A => Either[Throwable, B]): Either[Throwable, C] = {
    @annotation.tailrec
    def loop(acc: Builder[B, C]): Either[Throwable, C] =
      if (iter.hasNext) f(iter.next()) match {
        case Right(value) => loop(acc = acc += value)
        case Left(e)      => Left(e)
      } else {
        Right(acc.result())
      }
    loop(acc = factory.newBuilder)
  }

  final def traverseAsList[A, B](iter: Iterator[A])
                                (f: A => Either[Throwable, B]): Either[Throwable, List[B]] =
    traverseAs(List : Factory[B, List[B]])(iter)(f)

  final def traverseAsSet[A, B](iter: Iterator[A])
                               (f: A => Either[Throwable, B]): Either[Throwable, Set[B]] =
    traverseAs(Set : Factory[B, Set[B]])(iter)(f)

  final def traverseAsVector[A, B](iter: Iterator[A])
                                  (f: A => Either[Throwable, B]): Either[Throwable, Vector[B]] =
    traverseAs(Vector : Factory[B, Vector[B]])(iter)(f)

  final def traverseAsMap[A, K, V](iter: Iterator[A])
                                  (f: A => Either[Throwable, (K, V)]): Either[Throwable, Map[K, V]] =
    traverseAs(Map : Factory[(K, V), Map[K, V]])(iter)(f)
} 
Example 7
Source File: ShellCompleter.scala    From flamy   with Apache License 2.0 5 votes vote down vote up
package com.flaminem.flamy.exec.shell

import java.util

import com.flaminem.flamy.conf.FlamyContext
import com.flaminem.flamy.utils.CliUtils
import com.flaminem.flamy.utils.logging.Logging
import jline.console.completer.Completer

import scala.collection.JavaConversions._
import scala.collection.TraversableLike
import scala.collection.mutable.{Builder, ListBuffer}
import scala.util.control.NonFatal

object ShellCompleter {

  
class ShellCompleter(rootContext: FlamyContext) extends Completer with Logging {

  import ShellCompleter._

  val handler: CandidateListCompletionHandler = new CandidateListCompletionHandler()

  override def complete(buffer: String, cursor: Int, candidates: util.List[CharSequence]): Int = {
    handler.setPrintSpaceAfterFullCompletion(true)
    val args: Seq[String] = CliUtils.split(buffer.substring(0, cursor))
    val lastWord: String = args.lastOption.getOrElse("")
    try {
      val truncatedArgs: Seq[String] = args.dropRight(1)
      val cliArgs = CliArgs(truncatedArgs, lastWord)
      val Candidates(strings, shift) = new OptionCompleter(handler, rootContext).complete(cliArgs)
      candidates.addAll(strings.sorted)
      cursor - cliArgs.lastWord.length + shift
    }
    catch {
      case NonFatal(e) =>
        logger.debug("Exception caught during auto-completion", e)
        cursor - lastWord.length
    }
  }

} 
Example 8
Source File: UniqueList.scala    From flamy   with Apache License 2.0 5 votes vote down vote up
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 9
Source File: NamedCollection.scala    From flamy   with Apache License 2.0 5 votes vote down vote up
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()
    }
  }

}