vile / scheme / hashtable_hash_test.v
54 lines · 50 sloc · 2.7 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3fn hash_text(source string) string {
4 mut vm := new_with_options(Options{ max_steps: 0 }) or { panic(err) }
5 return write(vm.eval(source) or { panic('${source}: ${err}') }) or { panic(err) }
6}
7
8fn test_hash_functions_respect_existing_scalar_and_structural_equality() {
9 for source in [
10 '(= (equal-hash 0.0) (equal-hash -0.0))',
11 '(= (symbol-hash (string->symbol "same")) (symbol-hash (string->symbol "same")))',
12 '(= (equal-hash (list 1 (vector 2 "same") (bytevector 3 4))) (equal-hash (list 1 (vector 2 "same") (bytevector 3 4))))',
13 '(let ((a (list 1)) (b (list 1 1))) (set-cdr! a a) (set-cdr! (cdr b) b) (= (equal-hash a) (equal-hash b)))',
14 '(let ((a (vector 0)) (b (vector 0)) (c (vector 0))) (vector-set! a 0 a) (vector-set! b 0 c) (vector-set! c 0 b) (= (equal-hash a) (equal-hash b)))',
15 '(let ((child (list 1 2))) (= (equal-hash (vector child child)) (equal-hash (vector (list 1 2) (list 1 2)))))',
16 '(= (string-ci-hash "ÅλABC") (string-ci-hash "åΛabc"))',
17 '(= (equal-hash -9223372036854775808) (equal-hash (- 0 9223372036854775807 1)))',
18 '(let ((h (make-hashtable equal-hash equal?)) (a (list 1)) (b (list 1 1)))
19 (set-cdr! a a) (set-cdr! (cdr b) b) (hashtable-set! h a 42) (= (hashtable-ref h b 0) 42))',
20 '(let ((h (make-eqv-hashtable))) (hashtable-set! h 0.0 42) (= (hashtable-ref h -0.0 0) 42))',
21 '(let ((h (make-eq-hashtable))) (hashtable-set! h (string->symbol "same") 42) (= (hashtable-ref h (string->symbol "same") 0) 42))',
22 '(let ((h (make-hashtable string-ci-hash string-ci=?))) (hashtable-set! h "ÅλABC" 42) (= (hashtable-ref h "åΛabc" 0) 42))',
23 ] {
24 assert hash_text(source) == '#t', source
25 }
26}
27
28fn test_hashing_shared_branching_cycles_terminates_and_strings_follow_comparator_decoding() {
29 assert hash_text('(define v (vector 0 0 0 0)) (vector-fill! v v) (integer? (equal-hash v))') == '#t'
30 mut vm := new()
31 a := string_value([u8(0xff)].bytestr())
32 b := string_value([u8(0xfe)].bytestr())
33 hash_fn := vm.lookup('string-hash') or { panic(err) }
34 assert vm.call(vm.lookup('string=?') or { panic(err) }, [a, b]) or { panic(err) }.is_true()
35 assert eqv(vm.call(hash_fn, [a]) or { panic(err) }, vm.call(hash_fn, [b]) or { panic(err) })
36}
37
38fn test_scalar_and_bounded_structural_hashes_allocate_no_heap_buffers() {
39 $if gcboehm ? {
40 mut vm := new()
41 root := vm.eval('(let ((x (vector 0 0))) (vector-fill! x x) x)') or { panic(err) }
42 text := string_value('ÅλABC')
43 gc_collect()
44 before := gc_heap_usage().total_bytes
45 mut total := u64(0)
46 for i in 0 .. 1000 {
47 total ^= identity_key_hash(integer(i64(i)))
48 total ^= bounded_structural_hash(root)
49 total ^= u64(string_key_hash(text, true) or { panic(err) }.whole())
50 }
51 assert gc_heap_usage().total_bytes == before
52 assert total != 0
53 }
54}
55