mirror of
https://github.com/apple/swift-system
synced 2026-11-22 04:30:46 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
94fa6bd2ff | ||
|
|
a552fda216 | ||
|
|
bdb13a5a80 | ||
|
|
3920df78d9 | ||
|
|
469ede0fa2 | ||
|
|
afe2d35d0b | ||
|
|
25380a1bea | ||
|
|
74eb6f4ef8 | ||
|
|
6db5a4a43b | ||
|
|
5ba9e8fa77 | ||
|
|
914c782b96 | ||
|
|
82a6704912 | ||
|
|
bd5a7bb703 | ||
|
|
147ebc053a | ||
|
|
5c18991f29 | ||
|
|
7bb5279b57 | ||
|
|
865fd70605 | ||
|
|
ca6e888455 | ||
|
|
fea7d5030d | ||
|
|
d90bf8529a | ||
|
|
02daf4b6a7 | ||
|
|
7fab65f340 | ||
|
|
5d3519dcef | ||
|
|
23ac190631 | ||
|
|
a77a331dc7 | ||
|
|
1d5e35a460 | ||
|
|
fd82b5a0ce | ||
|
|
0c24d31e08 | ||
|
|
1daa0c9677 | ||
|
|
836bc4557b | ||
|
|
5d68cf0eca | ||
|
|
5703dc2b4d | ||
|
|
2fa26782e1 | ||
|
|
0c291a65c2 | ||
|
|
0ac080ea56 | ||
|
|
d2c4e4507a | ||
|
|
78847afcd4 | ||
|
|
689390f50f | ||
|
|
ce8b491073 | ||
|
|
39774ef16a | ||
|
|
58a2725013 | ||
|
|
e520e61616 | ||
|
|
4f36710d0b | ||
|
|
591ff41944 | ||
|
|
2bc160bfe3 | ||
|
|
578586ab80 | ||
|
|
8e3c23987f | ||
|
|
090d109c0f | ||
|
|
603718e247 | ||
|
|
65a906baf1 | ||
|
|
a973b97147 | ||
|
|
b614185c90 | ||
|
|
dd1da2991e | ||
|
|
bdfeb29148 | ||
|
|
83875613ec | ||
|
|
b761517c25 | ||
|
|
e191da860c | ||
|
|
eb215cf414 | ||
|
|
58e9e1c0c9 | ||
|
|
cd4b42e03d | ||
|
|
a611ed59c4 | ||
|
|
8031239cef | ||
|
|
2ac0cdc24b | ||
|
|
8b989f724f | ||
|
|
b28263a910 | ||
|
|
bae68a5651 | ||
|
|
b6558a3a90 | ||
|
|
16667a30c4 | ||
|
|
b9d290dc1e | ||
|
|
0734450867 | ||
|
|
d7611ca8ad | ||
|
|
b63554656d | ||
|
|
7b33caf850 | ||
|
|
4f0eafd24e | ||
|
|
37e23f208a | ||
|
|
2d24a58a41 | ||
|
|
a5b2501f9a | ||
|
|
b5a89a4601 | ||
|
|
2e9c1a7118 | ||
|
|
03c0b7ada5 | ||
|
|
90d412b6f3 | ||
|
|
47da6f147f | ||
|
|
2904f9ead3 | ||
|
|
11cc26a46b | ||
|
|
ac6f82162c | ||
|
|
5bea53afe7 | ||
|
|
d24083e1be | ||
|
|
05e3d04b0c | ||
|
|
2167575e66 | ||
|
|
920ef3085d | ||
|
|
79eed1f99d | ||
|
|
3367b485e1 | ||
|
|
5d1b2fb985 | ||
|
|
0627d28e6a | ||
|
|
4ffcc62e9b | ||
|
|
0b0d9d5fbb | ||
|
|
ac6ec0b19d | ||
|
|
bf90fedc88 | ||
|
|
28916d22fb | ||
|
|
1eeeaf7200 | ||
|
|
5712a28377 | ||
|
|
8f2622ad40 | ||
|
|
173c684973 | ||
|
|
d93ee62bbd | ||
|
|
ab94d189df | ||
|
|
d2e26f72f3 | ||
|
|
a8d07f8a04 | ||
|
|
98a1531ea0 | ||
|
|
138c7f1a71 | ||
|
|
9489545fed |
No files matched your search
@@ -3,3 +3,4 @@
|
||||
/Packages
|
||||
/*.xcodeproj
|
||||
xcuserdata/
|
||||
.*.sw?
|
||||
@@ -0,0 +1,24 @@
|
||||
#[[
|
||||
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
|
||||
#]]
|
||||
|
||||
cmake_minimum_required(VERSION 3.16.0)
|
||||
project(SwiftSystem
|
||||
LANGUAGES C Swift)
|
||||
|
||||
list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake/modules)
|
||||
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
set(CMAKE_Swift_MODULE_DIRECTORY ${CMAKE_BINARY_DIR}/swift)
|
||||
|
||||
include(SwiftSupport)
|
||||
|
||||
add_subdirectory(Sources)
|
||||
add_subdirectory(cmake/modules)
|
||||
+22
-18
@@ -12,28 +12,32 @@
|
||||
|
||||
import PackageDescription
|
||||
|
||||
let targets: [PackageDescription.Target] = [
|
||||
.target(
|
||||
name: "SystemPackage",
|
||||
dependencies: ["SystemInternals"],
|
||||
path: "Sources/System"),
|
||||
.target(
|
||||
name: "SystemInternals",
|
||||
dependencies: ["CSystem"]),
|
||||
.target(
|
||||
name: "CSystem",
|
||||
dependencies: []),
|
||||
|
||||
.testTarget(
|
||||
name: "SystemTests",
|
||||
dependencies: ["SystemPackage"]),
|
||||
]
|
||||
|
||||
let package = Package(
|
||||
name: "swift-system",
|
||||
products: [
|
||||
.library(name: "SystemPackage", targets: ["SystemPackage"]),
|
||||
],
|
||||
dependencies: [],
|
||||
targets: targets
|
||||
targets: [
|
||||
.target(
|
||||
name: "CSystem",
|
||||
dependencies: []),
|
||||
.target(
|
||||
name: "SystemPackage",
|
||||
dependencies: ["CSystem"],
|
||||
path: "Sources/System",
|
||||
cSettings: [
|
||||
.define("_CRT_SECURE_NO_WARNINGS")
|
||||
],
|
||||
swiftSettings: [
|
||||
.define("SYSTEM_PACKAGE"),
|
||||
.define("ENABLE_MOCKING", .when(configuration: .debug))
|
||||
]),
|
||||
.testTarget(
|
||||
name: "SystemTests",
|
||||
dependencies: ["SystemPackage"],
|
||||
swiftSettings: [
|
||||
.define("SYSTEM_PACKAGE")
|
||||
]),
|
||||
]
|
||||
)
|
||||
@@ -24,20 +24,11 @@ try fd.closeAfter {
|
||||
|
||||
## Adding `SystemPackage` as a Dependency
|
||||
|
||||
To use the `SystemPackage` library in a SwiftPM project,
|
||||
To use the `SystemPackage` library in a SwiftPM project,
|
||||
add the following line to the dependencies in your `Package.swift` file:
|
||||
|
||||
```swift
|
||||
.package(url: "https://github.com/apple/swift-system", from: "0.0.1"),
|
||||
```
|
||||
|
||||
Because `SystemPackage` is under active development,
|
||||
source-stability is only guaranteed within minor versions (e.g. between `0.0.3` and `0.0.4`).
|
||||
If you don't want potentially source-breaking package updates,
|
||||
use this dependency specification instead:
|
||||
|
||||
```swift
|
||||
.package(url: "https://github.com/apple/swift-system", .upToNextMinor(from: "0.0.1")),
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.0.0"),
|
||||
```
|
||||
|
||||
Finally, include `"SystemPackage"` as a dependency for your executable target:
|
||||
@@ -46,7 +37,7 @@ Finally, include `"SystemPackage"` as a dependency for your executable target:
|
||||
let package = Package(
|
||||
// name, platforms, products, etc.
|
||||
dependencies: [
|
||||
.package(url: "https://github.com/apple/swift-system", from: "0.0.1"),
|
||||
.package(url: "https://github.com/apple/swift-system", from: "1.0.0"),
|
||||
// other dependencies
|
||||
],
|
||||
targets: [
|
||||
@@ -57,3 +48,17 @@ let package = Package(
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
## Source Stability
|
||||
|
||||
The Swift System package is source stable. The version numbers follow [Semantic Versioning][semver] -- source breaking changes to public API can only land in a new major version.
|
||||
|
||||
[semver]: https://semver.org
|
||||
|
||||
## Contributing
|
||||
|
||||
Before contributing, please read [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
## LICENSE
|
||||
|
||||
See [LICENSE](LICENSE.txt) for license information.
|
||||
@@ -0,0 +1,11 @@
|
||||
#[[
|
||||
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
|
||||
#]]
|
||||
|
||||
add_subdirectory(CSystem)
|
||||
add_subdirectory(System)
|
||||
@@ -0,0 +1,20 @@
|
||||
#[[
|
||||
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
|
||||
#]]
|
||||
|
||||
add_library(CSystem INTERFACE)
|
||||
target_include_directories(CSystem INTERFACE
|
||||
include)
|
||||
|
||||
|
||||
install(FILES
|
||||
include/CSystemLinux.h
|
||||
include/CSystemWindows.h
|
||||
include/module.modulemap
|
||||
DESTINATION include/CSystem)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS CSystem)
|
||||
@@ -0,0 +1,17 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
#if defined(_WIN32)
|
||||
|
||||
#define NOMINMAX
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#define VC_EXTRA_LEAN
|
||||
#include <Windows.h>
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,5 @@
|
||||
module CSystem {
|
||||
header "CSystemLinux.h"
|
||||
header "CSystemWindows.h"
|
||||
export *
|
||||
}
|
||||
@@ -11,4 +11,8 @@
|
||||
|
||||
#include <CSystemLinux.h>
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if defined(_WIN32)
|
||||
#include <CSystemWindows.h>
|
||||
#endif
|
||||
@@ -0,0 +1,42 @@
|
||||
#[[
|
||||
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
|
||||
#]]
|
||||
|
||||
add_library(SystemPackage
|
||||
Errno.swift
|
||||
FileDescriptor.swift
|
||||
FileHelpers.swift
|
||||
FileOperations.swift
|
||||
FilePermissions.swift
|
||||
PlatformString.swift
|
||||
SystemString.swift
|
||||
Util.swift
|
||||
UtilConsumers.swift)
|
||||
set_target_properties(SystemPackage PROPERTIES
|
||||
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
|
||||
target_sources(SystemPackage PRIVATE
|
||||
FilePath/FilePath.swift
|
||||
FilePath/FilePathComponents.swift
|
||||
FilePath/FilePathComponentView.swift
|
||||
FilePath/FilePathParsing.swift
|
||||
FilePath/FilePathString.swift
|
||||
FilePath/FilePathSyntax.swift
|
||||
FilePath/FilePathWindows.swift)
|
||||
target_sources(SystemPackage PRIVATE
|
||||
Internals/CInterop.swift
|
||||
Internals/Constants.swift
|
||||
Internals/Exports.swift
|
||||
Internals/Mocking.swift
|
||||
Internals/Syscalls.swift
|
||||
Internals/WindowsSyscallAdapters.swift)
|
||||
target_link_libraries(SystemPackage PUBLIC
|
||||
CSystem)
|
||||
|
||||
|
||||
_install_target(SystemPackage)
|
||||
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS SystemPackage)
|
||||
@@ -1,427 +0,0 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
|
||||
// For platform constants redefined in Swift. We redefine them here so that they
|
||||
// can be @_alwaysEmitIntoClient without depending on Darwin or re-including a
|
||||
// header (and applying attributes).
|
||||
|
||||
// MARK: errno
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ERRNO_NOT_USED: CInt { 0 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPERM: CInt { 1 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOENT: CInt { 2 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESRCH: CInt { 3 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EINTR: CInt { 4 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EIO: CInt { 5 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENXIO: CInt { 6 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _E2BIG: CInt { 7 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOEXEC: CInt { 8 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADF: CInt { 9 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECHILD: CInt { 10 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDEADLK: CInt { 11 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOMEM: CInt { 12 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EACCES: CInt { 13 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EFAULT: CInt { 14 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTBLK: CInt { 15 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBUSY: CInt { 16 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EEXIST: CInt { 17 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EXDEV: CInt { 18 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENODEV: CInt { 19 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTDIR: CInt { 20 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EISDIR: CInt { 21 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EINVAL: CInt { 22 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENFILE: CInt { 23 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMFILE: CInt { 24 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTTY: CInt { 25 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETXTBSY: CInt { 26 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EFBIG: CInt { 27 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSPC: CInt { 28 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESPIPE: CInt { 29 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EROFS: CInt { 30 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMLINK: CInt { 31 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPIPE: CInt { 32 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDOM: CInt { 33 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ERANGE: CInt { 34 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EAGAIN: CInt { 35 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EWOULDBLOCK: CInt { _EAGAIN }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EINPROGRESS: CInt { 36 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EALREADY: CInt { 37 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTSOCK: CInt { 38 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDESTADDRREQ: CInt { 39 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMSGSIZE: CInt { 40 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROTOTYPE: CInt { 41 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOPROTOOPT: CInt { 42 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROTONOSUPPORT: CInt { 43 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESOCKTNOSUPPORT: CInt { 44 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTSUP: CInt { 45 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPFNOSUPPORT: CInt { 46 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EAFNOSUPPORT: CInt { 47 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EADDRINUSE: CInt { 48 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EADDRNOTAVAIL: CInt { 49 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENETDOWN: CInt { 50 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENETUNREACH: CInt { 51 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENETRESET: CInt { 52 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECONNABORTED: CInt { 53 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECONNRESET: CInt { 54 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOBUFS: CInt { 55 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EISCONN: CInt { 56 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTCONN: CInt { 57 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESHUTDOWN: CInt { 58 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETOOMANYREFS: CInt { 59 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETIMEDOUT: CInt { 60 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECONNREFUSED: CInt { 61 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ELOOP: CInt { 62 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENAMETOOLONG: CInt { 63 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EHOSTDOWN: CInt { 64 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EHOSTUNREACH: CInt { 65 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTEMPTY: CInt { 66 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROCLIM: CInt { 67 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EUSERS: CInt { 68 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDQUOT: CInt { 69 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESTALE: CInt { 70 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EREMOTE: CInt { 71 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADRPC: CInt { 72 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ERPCMISMATCH: CInt { 73 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROGUNAVAIL: CInt { 74 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROGMISMATCH: CInt { 75 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROCUNAVAIL: CInt { 76 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOLCK: CInt { 77 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSYS: CInt { 78 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EFTYPE: CInt { 79 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EAUTH: CInt { 80 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENEEDAUTH: CInt { 81 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPWROFF: CInt { 82 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDEVERR: CInt { 83 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EOVERFLOW: CInt { 84 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADEXEC: CInt { 85 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADARCH: CInt { 86 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESHLIBVERS: CInt { 87 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADMACHO: CInt { 88 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECANCELED: CInt { 89 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EIDRM: CInt { 90 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOMSG: CInt { 91 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EILSEQ: CInt { 92 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOATTR: CInt { 93 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADMSG: CInt { 94 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMULTIHOP: CInt { 95 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENODATA: CInt { 96 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOLINK: CInt { 97 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSR: CInt { 98 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSTR: CInt { 99 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROTO: CInt { 100 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETIME: CInt { 101 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EOPNOTSUPP: CInt { 102 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOPOLICY: CInt { 103 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTRECOVERABLE: CInt { 104 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EOWNERDEAD: CInt { 105 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EQFULL: CInt { 106 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ELAST: CInt { 106 }
|
||||
|
||||
// MARK: File Operations
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_RDONLY: CInt { 0x0000 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_WRONLY: CInt { 0x0001 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_RDWR: CInt { 0x0002 }
|
||||
|
||||
// TODO: API?
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_ACCMODE: CInt { 0x0003 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NONBLOCK: CInt { 0x0004 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_APPEND: CInt { 0x0008 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_SHLOCK: CInt { 0x0010 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_EXLOCK: CInt { 0x0020 }
|
||||
|
||||
// TODO: API?
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_ASYNC: CInt { 0x0040 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NOFOLLOW: CInt { 0x0100 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CREAT: CInt { 0x0200 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_TRUNC: CInt { 0x0400 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_EXCL: CInt { 0x0800 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_EVTONLY: CInt { 0x8000 }
|
||||
|
||||
// TODO: API?
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NOCTTY: CInt { 0x20000 }
|
||||
|
||||
// TODO: API?
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_DIRECTORY: CInt { 0x100000 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_SYMLINK: CInt { 0x200000 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CLOEXEC: CInt { 0x1000000 }
|
||||
|
||||
// TODO: API?
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_DP_GETRAWENCRYPTED: CInt { 0x0001 }
|
||||
|
||||
// TODO: API?
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_DP_GETRAWUNENCRYPTED: CInt { 0x0002 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_SET: CInt { 0 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_CUR: CInt { 1 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_END: CInt { 2 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_HOLE: CInt { 3 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_DATA: CInt { 4 }
|
||||
|
||||
#endif
|
||||
@@ -10,7 +10,7 @@
|
||||
/// An error number used by system calls to communicate what kind of error
|
||||
/// occurred.
|
||||
@frozen
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
public struct Errno: RawRepresentable, Error, Hashable, Codable {
|
||||
/// The raw C error number.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -229,6 +229,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
|
||||
@available(*, unavailable, renamed: "badAddress")
|
||||
public static var EFAULT: Errno { badAddress }
|
||||
|
||||
#if !os(Windows)
|
||||
/// Not a block device.
|
||||
///
|
||||
/// You attempted a block device operation on a nonblock device or file.
|
||||
@@ -240,6 +241,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "notBlockDevice")
|
||||
public static var ENOTBLK: Errno { notBlockDevice }
|
||||
#endif
|
||||
|
||||
/// Resource busy.
|
||||
///
|
||||
@@ -360,6 +362,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
|
||||
@available(*, unavailable, renamed: "tooManyOpenFiles")
|
||||
public static var EMFILE: Errno { tooManyOpenFiles }
|
||||
|
||||
#if !os(Windows)
|
||||
/// Inappropriate control function.
|
||||
///
|
||||
/// You attempted a control function
|
||||
@@ -388,6 +391,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "textFileBusy")
|
||||
public static var ETXTBSY: Errno { textFileBusy }
|
||||
#endif
|
||||
|
||||
/// The file is too large.
|
||||
///
|
||||
@@ -1123,6 +1127,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
|
||||
public static var EDEVERR: Errno { deviceError }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
/// Value too large to be stored in data type.
|
||||
///
|
||||
/// A numerical result of the function
|
||||
@@ -1135,6 +1140,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "overflow")
|
||||
public static var EOVERFLOW: Errno { overflow }
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
/// Bad executable or shared library.
|
||||
@@ -1199,6 +1205,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
|
||||
@available(*, unavailable, renamed: "canceled")
|
||||
public static var ECANCELED: Errno { canceled }
|
||||
|
||||
#if !os(Windows)
|
||||
/// Identifier removed.
|
||||
///
|
||||
/// An IPC identifier was removed while the current process was waiting on it.
|
||||
@@ -1223,6 +1230,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "noMessage")
|
||||
public static var ENOMSG: Errno { noMessage }
|
||||
#endif
|
||||
|
||||
/// Illegal byte sequence.
|
||||
///
|
||||
@@ -1252,6 +1260,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
|
||||
public static var ENOATTR: Errno { attributeNotFound }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
/// Bad message.
|
||||
///
|
||||
/// The message to be received is inappropriate
|
||||
@@ -1350,6 +1359,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "timeout")
|
||||
public static var ETIME: Errno { timeout }
|
||||
#endif
|
||||
|
||||
/// Operation not supported on socket.
|
||||
///
|
||||
@@ -1366,7 +1376,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
|
||||
}
|
||||
|
||||
// Constants defined in header but not man page
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension Errno {
|
||||
|
||||
/// Operation would block.
|
||||
@@ -1411,6 +1421,7 @@ extension Errno {
|
||||
public static var ENOPOLICY: Errno { noSuchPolicy }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
/// State not recoverable.
|
||||
///
|
||||
/// The corresponding C error is `ENOTRECOVERABLE`.
|
||||
@@ -1430,6 +1441,7 @@ extension Errno {
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "previousOwnerDied")
|
||||
public static var EOWNERDEAD: Errno { previousOwnerDied }
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
/// Interface output queue is full.
|
||||
@@ -1458,8 +1470,7 @@ extension Errno {
|
||||
#endif
|
||||
}
|
||||
|
||||
@_implementationOnly import SystemInternals
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension Errno {
|
||||
// TODO: We want to provide safe access to `errno`, but we need a
|
||||
// release-barrier to do so.
|
||||
@@ -1474,14 +1485,14 @@ extension Errno {
|
||||
}
|
||||
|
||||
// Use "hidden" entry points for `NSError` bridging
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension Errno {
|
||||
public var _code: Int { Int(rawValue) }
|
||||
|
||||
public var _domain: String { "NSPOSIXErrorDomain" }
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension Errno: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
/// A textual representation of the most recent error
|
||||
/// returned by a system call.
|
||||
@@ -1501,7 +1512,7 @@ extension Errno: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension Errno {
|
||||
@_alwaysEmitIntoClient
|
||||
public static func ~=(_ lhs: Errno, _ rhs: Error) -> Bool {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2021 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
|
||||
@@ -14,7 +14,7 @@
|
||||
/// of `FileDescriptor` values,
|
||||
/// in the same way as you manage a raw C file handle.
|
||||
@frozen
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
public struct FileDescriptor: RawRepresentable, Hashable, Codable {
|
||||
/// The raw C file handle.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -25,7 +25,22 @@ public struct FileDescriptor: RawRepresentable, Hashable, Codable {
|
||||
public init(rawValue: CInt) { self.rawValue = rawValue }
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
// Standard file descriptors
|
||||
extension FileDescriptor {
|
||||
/// The standard input file descriptor, with a numeric value of 0.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var standardInput: FileDescriptor { .init(rawValue: 0) }
|
||||
|
||||
/// The standard output file descriptor, with a numeric value of 1.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var standardOutput: FileDescriptor { .init(rawValue: 1) }
|
||||
|
||||
/// The standard error file descriptor, with a numeric value of 2.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var standardError: FileDescriptor { .init(rawValue: 2) }
|
||||
}
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension FileDescriptor {
|
||||
/// The desired read and write access for a newly opened file.
|
||||
@frozen
|
||||
@@ -83,6 +98,7 @@ extension FileDescriptor {
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ raw: CInt) { self.init(rawValue: raw) }
|
||||
|
||||
#if !os(Windows)
|
||||
/// Indicates that opening the file doesn't
|
||||
/// wait for the file or device to become available.
|
||||
///
|
||||
@@ -90,7 +106,7 @@ extension FileDescriptor {
|
||||
/// the system doesn't wait for the device or file
|
||||
/// to be ready or available.
|
||||
/// If the
|
||||
/// <doc:System/FileDescriptor/open(_:_:options:permissions:)-10dcs>
|
||||
/// <doc:FileDescriptor/open(_:_:options:permissions:retryOnInterrupt:)-2266j>
|
||||
/// call would result in the process being blocked for some reason,
|
||||
/// that method returns immediately.
|
||||
/// This flag also has the effect of making all
|
||||
@@ -103,6 +119,7 @@ extension FileDescriptor {
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "nonBlocking")
|
||||
public static var O_NONBLOCK: OpenOptions { nonBlocking }
|
||||
#endif
|
||||
|
||||
/// Indicates that each write operation appends to the file.
|
||||
///
|
||||
@@ -147,14 +164,14 @@ extension FileDescriptor {
|
||||
/// expecting that it doesn't exist.
|
||||
///
|
||||
/// If this option and ``create`` are both specified and the file exists,
|
||||
/// <doc:System/FileDescriptor/open(_:_:options:permissions:)-10dcs>
|
||||
/// <doc:FileDescriptor/open(_:_:options:permissions:retryOnInterrupt:)-2266j>
|
||||
/// returns an error instead of creating the file.
|
||||
/// You can use this, for example,
|
||||
/// to implement a simple exclusive-access locking mechanism.
|
||||
///
|
||||
/// If this option and ``create`` are both specified
|
||||
/// and the last component of the file's path is a symbolic link,
|
||||
/// <doc:System/FileDescriptor/open(_:_:options:permissions:)-10dcs>
|
||||
/// <doc:FileDescriptor/open(_:_:options:permissions:retryOnInterrupt:)-2266j>
|
||||
/// fails even if the symbolic link points to a nonexistent name.
|
||||
///
|
||||
/// The corresponding C constant is `O_EXCL`.
|
||||
@@ -201,11 +218,12 @@ extension FileDescriptor {
|
||||
public static var O_EXLOCK: OpenOptions { exclusiveLock }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
/// Indicates that opening the file doesn't follow symlinks.
|
||||
///
|
||||
/// If you specify this option
|
||||
/// and the file path you pass to
|
||||
/// <doc:System/FileDescriptor/open(_:_:options:permissions:)-10dcs>
|
||||
/// <doc:FileDescriptor/open(_:_:options:permissions:retryOnInterrupt:)-2266j>
|
||||
/// is a symbolic link,
|
||||
/// then that open operation fails.
|
||||
///
|
||||
@@ -217,13 +235,28 @@ extension FileDescriptor {
|
||||
@available(*, unavailable, renamed: "noFollow")
|
||||
public static var O_NOFOLLOW: OpenOptions { noFollow }
|
||||
|
||||
/// Indicates that opening the file only succeeds if the file is a directory.
|
||||
///
|
||||
/// If you specify this option and the file path you pass to
|
||||
/// <doc:FileDescriptor/open(_:_:options:permissions:retryOnInterrupt:)-2266j>
|
||||
/// is a not a directory, then that open operation fails.
|
||||
///
|
||||
/// The corresponding C constant is `O_DIRECTORY`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static var directory: OpenOptions { OpenOptions(_O_DIRECTORY) }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "directory")
|
||||
public static var O_DIRECTORY: OpenOptions { directory }
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
/// Indicates that opening the file
|
||||
/// opens symbolic links instead of following them.
|
||||
///
|
||||
/// If you specify this option
|
||||
/// and the file path you pass to
|
||||
/// <doc:System/FileDescriptor/open(_:_:options:permissions:)-10dcs>
|
||||
/// <doc:FileDescriptor/open(_:_:options:permissions:retryOnInterrupt:)-2266j>
|
||||
/// is a symbolic link,
|
||||
/// then the link itself is opened instead of what it links to.
|
||||
///
|
||||
@@ -252,6 +285,7 @@ extension FileDescriptor {
|
||||
public static var O_EVTONLY: OpenOptions { eventOnly }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
/// Indicates that executing a program closes the file.
|
||||
///
|
||||
/// Normally, file descriptors remain open
|
||||
@@ -271,6 +305,7 @@ extension FileDescriptor {
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "closeOnExec")
|
||||
public static var O_CLOEXEC: OpenOptions { closeOnExec }
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Options for specifying what a file descriptor's offset is relative to.
|
||||
@@ -350,7 +385,7 @@ extension FileDescriptor {
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension FileDescriptor.AccessMode
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
@@ -369,7 +404,7 @@ extension FileDescriptor.AccessMode
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension FileDescriptor.SeekOrigin
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
@@ -392,7 +427,7 @@ extension FileDescriptor.SeekOrigin
|
||||
public var debugDescription: String { self.description }
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension FileDescriptor.OpenOptions
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
@@ -413,6 +448,13 @@ extension FileDescriptor.OpenOptions
|
||||
(.eventOnly, ".eventOnly"),
|
||||
(.closeOnExec, ".closeOnExec")
|
||||
]
|
||||
#elseif os(Windows)
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.append, ".append"),
|
||||
(.create, ".create"),
|
||||
(.truncate, ".truncate"),
|
||||
(.exclusiveCreate, ".exclusiveCreate"),
|
||||
]
|
||||
#else
|
||||
let descriptions: [(Element, StaticString)] = [
|
||||
(.nonBlocking, ".nonBlocking"),
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension FileDescriptor {
|
||||
/// Runs a closure and then closes the file descriptor, even if an error occurs.
|
||||
///
|
||||
@@ -46,9 +46,6 @@ extension FileDescriptor {
|
||||
/// increments that position by the number of bytes written.
|
||||
/// See also ``seek(offset:from:)``.
|
||||
///
|
||||
/// This method either writes the entire contents of `sequence`,
|
||||
/// or throws an error if only part of the content was written.
|
||||
///
|
||||
/// If `sequence` doesn't implement
|
||||
/// the <doc://com.apple.documentation/documentation/swift/sequence/3128824-withcontiguousstorageifavailable> method,
|
||||
/// temporary space will be allocated as needed.
|
||||
|
||||
@@ -7,9 +7,7 @@
|
||||
See https://swift.org/LICENSE.txt for license information
|
||||
*/
|
||||
|
||||
@_implementationOnly import SystemInternals
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension FileDescriptor {
|
||||
/// Opens or creates a file for reading or writing.
|
||||
///
|
||||
@@ -33,7 +31,7 @@ extension FileDescriptor {
|
||||
permissions: FilePermissions? = nil,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> FileDescriptor {
|
||||
try path.withCString {
|
||||
try path.withPlatformString {
|
||||
try FileDescriptor.open(
|
||||
$0, mode, options: options, permissions: permissions, retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
@@ -55,7 +53,7 @@ extension FileDescriptor {
|
||||
/// The corresponding C function is `open`.
|
||||
@_alwaysEmitIntoClient
|
||||
public static func open(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions = FileDescriptor.OpenOptions(),
|
||||
permissions: FilePermissions? = nil,
|
||||
@@ -68,11 +66,11 @@ extension FileDescriptor {
|
||||
|
||||
@usableFromInline
|
||||
internal static func _open(
|
||||
_ path: UnsafePointer<CChar>,
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ mode: FileDescriptor.AccessMode,
|
||||
options: FileDescriptor.OpenOptions,
|
||||
permissions: FilePermissions?,
|
||||
retryOnInterrupt: Bool = true
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<FileDescriptor, Errno> {
|
||||
let oFlag = mode.rawValue | options.rawValue
|
||||
let descOrError: Result<CInt, Errno> = valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
@@ -98,7 +96,7 @@ extension FileDescriptor {
|
||||
|
||||
@usableFromInline
|
||||
internal func _close() -> Result<(), Errno> {
|
||||
nothingOrErrno(system_close(self.rawValue))
|
||||
nothingOrErrno(retryOnInterrupt: false) { system_close(self.rawValue) }
|
||||
}
|
||||
|
||||
/// Reposition the offset for the given file descriptor.
|
||||
@@ -122,8 +120,9 @@ extension FileDescriptor {
|
||||
internal func _seek(
|
||||
offset: Int64, from whence: FileDescriptor.SeekOrigin
|
||||
) -> Result<Int64, Errno> {
|
||||
let newOffset = system_lseek(self.rawValue, COffT(offset), whence.rawValue)
|
||||
return valueOrErrno(Int64(newOffset))
|
||||
valueOrErrno(retryOnInterrupt: false) {
|
||||
Int64(system_lseek(self.rawValue, _COffT(offset), whence.rawValue))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -165,7 +164,7 @@ extension FileDescriptor {
|
||||
@usableFromInline
|
||||
internal func _read(
|
||||
into buffer: UnsafeMutableRawBufferPointer,
|
||||
retryOnInterrupt: Bool = true
|
||||
retryOnInterrupt: Bool
|
||||
) throws -> Result<Int, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_read(self.rawValue, buffer.baseAddress, buffer.count)
|
||||
@@ -186,7 +185,7 @@ extension FileDescriptor {
|
||||
/// The <doc://com.apple.documentation/documentation/swift/unsafemutablerawbufferpointer/3019191-count> property of `buffer`
|
||||
/// determines the maximum number of bytes that are read into that buffer.
|
||||
///
|
||||
/// Unlike <doc:System/FileDescriptor/read(into:retryOnInterrupt:)>,
|
||||
/// Unlike <doc:FileDescriptor/read(into:retryOnInterrupt:)>,
|
||||
/// this method leaves the file's existing offset unchanged.
|
||||
///
|
||||
/// The corresponding C function is `pread`.
|
||||
@@ -210,7 +209,7 @@ extension FileDescriptor {
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Int, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_pread(self.rawValue, buffer.baseAddress, buffer.count, COffT(offset))
|
||||
system_pread(self.rawValue, buffer.baseAddress, buffer.count, _COffT(offset))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -292,7 +291,7 @@ extension FileDescriptor {
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<Int, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_pwrite(self.rawValue, buffer.baseAddress, buffer.count, COffT(offset))
|
||||
system_pwrite(self.rawValue, buffer.baseAddress, buffer.count, _COffT(offset))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -309,4 +308,141 @@ extension FileDescriptor {
|
||||
buffer,
|
||||
retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
|
||||
/// Duplicate this file descriptor and return the newly created copy.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - `target`: The desired target file descriptor, or `nil`, in which case
|
||||
/// the copy is assigned to the file descriptor with the lowest raw value
|
||||
/// that is not currently in use by the process.
|
||||
/// - retryOnInterrupt: Whether to retry the write operation
|
||||
/// if it throws ``Errno/interrupted``. The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
/// - Returns: The new file descriptor.
|
||||
///
|
||||
/// If the `target` descriptor is already in use, then it is first
|
||||
/// deallocated as if a close(2) call had been done first.
|
||||
///
|
||||
/// File descriptors are merely references to some underlying system resource.
|
||||
/// The system does not distinguish between the original and the new file
|
||||
/// descriptor in any way. For example, read, write and seek operations on
|
||||
/// one of them also affect the logical file position in the other, and
|
||||
/// append mode, non-blocking I/O and asynchronous I/O options are shared
|
||||
/// between the references. If a separate pointer into the file is desired,
|
||||
/// a different object reference to the file must be obtained by issuing an
|
||||
/// additional call to `open`.
|
||||
///
|
||||
/// However, each file descriptor maintains its own close-on-exec flag.
|
||||
///
|
||||
///
|
||||
/// The corresponding C functions are `dup` and `dup2`.
|
||||
@_alwaysEmitIntoClient
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
public func duplicate(
|
||||
as target: FileDescriptor? = nil,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> FileDescriptor {
|
||||
try _duplicate(as: target, retryOnInterrupt: retryOnInterrupt).get()
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
@usableFromInline
|
||||
internal func _duplicate(
|
||||
as target: FileDescriptor?,
|
||||
retryOnInterrupt: Bool
|
||||
) throws -> Result<FileDescriptor, Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
if let target = target {
|
||||
return system_dup2(self.rawValue, target.rawValue)
|
||||
}
|
||||
return system_dup(self.rawValue)
|
||||
}.map(FileDescriptor.init(rawValue:))
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "duplicate")
|
||||
public func dup() throws -> FileDescriptor {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, unavailable, renamed: "duplicate")
|
||||
public func dup2() throws -> FileDescriptor {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
/*System 1.1.0, @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)*/
|
||||
extension FileDescriptor {
|
||||
/// Create a pipe, a unidirectional data channel which can be used for interprocess communication.
|
||||
///
|
||||
/// - Returns: The pair of file descriptors.
|
||||
///
|
||||
/// The corresponding C function is `pipe`.
|
||||
@_alwaysEmitIntoClient
|
||||
/*System 1.1.0, @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)*/
|
||||
public static func pipe() throws -> (readEnd: FileDescriptor, writeEnd: FileDescriptor) {
|
||||
try _pipe().get()
|
||||
}
|
||||
|
||||
/*System 1.1.0, @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)*/
|
||||
@usableFromInline
|
||||
internal static func _pipe() -> Result<(readEnd: FileDescriptor, writeEnd: FileDescriptor), Errno> {
|
||||
var fds: (Int32, Int32) = (-1, -1)
|
||||
return withUnsafeMutablePointer(to: &fds) { pointer in
|
||||
pointer.withMemoryRebound(to: Int32.self, capacity: 2) { fds in
|
||||
valueOrErrno(retryOnInterrupt: false) {
|
||||
system_pipe(fds)
|
||||
}.map { _ in (.init(rawValue: fds[0]), .init(rawValue: fds[1])) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/*System 1.2.0, @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)*/
|
||||
extension FileDescriptor {
|
||||
/// Truncate or extend the file referenced by this file descriptor.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - newSize: The length in bytes to resize the file to.
|
||||
/// - retryOnInterrupt: Whether to retry the write operation
|
||||
/// if it throws ``Errno/interrupted``. The default is `true`.
|
||||
/// Pass `false` to try only once and throw an error upon interruption.
|
||||
///
|
||||
/// The file referenced by this file descriptor will by truncated (or extended) to `newSize`.
|
||||
///
|
||||
/// If the current size of the file exceeds `newSize`, any extra data is discarded. If the current
|
||||
/// size of the file is smaller than `newSize`, the file is extended and filled with zeros to the
|
||||
/// provided size.
|
||||
///
|
||||
/// This function requires that the file has been opened for writing.
|
||||
///
|
||||
/// - Note: This function does not modify the current offset for any open file descriptors
|
||||
/// associated with the file.
|
||||
///
|
||||
/// The corresponding C function is `ftruncate`.
|
||||
/*System 1.2.0, @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)*/
|
||||
@_alwaysEmitIntoClient
|
||||
public func resize(
|
||||
to newSize: Int64,
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws {
|
||||
try _resize(
|
||||
to: newSize,
|
||||
retryOnInterrupt: retryOnInterrupt
|
||||
).get()
|
||||
}
|
||||
|
||||
/*System 1.2.0, @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)*/
|
||||
@usableFromInline
|
||||
internal func _resize(
|
||||
to newSize: Int64,
|
||||
retryOnInterrupt: Bool
|
||||
) -> Result<(), Errno> {
|
||||
nothingOrErrno(retryOnInterrupt: retryOnInterrupt) {
|
||||
system_ftruncate(self.rawValue, _COffT(newSize))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,210 +0,0 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
extension UnsafePointer where Pointee == UInt8 {
|
||||
internal var _asCChar: UnsafePointer<CChar> {
|
||||
UnsafeRawPointer(self).assumingMemoryBound(to: CChar.self)
|
||||
}
|
||||
}
|
||||
extension UnsafePointer where Pointee == CChar {
|
||||
internal var _asUInt8: UnsafePointer<UInt8> {
|
||||
UnsafeRawPointer(self).assumingMemoryBound(to: UInt8.self)
|
||||
}
|
||||
}
|
||||
extension UnsafeBufferPointer where Element == UInt8 {
|
||||
internal var _asCChar: UnsafeBufferPointer<CChar> {
|
||||
let base = baseAddress?._asCChar
|
||||
return UnsafeBufferPointer<CChar>(start: base, count: self.count)
|
||||
}
|
||||
}
|
||||
extension UnsafeBufferPointer where Element == CChar {
|
||||
internal var _asUInt8: UnsafeBufferPointer<UInt8> {
|
||||
let base = baseAddress?._asUInt8
|
||||
return UnsafeBufferPointer<UInt8>(start: base, count: self.count)
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: FilePath not frozen for ABI flexibility
|
||||
|
||||
/// A null-terminated sequence of bytes
|
||||
/// that represents a location in the file system.
|
||||
///
|
||||
/// This structure doesn't give any meaning to the bytes that it contains,
|
||||
/// except for the requirement that the last byte is a NUL (`0x0`).
|
||||
/// The file system defines how this string is interpreted;
|
||||
/// for example, by its choice of string encoding.
|
||||
///
|
||||
/// The code below creates a file path from a string literal,
|
||||
/// and then uses it to open and append to a log file:
|
||||
///
|
||||
/// let message: String = "This is a log message."
|
||||
/// let path: FilePath = "/tmp/log"
|
||||
/// let fd = try FileDescriptor.open(path, .writeOnly, options: .append)
|
||||
/// try fd.closeAfter { try fd.writeAll(message.utf8) }
|
||||
///
|
||||
/// File paths conform to the
|
||||
/// and <doc://com.apple.documentation/documentation/swift/equatable>
|
||||
/// and <doc://com.apple.documentation/documentation/swift/hashable> protocols
|
||||
/// by performing the protocols' operations on their raw byte contents.
|
||||
/// This conformance allows file paths to be used,
|
||||
/// for example, as keys in a dictionary.
|
||||
/// However, the rules for path equivalence
|
||||
/// are file-system–specific and have additional considerations
|
||||
/// like case insensitivity, Unicode normalization, and symbolic links.
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
public struct FilePath {
|
||||
internal var bytes: [CChar]
|
||||
|
||||
/// Creates an empty, null-terminated path.
|
||||
public init() {
|
||||
self.bytes = [0]
|
||||
_invariantCheck()
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: - Public Interfaces
|
||||
//
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
extension FilePath {
|
||||
/// The length of the file path, excluding the null termination.
|
||||
public var length: Int { bytes.count - 1 }
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
extension FilePath {
|
||||
internal init<C: Collection>(nullTerminatedBytes: C) where C.Element == CChar {
|
||||
self.bytes = Array(nullTerminatedBytes)
|
||||
_invariantCheck()
|
||||
}
|
||||
|
||||
internal init<C: Collection>(byteContents bytes: C) where C.Element == CChar {
|
||||
var nulTermBytes = Array(bytes)
|
||||
nulTermBytes.append(0)
|
||||
self.init(nullTerminatedBytes: nulTermBytes)
|
||||
}
|
||||
}
|
||||
|
||||
@_implementationOnly import SystemInternals
|
||||
|
||||
//
|
||||
// MARK: - CString interfaces
|
||||
//
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
extension FilePath {
|
||||
/// Creates a file path by copying bytes from a null-terminated C string.
|
||||
///
|
||||
/// - Parameter cString: A pointer to a null-terminated C string.
|
||||
public init(cString: UnsafePointer<CChar>) {
|
||||
self.init(nullTerminatedBytes:
|
||||
UnsafeBufferPointer(start: cString, count: 1 + system_strlen(cString)))
|
||||
}
|
||||
|
||||
/// Calls the given closure with a pointer to the contents of the file path,
|
||||
/// represented as a null-terminated C string.
|
||||
///
|
||||
/// - Parameter body: A closure with a pointer parameter
|
||||
/// that points to a null-terminated C string.
|
||||
/// If `body` has a return value,
|
||||
/// that value is also used as the return value for this method.
|
||||
/// - Returns: The return value, if any, of the `body` closure parameter.
|
||||
///
|
||||
/// The pointer passed as an argument to `body` is valid
|
||||
/// only during the execution of this method.
|
||||
/// Don't try to store the pointer for later use.
|
||||
public func withCString<Result>(
|
||||
_ body: (UnsafePointer<Int8>) throws -> Result
|
||||
) rethrows -> Result {
|
||||
try bytes.withUnsafeBufferPointer { try body($0.baseAddress!) }
|
||||
}
|
||||
|
||||
// TODO: in the future, with opaque result types with associated
|
||||
// type constraints, we want to provide a RAC for terminated
|
||||
// byte contents and unterminated byte contents.
|
||||
}
|
||||
|
||||
//
|
||||
// MARK: - String interfaces
|
||||
//
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
extension FilePath: ExpressibleByStringLiteral {
|
||||
/// Creates a file path from a string literal.
|
||||
///
|
||||
/// - Parameter stringLiteral: A string literal
|
||||
/// whose UTF-8 contents to use as the contents of the path.
|
||||
public init(stringLiteral: String) {
|
||||
self.init(stringLiteral)
|
||||
}
|
||||
|
||||
/// Creates a file path from a string.
|
||||
///
|
||||
/// - Parameter string: A string
|
||||
/// whose UTF-8 contents to use as the contents of the path.
|
||||
public init(_ string: String) {
|
||||
var str = string
|
||||
self = str.withUTF8 { FilePath(byteContents: $0._asCChar) }
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
extension String {
|
||||
/// Creates a string by interpreting the file path's content as UTF-8.
|
||||
///
|
||||
/// - Parameter path: The file path to be interpreted as UTF-8.
|
||||
///
|
||||
/// If the content of the file path
|
||||
/// isn't a well-formed UTF-8 string,
|
||||
/// this initializer removes invalid bytes or replaces them with U+FFFD.
|
||||
/// This means that, depending on the semantics of the specific file system,
|
||||
/// conversion to a string and back to a path
|
||||
/// might result in a value that's different from the original path.
|
||||
public init(decoding path: FilePath) {
|
||||
self = path.withCString { String(cString: $0) }
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "String.init(decoding:)")
|
||||
public init(_ path: FilePath) {
|
||||
self.init(decoding: path)
|
||||
}
|
||||
|
||||
/// Creates a string from a file path, validating its UTF-8 contents.
|
||||
///
|
||||
/// - Parameter path: The file path be interpreted as UTF-8.
|
||||
///
|
||||
/// If the contents of the file path
|
||||
/// isn't a well-formed UTF-8 string,
|
||||
/// this initializer returns `nil`.
|
||||
public init?(validatingUTF8 path: FilePath) {
|
||||
guard let str = path.withCString({ String(validatingUTF8: $0) }) else {
|
||||
return nil
|
||||
}
|
||||
self = str
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
extension FilePath: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
/// A textual representation of the file path.
|
||||
@inline(never)
|
||||
public var description: String { String(decoding: self) }
|
||||
|
||||
/// A textual representation of the file path, suitable for debugging.
|
||||
public var debugDescription: String { self.description.debugDescription }
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
extension FilePath: Hashable, Codable {}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
extension FilePath {
|
||||
fileprivate func _invariantCheck() {
|
||||
precondition(bytes.last! == 0)
|
||||
_debugPrecondition(bytes.firstIndex(of: 0) == bytes.count - 1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
/// Represents a location in the file system.
|
||||
///
|
||||
/// This structure recognizes directory separators (e.g. `/`), roots, and
|
||||
/// requires that the content terminates in a NUL (`0x0`). Beyond that, it
|
||||
/// does not give any meaning to the bytes that it contains. The file system
|
||||
/// defines how the content is interpreted; for example, by its choice of string
|
||||
/// encoding.
|
||||
///
|
||||
/// On construction, `FilePath` will normalize separators by removing
|
||||
/// redundant intermediary separators and stripping any trailing separators.
|
||||
/// On Windows, `FilePath` will also normalize forward slashes `/` into
|
||||
/// backslashes `\`, as preferred by the platform.
|
||||
///
|
||||
/// The code below creates a file path from a string literal,
|
||||
/// and then uses it to open and append to a log file:
|
||||
///
|
||||
/// let message: String = "This is a log message."
|
||||
/// let path: FilePath = "/tmp/log"
|
||||
/// let fd = try FileDescriptor.open(path, .writeOnly, options: .append)
|
||||
/// try fd.closeAfter { try fd.writeAll(message.utf8) }
|
||||
///
|
||||
/// File paths conform to the
|
||||
/// <doc://com.apple.documentation/documentation/swift/equatable>
|
||||
/// and <doc://com.apple.documentation/documentation/swift/hashable> protocols
|
||||
/// by performing the protocols' operations on their raw byte contents.
|
||||
/// This conformance allows file paths to be used,
|
||||
/// for example, as keys in a dictionary.
|
||||
/// However, the rules for path equivalence
|
||||
/// are file-system–specific and have additional considerations
|
||||
/// like case insensitivity, Unicode normalization, and symbolic links.
|
||||
///
|
||||
// TODO(docs): Section on all the new syntactic operations, lexical normalization, decomposition,
|
||||
// components, etc.
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
public struct FilePath {
|
||||
internal var _storage: SystemString
|
||||
|
||||
/// Creates an empty, null-terminated path.
|
||||
public init() {
|
||||
self._storage = SystemString()
|
||||
_invariantCheck()
|
||||
}
|
||||
|
||||
// In addition to the empty init, this init will properly normalize
|
||||
// separators. All other initializers should be implemented by
|
||||
// ultimately deferring to a normalizing init.
|
||||
internal init(_ str: SystemString) {
|
||||
self._storage = str
|
||||
self._normalizeSeparators()
|
||||
_invariantCheck()
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension FilePath {
|
||||
/// The length of the file path, excluding the null terminator.
|
||||
public var length: Int { _storage.length }
|
||||
}
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension FilePath: Hashable, Codable {}
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
/*
|
||||
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
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath {
|
||||
/// A bidirectional, range replaceable collection of the non-root components
|
||||
/// that make up a file path.
|
||||
///
|
||||
/// ComponentView provides access to standard `BidirectionalCollection`
|
||||
/// algorithms for accessing components from the front or back, as well as
|
||||
/// standard `RangeReplaceableCollection` algorithms for modifying the
|
||||
/// file path using component or range of components granularity.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// var path: FilePath = "/./home/./username/scripts/./tree"
|
||||
/// let scriptIdx = path.components.lastIndex(of: "scripts")!
|
||||
/// path.components.insert("bin", at: scriptIdx)
|
||||
/// // path is "/./home/./username/bin/scripts/./tree"
|
||||
///
|
||||
/// path.components.removeAll { $0.kind == .currentDirectory }
|
||||
/// // path is "/home/username/bin/scripts/tree"
|
||||
///
|
||||
public struct ComponentView {
|
||||
internal var _path: FilePath
|
||||
internal var _start: SystemString.Index
|
||||
|
||||
internal init(_ path: FilePath) {
|
||||
self._path = path
|
||||
self._start = path._relativeStart
|
||||
_invariantCheck()
|
||||
}
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
/// View the non-root components that make up this path.
|
||||
public var components: ComponentView {
|
||||
get { ComponentView(self) }
|
||||
_modify {
|
||||
// RRC's empty init means that we can't guarantee that the yielded
|
||||
// view will restore our root. So copy it out first.
|
||||
//
|
||||
// TODO(perf): Small-form root (especially on Unix). Have Root
|
||||
// always copy out (not worth ref counting). Make sure that we're
|
||||
// not needlessly sliding values around or triggering a COW
|
||||
let rootStr = self.root?._systemString ?? SystemString()
|
||||
var comp = ComponentView(self)
|
||||
self = FilePath()
|
||||
defer {
|
||||
self = comp._path
|
||||
if root?._slice.elementsEqual(rootStr) != true {
|
||||
self.root = Root(rootStr)
|
||||
}
|
||||
}
|
||||
yield &comp
|
||||
}
|
||||
}
|
||||
#else
|
||||
/// View the non-root components that make up this path.
|
||||
public var components: ComponentView {
|
||||
__consuming get { ComponentView(self) }
|
||||
_modify {
|
||||
// RRC's empty init means that we can't guarantee that the yielded
|
||||
// view will restore our root. So copy it out first.
|
||||
//
|
||||
// TODO(perf): Small-form root (especially on Unix). Have Root
|
||||
// always copy out (not worth ref counting). Make sure that we're
|
||||
// not needlessly sliding values around or triggering a COW
|
||||
let rootStr = self.root?._systemString ?? SystemString()
|
||||
var comp = ComponentView(self)
|
||||
self = FilePath()
|
||||
defer {
|
||||
self = comp._path
|
||||
if root?._slice.elementsEqual(rootStr) != true {
|
||||
self.root = Root(rootStr)
|
||||
}
|
||||
}
|
||||
yield &comp
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath.ComponentView: BidirectionalCollection {
|
||||
public typealias Element = FilePath.Component
|
||||
public struct Index: Comparable, Hashable {
|
||||
internal typealias Storage = SystemString.Index
|
||||
|
||||
internal var _storage: Storage
|
||||
|
||||
public static func < (lhs: Self, rhs: Self) -> Bool {
|
||||
lhs._storage < rhs._storage
|
||||
}
|
||||
|
||||
fileprivate init(_ idx: Storage) {
|
||||
self._storage = idx
|
||||
}
|
||||
}
|
||||
|
||||
public var startIndex: Index { Index(_start) }
|
||||
public var endIndex: Index { Index(_path._storage.endIndex) }
|
||||
|
||||
public func index(after i: Index) -> Index {
|
||||
return Index(_path._parseComponent(startingAt: i._storage).nextStart)
|
||||
}
|
||||
|
||||
public func index(before i: Index) -> Index {
|
||||
Index(_path._parseComponent(priorTo: i._storage).lowerBound)
|
||||
}
|
||||
|
||||
public subscript(position: Index) -> FilePath.Component {
|
||||
let end = _path._parseComponent(startingAt: position._storage).componentEnd
|
||||
return FilePath.Component(_path, position._storage ..< end)
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath.ComponentView: RangeReplaceableCollection {
|
||||
public init() {
|
||||
self.init(FilePath())
|
||||
}
|
||||
|
||||
// TODO(perf): We probably want to have concrete overrides or generic
|
||||
// specializations taking FP.ComponentView and
|
||||
// FP.ComponentView.SubSequence because we
|
||||
// can just memcpy in those cases. We
|
||||
// probably want to do that for all RRC operations.
|
||||
|
||||
public mutating func replaceSubrange<C>(
|
||||
_ subrange: Range<Index>, with newElements: C
|
||||
) where C : Collection, Self.Element == C.Element {
|
||||
defer {
|
||||
_path._invariantCheck()
|
||||
_invariantCheck()
|
||||
}
|
||||
if isEmpty {
|
||||
_path = FilePath(root: _path.root, newElements)
|
||||
return
|
||||
}
|
||||
let range = subrange.lowerBound._storage ..< subrange.upperBound._storage
|
||||
if newElements.isEmpty {
|
||||
let fromEnd = subrange.upperBound == endIndex
|
||||
_path._storage.removeSubrange(range)
|
||||
if fromEnd {
|
||||
_path._removeTrailingSeparator()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// TODO(perf): Avoid extra allocation by sliding elements down and
|
||||
// filling in the bytes ourselves.
|
||||
|
||||
// If we're inserting at the end, we need a leading separator.
|
||||
var str = SystemString()
|
||||
let atEnd = subrange.lowerBound == endIndex
|
||||
if atEnd {
|
||||
str.append(platformSeparator)
|
||||
}
|
||||
str.appendComponents(components: newElements)
|
||||
if !atEnd {
|
||||
str.append(platformSeparator)
|
||||
}
|
||||
_path._storage.replaceSubrange(range, with: str)
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath {
|
||||
/// Create a file path from a root and a collection of components.
|
||||
public init<C: Collection>(
|
||||
root: Root?, _ components: C
|
||||
) where C.Element == Component {
|
||||
var str = root?._systemString ?? SystemString()
|
||||
str.appendComponents(components: components)
|
||||
self.init(str)
|
||||
}
|
||||
|
||||
/// Create a file path from a root and any number of components.
|
||||
public init(root: Root?, components: Component...) {
|
||||
self.init(root: root, components)
|
||||
}
|
||||
|
||||
/// Create a file path from an optional root and a slice of another path's
|
||||
/// components.
|
||||
public init(root: Root?, _ components: ComponentView.SubSequence) {
|
||||
var str = root?._systemString ?? SystemString()
|
||||
let (start, end) =
|
||||
(components.startIndex._storage, components.endIndex._storage)
|
||||
str.append(contentsOf: components.base._slice[start..<end])
|
||||
self.init(str)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Internals
|
||||
|
||||
extension FilePath.ComponentView: _PathSlice {
|
||||
internal var _range: Range<SystemString.Index> {
|
||||
_start ..< _path._storage.endIndex
|
||||
}
|
||||
|
||||
internal init(_ str: SystemString) {
|
||||
fatalError("TODO: consider dropping proto req")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Invariants
|
||||
|
||||
extension FilePath.ComponentView {
|
||||
internal func _invariantCheck() {
|
||||
#if DEBUG
|
||||
if isEmpty {
|
||||
precondition(_path.isEmpty == (_path.root == nil))
|
||||
return
|
||||
}
|
||||
|
||||
// If path has a root,
|
||||
if _path.root != nil {
|
||||
precondition(first!._slice.startIndex > _path._storage.startIndex)
|
||||
precondition(first!._slice.startIndex == _path._relativeStart)
|
||||
}
|
||||
|
||||
self.forEach { $0._invariantCheck() }
|
||||
|
||||
if let base = last {
|
||||
precondition(base._slice.endIndex == _path._storage.endIndex)
|
||||
}
|
||||
|
||||
precondition(FilePath(root: _path.root, self) == _path)
|
||||
#endif // DEBUG
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
/*
|
||||
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
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
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
|
||||
internal 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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
internal 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)
|
||||
}
|
||||
|
||||
internal init?(_platformString s: UnsafePointer<CInterop.PlatformChar>) {
|
||||
self.init(SystemString(platformString: s))
|
||||
}
|
||||
|
||||
internal 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 {
|
||||
internal var _storage: SystemString { _path._storage }
|
||||
}
|
||||
|
||||
extension FilePath.Component: _PathSlice {
|
||||
}
|
||||
extension FilePath.Root: _PathSlice {
|
||||
internal var _range: Range<SystemString.Index> {
|
||||
(..<_rootEnd).relative(to: _path._storage)
|
||||
}
|
||||
}
|
||||
extension FilePath: _PlatformStringable {
|
||||
@usableFromInline
|
||||
func _withPlatformString<Result>(_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result) rethrows -> Result {
|
||||
try _storage.withPlatformString(body)
|
||||
}
|
||||
|
||||
init(_platformString: UnsafePointer<CInterop.PlatformChar>) {
|
||||
self.init(SystemString(platformString: _platformString))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
extension FilePath.Component {
|
||||
internal 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()
|
||||
}
|
||||
}
|
||||
|
||||
extension FilePath.Root {
|
||||
internal 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
|
||||
|
||||
extension FilePath.Component {
|
||||
// TODO: ensure this all gets easily optimized away in release...
|
||||
internal func _invariantCheck() {
|
||||
#if DEBUG
|
||||
precondition(!_slice.isEmpty)
|
||||
precondition(_slice.last != .null)
|
||||
precondition(_slice.allSatisfy { !isSeparator($0) } )
|
||||
precondition(_path._relativeStart <= _slice.startIndex)
|
||||
#endif // DEBUG
|
||||
}
|
||||
}
|
||||
extension FilePath.Root {
|
||||
internal func _invariantCheck() {
|
||||
#if DEBUG
|
||||
precondition(self._rootEnd > _path._storage.startIndex)
|
||||
|
||||
// TODO: Windows root invariants
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// FIXME: Need to rewrite and simplify this code now that SystemString
|
||||
// manages (and hides) the null terminator
|
||||
|
||||
// The separator we use internally
|
||||
private var genericSeparator: SystemChar { .slash }
|
||||
|
||||
// The platform preferred separator
|
||||
//
|
||||
// TODO: Make private
|
||||
internal var platformSeparator: SystemChar {
|
||||
_windowsPaths ? .backslash : genericSeparator
|
||||
}
|
||||
|
||||
// Whether the character is the canonical separator
|
||||
// TODO: Make private
|
||||
internal func isSeparator(_ c: SystemChar) -> Bool {
|
||||
c == platformSeparator
|
||||
}
|
||||
|
||||
// Whether the character is a pre-normalized separator
|
||||
internal func isPrenormalSeparator(_ c: SystemChar) -> Bool {
|
||||
c == genericSeparator || c == platformSeparator
|
||||
}
|
||||
|
||||
// Separator normalization, checking, and root parsing is internally hosted
|
||||
// on SystemString for ease of unit testing.
|
||||
|
||||
extension SystemString {
|
||||
// For invariant enforcing/checking. Should always return false on
|
||||
// a fully-formed path
|
||||
fileprivate func _hasTrailingSeparator() -> Bool {
|
||||
// Just a root: do nothing
|
||||
guard _relativePathStart != endIndex else { return false }
|
||||
assert(!isEmpty)
|
||||
|
||||
return isSeparator(self.last!)
|
||||
}
|
||||
|
||||
// Enforce invariants by removing a trailing separator.
|
||||
//
|
||||
// Precondition: There is exactly zero or one trailing slashes
|
||||
//
|
||||
// Postcondition: Path is root, or has no trailing separator
|
||||
internal mutating func _removeTrailingSeparator() {
|
||||
if _hasTrailingSeparator() {
|
||||
self.removeLast()
|
||||
assert(!_hasTrailingSeparator())
|
||||
}
|
||||
}
|
||||
|
||||
// Enforce invariants by normalizing the internal separator representation.
|
||||
//
|
||||
// 1) Normalize all separators to platform-preferred separator
|
||||
// 2) Drop redundant separators
|
||||
// 3) Drop trailing separators
|
||||
//
|
||||
// On Windows, UNC and device paths are allowed to begin with two separators,
|
||||
// and partial or mal-formed roots are completed.
|
||||
//
|
||||
// The POSIX standard does allow two leading separators to
|
||||
// denote implementation-specific handling, but Darwin and Linux
|
||||
// do not treat these differently.
|
||||
//
|
||||
internal mutating func _normalizeSeparators() {
|
||||
guard !isEmpty else { return }
|
||||
var (writeIdx, readIdx) = (startIndex, startIndex)
|
||||
|
||||
if _windowsPaths {
|
||||
// Normalize forwards slashes to backslashes.
|
||||
//
|
||||
// NOTE: Ideally this would be done as part of separator coalescing
|
||||
// below. However, prenormalizing roots such as UNC paths requires
|
||||
// parsing and (potentially) fixing up semi-formed roots. This
|
||||
// normalization reduces the complexity of the task by allowing us to
|
||||
// use a read-only lexer.
|
||||
self._replaceAll(genericSeparator, with: platformSeparator)
|
||||
|
||||
// Windows roots can have meaningful repeated backslashes or may
|
||||
// need backslashes inserted for partially-formed roots. Delegate that to
|
||||
// `_prenormalizeWindowsRoots` and resume.
|
||||
readIdx = _prenormalizeWindowsRoots()
|
||||
writeIdx = readIdx
|
||||
} else {
|
||||
assert(genericSeparator == platformSeparator)
|
||||
}
|
||||
|
||||
while readIdx < endIndex {
|
||||
assert(writeIdx <= readIdx)
|
||||
|
||||
// Swap and advance our indices.
|
||||
let wasSeparator = isSeparator(self[readIdx])
|
||||
self.swapAt(writeIdx, readIdx)
|
||||
self.formIndex(after: &writeIdx)
|
||||
self.formIndex(after: &readIdx)
|
||||
|
||||
while wasSeparator, readIdx < endIndex, isSeparator(self[readIdx]) {
|
||||
self.formIndex(after: &readIdx)
|
||||
}
|
||||
}
|
||||
self.removeLast(self.distance(from: writeIdx, to: readIdx))
|
||||
self._removeTrailingSeparator()
|
||||
}
|
||||
}
|
||||
|
||||
extension FilePath {
|
||||
internal mutating func _removeTrailingSeparator() {
|
||||
_storage._removeTrailingSeparator()
|
||||
}
|
||||
|
||||
internal mutating func _normalizeSeparators() {
|
||||
_storage._normalizeSeparators()
|
||||
}
|
||||
|
||||
// Remove any `.` and `..` components
|
||||
internal mutating func _normalizeSpecialDirectories() {
|
||||
guard !isLexicallyNormal else { return }
|
||||
defer { assert(isLexicallyNormal) }
|
||||
|
||||
let relStart = _relativeStart
|
||||
let hasRoot = relStart != _storage.startIndex
|
||||
|
||||
// TODO: all this logic might be nicer if _parseComponent considered
|
||||
// the null character index to be the next start...
|
||||
|
||||
var (writeIdx, readIdx) = (relStart, relStart)
|
||||
while readIdx < _storage.endIndex {
|
||||
let (compEnd, nextStart) = _parseComponent(startingAt: readIdx)
|
||||
assert(readIdx < nextStart && compEnd <= nextStart)
|
||||
let component = readIdx..<compEnd
|
||||
|
||||
// `.` is skipped over
|
||||
if _isCurrentDirectory(component) {
|
||||
readIdx = nextStart
|
||||
continue
|
||||
}
|
||||
|
||||
// `..`s are preserved at the very beginning of a relative path,
|
||||
// otherwise parse-back a component to remove the parent (but stop at
|
||||
// root).
|
||||
if _isParentDirectory(component) {
|
||||
// Skip over it if we're at the root
|
||||
if hasRoot && writeIdx == relStart {
|
||||
readIdx = nextStart
|
||||
continue
|
||||
}
|
||||
|
||||
// Drop the parent (unless we're preserving `..`s)
|
||||
if writeIdx != relStart {
|
||||
let priorComponent = _parseComponent(priorTo: writeIdx)
|
||||
|
||||
if !_isParentDirectory(priorComponent) {
|
||||
writeIdx = priorComponent.lowerBound
|
||||
readIdx = nextStart
|
||||
continue
|
||||
}
|
||||
assert(self.root == nil && self.components.first!.kind == .parentDirectory)
|
||||
}
|
||||
}
|
||||
|
||||
if readIdx == writeIdx {
|
||||
(readIdx, writeIdx) = (nextStart, nextStart)
|
||||
continue
|
||||
}
|
||||
while readIdx != nextStart {
|
||||
_storage.swapAt(readIdx, writeIdx)
|
||||
readIdx = _storage.index(after: readIdx)
|
||||
writeIdx = _storage.index(after: writeIdx)
|
||||
}
|
||||
}
|
||||
|
||||
assert(readIdx == _storage.endIndex && readIdx >= writeIdx)
|
||||
if readIdx != writeIdx {
|
||||
_storage.removeSubrange(writeIdx...)
|
||||
_removeTrailingSeparator()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SystemString {
|
||||
internal var _relativePathStart: Index {
|
||||
_parseRoot().relativeBegin
|
||||
}
|
||||
}
|
||||
|
||||
extension FilePath {
|
||||
internal var _relativeStart: SystemString.Index {
|
||||
_storage._relativePathStart
|
||||
}
|
||||
internal var _hasRoot: Bool {
|
||||
_relativeStart != _storage.startIndex
|
||||
}
|
||||
}
|
||||
|
||||
// Parse separators
|
||||
|
||||
extension FilePath {
|
||||
internal typealias _Index = SystemString.Index
|
||||
|
||||
// Parse a component that starts at `i`. Returns the end
|
||||
// of the component and the start of the next. Parsing terminates
|
||||
// at the index of the null byte.
|
||||
internal func _parseComponent(
|
||||
startingAt i: _Index
|
||||
) -> (componentEnd: _Index, nextStart: _Index) {
|
||||
assert(i < _storage.endIndex)
|
||||
// Parse the root
|
||||
if i == _storage.startIndex {
|
||||
let relativeStart = _relativeStart
|
||||
if i != relativeStart {
|
||||
return (relativeStart, relativeStart)
|
||||
}
|
||||
}
|
||||
|
||||
assert(!isSeparator(_storage[i]))
|
||||
guard let nextSep = _storage[i...].firstIndex(where: isSeparator) else {
|
||||
return (_storage.endIndex, _storage.endIndex)
|
||||
}
|
||||
return (nextSep, _storage.index(after: nextSep))
|
||||
}
|
||||
|
||||
// Parse a component prior to the one that starts at `i`. Returns
|
||||
// the start of the prior component. If `i` is the index of null,
|
||||
// returns the last component.
|
||||
internal func _parseComponent(
|
||||
priorTo i: _Index
|
||||
) -> Range<_Index> {
|
||||
precondition(i > _storage.startIndex)
|
||||
let relStart = _relativeStart
|
||||
|
||||
if i == relStart { return _storage.startIndex..<relStart }
|
||||
assert(i > relStart)
|
||||
|
||||
var slice = _storage[..<i]
|
||||
if i != _storage.endIndex {
|
||||
assert(isSeparator(slice.last!))
|
||||
slice.removeLast()
|
||||
}
|
||||
let end = slice.endIndex
|
||||
while slice.endIndex != relStart, let c = slice.last, !isSeparator(c) {
|
||||
slice.removeLast()
|
||||
}
|
||||
|
||||
return slice.endIndex ..< end
|
||||
}
|
||||
|
||||
internal func _isCurrentDirectory(_ component: Range<_Index>) -> Bool {
|
||||
_storage[component].elementsEqual([.dot])
|
||||
}
|
||||
|
||||
internal func _isParentDirectory(_ component: Range<_Index>) -> Bool {
|
||||
_storage[component].elementsEqual([.dot, .dot])
|
||||
}
|
||||
|
||||
internal func _isSpecialDirectory(_ component: Range<_Index>) -> Bool {
|
||||
_isCurrentDirectory(component) || _isParentDirectory(component)
|
||||
}
|
||||
}
|
||||
|
||||
extension FilePath.ComponentView {
|
||||
// TODO: Store this...
|
||||
internal var _relativeStart: SystemString.Index {
|
||||
_path._relativeStart
|
||||
}
|
||||
}
|
||||
|
||||
extension SystemString {
|
||||
internal func _parseRoot() -> (
|
||||
rootEnd: Index, relativeBegin: Index
|
||||
) {
|
||||
guard !isEmpty else { return (startIndex, startIndex) }
|
||||
|
||||
// Windows roots are more complex
|
||||
if _windowsPaths { return _parseWindowsRoot() }
|
||||
|
||||
// A leading `/` is a root
|
||||
guard isSeparator(self.first!) else { return (startIndex, startIndex) }
|
||||
|
||||
let next = self.index(after: startIndex)
|
||||
return (next, next)
|
||||
}
|
||||
}
|
||||
|
||||
extension FilePath.Root {
|
||||
// Asserting self is a root, returns whether this is an
|
||||
// absolute root.
|
||||
//
|
||||
// On Unix, all roots are absolute. On Windows, `\` and `X:` are
|
||||
// relative roots
|
||||
//
|
||||
// TODO: public
|
||||
internal var isAbsolute: Bool {
|
||||
assert(FilePath(SystemString(self._slice)).root == self, "not a root")
|
||||
|
||||
guard _windowsPaths else { return true }
|
||||
|
||||
// `\` or `C:` are the only form of relative roots, and all
|
||||
// absolute roots are at least 3 chars long.
|
||||
let slice = self._slice
|
||||
guard slice.count < 3 else { return true }
|
||||
assert(
|
||||
(slice.count == 1 && slice.first == .backslash) ||
|
||||
(slice.count == 2 && slice.last == .colon))
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
extension FilePath {
|
||||
internal var _portableDescription: String {
|
||||
guard _windowsPaths else { return description }
|
||||
let utf8 = description.utf8.map { $0 == UInt8(ascii: #"\"#) ? UInt8(ascii: "/") : $0 }
|
||||
return String(decoding: utf8, as: UTF8.self)
|
||||
}
|
||||
}
|
||||
|
||||
// Whether we are providing Windows paths
|
||||
@inline(__always)
|
||||
internal var _windowsPaths: Bool {
|
||||
#if os(Windows)
|
||||
return true
|
||||
#else
|
||||
return forceWindowsPaths
|
||||
#endif
|
||||
}
|
||||
|
||||
extension FilePath {
|
||||
// Whether we should add a separator when doing an append
|
||||
internal var _needsSeparatorForAppend: Bool {
|
||||
guard let last = _storage.last, !isSeparator(last) else { return false }
|
||||
|
||||
// On Windows, we can have a path of the form `C:` which is a root and
|
||||
// does not need a separator after it
|
||||
if _windowsPaths && _relativeStart == _storage.endIndex {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Perform an append, inseting a separator if needed.
|
||||
// Note that this will not check whether `content` is a root
|
||||
internal mutating func _append(unchecked content: Slice<SystemString>) {
|
||||
assert(FilePath(SystemString(content)).root == nil)
|
||||
if content.isEmpty { return }
|
||||
if _needsSeparatorForAppend {
|
||||
_storage.append(platformSeparator)
|
||||
}
|
||||
_storage.append(contentsOf: content)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Invariants
|
||||
extension FilePath {
|
||||
internal func _invariantCheck() {
|
||||
#if DEBUG
|
||||
var normal = self
|
||||
normal._normalizeSeparators()
|
||||
precondition(self == normal)
|
||||
precondition(!self._storage._hasTrailingSeparator())
|
||||
precondition(_hasRoot == (self.root != nil))
|
||||
#endif // DEBUG
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,584 @@
|
||||
/*
|
||||
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: - Platform string
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath {
|
||||
/// Creates a file path by copying bytes from a null-terminated platform
|
||||
/// string.
|
||||
///
|
||||
/// - Parameter platformString: A pointer to a null-terminated platform
|
||||
/// string.
|
||||
public init(platformString: UnsafePointer<CInterop.PlatformChar>) {
|
||||
self.init(_platformString: platformString)
|
||||
}
|
||||
|
||||
/// Creates a file path by copying bytes from a null-terminated platform
|
||||
/// string.
|
||||
///
|
||||
/// - Note It is a precondition that `platformString` must be null-terminated.
|
||||
/// The absence of a null byte will trigger a runtime error.
|
||||
///
|
||||
/// - Parameter platformString: A null-terminated platform string.
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
public init(platformString: [CInterop.PlatformChar]) {
|
||||
guard let _ = platformString.firstIndex(of: 0) else {
|
||||
fatalError(
|
||||
"input of FilePath.init(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
self = platformString.withUnsafeBufferPointer {
|
||||
FilePath(platformString: $0.baseAddress!)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use FilePath.init(_ scalar: Unicode.Scalar)")
|
||||
public init(platformString: inout CInterop.PlatformChar) {
|
||||
guard platformString == 0 else {
|
||||
fatalError(
|
||||
"input of FilePath.init(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
self = FilePath()
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use FilePath(_: String) to create a path from a String")
|
||||
public init(platformString: String) {
|
||||
if let nullLoc = platformString.firstIndex(of: "\0") {
|
||||
self = FilePath(String(platformString[..<nullLoc]))
|
||||
} else {
|
||||
self = FilePath(platformString)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure with a pointer to the contents of the file path,
|
||||
/// represented as a null-terminated platform string.
|
||||
///
|
||||
/// - Parameter body: A closure with a pointer parameter
|
||||
/// that points to a null-terminated platform string.
|
||||
/// If `body` has a return value,
|
||||
/// that value is also used as the return value for this method.
|
||||
/// - Returns: The return value, if any, of the `body` closure parameter.
|
||||
///
|
||||
/// The pointer passed as an argument to `body` is valid
|
||||
/// only during the execution of this method.
|
||||
/// Don't try to store the pointer for later use.
|
||||
@_alwaysEmitIntoClient
|
||||
public func withPlatformString<Result>(
|
||||
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
|
||||
) rethrows -> Result {
|
||||
// For backwards deployment, call withCString if available.
|
||||
#if !os(Windows)
|
||||
return try withCString(body)
|
||||
#else
|
||||
return try _withPlatformString(body)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath.Component {
|
||||
/// Creates a file path component by copying bytes from a null-terminated
|
||||
/// platform string.
|
||||
///
|
||||
/// Returns `nil` if `platformString` is empty, is a root, or has more than
|
||||
/// one component in it.
|
||||
///
|
||||
/// - Parameter platformString: A pointer to a null-terminated platform
|
||||
/// string.
|
||||
///
|
||||
public init?(platformString: UnsafePointer<CInterop.PlatformChar>) {
|
||||
self.init(_platformString: platformString)
|
||||
}
|
||||
|
||||
/// Creates a file path component by copying bytes from a null-terminated
|
||||
/// platform string. It is a precondition that a null byte indicates the end of
|
||||
/// the string. The absence of a null byte will trigger a runtime error.
|
||||
///
|
||||
/// Returns `nil` if `platformString` is empty, is a root, or has more than
|
||||
/// one component in it.
|
||||
///
|
||||
/// - Note It is a precondition that `platformString` must be null-terminated.
|
||||
/// The absence of a null byte will trigger a runtime error.
|
||||
///
|
||||
/// - Parameter platformString: A null-terminated platform string.
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
public init?(platformString: [CInterop.PlatformChar]) {
|
||||
guard let _ = platformString.firstIndex(of: 0) else {
|
||||
fatalError(
|
||||
"input of FilePath.Component.init?(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
guard let component = platformString.withUnsafeBufferPointer({
|
||||
FilePath.Component(platformString: $0.baseAddress!)
|
||||
}) else {
|
||||
return nil
|
||||
}
|
||||
self = component
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use FilePath.Component.init(_ scalar: Unicode.Scalar)")
|
||||
public init?(platformString: inout CInterop.PlatformChar) {
|
||||
guard platformString == 0 else {
|
||||
fatalError(
|
||||
"input of FilePath.Component.init?(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use FilePath.Component.init(_: String)")
|
||||
public init?(platformString: String) {
|
||||
let string: String
|
||||
if let nullLoc = platformString.firstIndex(of: "\0") {
|
||||
string = String(platformString[..<nullLoc])
|
||||
} else {
|
||||
string = platformString
|
||||
}
|
||||
guard let component = FilePath.Component(string) else { return nil }
|
||||
self = component
|
||||
}
|
||||
|
||||
/// Calls the given closure with a pointer to the contents of the file path
|
||||
/// component, represented as a null-terminated platform string.
|
||||
///
|
||||
/// If this is not the last component of a path, an allocation will occur in
|
||||
/// order to add the null terminator.
|
||||
///
|
||||
/// - Parameter body: A closure with a pointer parameter
|
||||
/// that points to a null-terminated platform string.
|
||||
/// If `body` has a return value,
|
||||
/// that value is also used as the return value for this method.
|
||||
/// - Returns: The return value, if any, of the `body` closure parameter.
|
||||
///
|
||||
/// The pointer passed as an argument to `body` is valid
|
||||
/// only during the execution of this method.
|
||||
/// Don't try to store the pointer for later use.
|
||||
public func withPlatformString<Result>(
|
||||
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
|
||||
) rethrows -> Result {
|
||||
try _withPlatformString(body)
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath.Root {
|
||||
/// Creates a file path root by copying bytes from a null-terminated platform
|
||||
/// string.
|
||||
///
|
||||
/// Returns `nil` if `platformString` is empty or is not a root.
|
||||
///
|
||||
/// - Parameter platformString: A pointer to a null-terminated platform
|
||||
/// string.
|
||||
///
|
||||
public init?(platformString: UnsafePointer<CInterop.PlatformChar>) {
|
||||
self.init(_platformString: platformString)
|
||||
}
|
||||
|
||||
/// Creates a file path root by copying bytes from a null-terminated platform
|
||||
/// string. It is a precondition that a null byte indicates the end of
|
||||
/// the string. The absence of a null byte will trigger a runtime error.
|
||||
///
|
||||
/// Returns `nil` if `platformString` is empty or is not a root.
|
||||
///
|
||||
/// - Note It is a precondition that `platformString` must be null-terminated.
|
||||
/// The absence of a null byte will trigger a runtime error.
|
||||
///
|
||||
/// - Parameter platformString: A null-terminated platform string.
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
public init?(platformString: [CInterop.PlatformChar]) {
|
||||
guard let _ = platformString.firstIndex(of: 0) else {
|
||||
fatalError(
|
||||
"input of FilePath.Root.init?(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
guard let component = platformString.withUnsafeBufferPointer({
|
||||
FilePath.Root(platformString: $0.baseAddress!)
|
||||
}) else {
|
||||
return nil
|
||||
}
|
||||
self = component
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use FilePath.Root.init(_ scalar: Unicode.Scalar)")
|
||||
public init?(platformString: inout CInterop.PlatformChar) {
|
||||
guard platformString == 0 else {
|
||||
fatalError(
|
||||
"input of FilePath.Root.init?(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use FilePath.Root.init(_: String)")
|
||||
public init?(platformString: String) {
|
||||
let string: String
|
||||
if let nullLoc = platformString.firstIndex(of: "\0") {
|
||||
string = String(platformString[..<nullLoc])
|
||||
} else {
|
||||
string = platformString
|
||||
}
|
||||
guard let root = FilePath.Root(string) else { return nil }
|
||||
self = root
|
||||
}
|
||||
|
||||
/// Calls the given closure with a pointer to the contents of the file path
|
||||
/// root, represented as a null-terminated platform string.
|
||||
///
|
||||
/// If the path has a relative portion, an allocation will occur in order to
|
||||
/// add the null terminator.
|
||||
///
|
||||
/// - Parameter body: A closure with a pointer parameter
|
||||
/// that points to a null-terminated platform string.
|
||||
/// If `body` has a return value,
|
||||
/// that value is also used as the return value for this method.
|
||||
/// - Returns: The return value, if any, of the `body` closure parameter.
|
||||
///
|
||||
/// The pointer passed as an argument to `body` is valid
|
||||
/// only during the execution of this method.
|
||||
/// Don't try to store the pointer for later use.
|
||||
public func withPlatformString<Result>(
|
||||
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
|
||||
) rethrows -> Result {
|
||||
try _withPlatformString(body)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - String literals
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension FilePath: ExpressibleByStringLiteral {
|
||||
/// Creates a file path from a string literal.
|
||||
///
|
||||
/// - Parameter stringLiteral: A string literal
|
||||
/// whose Unicode encoded contents to use as the contents of the path.
|
||||
public init(stringLiteral: String) {
|
||||
self.init(stringLiteral)
|
||||
}
|
||||
|
||||
/// Creates a file path from a string.
|
||||
///
|
||||
/// - Parameter string: A string
|
||||
/// whose Unicode encoded contents to use as the contents of the path.
|
||||
public init(_ string: String) {
|
||||
self.init(SystemString(string))
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath.Component: ExpressibleByStringLiteral {
|
||||
/// Create a file path component from a string literal.
|
||||
///
|
||||
/// Precondition: `stringLiteral` is non-empty, is not a root,
|
||||
/// and has only one component in it.
|
||||
public init(stringLiteral: String) {
|
||||
guard let s = FilePath.Component(stringLiteral) else {
|
||||
// TODO: static assert
|
||||
fatalError("""
|
||||
FilePath.Component must be created from exactly one non-root component
|
||||
""")
|
||||
}
|
||||
self = s
|
||||
}
|
||||
|
||||
/// Create a file path component from a string.
|
||||
///
|
||||
/// Returns `nil` if `string` is empty, a root, or has more than one component
|
||||
/// in it.
|
||||
public init?(_ string: String) {
|
||||
self.init(SystemString(string))
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath.Root: ExpressibleByStringLiteral {
|
||||
/// Create a file path root from a string literal.
|
||||
///
|
||||
/// Precondition: `stringLiteral` is non-empty and is a root.
|
||||
public init(stringLiteral: String) {
|
||||
guard let s = FilePath.Root(stringLiteral) else {
|
||||
// TODO: static assert
|
||||
fatalError("""
|
||||
FilePath.Root must be created from a root
|
||||
""")
|
||||
}
|
||||
self = s
|
||||
}
|
||||
|
||||
/// Create a file path root from a string.
|
||||
///
|
||||
/// Returns `nil` if `string` is empty or is not a root.
|
||||
public init?(_ string: String) {
|
||||
self.init(SystemString(string))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Printing and dumping
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension FilePath: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
/// A textual representation of the file path.
|
||||
///
|
||||
/// If the content of the path isn't a well-formed Unicode string,
|
||||
/// this replaces invalid bytes with U+FFFD. See `String.init(decoding:)`
|
||||
@inline(never)
|
||||
public var description: String { String(decoding: self) }
|
||||
|
||||
/// A textual representation of the file path, suitable for debugging.
|
||||
///
|
||||
/// If the content of the path isn't a well-formed Unicode string,
|
||||
/// this replaces invalid bytes with U+FFFD. See `String.init(decoding:)`
|
||||
public var debugDescription: String { description.debugDescription }
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath.Component: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
|
||||
/// A textual representation of the path component.
|
||||
///
|
||||
/// If the content of the path component isn't a well-formed Unicode string,
|
||||
/// this replaces invalid bytes with U+FFFD. See `String.init(decoding:)`.
|
||||
@inline(never)
|
||||
public var description: String { String(decoding: self) }
|
||||
|
||||
/// A textual representation of the path component, suitable for debugging.
|
||||
///
|
||||
/// If the content of the path component isn't a well-formed Unicode string,
|
||||
/// this replaces invalid bytes with U+FFFD. See `String.init(decoding:)`.
|
||||
public var debugDescription: String { description.debugDescription }
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath.Root: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
|
||||
/// A textual representation of the path root.
|
||||
///
|
||||
/// If the content of the path root isn't a well-formed Unicode string,
|
||||
/// this replaces invalid bytes with U+FFFD. See `String.init(decoding:)`.
|
||||
@inline(never)
|
||||
public var description: String { String(decoding: self) }
|
||||
|
||||
/// A textual representation of the path root, suitable for debugging.
|
||||
///
|
||||
/// If the content of the path root isn't a well-formed Unicode string,
|
||||
/// this replaces invalid bytes with U+FFFD. See `String.init(decoding:)`.
|
||||
public var debugDescription: String { description.debugDescription }
|
||||
}
|
||||
|
||||
// MARK: - Convenience helpers
|
||||
|
||||
// Convenience helpers
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath {
|
||||
/// Creates a string by interpreting the path’s content as UTF-8 on Unix
|
||||
/// and UTF-16 on Windows.
|
||||
///
|
||||
/// This property is equivalent to calling `String(decoding: path)`
|
||||
public var string: String {
|
||||
String(decoding: self)
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath.Component {
|
||||
/// Creates a string by interpreting the component’s content as UTF-8 on Unix
|
||||
/// and UTF-16 on Windows.
|
||||
///
|
||||
/// This property is equivalent to calling `String(decoding: component)`.
|
||||
public var string: String {
|
||||
String(decoding: self)
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath.Root {
|
||||
/// On Unix, this returns `"/"`.
|
||||
///
|
||||
/// On Windows, interprets the root's content as UTF-16 on Windows.
|
||||
///
|
||||
/// This property is equivalent to calling `String(decoding: root)`.
|
||||
public var string: String {
|
||||
String(decoding: self)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Decoding and validating
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension String {
|
||||
/// Creates a string by interpreting the file path's content as UTF-8 on Unix
|
||||
/// and UTF-16 on Windows.
|
||||
///
|
||||
/// - Parameter path: The file path to be interpreted as
|
||||
/// `CInterop.PlatformUnicodeEncoding`.
|
||||
///
|
||||
/// If the content of the file path isn't a well-formed Unicode string,
|
||||
/// this initializer replaces invalid bytes with U+FFFD.
|
||||
/// This means that, depending on the semantics of the specific file system,
|
||||
/// conversion to a string and back to a path
|
||||
/// might result in a value that's different from the original path.
|
||||
public init(decoding path: FilePath) {
|
||||
self.init(_decoding: path)
|
||||
}
|
||||
|
||||
/// Creates a string from a file path, validating its contents as UTF-8 on
|
||||
/// Unix and UTF-16 on Windows.
|
||||
///
|
||||
/// - Parameter path: The file path to be interpreted as
|
||||
/// `CInterop.PlatformUnicodeEncoding`.
|
||||
///
|
||||
/// If the contents of the file path isn't a well-formed Unicode string,
|
||||
/// this initializer returns `nil`.
|
||||
public init?(validating path: FilePath) {
|
||||
self.init(_validating: path)
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension String {
|
||||
/// Creates a string by interpreting the path component's content as UTF-8 on
|
||||
/// Unix and UTF-16 on Windows.
|
||||
///
|
||||
/// - Parameter component: The path component to be interpreted as
|
||||
/// `CInterop.PlatformUnicodeEncoding`.
|
||||
///
|
||||
/// If the content of the path component isn't a well-formed Unicode string,
|
||||
/// this initializer replaces invalid bytes with U+FFFD.
|
||||
/// This means that, depending on the semantics of the specific file system,
|
||||
/// conversion to a string and back to a path component
|
||||
/// might result in a value that's different from the original path component.
|
||||
public init(decoding component: FilePath.Component) {
|
||||
self.init(_decoding: component)
|
||||
}
|
||||
|
||||
/// Creates a string from a path component, validating its contents as UTF-8
|
||||
/// on Unix and UTF-16 on Windows.
|
||||
///
|
||||
/// - Parameter component: The path component to be interpreted as
|
||||
/// `CInterop.PlatformUnicodeEncoding`.
|
||||
///
|
||||
/// If the contents of the path component isn't a well-formed Unicode string,
|
||||
/// this initializer returns `nil`.
|
||||
public init?(validating component: FilePath.Component) {
|
||||
self.init(_validating: component)
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension String {
|
||||
/// On Unix, creates the string `"/"`
|
||||
///
|
||||
/// On Windows, creates a string by interpreting the path root's content as
|
||||
/// UTF-16.
|
||||
///
|
||||
/// - Parameter root: The path root to be interpreted as
|
||||
/// `CInterop.PlatformUnicodeEncoding`.
|
||||
///
|
||||
/// If the content of the path root isn't a well-formed Unicode string,
|
||||
/// this initializer replaces invalid bytes with U+FFFD.
|
||||
/// This means that on Windows,
|
||||
/// conversion to a string and back to a path root
|
||||
/// might result in a value that's different from the original path root.
|
||||
public init(decoding root: FilePath.Root) {
|
||||
self.init(_decoding: root)
|
||||
}
|
||||
|
||||
/// On Unix, creates the string `"/"`
|
||||
///
|
||||
/// On Windows, creates a string from a path root, validating its contents as
|
||||
/// UTF-16 on Windows.
|
||||
///
|
||||
/// - Parameter root: The path root to be interpreted as
|
||||
/// `CInterop.PlatformUnicodeEncoding`.
|
||||
///
|
||||
/// On Windows, if the contents of the path root isn't a well-formed Unicode
|
||||
/// string, this initializer returns `nil`.
|
||||
public init?(validating root: FilePath.Root) {
|
||||
self.init(_validating: root)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Internal helpers
|
||||
|
||||
extension String {
|
||||
fileprivate init<PS: _PlatformStringable>(_decoding ps: PS) {
|
||||
self = ps._withPlatformString { String(platformString: $0) }
|
||||
}
|
||||
|
||||
fileprivate init?<PS: _PlatformStringable>(_validating ps: PS) {
|
||||
guard let str = ps._withPlatformString(
|
||||
String.init(validatingPlatformString:)
|
||||
) else {
|
||||
return nil
|
||||
}
|
||||
self = str
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Deprecations
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension String {
|
||||
@available(*, deprecated, renamed: "init(decoding:)")
|
||||
public init(_ path: FilePath) { self.init(decoding: path) }
|
||||
|
||||
@available(*, deprecated, renamed: "init(validating:)")
|
||||
public init?(validatingUTF8 path: FilePath) { self.init(validating: path) }
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension FilePath {
|
||||
/// For backwards compatibility only. This initializer is equivalent to
|
||||
/// the preferred `FilePath(platformString:)`.
|
||||
@available(*, deprecated, renamed: "init(platformString:)")
|
||||
public init(cString: UnsafePointer<CChar>) {
|
||||
self.init(platformString: cString)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "init(platformString:)")
|
||||
public init(cString: [CChar]) {
|
||||
self.init(platformString: cString)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "init(platformString:)")
|
||||
public init(cString: inout CChar) {
|
||||
self.init(platformString: &cString)
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "init(platformString:)")
|
||||
public init(cString: String) {
|
||||
self.init(platformString: cString)
|
||||
}
|
||||
|
||||
/// For backwards compatibility only. This function is equivalent to
|
||||
/// the preferred `withPlatformString`.
|
||||
public func withCString<Result>(
|
||||
_ body: (UnsafePointer<CChar>) throws -> Result
|
||||
) rethrows -> Result {
|
||||
return try _withPlatformString(body)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,611 @@
|
||||
/*
|
||||
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: - Query API
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath {
|
||||
/// Returns true if this path uniquely identifies the location of
|
||||
/// a file without reference to an additional starting location.
|
||||
///
|
||||
/// On Unix platforms, absolute paths begin with a `/`. `isAbsolute` is
|
||||
/// equivalent to `root != nil`.
|
||||
///
|
||||
/// On Windows, absolute paths are fully qualified paths. `isAbsolute` is
|
||||
/// _not_ equivalent to `root != nil` for traditional DOS paths
|
||||
/// (e.g. `C:foo` and `\bar` have roots but are not absolute). UNC paths
|
||||
/// and device paths are always absolute. Traditional DOS paths are
|
||||
/// absolute only if they begin with a volume or drive followed by
|
||||
/// a `:` and a separator.
|
||||
///
|
||||
/// NOTE: This does not perform shell expansion or substitute
|
||||
/// environment variables; paths beginning with `~` are considered relative.
|
||||
///
|
||||
/// Examples:
|
||||
/// * Unix:
|
||||
/// * `/usr/local/bin`
|
||||
/// * `/tmp/foo.txt`
|
||||
/// * `/`
|
||||
/// * Windows:
|
||||
/// * `C:\Users\`
|
||||
/// * `\\?\UNC\server\share\bar.exe`
|
||||
/// * `\\server\share\bar.exe`
|
||||
public var isAbsolute: Bool {
|
||||
self.root?.isAbsolute ?? false
|
||||
}
|
||||
|
||||
/// Returns true if this path is not absolute (see `isAbsolute`).
|
||||
///
|
||||
/// Examples:
|
||||
/// * Unix:
|
||||
/// * `~/bar`
|
||||
/// * `tmp/foo.txt`
|
||||
/// * Windows:
|
||||
/// * `bar\baz`
|
||||
/// * `C:Users\`
|
||||
/// * `\Users`
|
||||
public var isRelative: Bool { !isAbsolute }
|
||||
|
||||
/// Returns whether `other` is a prefix of `self`, only considering
|
||||
/// whole path components.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// let path: FilePath = "/usr/bin/ls"
|
||||
/// path.starts(with: "/") // true
|
||||
/// path.starts(with: "/usr/bin") // true
|
||||
/// path.starts(with: "/usr/bin/ls") // true
|
||||
/// path.starts(with: "/usr/bin/ls///") // true
|
||||
/// path.starts(with: "/us") // false
|
||||
///
|
||||
// TODO(Windows docs): examples with roots, such as whether `\foo\bar`
|
||||
// starts with `C:\foo`
|
||||
public func starts(with other: FilePath) -> Bool {
|
||||
guard !other.isEmpty else { return true }
|
||||
return self.root == other.root && components.starts(
|
||||
with: other.components)
|
||||
}
|
||||
|
||||
/// Returns whether `other` is a suffix of `self`, only considering
|
||||
/// whole path components.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// let path: FilePath = "/usr/bin/ls"
|
||||
/// path.ends(with: "ls") // true
|
||||
/// path.ends(with: "bin/ls") // true
|
||||
/// path.ends(with: "usr/bin/ls") // true
|
||||
/// path.ends(with: "/usr/bin/ls///") // true
|
||||
/// path.ends(with: "/ls") // false
|
||||
///
|
||||
// TODO(Windows docs): examples with roots, such as whether `C:\foo\bar`
|
||||
// ends with `C:bar`
|
||||
public func ends(with other: FilePath) -> Bool {
|
||||
if other.root != nil {
|
||||
// TODO: anything tricky here for Windows?
|
||||
return self == other
|
||||
}
|
||||
|
||||
return components.reversed().starts(
|
||||
with: other.components.reversed())
|
||||
}
|
||||
|
||||
/// Whether this path is empty
|
||||
public var isEmpty: Bool { _storage.isEmpty }
|
||||
}
|
||||
|
||||
// MARK: - Decompose a path
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath {
|
||||
/// Returns the root of a path if there is one, otherwise `nil`.
|
||||
///
|
||||
/// On Unix, this will return the leading `/` if the path is absolute
|
||||
/// and `nil` if the path is relative.
|
||||
///
|
||||
/// On Windows, for traditional DOS paths, this will return
|
||||
/// the path prefix up to and including a root directory or
|
||||
/// a supplied drive or volume. Otherwise, if the path is relative to
|
||||
/// both the current directory and current drive, returns `nil`.
|
||||
///
|
||||
/// On Windows, for UNC or device paths, this will return the path prefix
|
||||
/// up to and including the host and share for UNC paths or the volume for
|
||||
/// device paths followed by any subsequent separator.
|
||||
///
|
||||
/// Examples:
|
||||
/// * Unix:
|
||||
/// * `/foo/bar => /`
|
||||
/// * `foo/bar => nil`
|
||||
/// * Windows:
|
||||
/// * `C:\foo\bar => C:\`
|
||||
/// * `C:foo\bar => C:`
|
||||
/// * `\foo\bar => \ `
|
||||
/// * `foo\bar => nil`
|
||||
/// * `\\server\share\file => \\server\share\`
|
||||
/// * `\\?\UNC\server\share\file => \\?\UNC\server\share\`
|
||||
/// * `\\.\device\folder => \\.\device\`
|
||||
///
|
||||
/// Setting the root to `nil` will remove the root and setting a new
|
||||
/// root will replace the root.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// var path: FilePath = "/foo/bar"
|
||||
/// path.root = nil // path is "foo/bar"
|
||||
/// path.root = "/" // path is "/foo/bar"
|
||||
///
|
||||
/// Example (Windows):
|
||||
///
|
||||
/// var path: FilePath = #"\foo\bar"#
|
||||
/// path.root = nil // path is #"foo\bar"#
|
||||
/// path.root = "C:" // path is #"C:foo\bar"#
|
||||
/// path.root = #"C:\"# // path is #"C:\foo\bar"#
|
||||
///
|
||||
public var root: FilePath.Root? {
|
||||
get {
|
||||
guard _hasRoot else { return nil }
|
||||
return Root(self, rootEnd: _relativeStart)
|
||||
}
|
||||
set {
|
||||
defer { _invariantCheck() }
|
||||
guard let r = newValue else {
|
||||
_storage.removeSubrange(..<_relativeStart)
|
||||
return
|
||||
}
|
||||
_storage.replaceSubrange(..<_relativeStart, with: r._slice)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new path containing just the components, i.e. everything
|
||||
/// after `root`.
|
||||
///
|
||||
/// Returns self if `root == nil`.
|
||||
///
|
||||
/// Examples:
|
||||
/// * Unix:
|
||||
/// * `/foo/bar => foo/bar`
|
||||
/// * `foo/bar => foo/bar`
|
||||
/// * `/ => ""`
|
||||
/// * Windows:
|
||||
/// * `C:\foo\bar => foo\bar`
|
||||
/// * `foo\bar => foo\bar`
|
||||
/// * `\\?\UNC\server\share\file => file`
|
||||
/// * `\\?\device\folder\file.exe => folder\file.exe`
|
||||
/// * `\\server\share\file => file`
|
||||
/// * `\ => ""`
|
||||
///
|
||||
public __consuming func removingRoot() -> FilePath {
|
||||
var copy = self
|
||||
copy.root = nil
|
||||
return copy
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath {
|
||||
/// Returns the final component of the path.
|
||||
/// Returns `nil` if the path is empty or only contains a root.
|
||||
///
|
||||
/// Note: Even if the final component is a special directory
|
||||
/// (`.` or `..`), it will still be returned. See `lexicallyNormalize()`.
|
||||
///
|
||||
/// Examples:
|
||||
/// * Unix:
|
||||
/// * `/usr/local/bin/ => bin`
|
||||
/// * `/tmp/foo.txt => foo.txt`
|
||||
/// * `/tmp/foo.txt/.. => ..`
|
||||
/// * `/tmp/foo.txt/. => .`
|
||||
/// * `/ => nil`
|
||||
/// * Windows:
|
||||
/// * `C:\Users\ => Users`
|
||||
/// * `C:Users\ => Users`
|
||||
/// * `C:\ => nil`
|
||||
/// * `\Users\ => Users`
|
||||
/// * `\\?\UNC\server\share\bar.exe => bar.exe`
|
||||
/// * `\\server\share => nil`
|
||||
/// * `\\?\UNC\server\share\ => nil`
|
||||
///
|
||||
public var lastComponent: Component? { components.last }
|
||||
|
||||
/// Creates a new path with everything up to but not including
|
||||
/// `lastComponent`.
|
||||
///
|
||||
/// If the path only contains a root, returns `self`.
|
||||
/// If the path has no root and only includes a single component,
|
||||
/// returns an empty FilePath.
|
||||
///
|
||||
/// Examples:
|
||||
/// * Unix:
|
||||
/// * `/usr/bin/ls => /usr/bin`
|
||||
/// * `/foo => /`
|
||||
/// * `/ => /`
|
||||
/// * `foo => ""`
|
||||
/// * Windows:
|
||||
/// * `C:\foo\bar.exe => C:\foo`
|
||||
/// * `C:\ => C:\`
|
||||
/// * `\\server\share\folder\file.txt => \\server\share\folder`
|
||||
/// * `\\server\share\ => \\server\share\`
|
||||
public __consuming func removingLastComponent() -> FilePath {
|
||||
var copy = self
|
||||
copy.removeLastComponent()
|
||||
return copy
|
||||
}
|
||||
|
||||
/// In-place mutating variant of `removingLastComponent`.
|
||||
///
|
||||
/// If `self` only contains a root, does nothing and returns `false`.
|
||||
/// Otherwise removes `lastComponent` and returns `true`.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// var path = "/usr/bin"
|
||||
/// path.removeLastComponent() == true // path is "/usr"
|
||||
/// path.removeLastComponent() == true // path is "/"
|
||||
/// path.removeLastComponent() == false // path is "/"
|
||||
///
|
||||
@discardableResult
|
||||
public mutating func removeLastComponent() -> Bool {
|
||||
defer { _invariantCheck() }
|
||||
guard let lastRel = lastComponent else { return false }
|
||||
_storage.removeSubrange(lastRel._slice.indices)
|
||||
_removeTrailingSeparator()
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath.Component {
|
||||
/// The extension of this file or directory component.
|
||||
///
|
||||
/// If `self` does not contain a `.` anywhere, or only
|
||||
/// at the start, returns `nil`. Otherwise, returns everything after the dot.
|
||||
///
|
||||
/// Examples:
|
||||
/// * `foo.txt => txt`
|
||||
/// * `foo.tar.gz => gz`
|
||||
/// * `Foo.app => app`
|
||||
/// * `.hidden => nil`
|
||||
/// * `.. => nil`
|
||||
///
|
||||
public var `extension`: String? {
|
||||
guard let range = _extensionRange() else { return nil }
|
||||
return _slice[range].string
|
||||
}
|
||||
|
||||
/// The non-extension portion of this file or directory component.
|
||||
///
|
||||
/// Examples:
|
||||
/// * `foo.txt => foo`
|
||||
/// * `foo.tar.gz => foo.tar`
|
||||
/// * `Foo.app => Foo`
|
||||
/// * `.hidden => .hidden`
|
||||
/// * `.. => ..`
|
||||
///
|
||||
public var stem: String {
|
||||
_slice[_stemRange()].string
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath {
|
||||
|
||||
/// The extension of the file or directory last component.
|
||||
///
|
||||
/// If `lastComponent` is `nil` or one of the special path components
|
||||
/// `.` or `..`, `get` returns `nil` and `set` does nothing.
|
||||
///
|
||||
/// If `lastComponent` does not contain a `.` anywhere, or only
|
||||
/// at the start, `get` returns `nil` and `set` will append a
|
||||
/// `.` and `newValue` to `lastComponent`.
|
||||
///
|
||||
/// Otherwise `get` returns everything after the last `.` and `set` will
|
||||
/// replace the extension.
|
||||
///
|
||||
/// Examples:
|
||||
/// * `/tmp/foo.txt => txt`
|
||||
/// * `/Applications/Foo.app/ => app`
|
||||
/// * `/Applications/Foo.app/bar.txt => txt`
|
||||
/// * `/tmp/foo.tar.gz => gz`
|
||||
/// * `/tmp/.hidden => nil`
|
||||
/// * `/tmp/.hidden. => ""`
|
||||
/// * `/tmp/.. => nil`
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// var path = "/tmp/file"
|
||||
/// path.extension = "txt" // path is "/tmp/file.txt"
|
||||
/// path.extension = "o" // path is "/tmp/file.o"
|
||||
/// path.extension = nil // path is "/tmp/file"
|
||||
/// path.extension = "" // path is "/tmp/file."
|
||||
///
|
||||
public var `extension`: String? {
|
||||
get { lastComponent?.extension }
|
||||
set {
|
||||
defer { _invariantCheck() }
|
||||
guard let base = lastComponent, base.kind == .regular else { return }
|
||||
|
||||
let suffix: SystemString
|
||||
if let ext = newValue {
|
||||
suffix = _makeExtension(ext)
|
||||
} else {
|
||||
suffix = SystemString()
|
||||
}
|
||||
|
||||
let extRange = (
|
||||
base._extensionIndex() ?? base._slice.endIndex
|
||||
) ..< base._slice.endIndex
|
||||
|
||||
_storage.replaceSubrange(extRange, with: suffix)
|
||||
}
|
||||
}
|
||||
|
||||
/// The non-extension portion of the file or directory last component.
|
||||
///
|
||||
/// Returns `nil` if `lastComponent` is `nil`
|
||||
///
|
||||
/// * `/tmp/foo.txt => foo`
|
||||
/// * `/Appliations/Foo.app/ => Foo`
|
||||
/// * `/Appliations/Foo.app/bar.txt => bar`
|
||||
/// * `/tmp/.hidden => .hidden`
|
||||
/// * `/tmp/.. => ..`
|
||||
/// * `/ => nil`
|
||||
public var stem: String? { lastComponent?.stem }
|
||||
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath {
|
||||
/// Whether the path is in lexical-normal form, that is `.` and `..`
|
||||
/// components have been collapsed lexically (i.e. without following
|
||||
/// symlinks).
|
||||
///
|
||||
/// Examples:
|
||||
/// * `"/usr/local/bin".isLexicallyNormal == true`
|
||||
/// * `"../local/bin".isLexicallyNormal == true`
|
||||
/// * `"local/bin/..".isLexicallyNormal == false`
|
||||
public var isLexicallyNormal: Bool {
|
||||
// `..` components are permitted at the front of a
|
||||
// relative path, otherwise there should be no special directories
|
||||
//
|
||||
// FIXME: Windows `C:..\foo\bar` should probably be lexically normal, but
|
||||
// `\..\foo\bar` should not.
|
||||
components.drop(
|
||||
while: { root == nil && $0.kind == .parentDirectory }
|
||||
).allSatisfy { $0.kind == .regular }
|
||||
}
|
||||
|
||||
/// Collapse `.` and `..` components lexically (i.e. without following
|
||||
/// symlinks).
|
||||
///
|
||||
/// Examples:
|
||||
/// * `/usr/./local/bin/.. => /usr/local`
|
||||
/// * `/../usr/local/bin => /usr/local/bin`
|
||||
/// * `../usr/local/../bin => ../usr/bin`
|
||||
public mutating func lexicallyNormalize() {
|
||||
defer { _invariantCheck() }
|
||||
_normalizeSpecialDirectories()
|
||||
}
|
||||
|
||||
/// Returns a copy of `self` in lexical-normal form, that is `.` and `..`
|
||||
/// components have been collapsed lexically (i.e. without following
|
||||
/// symlinks). See `lexicallyNormalize`
|
||||
public __consuming func lexicallyNormalized() -> FilePath {
|
||||
var copy = self
|
||||
copy.lexicallyNormalize()
|
||||
return copy
|
||||
}
|
||||
|
||||
/// Create a new `FilePath` by resolving `subpath` relative to `self`,
|
||||
/// ensuring that the result is lexically contained within `self`.
|
||||
///
|
||||
/// `subpath` will be lexically normalized (see `lexicallyNormalize`) as
|
||||
/// part of resolution, meaning any contained `.` and `..` components will
|
||||
/// be collapsed without resolving symlinks. Any root in `subpath` will be
|
||||
/// ignored.
|
||||
///
|
||||
/// Returns `nil` if the result would "escape" from `self` through use of
|
||||
/// the special directory component `..`.
|
||||
///
|
||||
/// This is useful for protecting against arbitrary path traversal from an
|
||||
/// untrusted subpath: the result is guaranteed to be lexically contained
|
||||
/// within `self`. Since this operation does not consult the file system to
|
||||
/// resolve symlinks, any escaping symlinks nested inside of `self` can still
|
||||
/// be targeted by the result.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// let staticContent: FilePath = "/var/www/my-website/static"
|
||||
/// let links: [FilePath] =
|
||||
/// ["index.html", "/assets/main.css", "../../../../etc/passwd"]
|
||||
/// links.map { staticContent.lexicallyResolving($0) }
|
||||
/// // ["/var/www/my-website/static/index.html",
|
||||
/// // "/var/www/my-website/static/assets/main.css",
|
||||
/// // nil]
|
||||
public __consuming func lexicallyResolving(
|
||||
_ subpath: __owned FilePath
|
||||
) -> FilePath? {
|
||||
let subpath = subpath.removingRoot().lexicallyNormalized()
|
||||
guard !subpath.isEmpty else { return self }
|
||||
guard subpath.components.first?.kind != .parentDirectory else {
|
||||
return nil
|
||||
}
|
||||
return self.appending(subpath.components)
|
||||
}
|
||||
}
|
||||
|
||||
// Modification and concatenation API
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath {
|
||||
/// If `prefix` is a prefix of `self`, removes it and returns `true`.
|
||||
/// Otherwise returns `false`.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// var path: FilePath = "/usr/local/bin"
|
||||
/// path.removePrefix("/usr/bin") // false
|
||||
/// path.removePrefix("/us") // false
|
||||
/// path.removePrefix("/usr/local") // true, path is "bin"
|
||||
///
|
||||
// TODO(Windows docs): example with roots
|
||||
public mutating func removePrefix(_ prefix: FilePath) -> Bool {
|
||||
defer { _invariantCheck() }
|
||||
// FIXME: Should Windows have more nuanced semantics?
|
||||
guard root == prefix.root else { return false }
|
||||
let (tail, remainder) = _dropCommonPrefix(components, prefix.components)
|
||||
guard remainder.isEmpty else { return false }
|
||||
self._storage.removeSubrange(..<tail.startIndex._storage)
|
||||
return true
|
||||
}
|
||||
|
||||
/// Append a `component` on to the end of this path.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// var path: FilePath = "/tmp"
|
||||
/// let sub: FilePath = "foo/./bar/../baz/."
|
||||
/// for comp in sub.components.filter({ $0.kind != .currentDirectory }) {
|
||||
/// path.append(comp)
|
||||
/// }
|
||||
/// // path is "/tmp/foo/bar/../baz"
|
||||
///
|
||||
// TODO(Windows docs): example with roots
|
||||
public mutating func append(_ component: __owned FilePath.Component) {
|
||||
defer { _invariantCheck() }
|
||||
_append(unchecked: component._slice)
|
||||
}
|
||||
|
||||
/// Append `components` on to the end of this path.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// var path: FilePath = "/"
|
||||
/// path.append(["usr", "local"]) // path is "/usr/local"
|
||||
/// let otherPath: FilePath = "/bin/ls"
|
||||
/// path.append(otherPath.components) // path is "/usr/local/bin/ls"
|
||||
///
|
||||
// TODO(Windows docs): example with roots
|
||||
public mutating func append<C: Collection>(
|
||||
_ components: __owned C
|
||||
) where C.Element == FilePath.Component {
|
||||
defer { _invariantCheck() }
|
||||
for c in components {
|
||||
_append(unchecked: c._slice)
|
||||
}
|
||||
}
|
||||
|
||||
/// Append the contents of `other`, ignoring any spurious leading separators.
|
||||
///
|
||||
/// A leading separator is spurious if `self` is non-empty.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// var path: FilePath = ""
|
||||
/// path.append("/var/www/website") // "/var/www/website"
|
||||
/// path.append("static/assets") // "/var/www/website/static/assets"
|
||||
/// path.append("/main.css") // "/var/www/website/static/assets/main.css"
|
||||
///
|
||||
// TODO(Windows docs): example with roots, should we rephrase this "spurious
|
||||
// roots"?
|
||||
public mutating func append(_ other: __owned String) {
|
||||
defer { _invariantCheck() }
|
||||
guard !other.utf8.isEmpty else { return }
|
||||
guard !isEmpty else {
|
||||
self = FilePath(other)
|
||||
return
|
||||
}
|
||||
let otherPath = FilePath(other)
|
||||
_append(unchecked: otherPath._storage[otherPath._relativeStart...])
|
||||
}
|
||||
|
||||
/// Non-mutating version of `append(_:Component)`.
|
||||
///
|
||||
// TODO(Windows docs): example with roots
|
||||
public __consuming func appending(_ other: __owned Component) -> FilePath {
|
||||
var copy = self
|
||||
copy.append(other)
|
||||
return copy
|
||||
}
|
||||
|
||||
/// Non-mutating version of `append(_:C)`.
|
||||
///
|
||||
// TODO(Windows docs): example with roots
|
||||
public __consuming func appending<C: Collection>(
|
||||
_ components: __owned C
|
||||
) -> FilePath where C.Element == FilePath.Component {
|
||||
var copy = self
|
||||
copy.append(components)
|
||||
return copy
|
||||
}
|
||||
|
||||
/// Non-mutating version of `append(_:String)`.
|
||||
///
|
||||
// TODO(Windows docs): example with roots
|
||||
public __consuming func appending(_ other: __owned String) -> FilePath {
|
||||
var copy = self
|
||||
copy.append(other)
|
||||
return copy
|
||||
}
|
||||
|
||||
/// If `other` does not have a root, append each component of `other`. If
|
||||
/// `other` has a root, replaces `self` with other.
|
||||
///
|
||||
/// This operation mimics traversing a directory structure (similar to the
|
||||
/// `cd` command), where pushing a relative path will append its components
|
||||
/// and pushing an absolute path will first clear `self`'s existing
|
||||
/// components.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// var path: FilePath = "/tmp"
|
||||
/// path.push("dir/file.txt") // path is "/tmp/dir/file.txt"
|
||||
/// path.push("/bin") // path is "/bin"
|
||||
///
|
||||
// TODO(Windows docs): examples and docs with roots, update/generalize doc
|
||||
// comment
|
||||
public mutating func push(_ other: __owned FilePath) {
|
||||
defer { _invariantCheck() }
|
||||
guard other.root == nil else {
|
||||
self = other
|
||||
return
|
||||
}
|
||||
// FIXME: Windows drive-relative roots, etc?
|
||||
_append(unchecked: other._storage[...])
|
||||
}
|
||||
|
||||
/// Non-mutating version of `push()`.
|
||||
///
|
||||
// TODO(Windows docs): examples and docs with roots
|
||||
public __consuming func pushing(_ other: __owned FilePath) -> FilePath {
|
||||
var copy = self
|
||||
copy.push(other)
|
||||
return copy
|
||||
}
|
||||
|
||||
/// Remove the contents of the path, keeping the null terminator.
|
||||
public mutating func removeAll(keepingCapacity: Bool = false) {
|
||||
defer { _invariantCheck() }
|
||||
_storage.removeAll(keepingCapacity: keepingCapacity)
|
||||
}
|
||||
|
||||
/// Reserve enough storage space to store `minimumCapacity` platform
|
||||
/// characters.
|
||||
public mutating func reserveCapacity(_ minimumCapacity: Int) {
|
||||
defer { _invariantCheck() }
|
||||
self._storage.reserveCapacity(minimumCapacity)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK - Renamed
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath {
|
||||
@available(*, unavailable, renamed: "removingLastComponent()")
|
||||
public var dirname: FilePath { removingLastComponent() }
|
||||
|
||||
@available(*, unavailable, renamed: "lastComponent")
|
||||
public var basename: Component? { lastComponent }
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
internal struct _ParsedWindowsRoot {
|
||||
var rootEnd: SystemString.Index
|
||||
|
||||
// TODO: Remove when I normalize to always (except `C:`)
|
||||
// have trailing separator
|
||||
var relativeBegin: SystemString.Index
|
||||
|
||||
var drive: SystemChar?
|
||||
var fullyQualified: Bool
|
||||
|
||||
var deviceSigil: SystemChar?
|
||||
|
||||
var host: Range<SystemString.Index>?
|
||||
var volume: Range<SystemString.Index>?
|
||||
}
|
||||
|
||||
extension _ParsedWindowsRoot {
|
||||
static func traditional(
|
||||
drive: SystemChar?, fullQualified: Bool, endingAt idx: SystemString.Index
|
||||
) -> _ParsedWindowsRoot {
|
||||
_ParsedWindowsRoot(
|
||||
rootEnd: idx,
|
||||
relativeBegin: idx,
|
||||
drive: drive,
|
||||
fullyQualified: fullQualified,
|
||||
deviceSigil: nil,
|
||||
host: nil,
|
||||
volume: nil)
|
||||
}
|
||||
|
||||
static func unc(
|
||||
deviceSigil: SystemChar?,
|
||||
server: Range<SystemString.Index>,
|
||||
share: Range<SystemString.Index>,
|
||||
endingAt end: SystemString.Index,
|
||||
relativeBegin relBegin: SystemString.Index
|
||||
) -> _ParsedWindowsRoot {
|
||||
_ParsedWindowsRoot(
|
||||
rootEnd: end,
|
||||
relativeBegin: relBegin,
|
||||
drive: nil,
|
||||
fullyQualified: true,
|
||||
deviceSigil: deviceSigil,
|
||||
host: server,
|
||||
volume: share)
|
||||
}
|
||||
|
||||
static func device(
|
||||
deviceSigil: SystemChar,
|
||||
volume: Range<SystemString.Index>,
|
||||
endingAt end: SystemString.Index,
|
||||
relativeBegin relBegin: SystemString.Index
|
||||
) -> _ParsedWindowsRoot {
|
||||
_ParsedWindowsRoot(
|
||||
rootEnd: end,
|
||||
relativeBegin: relBegin,
|
||||
drive: nil,
|
||||
fullyQualified: true,
|
||||
deviceSigil: deviceSigil,
|
||||
host: nil,
|
||||
volume: volume)
|
||||
}
|
||||
}
|
||||
|
||||
struct _Lexer {
|
||||
var slice: Slice<SystemString>
|
||||
|
||||
init(_ str: SystemString) {
|
||||
self.slice = str[...]
|
||||
}
|
||||
|
||||
var backslash: SystemChar { .backslash }
|
||||
|
||||
// Try to eat a backslash, returns false if nothing happened
|
||||
mutating func eatBackslash() -> Bool {
|
||||
slice._eat(.backslash) != nil
|
||||
}
|
||||
|
||||
// Try to consume a drive letter and subsequent `:`.
|
||||
mutating func eatDrive() -> SystemChar? {
|
||||
let copy = slice
|
||||
if let d = slice._eat(if: { $0.isLetter }), slice._eat(.colon) != nil {
|
||||
return d
|
||||
}
|
||||
// Restore slice
|
||||
slice = copy
|
||||
return nil
|
||||
}
|
||||
|
||||
// Try to consume a device sigil (stand-alone . or ?)
|
||||
mutating func eatSigil() -> SystemChar? {
|
||||
let copy = slice
|
||||
guard let sigil = slice._eat(.question) ?? slice._eat(.dot) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Check for something like .hidden or ?question
|
||||
guard isEmpty || slice.first == backslash else {
|
||||
slice = copy
|
||||
return nil
|
||||
}
|
||||
|
||||
return sigil
|
||||
}
|
||||
|
||||
// Try to consume an explicit "UNC" directory
|
||||
mutating func eatUNC() -> Bool {
|
||||
slice._eatSequence("UNC".unicodeScalars.lazy.map { SystemChar(ascii: $0) }) != nil
|
||||
}
|
||||
|
||||
// Eat everything up to but not including a backslash or null
|
||||
mutating func eatComponent() -> Range<SystemString.Index> {
|
||||
let backslash = self.backslash
|
||||
let component = slice._eatWhile({ $0 != backslash })
|
||||
?? slice[slice.startIndex ..< slice.startIndex]
|
||||
return component.indices
|
||||
}
|
||||
|
||||
var isEmpty: Bool {
|
||||
return slice.isEmpty
|
||||
}
|
||||
|
||||
var current: SystemString.Index { slice.startIndex }
|
||||
|
||||
mutating func clear() {
|
||||
// TODO: Intern empty system string
|
||||
self = _Lexer(SystemString())
|
||||
}
|
||||
|
||||
mutating func reset(to: SystemString, at: SystemString.Index) {
|
||||
self.slice = to[at...]
|
||||
}
|
||||
}
|
||||
|
||||
internal struct WindowsRootInfo {
|
||||
// The "volume" of a root. For UNC paths, this is also known as the "share".
|
||||
internal enum Volume: Equatable {
|
||||
/// No volume specified
|
||||
///
|
||||
/// * Traditional root relative to the current drive: `\`,
|
||||
/// * Omitted volume from other forms: `\\.\`, `\\.\UNC\server\\`, `\\server\\`
|
||||
case empty
|
||||
|
||||
/// A specified drive.
|
||||
///
|
||||
/// * Traditional disk: `C:\`, `C:`
|
||||
/// * Device disk: `\\.\C:\`, `\\?\C:\`
|
||||
/// * UNC: `\\server\e:\`, `\\?\UNC\server\e:\`
|
||||
///
|
||||
// TODO: NT paths? Admin paths using `$`?
|
||||
case drive(Character)
|
||||
|
||||
/// A volume with a GUID in a non-traditional path
|
||||
///
|
||||
/// * UNC: `\\host\Volume{0000-...}\`, `\\.\UNC\host\Volume{0000-...}\`
|
||||
/// * Device roots: `\\.\Volume{0000-...}\`, `\\?\Volume{000-...}\`
|
||||
///
|
||||
// TODO: GUID type?
|
||||
case guid(String)
|
||||
|
||||
// TODO: Legacy DOS devices, such as COM1?
|
||||
|
||||
/// Device object or share name
|
||||
///
|
||||
/// * Device roots: `\\.\BootPartition\`
|
||||
/// * UNC: `\\host\volume\`
|
||||
case volume(String)
|
||||
|
||||
// TODO: Should legacy DOS devices be detected and/or converted at construction time?
|
||||
// TODO: What about NT paths: `\??\`
|
||||
}
|
||||
|
||||
/// Represents the syntactic form of the path
|
||||
internal enum Form: Equatable {
|
||||
/// Traditional DOS roots: `C:\`, `C:`, and `\`
|
||||
case traditional(fullyQualified: Bool) // `C:\`, `C:`, `\`
|
||||
|
||||
/// UNC syntactic form: `\\server\share\`
|
||||
case unc
|
||||
|
||||
/// DOS device syntactic form: `\\?\BootPartition`, `\\.\C:\`, `\\?\UNC\server\share`
|
||||
case device(sigil: Character)
|
||||
|
||||
// TODO: NT?
|
||||
}
|
||||
|
||||
/// The host for UNC paths, else `nil`.
|
||||
internal var host: String?
|
||||
|
||||
/// The specified volume (or UNC share) for the root
|
||||
internal var volume: Volume
|
||||
|
||||
/// The syntactic form the root is in
|
||||
internal var form: Form
|
||||
|
||||
init(host: String?, volume: Volume, form: Form) {
|
||||
self.host = host
|
||||
self.volume = volume
|
||||
self.form = form
|
||||
checkInvariants()
|
||||
}
|
||||
}
|
||||
|
||||
extension _ParsedWindowsRoot {
|
||||
fileprivate func volumeInfo(_ root: SystemString) -> WindowsRootInfo.Volume {
|
||||
if let d = self.drive {
|
||||
return .drive(Character(d.asciiScalar!))
|
||||
}
|
||||
|
||||
guard let vol = self.volume, !vol.isEmpty else { return .empty }
|
||||
|
||||
// TODO: check for GUID
|
||||
// TODO: check for drive
|
||||
return .volume(root[vol].string)
|
||||
}
|
||||
}
|
||||
|
||||
extension WindowsRootInfo {
|
||||
internal init(_ root: SystemString, _ parsed: _ParsedWindowsRoot) {
|
||||
self.volume = parsed.volumeInfo(root)
|
||||
|
||||
if let host = parsed.host {
|
||||
self.host = root[host].string
|
||||
} else {
|
||||
self.host = nil
|
||||
}
|
||||
|
||||
if let sig = parsed.deviceSigil {
|
||||
self.form = .device(sigil: Character(sig.asciiScalar!))
|
||||
} else if parsed.host != nil {
|
||||
assert(parsed.volume != nil)
|
||||
self.form = .unc
|
||||
} else {
|
||||
self.form = .traditional(fullyQualified: parsed.fullyQualified)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension WindowsRootInfo {
|
||||
/// NOT `\foo\bar` nor `C:foo\bar`
|
||||
internal var isFullyQualified: Bool {
|
||||
return form != .traditional(fullyQualified: false)
|
||||
}
|
||||
|
||||
///
|
||||
/// `\\server\share\foo\bar.exe`, `\\.\UNC\server\share\foo\bar.exe`
|
||||
internal var isUNC: Bool {
|
||||
host != nil
|
||||
}
|
||||
|
||||
///
|
||||
/// `\foo\bar.exe`
|
||||
internal var isTraditionalRooted: Bool {
|
||||
form == .traditional(fullyQualified: false) && volume == .empty
|
||||
}
|
||||
|
||||
///
|
||||
/// `C:foo\bar.exe`
|
||||
internal var isTraditionalDriveRelative: Bool {
|
||||
switch (form, volume) {
|
||||
case (.traditional(fullyQualified: false), .drive(_)): return true
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Should this be component?
|
||||
func formPath() -> FilePath {
|
||||
fatalError("Unimplemented")
|
||||
}
|
||||
|
||||
// static func traditional(
|
||||
// drive: Character?, fullyQualified: Bool
|
||||
// ) -> WindowsRootInfo {
|
||||
// let vol: Volume
|
||||
// if let d = Character {
|
||||
// vol = .drive(d)
|
||||
// } else {
|
||||
// vol = .relative
|
||||
// }
|
||||
//
|
||||
// return WindowsRootInfo(
|
||||
// volume: .relative, form: .traditional(fullyQualified: false))
|
||||
// }
|
||||
|
||||
internal func checkInvariants() {
|
||||
switch form {
|
||||
case .traditional(let qual):
|
||||
precondition(host == nil)
|
||||
switch volume {
|
||||
case .empty:
|
||||
precondition(!qual)
|
||||
break
|
||||
case .drive(_): break
|
||||
default: preconditionFailure()
|
||||
}
|
||||
case .unc:
|
||||
precondition(host != nil)
|
||||
case .device(_): break
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SystemString {
|
||||
// TODO: Or, should I always inline this to remove some of the bookeeping?
|
||||
private func _parseWindowsRootInternal() -> _ParsedWindowsRoot? {
|
||||
assert(_windowsPaths)
|
||||
|
||||
/*
|
||||
Windows root: device or UNC or DOS
|
||||
device: (`\\.` or `\\?`) `\` (drive or guid or UNC-link)
|
||||
drive: letter `:`
|
||||
guid: `Volume{` (hex-digit or `-`)* `}`
|
||||
UNC-link: `UNC\` UNC-volume
|
||||
UNC: `\\` UNC-volume
|
||||
UNC-volume: server `\` share
|
||||
DOS: fully-qualified or legacy-device or drive or `\`
|
||||
full-qualified: drive `\`
|
||||
|
||||
TODO: What is \\?\server1\e:\utilities\\filecomparer\ from the docs?
|
||||
TODO: What about admin use of `$` instead of `:`? E.g. \\system07\C$\
|
||||
|
||||
NOTE: Legacy devices are not handled by System at a library level, but
|
||||
are deferred to the relevant syscalls.
|
||||
*/
|
||||
|
||||
var lexer = _Lexer(self)
|
||||
|
||||
// Helper to parse a UNC root
|
||||
func parseUNC(deviceSigil: SystemChar?) -> _ParsedWindowsRoot {
|
||||
let serverRange = lexer.eatComponent()
|
||||
guard lexer.eatBackslash() else {
|
||||
fatalError("expected normalized root to contain backslash")
|
||||
}
|
||||
let shareRange = lexer.eatComponent()
|
||||
let rootEnd = lexer.current
|
||||
_ = lexer.eatBackslash()
|
||||
return .unc(
|
||||
deviceSigil: deviceSigil,
|
||||
server: serverRange, share: shareRange,
|
||||
endingAt: rootEnd, relativeBegin: lexer.current)
|
||||
}
|
||||
|
||||
|
||||
// `C:` or `C:\`
|
||||
if let d = lexer.eatDrive() {
|
||||
// `C:\` - fully qualified
|
||||
let fullyQualified = lexer.eatBackslash()
|
||||
return .traditional(
|
||||
drive: d, fullQualified: fullyQualified, endingAt: lexer.current)
|
||||
}
|
||||
|
||||
// `\` or else it's just a rootless relative path
|
||||
guard lexer.eatBackslash() else { return nil }
|
||||
|
||||
// `\\` or else it's just a current-drive rooted traditional path
|
||||
guard lexer.eatBackslash() else {
|
||||
return .traditional(
|
||||
drive: nil, fullQualified: false, endingAt: lexer.current)
|
||||
}
|
||||
|
||||
// `\\.` or `\\?` (device paths) or else it's just UNC
|
||||
guard let sigil = lexer.eatSigil() else {
|
||||
return parseUNC(deviceSigil: nil)
|
||||
}
|
||||
_ = sigil // suppress warnings
|
||||
|
||||
guard lexer.eatBackslash() else {
|
||||
fatalError("expected normalized root to contain backslash")
|
||||
}
|
||||
|
||||
if lexer.eatUNC() {
|
||||
guard lexer.eatBackslash() else {
|
||||
fatalError("expected normalized root to contain backslash")
|
||||
}
|
||||
return parseUNC(deviceSigil: sigil)
|
||||
}
|
||||
|
||||
let device = lexer.eatComponent()
|
||||
let rootEnd = lexer.current
|
||||
_ = lexer.eatBackslash()
|
||||
|
||||
return .device(
|
||||
deviceSigil: sigil, volume: device,
|
||||
endingAt: rootEnd, relativeBegin: lexer.current)
|
||||
}
|
||||
|
||||
@inline(never)
|
||||
internal func _parseWindowsRoot() -> (
|
||||
rootEnd: SystemString.Index, relativeBegin: SystemString.Index
|
||||
) {
|
||||
guard let parsed = _parseWindowsRootInternal() else {
|
||||
return (startIndex, startIndex)
|
||||
}
|
||||
return (parsed.rootEnd, parsed.relativeBegin)
|
||||
}
|
||||
}
|
||||
|
||||
extension SystemString {
|
||||
// UNC and device roots can have multiple repeated roots that are meaningful,
|
||||
// and extra backslashes may need to be inserted for partial roots (e.g. empty
|
||||
// volume).
|
||||
//
|
||||
// Returns the point where `_normalizeSeparators` should resume.
|
||||
internal mutating func _prenormalizeWindowsRoots() -> Index {
|
||||
assert(_windowsPaths)
|
||||
assert(!self.contains(.slash), "only valid after separator conversion")
|
||||
|
||||
var lexer = _Lexer(self)
|
||||
|
||||
// Only relevant for UNC or device paths
|
||||
guard lexer.eatBackslash(), lexer.eatBackslash() else {
|
||||
return lexer.current
|
||||
}
|
||||
|
||||
// Parse a backslash, inserting one if needed
|
||||
func expectBackslash() {
|
||||
if lexer.eatBackslash() { return }
|
||||
|
||||
// A little gross, but we reset the lexer because the lexer
|
||||
// holds a strong reference to `self`.
|
||||
//
|
||||
// TODO: Intern the empty SystemString. Right now, this is
|
||||
// along an uncommon/pathological case, but we want to in
|
||||
// general make empty strings without allocation
|
||||
let idx = lexer.current
|
||||
lexer.clear()
|
||||
self.insert(.backslash, at: idx)
|
||||
lexer.reset(to: self, at: idx)
|
||||
let p = lexer.eatBackslash()
|
||||
assert(p)
|
||||
}
|
||||
// Parse a component and subsequent backslash, insering one if needed
|
||||
func expectComponent() {
|
||||
_ = lexer.eatComponent()
|
||||
expectBackslash()
|
||||
}
|
||||
|
||||
// Check for `\\.` style paths
|
||||
if lexer.eatSigil() != nil {
|
||||
expectBackslash()
|
||||
if lexer.eatUNC() {
|
||||
expectBackslash()
|
||||
expectComponent()
|
||||
expectComponent()
|
||||
return lexer.current
|
||||
}
|
||||
expectComponent()
|
||||
return lexer.current
|
||||
}
|
||||
|
||||
expectComponent()
|
||||
expectComponent()
|
||||
return lexer.current
|
||||
}
|
||||
}
|
||||
@@ -17,18 +17,18 @@
|
||||
/// let perms = FilePermissions(rawValue: 0o644)
|
||||
/// perms == [.ownerReadWrite, .groupRead, .otherRead] // true
|
||||
@frozen
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
public struct FilePermissions: OptionSet, Hashable, Codable {
|
||||
/// The raw C file permissions.
|
||||
@_alwaysEmitIntoClient
|
||||
public let rawValue: CModeT
|
||||
public let rawValue: CInterop.Mode
|
||||
|
||||
/// Create a strongly-typed file permission from a raw C value.
|
||||
@_alwaysEmitIntoClient
|
||||
public init(rawValue: CModeT) { self.rawValue = rawValue }
|
||||
public init(rawValue: CInterop.Mode) { self.rawValue = rawValue }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
private init(_ raw: CModeT) { self.init(rawValue: raw) }
|
||||
private init(_ raw: CInterop.Mode) { self.init(rawValue: raw) }
|
||||
|
||||
/// Indicates that other users have read-only permission.
|
||||
@_alwaysEmitIntoClient
|
||||
@@ -135,7 +135,7 @@ public struct FilePermissions: OptionSet, Hashable, Codable {
|
||||
public static var saveText: FilePermissions { FilePermissions(0o1000) }
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
extension FilePermissions
|
||||
: CustomStringConvertible, CustomDebugStringConvertible
|
||||
{
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
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: - Public typealiases
|
||||
|
||||
/// The C `mode_t` type.
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
@available(*, deprecated, renamed: "CInterop.Mode")
|
||||
public typealias CModeT = CInterop.Mode
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#elseif os(Linux) || os(FreeBSD) || os(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import Glibc
|
||||
#elseif os(Windows)
|
||||
import CSystem
|
||||
import ucrt
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
/// A namespace for C and platform types
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
public enum CInterop {
|
||||
#if os(Windows)
|
||||
public typealias Mode = CInt
|
||||
#else
|
||||
public typealias Mode = mode_t
|
||||
#endif
|
||||
|
||||
/// The C `char` type
|
||||
public typealias Char = CChar
|
||||
|
||||
#if os(Windows)
|
||||
/// The platform's preferred character type. On Unix, this is an 8-bit C
|
||||
/// `char` (which may be signed or unsigned, depending on platform). On
|
||||
/// Windows, this is `UInt16` (a "wide" character).
|
||||
public typealias PlatformChar = UInt16
|
||||
#else
|
||||
/// The platform's preferred character type. On Unix, this is an 8-bit C
|
||||
/// `char` (which may be signed or unsigned, depending on platform). On
|
||||
/// Windows, this is `UInt16` (a "wide" character).
|
||||
public typealias PlatformChar = CInterop.Char
|
||||
#endif
|
||||
|
||||
#if os(Windows)
|
||||
/// The platform's preferred Unicode encoding. On Unix this is UTF-8 and on
|
||||
/// Windows it is UTF-16. Native strings may contain invalid Unicode,
|
||||
/// which will be handled by either error-correction or failing, depending
|
||||
/// on API.
|
||||
public typealias PlatformUnicodeEncoding = UTF16
|
||||
#else
|
||||
/// The platform's preferred Unicode encoding. On Unix this is UTF-8 and on
|
||||
/// Windows it is UTF-16. Native strings may contain invalid Unicode,
|
||||
/// which will be handled by either error-correction or failing, depending
|
||||
/// on API.
|
||||
public typealias PlatformUnicodeEncoding = UTF8
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,530 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// For platform constants redefined in Swift. We define them here so that
|
||||
// they can be used anywhere without imports and without confusion to
|
||||
// unavailable local decls.
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#elseif os(Linux) || os(FreeBSD) || os(Android)
|
||||
import Glibc
|
||||
#elseif os(Windows)
|
||||
import CSystem
|
||||
import ucrt
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// MARK: errno
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ERRNO_NOT_USED: CInt { 0 }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPERM: CInt { EPERM }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOENT: CInt { ENOENT }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESRCH: CInt { ESRCH }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EINTR: CInt { EINTR }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EIO: CInt { EIO }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENXIO: CInt { ENXIO }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _E2BIG: CInt { E2BIG }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOEXEC: CInt { ENOEXEC }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADF: CInt { EBADF }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECHILD: CInt { ECHILD }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDEADLK: CInt { EDEADLK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOMEM: CInt { ENOMEM }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EACCES: CInt { EACCES }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EFAULT: CInt { EFAULT }
|
||||
|
||||
#if !os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTBLK: CInt { ENOTBLK }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBUSY: CInt { EBUSY }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EEXIST: CInt { EEXIST }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EXDEV: CInt { EXDEV }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENODEV: CInt { ENODEV }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTDIR: CInt { ENOTDIR }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EISDIR: CInt { EISDIR }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EINVAL: CInt { EINVAL }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENFILE: CInt { ENFILE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMFILE: CInt { EMFILE }
|
||||
|
||||
#if !os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTTY: CInt { ENOTTY }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETXTBSY: CInt { ETXTBSY }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EFBIG: CInt { EFBIG }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSPC: CInt { ENOSPC }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESPIPE: CInt { ESPIPE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EROFS: CInt { EROFS }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMLINK: CInt { EMLINK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPIPE: CInt { EPIPE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDOM: CInt { EDOM }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ERANGE: CInt { ERANGE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EAGAIN: CInt { EAGAIN }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EWOULDBLOCK: CInt { EWOULDBLOCK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EINPROGRESS: CInt { EINPROGRESS }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EALREADY: CInt { EALREADY }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTSOCK: CInt { ENOTSOCK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDESTADDRREQ: CInt { EDESTADDRREQ }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMSGSIZE: CInt { EMSGSIZE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROTOTYPE: CInt { EPROTOTYPE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOPROTOOPT: CInt { ENOPROTOOPT }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROTONOSUPPORT: CInt { EPROTONOSUPPORT }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESOCKTNOSUPPORT: CInt {
|
||||
#if os(Windows)
|
||||
return WSAESOCKTNOSUPPORT
|
||||
#else
|
||||
return ESOCKTNOSUPPORT
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTSUP: CInt {
|
||||
#if os(Windows)
|
||||
return WSAEOPNOTSUPP
|
||||
#else
|
||||
return ENOTSUP
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPFNOSUPPORT: CInt {
|
||||
#if os(Windows)
|
||||
return WSAEPFNOSUPPORT
|
||||
#else
|
||||
return EPFNOSUPPORT
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EAFNOSUPPORT: CInt { EAFNOSUPPORT }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EADDRINUSE: CInt { EADDRINUSE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EADDRNOTAVAIL: CInt { EADDRNOTAVAIL }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENETDOWN: CInt { ENETDOWN }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENETUNREACH: CInt { ENETUNREACH }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENETRESET: CInt { ENETRESET }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECONNABORTED: CInt { ECONNABORTED }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECONNRESET: CInt { ECONNRESET }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOBUFS: CInt { ENOBUFS }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EISCONN: CInt { EISCONN }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTCONN: CInt { ENOTCONN }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESHUTDOWN: CInt {
|
||||
#if os(Windows)
|
||||
return WSAESHUTDOWN
|
||||
#else
|
||||
return ESHUTDOWN
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETOOMANYREFS: CInt {
|
||||
#if os(Windows)
|
||||
return WSAETOOMANYREFS
|
||||
#else
|
||||
return ETOOMANYREFS
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETIMEDOUT: CInt { ETIMEDOUT }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECONNREFUSED: CInt { ECONNREFUSED }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ELOOP: CInt { ELOOP }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENAMETOOLONG: CInt { ENAMETOOLONG }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EHOSTDOWN: CInt {
|
||||
#if os(Windows)
|
||||
return WSAEHOSTDOWN
|
||||
#else
|
||||
return EHOSTDOWN
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EHOSTUNREACH: CInt { EHOSTUNREACH }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTEMPTY: CInt { ENOTEMPTY }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROCLIM: CInt { EPROCLIM }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EUSERS: CInt {
|
||||
#if os(Windows)
|
||||
return WSAEUSERS
|
||||
#else
|
||||
return EUSERS
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDQUOT: CInt {
|
||||
#if os(Windows)
|
||||
return WSAEDQUOT
|
||||
#else
|
||||
return EDQUOT
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESTALE: CInt {
|
||||
#if os(Windows)
|
||||
return WSAESTALE
|
||||
#else
|
||||
return ESTALE
|
||||
#endif
|
||||
}
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EREMOTE: CInt {
|
||||
#if os(Windows)
|
||||
return WSAEREMOTE
|
||||
#else
|
||||
return EREMOTE
|
||||
#endif
|
||||
}
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADRPC: CInt { EBADRPC }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ERPCMISMATCH: CInt { ERPCMISMATCH }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROGUNAVAIL: CInt { EPROGUNAVAIL }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROGMISMATCH: CInt { EPROGMISMATCH }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROCUNAVAIL: CInt { EPROCUNAVAIL }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOLCK: CInt { ENOLCK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSYS: CInt { ENOSYS }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EFTYPE: CInt { EFTYPE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EAUTH: CInt { EAUTH }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENEEDAUTH: CInt { ENEEDAUTH }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPWROFF: CInt { EPWROFF }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDEVERR: CInt { EDEVERR }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EOVERFLOW: CInt { EOVERFLOW }
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADEXEC: CInt { EBADEXEC }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADARCH: CInt { EBADARCH }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESHLIBVERS: CInt { ESHLIBVERS }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADMACHO: CInt { EBADMACHO }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECANCELED: CInt { ECANCELED }
|
||||
|
||||
#if !os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EIDRM: CInt { EIDRM }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOMSG: CInt { ENOMSG }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EILSEQ: CInt { EILSEQ }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOATTR: CInt { ENOATTR }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADMSG: CInt { EBADMSG }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMULTIHOP: CInt { EMULTIHOP }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENODATA: CInt { ENODATA }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOLINK: CInt { ENOLINK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSR: CInt { ENOSR }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSTR: CInt { ENOSTR }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROTO: CInt { EPROTO }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETIME: CInt { ETIME }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EOPNOTSUPP: CInt { EOPNOTSUPP }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOPOLICY: CInt { ENOPOLICY }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTRECOVERABLE: CInt { ENOTRECOVERABLE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EOWNERDEAD: CInt { EOWNERDEAD }
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EQFULL: CInt { EQFULL }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ELAST: CInt { ELAST }
|
||||
#endif
|
||||
|
||||
// MARK: File Operations
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_RDONLY: CInt { O_RDONLY }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_WRONLY: CInt { O_WRONLY }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_RDWR: CInt { O_RDWR }
|
||||
|
||||
#if !os(Windows)
|
||||
// TODO: API?
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_ACCMODE: CInt { O_ACCMODE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NONBLOCK: CInt { O_NONBLOCK }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_APPEND: CInt { O_APPEND }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_SHLOCK: CInt { O_SHLOCK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_EXLOCK: CInt { O_EXLOCK }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
// TODO: API?
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_ASYNC: CInt { O_ASYNC }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NOFOLLOW: CInt { O_NOFOLLOW }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CREAT: CInt { O_CREAT }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_TRUNC: CInt { O_TRUNC }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_EXCL: CInt { O_EXCL }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_EVTONLY: CInt { O_EVTONLY }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
// TODO: API?
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NOCTTY: CInt { O_NOCTTY }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_DIRECTORY: CInt { O_DIRECTORY }
|
||||
#endif
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_SYMLINK: CInt { O_SYMLINK }
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CLOEXEC: CInt { O_CLOEXEC }
|
||||
#endif
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_SET: CInt { SEEK_SET }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_CUR: CInt { SEEK_CUR }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_END: CInt { SEEK_END }
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_HOLE: CInt { SEEK_HOLE }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_DATA: CInt { SEEK_DATA }
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// Internal wrappers and typedefs which help reduce #if littering in System's
|
||||
// code base.
|
||||
|
||||
// TODO: Should CSystem just include all the header files we need?
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#elseif os(Linux) || os(FreeBSD) || os(Android)
|
||||
@_implementationOnly import CSystem
|
||||
import Glibc
|
||||
#elseif os(Windows)
|
||||
import CSystem
|
||||
import ucrt
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
internal typealias _COffT = off_t
|
||||
|
||||
// MARK: syscalls and variables
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
internal var system_errno: CInt {
|
||||
get { Darwin.errno }
|
||||
set { Darwin.errno = newValue }
|
||||
}
|
||||
#elseif os(Windows)
|
||||
internal var system_errno: CInt {
|
||||
get {
|
||||
var value: CInt = 0
|
||||
// TODO(compnerd) handle the error?
|
||||
_ = ucrt._get_errno(&value)
|
||||
return value
|
||||
}
|
||||
set {
|
||||
_ = ucrt._set_errno(newValue)
|
||||
}
|
||||
}
|
||||
#else
|
||||
internal var system_errno: CInt {
|
||||
get { Glibc.errno }
|
||||
set { Glibc.errno = newValue }
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: C stdlib decls
|
||||
|
||||
// Convention: `system_foo` is system's wrapper for `foo`.
|
||||
|
||||
internal func system_strerror(_ __errnum: Int32) -> UnsafeMutablePointer<Int8>! {
|
||||
strerror(__errnum)
|
||||
}
|
||||
|
||||
internal func system_strlen(_ s: UnsafePointer<Int8>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
|
||||
// Convention: `system_platform_foo` is a
|
||||
// platform-representation-abstracted wrapper around `foo`-like functionality.
|
||||
// Type and layout differences such as the `char` vs `wchar` are abstracted.
|
||||
//
|
||||
|
||||
// strlen for the platform string
|
||||
internal func system_platform_strlen(_ s: UnsafePointer<CInterop.PlatformChar>) -> Int {
|
||||
#if os(Windows)
|
||||
return wcslen(s)
|
||||
#else
|
||||
return strlen(s)
|
||||
#endif
|
||||
}
|
||||
|
||||
// Interop between String and platfrom string
|
||||
extension String {
|
||||
internal func _withPlatformString<Result>(
|
||||
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
|
||||
) rethrows -> Result {
|
||||
// Need to #if because CChar may be signed
|
||||
#if os(Windows)
|
||||
return try withCString(encodedAs: CInterop.PlatformUnicodeEncoding.self, body)
|
||||
#else
|
||||
return try withCString(body)
|
||||
#endif
|
||||
}
|
||||
|
||||
internal init?(_platformString platformString: UnsafePointer<CInterop.PlatformChar>) {
|
||||
// Need to #if because CChar may be signed
|
||||
#if os(Windows)
|
||||
guard let strRes = String.decodeCString(
|
||||
platformString,
|
||||
as: CInterop.PlatformUnicodeEncoding.self,
|
||||
repairingInvalidCodeUnits: false
|
||||
) else { return nil }
|
||||
assert(strRes.repairsMade == false)
|
||||
self = strRes.result
|
||||
return
|
||||
|
||||
#else
|
||||
self.init(validatingUTF8: platformString)
|
||||
#endif
|
||||
}
|
||||
|
||||
internal init(
|
||||
_errorCorrectingPlatformString platformString: UnsafePointer<CInterop.PlatformChar>
|
||||
) {
|
||||
// Need to #if because CChar may be signed
|
||||
#if os(Windows)
|
||||
let strRes = String.decodeCString(
|
||||
platformString,
|
||||
as: CInterop.PlatformUnicodeEncoding.self,
|
||||
repairingInvalidCodeUnits: true)
|
||||
self = strRes!.result
|
||||
return
|
||||
#else
|
||||
self.init(cString: platformString)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// TLS
|
||||
#if os(Windows)
|
||||
internal typealias _PlatformTLSKey = DWORD
|
||||
#else
|
||||
internal typealias _PlatformTLSKey = pthread_key_t
|
||||
#endif
|
||||
|
||||
internal func makeTLSKey() -> _PlatformTLSKey {
|
||||
#if os(Windows)
|
||||
let raw: DWORD = FlsAlloc(nil)
|
||||
if raw == FLS_OUT_OF_INDEXES {
|
||||
fatalError("Unable to create key")
|
||||
}
|
||||
return raw
|
||||
#else
|
||||
var raw = pthread_key_t()
|
||||
guard 0 == pthread_key_create(&raw, nil) else {
|
||||
fatalError("Unable to create key")
|
||||
}
|
||||
return raw
|
||||
#endif
|
||||
}
|
||||
internal func setTLS(_ key: _PlatformTLSKey, _ p: UnsafeMutableRawPointer?) {
|
||||
#if os(Windows)
|
||||
guard FlsSetValue(key, p) else {
|
||||
fatalError("Unable to set TLS")
|
||||
}
|
||||
#else
|
||||
guard 0 == pthread_setspecific(key, p) else {
|
||||
fatalError("Unable to set TLS")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
internal func getTLS(_ key: _PlatformTLSKey) -> UnsafeMutableRawPointer? {
|
||||
#if os(Windows)
|
||||
return FlsGetValue(key)
|
||||
#else
|
||||
return pthread_getspecific(key)
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// Syscall mocking support.
|
||||
//
|
||||
// NOTE: This is currently the bare minimum needed for System's testing purposes, though we do
|
||||
// eventually want to expose some solution to users.
|
||||
//
|
||||
// Mocking is contextual, accessible through MockingDriver.withMockingEnabled. Mocking
|
||||
// state, including whether it is enabled, is stored in thread-local storage. Mocking is only
|
||||
// enabled in testing builds of System currently, to minimize runtime overhead of release builds.
|
||||
//
|
||||
|
||||
#if ENABLE_MOCKING
|
||||
internal struct Trace {
|
||||
internal struct Entry: Hashable {
|
||||
private var name: String
|
||||
private var arguments: [AnyHashable]
|
||||
|
||||
internal init(name: String, _ arguments: [AnyHashable]) {
|
||||
self.name = name
|
||||
self.arguments = arguments
|
||||
}
|
||||
}
|
||||
|
||||
private var entries: [Entry] = []
|
||||
private var firstEntry: Int = 0
|
||||
|
||||
internal var isEmpty: Bool { firstEntry >= entries.count }
|
||||
|
||||
internal mutating func dequeue() -> Entry? {
|
||||
guard !self.isEmpty else { return nil }
|
||||
defer { firstEntry += 1 }
|
||||
return entries[firstEntry]
|
||||
}
|
||||
|
||||
fileprivate mutating func add(_ e: Entry) {
|
||||
entries.append(e)
|
||||
}
|
||||
}
|
||||
|
||||
internal enum ForceErrno: Equatable {
|
||||
case none
|
||||
case always(errno: CInt)
|
||||
|
||||
case counted(errno: CInt, count: Int)
|
||||
}
|
||||
|
||||
// Provide access to the driver, context, and trace stack of mocking
|
||||
internal class MockingDriver {
|
||||
// Record syscalls and their arguments
|
||||
internal var trace = Trace()
|
||||
|
||||
// Mock errors inside syscalls
|
||||
internal var forceErrno = ForceErrno.none
|
||||
|
||||
// Whether we should pretend to be Windows for syntactic operations
|
||||
// inside FilePath
|
||||
fileprivate var forceWindowsSyntaxForPaths = false
|
||||
}
|
||||
|
||||
private let driverKey: _PlatformTLSKey = { makeTLSKey() }()
|
||||
|
||||
internal var currentMockingDriver: MockingDriver? {
|
||||
#if !ENABLE_MOCKING
|
||||
fatalError("Contextual mocking in non-mocking build")
|
||||
#endif
|
||||
|
||||
guard let rawPtr = getTLS(driverKey) else { return nil }
|
||||
|
||||
return Unmanaged<MockingDriver>.fromOpaque(rawPtr).takeUnretainedValue()
|
||||
}
|
||||
|
||||
extension MockingDriver {
|
||||
/// Enables mocking for the duration of `f` with a clean trace queue
|
||||
/// Restores prior mocking status and trace queue after execution
|
||||
internal static func withMockingEnabled(
|
||||
_ f: (MockingDriver) throws -> ()
|
||||
) rethrows {
|
||||
let priorMocking = currentMockingDriver
|
||||
let driver = MockingDriver()
|
||||
|
||||
defer {
|
||||
if let object = priorMocking {
|
||||
setTLS(driverKey, Unmanaged.passUnretained(object).toOpaque())
|
||||
} else {
|
||||
setTLS(driverKey, nil)
|
||||
}
|
||||
_fixLifetime(driver)
|
||||
}
|
||||
|
||||
setTLS(driverKey, Unmanaged.passUnretained(driver).toOpaque())
|
||||
return try f(driver)
|
||||
}
|
||||
}
|
||||
|
||||
// Check TLS for mocking
|
||||
@inline(never)
|
||||
private var contextualMockingEnabled: Bool {
|
||||
return currentMockingDriver != nil
|
||||
}
|
||||
|
||||
extension MockingDriver {
|
||||
internal static var enabled: Bool { mockingEnabled }
|
||||
|
||||
internal static var forceWindowsPaths: Bool {
|
||||
currentMockingDriver?.forceWindowsSyntaxForPaths ?? false
|
||||
}
|
||||
}
|
||||
|
||||
#endif // ENABLE_MOCKING
|
||||
|
||||
@inline(__always)
|
||||
internal var mockingEnabled: Bool {
|
||||
// Fast constant-foldable check for release builds
|
||||
#if ENABLE_MOCKING
|
||||
return contextualMockingEnabled
|
||||
#else
|
||||
return false
|
||||
#endif
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal var forceWindowsPaths: Bool {
|
||||
#if !ENABLE_MOCKING
|
||||
return false
|
||||
#else
|
||||
return MockingDriver.forceWindowsPaths
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
#if ENABLE_MOCKING
|
||||
// Strip the mock_system prefix and the arg list suffix
|
||||
private func originalSyscallName(_ function: String) -> String {
|
||||
// `function` must be of format `system_<name>(<parameters>)`
|
||||
precondition(function.starts(with: "system_"))
|
||||
return String(function.dropFirst("system_".count).prefix { $0 != "(" })
|
||||
}
|
||||
|
||||
private func mockImpl(
|
||||
name: String,
|
||||
path: UnsafePointer<CInterop.PlatformChar>?,
|
||||
_ args: [AnyHashable]
|
||||
) -> CInt {
|
||||
precondition(mockingEnabled)
|
||||
let origName = originalSyscallName(name)
|
||||
guard let driver = currentMockingDriver else {
|
||||
fatalError("Mocking requested from non-mocking context")
|
||||
}
|
||||
var mockArgs: Array<AnyHashable> = []
|
||||
if let p = path {
|
||||
mockArgs.append(String(_errorCorrectingPlatformString: p))
|
||||
}
|
||||
mockArgs.append(contentsOf: args)
|
||||
driver.trace.add(Trace.Entry(name: origName, mockArgs))
|
||||
|
||||
switch driver.forceErrno {
|
||||
case .none: break
|
||||
case .always(let e):
|
||||
system_errno = e
|
||||
return -1
|
||||
case .counted(let e, let count):
|
||||
assert(count >= 1)
|
||||
system_errno = e
|
||||
driver.forceErrno = count > 1 ? .counted(errno: e, count: count-1) : .none
|
||||
return -1
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
internal func _mock(
|
||||
name: String = #function, path: UnsafePointer<CInterop.PlatformChar>? = nil, _ args: AnyHashable...
|
||||
) -> CInt {
|
||||
return mockImpl(name: name, path: path, args)
|
||||
}
|
||||
internal func _mockInt(
|
||||
name: String = #function, path: UnsafePointer<CInterop.PlatformChar>? = nil, _ args: AnyHashable...
|
||||
) -> Int {
|
||||
Int(mockImpl(name: name, path: path, args))
|
||||
}
|
||||
|
||||
internal func _mockOffT(
|
||||
name: String = #function, path: UnsafePointer<CInterop.PlatformChar>? = nil, _ args: AnyHashable...
|
||||
) -> _COffT {
|
||||
_COffT(mockImpl(name: name, path: path, args))
|
||||
}
|
||||
#endif // ENABLE_MOCKING
|
||||
|
||||
// Force paths to be treated as Windows syntactically if `enabled` is
|
||||
// true.
|
||||
internal func _withWindowsPaths(enabled: Bool, _ body: () -> ()) {
|
||||
#if ENABLE_MOCKING
|
||||
guard enabled else {
|
||||
body()
|
||||
return
|
||||
}
|
||||
MockingDriver.withMockingEnabled { driver in
|
||||
driver.forceWindowsSyntaxForPaths = true
|
||||
body()
|
||||
}
|
||||
#else
|
||||
body()
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#elseif os(Linux) || os(FreeBSD) || os(Android)
|
||||
import Glibc
|
||||
#elseif os(Windows)
|
||||
import ucrt
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
// Interacting with the mocking system, tracing, etc., is a potentially significant
|
||||
// amount of code size, so we hand outline that code for every syscall
|
||||
|
||||
// open
|
||||
internal func system_open(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return _mock(path: path, oflag)
|
||||
}
|
||||
#endif
|
||||
return open(path, oflag)
|
||||
}
|
||||
|
||||
internal func system_open(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>,
|
||||
_ oflag: Int32, _ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled {
|
||||
return _mock(path: path, oflag, mode)
|
||||
}
|
||||
#endif
|
||||
return open(path, oflag, mode)
|
||||
}
|
||||
|
||||
// close
|
||||
internal func system_close(_ fd: Int32) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd) }
|
||||
#endif
|
||||
return close(fd)
|
||||
}
|
||||
|
||||
// read
|
||||
internal func system_read(
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(fd, buf, nbyte) }
|
||||
#endif
|
||||
return read(fd, buf, nbyte)
|
||||
}
|
||||
|
||||
// pread
|
||||
internal func system_pread(
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int, _ offset: off_t
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
|
||||
#endif
|
||||
return pread(fd, buf, nbyte, offset)
|
||||
}
|
||||
|
||||
// lseek
|
||||
internal func system_lseek(
|
||||
_ fd: Int32, _ off: off_t, _ whence: Int32
|
||||
) -> off_t {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockOffT(fd, off, whence) }
|
||||
#endif
|
||||
return lseek(fd, off, whence)
|
||||
}
|
||||
|
||||
// write
|
||||
internal func system_write(
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(fd, buf, nbyte) }
|
||||
#endif
|
||||
return write(fd, buf, nbyte)
|
||||
}
|
||||
|
||||
// pwrite
|
||||
internal func system_pwrite(
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int, _ offset: off_t
|
||||
) -> Int {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
|
||||
#endif
|
||||
return pwrite(fd, buf, nbyte, offset)
|
||||
}
|
||||
|
||||
internal func system_dup(_ fd: Int32) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd) }
|
||||
#endif
|
||||
return dup(fd)
|
||||
}
|
||||
|
||||
internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, fd2) }
|
||||
#endif
|
||||
return dup2(fd, fd2)
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fds) }
|
||||
#endif
|
||||
return pipe(fds)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !os(Windows)
|
||||
internal func system_ftruncate(_ fd: Int32, _ length: off_t) -> Int32 {
|
||||
#if ENABLE_MOCKING
|
||||
if mockingEnabled { return _mock(fd, length) }
|
||||
#endif
|
||||
return ftruncate(fd, length)
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
#if os(Windows)
|
||||
|
||||
import ucrt
|
||||
import WinSDK
|
||||
|
||||
@inline(__always)
|
||||
internal func open(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32
|
||||
) -> CInt {
|
||||
var fh: CInt = -1
|
||||
_ = _wsopen_s(&fh, path, oflag, _SH_DENYNO, _S_IREAD | _S_IWRITE)
|
||||
return fh
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func open(
|
||||
_ path: UnsafePointer<CInterop.PlatformChar>, _ oflag: Int32,
|
||||
_ mode: CInterop.Mode
|
||||
) -> CInt {
|
||||
// TODO(compnerd): Apply read/write permissions
|
||||
var fh: CInt = -1
|
||||
_ = _wsopen_s(&fh, path, oflag, _SH_DENYNO, _S_IREAD | _S_IWRITE)
|
||||
return fh
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func close(_ fd: Int32) -> Int32 {
|
||||
_close(fd)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func lseek(
|
||||
_ fd: Int32, _ off: Int64, _ whence: Int32
|
||||
) -> Int64 {
|
||||
_lseeki64(fd, off, whence)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func read(
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int
|
||||
) -> Int {
|
||||
Int(_read(fd, buf, numericCast(nbyte)))
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func write(
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int
|
||||
) -> Int {
|
||||
Int(_write(fd, buf, numericCast(nbyte)))
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func pread(
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int, _ offset: off_t
|
||||
) -> Int {
|
||||
let handle: intptr_t = _get_osfhandle(fd)
|
||||
if handle == /* INVALID_HANDLE_VALUE */ -1 { return Int(EBADF) }
|
||||
|
||||
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
|
||||
let hFile: HANDLE = HANDLE(bitPattern: handle)!
|
||||
|
||||
var ovlOverlapped: OVERLAPPED = OVERLAPPED()
|
||||
ovlOverlapped.OffsetHigh = DWORD(UInt32(offset >> 32) & 0xffffffff)
|
||||
ovlOverlapped.Offset = DWORD(UInt32(offset >> 0) & 0xffffffff)
|
||||
|
||||
var nNumberOfBytesRead: DWORD = 0
|
||||
if !ReadFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesRead, &ovlOverlapped) {
|
||||
let _ = GetLastError()
|
||||
// TODO(compnerd) map windows error to errno
|
||||
return Int(-1)
|
||||
}
|
||||
return Int(nNumberOfBytesRead)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func pwrite(
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int, _ offset: off_t
|
||||
) -> Int {
|
||||
let handle: intptr_t = _get_osfhandle(fd)
|
||||
if handle == /* INVALID_HANDLE_VALUE */ -1 { return Int(EBADF) }
|
||||
|
||||
// NOTE: this is a non-owning handle, do *not* call CloseHandle on it
|
||||
let hFile: HANDLE = HANDLE(bitPattern: handle)!
|
||||
|
||||
var ovlOverlapped: OVERLAPPED = OVERLAPPED()
|
||||
ovlOverlapped.OffsetHigh = DWORD(UInt32(offset >> 32) & 0xffffffff)
|
||||
ovlOverlapped.Offset = DWORD(UInt32(offset >> 0) & 0xffffffff)
|
||||
|
||||
var nNumberOfBytesWritten: DWORD = 0
|
||||
if !WriteFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesWritten,
|
||||
&ovlOverlapped) {
|
||||
let _ = GetLastError()
|
||||
// TODO(compnerd) map windows error to errno
|
||||
return Int(-1)
|
||||
}
|
||||
return Int(nNumberOfBytesWritten)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal func ftruncate(
|
||||
_ fd: Int32,
|
||||
_ length: off_t
|
||||
) -> Int32 {
|
||||
_chsize_s(fd, numericCast(length))
|
||||
}
|
||||
#endif
|
||||
@@ -1,487 +0,0 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
#if os(Linux)
|
||||
|
||||
// Ugh, this is really bad. For Darwin, we can at least rely on
|
||||
// these values not changing much, but in theory they could change
|
||||
// per Linux flavor or version (if no ABI)
|
||||
|
||||
// MARK: errno
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPERM: CInt { 1 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOENT: CInt { 2 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESRCH: CInt { 3 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EINTR: CInt { 4 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EIO: CInt { 5 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENXIO: CInt { 6 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _E2BIG: CInt { 7 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOEXEC: CInt { 8 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADF: CInt { 9 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECHILD: CInt { 10 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EAGAIN: CInt { 11 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOMEM: CInt { 12 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EACCES: CInt { 13 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EFAULT: CInt { 14 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTBLK: CInt { 15 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBUSY: CInt { 16 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EEXIST: CInt { 17 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EXDEV: CInt { 18 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENODEV: CInt { 19 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTDIR: CInt { 20 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EISDIR: CInt { 21 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EINVAL: CInt { 22 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENFILE: CInt { 23 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMFILE: CInt { 24 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTTY: CInt { 25 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETXTBSY: CInt { 26 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EFBIG: CInt { 27 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSPC: CInt { 28 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESPIPE: CInt { 29 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EROFS: CInt { 30 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMLINK: CInt { 31 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPIPE: CInt { 32 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDOM: CInt { 33 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ERANGE: CInt { 34 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDEADLK: CInt { 35 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENAMETOOLONG: CInt { 36 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOLCK: CInt { 37 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSYS: CInt { 38 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTEMPTY: CInt { 39 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ELOOP: CInt { 40 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EWOULDBLOCK: CInt { _EAGAIN }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOMSG: CInt { 42 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EIDRM: CInt { 43 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECHRNG: CInt { 44 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EL2NSYNC: CInt { 45 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EL3HLT: CInt { 46 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EL3RST: CInt { 47 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ELNRNG: CInt { 48 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EUNATCH: CInt { 49 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOCSI: CInt { 50 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EL2HLT: CInt { 51 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADE: CInt { 52 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADR: CInt { 53 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EXFULL: CInt { 54 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOANO: CInt { 55 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADRQC: CInt { 56 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADSLT: CInt { 57 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDEADLOCK: CInt { _EDEADLK }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBFONT: CInt { 59 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSTR: CInt { 60 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENODATA: CInt { 61 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETIME: CInt { 62 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOSR: CInt { 63 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENONET: CInt { 64 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOPKG: CInt { 65 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EREMOTE: CInt { 66 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOLINK: CInt { 67 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EADV: CInt { 68 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESRMNT: CInt { 69 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECOMM: CInt { 70 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROTO: CInt { 71 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMULTIHOP: CInt { 72 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDOTDOT: CInt { 73 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADMSG: CInt { 74 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EOVERFLOW: CInt { 75 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTUNIQ: CInt { 76 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EBADFD: CInt { 77 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EREMCHG: CInt { 78 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ELIBACC: CInt { 79 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ELIBBAD: CInt { 80 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ELIBSCN: CInt { 81 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ELIBMAX: CInt { 82 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ELIBEXEC: CInt { 83 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EILSEQ: CInt { 84 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ERESTART: CInt { 85 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESTRPIPE: CInt { 86 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EUSERS: CInt { 87 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTSOCK: CInt { 88 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDESTADDRREQ: CInt { 89 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMSGSIZE: CInt { 90 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROTOTYPE: CInt { 91 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOPROTOOPT: CInt { 92 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPROTONOSUPPORT: CInt { 93 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESOCKTNOSUPPORT: CInt { 94 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EOPNOTSUPP: CInt { 95 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTSUP: CInt { _EOPNOTSUPP }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EPFNOSUPPORT: CInt { 96 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EAFNOSUPPORT: CInt { 97 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EADDRINUSE: CInt { 98 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EADDRNOTAVAIL: CInt { 99 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENETDOWN: CInt { 100 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENETUNREACH: CInt { 101 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENETRESET: CInt { 102 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECONNABORTED: CInt { 103 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECONNRESET: CInt { 104 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOBUFS: CInt { 105 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EISCONN: CInt { 106 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTCONN: CInt { 107 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESHUTDOWN: CInt { 108 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETOOMANYREFS: CInt { 109 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ETIMEDOUT: CInt { 110 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECONNREFUSED: CInt { 111 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EHOSTDOWN: CInt { 112 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EHOSTUNREACH: CInt { 113 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EALREADY: CInt { 114 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EINPROGRESS: CInt { 115 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ESTALE: CInt { 116 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EUCLEAN: CInt { 117 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTNAM: CInt { 118 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENAVAIL: CInt { 119 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EISNAM: CInt { 120 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EREMOTEIO: CInt { 121 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EDQUOT: CInt { 122 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOMEDIUM: CInt { 123 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EMEDIUMTYPE: CInt { 124 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ECANCELED: CInt { 125 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOKEY: CInt { 126 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EKEYEXPIRED: CInt { 127 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EKEYREVOKED: CInt { 128 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EKEYREJECTED: CInt { 129 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EOWNERDEAD: CInt { 130 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ENOTRECOVERABLE: CInt { 131 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _ERFKILL: CInt { 132 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _EHWPOISON: CInt { 133 }
|
||||
|
||||
|
||||
// MARK: File Operations
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_ACCMODE: CInt { 0o00000003 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_RDONLY: CInt { 0o00000000 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_WRONLY: CInt { 0o00000001 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_RDWR: CInt { 0o00000002 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CREAT: CInt { 0o00000100 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_EXCL: CInt { 0o00000200 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NOCTTY: CInt { 0o00000400 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_TRUNC: CInt { 0o00001000 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_APPEND: CInt { 0o00002000 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NONBLOCK: CInt { 0o00004000 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_DSYNC: CInt { 0o00010000 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _FASYNC: CInt { 0o00020000 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_DIRECT: CInt { 0o00040000 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_LARGEFILE: CInt { 0o00100000 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_DIRECTORY: CInt { 0o00200000 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NOFOLLOW: CInt { 0o00400000 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_NOATIME: CInt { 0o01000000 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _O_CLOEXEC: CInt { 0o02000000 }
|
||||
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_SET: CInt { 0 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_CUR: CInt { 1 }
|
||||
|
||||
@_alwaysEmitIntoClient
|
||||
internal var _SEEK_END: CInt { 2 }
|
||||
|
||||
#endif
|
||||
@@ -1,20 +0,0 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
@_implementationOnly import SystemInternals
|
||||
|
||||
// Public typealiases that can't be reexported from SystemInternals
|
||||
|
||||
/// The C `mode_t` type.
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
public typealias CModeT = UInt16
|
||||
#else
|
||||
public typealias CModeT = UInt32
|
||||
#endif
|
||||
@@ -0,0 +1,193 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension String {
|
||||
/// Creates a string by interpreting the null-terminated platform string as
|
||||
/// UTF-8 on Unix and UTF-16 on Windows.
|
||||
///
|
||||
/// - Parameter platformString: The null-terminated platform string to be
|
||||
/// interpreted as `CInterop.PlatformUnicodeEncoding`.
|
||||
///
|
||||
/// If the content of the platform string isn't well-formed Unicode,
|
||||
/// this initializer replaces invalid bytes with U+FFFD.
|
||||
/// This means that, depending on the semantics of the specific platform,
|
||||
/// conversion to a string and back might result in a value that's different
|
||||
/// from the original platform string.
|
||||
public init(platformString: UnsafePointer<CInterop.PlatformChar>) {
|
||||
self.init(_errorCorrectingPlatformString: platformString)
|
||||
}
|
||||
|
||||
/// Creates a string by interpreting the null-terminated platform string as
|
||||
/// UTF-8 on Unix and UTF-16 on Windows.
|
||||
///
|
||||
/// - Parameter platformString: The null-terminated platform string to be
|
||||
/// interpreted as `CInterop.PlatformUnicodeEncoding`.
|
||||
///
|
||||
/// - Note It is a precondition that `platformString` must be null-terminated.
|
||||
/// The absence of a null byte will trigger a runtime error.
|
||||
///
|
||||
/// If the content of the platform string isn't well-formed Unicode,
|
||||
/// this initializer replaces invalid bytes with U+FFFD.
|
||||
/// This means that, depending on the semantics of the specific platform,
|
||||
/// conversion to a string and back might result in a value that's different
|
||||
/// from the original platform string.
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
public init(platformString: [CInterop.PlatformChar]) {
|
||||
guard let _ = platformString.firstIndex(of: 0) else {
|
||||
fatalError(
|
||||
"input of String.init(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
self = platformString.withUnsafeBufferPointer {
|
||||
String(platformString: $0.baseAddress!)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use String.init(_ scalar: Unicode.Scalar)")
|
||||
public init(platformString: inout CInterop.PlatformChar) {
|
||||
guard platformString == 0 else {
|
||||
fatalError(
|
||||
"input of String.init(platformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
self = ""
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use a copy of the String argument")
|
||||
public init(platformString: String) {
|
||||
if let nullLoc = platformString.firstIndex(of: "\0") {
|
||||
self = String(platformString[..<nullLoc])
|
||||
} else {
|
||||
self = platformString
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a string by interpreting the null-terminated platform string as
|
||||
/// UTF-8 on Unix and UTF-16 on Windows.
|
||||
///
|
||||
/// - Parameter platformString: The null-terminated platform string to be
|
||||
/// interpreted as `CInterop.PlatformUnicodeEncoding`.
|
||||
///
|
||||
/// If the contents of the platform string isn't well-formed Unicode,
|
||||
/// this initializer returns `nil`.
|
||||
public init?(
|
||||
validatingPlatformString platformString: UnsafePointer<CInterop.PlatformChar>
|
||||
) {
|
||||
self.init(_platformString: platformString)
|
||||
}
|
||||
|
||||
/// Creates a string by interpreting the null-terminated platform string as
|
||||
/// UTF-8 on Unix and UTF-16 on Windows.
|
||||
///
|
||||
/// - Parameter platformString: The null-terminated platform string to be
|
||||
/// interpreted as `CInterop.PlatformUnicodeEncoding`.
|
||||
///
|
||||
/// - Note It is a precondition that `platformString` must be null-terminated.
|
||||
/// The absence of a null byte will trigger a runtime error.
|
||||
///
|
||||
/// If the contents of the platform string isn't well-formed Unicode,
|
||||
/// this initializer returns `nil`.
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
public init?(
|
||||
validatingPlatformString platformString: [CInterop.PlatformChar]
|
||||
) {
|
||||
guard let _ = platformString.firstIndex(of: 0) else {
|
||||
fatalError(
|
||||
"input of String.init(validatingPlatformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
guard let string = platformString.withUnsafeBufferPointer({
|
||||
String(validatingPlatformString: $0.baseAddress!)
|
||||
}) else {
|
||||
return nil
|
||||
}
|
||||
self = string
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use String(_ scalar: Unicode.Scalar)")
|
||||
public init?(
|
||||
validatingPlatformString platformString: inout CInterop.PlatformChar
|
||||
) {
|
||||
guard platformString == 0 else {
|
||||
fatalError(
|
||||
"input of String.init(validatingPlatformString:) must be null-terminated"
|
||||
)
|
||||
}
|
||||
self = ""
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_alwaysEmitIntoClient
|
||||
@available(*, deprecated, message: "Use a copy of the String argument")
|
||||
public init?(
|
||||
validatingPlatformString platformString: String
|
||||
) {
|
||||
if let nullLoc = platformString.firstIndex(of: "\0") {
|
||||
self = String(platformString[..<nullLoc])
|
||||
} else {
|
||||
self = platformString
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls the given closure with a pointer to the contents of the string,
|
||||
/// represented as a null-terminated platform string.
|
||||
///
|
||||
/// - Parameter body: A closure with a pointer parameter
|
||||
/// that points to a null-terminated platform string.
|
||||
/// If `body` has a return value,
|
||||
/// that value is also used as the return value for this method.
|
||||
/// - Returns: The return value, if any, of the `body` closure parameter.
|
||||
///
|
||||
/// The pointer passed as an argument to `body` is valid
|
||||
/// only during the execution of this method.
|
||||
/// Don't try to store the pointer for later use.
|
||||
public func withPlatformString<Result>(
|
||||
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
|
||||
) rethrows -> Result {
|
||||
try _withPlatformString(body)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension CInterop.PlatformChar {
|
||||
internal var _platformCodeUnit: CInterop.PlatformUnicodeEncoding.CodeUnit {
|
||||
#if os(Windows)
|
||||
return self
|
||||
#else
|
||||
return CInterop.PlatformUnicodeEncoding.CodeUnit(bitPattern: self)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
extension CInterop.PlatformUnicodeEncoding.CodeUnit {
|
||||
internal var _platformChar: CInterop.PlatformChar {
|
||||
#if os(Windows)
|
||||
return self
|
||||
#else
|
||||
return CInterop.PlatformChar(bitPattern: self)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
internal protocol _PlatformStringable {
|
||||
func _withPlatformString<Result>(
|
||||
_ body: (UnsafePointer<CInterop.PlatformChar>) throws -> Result
|
||||
) rethrows -> Result
|
||||
|
||||
init?(_platformString: UnsafePointer<CInterop.PlatformChar>)
|
||||
}
|
||||
extension String: _PlatformStringable {}
|
||||
@@ -0,0 +1,293 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// A platform-native character representation, currently used for file paths
|
||||
internal struct SystemChar: RawRepresentable, Comparable, Hashable, Codable {
|
||||
internal typealias RawValue = CInterop.PlatformChar
|
||||
|
||||
internal var rawValue: RawValue
|
||||
|
||||
internal init(rawValue: RawValue) { self.rawValue = rawValue }
|
||||
|
||||
internal init(_ rawValue: RawValue) { self.init(rawValue: rawValue) }
|
||||
|
||||
static func < (lhs: SystemChar, rhs: SystemChar) -> Bool {
|
||||
lhs.rawValue < rhs.rawValue
|
||||
}
|
||||
}
|
||||
|
||||
extension SystemChar {
|
||||
internal init(ascii: Unicode.Scalar) {
|
||||
self.init(rawValue: numericCast(UInt8(ascii: ascii)))
|
||||
}
|
||||
internal init(codeUnit: CInterop.PlatformUnicodeEncoding.CodeUnit) {
|
||||
self.init(rawValue: codeUnit._platformChar)
|
||||
}
|
||||
|
||||
internal static var null: SystemChar { SystemChar(0x0) }
|
||||
internal static var slash: SystemChar { SystemChar(ascii: "/") }
|
||||
internal static var backslash: SystemChar { SystemChar(ascii: #"\"#) }
|
||||
internal static var dot: SystemChar { SystemChar(ascii: ".") }
|
||||
internal static var colon: SystemChar { SystemChar(ascii: ":") }
|
||||
internal static var question: SystemChar { SystemChar(ascii: "?") }
|
||||
|
||||
internal var codeUnit: CInterop.PlatformUnicodeEncoding.CodeUnit {
|
||||
rawValue._platformCodeUnit
|
||||
}
|
||||
|
||||
internal var asciiScalar: Unicode.Scalar? {
|
||||
guard isASCII else { return nil }
|
||||
return Unicode.Scalar(UInt8(truncatingIfNeeded: rawValue))
|
||||
}
|
||||
|
||||
internal var isASCII: Bool {
|
||||
(0...0x7F).contains(rawValue)
|
||||
}
|
||||
|
||||
internal var isLetter: Bool {
|
||||
guard isASCII else { return false }
|
||||
let asciiRaw: UInt8 = numericCast(rawValue)
|
||||
return (UInt8(ascii: "a") ... UInt8(ascii: "z")).contains(asciiRaw) ||
|
||||
(UInt8(ascii: "A") ... UInt8(ascii: "Z")).contains(asciiRaw)
|
||||
}
|
||||
}
|
||||
|
||||
// A platform-native string representation, currently for file paths
|
||||
//
|
||||
// Always null-terminated.
|
||||
internal struct SystemString {
|
||||
internal typealias Storage = [SystemChar]
|
||||
internal var nullTerminatedStorage: Storage
|
||||
}
|
||||
|
||||
extension SystemString {
|
||||
internal init() {
|
||||
self.nullTerminatedStorage = [.null]
|
||||
_invariantCheck()
|
||||
}
|
||||
|
||||
internal var length: Int {
|
||||
let len = nullTerminatedStorage.count - 1
|
||||
assert(len == self.count)
|
||||
return len
|
||||
}
|
||||
|
||||
// Common funnel point. Ensure all non-empty inits go here.
|
||||
internal init(nullTerminated storage: Storage) {
|
||||
self.nullTerminatedStorage = storage
|
||||
_invariantCheck()
|
||||
}
|
||||
|
||||
// Ensures that result is null-terminated
|
||||
internal init<C: Collection>(_ chars: C) where C.Element == SystemChar {
|
||||
var rawChars = Storage(chars)
|
||||
if rawChars.last != .null {
|
||||
rawChars.append(.null)
|
||||
}
|
||||
self.init(nullTerminated: rawChars)
|
||||
}
|
||||
}
|
||||
|
||||
extension SystemString {
|
||||
fileprivate func _invariantCheck() {
|
||||
#if DEBUG
|
||||
precondition(nullTerminatedStorage.last! == .null)
|
||||
precondition(nullTerminatedStorage.firstIndex(of: .null) == length)
|
||||
#endif // DEBUG
|
||||
}
|
||||
}
|
||||
|
||||
extension SystemString: RandomAccessCollection, MutableCollection {
|
||||
internal typealias Element = SystemChar
|
||||
internal typealias Index = Storage.Index
|
||||
internal typealias Indices = Range<Index>
|
||||
|
||||
internal var startIndex: Index {
|
||||
nullTerminatedStorage.startIndex
|
||||
}
|
||||
|
||||
internal var endIndex: Index {
|
||||
nullTerminatedStorage.index(before: nullTerminatedStorage.endIndex)
|
||||
}
|
||||
|
||||
internal subscript(position: Index) -> SystemChar {
|
||||
_read {
|
||||
precondition(position >= startIndex && position <= endIndex)
|
||||
yield nullTerminatedStorage[position]
|
||||
}
|
||||
set(newValue) {
|
||||
precondition(position >= startIndex && position <= endIndex)
|
||||
nullTerminatedStorage[position] = newValue
|
||||
_invariantCheck()
|
||||
}
|
||||
}
|
||||
}
|
||||
extension SystemString: RangeReplaceableCollection {
|
||||
internal mutating func replaceSubrange<C: Collection>(
|
||||
_ subrange: Range<Index>, with newElements: C
|
||||
) where C.Element == SystemChar {
|
||||
defer { _invariantCheck() }
|
||||
nullTerminatedStorage.replaceSubrange(subrange, with: newElements)
|
||||
}
|
||||
|
||||
internal mutating func reserveCapacity(_ n: Int) {
|
||||
defer { _invariantCheck() }
|
||||
nullTerminatedStorage.reserveCapacity(1 + n)
|
||||
}
|
||||
|
||||
// TODO: Below include null terminator, is this desired?
|
||||
|
||||
internal func withContiguousStorageIfAvailable<R>(
|
||||
_ body: (UnsafeBufferPointer<SystemChar>) throws -> R
|
||||
) rethrows -> R? {
|
||||
try nullTerminatedStorage.withContiguousStorageIfAvailable(body)
|
||||
}
|
||||
|
||||
internal mutating func withContiguousMutableStorageIfAvailable<R>(
|
||||
_ body: (inout UnsafeMutableBufferPointer<SystemChar>) throws -> R
|
||||
) rethrows -> R? {
|
||||
defer { _invariantCheck() }
|
||||
return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable(body)
|
||||
}
|
||||
}
|
||||
|
||||
extension SystemString: Hashable, Codable {}
|
||||
|
||||
extension SystemString {
|
||||
// TODO: Below include null terminator, is this desired?
|
||||
|
||||
internal func withSystemChars<T>(
|
||||
_ f: (UnsafeBufferPointer<SystemChar>) throws -> T
|
||||
) rethrows -> T {
|
||||
try withContiguousStorageIfAvailable(f)!
|
||||
}
|
||||
|
||||
internal func withCodeUnits<T>(
|
||||
_ f: (UnsafeBufferPointer<CInterop.PlatformUnicodeEncoding.CodeUnit>) throws -> T
|
||||
) rethrows -> T {
|
||||
try withSystemChars { chars in
|
||||
let length = chars.count * MemoryLayout<SystemChar>.stride
|
||||
let count = length / MemoryLayout<CInterop.PlatformUnicodeEncoding.CodeUnit>.stride
|
||||
return try chars.baseAddress!.withMemoryRebound(
|
||||
to: CInterop.PlatformUnicodeEncoding.CodeUnit.self,
|
||||
capacity: count
|
||||
) { pointer in
|
||||
try f(UnsafeBufferPointer(start: pointer, count: count))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Slice where Base == SystemString {
|
||||
internal func withCodeUnits<T>(
|
||||
_ f: (UnsafeBufferPointer<CInterop.PlatformUnicodeEncoding.CodeUnit>) throws -> T
|
||||
) rethrows -> T {
|
||||
try base.withCodeUnits {
|
||||
try f(UnsafeBufferPointer(rebasing: $0[indices]))
|
||||
}
|
||||
}
|
||||
|
||||
internal var string: String {
|
||||
withCodeUnits { String(decoding: $0, as: CInterop.PlatformUnicodeEncoding.self) }
|
||||
}
|
||||
|
||||
internal func withPlatformString<T>(
|
||||
_ f: (UnsafePointer<CInterop.PlatformChar>) throws -> T
|
||||
) rethrows -> T {
|
||||
// FIXME: avoid allocation if we're at the end
|
||||
return try SystemString(self).withPlatformString(f)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension String {
|
||||
internal init(decoding str: SystemString) {
|
||||
// TODO: Can avoid extra strlen
|
||||
self = str.withPlatformString {
|
||||
String(platformString: $0)
|
||||
}
|
||||
}
|
||||
internal init?(validating str: SystemString) {
|
||||
// TODO: Can avoid extra strlen
|
||||
guard let str = str.withPlatformString(String.init(validatingPlatformString:))
|
||||
else { return nil }
|
||||
|
||||
self = str
|
||||
}
|
||||
}
|
||||
|
||||
extension SystemString: ExpressibleByStringLiteral {
|
||||
internal init(stringLiteral: String) {
|
||||
self.init(stringLiteral)
|
||||
}
|
||||
|
||||
internal init(_ string: String) {
|
||||
// TODO: can avoid extra strlen
|
||||
self = string.withPlatformString {
|
||||
SystemString(platformString: $0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SystemString: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
internal var string: String { String(decoding: self) }
|
||||
|
||||
internal var description: String { string }
|
||||
internal var debugDescription: String { description.debugDescription }
|
||||
}
|
||||
|
||||
extension SystemString {
|
||||
/// Creates a system string by copying bytes from a null-terminated platform string.
|
||||
///
|
||||
/// - Parameter platformString: A pointer to a null-terminated platform string.
|
||||
internal init(platformString: UnsafePointer<CInterop.PlatformChar>) {
|
||||
let count = 1 + system_platform_strlen(platformString)
|
||||
|
||||
// TODO: Is this the right way?
|
||||
let chars: Array<SystemChar> = platformString.withMemoryRebound(
|
||||
to: SystemChar.self, capacity: count
|
||||
) {
|
||||
let bufPtr = UnsafeBufferPointer(start: $0, count: count)
|
||||
return Array(bufPtr)
|
||||
}
|
||||
|
||||
self.init(nullTerminated: chars)
|
||||
}
|
||||
|
||||
/// Calls the given closure with a pointer to the contents of the sytem string,
|
||||
/// represented as a null-terminated platform string.
|
||||
///
|
||||
/// - Parameter body: A closure with a pointer parameter
|
||||
/// that points to a null-terminated platform string.
|
||||
/// If `body` has a return value,
|
||||
/// that value is also used as the return value for this method.
|
||||
/// - Returns: The return value, if any, of the `body` closure parameter.
|
||||
///
|
||||
/// The pointer passed as an argument to `body` is valid
|
||||
/// only during the execution of this method.
|
||||
/// Don't try to store the pointer for later use.
|
||||
internal func withPlatformString<T>(
|
||||
_ f: (UnsafePointer<CInterop.PlatformChar>) throws -> T
|
||||
) rethrows -> T {
|
||||
try withSystemChars { chars in
|
||||
let length = chars.count * MemoryLayout<SystemChar>.stride
|
||||
return try chars.baseAddress!.withMemoryRebound(
|
||||
to: CInterop.PlatformChar.self,
|
||||
capacity: length / MemoryLayout<CInterop.PlatformChar>.stride
|
||||
) { pointer in
|
||||
assert(pointer[self.count] == 0)
|
||||
return try f(pointer)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: SystemString should use a COW-interchangable storage form rather
|
||||
// than array, so you could "borrow" the storage from a non-bridged String
|
||||
// or Data or whatever
|
||||
@@ -8,21 +8,21 @@
|
||||
*/
|
||||
|
||||
// Results in errno if i == -1
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
internal func valueOrErrno<I: FixedWidthInteger>(
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
private func valueOrErrno<I: FixedWidthInteger>(
|
||||
_ i: I
|
||||
) -> Result<I, Errno> {
|
||||
i == -1 ? .failure(Errno.current) : .success(i)
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
internal func nothingOrErrno<I: FixedWidthInteger>(
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
private func nothingOrErrno<I: FixedWidthInteger>(
|
||||
_ i: I
|
||||
) -> Result<(), Errno> {
|
||||
valueOrErrno(i).map { _ in () }
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
internal func valueOrErrno<I: FixedWidthInteger>(
|
||||
retryOnInterrupt: Bool, _ f: () -> I
|
||||
) -> Result<I, Errno> {
|
||||
@@ -36,17 +36,30 @@ internal func valueOrErrno<I: FixedWidthInteger>(
|
||||
} while true
|
||||
}
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
internal func nothingOrErrno<I: FixedWidthInteger>(
|
||||
retryOnInterrupt: Bool, _ f: () -> I
|
||||
) -> Result<(), Errno> {
|
||||
valueOrErrno(retryOnInterrupt: retryOnInterrupt, f).map { _ in () }
|
||||
}
|
||||
|
||||
// Run a precondition for debug client builds
|
||||
internal func _debugPrecondition(
|
||||
_ condition: @autoclosure () -> Bool, _ message: StaticString = StaticString(),
|
||||
_ condition: @autoclosure () -> Bool,
|
||||
_ message: StaticString = StaticString(),
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) {
|
||||
// Only check in debug mode.
|
||||
if _slowPath(_isDebugAssertConfiguration()) { precondition(condition()) }
|
||||
if _slowPath(_isDebugAssertConfiguration()) {
|
||||
precondition(
|
||||
condition(), String(describing: message), file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
extension OpaquePointer {
|
||||
internal var _isNULL: Bool { OpaquePointer(bitPattern: Int(bitPattern: self)) == nil }
|
||||
internal var _isNULL: Bool {
|
||||
OpaquePointer(bitPattern: Int(bitPattern: self)) == nil
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence {
|
||||
@@ -94,3 +107,23 @@ extension OptionSet {
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
internal func _dropCommonPrefix<C: Collection>(
|
||||
_ lhs: C, _ rhs: C
|
||||
) -> (C.SubSequence, C.SubSequence)
|
||||
where C.Element: Equatable {
|
||||
var (lhs, rhs) = (lhs[...], rhs[...])
|
||||
while lhs.first != nil && lhs.first == rhs.first {
|
||||
lhs.removeFirst()
|
||||
rhs.removeFirst()
|
||||
}
|
||||
return (lhs, rhs)
|
||||
}
|
||||
|
||||
extension MutableCollection where Element: Equatable {
|
||||
mutating func _replaceAll(_ e: Element, with new: Element) {
|
||||
for idx in self.indices {
|
||||
if self[idx] == e { self[idx] = new }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// TODO: Below should return an optional of what was eaten
|
||||
|
||||
extension Slice where Element: Equatable {
|
||||
internal mutating func _eat(if p: (Element) -> Bool) -> Element? {
|
||||
guard let s = self.first, p(s) else { return nil }
|
||||
self = self.dropFirst()
|
||||
return s
|
||||
}
|
||||
internal mutating func _eat(_ e: Element) -> Element? {
|
||||
_eat(if: { $0 == e })
|
||||
}
|
||||
|
||||
internal mutating func _eat(asserting e: Element) {
|
||||
let p = _eat(e)
|
||||
assert(p != nil)
|
||||
}
|
||||
|
||||
internal mutating func _eat(count c: Int) -> Slice {
|
||||
defer { self = self.dropFirst(c) }
|
||||
return self.prefix(c)
|
||||
}
|
||||
|
||||
internal mutating func _eatSequence<C: Collection>(_ es: C) -> Slice?
|
||||
where C.Element == Element
|
||||
{
|
||||
guard self.starts(with: es) else { return nil }
|
||||
return _eat(count: es.count)
|
||||
}
|
||||
|
||||
internal mutating func _eatUntil(_ idx: Index) -> Slice {
|
||||
precondition(idx >= startIndex && idx <= endIndex)
|
||||
defer { self = self[idx...] }
|
||||
return self[..<idx]
|
||||
}
|
||||
|
||||
internal mutating func _eatThrough(_ idx: Index) -> Slice {
|
||||
precondition(idx >= startIndex && idx <= endIndex)
|
||||
guard idx != endIndex else {
|
||||
defer { self = self[endIndex ..< endIndex] }
|
||||
return self
|
||||
}
|
||||
defer { self = self[index(after: idx)...] }
|
||||
return self[...idx]
|
||||
}
|
||||
|
||||
// If `e` is present, eat up to first occurence of `e`
|
||||
internal mutating func _eatUntil(_ e: Element) -> Slice? {
|
||||
guard let idx = self.firstIndex(of: e) else { return nil }
|
||||
return _eatUntil(idx)
|
||||
}
|
||||
|
||||
// If `e` is present, eat up to and through first occurence of `e`
|
||||
internal mutating func _eatThrough(_ e: Element) -> Slice? {
|
||||
guard let idx = self.firstIndex(of: e) else { return nil }
|
||||
return _eatThrough(idx)
|
||||
}
|
||||
|
||||
// Eat any elements from the front matching the predicate
|
||||
internal mutating func _eatWhile(_ p: (Element) -> Bool) -> Slice? {
|
||||
let idx = firstIndex(where: { !p($0) }) ?? endIndex
|
||||
guard idx != startIndex else { return nil }
|
||||
return _eatUntil(idx)
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
import CSystem
|
||||
|
||||
// TODO: Should CSystem just include all the header files we need?
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
import Darwin
|
||||
#elseif os(Linux) || os(FreeBSD) || os(Android)
|
||||
import Glibc
|
||||
#else
|
||||
#error("Unsupported Platform")
|
||||
#endif
|
||||
|
||||
public typealias COffT = off_t
|
||||
|
||||
// MARK: syscalls and variables
|
||||
|
||||
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
|
||||
public var system_errno: CInt {
|
||||
get { Darwin.errno }
|
||||
set { Darwin.errno = newValue }
|
||||
}
|
||||
#else
|
||||
public var system_errno: CInt {
|
||||
get { Glibc.errno }
|
||||
set { Glibc.errno = newValue }
|
||||
}
|
||||
#endif
|
||||
|
||||
public func system_open(_ path: UnsafePointer<CChar>, _ oflag: Int32) -> CInt {
|
||||
open(path, oflag)
|
||||
}
|
||||
|
||||
public func system_open(
|
||||
_ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t
|
||||
) -> CInt {
|
||||
open(path, oflag, mode)
|
||||
}
|
||||
|
||||
public func system_close(_ fd: Int32) -> Int32 {
|
||||
close(fd)
|
||||
}
|
||||
|
||||
public func system_read(
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int
|
||||
) -> Int {
|
||||
read(fd, buf, nbyte)
|
||||
}
|
||||
|
||||
public func system_pread(
|
||||
_ fd: Int32, _ buf: UnsafeMutableRawPointer!, _ nbyte: Int, _ offset: off_t
|
||||
) -> Int {
|
||||
pread(fd, buf, nbyte, offset)
|
||||
}
|
||||
|
||||
public func system_lseek(
|
||||
_ fd: Int32, _ off: off_t, _ whence: Int32
|
||||
) -> off_t {
|
||||
lseek(fd, off, whence)
|
||||
}
|
||||
|
||||
public func system_write(
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int
|
||||
) -> Int {
|
||||
write(fd, buf, nbyte)
|
||||
}
|
||||
|
||||
public func system_pwrite(
|
||||
_ fd: Int32, _ buf: UnsafeRawPointer!, _ nbyte: Int, _ offset: off_t
|
||||
) -> Int {
|
||||
pwrite(fd, buf, nbyte, offset)
|
||||
}
|
||||
|
||||
// MARK: C stdlib decls
|
||||
|
||||
public func system_strerror(_ __errnum: Int32) -> UnsafeMutablePointer<Int8>! {
|
||||
strerror(__errnum)
|
||||
}
|
||||
|
||||
public func system_strlen(_ s: UnsafePointer<Int8>) -> Int {
|
||||
strlen(s)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,3 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
import XCTest
|
||||
|
||||
import SystemTests
|
||||
|
||||
@@ -8,9 +8,14 @@
|
||||
*/
|
||||
|
||||
import XCTest
|
||||
import SystemPackage
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
#if SYSTEM_PACKAGE
|
||||
import SystemPackage
|
||||
#else
|
||||
import System
|
||||
#endif
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
final class ErrnoTest: XCTestCase {
|
||||
func testConstants() {
|
||||
XCTAssert(EPERM == Errno.notPermitted.rawValue)
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
extension FileDescriptor {
|
||||
internal func fileSize(
|
||||
retryOnInterrupt: Bool = true
|
||||
) throws -> Int64 {
|
||||
let current = try seek(offset: 0, from: .current)
|
||||
let size = try seek(offset: 0, from: .end)
|
||||
try seek(offset: current, from: .start)
|
||||
return size
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,201 @@
|
||||
*/
|
||||
|
||||
import XCTest
|
||||
import SystemPackage
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
#if SYSTEM_PACKAGE
|
||||
import SystemPackage
|
||||
#else
|
||||
import System
|
||||
#endif
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
final class FileOperationsTest: XCTestCase {
|
||||
// TODO: Mocking based testing
|
||||
func testSyscalls() {
|
||||
let fd = FileDescriptor(rawValue: 1)
|
||||
|
||||
let rawBuf = UnsafeMutableRawBufferPointer.allocate(byteCount: 100, alignment: 4)
|
||||
defer { rawBuf.deallocate() }
|
||||
let bufAddr = rawBuf.baseAddress
|
||||
let rawFD = fd.rawValue
|
||||
let bufCount = rawBuf.count
|
||||
let writeBuf = UnsafeRawBufferPointer(rawBuf)
|
||||
let writeBufAddr = writeBuf.baseAddress
|
||||
|
||||
let syscallTestCases: Array<MockTestCase> = [
|
||||
MockTestCase(name: "open", .interruptable, "a path", O_RDWR | O_APPEND) {
|
||||
retryOnInterrupt in
|
||||
_ = try FileDescriptor.open(
|
||||
"a path", .readWrite, options: [.append], retryOnInterrupt: retryOnInterrupt)
|
||||
},
|
||||
|
||||
MockTestCase(name: "open", .interruptable, "a path", O_WRONLY | O_CREAT | O_APPEND, 0o777) {
|
||||
retryOnInterrupt in
|
||||
_ = try FileDescriptor.open(
|
||||
"a path", .writeOnly, options: [.create, .append],
|
||||
permissions: [.groupReadWriteExecute, .ownerReadWriteExecute, .otherReadWriteExecute],
|
||||
retryOnInterrupt: retryOnInterrupt)
|
||||
},
|
||||
|
||||
MockTestCase(name: "read", .interruptable, rawFD, bufAddr, bufCount) {
|
||||
retryOnInterrupt in
|
||||
_ = try fd.read(into: rawBuf, retryOnInterrupt: retryOnInterrupt)
|
||||
},
|
||||
|
||||
MockTestCase(name: "pread", .interruptable, rawFD, bufAddr, bufCount, 5) {
|
||||
retryOnInterrupt in
|
||||
_ = try fd.read(fromAbsoluteOffset: 5, into: rawBuf, retryOnInterrupt: retryOnInterrupt)
|
||||
},
|
||||
|
||||
MockTestCase(name: "lseek", .noInterrupt, rawFD, -2, SEEK_END) {
|
||||
_ in
|
||||
_ = try fd.seek(offset: -2, from: .end)
|
||||
},
|
||||
|
||||
MockTestCase(name: "write", .interruptable, rawFD, writeBufAddr, bufCount) {
|
||||
retryOnInterrupt in
|
||||
_ = try fd.write(writeBuf, retryOnInterrupt: retryOnInterrupt)
|
||||
},
|
||||
|
||||
MockTestCase(name: "pwrite", .interruptable, rawFD, writeBufAddr, bufCount, 7) {
|
||||
retryOnInterrupt in
|
||||
_ = try fd.write(toAbsoluteOffset: 7, writeBuf, retryOnInterrupt: retryOnInterrupt)
|
||||
},
|
||||
|
||||
MockTestCase(name: "close", .noInterrupt, rawFD) {
|
||||
_ in
|
||||
_ = try fd.close()
|
||||
},
|
||||
|
||||
MockTestCase(name: "dup", .interruptable, rawFD) { retryOnInterrupt in
|
||||
_ = try fd.duplicate(retryOnInterrupt: retryOnInterrupt)
|
||||
},
|
||||
|
||||
MockTestCase(name: "dup2", .interruptable, rawFD, 42) { retryOnInterrupt in
|
||||
_ = try fd.duplicate(as: FileDescriptor(rawValue: 42),
|
||||
retryOnInterrupt: retryOnInterrupt)
|
||||
},
|
||||
]
|
||||
|
||||
for test in syscallTestCases { test.runAllTests() }
|
||||
}
|
||||
|
||||
func testHelpers() {
|
||||
// TODO: Test writeAll, writeAll(toAbsoluteOffset), closeAfter
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
func testAdHocPipe() throws {
|
||||
// Ad-hoc test testing `Pipe` functionality.
|
||||
// We cannot test `Pipe` using `MockTestCase` because it calls `pipe` with a pointer to an array local to the `Pipe`, the address of which we do not know prior to invoking `Pipe`.
|
||||
let pipe = try FileDescriptor.pipe()
|
||||
try pipe.readEnd.closeAfter {
|
||||
try pipe.writeEnd.closeAfter {
|
||||
var abc = "abc"
|
||||
try abc.withUTF8 {
|
||||
_ = try pipe.writeEnd.write(UnsafeRawBufferPointer($0))
|
||||
}
|
||||
let readLen = 3
|
||||
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { buf, count in
|
||||
count = try pipe.readEnd.read(into: UnsafeMutableRawBufferPointer(buf))
|
||||
}
|
||||
XCTAssertEqual(readBytes, Array(abc.utf8))
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
func testAdHocOpen() {
|
||||
// Ad-hoc test touching a file system.
|
||||
do {
|
||||
// TODO: Test this against a virtual in-memory file system
|
||||
let fd = try FileDescriptor.open("/tmp/b.txt", .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite)
|
||||
try fd.closeAfter {
|
||||
try fd.writeAll("abc".utf8)
|
||||
var def = "def"
|
||||
try def.withUTF8 {
|
||||
_ = try fd.write(UnsafeRawBufferPointer($0))
|
||||
}
|
||||
try fd.seek(offset: 1, from: .start)
|
||||
|
||||
let readLen = 3
|
||||
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { (buf, count) in
|
||||
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
|
||||
}
|
||||
let preadBytes = try Array<UInt8>(unsafeUninitializedCapacity: readLen) { (buf, count) in
|
||||
count = try fd.read(fromAbsoluteOffset: 1, into: UnsafeMutableRawBufferPointer(buf))
|
||||
}
|
||||
|
||||
XCTAssertEqual(readBytes.first!, "b".utf8.first!)
|
||||
XCTAssertEqual(readBytes, preadBytes)
|
||||
|
||||
// TODO: seek
|
||||
}
|
||||
} catch let err as Errno {
|
||||
print("caught \(err))")
|
||||
// Should we assert? I'd be interested in knowing if this happened
|
||||
XCTAssert(false)
|
||||
} catch {
|
||||
fatalError("FATAL: `testAdHocOpen`")
|
||||
}
|
||||
}
|
||||
|
||||
func testGithubIssues() {
|
||||
// https://github.com/apple/swift-system/issues/26
|
||||
let issue26 = MockTestCase(
|
||||
name: "open", .interruptable, "a path", O_WRONLY | O_CREAT, 0o020
|
||||
) {
|
||||
retryOnInterrupt in
|
||||
_ = try FileDescriptor.open(
|
||||
"a path", .writeOnly, options: [.create],
|
||||
permissions: [.groupWrite],
|
||||
retryOnInterrupt: retryOnInterrupt)
|
||||
}
|
||||
issue26.runAllTests()
|
||||
|
||||
}
|
||||
|
||||
#if !os(Windows)
|
||||
func testResizeFile() throws {
|
||||
let fd = try FileDescriptor.open("/tmp/\(UUID().uuidString).txt", .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite)
|
||||
try fd.closeAfter {
|
||||
// File should be empty initially.
|
||||
XCTAssertEqual(try fd.fileSize(), 0)
|
||||
// Write 3 bytes.
|
||||
try fd.writeAll("abc".utf8)
|
||||
// File should now be 3 bytes.
|
||||
XCTAssertEqual(try fd.fileSize(), 3)
|
||||
// Resize to 6 bytes.
|
||||
try fd.resize(to: 6)
|
||||
// File should now be 6 bytes.
|
||||
XCTAssertEqual(try fd.fileSize(), 6)
|
||||
// Read in the 6 bytes.
|
||||
let readBytes = try Array<UInt8>(unsafeUninitializedCapacity: 6) { (buf, count) in
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
// Should have read all 6 bytes.
|
||||
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
|
||||
XCTAssertEqual(count, 6)
|
||||
}
|
||||
// First 3 bytes should be unaffected by resize.
|
||||
XCTAssertEqual(Array(readBytes[..<3]), Array("abc".utf8))
|
||||
// Extension should be padded with zeros.
|
||||
XCTAssertEqual(Array(readBytes[3...]), Array(repeating: 0, count: 3))
|
||||
// File should still be 6 bytes.
|
||||
XCTAssertEqual(try fd.fileSize(), 6)
|
||||
// Resize to 2 bytes.
|
||||
try fd.resize(to: 2)
|
||||
// File should now be 2 bytes.
|
||||
XCTAssertEqual(try fd.fileSize(), 2)
|
||||
// Read in file with a buffer big enough for 6 bytes.
|
||||
let readBytesAfterTruncation = try Array<UInt8>(unsafeUninitializedCapacity: 6) { (buf, count) in
|
||||
try fd.seek(offset: 0, from: .start)
|
||||
count = try fd.read(into: UnsafeMutableRawBufferPointer(buf))
|
||||
// Should only have read 2 bytes.
|
||||
XCTAssertEqual(count, 2)
|
||||
}
|
||||
// Written content was trunctated.
|
||||
XCTAssertEqual(readBytesAfterTruncation, Array("ab".utf8))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
import XCTest
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
struct TestPathComponents: TestCase {
|
||||
var path: FilePath
|
||||
var expectedRoot: FilePath.Root?
|
||||
var expectedComponents: [FilePath.Component]
|
||||
|
||||
var pathComponents: Array<FilePath.Component> { Array(path.components) }
|
||||
|
||||
let file: StaticString
|
||||
let line: UInt
|
||||
|
||||
func failureMessage(_ reason: String?) -> String {
|
||||
"""
|
||||
|
||||
Fail \(reason ?? "")
|
||||
path: \(path)
|
||||
components: \(pathComponents))
|
||||
expected: \(expectedComponents)
|
||||
"""
|
||||
}
|
||||
|
||||
init<C: Collection>(
|
||||
_ path: FilePath,
|
||||
root: FilePath.Root?,
|
||||
_ components: C,
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) where C.Element == FilePath.Component {
|
||||
self.path = path
|
||||
self.expectedRoot = root
|
||||
self.expectedComponents = Array(components)
|
||||
self.file = file
|
||||
self.line = line
|
||||
}
|
||||
|
||||
func testComponents() {
|
||||
expectEqual(expectedRoot, path.root)
|
||||
expectEqualSequence(
|
||||
expectedComponents, Array(path.components), "testComponents()")
|
||||
}
|
||||
|
||||
func testBidi() {
|
||||
expectEqualSequence(
|
||||
expectedComponents.reversed(), path.components.reversed(), "reversed()")
|
||||
expectEqualSequence(
|
||||
path.components, path.components.reversed().reversed(),
|
||||
"reversed().reversed()")
|
||||
for i in 0 ..< path.components.count {
|
||||
expectEqualSequence(
|
||||
expectedComponents.dropLast(i), path.components.dropLast(i), "dropLast")
|
||||
expectEqualSequence(
|
||||
expectedComponents.suffix(i), path.components.suffix(i), "suffix")
|
||||
}
|
||||
}
|
||||
|
||||
func testRRC() {
|
||||
// TODO: programmatic tests showing parity with Array<Component>
|
||||
}
|
||||
|
||||
func testModify() {
|
||||
if path.root == nil {
|
||||
let rootedPath = FilePath(root: "/", path.components)
|
||||
expectNotEqual(rootedPath, path)
|
||||
var pathCopy = path
|
||||
expectEqual(path, pathCopy)
|
||||
pathCopy.components = rootedPath.components
|
||||
expectNil(pathCopy.root, "components.set doesn't assign root")
|
||||
expectEqual(path, pathCopy)
|
||||
} else {
|
||||
let rootlessPath = FilePath(root: nil, path.components)
|
||||
var pathCopy = path
|
||||
expectEqual(path, pathCopy)
|
||||
pathCopy.components = rootlessPath.components
|
||||
expectNotNil(pathCopy.root, "components.set preserves root")
|
||||
expectEqual(path, pathCopy)
|
||||
}
|
||||
}
|
||||
|
||||
func runAllTests() {
|
||||
testComponents()
|
||||
testBidi()
|
||||
testRRC()
|
||||
testModify()
|
||||
}
|
||||
}
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
final class FilePathComponentsTest: XCTestCase {
|
||||
func testAdHocRRC() {
|
||||
var path: FilePath = "/usr/local/bin"
|
||||
|
||||
func expect(
|
||||
_ s: String,
|
||||
_ file: StaticString = #file,
|
||||
_ line: UInt = #line
|
||||
) {
|
||||
if path == FilePath(s) { return }
|
||||
|
||||
defer { print("expected: \(s), actual: \(path)") }
|
||||
XCTAssert(false, file: file, line: line)
|
||||
}
|
||||
|
||||
// Run `body`, restoring `path` afterwards
|
||||
func restoreAfter(
|
||||
body: () -> ()
|
||||
) {
|
||||
let copy = path
|
||||
defer { path = copy }
|
||||
body()
|
||||
}
|
||||
|
||||
// Interior removal keeps path prefix intact, if there is one
|
||||
restoreAfter {
|
||||
path = "prefix//middle1/middle2////suffix"
|
||||
let suffix = path.components.indices.last!
|
||||
path.components.removeSubrange(..<suffix)
|
||||
expect("suffix")
|
||||
}
|
||||
|
||||
restoreAfter {
|
||||
path = "prefix//middle1/middle2////suffix"
|
||||
let firstMiddle = path.components.index(
|
||||
path.components.startIndex, offsetBy: 1)
|
||||
let suffix = path.components.indices.last!
|
||||
path.components.removeSubrange(firstMiddle ..< suffix)
|
||||
expect("prefix/suffix")
|
||||
}
|
||||
|
||||
restoreAfter {
|
||||
path.components.removeFirst()
|
||||
expect("/local/bin")
|
||||
path.components.removeFirst()
|
||||
expect("/bin")
|
||||
}
|
||||
|
||||
restoreAfter {
|
||||
path.components.insert(
|
||||
contentsOf: ["bar", "baz"], at: path.components.startIndex)
|
||||
expect("/bar/baz/usr/local/bin")
|
||||
}
|
||||
|
||||
restoreAfter {
|
||||
path.components.insert("start", at: path.components.startIndex)
|
||||
expect("/start/usr/local/bin")
|
||||
path.components.insert("prefix", at: path.components.startIndex)
|
||||
expect("/prefix/start/usr/local/bin")
|
||||
path.components.removeSubrange(
|
||||
..<path.components.index(path.components.startIndex, offsetBy: 4))
|
||||
expect("/bin")
|
||||
path.components.removeFirst()
|
||||
expect("/")
|
||||
path.components.append(contentsOf: ["usr", "local", "bin"])
|
||||
expect("/usr/local/bin")
|
||||
path.components.removeLast(2)
|
||||
expect("/usr")
|
||||
}
|
||||
|
||||
restoreAfter {
|
||||
path.root = nil
|
||||
expect("usr/local/bin")
|
||||
path.components.removeAll()
|
||||
expect("")
|
||||
path.components.insert("foo", at: path.components.startIndex)
|
||||
expect("foo")
|
||||
|
||||
path.components.removeAll()
|
||||
path.components.insert(
|
||||
contentsOf: ["bar", "baz"], at: path.components.startIndex)
|
||||
expect("bar/baz")
|
||||
}
|
||||
|
||||
restoreAfter {
|
||||
path.components.append("tail")
|
||||
expect("/usr/local/bin/tail")
|
||||
path.components.append(contentsOf: ["tail2", "tail3", "tail4"])
|
||||
expect("/usr/local/bin/tail/tail2/tail3/tail4")
|
||||
}
|
||||
|
||||
// Insertion into the middle adds trailing separator
|
||||
restoreAfter {
|
||||
path.components.remove(
|
||||
at: path.components.index(after: path.components.startIndex))
|
||||
expect("/usr/bin")
|
||||
path.components.insert("middle", at: path.components.indices.last!)
|
||||
expect("/usr/middle/bin")
|
||||
path.components.insert(
|
||||
contentsOf: ["middle2", "middle3"], at: path.components.indices.last!)
|
||||
expect("/usr/middle/middle2/middle3/bin")
|
||||
|
||||
let slice = path.components.dropFirst().dropLast()
|
||||
let range = slice.startIndex ..< slice.endIndex
|
||||
path.components.replaceSubrange(
|
||||
range, with: ["newMiddle", "newMiddle2", "newMiddle3", "newMiddle4/"])
|
||||
expect("/usr/newMiddle/newMiddle2/newMiddle3/newMiddle4/bin")
|
||||
}
|
||||
|
||||
restoreAfter {
|
||||
path.components.removeLast(3)
|
||||
expect("/")
|
||||
path.components.append(contentsOf: ["bar", "baz"])
|
||||
expect("/bar/baz")
|
||||
}
|
||||
|
||||
// Empty insertions / removals
|
||||
restoreAfter {
|
||||
path.components.replaceSubrange(..<path.components.startIndex, with: [])
|
||||
expect("/usr/local/bin")
|
||||
path.components.replaceSubrange(path.components.endIndex..., with: [])
|
||||
expect("/usr/local/bin")
|
||||
path.components.insert(contentsOf: [], at: path.components.startIndex)
|
||||
expect("/usr/local/bin")
|
||||
path.components.insert(contentsOf: [], at: path.components.indices.last!)
|
||||
expect("/usr/local/bin")
|
||||
}
|
||||
}
|
||||
|
||||
func testCases() {
|
||||
let testPaths: Array<TestPathComponents> = [
|
||||
TestPathComponents("", root: nil, []),
|
||||
TestPathComponents("/", root: "/", []),
|
||||
TestPathComponents("foo", root: nil, ["foo"]),
|
||||
TestPathComponents("foo/", root: nil, ["foo"]),
|
||||
TestPathComponents("/foo", root: "/", ["foo"]),
|
||||
TestPathComponents("foo/bar", root: nil, ["foo", "bar"]),
|
||||
TestPathComponents("foo/bar/", root: nil, ["foo", "bar"]),
|
||||
TestPathComponents("/foo/bar", root: "/", ["foo", "bar"]),
|
||||
TestPathComponents("///foo//", root: "/", ["foo"]),
|
||||
TestPathComponents("/foo///bar", root: "/", ["foo", "bar"]),
|
||||
TestPathComponents("foo/bar/", root: nil, ["foo", "bar"]),
|
||||
TestPathComponents("foo///bar/baz/", root: nil, ["foo", "bar", "baz"]),
|
||||
TestPathComponents("//foo///bar/baz/", root: "/", ["foo", "bar", "baz"]),
|
||||
TestPathComponents("./", root: nil, ["."]),
|
||||
TestPathComponents("./..", root: nil, [".", ".."]),
|
||||
TestPathComponents("/./..//", root: "/", [".", ".."]),
|
||||
]
|
||||
testPaths.forEach { $0.runAllTests() }
|
||||
}
|
||||
|
||||
func testSeparatorNormalization() {
|
||||
var paths: Array<FilePath> = [
|
||||
"/a/b",
|
||||
"/a/b/",
|
||||
"/a//b/",
|
||||
"/a/b//",
|
||||
"/a/b////",
|
||||
"/a////b/",
|
||||
]
|
||||
#if !os(Windows)
|
||||
paths.append("//a/b")
|
||||
paths.append("///a/b")
|
||||
paths.append("///a////b")
|
||||
paths.append("///a////b///")
|
||||
#endif
|
||||
|
||||
for path in paths {
|
||||
var path = path
|
||||
path._normalizeSeparators()
|
||||
XCTAssertEqual(path, "/a/b")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Test hashValue and equatable for equal components, i.e. make
|
||||
// sure indices are not part of the hash.
|
||||
@@ -0,0 +1,108 @@
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
// Why can't I write this extension on `FilePath.ComponentView.SubSequence`?
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension Slice where Base == FilePath.ComponentView {
|
||||
internal var _storageSlice: SystemString.SubSequence {
|
||||
base._path._storage[self.startIndex._storage ..< self.endIndex._storage]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Proposed API that didn't make the cut, but we stil want to keep our testing for
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
extension FilePath {
|
||||
/// Returns `self` relative to `base`.
|
||||
/// This does not cosult the file system or resolve symlinks.
|
||||
///
|
||||
/// Returns `nil` if `self.root != base.root`.
|
||||
///
|
||||
/// On Windows, if any component of either path could be interpreted as the root of
|
||||
/// a traditional DOS path (e.g. a directory named `C:`), returns `nil`.
|
||||
///
|
||||
/// Example:
|
||||
///
|
||||
/// let path: FilePath = "/usr/local/bin"
|
||||
/// path.lexicallyRelative(toBase: "/usr/local") == "bin"
|
||||
/// path.lexicallyRelative(toBase: "/usr/local/bin/ls") == ".."
|
||||
/// path.lexicallyRelative(toBase: "/tmp/foo.txt") == "../../usr/local/bin"
|
||||
/// path.lexicallyRelative(toBase: "local/bin") == nil
|
||||
internal func lexicallyRelative(toBase base: FilePath) -> FilePath? {
|
||||
guard root == base.root else { return nil }
|
||||
|
||||
// FIXME: On Windows, return nil if any component looks like a root
|
||||
|
||||
let (tail, baseTail) = _dropCommonPrefix(components, base.components)
|
||||
|
||||
var prefix = SystemString()
|
||||
for _ in 0..<baseTail.count {
|
||||
prefix.append(.dot)
|
||||
prefix.append(.dot)
|
||||
prefix.append(platformSeparator)
|
||||
}
|
||||
|
||||
return FilePath(prefix + tail._storageSlice)
|
||||
}
|
||||
|
||||
/// Whether a lexically-normalized `self` contains a lexically-normalized
|
||||
/// `other`.
|
||||
///
|
||||
public func lexicallyContains(_ other: FilePath) -> Bool {
|
||||
guard !other.isEmpty else { return true }
|
||||
guard !isEmpty else { return false }
|
||||
|
||||
let (selfLex, otherLex) =
|
||||
(self.lexicallyNormalized(), other.lexicallyNormalized())
|
||||
if otherLex.isAbsolute { return selfLex.starts(with: otherLex) }
|
||||
|
||||
// FIXME: Windows semantics with relative roots?
|
||||
|
||||
// TODO: better than this naive algorithm
|
||||
var slice = selfLex.components[...]
|
||||
while !slice.isEmpty {
|
||||
if slice.starts(with: otherLex.components) { return true }
|
||||
slice = slice.dropFirst()
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection where Element: Equatable, SubSequence == Slice<Self> {
|
||||
// Mock up RangeSet functionality until it's real
|
||||
func indices(where p: (Element) throws -> Bool) rethrows -> [Range<Index>] {
|
||||
var result = Array<Range<Index>>()
|
||||
guard !isEmpty else { return result }
|
||||
|
||||
var i = startIndex
|
||||
while i != endIndex {
|
||||
let next = index(after: i)
|
||||
if try p(self[i]) {
|
||||
result.append(i..<next)
|
||||
}
|
||||
i = next
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
extension RangeReplaceableCollection {
|
||||
mutating func removeSubranges(_ subranges: [Range<Index>]) {
|
||||
guard !subranges.isEmpty else { return }
|
||||
|
||||
var result = Self()
|
||||
var idx = startIndex
|
||||
for range in subranges {
|
||||
result.append(contentsOf: self[idx..<range.lowerBound])
|
||||
idx = range.upperBound
|
||||
}
|
||||
if idx != endIndex {
|
||||
result.append(contentsOf: self[idx...])
|
||||
}
|
||||
self = result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
import XCTest
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
import SystemPackage
|
||||
#else
|
||||
import System
|
||||
#endif
|
||||
|
||||
private struct ParsingTestCase: TestCase {
|
||||
// Whether we want the path to be constructed and syntactically
|
||||
// manipulated as though it were a Windows path
|
||||
let isWindows: Bool
|
||||
|
||||
// We defer forming the path until `runAllTests()` executes,
|
||||
// so that we can switch between unix and windows behavior.
|
||||
var pathStr: String
|
||||
|
||||
// The expected path post separator normalization
|
||||
var normalized: String
|
||||
|
||||
var file: StaticString
|
||||
var line: UInt
|
||||
}
|
||||
|
||||
extension ParsingTestCase {
|
||||
static func unix(
|
||||
_ path: String, normalized: String,
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) -> ParsingTestCase {
|
||||
ParsingTestCase(
|
||||
isWindows: false,
|
||||
pathStr: path, normalized: normalized,
|
||||
file: file, line: line)
|
||||
}
|
||||
|
||||
static func windows(
|
||||
_ path: String, normalized: String,
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) -> ParsingTestCase {
|
||||
ParsingTestCase(
|
||||
isWindows: true,
|
||||
pathStr: path, normalized: normalized,
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
extension ParsingTestCase {
|
||||
func runAllTests() {
|
||||
withWindowsPaths(enabled: isWindows) {
|
||||
let path = FilePath(pathStr)
|
||||
expectEqual(normalized, path.description)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
final class FilePathParsingTest: XCTestCase {
|
||||
func testNormalization() {
|
||||
let unixPaths: Array<ParsingTestCase> = [
|
||||
.unix("/", normalized: "/"),
|
||||
.unix("", normalized: ""),
|
||||
.unix("//", normalized: "/"),
|
||||
.unix("///", normalized: "/"),
|
||||
.unix("/foo/bar/", normalized: "/foo/bar"),
|
||||
.unix("foo//bar", normalized: "foo/bar"),
|
||||
.unix("//foo/bar//baz/", normalized: "/foo/bar/baz"),
|
||||
.unix("/foo/bar/baz//", normalized: "/foo/bar/baz"),
|
||||
.unix("/foo/bar/baz///", normalized: "/foo/bar/baz"),
|
||||
]
|
||||
|
||||
let windowsPaths: Array<ParsingTestCase> = [
|
||||
.windows(#"C:\\folder\file\"#, normalized: #"C:\folder\file"#),
|
||||
.windows(#"C:folder\\\file\\\"#, normalized: #"C:folder\file"#),
|
||||
.windows(#"C:/foo//bar/"#, normalized: #"C:\foo\bar"#),
|
||||
|
||||
.windows(#"\\server\share\"#, normalized: #"\\server\share\"#),
|
||||
.windows(#"//server/share/"#, normalized: #"\\server\share\"#),
|
||||
.windows(#"\\?\UNC/server\share\"#, normalized: #"\\?\UNC\server\share\"#),
|
||||
|
||||
.windows(#"\\.\C:\"#, normalized: #"\\.\C:\"#),
|
||||
.windows(#"C:\"#, normalized: #"C:\"#),
|
||||
.windows(#"\"#, normalized: #"\"#),
|
||||
]
|
||||
|
||||
for test in unixPaths {
|
||||
test.runAllTests()
|
||||
}
|
||||
for test in windowsPaths {
|
||||
test.runAllTests()
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+15
-13
@@ -8,27 +8,28 @@
|
||||
*/
|
||||
|
||||
import XCTest
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
import SystemPackage
|
||||
#else
|
||||
import System
|
||||
#endif
|
||||
|
||||
extension UnsafePointer where Pointee == UInt8 {
|
||||
internal var _asCChar: UnsafePointer<CChar> {
|
||||
UnsafeRawPointer(self).assumingMemoryBound(to: CChar.self)
|
||||
}
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
func filePathFromUnterminatedBytes<S: Sequence>(_ bytes: S) -> FilePath where S.Element == UInt8 {
|
||||
var array = Array(bytes)
|
||||
assert(array.last != 0, "already null terminated")
|
||||
array += [0]
|
||||
|
||||
return array.withUnsafeBufferPointer {
|
||||
FilePath(cString: $0.baseAddress!._asCChar)
|
||||
$0.withMemoryRebound(to: CChar.self) {
|
||||
FilePath(platformString: $0.baseAddress!)
|
||||
}
|
||||
}
|
||||
}
|
||||
let invalidBytes: [UInt8] = [0x2F, 0x61, 0x2F, 0x62, 0x2F, 0x83]
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
final class FilePathTest: XCTestCase {
|
||||
struct TestPath {
|
||||
let filePath: FilePath
|
||||
@@ -58,17 +59,18 @@ final class FilePathTest: XCTestCase {
|
||||
|
||||
XCTAssertEqual(testPath.string, String(decoding: testPath.filePath))
|
||||
|
||||
// TODO: test component UTF8 validation
|
||||
if testPath.validUTF8 {
|
||||
XCTAssertEqual(testPath.filePath, FilePath(testPath.string))
|
||||
XCTAssertEqual(testPath.string, String(validatingUTF8: testPath.filePath))
|
||||
XCTAssertEqual(testPath.string, String(validating: testPath.filePath))
|
||||
} else {
|
||||
XCTAssertNotEqual(testPath.filePath, FilePath(testPath.string))
|
||||
XCTAssertNil(String(validatingUTF8: testPath.filePath))
|
||||
XCTAssertNil(String(validating: testPath.filePath))
|
||||
}
|
||||
|
||||
testPath.filePath.withCString {
|
||||
testPath.filePath.withPlatformString {
|
||||
XCTAssertEqual(testPath.string, String(cString: $0))
|
||||
XCTAssertEqual(testPath.filePath, FilePath(cString: $0))
|
||||
XCTAssertEqual(testPath.filePath, FilePath(platformString: $0))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,28 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 Apple Inc. and the Swift System project authors
|
||||
Copyright (c) 2020 - 2021 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
|
||||
*/
|
||||
|
||||
import XCTest
|
||||
import SystemPackage
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
#if SYSTEM_PACKAGE
|
||||
import SystemPackage
|
||||
#else
|
||||
import System
|
||||
#endif
|
||||
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
final class FileDescriptorTest: XCTestCase {
|
||||
func testStandardDescriptors() {
|
||||
XCTAssertEqual(FileDescriptor.standardInput.rawValue, 0)
|
||||
XCTAssertEqual(FileDescriptor.standardOutput.rawValue, 1)
|
||||
XCTAssertEqual(FileDescriptor.standardError.rawValue, 2)
|
||||
}
|
||||
|
||||
// Test the constants match the C header values. For various reasons,
|
||||
func testConstants() {
|
||||
XCTAssertEqual(O_RDONLY, FileDescriptor.AccessMode.readOnly.rawValue)
|
||||
@@ -49,7 +60,7 @@ final class FileDescriptorTest: XCTestCase {
|
||||
|
||||
}
|
||||
|
||||
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
|
||||
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
|
||||
final class FilePermissionsTest: XCTestCase {
|
||||
|
||||
func testPermissions() {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
import XCTest
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
final class MockingTest: XCTestCase {
|
||||
func testMocking() {
|
||||
XCTAssertFalse(mockingEnabled)
|
||||
MockingDriver.withMockingEnabled { driver in
|
||||
XCTAssertTrue(mockingEnabled)
|
||||
XCTAssertTrue(driver === currentMockingDriver)
|
||||
|
||||
XCTAssertEqual(driver.forceErrno, .none)
|
||||
let forced = ForceErrno.always(errno: 42)
|
||||
driver.forceErrno = forced
|
||||
XCTAssertEqual(driver.forceErrno, forced)
|
||||
|
||||
// Test that a nested call swaps in a new driver and restores the old one after
|
||||
MockingDriver.withMockingEnabled { nestedDriver in
|
||||
XCTAssertTrue(mockingEnabled)
|
||||
XCTAssertTrue(nestedDriver === currentMockingDriver)
|
||||
XCTAssertFalse(nestedDriver === driver)
|
||||
XCTAssertEqual(nestedDriver.forceErrno, .none)
|
||||
}
|
||||
|
||||
XCTAssertTrue(mockingEnabled)
|
||||
XCTAssertEqual(driver.forceErrno, forced)
|
||||
}
|
||||
XCTAssertFalse(mockingEnabled)
|
||||
|
||||
// Mocking should be enabled even if we do not refer to the driver
|
||||
MockingDriver.withMockingEnabled { _ in
|
||||
XCTAssertTrue(mockingEnabled)
|
||||
}
|
||||
XCTAssertFalse(mockingEnabled)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
This source file is part of the Swift System open source project
|
||||
|
||||
Copyright (c) 2020 - 2021 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
|
||||
*/
|
||||
|
||||
import XCTest
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
final class SystemCharTest: XCTestCase {
|
||||
func testIsLetter() {
|
||||
let valid = SystemString(
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
|
||||
for char in valid {
|
||||
XCTAssertTrue(char.isLetter)
|
||||
}
|
||||
|
||||
// non printable
|
||||
for value in 0..<(UInt8(ascii: " ")) {
|
||||
XCTAssertFalse(SystemChar(codeUnit: value).isLetter)
|
||||
}
|
||||
XCTAssertFalse(SystemChar(codeUnit: 0x7F).isLetter) // DEL
|
||||
|
||||
// misc other
|
||||
let invalid = SystemString(
|
||||
##" !"#$%&'()*+,-./0123456789:;<=>?@[\]^_`{|}~"##)
|
||||
for char in invalid {
|
||||
XCTAssertFalse(char.isLetter)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// Tests for PlatformString, SystemString, and FilePath's forwarding APIs
|
||||
|
||||
// TODO: Adapt test to Windows
|
||||
|
||||
import XCTest
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
private func makeRaw(
|
||||
_ str: String
|
||||
) -> [CInterop.PlatformChar] {
|
||||
var str = str
|
||||
var array = str.withUTF8 { $0.withMemoryRebound(to: CChar.self, Array.init) }
|
||||
array.append(0)
|
||||
return array
|
||||
}
|
||||
private func makeStr(
|
||||
_ raw: [CInterop.PlatformChar]
|
||||
) -> String {
|
||||
precondition((raw.last ?? 0) == 0)
|
||||
// FIXME: Unfortunately, this relies on some of the same mechanisms tested...
|
||||
return raw.withUnsafeBufferPointer {
|
||||
String(platformString: $0.baseAddress!)
|
||||
}
|
||||
}
|
||||
|
||||
struct StringTest: TestCase {
|
||||
// The error-corrected string
|
||||
var string: String
|
||||
|
||||
// The raw contents
|
||||
var raw: [CInterop.PlatformChar]
|
||||
|
||||
var isValid: Bool
|
||||
|
||||
var file: StaticString
|
||||
var line: UInt
|
||||
|
||||
func runAllTests() {
|
||||
precondition((raw.last ?? 0) == 0, "invalid test case")
|
||||
|
||||
// Test idempotence post-validation
|
||||
string.withPlatformString {
|
||||
if isValid {
|
||||
let len = system_platform_strlen($0)
|
||||
expectEqual(raw.count, 1+len, "Validation idempotence")
|
||||
expectEqualSequence(raw, UnsafeBufferPointer(start: $0, count: 1+len),
|
||||
"Validation idempotence")
|
||||
}
|
||||
|
||||
let str = String(platformString: $0)
|
||||
expectEqualSequence(
|
||||
string.unicodeScalars, str.unicodeScalars, "Validation idempotence")
|
||||
|
||||
let validStr = String(validatingPlatformString: $0)
|
||||
expectEqual(string, validStr, "Validation idempotence")
|
||||
}
|
||||
|
||||
// Test String, SystemString, FilePath construction
|
||||
let sysStr = SystemString(string)
|
||||
expectEqualSequence(string.unicodeScalars, sysStr.string.unicodeScalars)
|
||||
expectEqual(string, String(decoding: sysStr))
|
||||
expectEqual(string, String(validating: sysStr))
|
||||
|
||||
let sysRaw = raw.withUnsafeBufferPointer {
|
||||
SystemString(platformString: $0.baseAddress!)
|
||||
}
|
||||
expectEqual(string, String(decoding: sysRaw))
|
||||
expectEqual(isValid, nil != String(validating: sysRaw))
|
||||
expectEqual(isValid, sysStr == sysRaw)
|
||||
|
||||
let strDecoded = raw.withUnsafeBufferPointer {
|
||||
String(platformString: $0.baseAddress!)
|
||||
}
|
||||
expectEqualSequence(string.unicodeScalars, strDecoded.unicodeScalars)
|
||||
|
||||
let strValidated = raw.withUnsafeBufferPointer {
|
||||
String(validatingPlatformString: $0.baseAddress!)
|
||||
}
|
||||
expectEqual(isValid, strValidated != nil, "String(validatingPlatformString:)")
|
||||
expectEqual(isValid, strDecoded == strValidated,
|
||||
"String(validatingPlatformString:)")
|
||||
|
||||
// Test null insertion
|
||||
let rawChars = raw.lazy.map { SystemChar($0) }
|
||||
expectEqual(sysRaw, SystemString(rawChars.dropLast()))
|
||||
sysRaw.withSystemChars { // TODO: assuming we want null in withSysChars
|
||||
expectEqualSequence(rawChars, $0, "rawChars")
|
||||
}
|
||||
|
||||
// Whether the content has normalized separators
|
||||
let hasNormalSeparators: Bool = {
|
||||
var normalSys = sysRaw
|
||||
normalSys._normalizeSeparators()
|
||||
return normalSys == sysRaw
|
||||
}()
|
||||
|
||||
let fpStr = FilePath(string)
|
||||
if hasNormalSeparators {
|
||||
expectEqualSequence(
|
||||
string.unicodeScalars, fpStr.string.unicodeScalars, "FilePath from string")
|
||||
expectEqual(string, String(decoding: fpStr), "FilePath from string")
|
||||
expectEqual(string, String(validating: fpStr), "FilePath from string")
|
||||
expectEqual(sysStr, fpStr._storage, "FilePath from string")
|
||||
}
|
||||
|
||||
let fpRaw = FilePath(sysRaw)
|
||||
if hasNormalSeparators {
|
||||
expectEqual(string, String(decoding: fpRaw), "raw FilePath")
|
||||
expectEqual(isValid, nil != String(validating: fpRaw), "raw FilePath")
|
||||
expectEqual(sysRaw, fpRaw._storage, "raw FilePath")
|
||||
expectEqual(isValid, fpStr == fpRaw, "raw FilePath")
|
||||
}
|
||||
fpRaw.withPlatformString { fp0 in
|
||||
fpRaw._storage.withPlatformString { storage0 in
|
||||
expectEqual(fp0, storage0,
|
||||
"FilePath withPlatformString address forwarding")
|
||||
}
|
||||
}
|
||||
|
||||
let isComponent = string == fpRaw.components.first?.string
|
||||
|
||||
if hasNormalSeparators && isComponent {
|
||||
// Test FilePath.Component
|
||||
let compStr = FilePath.Component(string)!
|
||||
expectEqualSequence(
|
||||
string.unicodeScalars, compStr.string.unicodeScalars, "Component from string")
|
||||
expectEqual(string, String(decoding: compStr), "Component from string")
|
||||
expectEqual(string, String(validating: compStr), "Component from string")
|
||||
expectEqual(sysStr, compStr._slice.base, "Component from string")
|
||||
|
||||
let compRaw = FilePath.Component(sysRaw)!
|
||||
expectEqual(string, String(decoding: compRaw), "raw Component")
|
||||
expectEqual(isValid, nil != String(validating: compRaw), "raw Component")
|
||||
expectEqual(sysRaw, compRaw._slice.base, "raw Component")
|
||||
expectEqual(isValid, compStr == compRaw, "raw Component")
|
||||
|
||||
// TODO: Below works after we add last component optimization
|
||||
// compRaw.withPlatformString { fp0 in
|
||||
// compRaw.slice.base.withPlatformString { storage0 in
|
||||
// expectEqual(fp0, storage0,
|
||||
// "Component withPlatformString address forwarding")
|
||||
// }
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
sysRaw.withPlatformString {
|
||||
let len = system_platform_strlen($0)
|
||||
expectEqual(raw.count, 1+len, "SystemString.withPlatformString")
|
||||
expectEqualSequence(raw, UnsafeBufferPointer(start: $0, count: 1+len),
|
||||
"SystemString.withPlatformString")
|
||||
if hasNormalSeparators {
|
||||
expectEqual(sysRaw, FilePath(platformString: $0)._storage)
|
||||
if isComponent {
|
||||
expectEqual(
|
||||
sysRaw, FilePath.Component(platformString: $0)!._slice.base)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
extension StringTest {
|
||||
|
||||
static func valid(
|
||||
_ str: String,
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) -> StringTest {
|
||||
StringTest(
|
||||
string: str,
|
||||
raw: makeRaw(str),
|
||||
isValid: true,
|
||||
file: file, line: line)
|
||||
}
|
||||
|
||||
static func invalid(
|
||||
_ raw: [CInterop.PlatformChar],
|
||||
file: StaticString = #file, line: UInt = #line
|
||||
) -> StringTest {
|
||||
StringTest(
|
||||
string: makeStr(raw),
|
||||
raw: raw,
|
||||
isValid: false,
|
||||
file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
final class SystemStringTest: XCTestCase {
|
||||
|
||||
let validCases: Array<StringTest> = [
|
||||
.valid(""),
|
||||
.valid("a"),
|
||||
.valid("abc"),
|
||||
.valid("/あ/🧟♀️"),
|
||||
.valid("/あ\\🧟♀️"),
|
||||
.valid("/あ\\🧟♀️///"),
|
||||
.valid("あ_🧟♀️"),
|
||||
.valid("/a/b/c"),
|
||||
.valid("/a/b/c//"),
|
||||
.valid(#"\a\b\c\\"#),
|
||||
.valid("_a_b_c"),
|
||||
]
|
||||
|
||||
#if os(Windows)
|
||||
let invalidCases: Array<StringTest> = [
|
||||
// TODO: Unpaired surrogates
|
||||
]
|
||||
#else
|
||||
let invalidCases: Array<StringTest> = [
|
||||
.invalid([CChar(bitPattern: 0x80), 0]),
|
||||
.invalid([CChar(bitPattern: 0xFF), 0]),
|
||||
.invalid([0x2F, 0x61, 0x2F, 0x62, 0x2F, CChar(bitPattern: 0x83), 0]),
|
||||
]
|
||||
#endif
|
||||
|
||||
func testPlatformString() {
|
||||
for test in validCases {
|
||||
test.runAllTests()
|
||||
}
|
||||
for test in invalidCases {
|
||||
test.runAllTests()
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: More exhaustive RAC+RRC SystemString tests
|
||||
|
||||
func testAdHoc() {
|
||||
var str: SystemString = "abc"
|
||||
str.append(SystemChar(ascii: "d"))
|
||||
XCTAssert(str == "abcd")
|
||||
XCTAssert(str.count == 4)
|
||||
XCTAssert(str.count == str.length)
|
||||
|
||||
str.reserveCapacity(100)
|
||||
XCTAssert(str == "abcd")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SystemStringTest {
|
||||
func test_String_initWithArrayConversion() {
|
||||
let source: [CInterop.PlatformChar] = [0x61, 0x62, 0, 0x63]
|
||||
let str = String(platformString: source)
|
||||
source.withUnsafeBufferPointer {
|
||||
XCTAssertEqual(str, String(platformString: $0.baseAddress!))
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_String_initWithStringConversion() {
|
||||
let source = "ab\0c"
|
||||
var str: String
|
||||
str = String(platformString: source)
|
||||
source.withPlatformString {
|
||||
XCTAssertEqual(str, String(platformString: $0))
|
||||
}
|
||||
str = String(platformString: "")
|
||||
XCTAssertEqual(str.isEmpty, true)
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_String_initWithInoutConversion() {
|
||||
var c: CInterop.PlatformChar = 0
|
||||
let str = String(platformString: &c)
|
||||
// Any other value of `c` would violate the null-terminated precondition
|
||||
XCTAssertEqual(str.isEmpty, true)
|
||||
}
|
||||
|
||||
func test_String_validatingPlatformStringWithArrayConversion() {
|
||||
var source: [CInterop.PlatformChar] = [0x61, 0x62, 0, 0x63]
|
||||
var str: String?
|
||||
str = String(validatingPlatformString: source)
|
||||
source.withUnsafeBufferPointer {
|
||||
XCTAssertEqual(str, String(validatingPlatformString: $0.baseAddress!))
|
||||
}
|
||||
source[1] = CInterop.PlatformChar(truncatingIfNeeded: 0xffff)
|
||||
str = String(validatingPlatformString: source)
|
||||
XCTAssertNil(str)
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_String_validatingPlatformStringWithStringConversion() {
|
||||
let source = "ab\0c"
|
||||
var str: String?
|
||||
str = String(validatingPlatformString: source)
|
||||
XCTAssertNotNil(str)
|
||||
source.withPlatformString {
|
||||
XCTAssertEqual(str, String.init(validatingPlatformString: $0))
|
||||
}
|
||||
str = String(validatingPlatformString: "")
|
||||
XCTAssertNotNil(str)
|
||||
XCTAssertEqual(str?.isEmpty, true)
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_String_validatingPlatformStringWithInoutConversion() {
|
||||
var c: CInterop.PlatformChar = 0
|
||||
let str = String(validatingPlatformString: &c)
|
||||
// Any other value of `c` would violate the null-terminated precondition
|
||||
XCTAssertNotNil(str)
|
||||
XCTAssertEqual(str?.isEmpty, true)
|
||||
}
|
||||
|
||||
func test_FilePath_initWithArrayConversion() {
|
||||
let source: [CInterop.PlatformChar] = [0x61, 0x62, 0, 0x63]
|
||||
let path = FilePath(platformString: source)
|
||||
source.withUnsafeBufferPointer {
|
||||
XCTAssertEqual(path, FilePath(platformString: $0.baseAddress!))
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_FilePath_initWithStringConversion() {
|
||||
let source = "ab\0c"
|
||||
var path: FilePath
|
||||
path = FilePath(platformString: source)
|
||||
source.withPlatformString {
|
||||
XCTAssertEqual(path, FilePath(platformString: $0))
|
||||
}
|
||||
path = FilePath(platformString: "")
|
||||
XCTAssertEqual(path.string.isEmpty, true)
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_FilePath_initWithInoutConversion() {
|
||||
var c: CInterop.PlatformChar = 0
|
||||
let path = FilePath(platformString: &c)
|
||||
// Any other value of `c` would violate the null-terminated precondition
|
||||
XCTAssertEqual(path.string.isEmpty, true)
|
||||
}
|
||||
|
||||
func test_FilePathComponent_initWithArrayConversion() {
|
||||
var source: [CInterop.PlatformChar] = [0x61, 0x62, 0, 0x63]
|
||||
var component: FilePath.Component?
|
||||
component = FilePath.Component(platformString: source)
|
||||
source.withUnsafeBufferPointer {
|
||||
XCTAssertEqual(component, .init(platformString: $0.baseAddress!))
|
||||
}
|
||||
source[1] = CInterop.PlatformChar(truncatingIfNeeded: 0xffff)
|
||||
component = FilePath.Component(platformString: source)
|
||||
source.withUnsafeBufferPointer {
|
||||
XCTAssertEqual(component, .init(platformString: $0.baseAddress!))
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_FilePathComponent_initWithStringConversion() {
|
||||
let source = "ab\0c"
|
||||
var component: FilePath.Component?
|
||||
component = FilePath.Component(platformString: source)
|
||||
source.withPlatformString {
|
||||
XCTAssertEqual(component, FilePath.Component(platformString: $0))
|
||||
}
|
||||
component = FilePath.Component(platformString: "")
|
||||
XCTAssertNil(component)
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_FilePathComponent_initWithInoutConversion() {
|
||||
var c: CInterop.PlatformChar = 0
|
||||
let component = FilePath.Component(platformString: &c)
|
||||
XCTAssertNil(component)
|
||||
}
|
||||
|
||||
func test_FilePathRoot_initWithArrayConversion() {
|
||||
let source: [CInterop.PlatformChar]
|
||||
#if os(Windows)
|
||||
source = [0x41, 0x3a, 0x5c, 0, 0x7f]
|
||||
#else // unix
|
||||
source = [0x2f, 0, 0x7f]
|
||||
#endif
|
||||
var root: FilePath.Root?
|
||||
root = FilePath.Root(platformString: source)
|
||||
source.withUnsafeBufferPointer {
|
||||
XCTAssertEqual(root, FilePath.Root(platformString: $0.baseAddress!))
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_FilePathRoot_initWithStringConversion() {
|
||||
#if os(Windows)
|
||||
let source = "C:\\\0 and the rest"
|
||||
#else // unix
|
||||
let source = "/\0 and the rest"
|
||||
#endif
|
||||
var root: FilePath.Root?
|
||||
root = FilePath.Root(platformString: source)
|
||||
source.withPlatformString {
|
||||
XCTAssertEqual(root, FilePath.Root(platformString: $0))
|
||||
}
|
||||
root = FilePath.Root(platformString: "")
|
||||
XCTAssertNil(root)
|
||||
}
|
||||
|
||||
@available(*, deprecated) // silence the warning for using a deprecated api
|
||||
func test_FilePathRoot_initWithInoutConversion() {
|
||||
var c: CInterop.PlatformChar = 0
|
||||
let root = FilePath.Root(platformString: &c)
|
||||
XCTAssertNil(root)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
import XCTest
|
||||
|
||||
#if SYSTEM_PACKAGE
|
||||
@testable import SystemPackage
|
||||
#else
|
||||
@testable import System
|
||||
#endif
|
||||
|
||||
// To aid debugging, force failures to fatal error
|
||||
internal var forceFatalFailures = false
|
||||
|
||||
internal protocol TestCase {
|
||||
// TODO: want a source location stack, more fidelity, kinds of stack entries, etc
|
||||
var file: StaticString { get }
|
||||
var line: UInt { get }
|
||||
|
||||
// TODO: Instead have an attribute to register a test in a allTests var, similar to the argument parser.
|
||||
func runAllTests()
|
||||
|
||||
// Customization hook: add adornment to reported failure reason
|
||||
// Defaut: reason or empty
|
||||
func failureMessage(_ reason: String?) -> String
|
||||
}
|
||||
|
||||
extension TestCase {
|
||||
// Default implementation
|
||||
func failureMessage(_ reason: String?) -> String { reason ?? "" }
|
||||
|
||||
func expectEqualSequence<S1: Sequence, S2: Sequence>(
|
||||
_ expected: S1, _ actual: S2,
|
||||
_ message: String? = nil
|
||||
) where S1.Element: Equatable, S1.Element == S2.Element {
|
||||
if !expected.elementsEqual(actual) {
|
||||
defer { print("expected: \(expected), actual: \(actual)") }
|
||||
fail(message)
|
||||
}
|
||||
}
|
||||
func expectEqual<E: Equatable>(
|
||||
_ expected: E, _ actual: E,
|
||||
_ message: String? = nil
|
||||
) {
|
||||
if actual != expected {
|
||||
defer { print("expected: \(expected), actual: \(actual)") }
|
||||
fail(message)
|
||||
}
|
||||
}
|
||||
func expectNotEqual<E: Equatable>(
|
||||
_ expected: E, _ actual: E,
|
||||
_ message: String? = nil
|
||||
) {
|
||||
if actual == expected {
|
||||
defer { print("expected not equal: \(expected) and \(actual)") }
|
||||
fail(message)
|
||||
}
|
||||
}
|
||||
func expectNil<T>(
|
||||
_ actual: T?,
|
||||
_ message: String? = nil
|
||||
) {
|
||||
if actual != nil {
|
||||
defer { print("expected nil: \(actual!)") }
|
||||
fail(message)
|
||||
}
|
||||
}
|
||||
func expectNotNil<T>(
|
||||
_ actual: T?,
|
||||
_ message: String? = nil
|
||||
) {
|
||||
if actual == nil {
|
||||
defer { print("expected non-nil") }
|
||||
fail(message)
|
||||
}
|
||||
}
|
||||
func expectTrue(
|
||||
_ actual: Bool,
|
||||
_ message: String? = nil
|
||||
) {
|
||||
if !actual { fail(message) }
|
||||
}
|
||||
func expectFalse(
|
||||
_ actual: Bool,
|
||||
_ message: String? = nil
|
||||
) {
|
||||
if actual { fail(message) }
|
||||
}
|
||||
|
||||
func fail(_ reason: String? = nil) {
|
||||
XCTAssert(false, failureMessage(reason), file: file, line: line)
|
||||
if forceFatalFailures {
|
||||
fatalError(reason ?? "<no reason>")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
internal struct MockTestCase: TestCase {
|
||||
var file: StaticString
|
||||
var line: UInt
|
||||
|
||||
var expected: Trace.Entry
|
||||
var interruptBehavior: InterruptBehavior
|
||||
|
||||
var interruptable: Bool { return interruptBehavior == .interruptable }
|
||||
|
||||
internal enum InterruptBehavior {
|
||||
// Retry the syscall on EINTR
|
||||
case interruptable
|
||||
|
||||
// Cannot return EINTR
|
||||
case noInterrupt
|
||||
|
||||
// Cannot error at all
|
||||
case noError
|
||||
}
|
||||
|
||||
var body: (_ retryOnInterrupt: Bool) throws -> ()
|
||||
|
||||
init(
|
||||
_ file: StaticString = #file,
|
||||
_ line: UInt = #line,
|
||||
name: String,
|
||||
_ interruptable: InterruptBehavior,
|
||||
_ args: AnyHashable...,
|
||||
body: @escaping (_ retryOnInterrupt: Bool) throws -> ()
|
||||
) {
|
||||
self.file = file
|
||||
self.line = line
|
||||
self.expected = Trace.Entry(name: name, args)
|
||||
self.interruptBehavior = interruptable
|
||||
self.body = body
|
||||
}
|
||||
|
||||
func runAllTests() {
|
||||
XCTAssertFalse(MockingDriver.enabled)
|
||||
MockingDriver.withMockingEnabled { mocking in
|
||||
// Make sure we completely match the trace queue
|
||||
self.expectTrue(mocking.trace.isEmpty)
|
||||
defer { self.expectTrue(mocking.trace.isEmpty) }
|
||||
|
||||
// Test our API mappings to the lower-level syscall invocation
|
||||
do {
|
||||
try body(true)
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue())
|
||||
} catch {
|
||||
self.fail()
|
||||
}
|
||||
|
||||
// Non-error-ing syscalls shouldn't ever throw
|
||||
guard interruptBehavior != .noError else {
|
||||
do {
|
||||
try body(interruptable)
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue())
|
||||
try body(!interruptable)
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue())
|
||||
} catch {
|
||||
self.fail()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Test interupt behavior. Interruptable calls will be told not to
|
||||
// retry to catch the EINTR. Non-interruptable calls will be told to
|
||||
// retry, to make sure they don't spin (e.g. if API changes to include
|
||||
// interruptable)
|
||||
do {
|
||||
mocking.forceErrno = .always(errno: EINTR)
|
||||
try body(!interruptable)
|
||||
self.fail()
|
||||
} catch Errno.interrupted {
|
||||
// Success!
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue())
|
||||
} catch {
|
||||
self.fail()
|
||||
}
|
||||
|
||||
// Force a limited number of EINTRs, and make sure interruptable functions
|
||||
// retry that number of times. Non-interruptable functions should throw it.
|
||||
do {
|
||||
mocking.forceErrno = .counted(errno: EINTR, count: 3)
|
||||
|
||||
try body(interruptable)
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue()) // EINTR
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue()) // EINTR
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue()) // EINTR
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue()) // Success
|
||||
} catch Errno.interrupted {
|
||||
self.expectFalse(interruptable)
|
||||
self.expectEqual(self.expected, mocking.trace.dequeue()) // EINTR
|
||||
} catch {
|
||||
self.fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal func withWindowsPaths(enabled: Bool, _ body: () -> ()) {
|
||||
_withWindowsPaths(enabled: enabled, body)
|
||||
}
|
||||
@@ -17,6 +17,54 @@ extension FileDescriptorTest {
|
||||
// to regenerate.
|
||||
static let __allTests__FileDescriptorTest = [
|
||||
("testConstants", testConstants),
|
||||
("testStandardDescriptors", testStandardDescriptors),
|
||||
]
|
||||
}
|
||||
|
||||
extension FileOperationsTest {
|
||||
// DO NOT MODIFY: This is autogenerated, use:
|
||||
// `swift test --generate-linuxmain`
|
||||
// to regenerate.
|
||||
static let __allTests__FileOperationsTest = [
|
||||
("testAdHocOpen", testAdHocOpen),
|
||||
("testAdHocPipe", testAdHocPipe),
|
||||
("testGithubIssues", testGithubIssues),
|
||||
("testHelpers", testHelpers),
|
||||
("testSyscalls", testSyscalls),
|
||||
]
|
||||
}
|
||||
|
||||
extension FilePathComponentsTest {
|
||||
// DO NOT MODIFY: This is autogenerated, use:
|
||||
// `swift test --generate-linuxmain`
|
||||
// to regenerate.
|
||||
static let __allTests__FilePathComponentsTest = [
|
||||
("testAdHocRRC", testAdHocRRC),
|
||||
("testCases", testCases),
|
||||
("testSeparatorNormalization", testSeparatorNormalization),
|
||||
]
|
||||
}
|
||||
|
||||
extension FilePathParsingTest {
|
||||
// DO NOT MODIFY: This is autogenerated, use:
|
||||
// `swift test --generate-linuxmain`
|
||||
// to regenerate.
|
||||
static let __allTests__FilePathParsingTest = [
|
||||
("testNormalization", testNormalization),
|
||||
]
|
||||
}
|
||||
|
||||
extension FilePathSyntaxTest {
|
||||
// DO NOT MODIFY: This is autogenerated, use:
|
||||
// `swift test --generate-linuxmain`
|
||||
// to regenerate.
|
||||
static let __allTests__FilePathSyntaxTest = [
|
||||
("testAdHocMutations", testAdHocMutations),
|
||||
("testFailableStringInitializers", testFailableStringInitializers),
|
||||
("testLexicallyRelative", testLexicallyRelative),
|
||||
("testPartialWindowsRoots", testPartialWindowsRoots),
|
||||
("testPathSyntax", testPathSyntax),
|
||||
("testPrefixSuffix", testPrefixSuffix),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -38,12 +86,47 @@ extension FilePermissionsTest {
|
||||
]
|
||||
}
|
||||
|
||||
extension MockingTest {
|
||||
// DO NOT MODIFY: This is autogenerated, use:
|
||||
// `swift test --generate-linuxmain`
|
||||
// to regenerate.
|
||||
static let __allTests__MockingTest = [
|
||||
("testMocking", testMocking),
|
||||
]
|
||||
}
|
||||
|
||||
extension SystemCharTest {
|
||||
// DO NOT MODIFY: This is autogenerated, use:
|
||||
// `swift test --generate-linuxmain`
|
||||
// to regenerate.
|
||||
static let __allTests__SystemCharTest = [
|
||||
("testIsLetter", testIsLetter),
|
||||
]
|
||||
}
|
||||
|
||||
extension SystemStringTest {
|
||||
// DO NOT MODIFY: This is autogenerated, use:
|
||||
// `swift test --generate-linuxmain`
|
||||
// to regenerate.
|
||||
static let __allTests__SystemStringTest = [
|
||||
("testAdHoc", testAdHoc),
|
||||
("testPlatformString", testPlatformString),
|
||||
]
|
||||
}
|
||||
|
||||
public func __allTests() -> [XCTestCaseEntry] {
|
||||
return [
|
||||
testCase(ErrnoTest.__allTests__ErrnoTest),
|
||||
testCase(FileDescriptorTest.__allTests__FileDescriptorTest),
|
||||
testCase(FileOperationsTest.__allTests__FileOperationsTest),
|
||||
testCase(FilePathComponentsTest.__allTests__FilePathComponentsTest),
|
||||
testCase(FilePathParsingTest.__allTests__FilePathParsingTest),
|
||||
testCase(FilePathSyntaxTest.__allTests__FilePathSyntaxTest),
|
||||
testCase(FilePathTest.__allTests__FilePathTest),
|
||||
testCase(FilePermissionsTest.__allTests__FilePermissionsTest),
|
||||
testCase(MockingTest.__allTests__MockingTest),
|
||||
testCase(SystemCharTest.__allTests__SystemCharTest),
|
||||
testCase(SystemStringTest.__allTests__SystemStringTest),
|
||||
]
|
||||
}
|
||||
#endif
|
||||
Executable
+85
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# This script can be used to automatically add/remove `@available` attributes to
|
||||
# declarations in Swift sources in this package.
|
||||
#
|
||||
# In order for this to work, ABI-impacting declarations need to be annotated
|
||||
# with special comments in the following format:
|
||||
#
|
||||
# /*System 0.0.2*/
|
||||
# public func greeting() -> String {
|
||||
# "Hello"
|
||||
# }
|
||||
#
|
||||
# The script adds full availability incantations to these comments. It can run
|
||||
# in one of two modes:
|
||||
#
|
||||
# By default, `expand-availability.py` expands availability macros within the
|
||||
# comments. This is useful during package development to cross-reference
|
||||
# availability across `SystemPackage` and the ABI-stable `System` module that
|
||||
# ships in Apple's OS releases:
|
||||
#
|
||||
# /*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
|
||||
# public func greeting() -> String {
|
||||
# "Hello"
|
||||
# }
|
||||
#
|
||||
# `expand-availability.py --attributes` adds actual availability attributes.
|
||||
# This is used by maintainers to build ABI stable releases of System on Apple's
|
||||
# platforms:
|
||||
#
|
||||
# /*System 0.0.2*/@available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)
|
||||
# public func greeting() -> String {
|
||||
# "Hello"
|
||||
# }
|
||||
#
|
||||
# The script recognizes all three forms of these annotations and updates them on
|
||||
# every run, so we can run the script to enable/disable attributes as needed.
|
||||
|
||||
import os
|
||||
import os.path
|
||||
import fileinput
|
||||
import re
|
||||
import sys
|
||||
import argparse
|
||||
|
||||
versions = {
|
||||
"System 0.0.1": "macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0",
|
||||
"System 0.0.2": "macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0",
|
||||
"System 1.1.0": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999",
|
||||
"System 1.2.0": "macOS 9999, iOS 9999, watchOS 9999, tvOS 9999",
|
||||
}
|
||||
|
||||
parser = argparse.ArgumentParser(description="Expand availability macros.")
|
||||
parser.add_argument("--attributes", help="Add @available attributes",
|
||||
action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
def swift_sources_in(path):
|
||||
result = []
|
||||
for (dir, _, files) in os.walk(path):
|
||||
for file in files:
|
||||
extension = os.path.splitext(file)[1]
|
||||
if extension == ".swift":
|
||||
result.append(os.path.join(dir, file))
|
||||
return result
|
||||
|
||||
macro_pattern = re.compile(
|
||||
r"/\*(System [^ *]+)(, @available\([^)]*\))?\*/(@available\([^)]*\))?")
|
||||
|
||||
sources = swift_sources_in("Sources") + swift_sources_in("Tests")
|
||||
for line in fileinput.input(files=sources, inplace=True):
|
||||
match = re.search(macro_pattern, line)
|
||||
if match:
|
||||
system_version = match.group(1)
|
||||
expansion = versions[system_version]
|
||||
if expansion is None:
|
||||
raise ValueError("{0}:{1}: error: Unknown System version '{0}'"
|
||||
.format(fileinput.filename(), fileinput.lineno(),
|
||||
system_version))
|
||||
if args.attributes:
|
||||
replacement = "/*{0}*/@available({1}, *)".format(system_version, expansion)
|
||||
else:
|
||||
replacement = "/*{0}, @available({1}, *)*/".format(system_version, expansion)
|
||||
line = line[:match.start()] + replacement + line[match.end():]
|
||||
print(line, end="")
|
||||
@@ -0,0 +1,19 @@
|
||||
#[[
|
||||
This source file is part of the Swift System open source Project
|
||||
|
||||
Copyright (c) 2021 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
|
||||
#]]
|
||||
|
||||
set(SWIFT_SYSTEM_EXPORTS_FILE ${CMAKE_CURRENT_BINARY_DIR}/SwiftSystemExports.cmake)
|
||||
|
||||
configure_file(SwiftSystemConfig.cmake.in
|
||||
${CMAKE_CURRENT_BINARY_DIR}/SwiftSystemConfig.cmake)
|
||||
|
||||
get_property(SWIFT_SYSTEM_EXPORTS GLOBAL PROPERTY SWIFT_SYSTEM_EXPORTS)
|
||||
export(TARGETS ${SWIFT_SYSTEM_EXPORTS}
|
||||
NAMESPACE SwiftSystem::
|
||||
FILE ${SWIFT_SYSTEM_EXPORTS_FILE}
|
||||
EXPORT_LINK_INTERFACE_LIBRARIES)
|
||||
@@ -0,0 +1,100 @@
|
||||
#[[
|
||||
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
|
||||
#]]
|
||||
|
||||
# Returns the architecture name in a variable
|
||||
#
|
||||
# Usage:
|
||||
# get_swift_host_arch(result_var_name)
|
||||
#
|
||||
# Sets ${result_var_name} with the converted architecture name derived from
|
||||
# CMAKE_SYSTEM_PROCESSOR.
|
||||
function(get_swift_host_arch result_var_name)
|
||||
if("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86_64")
|
||||
set("${result_var_name}" "x86_64" PARENT_SCOPE)
|
||||
elseif ("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "AArch64|aarch64|arm64")
|
||||
if(CMAKE_SYSTEM_NAME MATCHES Darwin)
|
||||
set("${result_var_name}" "arm64" PARENT_SCOPE)
|
||||
else()
|
||||
set("${result_var_name}" "aarch64" PARENT_SCOPE)
|
||||
endif()
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64")
|
||||
set("${result_var_name}" "powerpc64" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "ppc64le")
|
||||
set("${result_var_name}" "powerpc64le" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "s390x")
|
||||
set("${result_var_name}" "s390x" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv6l")
|
||||
set("${result_var_name}" "armv6" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7l")
|
||||
set("${result_var_name}" "armv7" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "armv7-a")
|
||||
set("${result_var_name}" "armv7" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "amd64")
|
||||
set("${result_var_name}" "amd64" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "AMD64")
|
||||
set("${result_var_name}" "x86_64" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "IA64")
|
||||
set("${result_var_name}" "itanium" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "x86")
|
||||
set("${result_var_name}" "i686" PARENT_SCOPE)
|
||||
elseif("${CMAKE_SYSTEM_PROCESSOR}" STREQUAL "i686")
|
||||
set("${result_var_name}" "i686" PARENT_SCOPE)
|
||||
else()
|
||||
message(FATAL_ERROR "Unrecognized architecture on host system: ${CMAKE_SYSTEM_PROCESSOR}")
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
# Returns the os name in a variable
|
||||
#
|
||||
# Usage:
|
||||
# get_swift_host_os(result_var_name)
|
||||
#
|
||||
#
|
||||
# Sets ${result_var_name} with the converted OS name derived from
|
||||
# CMAKE_SYSTEM_NAME.
|
||||
function(get_swift_host_os result_var_name)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL Darwin)
|
||||
set(${result_var_name} macosx PARENT_SCOPE)
|
||||
else()
|
||||
string(TOLOWER ${CMAKE_SYSTEM_NAME} cmake_system_name_lc)
|
||||
set(${result_var_name} ${cmake_system_name_lc} PARENT_SCOPE)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
function(_install_target module)
|
||||
get_swift_host_os(swift_os)
|
||||
get_target_property(type ${module} TYPE)
|
||||
|
||||
if(type STREQUAL STATIC_LIBRARY)
|
||||
set(swift swift_static)
|
||||
else()
|
||||
set(swift swift)
|
||||
endif()
|
||||
|
||||
install(TARGETS ${module}
|
||||
ARCHIVE DESTINATION lib/${swift}/${swift_os}
|
||||
LIBRARY DESTINATION lib/${swift}/${swift_os}
|
||||
RUNTIME DESTINATION bin)
|
||||
if(type STREQUAL EXECUTABLE)
|
||||
return()
|
||||
endif()
|
||||
|
||||
get_swift_host_arch(swift_arch)
|
||||
get_target_property(module_name ${module} Swift_MODULE_NAME)
|
||||
if(NOT module_name)
|
||||
set(module_name ${module})
|
||||
endif()
|
||||
|
||||
install(FILES $<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module_name}.swiftdoc
|
||||
DESTINATION lib/${swift}/${swift_os}/${module_name}.swiftmodule
|
||||
RENAME ${swift_arch}.swiftdoc)
|
||||
install(FILES $<TARGET_PROPERTY:${module},Swift_MODULE_DIRECTORY>/${module_name}.swiftmodule
|
||||
DESTINATION lib/${swift}/${swift_os}/${module_name}.swiftmodule
|
||||
RENAME ${swift_arch}.swiftmodule)
|
||||
endfunction()
|
||||
@@ -0,0 +1,12 @@
|
||||
#[[
|
||||
This source file is part of the Swift System open source Project
|
||||
|
||||
Copyright (c) 2021 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
|
||||
#]]
|
||||
|
||||
if(NOT TARGET SystemPackage)
|
||||
include(@SWIFT_SYSTEM_EXPORTS_FILE@)
|
||||
endif()
|
||||
Reference in new issue
Block a user