summaryrefslogtreecommitdiff
path: root/sources/scala/tools/nsc/util/HashSet.scala
blob: d74d7e958217f025c5d720a882d340a2e20b99f2 (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
/* NSC -- new scala compiler
 * Copyright 2005 LAMP/EPFL
 * @author  Martin Odersky
 */
// $Id$
package scala.tools.nsc.util;

class HashSet[T <: AnyRef](initialCapacity: int) extends Set[T] {

  private var capacity = initialCapacity;
  private var used = 0;
  private var table = new Array[Object](capacity);

  def size: int = used;

  def findEntry(x: T): T = {
    var h = x.hashCode() % capacity;
    var entry = table(h);
    while (entry != null && entry != x) {
      h = (h + 1) % capacity;
      entry = table(h)
    }
    entry.asInstanceOf[T]
  }

  def addEntry(x: T): unit = {
    if (used >= (capacity >> 2)) growTable;
    used = used + 1;
    var h = x.hashCode() % capacity;
    while (table(h) != null) {
      h = (h + 1) % capacity
    }
    table(h) = x
  }

  def elements = new Iterator[T] {
    private var i = 0;
    def hasNext: boolean = {
      while (i < capacity && table(i) == null) i = i + 1;
      i < capacity
    }
    def next: T =
      if (hasNext) { i = i + 1; table(i - 1).asInstanceOf[T] }
      else null
  }

  private def growTable: unit = {
    val oldtable = table;
    capacity = capacity * 2;
    table = new Array[Object](capacity);
    var i = 0;
    while (i < oldtable.length) {
      val entry = oldtable(i);
      if (entry != null) addEntry(entry.asInstanceOf[T]);
      i = i + 1
    }
  }
}