github.com/boomhut/fiber/v2@v2.0.0-20230603160335-b65c856e57d3/internal/gopsutil/mem/mem_darwin.go (about)

     1  //go:build darwin
     2  // +build darwin
     3  
     4  package mem
     5  
     6  import (
     7  	"context"
     8  	"encoding/binary"
     9  	"fmt"
    10  	"unsafe"
    11  
    12  	"golang.org/x/sys/unix"
    13  )
    14  
    15  func getHwMemsize() (uint64, error) {
    16  	totalString, err := unix.Sysctl("hw.memsize")
    17  	if err != nil {
    18  		return 0, err
    19  	}
    20  
    21  	// unix.sysctl() helpfully assumes the result is a null-terminated string and
    22  	// removes the last byte of the result if it's 0 :/
    23  	totalString += "\x00"
    24  
    25  	total := uint64(binary.LittleEndian.Uint64([]byte(totalString)))
    26  
    27  	return total, nil
    28  }
    29  
    30  // xsw_usage in sys/sysctl.h
    31  type swapUsage struct {
    32  	Total     uint64
    33  	Avail     uint64
    34  	Used      uint64
    35  	Pagesize  int32
    36  	Encrypted bool
    37  }
    38  
    39  // SwapMemory returns swapinfo.
    40  func SwapMemory() (*SwapMemoryStat, error) {
    41  	return SwapMemoryWithContext(context.Background())
    42  }
    43  
    44  func SwapMemoryWithContext(ctx context.Context) (*SwapMemoryStat, error) {
    45  	// https://github.com/yanllearnn/go-osstat/blob/ae8a279d26f52ec946a03698c7f50a26cfb427e3/memory/memory_darwin.go
    46  	var ret *SwapMemoryStat
    47  
    48  	value, err := unix.SysctlRaw("vm.swapusage")
    49  	if err != nil {
    50  		return ret, err
    51  	}
    52  	if len(value) != 32 {
    53  		return ret, fmt.Errorf("unexpected output of sysctl vm.swapusage: %v (len: %d)", value, len(value))
    54  	}
    55  	swap := (*swapUsage)(unsafe.Pointer(&value[0]))
    56  
    57  	u := float64(0)
    58  	if swap.Total != 0 {
    59  		u = ((float64(swap.Total) - float64(swap.Avail)) / float64(swap.Total)) * 100.0
    60  	}
    61  
    62  	ret = &SwapMemoryStat{
    63  		Total:       swap.Total,
    64  		Used:        swap.Used,
    65  		Free:        swap.Avail,
    66  		UsedPercent: u,
    67  	}
    68  
    69  	return ret, nil
    70  }