memory_darwin.go raw
1 // +build darwin
2
3 package memory
4
5 import (
6 "os/exec"
7 "regexp"
8 "strconv"
9 )
10
11 func sysTotalMemory() uint64 {
12 s, err := sysctlUint64("hw.memsize")
13 if err != nil {
14 return 0
15 }
16 return s
17 }
18
19 func sysFreeMemory() uint64 {
20 cmd := exec.Command("vm_stat")
21 outBytes, err := cmd.Output()
22 if err != nil {
23 return 0
24 }
25
26 rePageSize := regexp.MustCompile("page size of ([0-9]*) bytes")
27 reFreePages := regexp.MustCompile("Pages free: *([0-9]*)\\.")
28
29 // default: page size of 4096 bytes
30 matches := rePageSize.FindSubmatchIndex(outBytes)
31 pageSize := uint64(4096)
32 if len(matches) == 4 {
33 pageSize, err = strconv.ParseUint(string(outBytes[matches[2]:matches[3]]), 10, 64)
34 if err != nil {
35 return 0
36 }
37 }
38
39 // ex: Pages free: 1126961.
40 matches = reFreePages.FindSubmatchIndex(outBytes)
41 freePages := uint64(0)
42 if len(matches) == 4 {
43 freePages, err = strconv.ParseUint(string(outBytes[matches[2]:matches[3]]), 10, 64)
44 if err != nil {
45 return 0
46 }
47 }
48 return freePages * pageSize
49 }
50