-
Notifications
You must be signed in to change notification settings - Fork 2
/
sizeof.ss
109 lines (87 loc) · 3.12 KB
/
sizeof.ss
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#lang scheme
(require (planet schematics/schemeunit:3)
"web-server/web-cell.ss")
(require/expose "web-server/web-cell.ss"
(frame-namespace))
(define cache (make-parameter #f))
(define (sizeof/top x)
(parameterize ([cache (make-hasheq)])
(sizeof x)))
(define (sizeof x)
(if (hash-has-key? (cache) x)
(begin 0)
(begin (hash-set! (cache) x #t)
(cond [(frame? x) (sizeof/frame x)]
[(string? x) (sizeof/string x)]
[(symbol? x) (sizeof/symbol x)]
[(bytes? x) (sizeof/bytes x)]
[(number? x) (sizeof/number x)]
[(char? x) (sizeof/char x)]
[(boolean? x) (sizeof/boolean x)]
[(null? x) (sizeof/null x)]
[(pair? x) (sizeof/pair x)]
[(vector? x) (sizeof/vector x)]
[(struct? x) (sizeof/struct x)]
[(hash? x) (sizeof/hash x)]
[(namespace? x) (sizeof/namespace x)]
[(procedure? x) (sizeof/procedure x)]
[(struct-type? x) (sizeof/struct-type x)]
[else (printf " unknown ~a~n" x) 4]))))
;My impression is that
; cons pairs are 3 words,
; structs are n+2 words for n fields,
; strings are n+1 words for n characters,
; bytes are n/4 + 1 words for a bytes-length of n,
; vectors are n+1 words,
; objects are n+3 words for a class with n fields,
; classes are n+2 words for n methods,
; some of those "+1"s could be "+2"s (or +2s being +3s, etc).
(define (sizeof/frame frame)
(+ 4 ; struct descriptor
(sizeof (frame-id frame))
4 ; reference to parent
(sizeof (frame-namespace frame))))
(define (sizeof/string str)
(+ 4 ; length
(* 4 (string-length str)))) ; characters
(define (sizeof/symbol sym)
4)
(define (sizeof/bytes byt)
(+ 4 (bytes-length byt)))
(define (sizeof/number num)
4)
(define (sizeof/char char)
4)
(define (sizeof/boolean bool)
4)
(define (sizeof/null null)
4)
(define (sizeof/pair pair)
(+ 4
(sizeof (car pair))
(sizeof (cdr pair))))
(define (sizeof/vector vec)
(for/fold ([accum 4])
([item (in-vector vec)])
(+ accum (sizeof item))))
(define (sizeof/struct struct)
(sizeof/vector (struct->vector struct)))
(define (sizeof/hash hash)
(for/fold ([accum 4])
([(key val) (in-dict hash)])
(+ accum (sizeof key) (sizeof val))))
(define (sizeof/namespace ns)
(for/fold ([accum 4])
([name (in-list (namespace-mapped-symbols ns))])
(+ accum (sizeof name) (sizeof (namespace-variable-value name #t #f ns)))))
(define (sizeof/procedure proc)
4)
(define (sizeof/struct-type type)
(for/fold ([accum 4])
([item (in-list
(call-with-values
(lambda ()
(struct-type-info type))
list))])
(+ accum (sizeof item))))
(provide (rename-out [sizeof/top sizeof]))