-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathFilePathComponents.swift
298 lines (255 loc) · 8.93 KB
/
FilePathComponents.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
// MARK: - API
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath {
/// Represents a root of a file path.
///
/// On Unix, a root is simply the directory separator `/`.
///
/// On Windows, a root contains the entire path prefix up to and including
/// the final separator.
///
/// Examples:
/// * Unix:
/// * `/`
/// * Windows:
/// * `C:\`
/// * `C:`
/// * `\`
/// * `\\server\share\`
/// * `\\?\UNC\server\share\`
/// * `\\?\Volume{12345678-abcd-1111-2222-123445789abc}\`
public struct Root {
internal var _path: FilePath
internal var _rootEnd: _SystemString.Index
internal init(_ path: FilePath, rootEnd: _SystemString.Index) {
self._path = path
self._rootEnd = rootEnd
_invariantCheck()
}
// TODO: Definitely want a small form for this on Windows,
// and intern "/" for Unix.
}
/// Represents an individual, non-root component of a file path.
///
/// Components can be one of the special directory components (`.` or `..`)
/// or a file or directory name. Components are never empty and never
/// contain the directory separator.
///
/// Example:
///
/// var path: FilePath = "/tmp"
/// let file: FilePath.Component = "foo.txt"
/// file.kind == .regular // true
/// file.extension // "txt"
/// path.append(file) // path is "/tmp/foo.txt"
public struct Component {
internal var _path: FilePath
public var _range: Range<_SystemString.Index>
// TODO: Make a small-component form to save on ARC overhead when
// extracted from a path, and especially to save on allocation overhead
// when constructing one from a String literal.
internal init<RE: RangeExpression>(_ path: FilePath, _ range: RE)
where RE.Bound == _SystemString.Index {
self._path = path
self._range = range.relative(to: path._storage)
precondition(!self._range.isEmpty, "FilePath components cannot be empty")
self._invariantCheck()
}
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component {
/// Whether a component is a regular file or directory name, or a special
/// directory `.` or `..`
@frozen
public enum Kind {
/// The special directory `.`, representing the current directory.
case currentDirectory
/// The special directory `..`, representing the parent directory.
case parentDirectory
/// A file or directory name
case regular
}
/// The kind of this component
public var kind: Kind {
if _path._isCurrentDirectory(_range) { return .currentDirectory }
if _path._isParentDirectory(_range) { return .parentDirectory }
return .regular
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Root {
// TODO: Windows analysis APIs
}
// MARK: - Internals
extension _SystemString {
// TODO: take insertLeadingSlash: Bool
// TODO: turn into an insert operation with slide
internal mutating func appendComponents<C: Collection>(
components: C
) where C.Element == FilePath.Component {
// TODO(perf): Consider pre-pass to count capacity, slide
defer {
_removeTrailingSeparator()
FilePath(self)._invariantCheck()
}
for idx in components.indices {
let component = components[idx]
component._withSystemChars { self.append(contentsOf: $0) }
self.append(platformSeparator)
}
}
}
// Unifying protocol for common functionality between roots, components,
// and views onto_SystemString and FilePath.
public protocol _StrSlice: _PlatformStringable, Hashable, Codable {
var _storage: _SystemString { get }
var _range: Range<_SystemString.Index> { get }
init?(_ str: _SystemString)
func _invariantCheck()
}
extension _StrSlice {
internal var _slice: Slice<_SystemString> {
Slice(base: _storage, bounds: _range)
}
internal func _withSystemChars<T>(
_ f: (UnsafeBufferPointer<_SystemChar>) throws -> T
) rethrows -> T {
try _storage.withSystemChars {
try f(UnsafeBufferPointer(rebasing: $0[_range]))
}
}
internal func _withCodeUnits<T>(
_ f: (UnsafeBufferPointer<CInterop.PlatformUnicodeEncoding.CodeUnit>) throws -> T
) rethrows -> T {
try _slice.withCodeUnits(f)
}
public init?(_platformString s: UnsafePointer<CInterop.PlatformChar>) {
self.init(_SystemString(platformString: s))
}
public func _withPlatformString<Result>(
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
) rethrows -> Result {
try _slice.withPlatformString(body)
}
internal var _systemString: _SystemString {_SystemString(_slice) }
}
extension _StrSlice {
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs._slice.elementsEqual(rhs._slice)
}
public func hash(into hasher: inout Hasher) {
hasher.combine(_slice.count) // discriminator
for element in _slice {
hasher.combine(element)
}
}
}
internal protocol _PathSlice: _StrSlice {
var _path: FilePath { get }
}
extension _PathSlice {
public var _storage: _SystemString { _path._storage }
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component: _PathSlice {
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Root: _PathSlice {
public var _range: Range<_SystemString.Index> {
(..<_rootEnd).relative(to: _path._storage)
}
}
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
extension FilePath: _PlatformStringable {
public func _withPlatformString<Result>(_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result) rethrows -> Result {
try _storage.withPlatformString(body)
}
public init(_platformString: UnsafePointer<CInterop.PlatformChar>) {
self.init(_SystemString(platformString: _platformString))
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component {
// The index of the `.` denoting an extension
internal func _extensionIndex() ->_SystemString.Index? {
guard kind == .regular,
let idx = _slice.lastIndex(of: .dot),
idx != _slice.startIndex
else { return nil }
return idx
}
internal func _extensionRange() -> Range<_SystemString.Index>? {
guard let idx = _extensionIndex() else { return nil }
return _slice.index(after: idx) ..< _slice.endIndex
}
internal func _stemRange() -> Range<_SystemString.Index> {
_slice.startIndex ..< (_extensionIndex() ?? _slice.endIndex)
}
}
internal func _makeExtension(_ ext: String) ->_SystemString {
var result = _SystemString()
result.append(.dot)
result.append(contentsOf: ext.unicodeScalars.lazy.map(_SystemChar.init))
return result
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component {
public init?(_ str: _SystemString) {
// FIXME: explicit null root? Or something else?
let path = FilePath(str)
guard path.root == nil, path.components.count == 1 else {
return nil
}
self = path.components.first!
self._invariantCheck()
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Root {
public init?(_ str: _SystemString) {
// FIXME: explicit null root? Or something else?
let path = FilePath(str)
guard path.root != nil, path.components.isEmpty else {
return nil
}
self = path.root!
self._invariantCheck()
}
}
// MARK: - Invariants
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component {
// TODO: ensure this all gets easily optimized away in release...
public func _invariantCheck() {
#if DEBUG
precondition(!_slice.isEmpty)
precondition(_slice.last != .null)
precondition(_slice.allSatisfy { !isSeparator($0) } )
precondition(_path._relativeStart <= _slice.startIndex)
#endif // DEBUG
}
}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Root {
public func _invariantCheck() {
#if DEBUG
precondition(self._rootEnd > _path._storage.startIndex)
// TODO: Windows root invariants
#endif
}
}
#if compiler(>=5.5) && canImport(_Concurrency)
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Root: Sendable {}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component: Sendable {}
@available(/*System 0.0.2: macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0*/iOS 8, *)
extension FilePath.Component.Kind: Sendable {}
#endif