@@ -2,7 +2,9 @@ package main
22
33import (
44 "fmt"
5+ "github.com/antonmedv/expr/test/fuzz"
56 "os"
7+ "runtime"
68 "strings"
79
810 "github.com/antonmedv/expr"
@@ -14,7 +16,7 @@ import (
1416
1517var keywords = []string {
1618 // Commands:
17- "exit" , "opcodes" , "debug" ,
19+ "exit" , "opcodes" , "debug" , "mem" ,
1820
1921 // Operators:
2022 "and" , "or" , "in" , "not" , "not in" ,
@@ -36,9 +38,9 @@ func main() {
3638 }
3739 defer rl .Close ()
3840
39- env := map [ string ] any {
40- "ENV" : os . Environ (),
41- }
41+ env := fuzz . NewEnv ()
42+
43+ var memUsage uint64
4244 var program * vm.Program
4345
4446 for {
@@ -48,20 +50,26 @@ func main() {
4850 }
4951 line = strings .TrimSpace (line )
5052
51- if line == "exit" {
52- break
53- }
53+ switch line {
54+ case "" :
55+ continue
5456
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" :
5665 if program == nil {
5766 fmt .Println ("no program" )
5867 continue
5968 }
6069 fmt .Println (program .Disassemble ())
6170 continue
62- }
6371
64- if line == "debug" {
72+ case "debug" :
6573 if program == nil {
6674 fmt .Println ("no program" )
6775 continue
@@ -75,11 +83,15 @@ func main() {
7583 fmt .Printf ("compile error: %s\n " , err )
7684 continue
7785 }
86+
87+ start := memoryUsage ()
7888 output , err := expr .Run (program , env )
7989 if err != nil {
8090 fmt .Printf ("runtime error: %s\n " , err )
8191 continue
8292 }
93+ memUsage = memoryUsage () - start
94+
8395 fmt .Println (output )
8496 }
8597}
@@ -106,3 +118,23 @@ func (c completer) Do(line []rune, pos int) ([][]rune, int) {
106118
107119 return words , len (lastWord )
108120}
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