Import FoundationEssentials instead of Foundation when available (#227)

`FoundationEssentials` is more lightweight than `Foundation`, and so we
should switch to importing it when possible.
This commit is contained in:
Gus Cairo authored and GitHub committed 2025-02-24 14:17:11 +00:00
1 parent dc098a9193
commit a65f903b02
33 files changed
+456 -41

No files matched your search

+1
View File
@@ -59,6 +59,7 @@ add_library(X509
"Extensions.swift"
"ExtensionsBuilder.swift"
"GeneralName.swift"
"Lock.swift"
"LockedValueBox.swift"
"OCSP/BasicOCSPResponse.swift"
"OCSP/DirectoryString.swift"
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import SwiftASN1
/// A representation of a PKCS#10 Certificate Signing Request (CSR).
+4
View File
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import SwiftASN1
/// A representation of an X.509 certificate object.
+4
View File
@@ -13,7 +13,11 @@
//===----------------------------------------------------------------------===//
import SwiftASN1
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
@preconcurrency import Crypto
import _CryptoExtras
+4
View File
@@ -15,7 +15,11 @@
import SwiftASN1
@preconcurrency import Crypto
import _CryptoExtras
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
extension Certificate {
/// A public key that can be used with a certificate.
@@ -11,7 +11,11 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import SwiftASN1
import Crypto
@@ -13,7 +13,9 @@
//===----------------------------------------------------------------------===//
import SwiftASN1
#if canImport(Darwin) || swift(>=5.9.1)
#if canImport(FoundationEssentials)
import FoundationEssentials
#elseif canImport(Darwin) || swift(>=5.9.1)
import Foundation
#else
@preconcurrency import Foundation
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import SwiftASN1
/// ``CMSSignerInfo`` is defined in ASN.1 as:
+4
View File
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import SwiftASN1
import Crypto
+4
View File
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import Crypto
@usableFromInline
+275
View File
@@ -0,0 +1,275 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCertificates open source project
//
// Copyright (c) 2023 Apple Inc. and the SwiftCertificates project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftCertificates project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(Darwin)
import Darwin
#elseif os(Windows)
import ucrt
import WinSDK
#elseif canImport(Glibc)
import Glibc
#elseif canImport(Musl)
import Musl
#elseif canImport(Bionic)
import Bionic
#elseif canImport(WASILibc)
import WASILibc
#if canImport(wasi_pthread)
import wasi_pthread
#endif
#else
#error("The concurrency CertificatesLock module was unable to identify your C library.")
#endif
#if os(Windows)
@usableFromInline
typealias LockPrimitive = SRWLOCK
#else
@usableFromInline
typealias LockPrimitive = pthread_mutex_t
#endif
@usableFromInline
enum LockOperations {}
extension LockOperations {
@inlinable
static func create(_ mutex: UnsafeMutablePointer<LockPrimitive>) {
mutex.assertValidAlignment()
#if os(Windows)
InitializeSRWLock(mutex)
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
var attr = pthread_mutexattr_t()
pthread_mutexattr_init(&attr)
debugOnly {
pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK))
}
let err = pthread_mutex_init(mutex, &attr)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
#endif
}
@inlinable
static func destroy(_ mutex: UnsafeMutablePointer<LockPrimitive>) {
mutex.assertValidAlignment()
#if os(Windows)
// SRWLOCK does not need to be free'd
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
let err = pthread_mutex_destroy(mutex)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
#endif
}
@inlinable
static func lock(_ mutex: UnsafeMutablePointer<LockPrimitive>) {
mutex.assertValidAlignment()
#if os(Windows)
AcquireSRWLockExclusive(mutex)
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
let err = pthread_mutex_lock(mutex)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
#endif
}
@inlinable
static func unlock(_ mutex: UnsafeMutablePointer<LockPrimitive>) {
mutex.assertValidAlignment()
#if os(Windows)
ReleaseSRWLockExclusive(mutex)
#elseif (compiler(<6.1) && !os(WASI)) || (compiler(>=6.1) && _runtime(_multithreaded))
let err = pthread_mutex_unlock(mutex)
precondition(err == 0, "\(#function) failed in pthread_mutex with error \(err)")
#endif
}
}
// Tail allocate both the mutex and a generic value using ManagedBuffer.
// Both the header pointer and the elements pointer are stable for
// the class's entire lifetime.
//
// However, for safety reasons, we elect to place the lock in the "elements"
// section of the buffer instead of the head. The reasoning here is subtle,
// so buckle in.
//
// _As a practical matter_, the implementation of ManagedBuffer ensures that
// the pointer to the header is stable across the lifetime of the class, and so
// each time you call `withUnsafeMutablePointers` or `withUnsafeMutablePointerToHeader`
// the value of the header pointer will be the same. This is because ManagedBuffer uses
// `Builtin.addressOf` to load the value of the header, and that does ~magic~ to ensure
// that it does not invoke any weird Swift accessors that might copy the value.
//
// _However_, the header is also available via the `.header` field on the ManagedBuffer.
// This presents a problem! The reason there's an issue is that `Builtin.addressOf` and friends
// do not interact with Swift's exclusivity model. That is, the various `with` functions do not
// conceptually trigger a mutating access to `.header`. For elements this isn't a concern because
// there's literally no other way to perform the access, but for `.header` it's entirely possible
// to accidentally recursively read it.
//
// Our implementation is free from these issues, so we don't _really_ need to worry about it.
// However, out of an abundance of caution, we store the Value in the header, and the LockPrimitive
// in the trailing elements. We still don't use `.header`, but it's better to be safe than sorry,
// and future maintainers will be happier that we were cautious.
//
// See also: https://github.com/apple/swift/pull/40000
@usableFromInline
final class LockStorage<Value>: ManagedBuffer<Value, LockPrimitive> {
@inlinable
static func create(value: Value) -> Self {
let buffer = Self.create(minimumCapacity: 1) { _ in
value
}
// Intentionally using a force cast here to avoid a miss compiliation in 5.10.
// This is as fast as an unsafeDownCast since ManagedBuffer is inlined and the optimizer
// can eliminate the upcast/downcast pair
let storage = buffer as! Self
storage.withUnsafeMutablePointers { _, lockPtr in
LockOperations.create(lockPtr)
}
return storage
}
@inlinable
func lock() {
self.withUnsafeMutablePointerToElements { lockPtr in
LockOperations.lock(lockPtr)
}
}
@inlinable
func unlock() {
self.withUnsafeMutablePointerToElements { lockPtr in
LockOperations.unlock(lockPtr)
}
}
@inlinable
deinit {
self.withUnsafeMutablePointerToElements { lockPtr in
LockOperations.destroy(lockPtr)
}
}
@inlinable
func withLockPrimitive<T>(_ body: (UnsafeMutablePointer<LockPrimitive>) throws -> T) rethrows -> T {
try self.withUnsafeMutablePointerToElements { lockPtr in
try body(lockPtr)
}
}
@inlinable
func withLockedValue<T>(_ mutate: (inout Value) throws -> T) rethrows -> T {
try self.withUnsafeMutablePointers { valuePtr, lockPtr in
LockOperations.lock(lockPtr)
defer { LockOperations.unlock(lockPtr) }
return try mutate(&valuePtr.pointee)
}
}
}
/// A threading lock based on `libpthread` instead of `libdispatch`.
///
/// - Note: ``CertificatesLock`` has reference semantics.
///
/// This object provides a lock on top of a single `pthread_mutex_t`. This kind
/// of lock is safe to use with `libpthread`-based threading models.
/// On Windows, the lock is based on the substantially similar `SRWLOCK` type.
struct CertificatesLock {
@usableFromInline
internal let _storage: LockStorage<Void>
/// Create a new lock.
@inlinable
init() {
self._storage = .create(value: ())
}
/// Acquire the lock.
///
/// Whenever possible, consider using `withLock` instead of this method and
/// `unlock`, to simplify lock handling.
@inlinable
func lock() {
self._storage.lock()
}
/// Release the lock.
///
/// Whenever possible, consider using `withLock` instead of this method and
/// `lock`, to simplify lock handling.
@inlinable
func unlock() {
self._storage.unlock()
}
@inlinable
internal func withLockPrimitive<T>(_ body: (UnsafeMutablePointer<LockPrimitive>) throws -> T) rethrows -> T {
try self._storage.withLockPrimitive(body)
}
}
extension CertificatesLock {
/// Acquire the lock for the duration of the given block.
///
/// This convenience method should be preferred to `lock` and `unlock` in
/// most situations, as it ensures that the lock will be released regardless
/// of how `body` exits.
///
/// - Parameter body: The block to execute while holding the lock.
/// - Returns: The value returned by the block.
@inlinable
func withLock<T>(_ body: () throws -> T) rethrows -> T {
self.lock()
defer {
self.unlock()
}
return try body()
}
@inlinable
func withLockVoid(_ body: () throws -> Void) rethrows {
try self.withLock(body)
}
}
extension CertificatesLock: @unchecked Sendable {}
extension UnsafeMutablePointer {
@inlinable
func assertValidAlignment() {
assert(UInt(bitPattern: self) % UInt(MemoryLayout<Pointee>.alignment) == 0)
}
}
/// A utility function that runs the body code only in debug builds, without
/// emitting compiler warnings.
///
/// This is currently the only way to do this in Swift: see
/// https://forums.swift.org/t/support-debug-only-code/11037 for a discussion.
@inlinable
internal func debugOnly(_ body: () -> Void) {
assert(
{
body()
return true
}()
)
}
+58 -32
View File
@@ -12,45 +12,71 @@
//
//===----------------------------------------------------------------------===//
import Foundation
/// Provides locked access to `Value`.
///
/// - Note: ``LockedValueBox`` has reference semantics and holds the `Value`
/// alongside a lock behind a reference.
///
/// This is no different than creating a ``Lock`` and protecting all
/// accesses to a value using the lock. But it's easy to forget to actually
/// acquire/release the lock in the correct place. ``LockedValueBox`` makes
/// that much easier.
struct LockedValueBox<Value> {
final class LockedValueBox<Value> {
private let _lock: NSLock = .init()
private var _value: Value
var unsafeUnlockedValue: Value {
get { _value }
set { _value = newValue }
}
func lock() {
_lock.lock()
}
func unlock() {
_lock.unlock()
}
@usableFromInline
internal let _storage: LockStorage<Value>
/// Initialize the `Value`.
@inlinable
init(_ value: Value) {
self._value = value
self._storage = .create(value: value)
}
func withLockedValue<Result>(
_ body: (inout Value) throws -> Result
) rethrows -> Result {
try _lock.withLock {
try body(&_value)
/// Access the `Value`, allowing mutation of it.
@inlinable
func withLockedValue<T>(_ mutate: (inout Value) throws -> T) rethrows -> T {
try self._storage.withLockedValue(mutate)
}
/// Provides an unsafe view over the lock and its value.
///
/// This can be beneficial when you require fine grained control over the lock in some
/// situations but don't want lose the benefits of ``withLockedValue(_:)`` in others by
/// switching to ``NIOLock``.
var unsafe: Unsafe {
Unsafe(_storage: self._storage)
}
/// Provides an unsafe view over the lock and its value.
struct Unsafe {
@usableFromInline
let _storage: LockStorage<Value>
/// Manually acquire the lock.
@inlinable
func lock() {
self._storage.lock()
}
/// Manually release the lock.
@inlinable
func unlock() {
self._storage.unlock()
}
/// Mutate the value, assuming the lock has been acquired manually.
///
/// - Parameter mutate: A closure with scoped access to the value.
/// - Returns: The result of the `mutate` closure.
@inlinable
func withValueAssumingLockIsAcquired<Result>(
_ mutate: (_ value: inout Value) throws -> Result
) rethrows -> Result {
try self._storage.withUnsafeMutablePointerToHeader { value in
try mutate(&value.pointee)
}
}
}
}
extension LockedValueBox: @unchecked Sendable where Value: Sendable {}
extension NSLock {
// this API doesn't exist on Linux and therefore we have a copy of it here
func withLock<Result>(_ body: () throws -> Result) rethrows -> Result {
self.lock()
defer { self.unlock() }
return try body()
}
}
+3 -1
View File
@@ -14,7 +14,9 @@
import SwiftASN1
import Crypto
#if canImport(Darwin) || swift(>=5.9.1)
#if canImport(FoundationEssentials)
import FoundationEssentials
#elseif canImport(Darwin) || swift(>=5.9.1)
import Foundation
#else
@preconcurrency import Foundation
+7 -6
View File
@@ -25,19 +25,20 @@ final class Promise<Value: Sendable, Failure: Error> {
fileprivate var result: Result<Value, Failure> {
get async {
self.state.lock()
self.state.unsafe.lock()
switch self.state.unsafeUnlockedValue {
switch self.state.unsafe.withValueAssumingLockIsAcquired({ $0 }) {
case .fulfilled(let result):
defer { self.state.unlock() }
defer { self.state.unsafe.unlock() }
return result
case .unfulfilled(var observers):
return await withCheckedContinuation {
(continuation: CheckedContinuation<Result<Value, Failure>, Never>) in
observers.append(continuation)
self.state.unsafeUnlockedValue = .unfulfilled(observers: observers)
self.state.unlock()
self.state.unsafe.withValueAssumingLockIsAcquired { value in
value = .unfulfilled(observers: observers)
}
self.state.unsafe.unlock()
}
}
}
+4
View File
@@ -14,7 +14,11 @@
#if canImport(Darwin)
import SwiftASN1
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
@preconcurrency import Crypto
@preconcurrency import _CryptoExtras
@preconcurrency import Security
+4
View File
@@ -15,7 +15,11 @@
import SwiftASN1
import Crypto
import _CryptoExtras
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
extension Certificate {
/// An abstract representation of the cryptographic signature on a certificate.
@@ -11,7 +11,11 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import SwiftASN1
/// A sub-policy of the ``RFC5280Policy`` that polices the basicConstraints extension.
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import SwiftASN1
/// A sub-policy of the ``RFC5280Policy`` that polices expiry.
@@ -11,7 +11,11 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import SwiftASN1
/// A sub-policy of the ``RFC5280Policy`` that polices the nameConstraints extension.
@@ -11,7 +11,11 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import SwiftASN1
/// A ``VerifierPolicy`` that implements the core chain verifying policies from RFC 5280.
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
#if os(Windows)
import WinSDK
#elseif canImport(Glibc)
@@ -12,7 +12,12 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
import Glibc
#else
import Foundation
#endif
import SwiftASN1
#if os(Windows)
import WinSDK
@@ -12,7 +12,12 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
import Dispatch
#else
import Foundation
#endif
import SwiftASN1
/// This is a list of root CA file search paths. This list contains paths as validated against several distributions.
@@ -11,7 +11,11 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import SwiftASN1
import Crypto
+4
View File
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import SwiftASN1
// Time ::= CHOICE {
+4
View File
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import XCTest
import Crypto
import _CryptoExtras
+4
View File
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import XCTest
import Crypto
import _CryptoExtras
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import XCTest
import SwiftASN1
@testable import X509
@@ -16,7 +16,9 @@ import XCTest
@preconcurrency import Crypto
import SwiftASN1
@testable import X509
#if canImport(Darwin) || swift(>=5.9.1)
#if canImport(FoundationEssentials)
import FoundationEssentials
#elseif canImport(Darwin) || swift(>=5.9.1)
import Foundation
#else
@preconcurrency import Foundation
+4
View File
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import XCTest
import SwiftASN1
@testable import X509
+4
View File
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import XCTest
import SwiftASN1
@testable @_spi(DisableValidityCheck) import X509
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import XCTest
import Crypto
import SwiftASN1
+4
View File
@@ -12,7 +12,11 @@
//
//===----------------------------------------------------------------------===//
#if canImport(FoundationEssentials)
import FoundationEssentials
#else
import Foundation
#endif
import XCTest
import SwiftASN1
@testable import X509