Compare commits

..
57 Commits
Author SHA1 Message Date
Guillaume Lessard d2ba781702 Merge pull request #190 from glessard/enforce-file-path-invariants-in-decode-1.3.x
Cherry-pick: ensure invariants are enforced when decoding
2024-07-23 12:42:13 -07:00
Stephen Canon a1f77d0e1a Cherry-pick: ensure invariants are enforced when decoding
Ensure that FilePath and SystemString's invariants are enforced when decoding.

Cherry-pick of merge-commit 9c42c54644
from PR #189

# Conflicts:
#	Sources/System/FilePath/FilePath.swift
2024-07-23 11:26:26 -07:00
Guillaume Lessard 6a9e38e7bd Merge pull request #185 from glessard/disfavoredOverload-1.3.0
[1.3.x] Disfavor String.init(platformString: UnsafePointer<CChar>)
2024-06-07 17:43:21 -07:00
Guillaume Lessard 2b30f8820c Merge pull request #183 from kateinoigakukun/katei/suppress-cmakelists-warning-1.3
[1.3] Suppress unhandled CMakeLists.txt warning by SwiftPM
2024-06-06 13:44:13 -07:00
Yuta Saito f9d6b48027 Suppress unhandled CMakeLists.txt warning by SwiftPM 2024-06-05 18:05:57 +00:00
Karoy Lorentey f9266c8518 Merge pull request #177 from lorentey/fix-cmake
[1.3][CMake] Restore to working order on Apple platforms
2024-05-15 14:48:03 -07:00
Karoy Lorentey b7dc8e8e41 [CMake] Restore to working order on Apple platforms 2024-05-15 14:30:14 -07:00
Guillaume Lessard 7d45e0dd46 Update README.md to refer to 1.3.0 2024-05-12 11:40:14 -07:00
Guillaume Lessard ab09f04cfe Merge pull request #173 from lorentey/codeowners-1.3.0
Add CODEOWNERS
2024-05-10 17:07:55 -07:00
Karoy Lorentey 0cf079efea Add CODEOWNERS 2024-05-10 17:05:37 -07:00
Mishal Shah 52f603c6b3 [CI] Remove support for Swift 5.7 2024-05-10 16:31:46 -07:00
Guillaume Lessard de1f8bce5e Merge pull request #172 from glessard/visionOS-support-for-1.3.0
[1.3.0] visionOS support for 1.3.0
2024-05-10 16:23:53 -07:00
Mishal Shah 0368ce547b Add support for Swift CI on release/1.3.0 2024-05-10 16:18:08 -07:00
Guillaume Lessard 7b14e48d0d Remove the repeated list of Darwin-based platforms
Replaced with a constant defined in the package manifest.
2024-05-10 16:09:22 -07:00
Guillaume Lessard c456f4186e Change the package manifest to support visionOS 2024-05-10 16:02:32 -07:00
Karoy Lorentey ec395a7aa2 Merge pull request #171 from lorentey/require-5.8
[1.3.0] Require Swift 5.8
2024-05-10 15:59:40 -07:00
Karoy Lorentey f1f59e148f Update gitignore 2024-05-10 15:55:04 -07:00
Karoy Lorentey 37a5bbb965 Require Swift 5.8 or better 2024-05-10 15:54:56 -07:00
Karoy Lorentey f07d14ddb1 Merge pull request #168 from glessard/cherry-pick-pr148
Cherry-pick changes from PR148
2024-05-10 15:41:26 -07:00
Guillaume LessardandFinagolfin 9620c1d30e Cherry-pick changes from PR148
Co-authored-by: Finagolfin <finagolfin@tuta.io>
2024-05-09 22:24:04 -07:00
Guillaume LessardandHiroshi Yamauchi c7259554b5 Cherry-pick changes from PR151
Co-authored-by: Hiroshi Yamauchi <hjyamauchi@gmail.com>
2024-05-09 22:10:26 -07:00
Guillaume LessardandMax Desiatov c3a7235bf7 Cherry-pick changes from PR133
Co-authored-by: Max Desiatov <m_desiatov@apple.com>
2024-05-09 19:10:58 -07:00
Guillaume Lessard e5a56da50e Cherry-pick changes from PR154 2024-05-09 16:03:48 -07:00
Jeremy Schonfeld dd45c80062 Disfavor String.init(platformString: UnsafePointer<CChar>) 2024-05-02 13:25:04 -07:00
Karoy Lorentey 025bcb1165 Merge pull request #93 from apple/revert-89-sb/resize-windows
Revert "FileOperations: Add Windows implementation for FileDescriptor.resize(to:)"
2022-06-11 12:57:28 -07:00
Karoy Lorentey f5e4aac51b Revert "FileOperations: Add Windows implementation for FileDescriptor.resize(to:) (#89)"
This reverts commit 94fa6bd2ff.
2022-06-11 12:54:19 -07:00
Si Beaumont 94fa6bd2ff FileOperations: Add Windows implementation for FileDescriptor.resize(to:) (#89)
* FileOperations: Add Windows implementation for FileDescriptor.resize(to:)

Replace _chsize with _chsize_s on Windows
2022-06-09 09:51:28 -06:00
Alsey Coleman Miller a552fda216 Import C module as @_implementationOnly (#83) 2022-06-08 19:54:55 -06:00
Guillaume Lessard bdb13a5a80 Merge pull request #80 from apple/glessard/rdar91436410
Mitigate misuse of Swift's pointer conversion feature
2022-06-03 16:52:30 -06:00
Guillaume Lessard 3920df78d9 Correct deprecation messages 2022-06-03 16:43:25 -06:00
Guillaume Lessard 469ede0fa2 Add tests for every new overload added 2022-06-03 16:43:25 -06:00
Guillaume Lessard afe2d35d0b Mitigate misuse of pointer conversion in FilePath inits 2022-06-03 16:43:25 -06:00
Guillaume Lessard 25380a1bea Mitigate misuse of pointer conversion in String inits 2022-06-03 16:43:25 -06:00
Karoy Lorentey 74eb6f4ef8 Merge pull request #77 from amartini51/docs/develop
Fix broken links.
2022-06-03 15:37:23 -07:00
Alex Martini 6db5a4a43b Fix broken links.
Fixes rdar://79096457
2022-06-03 15:23:53 -07:00
Karoy Lorentey 5ba9e8fa77 Merge pull request #79 from apple/glessard/binding-fixes
Rebind byte types safely
2022-06-03 15:16:40 -07:00
Guillaume Lessard 914c782b96 Replace assumingMemoryBound with temporary rebinding
- this doesn’t use the new memory binding API.
2022-05-27 18:09:45 -06:00
Karoy Lorentey 82a6704912 Merge pull request #88 from apple/lorentey/unbroke-windows
Unbreak the Windows port
2022-05-21 12:46:19 -07:00
Karoy Lorentey bd5a7bb703 Remove test of minimal value 2022-05-21 12:44:00 -07:00
Karoy Lorentey 147ebc053a Unbreak the Windows port 2022-05-21 12:43:59 -07:00
Karoy Lorentey 5c18991f29 Merge pull request #82 from simonjbeaumont/sb/resize
FileDescriptor: Add resize(to newSize:) and fileSize() APIs
2022-05-20 11:30:26 -07:00
Si Beaumont 7bb5279b57 fixup: Tests run in parallel; use unique temp file name
Signed-off-by: Si Beaumont <beaumont@apple.com>
2022-05-20 19:25:41 +01:00
Si Beaumont 865fd70605 Merge branch 'main' into sb/resize 2022-05-20 18:26:33 +01:00
Si Beaumont ca6e888455 Utilities: Add version 1.2.0 to expand-availability.py tool
Signed-off-by: Si Beaumont <beaumont@apple.com>
2022-05-20 18:24:28 +01:00
Si Beaumont fea7d5030d docs: Removed duplicate paragraph from FileDescriptor.writeAll(_:) docs (#85) 2022-05-16 07:28:47 -07:00
Si Beaumont d90bf8529a fixup: Move FileDescriptor.fileSize() to an internal extension in SystemTests 2022-05-06 11:55:00 +01:00
Si Beaumont 02daf4b6a7 fixup: Move FileDescriptor.resize to extension with #if !os(Windows) 2022-05-06 11:55:00 +01:00
Si Beaumont 7fab65f340 fixup: Remove Windows syscall adaptor for ftruncate 2022-05-06 11:09:20 +01:00
Si Beaumont 5d3519dcef FileOperations: Add FileDescriptor.resize, using ftruncate(2)
Signed-off-by: Si Beaumont <beaumont@apple.com>
2022-05-05 08:24:48 +01:00
Si Beaumont 23ac190631 FileHelpers: Add FileDescriptor.fileSize
Signed-off-by: Si Beaumont <beaumont@apple.com>
2022-05-04 12:33:03 +01:00
Daniel Duan a77a331dc7 Update Linux test manifests (#81)
Run `swift package --generate-linuxmain` results in this patch.
2022-04-20 14:22:03 -06:00
Karoy Lorentey 1d5e35a460 Merge pull request #75 from lorentey/introduce-availability-macros
Unify availability annotations & introduce a script to manage them
2021-12-21 13:07:07 -08:00
Karoy Lorentey fd82b5a0ce Fix docs 2021-12-20 17:52:59 -08:00
Karoy Lorentey 0c24d31e08 Add script to manage availability annotations
By running this script, we can expand comments of the form

```
/*System 0.0.1*/
```

Into either a longer comment that includes the associated OS versions numbers,

```
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
```

or, when the `--attribute` option is used, into an actual `@available` attribute:

```
/*System 0.0.1*/@available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
```

The script can be run repeatedly to switch between these two forms, as needed.
2021-12-20 17:14:42 -08:00
Karoy Lorentey 1daa0c9677 Unify availability annotations and synchronize them with macOS 12 / iOS 15
Availability annotations now follow a rigid syntax that mentions the swift-system version that introduced the entry point:

```
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
public func greeting() -> String {
  "Hello"
}
```

This is designed to be processed by automated source generation tools.
2021-12-20 17:10:59 -08:00
Saleem Abdulrasool 836bc4557b Merge pull request #74 from compnerd/leaky-cauldron
build: install CSystem into the system
2021-12-02 11:22:32 -08:00
Saleem Abdulrasool 5d68cf0eca build: install CSystem into the system
CSystem is a leaky library dependency from System and must be
distributed.  Install the files and make the dependency public so that
it is emitted into the clients.
2021-12-02 09:19:43 -08:00
47 changed files with 1160 additions and 207 deletions

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
# Lines starting with '#' are comments.
# Each line is a case-sensitive file pattern followed by one or more owners.
# Order is important. The last matching pattern has the most precedence.
# More information: https://docs.github.com/en/articles/about-code-owners
#
# Please mirror the repository's file hierarchy in case-sensitive lexicographic
# order.
# Default owners
* @glessard @lorentey @milseman
# Swift CI configuration files
.swiftci/ @shahmishal
+1
View File
@@ -4,3 +4,4 @@
/*.xcodeproj
xcuserdata/
.*.sw?
/.swiftpm
+5
View File
@@ -0,0 +1,5 @@
LinuxSwiftPackageJob {
swift_version_tag = "5.10-jammy"
repo = "swift-system"
branch = "release/1.3.0"
}
+5
View File
@@ -0,0 +1,5 @@
LinuxSwiftPackageJob {
swift_version_tag = "5.8-jammy"
repo = "swift-system"
branch = "release/1.3.0"
}
+5
View File
@@ -0,0 +1,5 @@
LinuxSwiftPackageJob {
swift_version_tag = "5.9-jammy"
repo = "swift-system"
branch = "release/1.3.0"
}
+5
View File
@@ -0,0 +1,5 @@
macOSSwiftPackageJob {
swift_version = "6.0"
repo = "swift-system"
branch = "release/1.3.0"
}
+5
View File
@@ -0,0 +1,5 @@
LinuxSwiftPackageJob {
nightly_docker_tag = "nightly-6.0-jammy"
repo = "swift-system"
branch = "release/1.3.0"
}
+5
View File
@@ -0,0 +1,5 @@
macOSSwiftPackageJob {
swift_version = "main"
repo = "swift-system"
branch = "release/1.3.0"
}
+5
View File
@@ -0,0 +1,5 @@
LinuxSwiftPackageJob {
nightly_docker_tag = "nightly-jammy"
repo = "swift-system"
branch = "release/1.3.0"
}
+7
View File
@@ -0,0 +1,7 @@
WindowsSwiftPackageWithDockerImageJob {
docker_image = "swiftlang/swift:nightly-windowsservercore-1809"
repo = "swift-system"
branch = "release/1.3.0"
sub_dir = "swift-system"
label = "windows-server-2019"
}
+15 -5
View File
@@ -1,10 +1,9 @@
// swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
// swift-tools-version:5.8
/*
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-2024 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
@@ -12,6 +11,13 @@
import PackageDescription
let DarwinPlatforms: [Platform]
#if swift(<5.9)
DarwinPlatforms = [.macOS, .iOS, .watchOS, .tvOS]
#else
DarwinPlatforms = [.macOS, .iOS, .watchOS, .tvOS, .visionOS]
#endif
let package = Package(
name: "swift-system",
products: [
@@ -21,23 +27,27 @@ let package = Package(
targets: [
.target(
name: "CSystem",
dependencies: []),
dependencies: [],
exclude: ["CMakeLists.txt"]),
.target(
name: "SystemPackage",
dependencies: ["CSystem"],
path: "Sources/System",
exclude: ["CMakeLists.txt"],
cSettings: [
.define("_CRT_SECURE_NO_WARNINGS")
],
swiftSettings: [
.define("SYSTEM_PACKAGE"),
.define("SYSTEM_PACKAGE_DARWIN", .when(platforms: DarwinPlatforms)),
.define("ENABLE_MOCKING", .when(configuration: .debug))
]),
.testTarget(
name: "SystemTests",
dependencies: ["SystemPackage"],
swiftSettings: [
.define("SYSTEM_PACKAGE")
.define("SYSTEM_PACKAGE"),
.define("SYSTEM_PACKAGE_DARWIN", .when(platforms: DarwinPlatforms)),
]),
]
)
+2 -2
View File
@@ -28,7 +28,7 @@ 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: "1.0.0"),
.package(url: "https://github.com/apple/swift-system", from: "1.3.0"),
```
Finally, include `"SystemPackage"` as a dependency for your executable target:
@@ -37,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: "1.0.0"),
.package(url: "https://github.com/apple/swift-system", from: "1.3.0"),
// other dependencies
],
targets: [
+5
View File
@@ -12,4 +12,9 @@ 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)
+5 -1
View File
@@ -34,9 +34,13 @@ target_sources(SystemPackage PRIVATE
Internals/Mocking.swift
Internals/Syscalls.swift
Internals/WindowsSyscallAdapters.swift)
target_link_libraries(SystemPackage PRIVATE
target_link_libraries(SystemPackage PUBLIC
CSystem)
set(SWIFT_SYSTEM_APPLE_PLATFORMS "Darwin" "iOS" "watchOS" "tvOS" "visionOS")
if(CMAKE_SYSTEM_NAME IN_LIST SWIFT_SYSTEM_APPLE_PLATFORMS)
target_compile_definitions(SystemPackage PRIVATE SYSTEM_PACKAGE_DARWIN)
endif()
_install_target(SystemPackage)
set_property(GLOBAL APPEND PROPERTY SWIFT_SYSTEM_EXPORTS SystemPackage)
+16 -16
View File
@@ -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
@@ -23,7 +23,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
@_alwaysEmitIntoClient
private init(_ raw: CInt) { self.init(rawValue: raw) }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
/// Error. Not used.
@_alwaysEmitIntoClient
public static var notUsed: Errno { Errno(_ERRNO_NOT_USED) }
@@ -911,7 +911,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
@available(*, unavailable, renamed: "directoryNotEmpty")
public static var ENOTEMPTY: Errno { directoryNotEmpty }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
/// Too many processes.
///
/// The corresponding C error is `EPROCLIM`.
@@ -968,7 +968,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
public static var ESTALE: Errno { staleNFSFileHandle }
// TODO: Add Linux's RPC equivalents
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
/// The structure of the remote procedure call (RPC) is bad.
///
@@ -1060,7 +1060,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
public static var ENOSYS: Errno { noFunction }
// BSD
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
/// Inappropriate file type or format.
///
/// The file was the wrong type for the operation,
@@ -1075,7 +1075,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
public static var EFTYPE: Errno { badFileTypeOrFormat }
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
/// Authentication error.
///
/// The authentication ticket used to mount an NFS file system was invalid.
@@ -1102,7 +1102,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
public static var ENEEDAUTH: Errno { needAuthenticator }
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
/// Device power is off.
///
/// The corresponding C error is `EPWROFF`.
@@ -1142,7 +1142,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
public static var EOVERFLOW: Errno { overflow }
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
/// Bad executable or shared library.
///
/// The executable or shared library being referenced was malformed.
@@ -1246,7 +1246,7 @@ public struct Errno: RawRepresentable, Error, Hashable, Codable {
@available(*, unavailable, renamed: "illegalByteSequence")
public static var EILSEQ: Errno { illegalByteSequence }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
/// Attribute not found.
///
/// The specified extended attribute doesn't exist.
@@ -1376,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.
@@ -1409,7 +1409,7 @@ extension Errno {
@available(*, unavailable, renamed: "tooManyRemoteLevels")
public static var EREMOTE: Errno { tooManyRemoteLevels }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
/// No such policy registered.
///
/// The corresponding C error is `ENOPOLICY`.
@@ -1443,7 +1443,7 @@ extension Errno {
public static var EOWNERDEAD: Errno { previousOwnerDied }
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
/// Interface output queue is full.
///
/// The corresponding C error is `EQFULL`.
@@ -1470,7 +1470,7 @@ extension Errno {
#endif
}
// @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.
@@ -1485,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.
@@ -1512,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 {
+16 -16
View File
@@ -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
@@ -40,7 +40,7 @@ extension FileDescriptor {
public static var standardError: FileDescriptor { .init(rawValue: 2) }
}
// @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 {
/// The desired read and write access for a newly opened file.
@frozen
@@ -106,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
@@ -164,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`.
@@ -182,7 +182,7 @@ extension FileDescriptor {
@available(*, unavailable, renamed: "exclusiveCreate")
public static var O_EXCL: OpenOptions { exclusiveCreate }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
/// Indicates that opening the file
/// atomically obtains a shared lock on the file.
///
@@ -223,7 +223,7 @@ extension FileDescriptor {
///
/// 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.
///
@@ -238,7 +238,7 @@ extension FileDescriptor {
/// 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:System/FileDescriptor/open(_:_:options:permissions:)-10dcs>
/// <doc:FileDescriptor/open(_:_:options:permissions:retryOnInterrupt:)-2266j>
/// is a not a directory, then that open operation fails.
///
/// The corresponding C constant is `O_DIRECTORY`.
@@ -250,13 +250,13 @@ extension FileDescriptor {
public static var O_DIRECTORY: OpenOptions { directory }
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
/// 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.
///
@@ -353,7 +353,7 @@ extension FileDescriptor {
// TODO: These are available on some versions of Linux with appropriate
// macro defines.
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
/// Indicates that the offset should be set
/// to the next hole after the specified number of bytes.
///
@@ -385,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
{
@@ -404,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
{
@@ -415,7 +415,7 @@ extension FileDescriptor.SeekOrigin
case .start: return "start"
case .current: return "current"
case .end: return "end"
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
case .nextHole: return "nextHole"
case .nextData: return "nextData"
#endif
@@ -427,14 +427,14 @@ 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
{
/// A textual representation of the open options.
@inline(never)
public var description: String {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
let descriptions: [(Element, StaticString)] = [
(.nonBlocking, ".nonBlocking"),
(.append, ".append"),
+1 -4
View File
@@ -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.
+65 -11
View File
@@ -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 {
/// Opens or creates a file for reading or writing.
///
@@ -185,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`.
@@ -337,7 +337,7 @@ extension FileDescriptor {
///
/// The corresponding C functions are `dup` and `dup2`.
@_alwaysEmitIntoClient
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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
@@ -345,7 +345,7 @@ extension FileDescriptor {
try _duplicate(as: target, retryOnInterrupt: retryOnInterrupt).get()
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
@usableFromInline
internal func _duplicate(
as target: FileDescriptor?,
@@ -370,27 +370,81 @@ extension FileDescriptor {
public func dup2() throws -> FileDescriptor {
fatalError("Not implemented")
}
#if !os(Windows)
}
#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
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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
valueOrErrno(retryOnInterrupt: false) {
system_pipe(UnsafeMutableRawPointer(pointer).assumingMemoryBound(to: Int32.self))
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])) }
}
}.map { _ in (.init(rawValue: fds.0), .init(rawValue: fds.1)) }
}
}
#endif
}
#endif
#if !os(Windows)
/*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))
}
}
}
#endif
+22 -5
View File
@@ -40,7 +40,7 @@
///
// TODO(docs): Section on all the new syntactic operations, lexical normalization, decomposition,
// components, etc.
// @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 FilePath {
internal var _storage: SystemString
@@ -60,12 +60,29 @@ public struct FilePath {
}
}
// @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 FilePath {
/// The length of the file path, excluding the null terminator.
public var length: Int { _storage.length }
}
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
extension FilePath: Hashable, Codable {}
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
extension FilePath: Hashable, Codable {
// Encoder is synthesized; it probably should have been explicit and used
// a single-value container, but making that change now is somewhat risky.
// Decoder is written explicitly to ensure that we validate invariants on
// untrusted input.
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self._storage = try container.decode(SystemString.self, forKey: ._storage)
guard _invariantsSatisfied() else {
throw DecodingError.dataCorruptedError(
forKey: ._storage,
in: container,
debugDescription:
"Encoding does not satisfy the invariants of FilePath"
)
}
}
}
@@ -9,7 +9,7 @@
// MARK: - API
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
@@ -89,7 +89,7 @@ extension FilePath {
#endif
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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 {
@@ -123,7 +123,7 @@ extension FilePath.ComponentView: BidirectionalCollection {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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())
@@ -173,7 +173,7 @@ extension FilePath.ComponentView: RangeReplaceableCollection {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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>(
@@ -9,7 +9,7 @@
// MARK: - API
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
///
@@ -73,7 +73,7 @@ extension FilePath {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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
+10 -5
View File
@@ -359,13 +359,18 @@ extension FilePath {
// MARK: - Invariants
extension FilePath {
internal func _invariantCheck() {
#if DEBUG
internal func _invariantsSatisfied() -> Bool {
var normal = self
normal._normalizeSeparators()
precondition(self == normal)
precondition(!self._storage._hasTrailingSeparator())
precondition(_hasRoot == (self.root != nil))
guard self == normal else { return false }
guard !self._storage._hasTrailingSeparator() else { return false }
guard _hasRoot == (self.root != nil) else { return false }
return true
}
internal func _invariantCheck() {
#if DEBUG
precondition(_invariantsSatisfied())
#endif // DEBUG
}
}
+183 -19
View File
@@ -9,7 +9,7 @@
// MARK: - Platform string
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
@@ -20,6 +20,49 @@ extension FilePath {
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.
///
@@ -45,7 +88,7 @@ extension FilePath {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
@@ -60,6 +103,59 @@ extension FilePath.Component {
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.
///
@@ -82,7 +178,7 @@ extension FilePath.Component {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
@@ -96,6 +192,58 @@ extension FilePath.Root {
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.
///
@@ -120,7 +268,7 @@ extension FilePath.Root {
// MARK: - String literals
// @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 FilePath: ExpressibleByStringLiteral {
/// Creates a file path from a string literal.
///
@@ -139,7 +287,7 @@ extension FilePath: ExpressibleByStringLiteral {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
///
@@ -148,7 +296,7 @@ extension FilePath.Component: ExpressibleByStringLiteral {
public init(stringLiteral: String) {
guard let s = FilePath.Component(stringLiteral) else {
// TODO: static assert
preconditionFailure("""
fatalError("""
FilePath.Component must be created from exactly one non-root component
""")
}
@@ -164,7 +312,7 @@ extension FilePath.Component: ExpressibleByStringLiteral {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
///
@@ -172,7 +320,7 @@ extension FilePath.Root: ExpressibleByStringLiteral {
public init(stringLiteral: String) {
guard let s = FilePath.Root(stringLiteral) else {
// TODO: static assert
preconditionFailure("""
fatalError("""
FilePath.Root must be created from a root
""")
}
@@ -189,7 +337,7 @@ extension FilePath.Root: ExpressibleByStringLiteral {
// MARK: - Printing and dumping
// @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 FilePath: CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of the file path.
///
@@ -205,7 +353,7 @@ extension FilePath: CustomStringConvertible, CustomDebugStringConvertible {
public var debugDescription: String { description.debugDescription }
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
@@ -222,7 +370,7 @@ extension FilePath.Component: CustomStringConvertible, CustomDebugStringConverti
public var debugDescription: String { description.debugDescription }
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
@@ -242,7 +390,7 @@ extension FilePath.Root: CustomStringConvertible, CustomDebugStringConvertible {
// MARK: - Convenience helpers
// Convenience helpers
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
@@ -253,7 +401,7 @@ extension FilePath {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
@@ -264,7 +412,7 @@ extension FilePath.Component {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
extension FilePath.Root {
/// On Unix, this returns `"/"`.
///
@@ -278,7 +426,7 @@ extension FilePath.Root {
// MARK: - Decoding and validating
// @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 String {
/// Creates a string by interpreting the file path's content as UTF-8 on Unix
/// and UTF-16 on Windows.
@@ -308,7 +456,7 @@ extension String {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
@@ -338,7 +486,7 @@ extension String {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
extension String {
/// On Unix, creates the string `"/"`
///
@@ -391,7 +539,7 @@ extension String {
// MARK: - Deprecations
// @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 String {
@available(*, deprecated, renamed: "init(decoding:)")
public init(_ path: FilePath) { self.init(decoding: path) }
@@ -401,14 +549,30 @@ extension String {
}
#if !os(Windows)
// @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 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>(
+8 -8
View File
@@ -9,7 +9,7 @@
// MARK: - Query API
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
@@ -101,7 +101,7 @@ extension FilePath {
}
// MARK: - Decompose a path
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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`.
///
@@ -186,7 +186,7 @@ extension FilePath {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
@@ -258,7 +258,7 @@ extension FilePath {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
///
@@ -291,7 +291,7 @@ extension FilePath.Component {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
@@ -358,7 +358,7 @@ extension FilePath {
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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
@@ -439,7 +439,7 @@ extension FilePath {
}
// Modification and concatenation API
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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`.
@@ -601,7 +601,7 @@ extension FilePath {
}
// MARK - Renamed
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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() }
+2 -2
View File
@@ -17,7 +17,7 @@
/// 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
@@ -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
{
+9 -6
View File
@@ -10,24 +10,27 @@
// MARK: - Public typealiases
/// The C `mode_t` type.
// @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, *)*/
@available(*, deprecated, renamed: "CInterop.Mode")
public typealias CModeT = CInterop.Mode
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(Android)
import CSystem
import Glibc
#elseif os(Windows)
import CSystem
import ucrt
#elseif canImport(Glibc)
@_implementationOnly import CSystem
import Glibc
#elseif canImport(Musl)
@_implementationOnly import CSystem
import Musl
#else
#error("Unsupported Platform")
#endif
/// A namespace for C and platform types
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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
+22 -16
View File
@@ -11,20 +11,22 @@
// they can be used anywhere without imports and without confusion to
// unavailable local decls.
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(Android)
import CSystem
import Glibc
#elseif os(Windows)
import CSystem
import ucrt
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import CSystem
import Musl
#else
#error("Unsupported Platform")
#endif
// MARK: errno
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _ERRNO_NOT_USED: CInt { 0 }
#endif
@@ -270,7 +272,7 @@ internal var _EHOSTUNREACH: CInt { EHOSTUNREACH }
@_alwaysEmitIntoClient
internal var _ENOTEMPTY: CInt { ENOTEMPTY }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _EPROCLIM: CInt { EPROCLIM }
#endif
@@ -311,7 +313,7 @@ internal var _EREMOTE: CInt {
#endif
}
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _EBADRPC: CInt { EBADRPC }
@@ -334,7 +336,7 @@ internal var _ENOLCK: CInt { ENOLCK }
@_alwaysEmitIntoClient
internal var _ENOSYS: CInt { ENOSYS }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _EFTYPE: CInt { EFTYPE }
@@ -356,7 +358,7 @@ internal var _EDEVERR: CInt { EDEVERR }
internal var _EOVERFLOW: CInt { EOVERFLOW }
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _EBADEXEC: CInt { EBADEXEC }
@@ -384,7 +386,7 @@ internal var _ENOMSG: CInt { ENOMSG }
@_alwaysEmitIntoClient
internal var _EILSEQ: CInt { EILSEQ }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _ENOATTR: CInt { ENOATTR }
#endif
@@ -418,7 +420,7 @@ internal var _ETIME: CInt { ETIME }
@_alwaysEmitIntoClient
internal var _EOPNOTSUPP: CInt { EOPNOTSUPP }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _ENOPOLICY: CInt { ENOPOLICY }
#endif
@@ -431,7 +433,7 @@ internal var _ENOTRECOVERABLE: CInt { ENOTRECOVERABLE }
internal var _EOWNERDEAD: CInt { EOWNERDEAD }
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _EQFULL: CInt { EQFULL }
@@ -451,9 +453,13 @@ internal var _O_WRONLY: CInt { O_WRONLY }
internal var _O_RDWR: CInt { O_RDWR }
#if !os(Windows)
#if canImport(Musl)
internal var _O_ACCMODE: CInt { 0x03|O_SEARCH }
#else
// TODO: API?
@_alwaysEmitIntoClient
internal var _O_ACCMODE: CInt { O_ACCMODE }
#endif
@_alwaysEmitIntoClient
internal var _O_NONBLOCK: CInt { O_NONBLOCK }
@@ -462,7 +468,7 @@ internal var _O_NONBLOCK: CInt { O_NONBLOCK }
@_alwaysEmitIntoClient
internal var _O_APPEND: CInt { O_APPEND }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _O_SHLOCK: CInt { O_SHLOCK }
@@ -488,7 +494,7 @@ internal var _O_TRUNC: CInt { O_TRUNC }
@_alwaysEmitIntoClient
internal var _O_EXCL: CInt { O_EXCL }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _O_EVTONLY: CInt { O_EVTONLY }
#endif
@@ -502,7 +508,7 @@ internal var _O_NOCTTY: CInt { O_NOCTTY }
internal var _O_DIRECTORY: CInt { O_DIRECTORY }
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _O_SYMLINK: CInt { O_SYMLINK }
#endif
@@ -521,7 +527,7 @@ internal var _SEEK_CUR: CInt { SEEK_CUR }
@_alwaysEmitIntoClient
internal var _SEEK_END: CInt { SEEK_END }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
@_alwaysEmitIntoClient
internal var _SEEK_HOLE: CInt { SEEK_HOLE }
+14 -6
View File
@@ -12,14 +12,17 @@
// TODO: Should CSystem just include all the header files we need?
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(Android)
import CSystem
import Glibc
#elseif os(Windows)
import CSystem
import ucrt
#elseif canImport(Glibc)
@_implementationOnly import CSystem
import Glibc
#elseif canImport(Musl)
@_implementationOnly import CSystem
import Musl
#else
#error("Unsupported Platform")
#endif
@@ -28,7 +31,7 @@ internal typealias _COffT = off_t
// MARK: syscalls and variables
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
internal var system_errno: CInt {
get { Darwin.errno }
set { Darwin.errno = newValue }
@@ -45,11 +48,16 @@ internal var system_errno: CInt {
_ = ucrt._set_errno(newValue)
}
}
#else
#elseif canImport(Glibc)
internal var system_errno: CInt {
get { Glibc.errno }
set { Glibc.errno = newValue }
}
#elseif canImport(Musl)
internal var system_errno: CInt {
get { Musl.errno }
set { Musl.errno = newValue }
}
#endif
// MARK: C stdlib decls
+30 -2
View File
@@ -7,10 +7,12 @@
See https://swift.org/LICENSE.txt for license information
*/
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(Android)
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif os(Windows)
import ucrt
#else
@@ -69,7 +71,15 @@ internal func system_pread(
#if ENABLE_MOCKING
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
#endif
#if os(Android)
var zero = UInt8.zero
return withUnsafeMutablePointer(to: &zero) {
// this pread has a non-nullable `buf` pointer
pread(fd, buf ?? UnsafeMutableRawPointer($0), nbyte, offset)
}
#else
return pread(fd, buf, nbyte, offset)
#endif
}
// lseek
@@ -99,7 +109,15 @@ internal func system_pwrite(
#if ENABLE_MOCKING
if mockingEnabled { return _mockInt(fd, buf, nbyte, offset) }
#endif
#if os(Android)
var zero = UInt8.zero
return withUnsafeMutablePointer(to: &zero) {
// this pwrite has a non-nullable `buf` pointer
pwrite(fd, buf ?? UnsafeRawPointer($0), nbyte, offset)
}
#else
return pwrite(fd, buf, nbyte, offset)
#endif
}
internal func system_dup(_ fd: Int32) -> Int32 {
@@ -115,6 +133,7 @@ internal func system_dup2(_ fd: Int32, _ fd2: Int32) -> Int32 {
#endif
return dup2(fd, fd2)
}
#if !os(Windows)
internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
#if ENABLE_MOCKING
@@ -123,3 +142,12 @@ internal func system_pipe(_ fds: UnsafeMutablePointer<Int32>) -> CInt {
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
+108 -1
View File
@@ -7,7 +7,7 @@
See https://swift.org/LICENSE.txt for license information
*/
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
@@ -20,10 +20,61 @@ extension String {
/// 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.
@_disfavoredOverload
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.
///
@@ -38,6 +89,62 @@ extension String {
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.
///
+62 -22
View File
@@ -95,10 +95,18 @@ extension SystemString {
}
extension SystemString {
fileprivate func _invariantsSatisfied() -> Bool {
guard !nullTerminatedStorage.isEmpty else { return false }
guard nullTerminatedStorage.last! == .null else { return false }
guard nullTerminatedStorage.firstIndex(of: .null) == length else {
return false
}
return true
}
fileprivate func _invariantCheck() {
#if DEBUG
precondition(nullTerminatedStorage.last! == .null)
precondition(nullTerminatedStorage.firstIndex(of: .null) == length)
precondition(_invariantsSatisfied())
#endif // DEBUG
}
}
@@ -141,42 +149,72 @@ extension SystemString: RangeReplaceableCollection {
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)
// Do not include the null terminator, it is outside the Collection
try nullTerminatedStorage.withContiguousStorageIfAvailable {
try body(.init(start: $0.baseAddress, count: $0.count-1))
}
}
internal mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<SystemChar>) throws -> R
) rethrows -> R? {
defer { _invariantCheck() }
return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable(body)
// Do not include the null terminator, it is outside the Collection
return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable {
var buffer = UnsafeMutableBufferPointer<SystemChar>(
start: $0.baseAddress, count: $0.count-1
)
return try body(&buffer)
}
}
}
extension SystemString: Hashable, Codable {}
extension SystemString: Hashable, Codable {
// Encoder is synthesized; it probably should have been explicit and used
// a single-value container, but making that change now is somewhat risky.
// Decoder is written explicitly to ensure that we validate invariants on
// untrusted input.
public init(from decoder: any Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.nullTerminatedStorage = try container.decode(
Storage.self, forKey: .nullTerminatedStorage
)
guard _invariantsSatisfied() else {
throw DecodingError.dataCorruptedError(
forKey: .nullTerminatedStorage,
in: container,
debugDescription:
"Encoding does not satisfy the invariants of SystemString"
)
}
}
}
extension SystemString {
// TODO: Below include null terminator, is this desired?
// withSystemChars includes the null terminator
internal func withSystemChars<T>(
_ f: (UnsafeBufferPointer<SystemChar>) throws -> T
) rethrows -> T {
try withContiguousStorageIfAvailable(f)!
try nullTerminatedStorage.withContiguousStorageIfAvailable(f)!
}
internal func withCodeUnits<T>(
_ f: (UnsafeBufferPointer<CInterop.PlatformUnicodeEncoding.CodeUnit>) throws -> T
) rethrows -> T {
try withSystemChars {
// TODO: Is this the right way?
let base = UnsafeRawPointer(
$0.baseAddress
)!.assumingMemoryBound(to: CInterop.PlatformUnicodeEncoding.CodeUnit.self)
return try f(UnsafeBufferPointer(start: base, count: $0.count))
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))
}
}
}
}
@@ -272,13 +310,15 @@ extension SystemString {
internal func withPlatformString<T>(
_ f: (UnsafePointer<CInterop.PlatformChar>) throws -> T
) rethrows -> T {
try withSystemChars {
// TODO: Is this the right way?
let base = UnsafeRawPointer(
$0.baseAddress
)!.assumingMemoryBound(to: CInterop.PlatformChar.self)
assert(base[self.count] == 0)
return try f(base)
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)
}
}
}
}
+4 -4
View File
@@ -8,21 +8,21 @@
*/
// Results in errno if i == -1
// @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, *)*/
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, *)
/*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,7 +36,7 @@ internal func valueOrErrno<I: FixedWidthInteger>(
} while true
}
// @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 nothingOrErrno<I: FixedWidthInteger>(
retryOnInterrupt: Bool, _ f: () -> I
) -> Result<(), Errno> {
+8 -8
View File
@@ -15,7 +15,7 @@ import SystemPackage
import System
#endif
// @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 ErrnoTest: XCTestCase {
func testConstants() {
XCTAssert(EPERM == Errno.notPermitted.rawValue)
@@ -84,7 +84,7 @@ final class ErrnoTest: XCTestCase {
XCTAssert(EHOSTUNREACH == Errno.noRouteToHost.rawValue)
XCTAssert(ENOTEMPTY == Errno.directoryNotEmpty.rawValue)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
XCTAssert(EPROCLIM == Errno.tooManyProcesses.rawValue)
#endif
@@ -92,7 +92,7 @@ final class ErrnoTest: XCTestCase {
XCTAssert(EDQUOT == Errno.diskQuotaExceeded.rawValue)
XCTAssert(ESTALE == Errno.staleNFSFileHandle.rawValue)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
XCTAssert(EBADRPC == Errno.rpcUnsuccessful.rawValue)
XCTAssert(ERPCMISMATCH == Errno.rpcVersionMismatch.rawValue)
XCTAssert(EPROGUNAVAIL == Errno.rpcProgramUnavailable.rawValue)
@@ -103,7 +103,7 @@ final class ErrnoTest: XCTestCase {
XCTAssert(ENOLCK == Errno.noLocks.rawValue)
XCTAssert(ENOSYS == Errno.noFunction.rawValue)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
XCTAssert(EFTYPE == Errno.badFileTypeOrFormat.rawValue)
XCTAssert(EAUTH == Errno.authenticationError.rawValue)
XCTAssert(ENEEDAUTH == Errno.needAuthenticator.rawValue)
@@ -113,7 +113,7 @@ final class ErrnoTest: XCTestCase {
XCTAssert(EOVERFLOW == Errno.overflow.rawValue)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
XCTAssert(EBADEXEC == Errno.badExecutable.rawValue)
XCTAssert(EBADARCH == Errno.badCPUType.rawValue)
XCTAssert(ESHLIBVERS == Errno.sharedLibraryVersionMismatch.rawValue)
@@ -125,7 +125,7 @@ final class ErrnoTest: XCTestCase {
XCTAssert(ENOMSG == Errno.noMessage.rawValue)
XCTAssert(EILSEQ == Errno.illegalByteSequence.rawValue)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
XCTAssert(ENOATTR == Errno.attributeNotFound.rawValue)
#endif
@@ -144,14 +144,14 @@ final class ErrnoTest: XCTestCase {
XCTAssert(ETOOMANYREFS == Errno.tooManyReferences.rawValue)
XCTAssert(EREMOTE == Errno.tooManyRemoteLevels.rawValue)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
XCTAssert(ENOPOLICY == Errno.noSuchPolicy.rawValue)
#endif
XCTAssert(ENOTRECOVERABLE == Errno.notRecoverable.rawValue)
XCTAssert(EOWNERDEAD == Errno.previousOwnerDied.rawValue)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
XCTAssert(EQFULL == Errno.outputQueueFull.rawValue)
XCTAssert(ELAST == Errno.lastErrnoValue.rawValue)
#endif
@@ -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
}
}
+69 -1
View File
@@ -15,7 +15,7 @@ import SystemPackage
import System
#endif
// @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 FileOperationsTest: XCTestCase {
func testSyscalls() {
let fd = FileDescriptor(rawValue: 1)
@@ -86,6 +86,30 @@ final class FileOperationsTest: XCTestCase {
for test in syscallTestCases { test.runAllTests() }
}
func testWriteFromEmptyBuffer() throws {
let fd = try FileDescriptor.open(FilePath("/dev/null"), .writeOnly)
let written1 = try fd.write(toAbsoluteOffset: 0, .init(start: nil, count: 0))
XCTAssertEqual(written1, 0)
let pointer = UnsafeMutableRawPointer.allocate(byteCount: 8, alignment: 8)
defer { pointer.deallocate() }
let empty = UnsafeRawBufferPointer(start: pointer, count: 0)
let written2 = try fd.write(toAbsoluteOffset: 0, empty)
XCTAssertEqual(written2, 0)
}
func testReadToEmptyBuffer() throws {
let fd = try FileDescriptor.open(FilePath("/dev/random"), .readOnly)
let read1 = try fd.read(fromAbsoluteOffset: 0, into: .init(start: nil, count: 0))
XCTAssertEqual(read1, 0)
let pointer = UnsafeMutableRawPointer.allocate(byteCount: 8, alignment: 8)
defer { pointer.deallocate() }
let empty = UnsafeMutableRawBufferPointer(start: pointer, count: 0)
let read2 = try fd.read(fromAbsoluteOffset: 0, into: empty)
XCTAssertEqual(read2, 0)
}
func testHelpers() {
// TODO: Test writeAll, writeAll(toAbsoluteOffset), closeAfter
}
@@ -160,5 +184,49 @@ final class FileOperationsTest: XCTestCase {
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
}
@@ -15,7 +15,7 @@ import XCTest
@testable import System
#endif
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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?
@@ -100,7 +100,7 @@ struct TestPathComponents: TestCase {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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"
@@ -0,0 +1,129 @@
/*
This source file is part of the Swift System open source project
Copyright (c)2024 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
@available(/*System 0.0.1: macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0*/iOS 8, *)
final class FilePathDecodableTest: XCTestCase {
func testInvalidFilePath() {
// _storage is a valid SystemString, but the invariants of FilePath are
// violated (specifically, _storage is not normal).
let input: [UInt8] = [
123, 34, 95,115,116,111,114, 97,103,101, 34, 58,123, 34,110,117,108,108,
84,101,114,109,105,110, 97,116,101,100, 83,116,111,114, 97,103,101, 34,
58, 91, 49, 48, 57, 44, 45, 55, 54, 44, 53, 53, 44, 55, 49, 44, 49, 52,
44, 53, 57, 44, 45, 49, 49, 50, 44, 45, 56, 52, 44, 52, 50, 44, 45, 55,
48, 44, 45, 49, 48, 52, 44, 55, 51, 44, 45, 54, 44, 50, 44, 53, 55, 44,
54, 50, 44, 45, 56, 55, 44, 45, 53, 44, 45, 54, 53, 44, 45, 51, 57, 44,
45, 49, 48, 57, 44, 45, 55, 54, 44, 51, 48, 44, 53, 50, 44, 45, 56, 50,
44, 45, 54, 48, 44, 45, 50, 44, 56, 53, 44, 49, 50, 51, 44, 45, 56, 52,
44, 45, 53, 56, 44, 49, 49, 52, 44, 49, 44, 45, 49, 49, 54, 44, 56, 48,
44, 49, 48, 52, 44, 45, 55, 56, 44, 45, 52, 53, 44, 49, 54, 44, 45, 52,
54, 44, 55, 44, 49, 49, 56, 44, 45, 50, 52, 44, 54, 50, 44, 54, 52, 44,
45, 52, 49, 44, 45, 49, 48, 51, 44, 53, 44, 45, 55, 53, 44, 50, 50, 44,
45, 49, 48, 53, 44, 45, 49, 54, 44, 52, 55, 44, 52, 55, 44, 49, 50, 52,
44, 45, 53, 55, 44, 53, 51, 44, 49, 49, 49, 44, 49, 53, 44, 45, 50, 55,
44, 54, 54, 44, 45, 49, 54, 44, 49, 48, 50, 44, 49, 48, 54, 44, 49, 51,
44, 49, 48, 53, 44, 45, 49, 49, 50, 44, 55, 56, 44, 45, 53, 48, 44, 50,
48, 44, 56, 44, 45, 50, 55, 44, 52, 52, 44, 52, 44, 56, 44, 54, 53, 44,
50, 51, 44, 57, 55, 44, 45, 50, 56, 44, 56, 56, 44, 52, 50, 44, 45, 51,
54, 44, 45, 50, 51, 44, 49, 48, 51, 44, 57, 57, 44, 45, 53, 56, 44, 45,
49, 49, 48, 44, 45, 53, 52, 44, 45, 49, 49, 55, 44, 45, 57, 52, 44, 45,
55, 50, 44, 50, 57, 44, 45, 50, 52, 44, 45, 56, 52, 44, 53, 55, 44, 45,
49, 50, 54, 44, 52, 52, 44, 55, 53, 44, 55, 54, 44, 52, 57, 44, 45, 52,
49, 44, 45, 50, 53, 44, 50, 52, 44, 45, 49, 50, 54, 44, 55, 44, 50, 56,
44, 45, 52, 56, 44, 56, 55, 44, 51, 49, 44, 45, 49, 49, 53, 44, 55, 44,
45, 54, 48, 44, 53, 57, 44, 49, 51, 44, 55, 57, 44, 53, 48, 44, 45, 57,
54, 44, 45, 50, 44, 45, 50, 52, 44, 45, 57, 49, 44, 55, 49, 44, 45, 49,
50, 53, 44, 52, 50, 44, 45, 56, 52, 44, 52, 44, 53, 57, 44, 49, 50, 53,
44, 49, 50, 49, 44, 45, 50, 54, 44, 45, 49, 50, 44, 45, 49, 48, 53, 44,
53, 54, 44, 49, 49, 48, 44, 49, 52, 44, 45, 49, 48, 52, 44, 45, 53, 50,
44, 45, 53, 56, 44, 45, 54, 44, 45, 50, 54, 44, 45, 52, 55, 44, 53, 57,
44, 52, 50, 44, 49, 50, 51, 44, 52, 52, 44, 45, 57, 50, 44, 45, 50, 57,
44, 45, 51, 54, 44, 45, 54, 50, 44, 50, 54, 44, 45, 49, 55, 44, 45, 49,
48, 44, 45, 56, 49, 44, 54, 49, 44, 52, 55, 44, 45, 57, 52, 44, 45, 49,
48, 54, 44, 49, 53, 44, 49, 48, 48, 44, 45, 49, 50, 49, 44, 45, 49, 49,
49, 44, 51, 44, 45, 57, 44, 52, 54, 44, 45, 55, 48, 44, 45, 49, 57, 44,
52, 56, 44, 45, 49, 50, 44, 45, 57, 49, 44, 45, 50, 48, 44, 49, 51, 44,
54, 53, 44, 45, 55, 48, 44, 52, 49, 44, 45, 57, 53, 44, 49, 48, 52, 44,
45, 55, 53, 44, 45, 49, 49, 53, 44, 49, 48, 49, 44, 45, 57, 52, 44, 45,
49, 50, 51, 44, 45, 51, 53, 44, 45, 50, 49, 44, 45, 52, 50, 44, 45, 51,
48, 44, 45, 55, 49, 44, 45, 49, 49, 57, 44, 52, 52, 44, 49, 49, 49, 44,
49, 48, 53, 44, 54, 54, 44, 45, 49, 50, 54, 44, 55, 50, 44, 45, 52, 48,
44, 49, 50, 49, 44, 45, 50, 49, 44, 52, 50, 44, 45, 55, 56, 44, 49, 50,
54, 44, 56, 49, 44, 45, 57, 52, 44, 55, 52, 44, 49, 49, 50, 44, 45, 56,
54, 44, 51, 50, 44, 55, 54, 44, 49, 49, 55, 44, 45, 56, 44, 56, 54, 44,
49, 48, 51, 44, 54, 50, 44, 49, 49, 55, 44, 54, 55, 44, 45, 56, 54, 44,
45, 49, 48, 48, 44, 45, 49, 48, 57, 44, 45, 53, 52, 44, 45, 51, 49, 44,
45, 56, 57, 44, 48, 93,125,125,
]
XCTAssertThrowsError(try JSONDecoder().decode(
FilePath.self,
from: Data(input)
))
}
func testInvalidSystemString() {
// _storage is a SystemString whose invariants are violated; it contains
// a non-terminating null byte.
let input: [UInt8] = [
123, 34, 95,115,116,111,114, 97,103,101, 34, 58,123, 34,110,117,108,108,
84,101,114,109,105,110, 97,116,101,100, 83,116,111,114, 97,103,101, 34,
58, 91, 49, 49, 49, 44, 48, 44, 45, 49, 54, 44, 57, 49, 44, 52, 54, 44,
45, 49, 48, 50, 44, 49, 49, 53, 44, 45, 50, 49, 44, 45, 49, 49, 56, 44,
52, 57, 44, 57, 50, 44, 45, 49, 48, 44, 53, 56, 44, 45, 55, 48, 44, 57,
55, 44, 56, 44, 57, 57, 44, 48, 93,125, 125
]
XCTAssertThrowsError(try JSONDecoder().decode(
FilePath.self,
from: Data(input)
))
}
func testInvalidExample() {
// Another misformed example from Johannes that violates FilePath's
// invariants by virtue of not being normalized.
let input: [UInt8] = [
123, 34, 95,115,116,111,114, 97,103,101, 34, 58,123, 34,110,117,108,108,
84,101,114,109,105,110, 97,116,101,100, 83,116,111,114, 97,103,101, 34,
58, 91, 56, 55, 44, 50, 52, 44, 45, 49, 49, 53, 44, 45, 49, 57, 44, 49,
50, 50, 44, 45, 54, 56, 44, 57, 49, 44, 45, 49, 48, 54, 44, 45, 49, 48,
48, 44, 45, 49, 49, 52, 44, 53, 54, 44, 45, 54, 53, 44, 49, 49, 56, 44,
45, 54, 48, 44, 54, 54, 44, 45, 52, 50, 44, 55, 55, 44, 45, 54, 44, 45,
52, 50, 44, 45, 56, 56, 44, 52, 55, 44, 48, 93,125, 125
]
XCTAssertThrowsError(try JSONDecoder().decode(
FilePath.self,
from: Data(input)
))
}
func testEmptyString() {
// FilePath with an empty (and hence not null-terminated) SystemString.
let input: [UInt8] = [
123, 34, 95,115,116,111,114, 97,103,101, 34, 58,123, 34,110,117,108,108,
84,101,114,109,105,110, 97,116,101,100, 83,116,111,114, 97,103,101, 34,
58, 91, 93,125,125
]
XCTAssertThrowsError(try JSONDecoder().decode(
FilePath.self,
from: Data(input)
))
}
}
@@ -6,7 +6,7 @@
#endif
// Why can't I write this extension on `FilePath.ComponentView.SubSequence`?
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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]
@@ -15,7 +15,7 @@ extension Slice where Base == FilePath.ComponentView {
// Proposed API that didn't make the cut, but we stil want to keep our testing for
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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.
@@ -68,7 +68,7 @@ extension ParsingTestCase {
@testable import System
#endif
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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> = [
@@ -146,7 +146,7 @@ extension SyntaxTestCase {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
extension SyntaxTestCase {
func testComponents(_ path: FilePath, expected: [String]) {
let expectedComponents = expected.map { FilePath.Component($0)! }
@@ -342,7 +342,7 @@ private struct WindowsRootTestCase: TestCase {
var line: UInt
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
extension WindowsRootTestCase {
func runAllTests() {
withWindowsPaths(enabled: true) {
@@ -357,7 +357,7 @@ extension WindowsRootTestCase {
}
}
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*System 0.0.2, @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *)*/
final class FilePathSyntaxTest: XCTestCase {
func testPathSyntax() {
let unixPaths: Array<SyntaxTestCase> = [
@@ -15,19 +15,21 @@ import SystemPackage
import System
#endif
// @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(platformString: $0.baseAddress!._asCChar)
$0.withMemoryRebound(to: CChar.self) {
FilePath(platformString: $0.baseAddress!)
}
}
}
let invalidBytes: [UInt8] = [0x2F, 0x61, 0x2F, 0x62, 0x2F, 0x83]
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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
+4 -4
View File
@@ -15,7 +15,7 @@ import SystemPackage
import System
#endif
// @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 FileDescriptorTest: XCTestCase {
func testStandardDescriptors() {
XCTAssertEqual(FileDescriptor.standardInput.rawValue, 0)
@@ -38,7 +38,7 @@ final class FileDescriptorTest: XCTestCase {
XCTAssertEqual(O_CLOEXEC, FileDescriptor.OpenOptions.closeOnExec.rawValue)
// BSD only
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
XCTAssertEqual(O_SHLOCK, FileDescriptor.OpenOptions.sharedLock.rawValue)
XCTAssertEqual(O_EXLOCK, FileDescriptor.OpenOptions.exclusiveLock.rawValue)
XCTAssertEqual(O_SYMLINK, FileDescriptor.OpenOptions.symlink.rawValue)
@@ -49,7 +49,7 @@ final class FileDescriptorTest: XCTestCase {
XCTAssertEqual(SEEK_CUR, FileDescriptor.SeekOrigin.current.rawValue)
XCTAssertEqual(SEEK_END, FileDescriptor.SeekOrigin.end.rawValue)
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
#if SYSTEM_PACKAGE_DARWIN
XCTAssertEqual(SEEK_HOLE, FileDescriptor.SeekOrigin.nextHole.rawValue)
XCTAssertEqual(SEEK_DATA, FileDescriptor.SeekOrigin.nextData.rawValue)
#endif
@@ -60,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() {
+1 -1
View File
@@ -15,7 +15,7 @@ import XCTest
@testable import System
#endif
// @available(macOS 9999, iOS 9999, watchOS 9999, tvOS 9999, *)
/*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)
+163 -24
View File
@@ -10,29 +10,6 @@
// Tests for PlatformString, SystemString, and FilePath's forwarding APIs
// TODO: Adapt test to Windows
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)
}
}
import XCTest
@@ -46,7 +23,7 @@ private func makeRaw(
_ str: String
) -> [CInterop.PlatformChar] {
var str = str
var array = str.withUTF8 { Array($0._asCChar) }
var array = str.withUTF8 { $0.withMemoryRebound(to: CChar.self, Array.init) }
array.append(0)
return array
}
@@ -275,3 +252,165 @@ final class SystemStringTest: XCTestCase {
}
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)
}
}
+1
View File
@@ -27,6 +27,7 @@ extension FileOperationsTest {
// to regenerate.
static let __allTests__FileOperationsTest = [
("testAdHocOpen", testAdHocOpen),
("testAdHocPipe", testAdHocPipe),
("testGithubIssues", testGithubIssues),
("testHelpers", testHelpers),
("testSyscalls", testSyscalls),
+85
View File
@@ -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="")
+1 -1
View File
@@ -17,7 +17,7 @@ See https://swift.org/LICENSE.txt for license information
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")
elseif ("${CMAKE_SYSTEM_PROCESSOR}" MATCHES "AArch64|aarch64|arm64|ARM64")
if(CMAKE_SYSTEM_NAME MATCHES Darwin)
set("${result_var_name}" "arm64" PARENT_SCOPE)
else()