[Future] Bovine → Shared

This commit is contained in:
Karoy Lorentey committed 2024-09-01 20:40:04 -07:00
1 parent 27ce1d423c
commit bfbb0f605e
6 files changed
+198 -138

No files matched your search

+1 -1
View File
@@ -15,7 +15,7 @@ add_library(Future
"LifetimeOverride.swift"
"RawSpan.swift"
"Span.swift"
"Containers/Bovine.swift"
"Containers/Shared.swift"
"Containers/Container.swift"
"Containers/DynamicArray.swift"
"Containers/NewArray.swift"
-128
View File
@@ -1,128 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import Builtin // For Bovine.isIdentical
/// A utility adapter that wraps a noncopyable storage type in a copy-on-write
/// struct, enabling efficient implementation of value semantics. The type
/// allows safe borrowing and mutating access to its storage, with minimal fuss.
///
/// Like `ManagedBufferPointer`, this type is intended to be used within the
/// internal implementation of public types. Instances of it aren't designed
/// to be exposed as public.
///
/// (The placeholder name `Bovine` is hinting at the common abbreviation of the
/// copy-on-write optimization.)
@frozen
public struct Bovine<Storage: ~Copyable> {
@usableFromInline
internal var _box: _Box
@inlinable
public init(_ storage: consuming Storage) {
self._box = _Box(storage)
}
}
extension Bovine: @unchecked Sendable where Storage: Sendable & ~Copyable {}
#if true // FIXME: Silent error on class definition nested in noncopyable struct
@usableFromInline
internal final class _BovineBox<Storage: ~Copyable> {
@exclusivity(unchecked)
@usableFromInline
internal var storage: Storage
@inlinable
internal init(_ storage: consuming Storage) {
self.storage = storage
}
}
extension Bovine where Storage: ~Copyable {
@usableFromInline
internal typealias _Box = _BovineBox<Storage>
}
#else
extension Bovine where Storage: ~Copyable {
@usableFromInline
internal final class _Box {
@exclusivity(unchecked)
@usableFromInline
internal var storage: Storage
@inlinable
internal init(_ storage: consuming Storage) {
self.storage = storage
}
}
}
#endif
extension Bovine where Storage: ~Copyable {
@inlinable
@inline(__always)
public mutating func isUnique() -> Bool {
isKnownUniquelyReferenced(&_box)
}
@inlinable
public mutating func ensureUnique(
cloner: (borrowing Storage) -> Storage
) {
if isUnique() { return }
_box = _Box(cloner(_box.storage))
}
}
extension Bovine where Storage: ~Copyable {
@inlinable
@inline(__always)
public var value: Storage {
_read {
yield _box.storage
}
_modify {
precondition(isUnique())
yield &_box.storage
}
}
@inlinable
@inline(__always)
public func read<E: Error, R: ~Copyable>(
_ body: (borrowing Storage) throws(E) -> R
) throws(E) -> R {
try body(_box.storage)
}
@inlinable
@inline(__always)
public mutating func update<E: Error, R: ~Copyable>(
_ body: (inout Storage) throws(E) -> R
) throws(E) -> R {
precondition(isUnique())
return try body(&_box.storage)
}
}
extension Bovine where Storage: ~Copyable {
@inlinable
public func isIdentical(to other: Self) -> Bool {
if #available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) {
return self._box === other._box
} else {
let a = Builtin.bridgeToRawPointer(self._box)
let b = Builtin.bridgeToRawPointer(other._box)
return Bool(Builtin.cmp_eq_RawPointer(a, b))
}
}
}
+4 -4
View File
@@ -13,11 +13,11 @@
@frozen
public struct NewArray<Element> {
@usableFromInline
internal var _storage: Bovine<RigidArray<Element>>
internal var _storage: Shared<RigidArray<Element>>
@inlinable
public init(minimumCapacity: Int) {
self._storage = Bovine(RigidArray(capacity: minimumCapacity))
self._storage = Shared(RigidArray(capacity: minimumCapacity))
}
}
@@ -34,9 +34,9 @@ extension NewArray {
internal mutating func _ensureUnique(minimumCapacity: Int) {
if !_storage.isUnique() {
let c = Swift.max(count, minimumCapacity)
_storage = Bovine(_storage.read { $0._copy(capacity: c) })
_storage = Shared(_storage.read { $0._copy(capacity: c) })
} else if minimumCapacity > self.capacity {
_storage = Bovine(_storage.update { $0._move(capacity: minimumCapacity) })
_storage = Shared(_storage.update { $0._move(capacity: minimumCapacity) })
}
}
+186
View File
@@ -0,0 +1,186 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import Builtin // For Shared.isIdentical
/// A utility adapter that wraps a noncopyable storage type in a copy-on-write
/// struct, enabling efficient implementation of value semantics. The type
/// allows safe borrowing and mutating access to its storage, with minimal fuss.
///
/// Like `ManagedBufferPointer`, this type is intended to be used within the
/// internal implementation of public types. Instances of it aren't designed
/// to be exposed as public.
@frozen
public struct Shared<Storage: ~Copyable> {
@usableFromInline
internal var _box: _Box
@inlinable
public init(_ storage: consuming Storage) {
self._box = _Box(storage)
}
}
extension Shared: @unchecked Sendable where Storage: Sendable & ~Copyable {}
#if true // FIXME: Silent error on class definition nested in noncopyable struct
@usableFromInline
internal final class _SharedBox<Storage: ~Copyable> {
@exclusivity(unchecked)
@usableFromInline
internal var storage: Storage
@inlinable
internal init(_ storage: consuming Storage) {
self.storage = storage
}
}
extension Shared where Storage: ~Copyable {
@usableFromInline
internal typealias _Box = _SharedBox<Storage>
}
#else
extension Shared where Storage: ~Copyable {
@usableFromInline
internal final class _Box {
@exclusivity(unchecked)
@usableFromInline
internal var storage: Storage
@inlinable
internal init(_ storage: consuming Storage) {
self.storage = storage
}
}
}
#endif
extension Shared where Storage: ~Copyable {
@inlinable
@inline(__always)
public mutating func isUnique() -> Bool {
isKnownUniquelyReferenced(&_box)
}
@inlinable
public mutating func ensureUnique(
cloner: (borrowing Storage) -> Storage
) {
if isUnique() { return }
_box = _Box(cloner(_box.storage))
}
}
import struct SwiftShims.HeapObject
extension Shared where Storage: ~Copyable {
// FIXME: Can we avoid hacks like this? If not, perhaps `_Box.storage` should be tail-allocated.
@inlinable
internal var _address: UnsafePointer<Storage> {
// Adapted from _getUnsafePointerToStoredProperties
let p = (
UnsafeRawPointer(Builtin.bridgeToRawPointer(_box))
+ MemoryLayout<HeapObject>.size)
return p.alignedUp(for: Storage.self).assumingMemoryBound(to: Storage.self)
}
@inlinable
internal var _mutableAddress: UnsafeMutablePointer<Storage> {
// Adapted from _getUnsafePointerToStoredProperties
let p = (
UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_box))
+ MemoryLayout<HeapObject>.size)
return p.alignedUp(for: Storage.self).assumingMemoryBound(to: Storage.self)
}
}
extension Shared where Storage: ~Copyable {
@inlinable
@inline(__always)
public var value: /*FIXME: dependsOn(self)*/ Storage {
// FIXME: This implements the wrong shape.
// FIXME: Semantically it yields a borrow scoped to an access of this `value` variable,
// FIXME: not the much wider borrow of `self`, which we'd actually want.
_read {
yield _box.storage
}
_modify {
precondition(isUnique())
yield &_box.storage
}
}
// FIXME: This builds, but attempts to use it don't: they fail with an unexpected exclusivity violation.
@inlinable
public subscript() -> dependsOn(self) Storage {
//@_transparent
unsafeAddress {
_address
}
//@_transparent
unsafeMutableAddress {
precondition(isUnique())
return _mutableAddress
}
}
@inlinable
@inline(__always)
public func read<E: Error, R: ~Copyable>(
_ body: (borrowing Storage) throws(E) -> R
) throws(E) -> R {
// FIXME: This also implements the wrong shape.
// FIXME: The borrow of `Storage` isn't tied to `self` at all, and
// FIXME: it obviously cannot legally escape the `read` call.
try body(_box.storage)
}
@inlinable
@inline(__always)
public mutating func update<E: Error, R: ~Copyable>(
_ body: (inout Storage) throws(E) -> R
) throws(E) -> R {
precondition(isUnique())
return try body(&_box.storage)
}
}
#if false // FIXME: Use it or lose it
extension Shared where Storage: ~Copyable {
// This is the actual shape we want. There is currently no way to express it.
@inlinable
public borrowing func read() -> dependsOn(self) Borrow<Storage> {
// This is gloriously (and very explicitly) unsafe, as it should be.
// `Shared` is carefully constructed to guarantee that
// lifetime(self) == lifetime(_box.storage); but we have not
// (cannot) explain this to the compiler.
Borrow(unsafeAddress: _address, owner: self)
}
}
#endif
extension Shared where Storage: ~Copyable {
@inlinable
public func isIdentical(to other: Self) -> Bool {
if #available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *) {
return self._box === other._box
} else {
// To call the standard `===`, we need to do `_SharedBox` -> AnyObject conversions
// that are only supported in the Swift 6+ runtime.
let a = Builtin.bridgeToRawPointer(self._box)
let b = Builtin.bridgeToRawPointer(other._box)
return Bool(Builtin.cmp_eq_RawPointer(a, b))
}
}
}
+3 -1
View File
@@ -13,8 +13,10 @@
import Builtin
@_unsafeNonescapableResult
@inlinable @inline(__always)
public func unsafelyOverrideLifetime<
T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable
T: ~Copyable & ~Escapable,
U: ~Copyable & ~Escapable
>(
of dependent: consuming T,
to source: borrowing U
+4 -4
View File
@@ -9,7 +9,7 @@
/* Begin PBXBuildFile section */
7D380E052C6ABF6800AD8F58 /* NewArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D380E042C6ABF6000AD8F58 /* NewArray.swift */; };
7D380E072C6BFB9B00AD8F58 /* LifetimeOverride.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D380E062C6BFB9500AD8F58 /* LifetimeOverride.swift */; };
7D380E0D2C6D565300AD8F58 /* Bovine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D380E0C2C6D565000AD8F58 /* Bovine.swift */; };
7D380E0D2C6D565300AD8F58 /* Shared.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D380E0C2C6D565000AD8F58 /* Shared.swift */; };
7D9B859729E4F74400B291CD /* BitArray+Shifts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859129E4F74400B291CD /* BitArray+Shifts.swift */; };
7D9B859829E4F74400B291CD /* BitArray+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859229E4F74400B291CD /* BitArray+Descriptions.swift */; };
7D9B859929E4F74400B291CD /* BitArray+LosslessStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859329E4F74400B291CD /* BitArray+LosslessStringConvertible.swift */; };
@@ -442,7 +442,7 @@
/* Begin PBXFileReference section */
7D380E042C6ABF6000AD8F58 /* NewArray.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NewArray.swift; sourceTree = "<group>"; };
7D380E062C6BFB9500AD8F58 /* LifetimeOverride.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LifetimeOverride.swift; sourceTree = "<group>"; };
7D380E0C2C6D565000AD8F58 /* Bovine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Bovine.swift; sourceTree = "<group>"; };
7D380E0C2C6D565000AD8F58 /* Shared.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Shared.swift; sourceTree = "<group>"; };
7D5A64D229CCE8CC00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = "<group>"; };
7D5A64D329CCEE9A00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = "<group>"; };
7D5A64D429CCEF1500CB2595 /* generate-sources.sh */ = {isa = PBXFileReference; lastKnownFileType = text.script.sh; path = "generate-sources.sh"; sourceTree = "<group>"; };
@@ -1803,7 +1803,7 @@
isa = PBXGroup;
children = (
7DEBEC182C5AE43C00A1BF15 /* Container.swift */,
7D380E0C2C6D565000AD8F58 /* Bovine.swift */,
7D380E0C2C6D565000AD8F58 /* Shared.swift */,
7DEBEC192C5AE43C00A1BF15 /* DynamicArray.swift */,
7DEBEC1A2C5AE43C00A1BF15 /* RigidArray.swift */,
7D380E042C6ABF6000AD8F58 /* NewArray.swift */,
@@ -2171,7 +2171,7 @@
7DE9207A29CA70F4004483EB /* BigString+UTF8View.swift in Sources */,
7DE9201329CA70F3004483EB /* OrderedDictionary+CustomReflectable.swift in Sources */,
7DE9201C29CA70F3004483EB /* OrderedDictionary+Partial MutableCollection.swift in Sources */,
7D380E0D2C6D565300AD8F58 /* Bovine.swift in Sources */,
7D380E0D2C6D565300AD8F58 /* Shared.swift in Sources */,
7DE9202729CA70F3004483EB /* OrderedSet+Insertions.swift in Sources */,
7DE9205B29CA70F3004483EB /* Deque+ExpressibleByArrayLiteral.swift in Sources */,
7DE9208729CA70F4004483EB /* BigString+Sequence.swift in Sources */,