github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/util/disk/usage_windows.go (about)

     1  package disk
     2  
     3  import (
     4  	"os"
     5  	"syscall"
     6  	"unsafe"
     7  
     8  	"golang.org/x/sys/windows"
     9  
    10  	"github.com/pyroscope-io/pyroscope/pkg/util/bytesize"
    11  )
    12  
    13  var (
    14  	kernel32 = windows.NewLazySystemDLL("kernel32.dll")
    15  	// https://msdn.microsoft.com/en-us/library/windows/desktop/aa364937(v=vs.85).aspx
    16  	getDiskFreeSpaceEx = kernel32.NewProc("GetDiskFreeSpaceExW")
    17  )
    18  
    19  func Usage(path string) (UsageStats, error) {
    20  	dirPath, err := syscall.UTF16PtrFromString(path)
    21  	if err != nil {
    22  		return UsageStats{}, err
    23  	}
    24  
    25  	var (
    26  		freeBytesAvailableToCaller uint64
    27  		totalNumberOfBytes         uint64
    28  		totalNumberOfFreeBytes     uint64
    29  	)
    30  
    31  	ret, _, err := getDiskFreeSpaceEx.Call(
    32  		uintptr(unsafe.Pointer(dirPath)),
    33  		uintptr(unsafe.Pointer(&freeBytesAvailableToCaller)),
    34  		uintptr(unsafe.Pointer(&totalNumberOfBytes)),
    35  		uintptr(unsafe.Pointer(&totalNumberOfFreeBytes)))
    36  	if ret == 0 {
    37  		return UsageStats{}, os.NewSyscallError("GetDiskFreeSpaceEx", err)
    38  	}
    39  
    40  	u := UsageStats{
    41  		Total:     bytesize.ByteSize(totalNumberOfBytes),
    42  		Available: bytesize.ByteSize(freeBytesAvailableToCaller),
    43  	}
    44  	return u, nil
    45  }