Skip to content

Commit e02adf3

Browse files
committed
FoundationEssentials: correct directory enumeration on Windows
When enumerating a directory on Windows, we would fail to increment the iterator as we would increment _after_ the return. Insert a `defer`'ed increment on the iterator to allow us to track the state properly. Because the iteration was may have completed on the previous run, we need to track an additional bit of state as `bValid` which provides us an indication if iteration has completed.
1 parent 7ce7be4 commit e02adf3

File tree

1 file changed

+3
-0
lines changed

1 file changed

+3
-0
lines changed

Sources/FoundationEssentials/FileManager/FileOperations+Enumeration.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ struct _Win32DirectoryContentsSequence: Sequence {
2323
}
2424

2525
private var hFind: HANDLE?
26+
private var bValid: Bool = true
2627
private var ffdData: WIN32_FIND_DATAW = .init()
2728
private var prefix: String = ""
2829
private var slash: Bool
@@ -69,6 +70,7 @@ struct _Win32DirectoryContentsSequence: Sequence {
6970

7071
func next() -> Element? {
7172
guard let hFind else { return nil }
73+
guard bValid else { return nil }
7274
repeat {
7375
let name = withUnsafeBytes(of: ffdData.cFileName) {
7476
String(decodingCString: $0.baseAddress!.assumingMemoryBound(to: WCHAR.self), as: UTF16.self)
@@ -80,6 +82,7 @@ struct _Win32DirectoryContentsSequence: Sequence {
8082

8183
let prefixed: String =
8284
prefix + name + ((slash && ffdData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY == FILE_ATTRIBUTE_DIRECTORY) ? #"\"# : "")
85+
defer { bValid = FindNextFileW(hFind, &ffdData) }
8386
return Element(fileName: name, fileNameWithPrefix: prefixed, dwFileAttributes: ffdData.dwFileAttributes)
8487
} while FindNextFileW(hFind, &ffdData)
8588
return nil

0 commit comments

Comments
 (0)