summaryrefslogtreecommitdiff
path: root/src/scalacheck/org/scalacheck/util/Buildable.scala
blob: 140c541a956ebaf186c7ca09fd9d4c1a28ea351b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*-------------------------------------------------------------------------*\
**  ScalaCheck                                                             **
**  Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved.          **
**  http://www.scalacheck.org                                              **
**                                                                         **
**  This software is released under the terms of the Revised BSD License.  **
**  There is NO WARRANTY. See the file LICENSE for the full text.          **
\*------------------------------------------------------------------------ */

package org.scalacheck.util

import scala.collection._

trait Buildable[T,C[_]] {
  def builder: mutable.Builder[T,C[T]]
  def fromIterable(it: Traversable[T]): C[T] = {
    val b = builder
    b ++= it
    b.result()
  }
}

object Buildable {

  implicit def buildableList[T] = new Buildable[T,List] {
    def builder = new mutable.ListBuffer[T]
  }

  implicit def buildableStream[T] = new Buildable[T,Stream] {
    def builder = (new mutable.ListBuffer[T]).mapResult(_.toStream)
  }

  implicit def buildableArray[T](implicit cm: ClassManifest[T]) =
    new Buildable[T,Array] {
      def builder = mutable.ArrayBuilder.make[T]
    }

  implicit def buildableMutableSet[T] = new Buildable[T,mutable.Set] {
    def builder = new mutable.SetBuilder(mutable.Set.empty[T])
  }

  implicit def buildableImmutableSet[T] = new Buildable[T,immutable.Set] {
    def builder = new mutable.SetBuilder(immutable.Set.empty[T])
  }

  implicit def buildableSet[T] = new Buildable[T,Set] {
    def builder = new mutable.SetBuilder(Set.empty[T])
  }

  import java.util.ArrayList
  implicit def buildableArrayList[T] = new Buildable[T,ArrayList] {
    def builder = new mutable.Builder[T,ArrayList[T]] {
      val al = new ArrayList[T]
      def +=(x: T) = {
        al.add(x)
        this
      }
      def clear() = al.clear()
      def result() = al
    }
  }

}