@@ -2,7 +2,9 @@ package main
2
2
3
3
import (
4
4
"fmt"
5
+ "github.com/antonmedv/expr/test/fuzz"
5
6
"os"
7
+ "runtime"
6
8
"strings"
7
9
8
10
"github.com/antonmedv/expr"
@@ -14,7 +16,7 @@ import (
14
16
15
17
var keywords = []string {
16
18
// Commands:
17
- "exit" , "opcodes" , "debug" ,
19
+ "exit" , "opcodes" , "debug" , "mem" ,
18
20
19
21
// Operators:
20
22
"and" , "or" , "in" , "not" , "not in" ,
@@ -36,9 +38,9 @@ func main() {
36
38
}
37
39
defer rl .Close ()
38
40
39
- env := map [ string ] any {
40
- "ENV" : os . Environ (),
41
- }
41
+ env := fuzz . NewEnv ()
42
+
43
+ var memUsage uint64
42
44
var program * vm.Program
43
45
44
46
for {
@@ -48,20 +50,26 @@ func main() {
48
50
}
49
51
line = strings .TrimSpace (line )
50
52
51
- if line == "exit" {
52
- break
53
- }
53
+ switch line {
54
+ case "" :
55
+ continue
54
56
55
- if line == "opcodes" {
57
+ case "exit" :
58
+ return
59
+
60
+ case "mem" :
61
+ fmt .Printf ("memory usage: %s\n " , humanizeBytes (memUsage ))
62
+ continue
63
+
64
+ case "opcodes" :
56
65
if program == nil {
57
66
fmt .Println ("no program" )
58
67
continue
59
68
}
60
69
fmt .Println (program .Disassemble ())
61
70
continue
62
- }
63
71
64
- if line == "debug" {
72
+ case "debug" :
65
73
if program == nil {
66
74
fmt .Println ("no program" )
67
75
continue
@@ -75,11 +83,15 @@ func main() {
75
83
fmt .Printf ("compile error: %s\n " , err )
76
84
continue
77
85
}
86
+
87
+ start := memoryUsage ()
78
88
output , err := expr .Run (program , env )
79
89
if err != nil {
80
90
fmt .Printf ("runtime error: %s\n " , err )
81
91
continue
82
92
}
93
+ memUsage = memoryUsage () - start
94
+
83
95
fmt .Println (output )
84
96
}
85
97
}
@@ -106,3 +118,23 @@ func (c completer) Do(line []rune, pos int) ([][]rune, int) {
106
118
107
119
return words , len (lastWord )
108
120
}
121
+
122
+ func memoryUsage () uint64 {
123
+ var m runtime.MemStats
124
+ runtime .ReadMemStats (& m )
125
+ return m .Alloc
126
+ }
127
+
128
+ func humanizeBytes (b uint64 ) string {
129
+ const unit = 1024
130
+ if b < unit {
131
+ return fmt .Sprintf ("%d B" , b )
132
+ }
133
+ div , exp := uint64 (unit ), 0
134
+ for n := b / unit ; n >= unit ; n /= unit {
135
+ div *= unit
136
+ exp ++
137
+ }
138
+ return fmt .Sprintf ("%.2f %ciB" ,
139
+ float64 (b )/ float64 (div ), "KMGTPE" [exp ])
140
+ }
0 commit comments