module scheme fn hash_text(source string) string { mut vm := new_with_options(Options{ max_steps: 0 }) or { panic(err) } return write(vm.eval(source) or { panic('${source}: ${err}') }) or { panic(err) } } fn test_hash_functions_respect_existing_scalar_and_structural_equality() { for source in [ '(= (equal-hash 0.0) (equal-hash -0.0))', '(= (symbol-hash (string->symbol "same")) (symbol-hash (string->symbol "same")))', '(= (equal-hash (list 1 (vector 2 "same") (bytevector 3 4))) (equal-hash (list 1 (vector 2 "same") (bytevector 3 4))))', '(let ((a (list 1)) (b (list 1 1))) (set-cdr! a a) (set-cdr! (cdr b) b) (= (equal-hash a) (equal-hash b)))', '(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)))', '(let ((child (list 1 2))) (= (equal-hash (vector child child)) (equal-hash (vector (list 1 2) (list 1 2)))))', '(= (string-ci-hash "ÅλABC") (string-ci-hash "åΛabc"))', '(= (equal-hash -9223372036854775808) (equal-hash (- 0 9223372036854775807 1)))', '(let ((h (make-hashtable equal-hash equal?)) (a (list 1)) (b (list 1 1))) (set-cdr! a a) (set-cdr! (cdr b) b) (hashtable-set! h a 42) (= (hashtable-ref h b 0) 42))', '(let ((h (make-eqv-hashtable))) (hashtable-set! h 0.0 42) (= (hashtable-ref h -0.0 0) 42))', '(let ((h (make-eq-hashtable))) (hashtable-set! h (string->symbol "same") 42) (= (hashtable-ref h (string->symbol "same") 0) 42))', '(let ((h (make-hashtable string-ci-hash string-ci=?))) (hashtable-set! h "ÅλABC" 42) (= (hashtable-ref h "åΛabc" 0) 42))', ] { assert hash_text(source) == '#t', source } } fn test_hashing_shared_branching_cycles_terminates_and_strings_follow_comparator_decoding() { assert hash_text('(define v (vector 0 0 0 0)) (vector-fill! v v) (integer? (equal-hash v))') == '#t' mut vm := new() a := string_value([u8(0xff)].bytestr()) b := string_value([u8(0xfe)].bytestr()) hash_fn := vm.lookup('string-hash') or { panic(err) } assert vm.call(vm.lookup('string=?') or { panic(err) }, [a, b]) or { panic(err) }.is_true() assert eqv(vm.call(hash_fn, [a]) or { panic(err) }, vm.call(hash_fn, [b]) or { panic(err) }) } fn test_scalar_and_bounded_structural_hashes_allocate_no_heap_buffers() { $if gcboehm ? { mut vm := new() root := vm.eval('(let ((x (vector 0 0))) (vector-fill! x x) x)') or { panic(err) } text := string_value('ÅλABC') gc_collect() before := gc_heap_usage().total_bytes mut total := u64(0) for i in 0 .. 1000 { total ^= identity_key_hash(integer(i64(i))) total ^= bounded_structural_hash(root) total ^= u64(string_key_hash(text, true) or { panic(err) }.whole()) } assert gc_heap_usage().total_bytes == before assert total != 0 } }