github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/system/mem/mem_darwin.go (about)

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