github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/utils/memory/memory_darwin.go (about)

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