Skip to content

Commit 42422ce

Browse files
committed
feat: added a new mechanism for disk free space reader that potentially will take less CPU to make a read
1 parent 2649d40 commit 42422ce

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

Modules/Disk/readers.swift

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import Cocoa
1313
import Kit
1414
import IOKit.storage
15+
import CoreServices
1516

1617
let kIONVMeSMARTUserClientTypeID = CFUUIDGetConstantUUIDWithBytes(nil,
1718
0xAA, 0x0F, 0xA6, 0xF9,
@@ -38,6 +39,7 @@ internal class CapacityReader: Reader<Disks> {
3839
private var SMART: Bool {
3940
Store.shared.bool(key: "\(ModuleType.disk.stringValue)_SMART", defaultValue: true)
4041
}
42+
private var purgableSpace: [URL: (Date, Int64)] = [:]
4143

4244
public override func read() {
4345
let keys: [URLResourceKey] = [.volumeNameKey]
@@ -96,6 +98,26 @@ internal class CapacityReader: Reader<Disks> {
9698
}
9799

98100
private func freeDiskSpaceInBytes(_ path: URL) -> Int64 {
101+
var stat = statfs()
102+
if statfs(path.path, &stat) == 0 {
103+
var purgeable: Int64 = 0
104+
if self.purgableSpace[path] == nil {
105+
let value = CSDiskSpaceGetRecoveryEstimate(path as NSURL)
106+
purgeable = Int64(value)
107+
self.purgableSpace[path] = (Date(), purgeable)
108+
} else if let pair = self.purgableSpace[path] {
109+
let delta = Date().timeIntervalSince(pair.0)
110+
if delta > 60 {
111+
let value = CSDiskSpaceGetRecoveryEstimate(path as NSURL)
112+
purgeable = Int64(value)
113+
self.purgableSpace[path] = (Date(), purgeable)
114+
} else {
115+
purgeable = pair.1
116+
}
117+
}
118+
return (Int64(stat.f_bfree) * Int64(stat.f_bsize)) + Int64(purgeable)
119+
}
120+
99121
do {
100122
if let url = URL(string: path.absoluteString) {
101123
let values = try url.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])

0 commit comments

Comments
 (0)