Compare commits

...
31 Commits
Author SHA1 Message Date
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
33 changed files with 775 additions and 134 deletions

No files matched your search

+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)
+1 -1
View File
@@ -34,7 +34,7 @@ target_sources(SystemPackage PRIVATE
Internals/Mocking.swift
Internals/Syscalls.swift
Internals/WindowsSyscallAdapters.swift)
target_link_libraries(SystemPackage PRIVATE
target_link_libraries(SystemPackage PUBLIC
CSystem)
+6 -6
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
@@ -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.
@@ -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 {
+11 -11
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`.
@@ -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`.
@@ -256,7 +256,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 the link itself is opened instead of what it links to.
///
@@ -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
{
@@ -427,7 +427,7 @@ extension FileDescriptor.SeekOrigin
public var debugDescription: String { self.description }
}
// @available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
extension FileDescriptor.OpenOptions
: CustomStringConvertible, CustomDebugStringConvertible
{
+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.
+63 -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,79 @@ 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
/*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
}
+3 -3
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,12 @@ 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, *)
/*System 0.0.1, @available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)*/
extension FilePath: Hashable, Codable {}
@@ -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
+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
{
+3 -3
View File
@@ -10,14 +10,14 @@
// 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)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(Android)
import CSystem
@_implementationOnly import CSystem
import Glibc
#elseif os(Windows)
import CSystem
@@ -27,7 +27,7 @@ import ucrt
#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
-1
View File
@@ -14,7 +14,6 @@
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(Android)
import CSystem
import Glibc
#elseif os(Windows)
import CSystem
+1 -1
View File
@@ -15,7 +15,7 @@
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(Android)
import CSystem
@_implementationOnly import CSystem
import Glibc
#elseif os(Windows)
import CSystem
+10
View File
@@ -115,6 +115,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 +124,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
@@ -105,4 +105,11 @@ internal func pwrite(
return Int(nNumberOfBytesWritten)
}
@inline(__always)
internal func ftruncate(
_ fd: Int32,
_ length: off_t
) -> Int32 {
_chsize_s(fd, numericCast(length))
}
#endif
+107 -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.
@@ -24,6 +24,56 @@ extension String {
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 +88,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.
///
+18 -13
View File
@@ -171,12 +171,15 @@ extension SystemString {
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 +275,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> {
+1 -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 ErrnoTest: XCTestCase {
func testConstants() {
XCTAssert(EPERM == Errno.notPermitted.rawValue)
@@ -0,0 +1,25 @@
/*
This source file is part of the Swift System open source project
Copyright (c) 2020 Apple Inc. and the Swift System project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
*/
#if SYSTEM_PACKAGE
@testable import SystemPackage
#else
@testable import System
#endif
extension FileDescriptor {
internal func fileSize(
retryOnInterrupt: Bool = true
) throws -> Int64 {
let current = try seek(offset: 0, from: .current)
let size = try seek(offset: 0, from: .end)
try seek(offset: current, from: .start)
return size
}
}
+45 -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)
@@ -160,5 +160,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"
@@ -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
+2 -2
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)
@@ -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="")