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