1 // $G $F.go && $L $F.$A && ./$A.out
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
9 // ----------------------------------------------------------------------------
19 // ----------------------------------------------------------------------------
20 // Implementation of the HashMap
22 type KeyType interface {
24 Match(other KeyType) bool
28 type ValueType interface {
39 type Array [1024]Entry
48 func (m *HashMap) capacity() uint32 {
49 return 1 << m.log2_capacity_
53 func (m *HashMap) Clear() {
54 // Mark all entries as empty.
55 var i uint32 = m.capacity() - 1
64 func (m *HashMap) Initialize (initial_log2_capacity uint32) {
65 m.log2_capacity_ = initial_log2_capacity
71 func (m *HashMap) Probe (key KeyType) *Entry {
74 var i uint32 = key.Hash() % m.capacity()
75 ASSERT(0 <= i && i < m.capacity())
77 ASSERT(m.occupancy_ < m.capacity()) // guarantees loop termination
78 for m.map_[i].key != nil && !m.map_[i].key.Match(key) {
80 if i >= m.capacity() {
89 func (m *HashMap) Lookup (key KeyType, insert bool) *Entry {
90 // Find a matching entry.
91 var p *Entry = m.Probe(key)
96 // No entry found; insert one if necessary.
102 // Grow the map if we reached >= 80% occupancy.
103 if m.occupancy_ + m.occupancy_/4 >= m.capacity() {
111 // No entry found and none inserted.
116 func (m *HashMap) Resize() {
117 var hmap *Array = m.map_
118 var n uint32 = m.occupancy_
120 // Allocate a new map of twice the current size.
121 m.Initialize(m.log2_capacity_ << 1)
123 // Rehash all current entries.
126 if hmap[i].key != nil {
127 m.Lookup(hmap[i].key, true).value = hmap[i].value
135 // ----------------------------------------------------------------------------
143 func (n *Number) Hash() uint32 {
148 func (n *Number) Match(other KeyType) bool {
149 // var y *Number = other
155 func MakeNumber (x uint32) *Number {
156 var n *Number = new(Number)
163 // func (n int) int { return n + 1; }(1)
165 //print "HashMap - gri 2/8/2008\n"
167 var hmap *HashMap = new(HashMap)
170 var x1 *Number = MakeNumber(1001)
171 var x2 *Number = MakeNumber(2002)
172 var x3 *Number = MakeNumber(3003)
175 // this doesn't work I think...
176 //hmap.Lookup(x1, true)
177 //hmap.Lookup(x2, true)
178 //hmap.Lookup(x3, true)