1 (in-package :alexandria
)
3 (defun copy-hash-table (table &key key test size
4 rehash-size rehash-threshold
)
5 "Returns a copy of hash table TABLE, with the same keys and values
6 as the TABLE. The copy has the same properties as the original, unless
7 overridden by the keyword arguments.
9 Before each of the original values is set into the new hash-table, KEY
10 is invoked on the value. As KEY defaults to CL:IDENTITY, a shallow
11 copy is returned by default."
12 (setf key
(or key
'identity
))
13 (setf test
(or test
(hash-table-test table
)))
14 (setf size
(or size
(hash-table-size table
)))
15 (setf rehash-size
(or rehash-size
(hash-table-rehash-size table
)))
16 (setf rehash-threshold
(or rehash-threshold
(hash-table-rehash-threshold table
)))
17 (let ((copy (make-hash-table :test test
:size size
18 :rehash-size rehash-size
19 :rehash-threshold rehash-threshold
)))
20 (maphash (lambda (k v
)
21 (setf (gethash k copy
) (funcall key v
)))
25 (declaim (inline maphash-keys
))
26 (defun maphash-keys (function table
)
27 "Like MAPHASH, but calls FUNCTION with each key in the hash table TABLE."
28 (maphash (lambda (k v
)
33 (declaim (inline maphash-values
))
34 (defun maphash-values (function table
)
35 "Like MAPHASH, but calls FUNCTION with each value in the hash table TABLE."
36 (maphash (lambda (k v
)
41 (defun hash-table-keys (table)
42 "Returns a list containing the keys of hash table TABLE."
44 (maphash-keys (lambda (k)
49 (defun hash-table-values (table)
50 "Returns a list containing the values of hash table TABLE."
52 (maphash-values (lambda (v)
57 (defun hash-table-alist (table)
58 "Returns an association list containing the keys and values of hash table
61 (maphash (lambda (k v
)
62 (push (cons k v
) alist
))
66 (defun hash-table-plist (table)
67 "Returns a property list containing the keys and values of hash table
70 (maphash (lambda (k v
)
71 (setf plist
(list* k v plist
)))
75 (defun alist-hash-table (alist &rest hash-table-initargs
)
76 "Returns a hash table containing the keys and values of the association list
77 ALIST. Hash table is initialized using the HASH-TABLE-INITARGS."
78 (let ((table (apply #'make-hash-table hash-table-initargs
)))
80 (setf (gethash (car cons
) table
) (cdr cons
)))
83 (defun plist-hash-table (plist &rest hash-table-initargs
)
84 "Returns a hash table containing the keys and values of the property list
85 PLIST. Hash table is initialized using the HASH-TABLE-INITARGS."
86 (let ((table (apply #'make-hash-table hash-table-initargs
)))
87 (do ((tail plist
(cddr tail
)))
89 (setf (gethash (car tail
) table
) (cadr tail
)))
92 (defmacro ensure-gethash
(key hash-table
&optional default
)
93 "Like GETHASH, but if KEY is not found in the HASH-TABLE saves the DEFAULT
94 under key before returning it. Secondary return value is true if key was
95 already in the table."
96 `(multiple-value-bind (value ok
) (gethash ,key
,hash-table
)
99 (values (setf (gethash ,key
,hash-table
) ,default
) nil
))))