compat icon indicating copy to clipboard operation
compat copied to clipboard

** New function 'hash-table-contains-p'.

Open minad opened this issue 10 months ago • 3 comments

This function returns non-nil if a given key is present in a hash table.

minad avatar Mar 29 '25 14:03 minad

Just added in https://github.com/emacs-mirror/emacs/commit/dd0dd87e3aaf3116c400fba858cbe35ced15f04e. The implementation looks unnecessarily inefficient though since it always allocates a new symbol.

(defsubst hash-table-contains-p (key table)
  "Return non-nil if TABLE has an element with KEY."
  (declare (side-effect-free t)
           (important-return-value t))
  (let ((missing (make-symbol "missing")))
    (not (eq (gethash key table missing) missing))))

Maybe the following is a better alternative? It works well enough as long as hash table users do use the private hash-table--missing.

(defconst hash-table--missing (make-symbol "hash-table--missing"))
(defsubst hash-table-contains-p (key table)
  "Return non-nil if TABLE has an element with KEY."
  (declare (side-effect-free t)
           (important-return-value t))
  (not (eq (gethash key table hash-table--missing) hash-table--missing)))

cc @phikal @skangas

minad avatar Mar 29 '25 14:03 minad

Is it possible to leverage eval-when-compile?

(defsubst hash-table-contains-p (key table)
  "Return non-nil if TABLE has an element with KEY."
  (declare (side-effect-free t)
           (important-return-value t))
  (let ((missing (eval-when-compile (make-symbol "missing"))))
    (not (eq (gethash key table missing) missing))))

(I lack the understanding of the fine details of uninterned symbols and their behavior during compilation.)

minad avatar Mar 29 '25 14:03 minad

Reported upstream as https://debbugs.gnu.org/cgi/bugreport.cgi?bug=78162

minad avatar Apr 30 '25 15:04 minad

Done in https://github.com/emacs-compat/compat/commit/cfe89a74a63e8205782b7217ae01145b54a27fcc

minad avatar May 12 '25 22:05 minad