github.com/gofiber/fiber/v2@v2.47.0/internal/gopsutil/mem/mem_darwin_cgo.go (about) 1 //go:build darwin && cgo 2 // +build darwin,cgo 3 4 package mem 5 6 /* 7 #include <mach/mach_host.h> 8 */ 9 import "C" 10 11 import ( 12 "context" 13 "fmt" 14 "unsafe" 15 16 "golang.org/x/sys/unix" 17 ) 18 19 // VirtualMemory returns VirtualmemoryStat. 20 func VirtualMemory() (*VirtualMemoryStat, error) { 21 return VirtualMemoryWithContext(context.Background()) 22 } 23 24 func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) { 25 count := C.mach_msg_type_number_t(C.HOST_VM_INFO_COUNT) 26 var vmstat C.vm_statistics_data_t 27 28 status := C.host_statistics(C.host_t(C.mach_host_self()), 29 C.HOST_VM_INFO, 30 C.host_info_t(unsafe.Pointer(&vmstat)), 31 &count) 32 33 if status != C.KERN_SUCCESS { 34 return nil, fmt.Errorf("host_statistics error=%d", status) 35 } 36 37 pageSize := uint64(unix.Getpagesize()) 38 total, err := getHwMemsize() 39 if err != nil { 40 return nil, err 41 } 42 totalCount := C.natural_t(total / pageSize) 43 44 availableCount := vmstat.inactive_count + vmstat.free_count 45 usedPercent := 100 * float64(totalCount-availableCount) / float64(totalCount) 46 47 usedCount := totalCount - availableCount 48 49 return &VirtualMemoryStat{ 50 Total: total, 51 Available: pageSize * uint64(availableCount), 52 Used: pageSize * uint64(usedCount), 53 UsedPercent: usedPercent, 54 Free: pageSize * uint64(vmstat.free_count), 55 Active: pageSize * uint64(vmstat.active_count), 56 Inactive: pageSize * uint64(vmstat.inactive_count), 57 Wired: pageSize * uint64(vmstat.wire_count), 58 }, nil 59 }