0.9.3.34: cosmetics
[sbcl.git] / src / code / target-hash-table.lisp
1 ;;;; that part of the implementation of HASH-TABLE which lives solely
2 ;;;; on the target system, not on the cross-compilation host
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!IMPL")
14 \f
15 ;;;; utilities
16
17 (eval-when (:compile-toplevel :load-toplevel :execute)
18   (defconstant max-hash sb!xc:most-positive-fixnum))
19
20 (deftype hash ()
21   `(integer 0 ,max-hash))
22
23 ;;; FIXME: Does this always make a nonnegative FIXNUM? If so, then
24 ;;; explain why. If not (or if the reason it always makes a
25 ;;; nonnegative FIXNUM is only the accident that pointers in supported
26 ;;; architectures happen to be in the lower half of the address
27 ;;; space), then fix it.
28 #!-sb-fluid (declaim (inline pointer-hash))
29 (defun pointer-hash (key)
30   (declare (values hash))
31   (truly-the hash (%primitive sb!c:make-fixnum key)))
32
33 #!-sb-fluid (declaim (inline eq-hash))
34 (defun eq-hash (key)
35   (declare (values hash (member t nil)))
36   (values (pointer-hash key)
37           (oddp (get-lisp-obj-address key))))
38
39 #!-sb-fluid (declaim (inline equal-hash))
40 (defun equal-hash (key)
41   (declare (values hash (member t nil)))
42   (values (sxhash key) nil))
43
44 #!-sb-fluid (declaim (inline eql-hash))
45 (defun eql-hash (key)
46   (declare (values hash (member t nil)))
47   (if (numberp key)
48       (equal-hash key)
49       (eq-hash key)))
50
51 (defun equalp-hash (key)
52   (declare (values hash (member t nil)))
53   (values (psxhash key) nil))
54
55 (defun almost-primify (num)
56   (declare (type index num))
57   #!+sb-doc
58   "Return an almost prime number greater than or equal to NUM."
59   (if (= (rem num 2) 0)
60       (setq num (+ 1 num)))
61   (if (= (rem num 3) 0)
62       (setq num (+ 2 num)))
63   (if (= (rem num 7) 0)
64       (setq num (+ 4 num)))
65   num)
66 \f
67 ;;;; user-defined hash table tests
68
69 (defvar *hash-table-tests* nil)
70
71 (defun define-hash-table-test (name test-fun hash-fun)
72   #!+sb-doc
73   "Define a new kind of hash table test."
74   (declare (type symbol name)
75            (type function test-fun hash-fun))
76   (setf *hash-table-tests*
77         (cons (list name test-fun hash-fun)
78               (remove name *hash-table-tests* :test #'eq :key #'car)))
79   name)
80 \f
81 ;;;; construction and simple accessors
82
83 (defconstant +min-hash-table-size+ 16)
84 (defconstant +min-hash-table-rehash-threshold+ (float 1/16 1.0))
85 ;; as explained by pmai on openprojects #lisp IRC 2002-07-30: #x80000000
86 ;; is bigger than any possible nonEQ hash value, and thus indicates an
87 ;; empty slot; and EQ hash tables don't use HASH-TABLE-HASH-VECTOR
88 (defconstant +magic-hash-vector-value+ #x80000000)
89
90 (defun make-hash-table (&key (test 'eql)
91                              (size +min-hash-table-size+)
92                              (rehash-size 1.5)
93                              (rehash-threshold 1)
94                              (weak-p nil))
95   #!+sb-doc
96   "Create and return a new hash table. The keywords are as follows:
97      :TEST -- Indicates what kind of test to use.
98      :SIZE -- A hint as to how many elements will be put in this hash
99        table.
100      :REHASH-SIZE -- Indicates how to expand the table when it fills up.
101        If an integer, add space for that many elements. If a floating
102        point number (which must be greater than 1.0), multiply the size
103        by that amount.
104      :REHASH-THRESHOLD -- Indicates how dense the table can become before
105        forcing a rehash. Can be any positive number <=1, with density
106        approaching zero as the threshold approaches 0. Density 1 means an
107        average of one entry per bucket.
108      :WEAK-P -- (This is an extension from CMU CL, not currently supported
109        in SBCL 0.6.6, but perhaps supported in a future version.) If T,
110        don't keep entries if the key would otherwise be garbage."
111   (declare (type (or function symbol) test))
112   (declare (type unsigned-byte size))
113   (when weak-p
114     (error "stub: unsupported WEAK-P option"))
115   (multiple-value-bind (test test-fun hash-fun)
116       (cond ((or (eq test #'eq) (eq test 'eq))
117              (values 'eq #'eq #'eq-hash))
118             ((or (eq test #'eql) (eq test 'eql))
119              (values 'eql #'eql #'eql-hash))
120             ((or (eq test #'equal) (eq test 'equal))
121              (values 'equal #'equal #'equal-hash))
122             ((or (eq test #'equalp) (eq test 'equalp))
123              (values 'equalp #'equalp #'equalp-hash))
124             (t
125              ;; FIXME: I'd like to remove *HASH-TABLE-TESTS* stuff.
126              ;; Failing that, I'd like to rename it to
127              ;; *USER-HASH-TABLE-TESTS*.
128              (dolist (info *hash-table-tests*
129                            (error "unknown :TEST for MAKE-HASH-TABLE: ~S"
130                                   test))
131                (destructuring-bind (test-name test-fun hash-fun) info
132                  (when (or (eq test test-name) (eq test test-fun))
133                    (return (values test-name test-fun hash-fun)))))))
134     (let* ((size (max +min-hash-table-size+
135                       (min size
136                            ;; SIZE is just a hint, so if the user asks
137                            ;; for a SIZE which'd be too big for us to
138                            ;; easily implement, we bump it down.
139                            (floor array-dimension-limit 1024))))
140            (rehash-size (if (integerp rehash-size)
141                             rehash-size
142                             (float rehash-size 1.0)))
143            ;; FIXME: Original REHASH-THRESHOLD default should be 1.0,
144            ;; not 1, to make it easier for the compiler to avoid
145            ;; boxing.
146            (rehash-threshold (max +min-hash-table-rehash-threshold+
147                                   (float rehash-threshold 1.0)))
148            (size+1 (1+ size))           ; The first element is not usable.
149            ;; KLUDGE: The most natural way of expressing the below is
150            ;; (round (/ (float size+1) rehash-threshold)), and indeed
151            ;; it was expressed like that until 0.7.0. However,
152            ;; MAKE-HASH-TABLE is called very early in cold-init, and
153            ;; the SPARC has no primitive instructions for rounding,
154            ;; but only for truncating; therefore, we fudge this issue
155            ;; a little. The other uses of truncate, below, similarly
156            ;; used to be round. -- CSR, 2002-10-01
157            ;;
158            ;; Note that this has not yet been audited for
159            ;; correctness. It just seems to work. -- CSR, 2002-11-02
160            (scaled-size (truncate (/ (float size+1) rehash-threshold)))
161            (length (almost-primify (max scaled-size
162                                         (1+ +min-hash-table-size+))))
163            (index-vector (make-array length
164                                      :element-type
165                                      '(unsigned-byte #.sb!vm:n-word-bits)
166                                      :initial-element 0))
167            ;; needs to be the same length as the KV vector
168            ;; (FIXME: really?  why doesn't the code agree?)
169            (next-vector (make-array size+1
170                                     :element-type
171                                     '(unsigned-byte #.sb!vm:n-word-bits)))
172            (kv-vector (make-array (* 2 size+1)
173                                   :initial-element +empty-ht-slot+))
174            (table (%make-hash-table
175                    :test test
176                    :test-fun test-fun
177                    :hash-fun hash-fun
178                    :rehash-size rehash-size
179                    :rehash-threshold rehash-threshold
180                    :rehash-trigger size
181                    :table kv-vector
182                    :weak-p weak-p
183                    :index-vector index-vector
184                    :next-vector next-vector
185                    :hash-vector (unless (eq test 'eq)
186                                   (make-array size+1
187                                               :element-type '(unsigned-byte #.sb!vm:n-word-bits)
188                                               :initial-element +magic-hash-vector-value+)))))
189       (declare (type index size+1 scaled-size length))
190       ;; Set up the free list, all free. These lists are 0 terminated.
191       (do ((i 1 (1+ i)))
192           ((>= i size))
193         (setf (aref next-vector i) (1+ i)))
194       (setf (aref next-vector size) 0)
195       (setf (hash-table-next-free-kv table) 1)
196       (setf (hash-table-needing-rehash table) 0)
197       (setf (aref kv-vector 0) table)
198       table)))
199
200 (defun hash-table-count (hash-table)
201   #!+sb-doc
202   "Return the number of entries in the given HASH-TABLE."
203   (declare (type hash-table hash-table)
204            (values index))
205   (hash-table-number-entries hash-table))
206
207 #!+sb-doc
208 (setf (fdocumentation 'hash-table-rehash-size 'function)
209       "Return the rehash-size HASH-TABLE was created with.")
210
211 #!+sb-doc
212 (setf (fdocumentation 'hash-table-rehash-threshold 'function)
213       "Return the rehash-threshold HASH-TABLE was created with.")
214
215 (defun hash-table-size (hash-table)
216   #!+sb-doc
217   "Return a size that can be used with MAKE-HASH-TABLE to create a hash
218    table that can hold however many entries HASH-TABLE can hold without
219    having to be grown."
220   (hash-table-rehash-trigger hash-table))
221
222 #!+sb-doc
223 (setf (fdocumentation 'hash-table-test 'function)
224       "Return the test HASH-TABLE was created with.")
225
226 #!+sb-doc
227 (setf (fdocumentation 'hash-table-weak-p 'function)
228       "Return T if HASH-TABLE will not keep entries for keys that would
229    otherwise be garbage, and NIL if it will.")
230 \f
231 ;;;; accessing functions
232
233 ;;; Make new vectors for the table, extending the table based on the
234 ;;; rehash-size.
235 (defun rehash (table)
236   (declare (type hash-table table))
237   (let* ((old-kv-vector (hash-table-table table))
238          (old-next-vector (hash-table-next-vector table))
239          (old-hash-vector (hash-table-hash-vector table))
240          (old-size (length old-next-vector))
241          (new-size
242           (let ((rehash-size (hash-table-rehash-size table)))
243             (etypecase rehash-size
244               (fixnum
245                (+ rehash-size old-size))
246               (float
247                (the index (truncate (* rehash-size old-size)))))))
248          (new-kv-vector (make-array (* 2 new-size)
249                                     :initial-element +empty-ht-slot+))
250          (new-next-vector (make-array new-size
251                                       :element-type '(unsigned-byte #.sb!vm:n-word-bits)
252                                       :initial-element 0))
253          (new-hash-vector (when old-hash-vector
254                             (make-array new-size
255                                         :element-type '(unsigned-byte #.sb!vm:n-word-bits)
256                                         :initial-element +magic-hash-vector-value+)))
257          (old-index-vector (hash-table-index-vector table))
258          (new-length (almost-primify
259                       (truncate (/ (float new-size)
260                                 (hash-table-rehash-threshold table)))))
261          (new-index-vector (make-array new-length
262                                        :element-type '(unsigned-byte #.sb!vm:n-word-bits)
263                                        :initial-element 0)))
264     (declare (type index new-size new-length old-size))
265
266     ;; Disable GC tricks on the OLD-KV-VECTOR.
267     (set-header-data old-kv-vector sb!vm:vector-normal-subtype)
268
269     ;; FIXME: here and in several other places in the hash table code,
270     ;; loops like this one are used when FILL or REPLACE would be
271     ;; appropriate.  why are standard CL functions not used?
272     ;; Performance issues?  General laziness?  -- NJF, 2004-03-10
273
274     ;; Copy over the kv-vector. The element positions should not move
275     ;; in case there are active scans.
276     (dotimes (i (* old-size 2))
277       (declare (type index i))
278       (setf (aref new-kv-vector i) (aref old-kv-vector i)))
279
280     ;; Copy over the hash-vector.
281     (when old-hash-vector
282       (dotimes (i old-size)
283         (setf (aref new-hash-vector i) (aref old-hash-vector i))))
284
285     (setf (hash-table-next-free-kv table) 0)
286     (setf (hash-table-needing-rehash table) 0)
287     ;; Rehash all the entries; last to first so that after the pushes
288     ;; the chains are first to last.
289     (do ((i (1- new-size) (1- i)))
290         ((zerop i))
291       (let ((key (aref new-kv-vector (* 2 i)))
292             (value (aref new-kv-vector (1+ (* 2 i)))))
293         (cond ((and (eq key +empty-ht-slot+)
294                     (eq value +empty-ht-slot+))
295                ;; Slot is empty, push it onto the free list.
296                (setf (aref new-next-vector i)
297                      (hash-table-next-free-kv table))
298                (setf (hash-table-next-free-kv table) i))
299               ((and new-hash-vector
300                     (not (= (aref new-hash-vector i) +magic-hash-vector-value+)))
301                ;; Can use the existing hash value (not EQ based)
302                (let* ((hashing (aref new-hash-vector i))
303                       (index (rem hashing new-length))
304                       (next (aref new-index-vector index)))
305                  (declare (type index index)
306                           (type hash hashing))
307                  ;; Push this slot into the next chain.
308                  (setf (aref new-next-vector i) next)
309                  (setf (aref new-index-vector index) i)))
310               (t
311                ;; EQ base hash.
312                ;; Enable GC tricks.
313                (set-header-data new-kv-vector
314                                 sb!vm:vector-valid-hashing-subtype)
315                (let* ((hashing (pointer-hash key))
316                       (index (rem hashing new-length))
317                       (next (aref new-index-vector index)))
318                  (declare (type index index)
319                           (type hash hashing))
320                  ;; Push this slot onto the next chain.
321                  (setf (aref new-next-vector i) next)
322                  (setf (aref new-index-vector index) i))))))
323     (setf (hash-table-table table) new-kv-vector)
324     (setf (hash-table-index-vector table) new-index-vector)
325     (setf (hash-table-next-vector table) new-next-vector)
326     (setf (hash-table-hash-vector table) new-hash-vector)
327     ;; Shrink the old vectors to 0 size to help the conservative GC.
328     (shrink-vector old-kv-vector 0)
329     (shrink-vector old-index-vector 0)
330     (shrink-vector old-next-vector 0)
331     (when old-hash-vector
332       (shrink-vector old-hash-vector 0))
333     (setf (hash-table-rehash-trigger table) new-size))
334   (values))
335
336 ;;; Use the same size as before, re-using the vectors.
337 (defun rehash-without-growing (table)
338   (declare (type hash-table table))
339   (let* ((kv-vector (hash-table-table table))
340          (next-vector (hash-table-next-vector table))
341          (hash-vector (hash-table-hash-vector table))
342          (size (length next-vector))
343          (index-vector (hash-table-index-vector table))
344          (length (length index-vector)))
345     (declare (type index size length))
346
347     ;; Disable GC tricks, they will be re-enabled during the re-hash
348     ;; if necesary.
349     (set-header-data kv-vector sb!vm:vector-normal-subtype)
350
351     ;; Rehash all the entries.
352     (setf (hash-table-next-free-kv table) 0)
353     (setf (hash-table-needing-rehash table) 0)
354     (dotimes (i size)
355       (setf (aref next-vector i) 0))
356     (dotimes (i length)
357       (setf (aref index-vector i) 0))
358     (do ((i (1- size) (1- i)))
359         ((zerop i))
360       (let ((key (aref kv-vector (* 2 i)))
361             (value (aref kv-vector (1+ (* 2 i)))))
362         (cond ((and (eq key +empty-ht-slot+)
363                     (eq value +empty-ht-slot+))
364                ;; Slot is empty, push it onto free list.
365                (setf (aref next-vector i) (hash-table-next-free-kv table))
366                (setf (hash-table-next-free-kv table) i))
367               ((and hash-vector (not (= (aref hash-vector i) +magic-hash-vector-value+)))
368                ;; Can use the existing hash value (not EQ based)
369                (let* ((hashing (aref hash-vector i))
370                       (index (rem hashing length))
371                       (next (aref index-vector index)))
372                  (declare (type index index))
373                  ;; Push this slot into the next chain.
374                  (setf (aref next-vector i) next)
375                  (setf (aref index-vector index) i)))
376               (t
377                ;; EQ base hash.
378                ;; Enable GC tricks.
379                (set-header-data kv-vector sb!vm:vector-valid-hashing-subtype)
380                (let* ((hashing (pointer-hash key))
381                       (index (rem hashing length))
382                       (next (aref index-vector index)))
383                  (declare (type index index)
384                           (type hash hashing))
385                  ;; Push this slot into the next chain.
386                  (setf (aref next-vector i) next)
387                  (setf (aref index-vector index) i)))))))
388   (values))
389
390 (defun flush-needing-rehash (table)
391   (let* ((kv-vector (hash-table-table table))
392          (index-vector (hash-table-index-vector table))
393          (next-vector (hash-table-next-vector table))
394          (length (length index-vector)))
395     (do ((next (hash-table-needing-rehash table)))
396         ((zerop next))
397       (declare (type index next))
398       (let* ((key (aref kv-vector (* 2 next)))
399              (hashing (pointer-hash key))
400              (index (rem hashing length))
401              (temp (aref next-vector next)))
402         (setf (aref next-vector next) (aref index-vector index))
403         (setf (aref index-vector index) next)
404         (setf next temp))))
405   (setf (hash-table-needing-rehash table) 0)
406   (values))
407
408 (defun gethash (key hash-table &optional default)
409   #!+sb-doc
410   "Finds the entry in HASH-TABLE whose key is KEY and returns the associated
411    value and T as multiple values, or returns DEFAULT and NIL if there is no
412    such entry. Entries can be added using SETF."
413   (declare (type hash-table hash-table)
414            (values t (member t nil)))
415   (gethash3 key hash-table default))
416
417 (defun gethash2 (key hash-table)
418   #!+sb-doc
419   "Two argument version of GETHASH"
420   (declare (type hash-table hash-table)
421            (values t (member t nil)))
422   (gethash3 key hash-table nil))
423
424 (defun gethash3 (key hash-table default)
425   #!+sb-doc
426   "Three argument version of GETHASH"
427   (declare (type hash-table hash-table)
428            (values t (member t nil)))
429   (without-gcing
430    (cond ((= (get-header-data (hash-table-table hash-table))
431              sb!vm:vector-must-rehash-subtype)
432           (rehash-without-growing hash-table))
433          ((not (zerop (hash-table-needing-rehash hash-table)))
434           (flush-needing-rehash hash-table)))
435
436    ;; First check the cache.  Use EQ here for speed.
437    (let ((cache (hash-table-cache hash-table))
438          (table (hash-table-table hash-table)))
439
440      (if (and cache (< cache (length table)) (eq (aref table cache) key))
441          (values (aref table (1+ cache)) t)
442
443        ;; Search for key in the hash table.
444        (multiple-value-bind (hashing eq-based)
445            (funcall (hash-table-hash-fun hash-table) key)
446          (declare (type hash hashing))
447          (let* ((index-vector (hash-table-index-vector hash-table))
448                 (length (length index-vector))
449                 (index (rem hashing length))
450                 (next (aref index-vector index))
451                 (next-vector (hash-table-next-vector hash-table))
452                 (hash-vector (hash-table-hash-vector hash-table))
453                 (test-fun (hash-table-test-fun hash-table)))
454            (declare (type index index))
455            ;; Search next-vector chain for a matching key.
456            (if (or eq-based (not hash-vector))
457                (do ((next next (aref next-vector next)))
458                    ((zerop next) (values default nil))
459                  (declare (type index next))
460                  (when (eq key (aref table (* 2 next)))
461                    (setf (hash-table-cache hash-table) (* 2 next))
462                    (return (values (aref table (1+ (* 2 next))) t))))
463              (do ((next next (aref next-vector next)))
464                  ((zerop next) (values default nil))
465                (declare (type index next))
466                (when (and (= hashing (aref hash-vector next))
467                           (funcall test-fun key (aref table (* 2 next))))
468                  ;; Found.
469                  (setf (hash-table-cache hash-table) (* 2 next))
470                  (return (values (aref table (1+ (* 2 next))) t)))))))))))
471
472 ;;; so people can call #'(SETF GETHASH)
473 (defun (setf gethash) (new-value key table &optional default)
474   (declare (ignore default))
475   (%puthash key table new-value))
476
477 (defun %puthash (key hash-table value)
478   (declare (type hash-table hash-table))
479   (aver (hash-table-index-vector hash-table))
480   (without-gcing
481    ;; We need to rehash here so that a current key can be found if it
482    ;; exists. Check that there is room for one more entry. May not be
483    ;; needed if the key is already present.
484    (cond ((zerop (hash-table-next-free-kv hash-table))
485           (rehash hash-table))
486          ((= (get-header-data (hash-table-table hash-table))
487              sb!vm:vector-must-rehash-subtype)
488           (rehash-without-growing hash-table))
489          ((not (zerop (hash-table-needing-rehash hash-table)))
490           (flush-needing-rehash hash-table)))
491
492    (let ((cache (hash-table-cache hash-table))
493          (kv-vector (hash-table-table hash-table)))
494
495      ;; Check the cache
496      (if (and cache (< cache (length kv-vector)) (eq (aref kv-vector cache) key))
497          ;; If cached, just store here
498          (setf (aref kv-vector (1+ cache)) value)
499
500        ;; Search for key in the hash table.
501        (multiple-value-bind (hashing eq-based)
502            (funcall (hash-table-hash-fun hash-table) key)
503          (declare (type hash hashing))
504          (let* ((index-vector (hash-table-index-vector hash-table))
505                 (length (length index-vector))
506                 (index (rem hashing length))
507                 (next (aref index-vector index))
508                 (kv-vector (hash-table-table hash-table))
509                 (next-vector (hash-table-next-vector hash-table))
510                 (hash-vector (hash-table-hash-vector hash-table))
511                 (test-fun (hash-table-test-fun hash-table)))
512            (declare (type index index))
513
514            (cond ((or eq-based (not hash-vector))
515                   (when eq-based
516                     (set-header-data kv-vector sb!vm:vector-valid-hashing-subtype))
517
518                   ;; Search next-vector chain for a matching key.
519                   (do ((next next (aref next-vector next)))
520                       ((zerop next))
521                     (declare (type index next))
522                     (when (eq key (aref kv-vector (* 2 next)))
523                       ;; Found, just replace the value.
524                       (setf (hash-table-cache hash-table) (* 2 next))
525                       (setf (aref kv-vector (1+ (* 2 next))) value)
526                       (return-from %puthash value))))
527                  (t
528                   ;; Search next-vector chain for a matching key.
529                   (do ((next next (aref next-vector next)))
530                       ((zerop next))
531                     (declare (type index next))
532                     (when (and (= hashing (aref hash-vector next))
533                                (funcall test-fun key
534                                         (aref kv-vector (* 2 next))))
535                       ;; Found, just replace the value.
536                       (setf (hash-table-cache hash-table) (* 2 next))
537                       (setf (aref kv-vector (1+ (* 2 next))) value)
538                       (return-from %puthash value)))))
539
540            ;; Pop a KV slot off the free list
541            (let ((free-kv-slot (hash-table-next-free-kv hash-table)))
542              ;; Double-check for overflow.
543              (aver (not (zerop free-kv-slot)))
544              (setf (hash-table-next-free-kv hash-table)
545                    (aref next-vector free-kv-slot))
546              (incf (hash-table-number-entries hash-table))
547
548              (setf (hash-table-cache hash-table) (* 2 free-kv-slot))
549              (setf (aref kv-vector (* 2 free-kv-slot)) key)
550              (setf (aref kv-vector (1+ (* 2 free-kv-slot))) value)
551
552              ;; Setup the hash-vector if necessary.
553              (when hash-vector
554                (if (not eq-based)
555                    (setf (aref hash-vector free-kv-slot) hashing)
556                  (aver (= (aref hash-vector free-kv-slot) +magic-hash-vector-value+))))
557
558              ;; Push this slot into the next chain.
559              (setf (aref next-vector free-kv-slot) next)
560              (setf (aref index-vector index) free-kv-slot)))))))
561   value)
562
563 (defun remhash (key hash-table)
564   #!+sb-doc
565   "Remove the entry in HASH-TABLE associated with KEY. Return T if there
566    was such an entry, or NIL if not."
567   (declare (type hash-table hash-table)
568            (values (member t nil)))
569   (without-gcing
570    ;; We need to rehash here so that a current key can be found if it
571    ;; exists.
572    (cond ((= (get-header-data (hash-table-table hash-table))
573              sb!vm:vector-must-rehash-subtype)
574           (rehash-without-growing hash-table))
575          ((not (zerop (hash-table-needing-rehash hash-table)))
576           (flush-needing-rehash hash-table)))
577
578    ;; For now, just clear the cache
579    (setf (hash-table-cache hash-table) nil)
580
581    ;; Search for key in the hash table.
582    (multiple-value-bind (hashing eq-based)
583        (funcall (hash-table-hash-fun hash-table) key)
584      (declare (type hash hashing))
585      (let* ((index-vector (hash-table-index-vector hash-table))
586             (length (length index-vector))
587             (index (rem hashing length))
588             (next (aref index-vector index))
589             (table (hash-table-table hash-table))
590             (next-vector (hash-table-next-vector hash-table))
591             (hash-vector (hash-table-hash-vector hash-table))
592             (test-fun (hash-table-test-fun hash-table)))
593        (declare (type index index next))
594        (flet ((clear-slot (chain-vector prior-slot-location slot-location)
595                 ;; Mark slot as empty.
596                 (setf (aref table (* 2 slot-location)) +empty-ht-slot+
597                       (aref table (1+ (* 2 slot-location))) +empty-ht-slot+)
598                 ;; Update the prior pointer in the chain to skip this.
599                 (setf (aref chain-vector prior-slot-location)
600                       (aref next-vector slot-location))
601                 ;; Push KV slot onto free chain.
602                 (setf (aref next-vector slot-location)
603                       (hash-table-next-free-kv hash-table))
604                 (setf (hash-table-next-free-kv hash-table) slot-location)
605                 (when hash-vector
606                   (setf (aref hash-vector slot-location) +magic-hash-vector-value+))
607                 (decf (hash-table-number-entries hash-table))
608                 t))
609          (cond ((zerop next)
610                 nil)
611                ((if (or eq-based (not hash-vector))
612                     (eq key (aref table (* 2 next)))
613                     (and (= hashing (aref hash-vector next))
614                          (funcall test-fun key (aref table (* 2 next)))))
615                 (clear-slot index-vector index next))
616                ;; Search next-vector chain for a matching key.
617                ((or eq-based (not hash-vector))
618                 ;; EQ based
619                 (do ((prior next next)
620                      (next (aref next-vector next) (aref next-vector next)))
621                     ((zerop next) nil)
622                   (declare (type index next))
623                   (when (eq key (aref table (* 2 next)))
624                     (return-from remhash (clear-slot next-vector prior next)))))
625                (t
626                 ;; not EQ based
627                 (do ((prior next next)
628                      (next (aref next-vector next) (aref next-vector next)))
629                     ((zerop next) nil)
630                   (declare (type index next))
631                   (when (and (= hashing (aref hash-vector next))
632                              (funcall test-fun key (aref table (* 2 next))))
633                     (return-from remhash (clear-slot next-vector prior next)))))))))))
634
635 (defun clrhash (hash-table)
636   #!+sb-doc
637   "This removes all the entries from HASH-TABLE and returns the hash table
638    itself."
639   (declare (optimize speed))
640   (let* ((kv-vector (hash-table-table hash-table))
641          (next-vector (hash-table-next-vector hash-table))
642          (hash-vector (hash-table-hash-vector hash-table))
643          (size (length next-vector))
644          (index-vector (hash-table-index-vector hash-table)))
645     ;; Disable GC tricks.
646     (set-header-data kv-vector sb!vm:vector-normal-subtype)
647     ;; Mark all slots as empty by setting all keys and values to magic
648     ;; tag.
649     (aver (eq (aref kv-vector 0) hash-table))
650     (fill kv-vector +empty-ht-slot+ :start 2)
651     ;; Set up the free list, all free.
652     (do ((i 1 (1+ i)))
653         ((>= i (1- size)))
654       (setf (aref next-vector i) (1+ i)))
655     (setf (aref next-vector (1- size)) 0)
656     (setf (hash-table-next-free-kv hash-table) 1)
657     (setf (hash-table-needing-rehash hash-table) 0)
658     ;; Clear the index-vector.
659     (fill index-vector 0)
660     ;; Clear the hash-vector.
661     (when hash-vector
662       (fill hash-vector +magic-hash-vector-value+)))
663   (setf (hash-table-cache hash-table) nil)
664   (setf (hash-table-number-entries hash-table) 0)
665   hash-table)
666 \f
667 ;;;; MAPHASH
668
669 ;;; FIXME: This should be made into a compiler transform for two reasons:
670 ;;;   1. It would then be available for compiling the entire system,
671 ;;;      not only parts of the system which are defined after DEFUN MAPHASH.
672 ;;;   2. It could be conditional on compilation policy, so that
673 ;;;      it could be compiled as a full call instead of an inline
674 ;;;      expansion when SPACE>SPEED.
675 (declaim (inline maphash))
676 (defun maphash (function-designator hash-table)
677   #!+sb-doc
678   "For each entry in HASH-TABLE, call the designated two-argument function
679    on the key and value of the entry. Return NIL."
680   (let ((fun (%coerce-callable-to-fun function-designator))
681         (size (length (hash-table-next-vector hash-table))))
682     (declare (type function fun))
683     (do ((i 1 (1+ i)))
684         ((>= i size))
685       (declare (type index i))
686       (let* ((kv-vector (hash-table-table hash-table))
687              (key (aref kv-vector (* 2 i)))
688              (value (aref kv-vector (1+ (* 2 i)))))
689         (unless (and (eq key +empty-ht-slot+)
690                      (eq value +empty-ht-slot+))
691           (funcall fun key value))))))
692 \f
693 ;;;; methods on HASH-TABLE
694
695 ;;; Return a list of keyword args and values to use for MAKE-HASH-TABLE
696 ;;; when reconstructing HASH-TABLE.
697 (defun %hash-table-ctor-args (hash-table)
698   (when (hash-table-weak-p hash-table)
699     ;; FIXME: This might actually work with no trouble, but as of
700     ;; sbcl-0.6.12.10 when this code was written, weak hash tables
701     ;; weren't working yet, so I couldn't test it. When weak hash
702     ;; tables are supported again, this should be fixed.
703     (error "can't dump weak hash tables readably")) ; defensive programming..
704   `(:test             ',(hash-table-test             hash-table)
705     :size             ',(hash-table-size             hash-table)
706     :rehash-size      ',(hash-table-rehash-size      hash-table)
707     :rehash-threshold ',(hash-table-rehash-threshold hash-table)))
708
709 ;;; Return an association list representing the same data as HASH-TABLE.
710 (defun %hash-table-alist (hash-table)
711   (let ((result nil))
712     (maphash (lambda (key value)
713                (push (cons key value) result))
714              hash-table)
715     result))
716
717 ;;; Stuff an association list into HASH-TABLE. Return the hash table,
718 ;;; so that we can use this for the *PRINT-READABLY* case in
719 ;;; PRINT-OBJECT (HASH-TABLE T) without having to worry about LET
720 ;;; forms and readable gensyms and stuff.
721 (defun %stuff-hash-table (hash-table alist)
722   (dolist (x alist)
723     (setf (gethash (car x) hash-table) (cdr x)))
724   hash-table)
725
726 (def!method print-object ((hash-table hash-table) stream)
727   (declare (type stream stream))
728   (cond ((not *print-readably*)
729          (print-unreadable-object (hash-table stream :type t :identity t)
730            (format stream
731                    ":TEST ~S :COUNT ~S"
732                    (hash-table-test hash-table)
733                    (hash-table-count hash-table))))
734         ((not *read-eval*)
735          (error "can't print hash tables readably without *READ-EVAL*"))
736         (t
737          (with-standard-io-syntax
738           (format stream
739                   "#.~W"
740                   `(%stuff-hash-table (make-hash-table ,@(%hash-table-ctor-args
741                                                           hash-table))
742                                      ',(%hash-table-alist hash-table)))))))
743
744 (def!method make-load-form ((hash-table hash-table) &optional environment)
745   (declare (ignore environment))
746   (values `(make-hash-table ,@(%hash-table-ctor-args hash-table))
747           `(%stuff-hash-table ,hash-table ',(%hash-table-alist hash-table))))