Merge commit 'e20d7001c3f7150400169fecb0bf0eefdf122fe2' into vm-check
[bpt/guile.git] / module / ice-9 / hcons.scm
1 ;;; installed-scm-file
2
3 ;;;; Copyright (C) 1995, 1996, 1998, 2001, 2003, 2006 Free Software Foundation, Inc.
4 ;;;;
5 ;;;; This library is free software; you can redistribute it and/or
6 ;;;; modify it under the terms of the GNU Lesser General Public
7 ;;;; License as published by the Free Software Foundation; either
8 ;;;; version 2.1 of the License, or (at your option) any later version.
9 ;;;;
10 ;;;; This library is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;;;; Lesser General Public License for more details.
14 ;;;;
15 ;;;; You should have received a copy of the GNU Lesser General Public
16 ;;;; License along with this library; if not, write to the Free Software
17 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 ;;;;
19
20 \f
21 (define-module (ice-9 hcons)
22 :export (hashq-cons-hash hashq-cons-assoc hashq-cons-get-handle
23 hashq-cons-create-handle! hashq-cons-ref hashq-cons-set! hashq-cons
24 hashq-conser make-gc-buffer))
25
26 \f
27 ;;; {Eq? hash-consing}
28 ;;;
29 ;;; A hash conser maintains a private universe of pairs s.t. if
30 ;;; two cons calls pass eq? arguments, the pairs returned are eq?.
31 ;;;
32 ;;; A hash conser does not contribute life to the pairs it returns.
33 ;;;
34
35 (define (hashq-cons-hash pair n)
36 (modulo (logxor (hashq (car pair) 4194303)
37 (hashq (cdr pair) 4194303))
38 n))
39
40 (define (hashq-cons-assoc key l)
41 (and (not (null? l))
42 (or (and (pair? l) ; If not a pair, use its cdr?
43 (pair? (car l))
44 (pair? (caar l))
45 (eq? (car key) (caaar l))
46 (eq? (cdr key) (cdaar l))
47 (car l))
48 (hashq-cons-assoc key (cdr l)))))
49
50 (define (hashq-cons-get-handle table key)
51 (hashx-get-handle hashq-cons-hash hashq-cons-assoc table key))
52
53 (define (hashq-cons-create-handle! table key init)
54 (hashx-create-handle! hashq-cons-hash hashq-cons-assoc table key init))
55
56 (define (hashq-cons-ref table key)
57 (hashx-ref hashq-cons-hash hashq-cons-assoc table key #f))
58
59 (define (hashq-cons-set! table key val)
60 (hashx-set! hashq-cons-hash hashq-cons-assoc table key val))
61
62 (define (hashq-cons table a d)
63 (car (hashq-cons-create-handle! table (cons a d) #f)))
64
65 (define (hashq-conser hash-tab-or-size)
66 (let ((table (if (vector? hash-tab-or-size)
67 hash-tab-or-size
68 (make-doubly-weak-hash-table hash-tab-or-size))))
69 (lambda (a d) (hashq-cons table a d))))
70
71
72 \f
73
74 (define (make-gc-buffer n)
75 (let ((ring (make-list n #f)))
76 (append! ring ring)
77 (lambda (next)
78 (set-car! ring next)
79 (set! ring (cdr ring))
80 next)))