4b3da969b7f11a055383829029a3f93e6d827230
[sbcl.git] / src / code / hash-table.lisp
1 ;;;; the needed-on-the-cross-compilation-host part of HASH-TABLE
2 ;;;; implementation
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
15 ;;; HASH-TABLE is implemented as a STRUCTURE-OBJECT.
16 (sb!xc:defstruct (hash-table (:constructor %make-hash-table))
17   ;; The type of hash table this is. Only used for printing and as
18   ;; part of the exported interface.
19   (test (missing-arg) :type symbol :read-only t)
20   ;; The function used to compare two keys. Returns T if they are the
21   ;; same and NIL if not.
22   (test-fun (missing-arg) :type function :read-only t)
23   ;; The function used to compute the hashing of a key. Returns two
24   ;; values: the index hashing and T if that might change with the
25   ;; next GC.
26   (hash-fun (missing-arg) :type function :read-only t)
27   ;; How much to grow the hash table by when it fills up. If an index,
28   ;; then add that amount. If a floating point number, then multiply
29   ;; it by that.
30   (rehash-size (missing-arg) :type (or index (single-float (1.0)))
31                :read-only t)
32   ;; How full the hash table has to get before we rehash
33   (rehash-threshold (missing-arg) :type (single-float (0.0) 1.0) :read-only t)
34   ;; The number of entries before a rehash, just one less than the
35   ;; size of the next-vector, hash-vector, and half the size of the
36   ;; kv-vector.
37   (rehash-trigger (missing-arg) :type index)
38   ;; The current number of entries in the table.
39   (number-entries 0 :type index)
40   ;; The Key-Value pair vector.
41   (table (missing-arg) :type simple-vector)
42   ;; This slot is used to link weak hash tables during GC. When the GC
43   ;; isn't running it is always NIL.
44   (next-weak-hash-table nil :type null)
45   ;; Non-NIL if this is some kind of weak hash table. For details see
46   ;; the docstring of MAKE-HASH-TABLE.
47   (weakness nil :type (member nil :key :value :key-or-value :key-and-value)
48             :read-only t)
49   ;; Index into the Next vector chaining together free slots in the KV
50   ;; vector.
51   (next-free-kv 0 :type index)
52   ;; A cache that is either nil or is an index into the hash table
53   ;; that should be checked first
54   (cache nil :type (or null index))
55   ;; The index vector. This may be larger than the hash size to help
56   ;; reduce collisions.
57   (index-vector (missing-arg) :type (simple-array sb!vm:word (*)))
58   ;; This table parallels the KV vector, and is used to chain together
59   ;; the hash buckets and the free list. A slot will only ever be in
60   ;; one of these lists.
61   (next-vector (missing-arg) :type (simple-array sb!vm:word (*)))
62   ;; This table parallels the KV table, and can be used to store the
63   ;; hash associated with the key, saving recalculation. Could be
64   ;; useful for EQL, and EQUAL hash tables. This table is not needed
65   ;; for EQ hash tables, and when present the value of
66   ;; +MAGIC-HASH-VECTOR-VALUE+ represents EQ-based hashing on the
67   ;; respective key.
68   (hash-vector nil :type (or null (simple-array sb!vm:word (*))))
69   ;; Used for locking GETHASH/(SETF GETHASH)/REMHASH
70   (lock (sb!thread:make-mutex :name "hash-table lock")
71         :type sb!thread:mutex :read-only t)
72   ;; The GC will set this to T if it moves an EQ-based key. This used
73   ;; to be signaled by a bit in the header of the kv vector, but that
74   ;; implementation caused some concurrency issues when we stopped
75   ;; inhibiting GC during hash-table lookup.
76   (needs-rehash-p nil :type (member nil t))
77   ;; Has user requested synchronization?
78   (synchronized-p nil :type (member nil t) :read-only t)
79   ;; For detecting concurrent accesses.
80   #!+sb-hash-table-debug
81   (signal-concurrent-access t :type (member nil t))
82   #!+sb-hash-table-debug
83   (reading-thread nil)
84   #!+sb-hash-table-debug
85   (writing-thread nil))
86
87 ;; as explained by pmai on openprojects #lisp IRC 2002-07-30: #x80000000
88 ;; is bigger than any possible nonEQ hash value, and thus indicates an
89 ;; empty slot; and EQ hash tables don't use HASH-TABLE-HASH-VECTOR.
90 ;; The previous sentence was written when SBCL was 32-bit only. The value
91 ;; now depends on the word size. It is propagated to C in genesis because
92 ;; the generational garbage collector needs to know it.
93 (defconstant +magic-hash-vector-value+ (ash 1 (1- sb!vm:n-word-bits)))
94
95 (defmacro-mundanely with-hash-table-iterator ((name hash-table) &body body)
96   #!+sb-doc
97   "WITH-HASH-TABLE-ITERATOR ((name hash-table) &body body)
98
99 Provides a method of manually looping over the elements of a hash-table. NAME
100 is bound to a generator-macro that, within the scope of the invocation,
101 returns one or three values. The first value tells whether any objects remain
102 in the hash table. When the first value is non-NIL, the second and third
103 values are the key and the value of the next object.
104
105 Consequences are undefined if HASH-TABLE is mutated during execution of BODY,
106 except for changing or removing elements corresponding to the current key. The
107 applies to all threads, not just the curren one -- even for synchronized
108 hash-tables. If the table may be mutated by another thread during iteration,
109 use eg. SB-EXT:WITH-LOCKED-HASH-TABLE to protect the WITH-HASH-TABLE-ITERATOR
110 for."
111   ;; This essentially duplicates MAPHASH, so any changes here should
112   ;; be reflected there as well.
113   (let ((function (make-symbol (concatenate 'string (symbol-name name) "-FUN"))))
114     `(let ((,function
115             (let* ((table ,hash-table)
116                    (length (length (hash-table-next-vector table)))
117                    (index 1))
118               (declare (type index/2 index))
119               (labels
120                   ((,name ()
121                      ;; (We grab the table again on each iteration just in
122                      ;; case it was rehashed by a PUTHASH.)
123                      (let ((kv-vector (hash-table-table table)))
124                        (do ()
125                            ((>= index length) (values nil))
126                          (let ((key (aref kv-vector (* 2 index)))
127                                (value (aref kv-vector (1+ (* 2 index)))))
128                            (incf index)
129                            (unless (or (eq key +empty-ht-slot+)
130                                        (eq value +empty-ht-slot+))
131                              (return (values t key value))))))))
132                 #',name))))
133        (macrolet ((,name () '(funcall ,function)))
134          ,@body))))
135
136 (defmacro-mundanely with-locked-hash-table ((hash-table) &body body)
137   #!+sb-doc
138   "Limits concurrent accesses to HASH-TABLE for the duration of BODY.
139 If HASH-TABLE is synchronized, BODY will execute with exclusive
140 ownership of the table. If HASH-TABLE is not synchronized, BODY will
141 execute with other WITH-LOCKED-HASH-TABLE bodies excluded -- exclusion
142 of hash-table accesses not surrounded by WITH-LOCKED-HASH-TABLE is
143 unspecified."
144   ;; Needless to say, this also excludes some internal bits, but
145   ;; getting there is too much detail when "unspecified" says what
146   ;; is important -- unpredictable, but harmless.
147   `(sb!thread::with-recursive-lock ((hash-table-lock ,hash-table))
148      ,@body))
149
150 (defmacro-mundanely with-locked-system-table ((hash-table) &body body)
151   `(sb!thread::with-recursive-system-lock
152        ((hash-table-lock ,hash-table))
153      ,@body))