Merge pull request #424 from glessard/just-span

recent work on Span and related types
This commit is contained in:
Guillaume Lessard authored and GitHub committed 2024-10-06 11:30:33 -07:00
commit df517649e5
24 files changed
+3549 -731

No files matched your search

+4 -7
View File
@@ -53,20 +53,17 @@ var defines: [String] = [
]
let _sharedSettings: [SwiftSetting] = defines.map { .define($0) } + [
.enableExperimentalFeature("AllowUnsafeAttribute"),
.enableExperimentalFeature("BuiltinModule"),
.enableExperimentalFeature("NonescapableTypes"),
.enableExperimentalFeature("BitwiseCopyable"),
.enableExperimentalFeature("RawLayout"),
.enableExperimentalFeature("SuppressedAssociatedTypes"),
]
let _settings: [SwiftSetting] = _sharedSettings + [
.swiftLanguageVersion(.v6),
]
let _testSettings: [SwiftSetting] = _sharedSettings + [
.swiftLanguageVersion(.v5),
]
let _settings: [SwiftSetting] = _sharedSettings + []
let _testSettings: [SwiftSetting] = _sharedSettings + []
struct CustomTarget {
enum Kind {
@@ -13,6 +13,8 @@
import InternalCollectionsUtilities
#endif
import Future
extension Deque {
// Implementation note: we could also use the default `IndexingIterator` here.
// This custom implementation performs direct storage access to eliminate any
@@ -9,6 +9,8 @@
//
//===----------------------------------------------------------------------===//
import Future
extension Deque: Equatable where Element: Equatable {
/// Returns a Boolean value indicating whether two values are equal. Two
/// deques are considered equal if they contain the same elements in the same
+2
View File
@@ -9,6 +9,8 @@
//
//===----------------------------------------------------------------------===//
import Future
/// A collection implementing a double-ended queue. `Deque` (pronounced "deck")
/// implements an ordered random-access collection that supports efficient
/// insertions and removals from both ends.
+3 -3
View File
@@ -95,16 +95,16 @@ public struct _DequeBorrowingIterator<Element: ~Copyable>: BorrowingIteratorProt
let d = Swift.min(maximumCount, _segments.first.count - _offset)
let slice = _segments.first.extracting(_offset ..< _offset + d)
_offset += d
return Span(unsafeElements: slice, owner: self)
return Span(_unsafeElements: slice)
}
guard let second = _segments.second else {
return Span(unsafeElements: UnsafeBufferPointer._empty, owner: self)
return Span(_unsafeElements: UnsafeBufferPointer._empty)
}
let o = _offset - _segments.first.count
let d = Swift.min(maximumCount, second.count - o)
let slice = second.extracting(o ..< o + d)
_offset += d
return Span(unsafeElements: slice, owner: self)
return Span(_unsafeElements: slice)
}
}
+4
View File
@@ -12,9 +12,13 @@ add_library(Future
"Cell.swift"
"ContiguousStorage.swift"
"Inout.swift"
"OutputSpan.swift"
"LifetimeOverride.swift"
"RawSpan.swift"
"Span.swift"
"Span+Iterator.swift"
"StdlibOutputSpanExtensions.swift"
"StdlibSpanExtensions.swift"
"Containers/Shared.swift"
"Containers/Container.swift"
"Containers/DynamicArray.swift"
+2 -2
View File
@@ -27,7 +27,7 @@ extension NewArray {
// FIXME: This is what I want to write; alas, lifetimes are messed up.
return _storage.value.storage
#else
return Span(unsafeElements: _storage.value._items, owner: self)
return Span(_unsafeElements: _storage.value._items)
#endif
}
}
@@ -108,7 +108,7 @@ extension NewArray: RangeReplaceableCollection {
self._storage = Shared(RigidArray(capacity: 0))
}
public func replaceSubrange(
mutating public func replaceSubrange(
_ subrange: Range<Int>,
with newElements: some Collection<Element>
) {
+6 -4
View File
@@ -60,7 +60,7 @@ extension RigidArray where Element: ~Copyable {
extension RigidArray where Element: ~Copyable {
public var storage: Span<Element> {
Span(unsafeElements: _items, owner: self)
Span(_unsafeElements: _items)
}
}
@@ -84,7 +84,7 @@ extension RigidArray: RandomAccessContainer where Element: ~Copyable {
let end = _offset + Swift.min(maximumCount, _items.count - _offset)
defer { _offset = end }
let chunk = _items.extracting(Range(uncheckedBounds: (_offset, end)))
return Span(unsafeElements: chunk, owner: self)
return Span(_unsafeElements: chunk)
}
}
@@ -242,7 +242,8 @@ extension RigidArray {
internal func _copy(capacity: Int) -> Self {
precondition(capacity >= count)
var result = RigidArray<Element>(capacity: capacity)
result._storage.initializeAll(fromContentsOf: _storage)
let initialized = result._storage.initialize(fromContentsOf: _storage)
precondition(initialized == count)
result._count = count
return result
}
@@ -251,7 +252,8 @@ extension RigidArray {
internal mutating func _move(capacity: Int) -> Self {
precondition(capacity >= count)
var result = RigidArray<Element>(capacity: capacity)
result._storage.moveInitializeAll(fromContentsOf: _storage)
let initialized = result._storage.moveInitialize(fromContentsOf: _storage)
precondition(initialized == count)
result._count = count
self._count = 0
return result
+9 -9
View File
@@ -24,13 +24,13 @@ extension Array: ContiguousStorage {
public var storage: Span<Element> {
_read {
if let a = _baseAddressIfContiguous {
yield Span(unsafeStart: a, count: count, owner: self)
yield Span(_unsafeStart: a, count: count)
}
else {
let a = ContiguousArray(copy self)
#if true
let s = Span(
unsafeStart: a._baseAddressIfContiguous!, count: a.count, owner: a
_unsafeStart: a._baseAddressIfContiguous!, count: a.count
)
#else
let s = a.storage
@@ -45,7 +45,7 @@ extension ContiguousArray: ContiguousStorage {
public var storage: Span<Element> {
borrowing get {
Span(
unsafeStart: _baseAddressIfContiguous!, count: count, owner: self
_unsafeStart: _baseAddressIfContiguous!, count: count
)
}
}
@@ -57,13 +57,13 @@ extension CollectionOfOne: ContiguousStorage {
/* ideally: (with strawman syntax)
@addressable let value = self._element
yield Span(
unsafePointer: Builtin.addressable(value), count: 1, owner: self
)
unsafePointer: Builtin.addressable(value), count: 1
)
*/
let a = ContiguousArray(self)
yield Span(
unsafeStart: a._baseAddressIfContiguous!, count: 1, owner: a
_unsafeStart: a._baseAddressIfContiguous!, count: 1
)
}
}
@@ -85,18 +85,18 @@ extension String.UTF8View: ContiguousStorage {
let a = ContiguousArray(self)
// yield a.storage
yield Span(
unsafeStart: a._baseAddressIfContiguous!, count: 1, owner: a
_unsafeStart: a._baseAddressIfContiguous!, count: 1
)
}
else if let buffer = withContiguousStorageIfAvailable({ $0 }) {
// this is totally wrong, but there is a way with stdlib-internal API
yield Span(unsafeElements: buffer, owner: self)
yield Span(_unsafeElements: buffer)
}
else { // copy non-fast code units if we don't have eager bridging
let a = ContiguousArray(self)
// yield a.storage
yield Span(
unsafeStart: a._baseAddressIfContiguous!, count: 1, owner: a
_unsafeStart: a._baseAddressIfContiguous!, count: 1
)
}
}
+735
View File
@@ -0,0 +1,735 @@
//===--- MutableSpan.swift ------------------------------------------------===//
//
// This source file is part of the Swift.org 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Builtin
// A MutableSpan<Element> represents a span of memory which
// contains initialized `Element` instances.
@_disallowFeatureSuppression(NonescapableTypes)
@frozen
public struct MutableSpan<Element: ~Copyable>: ~Copyable & ~Escapable {
@usableFromInline let _pointer: UnsafeMutableRawPointer?
@usableFromInline let _count: Int
@usableFromInline @inline(__always)
var _start: UnsafeMutableRawPointer { _pointer.unsafelyUnwrapped }
@_disallowFeatureSuppression(NonescapableTypes)
@usableFromInline @inline(__always)
init(
_unchecked start: UnsafeMutableRawPointer?,
count: Int
) -> dependsOn(immortal) Self {
_pointer = start
_count = count
}
}
@_disallowFeatureSuppression(NonescapableTypes)
@available(*, unavailable)
extension MutableSpan: Sendable {}
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: ~Copyable {
@_disallowFeatureSuppression(NonescapableTypes)
@usableFromInline @inline(__always)
internal init(
_unchecked elements: UnsafeMutableBufferPointer<Element>
) -> dependsOn(immortal) Self {
_pointer = .init(elements.baseAddress)
_count = elements.count
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_unsafeElements buffer: UnsafeMutableBufferPointer<Element>
) -> dependsOn(immortal) Self {
precondition(
((Int(bitPattern: buffer.baseAddress) &
(MemoryLayout<Element>.alignment&-1)) == 0),
"baseAddress must be properly aligned to access Element"
)
self.init(_unchecked: buffer)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_unsafeStart start: UnsafeMutablePointer<Element>,
count: Int
) -> dependsOn(immortal) Self {
precondition(count >= 0, "Count must not be negative")
self.init(_unsafeElements: .init(start: start, count: count))
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_unsafeElements elements: Slice<UnsafeMutableBufferPointer<Element>>
) -> dependsOn(immortal) Self {
self.init(_unsafeElements: UnsafeMutableBufferPointer(rebasing: elements))
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: BitwiseCopyable {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_unsafeBytes buffer: UnsafeMutableRawBufferPointer
) -> dependsOn(immortal) Self {
precondition(
((Int(bitPattern: buffer.baseAddress) &
(MemoryLayout<Element>.alignment&-1)) == 0),
"baseAddress must be properly aligned to access Element"
)
let (byteCount, stride) = (buffer.count, MemoryLayout<Element>.stride)
let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride)
precondition(remainder == 0, "Span must contain a whole number of elements")
self.init(_unchecked: buffer.baseAddress, count: count)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_unsafeStart pointer: UnsafeMutableRawPointer,
byteCount: Int
) -> dependsOn(immortal) Self {
precondition(byteCount >= 0, "Count must not be negative")
self.init(_unsafeBytes: .init(start: pointer, count: byteCount))
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_unsafeBytes buffer: Slice<UnsafeMutableRawBufferPointer>
) -> dependsOn(immortal) Self {
self.init(_unsafeBytes: UnsafeMutableRawBufferPointer(rebasing: buffer))
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: ~Copyable {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(_unsafeMutableSpan mutableSpan: borrowing MutableSpan<Element>) {
self.init(_unchecked: mutableSpan._start, count: mutableSpan.count)
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: ~Copyable {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public var storage: Span<Element> { Span(_unsafeMutableSpan: self) }
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func withSpan<E: Error, Result: ~Copyable>(
_ body: (Span<Element>) throws(E) -> Result
) throws(E) -> Result {
try body(Span(_unsafeMutableSpan: self))
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension RawSpan {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init<Element: BitwiseCopyable>(
_unsafeMutableSpan mutableSpan: borrowing MutableSpan<Element>
) {
self.init(
_unchecked: mutableSpan._start,
byteCount: mutableSpan.count &* MemoryLayout<Element>.stride
)
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: Equatable {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func _elementsEqual(_ other: borrowing Self) -> Bool {
_elementsEqual(Span(_unsafeMutableSpan: other))
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func _elementsEqual(_ other: Span<Element>) -> Bool {
Span(_unsafeMutableSpan: self)._elementsEqual(other)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func _elementsEqual(_ other: some Collection<Element>) -> Bool {
Span(_unsafeMutableSpan: self)._elementsEqual(other)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func _elementsEqual(_ other: some Sequence<Element>) -> Bool {
Span(_unsafeMutableSpan: self)._elementsEqual(other)
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: ~Copyable {
@_alwaysEmitIntoClient
public var description: String {
let addr = String(UInt(bitPattern: _pointer), radix: 16, uppercase: false)
return "(0x\(addr), \(_count))"
}
}
//MARK: Collection, RandomAccessCollection
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: ~Copyable {
@_alwaysEmitIntoClient
public var count: Int { _count }
@_alwaysEmitIntoClient
public var isEmpty: Bool { _count == 0 }
@_alwaysEmitIntoClient
public var _indices: Range<Int> {
Range(uncheckedBounds: (0, _count))
}
}
//MARK: Bounds Checking
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: ~Copyable {
/// Return true if `index` is a valid offset into this `Span`
///
/// - Parameters:
/// - index: an index to validate
/// - Returns: true if `index` is valid
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func boundsContain(_ index: Int) -> Bool {
0 <= index && index < _count
}
/// Return true if `indices` is a valid range of indices into this `Span`
///
/// - Parameters:
/// - indices: a range of indices to validate
/// - Returns: true if `indices` is a valid range of indices
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func boundsContain(_ indices: Range<Int>) -> Bool {
boundsContain(indices.lowerBound) && indices.upperBound <= _count
}
/// Return true if `indices` is a valid range of indices into this `Span`
///
/// - Parameters:
/// - indices: a range of indices to validate
/// - Returns: true if `indices` is a valid range of indices
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func boundsContain(_ indices: ClosedRange<Int>) -> Bool {
boundsContain(indices.lowerBound) && indices.upperBound < _count
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: BitwiseCopyable {
/// Construct a RawSpan over the memory represented by this span
///
/// - Returns: a RawSpan over the memory represented by this span
@_disallowFeatureSuppression(NonescapableTypes)
@unsafe //FIXME: remove when the lifetime inference is fixed
@_alwaysEmitIntoClient
public var _unsafeRawSpan: RawSpan { RawSpan(_unsafeMutableSpan: self) }
}
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: ~Copyable {
/// Accesses the element at the specified position in the `Span`.
///
/// - Parameter position: The offset of the element to access. `position`
/// must be greater or equal to zero, and less than `count`.
///
/// - Complexity: O(1)
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public subscript(_ position: Int) -> Element {
_read {
precondition(boundsContain(position), "index out of bounds")
yield self[unchecked: position]
}
_modify {
precondition(boundsContain(position), "index out of bounds")
yield &self[unchecked: position]
}
}
/// Accesses the element at the specified position in the `Span`.
///
/// This subscript does not validate `position`; this is an unsafe operation.
///
/// - Parameter position: The offset of the element to access. `position`
/// must be greater or equal to zero, and less than `count`.
///
/// - Complexity: O(1)
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public subscript(unchecked position: Int) -> Element {
_read {
let offset = position&*MemoryLayout<Element>.stride
let p = UnsafeRawPointer(_start).advanced(by: offset)._rawValue
let binding = Builtin.bindMemory(p, count._builtinWordValue, Element.self)
defer { Builtin.rebindMemory(p, binding) }
yield UnsafePointer(p).pointee
}
_modify {
let offset = position&*MemoryLayout<Element>.stride
let p = UnsafeMutableRawPointer(_start).advanced(by: offset)._rawValue
let binding = Builtin.bindMemory(p, 1._builtinWordValue, Element.self)
defer { Builtin.rebindMemory(p, binding) }
yield &(UnsafeMutablePointer(p).pointee)
}
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: BitwiseCopyable {
/// Accesses the element at the specified position in the `Span`.
///
/// - Parameter position: The offset of the element to access. `position`
/// must be greater or equal to zero, and less than `count`.
///
/// - Complexity: O(1)
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public subscript(_ position: Int) -> Element {
get {
precondition(boundsContain(position))
return self[unchecked: position]
}
set {
precondition(boundsContain(position))
self[unchecked: position] = newValue
}
}
/// Accesses the element at the specified position in the `Span`.
///
/// This subscript does not validate `position`; this is an unsafe operation.
///
/// - Parameter position: The offset of the element to access. `position`
/// must be greater or equal to zero, and less than `count`.
///
/// - Complexity: O(1)
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public subscript(unchecked position: Int) -> Element {
get {
let offset = position&*MemoryLayout<Element>.stride
return _start.loadUnaligned(fromByteOffset: offset, as: Element.self)
}
set {
let offset = position&*MemoryLayout<Element>.stride
_start.storeBytes(of: newValue, toByteOffset: offset, as: Element.self)
}
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: ~Copyable {
//FIXME: mark closure parameter as non-escaping
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func withUnsafeBufferPointer<E: Error, Result: ~Copyable>(
_ body: (_ buffer: UnsafeBufferPointer<Element>) throws(E) -> Result
) throws(E) -> Result {
try Span(_unsafeMutableSpan: self).withUnsafeBufferPointer(body)
}
//FIXME: mark closure parameter as non-escaping
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func withUnsafeMutableBufferPointer<E: Error, Result: ~Copyable>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws(E) -> Result
) throws(E) -> Result {
func executeBody(
_ start: UnsafeMutablePointer<Element>?, _ count: Int
) throws(E) -> Result {
var buf = UnsafeMutableBufferPointer<Element>(start: start, count: count)
defer {
precondition(
(buf.baseAddress, buf.count) == (start, count),
"MutableSpan.withUnsafeMutableBufferPointer: replacing the buffer is not allowed"
)
}
return try body(&buf)
}
guard let pointer = _pointer, count > 0 else {
return try executeBody(nil, 0)
}
return try pointer.withMemoryRebound(to: Element.self, capacity: count) {
pointer throws(E) -> Result in
return try executeBody(pointer, count)
}
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: BitwiseCopyable {
//FIXME: mark closure parameter as non-escaping
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func withUnsafeBytes<E: Error, Result: ~Copyable>(
_ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result
) throws(E) -> Result {
try RawSpan(_unsafeMutableSpan: self).withUnsafeBytes(body)
}
//FIXME: mark closure parameter as non-escaping
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func withUnsafeMutableBytes<E: Error, Result: ~Copyable>(
_ body: (_ buffer: UnsafeMutableRawBufferPointer) throws(E) -> Result
) throws(E) -> Result {
let bytes = UnsafeMutableRawBufferPointer(
start: (_count == 0) ? nil : _start,
count: _count &* MemoryLayout<Element>.stride
)
return try body(bytes)
}
}
//MARK: bulk-update functions
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan {
@_alwaysEmitIntoClient
public mutating func update(repeating repeatedValue: Element) {
_start.withMemoryRebound(to: Element.self, capacity: count) {
$0.update(repeating: repeatedValue, count: count)
}
}
@_alwaysEmitIntoClient
public mutating func update<S: Sequence>(
from source: S
) -> (unwritten: S.Iterator, index: Int) where S.Element == Element {
var iterator = source.makeIterator()
let index = update(from: &iterator)
return (iterator, index)
}
@_alwaysEmitIntoClient
public mutating func update(
from elements: inout some IteratorProtocol<Element>
) -> Int {
var index = 0
while index < _count {
guard let element = elements.next() else { break }
self[unchecked: index] = element
index &+= 1
}
return index
}
@_alwaysEmitIntoClient
public mutating func update(
fromContentsOf source: some Collection<Element>
) -> Int {
let updated = source.withContiguousStorageIfAvailable {
self.update(fromContentsOf: Span(_unsafeElements: $0))
}
if let updated {
return 0.advanced(by: updated)
}
if self.isEmpty {
precondition(
source.isEmpty,
"destination buffer view cannot contain every element from source."
)
return 0
}
var iterator = source.makeIterator()
var index = 0
while let value = iterator.next() {
precondition(
index < _count,
"destination buffer view cannot contain every element from source."
)
self[unchecked: index] = value
index &+= 1
}
return index
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func update(fromContentsOf source: Span<Element>) -> Int {
guard !source.isEmpty else { return 0 }
precondition(
source.count <= self.count,
"destination span cannot contain every element from source."
)
_start.withMemoryRebound(to: Element.self, capacity: source.count) { dest in
source._start.withMemoryRebound(to: Element.self, capacity: source.count) {
dest.update(from: $0, count: source.count)
}
}
return source.count
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func update(
fromContentsOf source: borrowing MutableSpan<Element>
) -> Int {
source.withSpan { self.update(fromContentsOf: $0) }
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: ~Copyable {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func moveUpdate(
fromContentsOf source: consuming OutputSpan<Element>
) -> Int {
guard !source.isEmpty else { return 0 }
precondition(
source.count <= self.count,
"destination span cannot contain every element from source."
)
let buffer = source.relinquishBorrowedMemory()
// we must now deinitialize the returned UMBP
_start.moveInitializeMemory(
as: Element.self, from: buffer.baseAddress!, count: buffer.count
)
return buffer.count
}
public mutating func moveUpdate(
fromContentsOf source: UnsafeMutableBufferPointer<Element>
) -> Int {
#if false
guard let sourceAddress = source.baseAddress, source.count > 0 else {
return 0
}
precondition(
source.count <= self.count,
"destination span cannot contain every element from source."
)
_start.withMemoryRebound(to: Element.self, capacity: source.count) {
$0.moveUpdate(from: sourceAddress, count: source.count)
}
return source.count
#else
let source = OutputSpan(_initializing: source, initialized: source.count)
return self.moveUpdate(fromContentsOf: source)
#endif
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan {
public mutating func moveUpdate(
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
) -> Int {
self.moveUpdate(fromContentsOf: .init(rebasing: source))
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: BitwiseCopyable {
@_alwaysEmitIntoClient
public mutating func update(
repeating repeatedValue: Element
) where Element: BitwiseCopyable {
guard count > 0 else { return }
// rebind _start manually in order to avoid assumptions about alignment.
let rp = _start._rawValue
let binding = Builtin.bindMemory(rp, count._builtinWordValue, Element.self)
UnsafeMutablePointer(rp).update(repeating: repeatedValue, count: count)
Builtin.rebindMemory(rp, binding)
}
@_alwaysEmitIntoClient
public mutating func update<S: Sequence>(
from source: S
) -> (unwritten: S.Iterator, index: Int)
where S.Element == Element, Element: BitwiseCopyable {
var iterator = source.makeIterator()
let index = update(from: &iterator)
return (iterator, index)
}
@_alwaysEmitIntoClient
public mutating func update(
from elements: inout some IteratorProtocol<Element>
) -> Int {
var index = 0
while index < _count {
guard let element = elements.next() else { break }
self[unchecked: index] = element
index &+= 1
}
return index
}
@_alwaysEmitIntoClient
public mutating func update(
fromContentsOf source: some Collection<Element>
) -> Int where Element: BitwiseCopyable {
let updated = source.withContiguousStorageIfAvailable {
self.update(fromContentsOf: Span(_unsafeElements: $0))
}
if let updated {
return 0.advanced(by: updated)
}
if self.isEmpty {
precondition(
source.isEmpty,
"destination buffer view cannot contain every element from source."
)
return 0
}
var iterator = source.makeIterator()
var index = 0
while let value = iterator.next() {
guard index < _count else {
fatalError(
"destination buffer view cannot contain every element from source."
)
}
self[unchecked: index] = value
index &+= 1
}
return index
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func update(
fromContentsOf source: Span<Element>
) -> Int where Element: BitwiseCopyable {
guard !source.isEmpty else { return 0 }
precondition(
source.count <= self.count,
"destination span cannot contain every element from source."
)
_start.copyMemory(
from: source._start, byteCount: source.count&*MemoryLayout<Element>.stride
)
return source.count
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func update(
fromContentsOf source: borrowing MutableSpan<Element>
) -> Int where Element: BitwiseCopyable {
self.update(fromContentsOf: source.storage)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
@unsafe
public mutating func update(
fromContentsOf source: RawSpan
) -> Int where Element: BitwiseCopyable {
self.update(fromContentsOf: source.unsafeView(as: Element.self))
}
// We have to define the overloads for raw buffers and their slices,
// otherwise they would try to use their `Collection` conformance
// and fail due to the mismatch in `Element` type.
@_alwaysEmitIntoClient
public mutating func update(
fromContentsOf source: UnsafeRawBufferPointer
) -> Int where Element: BitwiseCopyable {
self.update(fromContentsOf: RawSpan(_unsafeBytes: source))
}
@_alwaysEmitIntoClient
public mutating func update(
fromContentsOf source: UnsafeMutableRawBufferPointer
) -> Int where Element: BitwiseCopyable {
self.update(fromContentsOf: RawSpan(_unsafeBytes: source))
}
@_alwaysEmitIntoClient
public mutating func update(
fromContentsOf source: Slice<UnsafeRawBufferPointer>
) -> Int where Element: BitwiseCopyable {
self.update(fromContentsOf: RawSpan(_unsafeBytes: source))
}
@_alwaysEmitIntoClient
public mutating func update(
fromContentsOf source: Slice<UnsafeMutableRawBufferPointer>
) -> Int where Element: BitwiseCopyable {
self.update(fromContentsOf: RawSpan(_unsafeBytes: source))
}
}
//MARK: copyMemory
//FIXME: move these to a MutableRawSpan
@_disallowFeatureSuppression(NonescapableTypes)
extension MutableSpan where Element: BitwiseCopyable {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func copyMemory(
from source: borrowing MutableSpan<Element>
) -> Int where Element: BitwiseCopyable {
self.update(fromContentsOf: source.storage)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func copyMemory(
from source: Span<Element>
) -> Int where Element: BitwiseCopyable {
self.update(fromContentsOf: source)
}
}
+425
View File
@@ -0,0 +1,425 @@
//===--- OutputSpan.swift -------------------------------------------------===//
//
// This source file is part of the Swift.org 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// OutputSpan<Element> represents a span of memory which contains
// a variable number of `Element` instances, followed by uninitialized memory.
@_disallowFeatureSuppression(NonescapableTypes)
@frozen
public struct OutputSpan<Element: ~Copyable>: ~Copyable, ~Escapable {
@usableFromInline let _pointer: UnsafeMutableRawPointer?
public let capacity: Int
@usableFromInline
var _initialized: Int = 0
@usableFromInline @inline(__always)
var _start: UnsafeMutableRawPointer { _pointer.unsafelyUnwrapped }
@_alwaysEmitIntoClient
public var available: Int { capacity &- _initialized }
@_alwaysEmitIntoClient
public var count: Int { _initialized }
@_alwaysEmitIntoClient
public var isEmpty: Bool { _initialized == 0 }
deinit {
// `self` always borrows memory, and it shouldn't have gotten here.
// Failing to use `relinquishBorrowedMemory()` is an error.
if _initialized > 0 {
#if false
_start.withMemoryRebound(to: Element.self, capacity: _initialized) {
$0.deinitialize(count: _initialized)
}
#else
fatalError()
#endif
}
}
@_disallowFeatureSuppression(NonescapableTypes)
@usableFromInline @inline(__always)
init(
_unchecked start: UnsafeMutableRawPointer?,
capacity: Int,
initialized: Int
) -> dependsOn(immortal) Self {
_pointer = start
self.capacity = capacity
_initialized = initialized
}
}
@_disallowFeatureSuppression(NonescapableTypes)
@available(*, unavailable)
extension OutputSpan: Sendable {}
@_disallowFeatureSuppression(NonescapableTypes)
extension OutputSpan where Element: ~Copyable {
@_disallowFeatureSuppression(NonescapableTypes)
@usableFromInline @inline(__always)
init(
_unchecked buffer: UnsafeMutableBufferPointer<Element>,
initialized: Int
) -> dependsOn(immortal) Self {
_pointer = .init(buffer.baseAddress)
capacity = buffer.count
_initialized = initialized
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_initializing buffer: UnsafeMutableBufferPointer<Element>,
initialized: Int = 0
) -> dependsOn(immortal) Self {
precondition(
((Int(bitPattern: buffer.baseAddress) &
(MemoryLayout<Element>.alignment&-1)) == 0),
"baseAddress must be properly aligned to access Element"
)
self.init(_unchecked: buffer, initialized: initialized)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_initializing pointer: UnsafeMutablePointer<Element>,
capacity: Int,
initialized: Int = 0
) -> dependsOn(immortal) Self {
precondition(capacity >= 0, "Capacity must be 0 or greater")
self.init(
_initializing: .init(start: pointer, count: capacity),
initialized: initialized
)
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension OutputSpan {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_initializing buffer: Slice<UnsafeMutableBufferPointer<Element>>,
initialized: Int = 0
) -> dependsOn(immortal) Self {
self.init(_initializing: .init(rebasing: buffer), initialized: initialized)
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension OutputSpan where Element: BitwiseCopyable {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_initializing bytes: UnsafeMutableRawBufferPointer,
initialized: Int = 0
) -> dependsOn(immortal) Self {
precondition(
((Int(bitPattern: bytes.baseAddress) &
(MemoryLayout<Element>.alignment&-1)) == 0),
"baseAddress must be properly aligned to access Element"
)
let (byteCount, stride) = (bytes.count, MemoryLayout<Element>.stride)
let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride)
precondition(remainder == 0, "Span must contain a whole number of elements")
self.init(
_unchecked: bytes.baseAddress, capacity: count, initialized: initialized
)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_initializing pointer: UnsafeMutableRawPointer,
capacity: Int,
initialized: Int = 0
) -> dependsOn(immortal) Self {
precondition(capacity >= 0, "Capacity must be 0 or greater")
self.init(
_initializing: .init(start: pointer, count: capacity),
initialized: initialized
)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_initializing buffer: Slice<UnsafeMutableRawBufferPointer>,
initialized: Int = 0
) -> dependsOn(immortal) Self {
self.init(
_initializing: UnsafeMutableRawBufferPointer(rebasing: buffer),
initialized: initialized
)
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension OutputSpan where Element: ~Copyable {
@_alwaysEmitIntoClient
public mutating func appendElement(_ value: consuming Element) {
precondition(_initialized < capacity, "Output buffer overflow")
let p = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
p.initializeMemory(as: Element.self, to: value)
_initialized &+= 1
}
@_alwaysEmitIntoClient
public mutating func deinitializeLastElement() -> Element? {
guard _initialized > 0 else { return nil }
_initialized &-= 1
let p = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
return p.withMemoryRebound(to: Element.self, capacity: 1, { $0.move() })
}
@_alwaysEmitIntoClient
public mutating func deinitialize() {
_ = _start.withMemoryRebound(to: Element.self, capacity: _initialized) {
$0.deinitialize(count: _initialized)
}
_initialized = 0
}
}
//MARK: bulk-update functions
@_disallowFeatureSuppression(NonescapableTypes)
extension OutputSpan {
@_alwaysEmitIntoClient
public mutating func append(repeating repeatedValue: Element, count: Int) {
let available = capacity &- _initialized
precondition(
count <= available,
"destination span cannot contain number of elements requested."
)
let offset = _initialized&*MemoryLayout<Element>.stride
let p = _start.advanced(by: offset)
p.withMemoryRebound(to: Element.self, capacity: count) {
$0.initialize(repeating: repeatedValue, count: count)
}
_initialized &+= count
}
@_alwaysEmitIntoClient
public mutating func append<S>(
from elements: S
) -> S.Iterator where S: Sequence, S.Element == Element {
var iterator = elements.makeIterator()
append(from: &iterator)
return iterator
}
@_alwaysEmitIntoClient
public mutating func append(
from elements: inout some IteratorProtocol<Element>
) {
while _initialized < capacity {
guard let element = elements.next() else { break }
let p = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
p.initializeMemory(as: Element.self, to: element)
_initialized &+= 1
}
}
@_alwaysEmitIntoClient
public mutating func append(
fromContentsOf source: some Collection<Element>
) {
let void: Void? = source.withContiguousStorageIfAvailable {
#if false
append(fromContentsOf: Span(_unsafeElements: $0))
#else //FIXME: remove once rdar://136838539 & rdar://136849171 are fixed
append(fromContentsOf: $0)
#endif
}
if void != nil {
return
}
let available = capacity &- _initialized
let tail = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
var (iterator, copied) =
tail.withMemoryRebound(to: Element.self, capacity: available) {
let suffix = UnsafeMutableBufferPointer(start: $0, count: available)
return source._copyContents(initializing: suffix)
}
precondition(
iterator.next() == nil,
"destination span cannot contain every element from source."
)
assert(_initialized + copied <= capacity) // invariant check
_initialized &+= copied
}
//FIXME: remove once rdar://136838539 & rdar://136849171 are fixed
public mutating func append(
fromContentsOf source: UnsafeBufferPointer<Element>
) {
guard !source.isEmpty else { return }
precondition(
source.count <= available,
"destination span cannot contain every element from source."
)
let tail = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
source.baseAddress!.withMemoryRebound(to: Element.self, capacity: source.count) {
_ = tail.initializeMemory(as: Element.self, from: $0, count: source.count)
}
_initialized += source.count
}
//FIXME: rdar://136838539 & rdar://136849171
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func append(
fromContentsOf source: Span<Element>
) {
guard !source.isEmpty else { return }
precondition(
source.count <= available,
"destination span cannot contain every element from source."
)
let tail = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
source._start.withMemoryRebound(to: Element.self, capacity: source.count) {
_ = tail.initializeMemory(as: Element.self, from: $0, count: source.count)
}
_initialized += source.count
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func append(fromContentsOf source: borrowing MutableSpan<Element>) {
source.withUnsafeBufferPointer { append(fromContentsOf: $0) }
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension OutputSpan where Element: ~Copyable {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func moveAppend(
fromContentsOf source: consuming Self
) {
guard !source.isEmpty else { return }
precondition(
source.count <= available,
"buffer cannot contain every element from source."
)
let buffer = source.relinquishBorrowedMemory()
// we must now deinitialize the returned UMBP
let tail = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
tail.moveInitializeMemory(
as: Element.self, from: buffer.baseAddress!, count: buffer.count
)
_initialized &+= buffer.count
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func moveAppend(
fromContentsOf source: UnsafeMutableBufferPointer<Element>
) {
#if false //FIXME: rdar://136838539 & rdar://136849171
let source = OutputSpan(_initializing: source, initialized: source.count)
moveAppend(fromContentsOf: source)
#else
guard !source.isEmpty else { return }
precondition(
source.count <= available,
"buffer cannot contain every element from source."
)
let tail = _start.advanced(by: _initialized&*MemoryLayout<Element>.stride)
tail.moveInitializeMemory(
as: Element.self, from: source.baseAddress!, count: source.count
)
_initialized &+= source.count
#endif
}
}
extension OutputSpan {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func moveAppend(
fromContentsOf source: Slice<UnsafeMutableBufferPointer<Element>>
) {
moveAppend(fromContentsOf: UnsafeMutableBufferPointer(rebasing: source))
}
}
extension OutputSpan where Element: BitwiseCopyable {
}
extension OutputSpan where Element: ~Copyable {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public var initializedPrefix: Span<Element> {
get { Span(_unchecked: _pointer, count: _initialized) }
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func withSpan<E: Error, R: ~Copyable>(
_ body: (Span<Element>) throws(E) -> R
) throws(E) -> R {
try body(initializedPrefix)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func withMutableSpan<E: Error, Result: ~Copyable>(
_ body: (inout MutableSpan<Element>) throws(E) -> Result
) throws(E) -> Result {
var span = MutableSpan<Element>(_unchecked: _pointer, count: _initialized)
defer {
precondition(
span.count == _initialized && span._pointer == _start,
"Substituting the MutableSpan is unsound and unsafe."
)
}
return try body(&span)
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension OutputSpan where Element: ~Copyable {
@_alwaysEmitIntoClient
public consuming func relinquishBorrowedMemory() -> UnsafeMutableBufferPointer<Element> {
let (start, count) = (self._pointer, self._initialized)
discard self
let typed = start?.bindMemory(to: Element.self, capacity: count)
return .init(start: typed, count: count)
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension OutputSpan where Element: BitwiseCopyable {
@_alwaysEmitIntoClient
public consuming func relinquishBorrowedBytes() -> UnsafeMutableRawBufferPointer {
let (start, count) = (self._pointer, self._initialized)
discard self
return .init(start: start, count: count&*MemoryLayout<Element>.stride)
}
}
+200 -236
View File
@@ -10,27 +10,22 @@
//
//===----------------------------------------------------------------------===//
import Builtin
// A RawSpan represents a span of initialized memory
// of unspecified type.
@frozen
public struct RawSpan: Copyable, ~Escapable {
@usableFromInline
internal let _pointer: UnsafeRawPointer?
@usableFromInline let _pointer: UnsafeRawPointer?
@usableFromInline @inline(__always)
internal var _start: UnsafeRawPointer { _pointer.unsafelyUnwrapped }
var _start: UnsafeRawPointer { _pointer.unsafelyUnwrapped }
@usableFromInline
internal let _count: Int
@usableFromInline let _count: Int
@inlinable @inline(__always)
internal init<Owner: ~Copyable & ~Escapable>(
@_alwaysEmitIntoClient
internal init(
_unchecked start: UnsafeRawPointer?,
byteCount: Int,
owner: borrowing Owner
) {
byteCount: Int
) -> dependsOn(immortal) Self {
_pointer = start
_count = byteCount
}
@@ -50,16 +45,22 @@ extension RawSpan {
/// - buffer: an `UnsafeRawBufferPointer` to initialized memory.
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `RawSpan`.
@inlinable @inline(__always)
public init<Owner: ~Copyable & ~Escapable>(
unsafeBytes buffer: UnsafeRawBufferPointer,
owner: borrowing Owner
) {
@_alwaysEmitIntoClient
public init(
_unsafeBytes buffer: UnsafeRawBufferPointer
) -> dependsOn(immortal) Self {
self.init(
_unchecked: buffer.baseAddress, byteCount: buffer.count, owner: owner
_unchecked: buffer.baseAddress, byteCount: buffer.count
)
}
@_alwaysEmitIntoClient
public init(
_unsafeBytes buffer: Slice<UnsafeRawBufferPointer>
) -> dependsOn(immortal) Self {
self.init(_unsafeBytes: UnsafeRawBufferPointer(rebasing: buffer))
}
/// Unsafely create a `RawSpan` over initialized memory.
///
/// The memory in `buffer` must be owned by the instance `owner`,
@@ -70,11 +71,17 @@ extension RawSpan {
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `RawSpan`.
@_alwaysEmitIntoClient
public init<Owner: ~Copyable & ~Escapable>(
unsafeBytes buffer: UnsafeMutableRawBufferPointer,
owner: borrowing Owner
) {
self.init(unsafeBytes: UnsafeRawBufferPointer(buffer), owner: owner)
public init(
_unsafeBytes buffer: UnsafeMutableRawBufferPointer
) -> dependsOn(immortal) Self {
self.init(_unsafeBytes: UnsafeRawBufferPointer(buffer))
}
@_alwaysEmitIntoClient
public init(
_unsafeBytes buffer: Slice<UnsafeMutableRawBufferPointer>
) -> dependsOn(immortal) Self {
self.init(_unsafeBytes: UnsafeRawBufferPointer(rebasing: buffer))
}
/// Unsafely create a `RawSpan` over initialized memory.
@@ -88,14 +95,67 @@ extension RawSpan {
/// - byteCount: the number of initialized bytes in the span.
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `RawSpan`.
@inlinable @inline(__always)
public init<Owner: ~Copyable & ~Escapable>(
unsafeStart pointer: UnsafeRawPointer,
byteCount: Int,
owner: borrowing Owner
) {
@_alwaysEmitIntoClient
public init(
_unsafeStart pointer: UnsafeRawPointer,
byteCount: Int
) -> dependsOn(immortal) Self {
precondition(byteCount >= 0, "Count must not be negative")
self.init(_unchecked: pointer, byteCount: byteCount, owner: owner)
self.init(_unchecked: pointer, byteCount: byteCount)
}
/// Unsafely create a `RawSpan` over initialized memory.
///
/// The memory in `buffer` must be owned by the instance `owner`,
/// meaning that as long as `owner` is alive the memory will remain valid.
///
/// - Parameters:
/// - buffer: an `UnsafeRawBufferPointer` to initialized memory.
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `RawSpan`.
@_alwaysEmitIntoClient
public init<T: BitwiseCopyable>(
_unsafeElements buffer: UnsafeBufferPointer<T>
) -> dependsOn(immortal) Self {
self.init(_unsafeBytes: UnsafeRawBufferPointer(buffer))
}
/// Unsafely create a `RawSpan` over initialized memory.
///
/// The memory in `buffer` must be owned by the instance `owner`,
/// meaning that as long as `owner` is alive the memory will remain valid.
///
/// - Parameters:
/// - buffer: an `UnsafeMutableRawBufferPointer` to initialized memory.
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `RawSpan`.
@_alwaysEmitIntoClient
public init<T: BitwiseCopyable>(
_unsafeElements buffer: UnsafeMutableBufferPointer<T>
) -> dependsOn(immortal) Self {
self.init(_unsafeElements: UnsafeBufferPointer(buffer))
}
/// Unsafely create a `RawSpan` over initialized memory.
///
/// The memory over `count` bytes starting at
/// `pointer` must be owned by the instance `owner`,
/// meaning that as long as `owner` is alive the memory will remain valid.
///
/// - Parameters:
/// - pointer: a pointer to the first initialized byte.
/// - byteCount: the number of initialized bytes in the span.
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `RawSpan`.
@_alwaysEmitIntoClient
public init<T: BitwiseCopyable>(
_unsafeStart pointer: UnsafePointer<T>,
count: Int
) -> dependsOn(immortal) Self {
precondition(count >= 0, "Count must not be negative")
self.init(
_unchecked: pointer, byteCount: count*MemoryLayout<T>.stride
)
}
/// Create a `RawSpan` over the memory represented by a `Span<T>`
@@ -103,32 +163,24 @@ extension RawSpan {
/// - Parameters:
/// - span: An existing `Span<T>`, which will define both this
/// `RawSpan`'s lifetime and the memory it represents.
@inlinable @inline(__always)
public init<T: BitwiseCopyable>(_ span: borrowing Span<T>) {
@_alwaysEmitIntoClient
public init<Element: BitwiseCopyable>(
_unsafeSpan span: borrowing Span<Element>
) -> dependsOn(immortal) Self {
self.init(
_unchecked: UnsafeRawPointer(span._start),
byteCount: span.count * MemoryLayout<T>.stride,
owner: span
byteCount: span.count &* MemoryLayout<Element>.stride
)
}
}
extension RawSpan {
/// Returns a Boolean value indicating whether two `RawSpan` instances
/// refer to the same region in memory.
@inlinable @inline(__always)
public static func ===(_ a: Self, _ b: Self) -> Bool {
(a._pointer == b._pointer) && (a._count == b._count)
}
}
extension RawSpan {
private var _address: String {
String(UInt(bitPattern: _pointer), radix: 16, uppercase: false)
}
public var description: String {
public var _description: String {
"(0x\(_address), \(_count))"
}
}
@@ -141,13 +193,13 @@ extension RawSpan {
/// instead of comparing `count` to zero.
///
/// - Complexity: O(1)
@inlinable @inline(__always)
@_alwaysEmitIntoClient
public var byteCount: Int { _count }
/// A Boolean value indicating whether the span is empty.
///
/// - Complexity: O(1)
@inlinable @inline(__always)
@_alwaysEmitIntoClient
public var isEmpty: Bool { byteCount == 0 }
/// The indices that are valid for subscripting the span, in ascending
@@ -163,46 +215,34 @@ extension RawSpan {
//MARK: Bounds Checking
extension RawSpan {
/// Return true if `offset` is a valid offset into this `RawSpan`
/// Return true if `offset` is a valid byte offset into this `RawSpan`
///
/// - Parameters:
/// - position: an index to validate
/// - Returns: true if `offset` is a valid index
@inlinable @inline(__always)
public func validateBounds(_ offset: Int) -> Bool {
/// - position: a byte offset to validate
/// - Returns: true if `offset` is a valid byte offset
@_alwaysEmitIntoClient
public func boundsContain(_ offset: Int) -> Bool {
0 <= offset && offset < byteCount
}
/// Traps if `offset` is not a valid offset into this `RawSpan`
///
/// - Parameters:
/// - position: an index to validate
@inlinable @inline(__always)
public func assertValidity(_ offset: Int) {
precondition(
validateBounds(offset), "Offset out of bounds"
)
}
/// Return true if `offsets` is a valid range of offsets into this `RawSpan`
///
/// - Parameters:
/// - offsets: a range of indices to validate
/// - Returns: true if `offsets` is a valid range of indices
@inlinable @inline(__always)
public func validateBounds(_ offsets: Range<Int>) -> Bool {
0 <= offsets.lowerBound && offsets.upperBound <= byteCount
/// - offsets: a range of byte offsets to validate
/// - Returns: true if `offsets` is a valid range of byte offsets
@_alwaysEmitIntoClient
public func boundsContain(_ offsets: Range<Int>) -> Bool {
boundsContain(offsets.lowerBound) && offsets.upperBound <= byteCount
}
/// Traps if `offsets` is not a valid range of offsets into this `RawSpan`
/// Return true if `offsets` is a valid range of offsets into this `RawSpan`
///
/// - Parameters:
/// - offsets: a range of indices to validate
@inlinable @inline(__always)
public func assertValidity(_ offsets: Range<Int>) {
precondition(
validateBounds(offsets), "Range of offsets out of bounds"
)
/// - offsets: a range of byte offsets to validate
/// - Returns: true if `offsets` is a valid range of byte offsets
@_alwaysEmitIntoClient
public func boundsContain(_ offsets: ClosedRange<Int>) -> Bool {
boundsContain(offsets.lowerBound) && offsets.upperBound < byteCount
}
}
@@ -222,10 +262,15 @@ extension RawSpan {
/// - Returns: A span over the bytes within `bounds`
///
/// - Complexity: O(1)
@inlinable @inline(__always)
public func extracting(_ bounds: Range<Int>) -> Self {
assertValidity(bounds)
return extracting(unchecked: bounds)
@_alwaysEmitIntoClient
@usableFromInline func _extracting(_ bounds: Range<Int>) -> Self {
precondition(boundsContain(bounds))
return _extracting(unchecked: bounds)
}
@_alwaysEmitIntoClient
public mutating func _shrink(to bounds: Range<Int>) {
self = _extracting(bounds)
}
/// Constructs a new span over the bytes within the supplied range of
@@ -243,15 +288,19 @@ extension RawSpan {
/// - Returns: A span over the bytes within `bounds`
///
/// - Complexity: O(1)
@inlinable @inline(__always)
public func extracting(unchecked bounds: Range<Int>) -> Self {
@_alwaysEmitIntoClient
@usableFromInline func _extracting(unchecked bounds: Range<Int>) -> Self {
RawSpan(
_unchecked: _pointer?.advanced(by: bounds.lowerBound),
byteCount: bounds.count,
owner: self
byteCount: bounds.count
)
}
@_alwaysEmitIntoClient
public mutating func _shrink(toUnchecked bounds: Range<Int>) {
self = _extracting(unchecked: bounds)
}
/// Constructs a new span over the bytes within the supplied range of
/// positions within this span.
///
@@ -266,8 +315,13 @@ extension RawSpan {
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
public func extracting(_ bounds: some RangeExpression<Int>) -> Self {
extracting(bounds.relative(to: _byteOffsets))
@usableFromInline func _extracting(_ bounds: some RangeExpression<Int>) -> Self {
_extracting(bounds.relative(to: _byteOffsets))
}
@_alwaysEmitIntoClient
public mutating func _shrink(_ bounds: some RangeExpression<Int>) {
self = _extracting(bounds)
}
/// Constructs a new span over the bytes within the supplied range of
@@ -286,10 +340,15 @@ extension RawSpan {
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
public func extracting(
@usableFromInline func _extracting(
unchecked bounds: some RangeExpression<Int>
) -> Self {
extracting(unchecked: bounds.relative(to: _byteOffsets))
_extracting(unchecked: bounds.relative(to: _byteOffsets))
}
@_alwaysEmitIntoClient
public mutating func _shrink(toUnchecked bounds: some RangeExpression<Int>) {
self = _extracting(unchecked: bounds)
}
/// Constructs a new span over all the bytes of this span.
@@ -302,7 +361,7 @@ extension RawSpan {
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
public func extracting(_: UnboundedRange) -> Self {
@usableFromInline func _extracting(_: UnboundedRange) -> Self {
self
}
}
@@ -352,7 +411,7 @@ extension RawSpan {
public func unsafeView<T: BitwiseCopyable>(
as type: T.Type
) -> Span<T> {
Span(unsafeStart: _start, byteCount: byteCount, owner: self)
Span(_unsafeStart: _start, byteCount: byteCount)
}
}
@@ -376,13 +435,13 @@ extension RawSpan {
/// - Returns: A new instance of type `T`, read from the raw bytes at
/// `offset`. The returned instance is memory-managed and unassociated
/// with the value in the memory referenced by this pointer.
@inlinable @inline(__always)
@_alwaysEmitIntoClient
public func unsafeLoad<T>(
fromByteOffset offset: Int = 0, as: T.Type
) -> T {
assertValidity(
precondition(boundsContain(
Range(uncheckedBounds: (offset, offset+MemoryLayout<T>.size))
)
))
return unsafeLoad(fromUncheckedByteOffset: offset, as: T.self)
}
@@ -404,7 +463,7 @@ extension RawSpan {
/// - Returns: A new instance of type `T`, read from the raw bytes at
/// `offset`. The returned instance is memory-managed and unassociated
/// with the value in the memory referenced by this pointer.
@inlinable @inline(__always)
@_alwaysEmitIntoClient
public func unsafeLoad<T>(
fromUncheckedByteOffset offset: Int, as: T.Type
) -> T {
@@ -431,9 +490,9 @@ extension RawSpan {
public func unsafeLoadUnaligned<T: BitwiseCopyable>(
fromByteOffset offset: Int = 0, as: T.Type
) -> T {
assertValidity(
precondition(boundsContain(
Range(uncheckedBounds: (offset, offset+MemoryLayout<T>.size))
)
))
return unsafeLoadUnaligned(fromUncheckedByteOffset: offset, as: T.self)
}
@@ -463,19 +522,11 @@ extension RawSpan {
}
extension RawSpan {
/// Returns true if the memory represented by `span` is a subrange of
/// the memory represented by `self`
///
/// Parameters:
/// - span: a span of the same type as `self`
/// Returns: whether `span` is a subrange of `self`
@inlinable @inline(__always)
public func contains(_ span: borrowing Self) -> Bool {
if span._count > _count { return false }
if _count == 0 || span._count == 0 { return true }
if _start > span._start { return false }
return span._start.advanced(by: span._count) <= _start.advanced(by: _count)
/// Returns a Boolean value indicating whether two `RawSpan` instances
/// refer to the same region in memory.
@_alwaysEmitIntoClient
public func isIdentical(to other: Self) -> Bool {
(self._pointer == other._pointer) && (self._count == other._count)
}
/// Returns the offsets where the memory of `span` is located within
@@ -486,15 +537,17 @@ extension RawSpan {
/// Parameters:
/// - span: a subrange of `self`
/// Returns: A range of offsets within `self`
@inlinable @inline(__always)
public func offsets(of span: borrowing Self) -> Range<Int> {
precondition(contains(span))
var (s, e) = (0, 0)
if _pointer != nil && span._pointer != nil {
s = _start.distance(to: span._start)
e = s + span._count
@_alwaysEmitIntoClient
public func byteOffsets(of span: borrowing Self) -> Range<Int>? {
if span._count > _count { return nil }
guard let subspanStart = span._pointer, _count > 0 else {
return _pointer == span._pointer ? Range(uncheckedBounds: (0, 0)) : nil
}
return Range(uncheckedBounds: (s, e))
if subspanStart < _start { return nil }
let lower = _start.distance(to: subspanStart)
let upper = lower + span._count
guard upper <= _count else { return nil }
return Range(uncheckedBounds: (lower, upper))
}
}
@@ -516,11 +569,16 @@ extension RawSpan {
/// - Returns: A span with at most `maxLength` bytes.
///
/// - Complexity: O(1)
@inlinable
public func extracting(first maxLength: Int) -> Self {
@_alwaysEmitIntoClient
@usableFromInline func _extracting(first maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a prefix of negative length.")
let newCount = min(maxLength, byteCount)
return Self(_unchecked: _pointer, byteCount: newCount, owner: self)
return Self(_unchecked: _pointer, byteCount: newCount)
}
@_alwaysEmitIntoClient
public mutating func _shrink(toFirst maxLength: Int) {
self = _extracting(first: maxLength)
}
/// Returns a span over all but the given number of trailing bytes.
@@ -537,11 +595,16 @@ extension RawSpan {
/// - Returns: A span leaving off the specified number of bytes at the end.
///
/// - Complexity: O(1)
@inlinable
public func extracting(droppingLast k: Int) -> Self {
@_alwaysEmitIntoClient
@usableFromInline func _extracting(droppingLast k: Int) -> Self {
precondition(k >= 0, "Can't drop a negative number of elements.")
let dc = min(k, byteCount)
return Self(_unchecked: _pointer, byteCount: byteCount&-dc, owner: self)
return Self(_unchecked: _pointer, byteCount: byteCount&-dc)
}
@_alwaysEmitIntoClient
public mutating func _shrink(droppingLast k: Int) {
self = _extracting(droppingLast: k)
}
/// Returns a span containing the trailing bytes of the span,
@@ -559,12 +622,17 @@ extension RawSpan {
/// - Returns: A span with at most `maxLength` bytes.
///
/// - Complexity: O(1)
@inlinable
public func extracting(last maxLength: Int) -> Self {
@_alwaysEmitIntoClient
@usableFromInline func _extracting(last maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a suffix of negative length.")
let newCount = min(maxLength, byteCount)
let newStart = _pointer?.advanced(by: byteCount&-newCount)
return Self(_unchecked: newStart, byteCount: newCount, owner: self)
return Self(_unchecked: newStart, byteCount: newCount)
}
@_alwaysEmitIntoClient
public mutating func _shrink(toLast maxLength: Int) {
self = _extracting(last: maxLength)
}
/// Returns a span over all but the given number of initial bytes.
@@ -581,120 +649,16 @@ extension RawSpan {
/// - Returns: A span starting after the specified number of bytes.
///
/// - Complexity: O(1)
@inlinable
public func extracting(droppingFirst k: Int) -> Self {
@_alwaysEmitIntoClient
@usableFromInline func _extracting(droppingFirst k: Int) -> Self {
precondition(k >= 0, "Can't drop a negative number of elements.")
let dc = min(k, byteCount)
let newStart = _pointer?.advanced(by: dc)
return Self(_unchecked: newStart, byteCount: byteCount&-dc, owner: self)
}
}
/// An error indicating that out-of-bounds access was attempted
@frozen
public struct OutOfBoundsError: Error {
/// The number of elements expected
public var expected: Int
/// The number of elements found
public var has: Int
@inlinable
public init(expected: Int, has: Int) {
(self.expected, self.has) = (expected, has)
}
}
extension RawSpan {
/// Parse an instance of `T`, advancing `position`.
@inlinable
public func parse<T: BitwiseCopyable>(
_ position: inout Int, as t: T.Type = T.self
) throws(OutOfBoundsError) -> T {
let length = MemoryLayout<T>.size
guard position >= 0 else {
throw OutOfBoundsError(expected: length, has: 0)
}
let end = position &+ length
guard end <= length else {
throw OutOfBoundsError(expected: length, has: byteCount&-position)
}
return unsafeLoadUnaligned(fromUncheckedByteOffset: position, as: T.self)
}
/// Parse `numBytes` of data, advancing `position`.
@inlinable
public func parse(
_ position: inout Int, numBytes: some FixedWidthInteger
) throws (OutOfBoundsError) -> Self {
let length = Int(numBytes)
guard position >= 0 else {
throw OutOfBoundsError(expected: length, has: 0)
}
let end = position &+ length
guard end <= length else {
throw OutOfBoundsError(expected: length, has: byteCount&-position)
}
return extracting(position..<end)
}
}
extension RawSpan {
@frozen
public struct Cursor: Copyable, ~Escapable {
public let base: RawSpan
/// The range within which we parse
public let parseRange: Range<Int>
/// The current parsing position
public var position: Int
@inlinable
public init(_ base: RawSpan, in range: Range<Int>) {
base.assertValidity(range)
position = 0
self.base = base
parseRange = range
}
@inlinable
public init(_ base: RawSpan) {
position = 0
self.base = base
parseRange = base._byteOffsets
}
/// Parse an instance of `T` and advance
@inlinable
public mutating func parse<T: BitwiseCopyable>(
_ t: T.Type = T.self
) throws(OutOfBoundsError) -> T {
try base.parse(&position, as: T.self)
}
/// Parse `numBytes`and advance
@inlinable
public mutating func parse(
numBytes: some FixedWidthInteger
) throws (OutOfBoundsError) -> RawSpan {
try base.parse(&position, numBytes: numBytes)
}
/// The bytes that we've parsed so far
@inlinable
public var parsedBytes: RawSpan { base.extracting(..<position) }
/// The number of bytes left to parse
@inlinable
public var remainingBytes: Int { base.byteCount &- position }
}
@inlinable
public func makeCursor() -> Cursor { Cursor(self) }
@inlinable
public func makeCursor(in range: Range<Int>) -> Cursor {
Cursor(self, in: range)
return Self(_unchecked: newStart, byteCount: byteCount&-dc)
}
@_alwaysEmitIntoClient
public mutating func _shrink(droppingFirst k: Int) {
self = _extracting(droppingFirst: k)
}
}
+59
View File
@@ -0,0 +1,59 @@
//===--- SpanIterator.swift -----------------------------------------------===//
//
// This source file is part of the Swift.org 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension Span where Element: ~Copyable {
@frozen
public struct Iterator: Copyable, ~Escapable {
var curPointer: UnsafeRawPointer?
let endPointer: UnsafeRawPointer?
public init(from span: consuming Span<Element>) -> dependsOn(immortal) Self {
curPointer = span._pointer
endPointer = span._pointer?.advanced(
by: span.count*MemoryLayout<Element>.stride
)
}
}
}
extension Span.Iterator where Element: Copyable {
// This is the `IteratorProtocol` requirement, except that
// Span.Iterator does not conform to `Escapable`
public mutating func next() -> Element? {
guard curPointer != endPointer,
let cur = curPointer, cur < endPointer.unsafelyUnwrapped
else { return nil }
defer {
curPointer = cur.advanced(by: MemoryLayout<Element>.stride)
}
if _isPOD(Element.self) {
return cur.loadUnaligned(as: Element.self)
}
return cur.load(as: Element.self)
}
}
extension Span.Iterator where Element: BitwiseCopyable {
// This is the `IteratorProtocol` requirement, except that
// Span.Iterator does not conform to `Escapable`
public mutating func next() -> Element? {
guard curPointer != endPointer,
let cur = curPointer, cur < endPointer.unsafelyUnwrapped
else { return nil }
defer {
curPointer = cur.advanced(by: MemoryLayout<Element>.stride)
}
return cur.loadUnaligned(as: Element.self)
}
}
+292 -270
View File
@@ -14,50 +14,42 @@ import Builtin
// A Span<Element> represents a span of memory which
// contains initialized instances of `Element`.
@_disallowFeatureSuppression(NonescapableTypes)
@frozen
public struct Span<Element: ~Copyable /*& ~Escapable*/>: Copyable, ~Escapable {
@usableFromInline
internal let _buffer: UnsafeBufferPointer<Element>
public struct Span<Element: ~Copyable & ~Escapable>: Copyable, ~Escapable {
@usableFromInline let _pointer: UnsafeRawPointer?
@usableFromInline @inline(__always)
internal var _pointer: UnsafePointer<Element>? { _buffer.baseAddress }
var _start: UnsafeRawPointer { _pointer.unsafelyUnwrapped }
@usableFromInline let _count: Int
@_disallowFeatureSuppression(NonescapableTypes)
@usableFromInline @inline(__always)
internal var _start: UnsafePointer<Element> { _pointer.unsafelyUnwrapped }
@usableFromInline @inline(__always)
internal var _count: Int { _buffer.count }
@inlinable @inline(__always)
internal init<Owner: ~Copyable & ~Escapable>(
_unchecked elements: UnsafeBufferPointer<Element>,
owner: borrowing Owner
) {
_buffer = elements
}
@inlinable @inline(__always)
internal init<Owner: ~Copyable & ~Escapable>(
_unchecked start: UnsafePointer<Element>?,
count: Int,
owner: borrowing Owner
) {
self.init(_unchecked: .init(start: start, count: count), owner: owner)
init(
_unchecked start: UnsafeRawPointer?,
count: Int
) -> dependsOn(immortal) Self {
_pointer = start
_count = count
}
}
@_disallowFeatureSuppression(NonescapableTypes)
@available(*, unavailable)
extension Span: Sendable {}
extension UnsafePointer where Pointee: ~Copyable /*& ~Escapable*/ {
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: ~Copyable {
@_disallowFeatureSuppression(NonescapableTypes)
@usableFromInline @inline(__always)
var isAligned: Bool {
(Int(bitPattern: self) & (MemoryLayout<Pointee>.alignment-1)) == 0
internal init(
_unchecked elements: UnsafeBufferPointer<Element>
) -> dependsOn(immortal) Self {
_pointer = .init(elements.baseAddress)
_count = elements.count
}
}
extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// Unsafely create a `Span` over initialized memory.
///
@@ -68,16 +60,17 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// - buffer: an `UnsafeBufferPointer` to initialized elements.
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `Span`.
@inlinable @inline(__always)
public init<Owner: ~Copyable & ~Escapable>(
unsafeElements buffer: UnsafeBufferPointer<Element>,
owner: borrowing Owner
) {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_unsafeElements buffer: UnsafeBufferPointer<Element>
) -> dependsOn(immortal) Self {
precondition(
buffer.count == 0 || buffer.baseAddress.unsafelyUnwrapped.isAligned,
"baseAddress must be properly aligned for accessing \(Element.self)"
((Int(bitPattern: buffer.baseAddress) &
(MemoryLayout<Element>.alignment&-1)) == 0),
"baseAddress must be properly aligned to access Element"
)
self.init(_unchecked: buffer, owner: owner)
self.init(_unchecked: buffer)
}
/// Unsafely create a `Span` over initialized memory.
@@ -89,12 +82,12 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// - buffer: an `UnsafeMutableBufferPointer` to initialized elements.
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `Span`.
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init<Owner: ~Copyable & ~Escapable>(
unsafeElements buffer: UnsafeMutableBufferPointer<Element>,
owner: borrowing Owner
) {
self.init(unsafeElements: UnsafeBufferPointer(buffer), owner: owner)
public init(
_unsafeElements buffer: UnsafeMutableBufferPointer<Element>
) -> dependsOn(immortal) Self {
self.init(_unsafeElements: UnsafeBufferPointer(buffer))
}
/// Unsafely create a `Span` over initialized memory.
@@ -108,78 +101,40 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// - count: the number of initialized elements in the span.
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `Span`.
@inlinable @inline(__always)
public init<Owner: ~Copyable & ~Escapable>(
unsafeStart start: UnsafePointer<Element>,
count: Int,
owner: borrowing Owner
) {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_unsafeStart start: UnsafePointer<Element>,
count: Int
) -> dependsOn(immortal) Self {
precondition(count >= 0, "Count must not be negative")
precondition(
start.isAligned,
"baseAddress must be properly aligned for accessing \(Element.self)"
)
self.init(_unchecked: start, count: count, owner: owner)
self.init(_unsafeElements: .init(start: start, count: count))
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension Span {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_unsafeElements buffer: Slice<UnsafeBufferPointer<Element>>
) -> dependsOn(immortal) Self {
self.init(_unsafeElements: UnsafeBufferPointer(rebasing: buffer))
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_unsafeElements buffer: Slice<UnsafeMutableBufferPointer<Element>>
) -> dependsOn(immortal) Self {
self.init(_unsafeElements: UnsafeBufferPointer(rebasing: buffer))
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: BitwiseCopyable {
/// Unsafely create a `Span` over initialized memory.
///
/// The memory in `buffer` must be owned by the instance `owner`,
/// meaning that as long as `owner` is alive the memory will remain valid.
///
/// - Parameters:
/// - buffer: an `UnsafeBufferPointer` to initialized elements.
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `Span`.
@inlinable @inline(__always)
public init<Owner: ~Copyable & ~Escapable>(
unsafeElements buffer: UnsafeBufferPointer<Element>,
owner: borrowing Owner
) {
self.init(_unchecked: buffer, owner: owner)
}
/// Unsafely create a `Span` over initialized memory.
///
/// The memory in `buffer` must be owned by the instance `owner`,
/// meaning that as long as `owner` is alive the memory will remain valid.
///
/// - Parameters:
/// - buffer: an `UnsafeMutableBufferPointer` to initialized elements.
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `Span`.
@_alwaysEmitIntoClient
public init<Owner: ~Copyable & ~Escapable>(
unsafeElements buffer: UnsafeMutableBufferPointer<Element>,
owner: borrowing Owner
) {
self.init(unsafeElements: UnsafeBufferPointer(buffer), owner: owner)
}
/// Unsafely create a `Span` over initialized memory.
///
/// The memory representing `count` instances starting at
/// `pointer` must be owned by the instance `owner`,
/// meaning that as long as `owner` is alive the memory will remain valid.
///
/// - Parameters:
/// - pointer: a pointer to the first initialized element.
/// - count: the number of initialized elements in the span.
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `Span`.
@inlinable @inline(__always)
public init<Owner: ~Copyable & ~Escapable>(
unsafeStart start: UnsafePointer<Element>,
count: Int,
owner: borrowing Owner
) {
precondition(count >= 0, "Count must not be negative")
self.init(_unchecked: start, count: count, owner: owner)
}
/// Unsafely create a `Span` over initialized memory.
///
/// The memory in `unsafeBytes` must be owned by the instance `owner`
@@ -194,20 +149,20 @@ extension Span where Element: BitwiseCopyable {
/// - type: the type to use when interpreting the bytes in memory.
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `Span`.
@inlinable @inline(__always)
public init<Owner: ~Copyable & ~Escapable>(
unsafeBytes buffer: UnsafeRawBufferPointer,
owner: borrowing Owner
) {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_unsafeBytes buffer: UnsafeRawBufferPointer
) -> dependsOn(immortal) Self {
precondition(
((Int(bitPattern: buffer.baseAddress) &
(MemoryLayout<Element>.alignment&-1)) == 0),
"baseAddress must be properly aligned to access Element"
)
let (byteCount, stride) = (buffer.count, MemoryLayout<Element>.stride)
assert(byteCount >= 0, "Count must not be negative")
let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride)
precondition(remainder == 0)
self.init(
_unchecked: buffer.baseAddress?.assumingMemoryBound(to: Element.self),
count: count,
owner: owner
)
precondition(remainder == 0, "Span must contain a whole number of elements")
self.init(_unchecked: buffer.baseAddress, count: count)
}
/// Unsafely create a `Span` over initialized memory.
@@ -224,12 +179,12 @@ extension Span where Element: BitwiseCopyable {
/// - type: the type to use when interpreting the bytes in memory.
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `Span`.
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init<Owner: ~Copyable & ~Escapable>(
unsafeBytes buffer: UnsafeMutableRawBufferPointer,
owner: borrowing Owner
) {
self.init(unsafeBytes: UnsafeRawBufferPointer(buffer), owner: owner)
public init(
_unsafeBytes buffer: UnsafeMutableRawBufferPointer
) -> dependsOn(immortal) Self {
self.init(_unsafeBytes: UnsafeRawBufferPointer(buffer))
}
/// Unsafely create a `Span` over initialized memory.
@@ -243,24 +198,34 @@ extension Span where Element: BitwiseCopyable {
/// - count: the number of initialized elements in the span.
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `Span`.
@inlinable @inline(__always)
public init<Owner: ~Copyable & ~Escapable>(
unsafeStart pointer: UnsafeRawPointer,
byteCount: Int,
owner: borrowing Owner
) {
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_unsafeStart pointer: UnsafeRawPointer,
byteCount: Int
) -> dependsOn(immortal) Self {
precondition(byteCount >= 0, "Count must not be negative")
let stride = MemoryLayout<Element>.stride
let (count, remainder) = byteCount.quotientAndRemainder(dividingBy: stride)
precondition(remainder == 0)
self.init(
_unchecked: pointer.assumingMemoryBound(to: Element.self),
count: count,
owner: owner
)
self.init(_unsafeBytes: .init(start: pointer, count: byteCount))
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_unsafeBytes buffer: Slice<UnsafeRawBufferPointer>
) -> dependsOn(immortal) Self {
self.init(_unsafeBytes: UnsafeRawBufferPointer(rebasing: buffer))
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public init(
_unsafeBytes buffer: Slice<UnsafeMutableRawBufferPointer>
) -> dependsOn(immortal) Self {
self.init(_unsafeBytes: UnsafeRawBufferPointer(rebasing: buffer))
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: Equatable {
/// Returns a Boolean value indicating whether this and another span
@@ -273,6 +238,8 @@ extension Span where Element: Equatable {
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func _elementsEqual(_ other: Self) -> Bool {
guard count == other.count else { return false }
if count == 0 { return true }
@@ -299,7 +266,8 @@ extension Span where Element: Equatable {
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func _elementsEqual(_ other: some Collection<Element>) -> Bool {
guard count == other.count else { return false }
if count == 0 { return true }
@@ -317,7 +285,8 @@ extension Span where Element: Equatable {
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func _elementsEqual(_ other: some Sequence<Element>) -> Bool {
var offset = 0
for otherElement in other {
@@ -329,27 +298,18 @@ extension Span where Element: Equatable {
}
}
extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// Returns a Boolean value indicating whether two `RawSpan` instances
/// refer to the same region in memory.
@inlinable @inline(__always)
public static func ===(_ a: Self, _ b: Self) -> Bool {
(a._pointer == b._pointer) && (a._count == b._count)
}
}
extension Span where Element: ~Copyable /*& ~Escapable*/ {
private var _address: String {
String(UInt(bitPattern: _pointer), radix: 16, uppercase: false)
}
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: ~Copyable {
@_alwaysEmitIntoClient
public var description: String {
"(0x\(_address), \(_count))"
let addr = String(UInt(bitPattern: _pointer), radix: 16, uppercase: false)
return "(0x\(addr), \(_count))"
}
}
extension Span where Element: ~Copyable /*& ~Escapable*/ {
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: ~Copyable {
/// The number of elements in the span.
///
@@ -357,13 +317,13 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// instead of comparing `count` to zero.
///
/// - Complexity: O(1)
@inlinable @inline(__always)
@_alwaysEmitIntoClient
public var count: Int { _count }
/// A Boolean value indicating whether the span is empty.
///
/// - Complexity: O(1)
@inlinable @inline(__always)
@_alwaysEmitIntoClient
public var isEmpty: Bool { _count == 0 }
/// The indices that are valid for subscripting the span, in ascending
@@ -372,67 +332,63 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// - Complexity: O(1)
@_alwaysEmitIntoClient
public var _indices: Range<Int> {
.init(uncheckedBounds: (0, _count))
Range(uncheckedBounds: (0, _count))
}
}
//MARK: Bounds Checking
extension Span where Element: ~Copyable /*& ~Escapable*/ {
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: ~Copyable {
/// Return true if `offset` is a valid offset into this `Span`
/// Return true if `index` is a valid offset into this `Span`
///
/// - Parameters:
/// - position: an index to validate
/// - Returns: true if `offset` is a valid index
@inlinable @inline(__always)
public func validateBounds(_ offset: Int) -> Bool {
0 <= offset && offset < count
/// - index: an index to validate
/// - Returns: true if `index` is valid
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func boundsContain(_ index: Int) -> Bool {
0 <= index && index < _count
}
/// Traps if `offset` is not a valid offset into this `Span`
/// Return true if `indices` is a valid range of indices into this `Span`
///
/// - Parameters:
/// - position: an index to validate
@inlinable @inline(__always)
public func assertValidity(_ offset: Int) {
precondition(
validateBounds(offset), "Offset out of bounds"
)
/// - indices: a range of indices to validate
/// - Returns: true if `indices` is a valid range of indices
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func boundsContain(_ indices: Range<Int>) -> Bool {
boundsContain(indices.lowerBound) && indices.upperBound <= _count
}
/// Return true if `offsets` is a valid range of offsets into this `Span`
/// Return true if `indices` is a valid range of indices into this `Span`
///
/// - Parameters:
/// - offsets: a range of indices to validate
/// - Returns: true if `offsets` is a valid range of indices
@inlinable @inline(__always)
public func validateBounds(_ offsets: Range<Int>) -> Bool {
0 <= offsets.lowerBound && offsets.upperBound <= count
}
/// Traps if `offsets` is not a valid range of offsets into this `Span`
///
/// - Parameters:
/// - offsets: a range of indices to validate
@inlinable @inline(__always)
public func assertValidity(_ offsets: Range<Int>) {
precondition(
validateBounds(offsets), "Range of offsets out of bounds"
)
/// - indices: a range of indices to validate
/// - Returns: true if `indices` is a valid range of indices
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func boundsContain(_ indices: ClosedRange<Int>) -> Bool {
boundsContain(indices.lowerBound) && indices.upperBound < _count
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: BitwiseCopyable {
/// Construct a RawSpan over the memory represented by this span
///
/// - Returns: a RawSpan over the memory represented by this span
@inlinable @inline(__always)
public var rawSpan: RawSpan { RawSpan(self) }
@_disallowFeatureSuppression(NonescapableTypes)
@unsafe //FIXME: remove when the lifetime inference is fixed
@_alwaysEmitIntoClient
public var _unsafeRawSpan: RawSpan { RawSpan(_unsafeSpan: self) }
}
//MARK: integer offset subscripts
extension Span where Element: ~Copyable /*& ~Escapable*/ {
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: ~Copyable {
/// Accesses the element at the specified position in the `Span`.
///
@@ -440,10 +396,10 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// must be greater or equal to zero, and less than `count`.
///
/// - Complexity: O(1)
@inlinable @inline(__always)
@_alwaysEmitIntoClient
public subscript(_ position: Int) -> Element {
_read {
assertValidity(position)
precondition(boundsContain(position), "index out of bounds")
yield self[unchecked: position]
}
}
@@ -456,14 +412,19 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// must be greater or equal to zero, and less than `count`.
///
/// - Complexity: O(1)
@inlinable @inline(__always)
@unsafe
@_alwaysEmitIntoClient
public subscript(unchecked position: Int) -> Element {
_read {
yield _start.advanced(by: position).pointee
let element = _start.advanced(by: position&*MemoryLayout<Element>.stride)
let binding = Builtin.bindMemory(element._rawValue, count._builtinWordValue, Element.self)
defer { Builtin.rebindMemory(element._rawValue, binding) }
yield UnsafePointer<Element>(element._rawValue).pointee
}
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: BitwiseCopyable {
/// Accesses the element at the specified position in the `Span`.
@@ -472,10 +433,10 @@ extension Span where Element: BitwiseCopyable {
/// must be greater or equal to zero, and less than `count`.
///
/// - Complexity: O(1)
@inlinable @inline(__always)
@_alwaysEmitIntoClient
public subscript(_ position: Int) -> Element {
get {
assertValidity(position)
precondition(boundsContain(position), "index out of bounds")
return self[unchecked: position]
}
}
@@ -488,17 +449,19 @@ extension Span where Element: BitwiseCopyable {
/// must be greater or equal to zero, and less than `count`.
///
/// - Complexity: O(1)
@inlinable @inline(__always)
@unsafe
@_alwaysEmitIntoClient
public subscript(unchecked position: Int) -> Element {
get {
let address = UnsafeRawPointer(_start.advanced(by: position))
let address = _start.advanced(by: position&*MemoryLayout<Element>.stride)
return address.loadUnaligned(as: Element.self)
}
}
}
//MARK: extracting sub-spans
extension Span where Element: ~Copyable /*& ~Escapable*/ {
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: ~Copyable {
/// Constructs a new span over the items within the supplied range of
/// positions within this span.
@@ -513,10 +476,16 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// - Returns: A `Span` over the items within `bounds`
///
/// - Complexity: O(1)
@inlinable @inline(__always)
public func extracting(_ bounds: Range<Int>) -> Self {
assertValidity(bounds)
return extracting(unchecked: bounds)
@_disallowFeatureSuppression(NonescapableTypes)
@usableFromInline func _extracting(_ bounds: Range<Int>) -> Self {
precondition(boundsContain(bounds), "index out of bounds")
return _extracting(unchecked: bounds)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func _shrink(to bounds: Range<Int>) {
self = _extracting(bounds)
}
/// Constructs a new span over the items within the supplied range of
@@ -534,15 +503,22 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// - Returns: A `Span` over the items within `bounds`
///
/// - Complexity: O(1)
@inlinable @inline(__always)
public func extracting(unchecked bounds: Range<Int>) -> Self {
@_disallowFeatureSuppression(NonescapableTypes)
@unsafe
@usableFromInline func _extracting(unchecked bounds: Range<Int>) -> Self {
Span(
_unchecked: _pointer?.advanced(by: bounds.lowerBound),
count: bounds.count,
owner: self
_unchecked: _pointer?.advanced(by: bounds.lowerBound&*MemoryLayout<Element>.stride),
count: bounds.count
)
}
@_disallowFeatureSuppression(NonescapableTypes)
@unsafe
@_alwaysEmitIntoClient
public mutating func _shrink(toUnchecked bounds: Range<Int>) {
self = _extracting(unchecked: bounds)
}
/// Constructs a new span over the items within the supplied range of
/// positions within this span.
///
@@ -556,9 +532,15 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// - Returns: A `Span` over the items within `bounds`
///
/// - Complexity: O(1)
@_disallowFeatureSuppression(NonescapableTypes)
@usableFromInline func _extracting(_ bounds: some RangeExpression<Int>) -> Self {
_extracting(bounds.relative(to: _indices))
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func extracting(_ bounds: some RangeExpression<Int>) -> Self {
extracting(bounds.relative(to: _indices))
public mutating func _shrink(to bounds: some RangeExpression<Int>) {
self = _extracting(bounds)
}
/// Constructs a new span over the items within the supplied range of
@@ -576,11 +558,19 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// - Returns: A `Span` over the items within `bounds`
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
public func extracting(
@_disallowFeatureSuppression(NonescapableTypes)
@unsafe
@usableFromInline func _extracting(
uncheckedBounds bounds: some RangeExpression<Int>
) -> Self {
extracting(unchecked: bounds.relative(to: _indices))
_extracting(unchecked: bounds.relative(to: _indices))
}
@_disallowFeatureSuppression(NonescapableTypes)
@unsafe
@_alwaysEmitIntoClient
public mutating func _shrink(toUnchecked bounds: some RangeExpression<Int>) {
self = _extracting(uncheckedBounds: bounds)
}
/// Constructs a new span over all the items of this span.
@@ -592,14 +582,15 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// - Returns: A `Span` over all the items of this span.
///
/// - Complexity: O(1)
@_alwaysEmitIntoClient
public func extracting(_: UnboundedRange) -> Self {
@_disallowFeatureSuppression(NonescapableTypes)
@usableFromInline func _extracting(_: UnboundedRange) -> Self {
self
}
}
//MARK: withUnsafePointer, etc.
extension Span where Element: ~Copyable /*& ~Escapable*/ {
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: ~Copyable {
//FIXME: mark closure parameter as non-escaping
/// Calls a closure with a pointer to the viewed contiguous storage.
@@ -614,14 +605,21 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// for the `withUnsafeBufferPointer(_:)` method. The closure's
/// parameter is valid only for the duration of its execution.
/// - Returns: The return value of the `body` closure parameter.
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func withUnsafeBufferPointer<E: Error, Result: ~Copyable & ~Escapable>(
public func withUnsafeBufferPointer<E: Error, Result: ~Copyable>(
_ body: (_ buffer: UnsafeBufferPointer<Element>) throws(E) -> Result
) throws(E) -> Result {
try body(.init(start: (count==0) ? nil : _start, count: count))
guard let pointer = _pointer, count > 0 else {
return try body(.init(start: nil, count: 0))
}
let binding = Builtin.bindMemory(pointer._rawValue, count._builtinWordValue, Element.self)
defer { Builtin.rebindMemory(pointer._rawValue, binding) }
return try body(.init(start: .init(pointer._rawValue), count: count))
}
}
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: BitwiseCopyable {
//FIXME: mark closure parameter as non-escaping
@@ -639,11 +637,12 @@ extension Span where Element: BitwiseCopyable {
/// The closure's parameter is valid only for the duration of
/// its execution.
/// - Returns: The return value of the `body` closure parameter.
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func withUnsafeBytes<E: Error, Result: ~Copyable & ~Escapable>(
public func withUnsafeBytes<E: Error, Result: ~Copyable>(
_ body: (_ buffer: UnsafeRawBufferPointer) throws(E) -> Result
) throws(E) -> Result {
try RawSpan(self).withUnsafeBytes(body)
try RawSpan(_unsafeSpan: self).withUnsafeBytes(body)
}
}
@@ -656,7 +655,7 @@ extension Span where Element: Copyable {
/// If the span is empty, the value of this property is `nil`.
///
/// - Returns: The first element in the span, or `nil` if empty
@inlinable
@_alwaysEmitIntoClient
public var first: Element? {
isEmpty ? nil : self[unchecked: 0]
}
@@ -666,50 +665,49 @@ extension Span where Element: Copyable {
/// If the span is empty, the value of this property is `nil`.
///
/// - Returns: The last element in the span, or `nil` if empty
@inlinable
@_alwaysEmitIntoClient
public var last: Element? {
isEmpty ? nil : self[unchecked: count &- 1]
}
}
extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// Returns true if the memory represented by `span` is a subrange of
/// the memory represented by `self`
///
/// Parameters:
/// - span: a span of the same type as `self`
/// Returns: whether `span` is a subrange of `self`
@inlinable @inline(__always)
public func contains(_ span: borrowing Self) -> Bool {
if span._count > _count { return false }
if _count == 0 || span._count == 0 { return true }
if _start > span._start { return false }
return span._start.advanced(by: span._count) <= _start.advanced(by: _count)
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: ~Copyable {
/// Returns a Boolean value indicating whether two `Span` instances
/// refer to the same region in memory.
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func isIdentical(to other: Self) -> Bool {
(self._pointer == other._pointer) && (self._count == other._count)
}
/// Returns the offsets where the memory of `span` is located within
/// the memory represented by `self`
///
/// Note: `span` must be a subrange of `self`
/// Returns the indices within `self` where the memory represented by `span`
/// is located, or `nil` if `span` is not located within `self`.
///
/// Parameters:
/// - span: a subrange of `self`
/// Returns: A range of offsets within `self`
@inlinable @inline(__always)
public func offsets(of span: borrowing Self) -> Range<Int> {
precondition(contains(span))
var (s, e) = (0, 0)
if _pointer != nil && span._pointer != nil {
s = _start.distance(to: span._start)
e = s + span._count
/// - span: a span that may be a subrange of `self`
/// Returns: A range of indices within `self`, or `nil`
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public func indices(of span: borrowing Self) -> Range<Int>? {
if span._count > _count { return nil }
guard let subspanStart = span._pointer, _count > 0 else {
return _pointer == span._pointer ? Range(uncheckedBounds: (0, 0)) : nil
}
return Range(uncheckedBounds: (s, e))
if subspanStart < _start { return nil }
let byteOffset = _start.distance(to: subspanStart)
let stride = MemoryLayout<Element>.stride
let (lower, r) = byteOffset.quotientAndRemainder(dividingBy: stride)
guard r == 0 else { return nil }
let upper = lower + span._count
guard upper <= _count else { return nil }
return Range(uncheckedBounds: (lower, upper))
}
}
//MARK: one-sided slicing operations
extension Span where Element: ~Copyable /*& ~Escapable*/ {
@_disallowFeatureSuppression(NonescapableTypes)
extension Span where Element: ~Copyable {
/// Returns a span containing the initial elements of this span,
/// up to the specified maximum length.
@@ -726,11 +724,17 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// - Returns: A span with at most `maxLength` elements.
///
/// - Complexity: O(1)
@inlinable
public func extracting(first maxLength: Int) -> Self {
@_disallowFeatureSuppression(NonescapableTypes)
@usableFromInline func _extracting(first maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a prefix of negative length.")
let newCount = min(maxLength, count)
return Self(_unchecked: _pointer, count: newCount, owner: self)
return Self(_unchecked: _pointer, count: newCount)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func _shrink(toFirst maxLength: Int) {
self = _extracting(first: maxLength)
}
/// Returns a span over all but the given number of trailing elements.
@@ -747,11 +751,17 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// - Returns: A span leaving off the specified number of elements at the end.
///
/// - Complexity: O(1)
@inlinable
public func extracting(droppingLast k: Int) -> Self {
@_disallowFeatureSuppression(NonescapableTypes)
@usableFromInline func _extracting(droppingLast k: Int) -> Self {
precondition(k >= 0, "Can't drop a negative number of elements.")
let droppedCount = min(k, count)
return Self(_unchecked: _pointer, count: count&-droppedCount, owner: self)
return Self(_unchecked: _pointer, count: count&-droppedCount)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func _shrink(droppingLast k: Int) {
self = _extracting(droppingLast: k)
}
/// Returns a span containing the final elements of the span,
@@ -769,12 +779,18 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// - Returns: A span with at most `maxLength` elements.
///
/// - Complexity: O(1)
@inlinable
public func extracting(last maxLength: Int) -> Self {
@_disallowFeatureSuppression(NonescapableTypes)
@usableFromInline func _extracting(last maxLength: Int) -> Self {
precondition(maxLength >= 0, "Can't have a suffix of negative length.")
let newCount = min(maxLength, count)
let newStart = _pointer?.advanced(by: count&-newCount)
return Self(_unchecked: newStart, count: newCount, owner: self)
let newStart = _pointer?.advanced(by: (count&-newCount)*MemoryLayout<Element>.stride)
return Self(_unchecked: newStart, count: newCount)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func _shrink(toLast maxLength: Int) {
self = _extracting(last: maxLength)
}
/// Returns a span over all but the given number of initial elements.
@@ -791,11 +807,17 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// - Returns: A span starting after the specified number of elements.
///
/// - Complexity: O(1)
@inlinable
public func extracting(droppingFirst k: Int) -> Self {
@_disallowFeatureSuppression(NonescapableTypes)
@usableFromInline func _extracting(droppingFirst k: Int) -> Self {
precondition(k >= 0, "Can't drop a negative number of elements.")
let droppedCount = min(k, count)
let newStart = _pointer?.advanced(by: droppedCount)
return Self(_unchecked: newStart, count: count&-droppedCount, owner: self)
let newStart = _pointer?.advanced(by: droppedCount*MemoryLayout<Element>.stride)
return Self(_unchecked: newStart, count: count&-droppedCount)
}
@_disallowFeatureSuppression(NonescapableTypes)
@_alwaysEmitIntoClient
public mutating func _shrink(droppingFirst k: Int) {
self = _extracting(droppingFirst: k)
}
}
@@ -0,0 +1,86 @@
//===--- StdlibOutputSpanExtensions.swift ---------------------------------===//
//
// This source file is part of the Swift.org 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension Array {
public init(
capacity: Int,
initializingWith initializer: (inout OutputSpan<Element>) throws -> Void
) rethrows {
try self.init(
unsafeUninitializedCapacity: capacity,
initializingWith: { (buffer, count) in
var output = OutputSpan<Element>(
_initializing: buffer.baseAddress.unsafelyUnwrapped,
capacity: buffer.count
)
try initializer(&output)
let initialized = output.relinquishBorrowedMemory()
assert(initialized.baseAddress == buffer.baseAddress)
count = initialized.count
}
)
}
}
extension String {
// also see https://github.com/apple/swift/pull/23050
// and `final class __SharedStringStorage`
@available(macOS 11, *)
public init(
utf8Capacity capacity: Int,
initializingWith initializer: (inout OutputSpan<UInt8>) throws -> Void
) rethrows {
try self.init(
unsafeUninitializedCapacity: capacity,
initializingUTF8With: { buffer in
var output = OutputSpan(
_initializing: buffer.baseAddress.unsafelyUnwrapped,
capacity: capacity
)
try initializer(&output)
let initialized = output.relinquishBorrowedMemory()
assert(initialized.baseAddress == buffer.baseAddress)
return initialized.count
}
)
}
}
import Foundation
extension Data {
public init(
capacity: Int,
initializingWith initializer: (inout OutputSpan<UInt8>) throws -> Void
) rethrows {
self = Data(count: capacity) // initialized with zeroed buffer
let count = try self.withUnsafeMutableBytes { rawBuffer in
try rawBuffer.withMemoryRebound(to: UInt8.self) { buffer in
buffer.deinitialize()
var output = OutputSpan(
_initializing: buffer.baseAddress.unsafelyUnwrapped,
capacity: capacity
)
try initializer(&output)
let initialized = output.relinquishBorrowedMemory()
assert(initialized.baseAddress == buffer.baseAddress)
return initialized.count
}
}
assert(count <= self.count)
self.replaceSubrange(count..<self.count, with: EmptyCollection())
}
}
+502
View File
@@ -0,0 +1,502 @@
//===--- StdlibSpanExtensions.swift ---------------------------------------===//
//
// This source file is part of the Swift.org 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension UnsafeBufferPointer where Element: ~Copyable {
public func withSpan<E: Error, Result: ~Copyable>(
_ body: (_ elements: Span<Element>) throws(E) -> Result
) throws(E) -> Result {
try body(Span(_unsafeElements: self))
}
public func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ elements: RawSpan) throws(E) -> Result
) throws(E) -> Result where Element: BitwiseCopyable {
try body(RawSpan(_unsafeBytes: UnsafeRawBufferPointer(self)))
}
}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
public func withSpan<E: Error, Result: ~Copyable>(
_ body: (_ elements: Span<Element>) throws(E) -> Result
) throws(E) -> Result {
try body(Span(_unsafeElements: self))
}
public func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ elements: RawSpan) throws(E) -> Result
) throws(E) -> Result where Element: BitwiseCopyable {
try body(RawSpan(_unsafeBytes: UnsafeRawBufferPointer(self)))
}
}
extension UnsafeRawBufferPointer {
public func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ elements: RawSpan) throws(E) -> Result
) throws(E) -> Result {
try body(RawSpan(_unsafeBytes: self))
}
}
extension UnsafeMutableRawBufferPointer {
public func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ elements: RawSpan) throws(E) -> Result
) throws(E) -> Result {
try body(RawSpan(_unsafeBytes: self))
}
}
extension Slice {
public func withSpan<Element, E: Error, Result: ~Copyable>(
_ body: (_ elements: Span<Element>) throws(E) -> Result
) throws(E) -> Result
where Base == UnsafeBufferPointer<Element> {
try body(Span(_unsafeElements: UnsafeBufferPointer(rebasing: self)))
}
public func withBytes<Element: BitwiseCopyable, E: Error, Result: ~Copyable>(
_ body: (_ elements: RawSpan) throws(E) -> Result
) throws(E) -> Result
where Base == UnsafeBufferPointer<Element> {
try body(RawSpan(_unsafeBytes: .init(UnsafeBufferPointer(rebasing: self))))
}
public func withSpan<Element, E: Error, Result: ~Copyable>(
_ body: (_ elements: Span<Element>) throws(E) -> Result
) throws(E) -> Result
where Base == UnsafeMutableBufferPointer<Element> {
try body(Span(_unsafeElements: UnsafeBufferPointer(rebasing: self)))
}
public func withBytes<Element: BitwiseCopyable, E: Error, Result: ~Copyable>(
_ body: (_ elements: RawSpan) throws(E) -> Result
) throws(E) -> Result
where Base == UnsafeMutableBufferPointer<Element> {
try body(RawSpan(_unsafeBytes: .init(UnsafeBufferPointer(rebasing: self))))
}
public func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ elements: RawSpan) throws(E) -> Result
) throws(E) -> Result
where Base == UnsafeRawBufferPointer {
try body(RawSpan(_unsafeBytes: UnsafeRawBufferPointer(rebasing: self)))
}
public func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ elements: RawSpan) throws(E) -> Result
) throws(E) -> Result
where Base == UnsafeMutableRawBufferPointer {
try body(RawSpan(_unsafeBytes: UnsafeRawBufferPointer(rebasing: self)))
}
}
import struct Foundation.Data
extension Data {
public func withSpan<E: Error, Result: ~Copyable>(
_ body: (_ elements: Span<UInt8>) throws(E) -> Result
) throws(E) -> Result {
let result = withUnsafeTemporaryAllocation(
of: Swift.Result<Result, E>.self, capacity: 1
) {
buffer -> Swift.Result<Result, E> in
self.withUnsafeBytes {
bytes in
do throws(E) {
let result = try body(Span<UInt8>(_unsafeBytes: bytes))
buffer.initializeElement(at: 0, to: .success(result))
} catch {
buffer.initializeElement(at: 0, to: .failure(error))
}
}
return buffer.moveElement(from: 0)
}
return try result.get()
}
public func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result {
let result = withUnsafeTemporaryAllocation(
of: Swift.Result<Result, E>.self, capacity: 1
) {
buffer -> Swift.Result<Result, E> in
self.withUnsafeBytes {
bytes in
do throws(E) {
let result = try body(RawSpan(_unsafeBytes: bytes))
buffer.initializeElement(at: 0, to: .success(result))
} catch {
buffer.initializeElement(at: 0, to: .failure(error))
}
}
return buffer.moveElement(from: 0)
}
return try result.get()
}
}
extension Array {
/// Calls a closure with a `Span` of the array's contiguous storage.
///
/// Often, the optimizer can eliminate bounds checks within an array
/// algorithm, but when that fails, invoking the same algorithm on the
/// buffer pointer passed into your closure lets you trade safety for speed.
///
/// The following example shows how you can iterate over the contents of the
/// buffer pointer:
///
/// let numbers = [1, 2, 3, 4, 5]
/// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in
/// var result = 0
/// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) {
/// result += buffer[i]
/// }
/// return result
/// }
/// // 'sum' == 9
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the
/// pointer for later use.
///
/// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that
/// points to the contiguous storage for the array. If no such storage exists, it is created. If
/// `body` has a return value, that value is also used as the return value
/// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is
/// valid only for the duration of the method's execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
public func withSpan<E: Error, Result: ~Copyable>(
_ body: (_ elements: Span<Element>) throws(E) -> Result
) throws(E) -> Result {
let result = withUnsafeTemporaryAllocation(
of: Swift.Result<Result, E>.self, capacity: 1
) {
buffer -> Swift.Result<Result, E> in
self.withUnsafeBufferPointer {
elements in
do throws(E) {
let result = try body(Span(_unsafeElements: elements))
buffer.initializeElement(at: 0, to: .success(result))
} catch {
buffer.initializeElement(at: 0, to: .failure(error))
}
}
return buffer.moveElement(from: 0)
}
return try result.get()
}
// public func withSpan<E: Error, Result: ~Copyable>(
// _ body: (_ elements: Span<Element>) throws(E) -> Result
// ) throws(E) -> Result {
// try withUnsafeTemporaryAllocation(of: Result.self, capacity: 1) {
// buffer -> Result in
// try self.withUnsafeBufferPointer {
// let result = try body(Span(_unsafeElements: $0))
// buffer.initializeElement(at: 0, to: result)
// }
// return buffer.moveElement(from: 0)
// }
// }
// public func withSpan<E: Error, Result: ~Copyable>(
// _ body: (_ elements: Span<Element>) throws(E) -> Result
// ) throws(E) -> Result {
// try self.withUnsafeBufferPointer {
// try body(Span(_unsafeElements: $0))
// }
// }
public func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result where Element: BitwiseCopyable {
let result = withUnsafeTemporaryAllocation(
of: Swift.Result<Result, E>.self, capacity: 1
) {
buffer -> Swift.Result<Result, E> in
self.withUnsafeBytes {
bytes in
do throws(E) {
let result = try body(RawSpan(_unsafeBytes: bytes))
buffer.initializeElement(at: 0, to: .success(result))
} catch {
buffer.initializeElement(at: 0, to: .failure(error))
}
}
return buffer.moveElement(from: 0)
}
return try result.get()
}
}
extension ContiguousArray {
public func withSpan<E: Error, Result: ~Copyable>(
_ body: (_ elements: Span<Element>) throws(E) -> Result
) throws(E) -> Result {
let result = withUnsafeTemporaryAllocation(
of: Swift.Result<Result, E>.self, capacity: 1
) {
buffer -> Swift.Result<Result, E> in
self.withUnsafeBufferPointer {
elements in
do throws(E) {
let result = try body(Span(_unsafeElements: elements))
buffer.initializeElement(at: 0, to: .success(result))
} catch {
buffer.initializeElement(at: 0, to: .failure(error))
}
}
return buffer.moveElement(from: 0)
}
return try result.get()
}
}
extension ContiguousArray where Element: BitwiseCopyable {
public func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result where Element: BitwiseCopyable {
let result = withUnsafeTemporaryAllocation(
of: Swift.Result<Result, E>.self, capacity: 1
) {
buffer -> Swift.Result<Result, E> in
self.withUnsafeBytes {
bytes in
do throws(E) {
let result = try body(RawSpan(_unsafeBytes: bytes))
buffer.initializeElement(at: 0, to: .success(result))
} catch {
buffer.initializeElement(at: 0, to: .failure(error))
}
}
return buffer.moveElement(from: 0)
}
return try result.get()
}
}
extension ArraySlice {
public func withSpan<E: Error, Result: ~Copyable>(
_ body: (_ elements: Span<Element>) throws(E) -> Result
) throws(E) -> Result {
let result = withUnsafeTemporaryAllocation(
of: Swift.Result<Result, E>.self, capacity: 1
) {
buffer -> Swift.Result<Result, E> in
self.withUnsafeBufferPointer {
elements in
do throws(E) {
let result = try body(Span(_unsafeElements: elements))
buffer.initializeElement(at: 0, to: .success(result))
} catch {
buffer.initializeElement(at: 0, to: .failure(error))
}
}
return buffer.moveElement(from: 0)
}
return try result.get()
}
}
extension ArraySlice where Element: BitwiseCopyable {
public func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result where Element: BitwiseCopyable {
let result = withUnsafeTemporaryAllocation(
of: Swift.Result<Result, E>.self, capacity: 1
) {
buffer -> Swift.Result<Result, E> in
self.withUnsafeBytes {
bytes in
do throws(E) {
let result = try body(RawSpan(_unsafeBytes: bytes))
buffer.initializeElement(at: 0, to: .success(result))
} catch {
buffer.initializeElement(at: 0, to: .failure(error))
}
}
return buffer.moveElement(from: 0)
}
return try result.get()
}
}
extension String.UTF8View {
public func withSpan<E: Error, Result: ~Copyable>(
_ body: (_ elements: Span<UTF8.CodeUnit>) throws(E) -> Result
) throws(E) -> Result {
let result = withUnsafeTemporaryAllocation(
of: Swift.Result<Result, E>.self, capacity: 1
) {
buffer -> Swift.Result<Result, E>? in
let ran: Void? = self.withContiguousStorageIfAvailable {
elements in
do throws(E) {
let result = try body(Span(_unsafeElements: elements))
buffer.initializeElement(at: 0, to: .success(result))
} catch {
buffer.initializeElement(at: 0, to: .failure(error))
}
}
return (ran == nil) ? nil : buffer.moveElement(from: 0)
}
if let result {
return try result.get()
}
return try ContiguousArray(self).withSpan(body)
}
public func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result {
let result = withUnsafeTemporaryAllocation(
of: Swift.Result<Result, E>.self, capacity: 1
) {
buffer -> Swift.Result<Result, E>? in
let ran: Void? = self.withContiguousStorageIfAvailable {
do throws(E) {
let result = try body(RawSpan(_unsafeElements: $0))
buffer.initializeElement(at: 0, to: .success(result))
} catch {
buffer.initializeElement(at: 0, to: .failure(error))
}
}
return (ran == nil) ? nil : buffer.moveElement(from: 0)
}
if let result {
return try result.get()
}
return try ContiguousArray(self).withBytes(body)
}
}
extension Substring.UTF8View {
public func withSpan<E: Error, Result: ~Copyable>(
_ body: (_ elements: Span<UTF8.CodeUnit>) throws(E) -> Result
) throws(E) -> Result {
let result = withUnsafeTemporaryAllocation(
of: Swift.Result<Result, E>.self, capacity: 1
) {
buffer -> Swift.Result<Result, E>? in
let ran: Void? = self.withContiguousStorageIfAvailable {
elements in
do throws(E) {
let result = try body(Span(_unsafeElements: elements))
buffer.initializeElement(at: 0, to: .success(result))
} catch {
buffer.initializeElement(at: 0, to: .failure(error))
}
}
return (ran == nil) ? nil : buffer.moveElement(from: 0)
}
if let result {
return try result.get()
}
return try ContiguousArray(self).withSpan(body)
}
public func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result {
let result = withUnsafeTemporaryAllocation(
of: Swift.Result<Result, E>.self, capacity: 1
) {
buffer -> Swift.Result<Result, E>? in
let ran: Void? = self.withContiguousStorageIfAvailable {
elements in
do throws(E) {
let result = try body(RawSpan(_unsafeElements: elements))
buffer.initializeElement(at: 0, to: .success(result))
} catch {
buffer.initializeElement(at: 0, to: .failure(error))
}
}
return (ran == nil) ? nil : buffer.moveElement(from: 0)
}
if let result {
return try result.get()
}
return try ContiguousArray(self).withBytes(body)
}
}
extension CollectionOfOne {
public func withSpan<E: Error, Result: ~Copyable>(
_ body: (_ elements: Span<Element>) throws(E) -> Result
) throws(E) -> Result {
var collection = self
return try withUnsafePointer(to: &collection) {
pointer throws(E) -> Result in
try pointer.withMemoryRebound(to: Element.self, capacity: 1) {
element throws(E) -> Result in
try body(Span(_unsafeStart: element, count: 1))
}
}
}
}
extension CollectionOfOne where Element: BitwiseCopyable {
public func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result {
var collection = self
return try Swift.withUnsafeBytes(of: &collection) {
bytes throws(E) -> Result in
try body(RawSpan(_unsafeBytes: bytes))
}
}
}
extension KeyValuePairs {
public func withSpan<E: Error, Result: ~Copyable>(
_ body: (
_ elements: Span<(key: Key, value: Value)>
) throws(E) -> Result
) throws(E) -> Result {
try ContiguousArray(self).withSpan(body)
}
}
extension KeyValuePairs where Element: BitwiseCopyable {
public func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result {
try ContiguousArray(self).withBytes(body)
}
}
extension Span where Element: ~Copyable /*& ~Escapable*/ {
public consuming func withSpan<E: Error, Result: ~Copyable>(
_ body: (_ elements: Span<Element>) throws(E) -> Result
) throws(E) -> Result {
try body(self)
}
}
extension Span where Element: BitwiseCopyable {
public consuming func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ elements: RawSpan) throws(E) -> Result
) throws(E) -> Result {
try body(RawSpan(_unsafeSpan: self))
}
}
extension RawSpan {
public consuming func withBytes<E: Error, Result: ~Copyable>(
_ body: (_ elements: RawSpan) throws(E) -> Result
) throws(E) -> Result {
try body(self)
}
}
//TODO: extend SIMD vectors with `withSpan` and with `withBytes`.
+491
View File
@@ -0,0 +1,491 @@
//===--- MutableSpanTests.swift -------------------------------------------===//
//
// This source file is part of the Swift.org 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import XCTest
@testable import Future
class ID {
let id: Int
init(id: Int) {
self.id = id
}
deinit {
// print(id)
}
}
final class MutableSpanTests: XCTestCase {
func testOptionalStorage() {
// XCTAssertEqual(
// MemoryLayout<MutableSpan<UInt8>>.size, MemoryLayout<MutableSpan<UInt8>?>.size
// )
// XCTAssertEqual(
// MemoryLayout<MutableSpan<UInt8>>.stride, MemoryLayout<MutableSpan<UInt8>?>.stride
// )
// XCTAssertEqual(
// MemoryLayout<MutableSpan<UInt8>>.alignment, MemoryLayout<MutableSpan<UInt8>?>.alignment
// )
}
func testInitOrdinaryElement() {
let capacity = 4
var s = (0..<capacity).map({ "\(#file)+\(#function)--\($0)" })
s.withUnsafeMutableBufferPointer {
let b = MutableSpan(_unsafeElements: $0)
XCTAssertEqual(b.count, $0.count)
}
}
func testInitBitwiseCopyableElement() {
let capacity = 4
var a = Array(0..<capacity)
a.withUnsafeMutableBufferPointer {
let b = MutableSpan(_unsafeElements: $0)
XCTAssertEqual(b.count, $0.count)
}
a.withUnsafeMutableBytes {
let b = MutableSpan<UInt>(_unsafeBytes: $0)
XCTAssertEqual(b.count, capacity)
let r = MutableSpan<Int8>(_unsafeBytes: $0)
XCTAssertEqual(r.count, capacity*MemoryLayout<Int>.stride)
}
// let v = UnsafeRawBufferPointer(start: nil, count: 0)
// XCTAssertNil(MutableSpan<Int>(unsafeRawBufferPointer: v))
}
// public func testIteratorOrdinaryElement() {
// let capacity = 4
// var s = (0..<capacity).map({ "\(#file)+\(#function)--\($0)" })
// s.withUnsafeMutableBufferPointer {
// let view = MutableSpan(_unsafeElements: $0)
//
// var iterator = view.makeIterator()
// var buffered = 0
// while let value = iterator.next() {
// XCTAssertEqual(value.isEmpty, false)
// buffered += 1
// }
// XCTAssertEqual(buffered, $0.count)
// }
// }
// public func testIteratorBitwiseCopyable() {
// let count = 4
// let offset = 1
// XCTAssertLessThan(offset, MemoryLayout<UInt64>.stride)
// let bytes = count*MemoryLayout<UInt64>.stride + offset
// let align = MemoryLayout<UInt64>.alignment
// let p = UnsafeMutableRawPointer.allocate(byteCount: bytes, alignment: align)
// defer { p.deallocate() }
// for i in 0..<bytes where i%8 == offset {
// p.storeBytes(of: 1, toByteOffset: i, as: UInt8.self)
// }
//
// let orig = p.loadUnaligned(as: Int64.self)
// XCTAssertNotEqual(orig, 1)
//
// // MutableSpan doesn't need to be aligned for accessing `BitwiseCopyable` types.
// let buffer = MutableSpan<Int64>(_unsafeStart: p+offset, byteCount: count*8)
//
// var buffered = 0
// for value in 0..<buffer.count {
// XCTAssertNotEqual(value, 1)
// buffered += 1
// }
// XCTAssertEqual(buffered, count)
// }
func testIsEmpty() {
var array = [0, 1, 2]
array.withUnsafeMutableBufferPointer {
let span = MutableSpan(_unsafeElements: $0)
XCTAssertFalse(span.isEmpty)
let empty = MutableSpan(_unsafeElements: .init(rebasing: $0.prefix(0)))
XCTAssertTrue(empty.isEmpty)
}
}
func testSpanFromMutableSpan() {
var array = [0, 1, 2]
array.withUnsafeMutableBufferPointer {
let mutable = MutableSpan(_unsafeElements: $0)
let immutable = Span(_unsafeMutableSpan: mutable)
XCTAssertEqual(mutable.count, immutable.count)
}
}
func testRawSpanFromMutableSpan() {
let count = 4
var array = Array(0..<count)
array.withUnsafeMutableBufferPointer {
let span = MutableSpan(_unsafeElements: $0)
let raw = span._unsafeRawSpan
XCTAssertEqual(raw.byteCount, count*MemoryLayout<Int>.stride)
}
}
func testSpanIndices() {
let capacity = 4
var a = Array(0..<capacity)
a.withUnsafeMutableBufferPointer {
let view = MutableSpan(_unsafeElements: $0)
XCTAssertEqual(view.count, view._indices.count)
XCTAssert(view._indices.elementsEqual(0..<view.count))
}
}
func testElementsEqual() {
let capacity = 4
var a = Array<Int>(unsafeUninitializedCapacity: capacity) {
for i in $0.indices {
$0.initializeElement(at: i, to: .random(in: 0..<10))
}
$1 = $0.count
}
a.withUnsafeMutableBufferPointer {
var v1 = MutableSpan(_unsafeElements: $0)
XCTAssertEqual(v1._elementsEqual(Span(_unsafeMutableSpan: v1)._extracting(first: 1)), false)
XCTAssertEqual(Span(_unsafeMutableSpan: v1)._extracting(first: 0)._elementsEqual(Span(_unsafeMutableSpan: v1)._extracting(last: 0)), true)
XCTAssertEqual(v1._elementsEqual(v1), true)
XCTAssertEqual(Span(_unsafeMutableSpan: v1)._extracting(first: 3)._elementsEqual(Span(_unsafeMutableSpan: v1)._extracting(last: 3)), false)
var b = v1.withUnsafeMutableBufferPointer { Array($0) }
b.withUnsafeMutableBufferPointer {
let v2 = MutableSpan(_unsafeElements: $0)
XCTAssertEqual(v1._elementsEqual(v2), true)
}
}
}
func testElementsEqualCollection() {
let capacity = 4
var a = Array(0..<capacity)
a.withUnsafeMutableBufferPointer {
let span = MutableSpan(_unsafeElements: $0)
let a = $0.indices.randomElement()!
let emptySpan = MutableSpan(_unsafeElements: .init(rebasing: $0[a..<a]))
XCTAssertEqual(span._elementsEqual($0), true)
XCTAssertEqual(emptySpan._elementsEqual([]), true)
XCTAssertEqual(span._elementsEqual($0.dropLast()), false)
}
}
func testElementsEqualSequence() {
let capacity = 4
var a = Array(0..<capacity)
let s = AnySequence(a)
a.withUnsafeMutableBufferPointer {
let span = MutableSpan(_unsafeElements: $0)
let subSpan = MutableSpan(_unsafeElements: .init(rebasing: $0.dropLast()))
XCTAssertEqual(span._elementsEqual(s), true)
XCTAssertEqual(subSpan._elementsEqual(s), false)
XCTAssertEqual(span._elementsEqual(s.dropFirst()), false)
}
}
func testIndexingSubscript() {
let capacity = 4
var a = Array(0..<capacity)
a.withUnsafeMutableBufferPointer {
[first = a.first] in
var v = MutableSpan(_unsafeElements: $0)
XCTAssertEqual(v[0], first)
v[0] += 1
XCTAssertEqual(v[0], first?.advanced(by: 1))
}
var b = a.map(String.init)
b.withUnsafeMutableBufferPointer {
[first = b.first] in
var v = MutableSpan(_unsafeElements: $0)
XCTAssertEqual(v[0], first)
v[0].append("!")
XCTAssertEqual(v[0], first?.appending("!"))
}
}
public func testWithUnsafeBufferPointer() {
let capacity: UInt8 = 64
var a = Array(0..<capacity)
let i = Int.random(in: a.indices)
a.withUnsafeMutableBufferPointer {
let view = MutableSpan(_unsafeElements: $0)
view.withUnsafeBufferPointer {
XCTAssertEqual($0[i], $0[i])
}
}
}
public func testWithUnsafeBytes() {
let capacity: UInt8 = 64
var a = Array(0..<capacity)
let i = Int.random(in: a.indices)
a.withUnsafeMutableBufferPointer {
let view = MutableSpan(_unsafeElements: $0)
view.withUnsafeBytes {
XCTAssertEqual($0.load(fromByteOffset: i, as: UInt8.self), $0[i])
}
}
}
public func testWithUnsafeMutableBufferPointer() {
let capacity: UInt8 = 64
var a = Array(0..<capacity)
let i = Int.random(in: a.indices)
a.withUnsafeMutableBufferPointer {
var view = MutableSpan(_unsafeElements: $0)
view.withUnsafeMutableBufferPointer {
$0[i] += 1
// $0 = .allocate(capacity: 64)
}
var emptySpan = MutableSpan<UInt8>(
_unsafeElements: .init(start: $0.baseAddress, count: 0)
)
emptySpan.withUnsafeMutableBufferPointer {
XCTAssertEqual($0.count, 0)
XCTAssertNil($0.baseAddress)
}
}
XCTAssertEqual(Int(a[i]), i+1)
}
public func testWithUnsafeMutableBytes() {
let capacity: UInt8 = 64
var a = Array(0..<capacity)
let i = Int.random(in: a.indices)
a.withUnsafeMutableBufferPointer {
var view = MutableSpan(_unsafeElements: $0)
view.withUnsafeMutableBytes {
$0.storeBytes(of: UInt8(i+1), toByteOffset: i, as: UInt8.self)
}
var emptySpan = MutableSpan<UInt8>(
_unsafeElements: .init(start: $0.baseAddress, count: 0)
)
emptySpan.withUnsafeMutableBytes {
XCTAssertEqual($0.count, 0)
XCTAssertNil($0.baseAddress)
}
}
XCTAssertEqual(Int(a[i]), i+1)
}
public func testUpdateRepeatingBitwiseCopyable() {
var a = Array(0..<8)
XCTAssertEqual(a.contains(.max), false)
a.withUnsafeMutableBufferPointer {
var span = MutableSpan(_unsafeElements: $0)
span.update(repeating: .max)
}
XCTAssertEqual(a.allSatisfy({ $0 == .max }), true)
}
public func testUpdateRepeating() {
var a = (0..<8).map(ID.init(id:))
XCTAssertEqual(a.map(\.id).contains(.max), false)
a.withUnsafeMutableBufferPointer {
var span = MutableSpan(_unsafeElements: $0)
span.update(repeating: ID(id: .max))
}
XCTAssertEqual(a.allSatisfy({ $0.id == .max }), true)
}
public func testUpdateFromSequenceBitwiseCopyable() {
let capacity = 8
var a = Array(repeating: Int.max, count: capacity)
XCTAssertEqual(a.allSatisfy({ $0 == .max }), true)
a.withUnsafeMutableBufferPointer {
var span = MutableSpan<Int>(_unsafeElements: .init(start: nil, count: 0))
var (iterator, updated) = span.update(from: 0..<0)
XCTAssertNil(iterator.next())
XCTAssertEqual(updated, 0)
span = MutableSpan(_unsafeElements: $0)
(iterator, updated) = span.update(from: 0..<0)
XCTAssertNil(iterator.next())
XCTAssertEqual(updated, 0)
(iterator, updated) = span.update(from: 0..<10000)
XCTAssertNotNil(iterator.next())
XCTAssertEqual(updated, capacity)
}
XCTAssertEqual(a.elementsEqual(0..<capacity), true)
}
public func testUpdateFromSequence() {
let capacity = 8
var a = Array(repeating: ID(id: .max), count: capacity)
XCTAssertEqual(a.allSatisfy({ $0.id == .max }), true)
a.withUnsafeMutableBufferPointer {
var span = MutableSpan(_unsafeElements: $0.prefix(0))
var (iterator, updated) = span.update(from: [])
XCTAssertNil(iterator.next())
XCTAssertEqual(updated, 0)
span = MutableSpan(_unsafeElements: $0)
(iterator, updated) = span.update(from: [])
XCTAssertNil(iterator.next())
XCTAssertEqual(updated, 0)
(iterator, updated) = span.update(from: (0..<12).map(ID.init(id:)))
XCTAssertNotNil(iterator.next())
XCTAssertEqual(updated, capacity)
}
XCTAssertEqual(a.map(\.id).elementsEqual(0..<capacity), true)
}
public func testUpdateFromCollectionBitwiseCopyable() {
let capacity = 8
var a = Array(repeating: Int.max, count: capacity)
XCTAssertEqual(a.allSatisfy({ $0 == .max }), true)
a.withUnsafeMutableBufferPointer {
var span = MutableSpan(_unsafeElements: $0.prefix(0))
var updated = span.update(fromContentsOf: [])
XCTAssertEqual(updated, 0)
updated = span.update(fromContentsOf: AnyCollection([]))
XCTAssertEqual(updated, 0)
span = MutableSpan(_unsafeElements: $0)
updated = span.update(fromContentsOf: 0..<capacity)
XCTAssertEqual(updated, capacity)
}
XCTAssertEqual(a.elementsEqual(0..<capacity), true)
}
public func testUpdateFromCollection() {
let capacity = 8
var a = Array(repeating: ID(id: .max), count: capacity)
XCTAssertEqual(a.allSatisfy({ $0.id == .max }), true)
a.withUnsafeMutableBufferPointer {
var span = MutableSpan(_unsafeElements: $0.prefix(0))
var updated = span.update(fromContentsOf: [])
XCTAssertEqual(updated, 0)
updated = span.update(fromContentsOf: AnyCollection([]))
XCTAssertEqual(updated, 0)
span = MutableSpan(_unsafeElements: $0)
let elements = (0..<capacity).map(ID.init(id:))
updated = span.update(fromContentsOf: AnyCollection(elements))
XCTAssertEqual(updated, capacity)
}
XCTAssertEqual(a.map(\.id).elementsEqual(0..<capacity), true)
}
public func testUpdateFromContiguousMemoryBitwiseCopyable() {
let capacity = 8
var a = Array(repeating: Int.max, count: capacity)
XCTAssertEqual(a.allSatisfy({ $0 == .max }), true)
a.withUnsafeMutableBufferPointer {
var span = MutableSpan(_unsafeElements: $0.prefix(0))
var update = span.update(fromContentsOf: [])
XCTAssertEqual(update, 0)
span = MutableSpan(_unsafeElements: $0)
let array = Array(0..<capacity)
update = span.update(fromContentsOf: array)
XCTAssertEqual(update, capacity)
}
XCTAssertEqual(a.elementsEqual(0..<capacity), true)
}
public func testUpdateFromContiguousMemory() {
let capacity = 8
var a = Array(repeating: ID(id: .max), count: capacity)
XCTAssertEqual(a.allSatisfy({ $0.id == .max }), true)
a.withUnsafeMutableBufferPointer {
var span = MutableSpan(_unsafeElements: $0.prefix(0))
var updated = span.update(fromContentsOf: UnsafeBufferPointer(start: nil, count: 0))
XCTAssertEqual(updated, 0)
span = MutableSpan(_unsafeElements: $0)
let elements = (0..<capacity).map(ID.init(id:))
updated = span.update(fromContentsOf: elements)
XCTAssertEqual(updated, capacity)
}
XCTAssertEqual(a.map(\.id).elementsEqual(0..<capacity), true)
}
public func testUpdateFromRawContiguousMemory() {
let capacity = 8
var a = Array(repeating: Int32.max, count: capacity)
XCTAssertEqual(a.allSatisfy({ $0 == .max }), true)
a.withUnsafeMutableBufferPointer {
var span = MutableSpan(_unsafeElements: $0.prefix(0))
let empty = UnsafeRawBufferPointer(start: $0.baseAddress, count: 0)
var updated = span.update(fromContentsOf: empty)
XCTAssertEqual(updated, 0)
span = MutableSpan(_unsafeElements: $0)
let b = Array(UInt32(0)..<UInt32(capacity))
updated = b.withUnsafeBytes { span.update(fromContentsOf: $0) }
XCTAssertEqual(updated, capacity)
}
XCTAssertEqual(a.elementsEqual(0..<Int32(capacity)), true)
}
public func testMoveUpdate() {
let capacity = 8
var a = Array(repeating: ID(id: .max), count: capacity)
a.withUnsafeMutableBufferPointer {
var span = MutableSpan(_unsafeElements: $0)
let empty = UnsafeMutableBufferPointer(start: $0.baseAddress, count: 0)
let updated = span.moveUpdate(fromContentsOf: empty)
XCTAssertEqual(updated, 0)
}
XCTAssertEqual(a.allSatisfy({ $0.id == .max }), true)
var b = UnsafeMutableBufferPointer<ID>.allocate(capacity: capacity)
a.withUnsafeMutableBufferPointer {
var span = MutableSpan(_unsafeElements: $0)
var o = OutputSpan(_initializing: b)
o.append(fromContentsOf: (0..<capacity).map(ID.init(id:)))
XCTAssertEqual(o.count, capacity)
let updated = span.moveUpdate(fromContentsOf: o)
XCTAssertEqual(updated, capacity)
}
XCTAssertEqual(a.map(\.id).elementsEqual(0..<capacity), true)
b.deallocate()
b = .allocate(capacity: 2*capacity)
let i = b.initialize(fromContentsOf: (0..<2*capacity).map(ID.init(id:)))
XCTAssertEqual(i, 2*capacity)
a.withUnsafeMutableBufferPointer {
var span = MutableSpan(_unsafeElements: $0)
let updated = span.moveUpdate(fromContentsOf: b.suffix(capacity))
XCTAssertEqual(updated, capacity)
}
XCTAssertEqual(a.map(\.id).elementsEqual(capacity..<2*capacity), true)
a = []
b.prefix(capacity).deinitialize()
b.deallocate()
}
}
+260
View File
@@ -0,0 +1,260 @@
//===--- OutputSpanTests.swift --------------------------------------------===//
//
// This source file is part of the Swift.org 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import XCTest
import Future
struct Allocation<T>: ~Copyable {
let allocation: UnsafeMutablePointer<T>
let capacity: Int
var count: Int? = nil
init(of count: Int = 1, _ t: T.Type) {
precondition(count >= 0)
capacity = count
allocation = UnsafeMutablePointer<T>.allocate(capacity: capacity)
}
var isInitialized: Bool { count != nil }
mutating func initialize(
_ body: (/* mutating */ inout OutputSpan<T>) throws -> Void
) rethrows {
if count != nil { fatalError() }
var outputBuffer = OutputSpan<T>(
_initializing: allocation, capacity: capacity
)
do {
try body(&outputBuffer)
let initialized = outputBuffer.relinquishBorrowedMemory()
assert(initialized.baseAddress == allocation)
count = initialized.count
}
catch {
outputBuffer.deinitialize()
let empty = outputBuffer.relinquishBorrowedMemory()
assert(empty.baseAddress == allocation)
assert(empty.count == 0)
throw error
}
}
borrowing func examine<E, R>(
_ body: (borrowing Span<T>) throws(E) -> R
) throws(E) -> R {
try body(initializedPrefix)
}
var initializedPrefix: Span<T> {
Span(_unsafeStart: allocation, count: count ?? 0)
}
// mutating func mutate<R>(
// _ body: (/* mutating */ inout MutableBufferView<T>) -> R
// ) -> R {
// guard let count else { fatalError() }
// var mutable = MutableBufferView<T>(
// baseAddress: allocation, count: count, dependsOn: /*self*/ allocation
// )
// return body(&mutable)
// }
deinit {
if let count {
allocation.deinitialize(count: count)
}
allocation.deallocate()
}
}
enum MyTestError: Error { case error }
final class OutputBufferTests: XCTestCase {
func testOutputBufferInitialization() {
let c = 48
let allocation = UnsafeMutablePointer<UInt8>.allocate(capacity: c)
defer { allocation.deallocate() }
let ob = OutputSpan(_initializing: allocation, capacity: c)
let initialized = ob.relinquishBorrowedMemory()
XCTAssertNotNil(initialized.baseAddress)
XCTAssertEqual(initialized.count, 0)
}
func testInitializeBufferByAppendingElements() {
var a = Allocation(of: 48, Int.self)
let c = 10
a.initialize {
for i in 0...c {
$0.appendElement(i)
}
let oops = $0.deinitializeLastElement()
XCTAssertEqual(oops, c)
}
a.examine {
XCTAssertEqual($0.count, c)
XCTAssert($0._elementsEqual(0..<c))
}
let span = a.initializedPrefix
XCTAssertEqual(span.count, c)
XCTAssert(span._elementsEqual(0..<c))
}
func testInitializeBufferByAppendingRepeatedElements() {
var a = Allocation(of: 48, Int.self)
let c = 10
a.initialize {
$0.append(repeating: c, count: c)
let oops = $0.deinitializeLastElement()
XCTAssertEqual(oops, c)
XCTAssertEqual($0.count, c-1)
}
a.examine {
XCTAssertEqual($0.count, c-1)
XCTAssert($0._elementsEqual(Array(repeating: c, count: c-1)))
}
let span = a.initializedPrefix
XCTAssertEqual(span.count, c-1)
XCTAssert(span._elementsEqual(Array(repeating: c, count: c-1)))
}
func testInitializeBufferFromSequence() {
var a = Allocation(of: 48, Int.self)
a.initialize {
var it = $0.append(from: 0..<18)
XCTAssertNil(it.next())
}
let span = a.initializedPrefix
XCTAssertEqual(span.count, 18)
XCTAssert(span._elementsEqual(0..<18))
}
func testInitializeBufferFromCollectionNotContiguous() {
var a = Allocation(of: 48, Int.self)
let c = 24
a.initialize {
$0.append(fromContentsOf: 0..<c)
let span = $0.initializedPrefix
XCTAssertEqual(span.count, c)
XCTAssert(span._elementsEqual(0..<c))
}
}
func testInitializeBufferFromContiguousCollection() {
var a = Allocation(of: 48, Int.self)
let c = 24
a.initialize {
$0.append(fromContentsOf: Array(0..<c))
let prefix = $0.initializedPrefix
XCTAssertEqual(prefix.count, c)
XCTAssert(prefix._elementsEqual(0..<c))
}
let span = a.initializedPrefix
XCTAssertEqual(span.count, c)
XCTAssert(span._elementsEqual(0..<c))
}
func testInitializeBufferFromSpan() {
var a = Allocation(of: 48, Int.self)
let c = 24
a.initialize {
let array = Array(0..<c)
#if false
array.withUnsafeBufferPointer {
// let storage = Span(_unsafeElements: $0)
let storage = Span<Int>(_unsafeElements: .init(start: nil, count: 0))
$0.append(fromContentsOf: storage)
}
#else
$0.append(fromContentsOf: array)
#endif
}
let span = a.initializedPrefix
XCTAssertEqual(span.count, c)
XCTAssert(span._elementsEqual(0..<c))
}
func testInitializeBufferFromEmptyContiguousCollection() {
var a = Allocation(of: 48, Int.self)
a.initialize {
$0.append(fromContentsOf: [])
}
XCTAssertTrue(a.isInitialized)
XCTAssertTrue(a.initializedPrefix.isEmpty)
}
func testMoveAppend() {
class I {
let i: Int
init(_ i: Int) {
self.i = i
}
}
let c = 20
let b = UnsafeMutableBufferPointer<I>.allocate(capacity: c)
for i in 0..<c {
b.initializeElement(at: i, to: I(i))
}
var a = Allocation(of: 48, I.self)
a.initialize {
$0.moveAppend(fromContentsOf: b)
$0.moveAppend(fromContentsOf: b[c..<c])
}
XCTAssertTrue(a.isInitialized)
XCTAssertEqual(a.initializedPrefix.count, c)
}
func testDeinitializeBuffer() throws {
var a = Allocation(of: 48, Int.self)
do {
try a.initialize {
$0.appendElement(0)
$0.appendElement(1)
XCTAssertTrue($0.count > 0)
throw MyTestError.error
}
}
catch MyTestError.error {
XCTAssertEqual(a.isInitialized, false)
}
}
func testMutateOutputSpan() throws {
let b = UnsafeMutableBufferPointer<Int>.allocate(capacity: 10)
defer { b.deallocate() }
var span = OutputSpan(_initializing: b)
XCTAssertEqual(span.count, 0)
span.append(fromContentsOf: 0..<10)
XCTAssertEqual(span.count, 10)
span.withMutableSpan {
#if false
let b = UnsafeMutableBufferPointer<Int>.allocate(capacity: 8)
b.initialize(repeating: .max)
$0 = MutableSpan(_unsafeElements: b)
#else
for i in 0..<$0.count {
$0[i] *= 2
}
#endif
}
let r = span.relinquishBorrowedMemory()
print(Array(r))
r.deinitialize()
}
}
+72 -89
View File
@@ -11,7 +11,7 @@
//===----------------------------------------------------------------------===//
import XCTest
import Future
@testable import Future
final class RawSpanTests: XCTestCase {
@@ -30,14 +30,14 @@ final class RawSpanTests: XCTestCase {
func testInitWithSpanOfIntegers() {
let capacity = 4
let a = Array(0..<capacity)
let span = RawSpan(a.storage)
let span = RawSpan(_unsafeSpan: a.storage)
XCTAssertEqual(span.byteCount, capacity*MemoryLayout<Int>.stride)
XCTAssertFalse(span.isEmpty)
}
func testInitWithEmptySpanOfIntegers() {
let a: [Int] = []
let span = RawSpan(a.storage)
let span = RawSpan(_unsafeSpan: a.storage)
XCTAssertTrue(span.isEmpty)
}
@@ -45,12 +45,12 @@ final class RawSpanTests: XCTestCase {
let capacity = 4
var a = Array(0..<capacity)
a.withUnsafeBytes {
let span = RawSpan(unsafeBytes: $0, owner: a)
let span = RawSpan(_unsafeBytes: $0)
XCTAssertEqual(span.byteCount, capacity*MemoryLayout<Int>.stride)
}
a.withUnsafeMutableBytes {
let span = RawSpan(unsafeBytes: $0, owner: $0)
let span = RawSpan(_unsafeBytes: $0)
XCTAssertEqual(span.byteCount, capacity*MemoryLayout<Int>.stride)
}
}
@@ -61,9 +61,8 @@ final class RawSpanTests: XCTestCase {
a.withUnsafeBytes {
let pointer = $0.baseAddress!
let span = RawSpan(
unsafeStart: pointer,
byteCount: capacity*MemoryLayout<Int>.stride,
owner: a
_unsafeStart: pointer,
byteCount: capacity*MemoryLayout<Int>.stride
)
XCTAssertEqual(span.byteCount, $0.count)
}
@@ -71,9 +70,8 @@ final class RawSpanTests: XCTestCase {
a.withUnsafeMutableBytes {
let pointer = $0.baseAddress!
let span = RawSpan(
unsafeStart: pointer,
byteCount: capacity*MemoryLayout<Int>.stride,
owner: $0
_unsafeStart: pointer,
byteCount: capacity*MemoryLayout<Int>.stride
)
XCTAssertEqual(span.byteCount, $0.count)
}
@@ -83,7 +81,7 @@ final class RawSpanTests: XCTestCase {
let capacity = 4
let s = (0..<capacity).map({ "\(#file)+\(#function) #\($0)" })
s.withUnsafeBytes {
let span = RawSpan(unsafeBytes: $0, owner: $0)
let span = RawSpan(_unsafeBytes: $0)
let stride = MemoryLayout<String>.stride
let s0 = span.unsafeLoad(as: String.self)
@@ -99,9 +97,11 @@ final class RawSpanTests: XCTestCase {
let capacity = 64
let a = Array(0..<UInt8(capacity))
a.withUnsafeBytes {
let span = RawSpan(unsafeBytes: $0, owner: $0)
let span = RawSpan(_unsafeBytes: $0)
let u0 = span.extracting(droppingFirst: 2).unsafeLoadUnaligned(as: UInt64.self)
var copy = span
copy._shrink(droppingFirst: 2)
let u0 = copy.unsafeLoadUnaligned(as: UInt64.self)
XCTAssertEqual(u0 & 0xff, 2)
XCTAssertEqual(u0.byteSwapped & 0xff, 9)
let u1 = span.unsafeLoadUnaligned(fromByteOffset: 6, as: UInt64.self)
@@ -115,11 +115,11 @@ final class RawSpanTests: XCTestCase {
let capacity = 4
let b = (0..<capacity).map(Int8.init)
b.withUnsafeBytes {
let span = RawSpan(unsafeBytes: $0, owner: $0)
let sub1 = span.extracting(0..<2)
let sub2 = span.extracting(..<2)
let sub3 = span.extracting(...)
let sub4 = span.extracting(unchecked: 2...)
let span = RawSpan(_unsafeBytes: $0)
let sub1 = span._extracting(0..<2)
let sub2 = span._extracting(..<2)
let sub3 = span._extracting(...)
let sub4 = span._extracting(unchecked: 2...)
XCTAssertTrue(
sub1.unsafeView(as: UInt8.self)._elementsEqual(sub2.unsafeView(as: UInt8.self))
)
@@ -136,9 +136,11 @@ final class RawSpanTests: XCTestCase {
let capacity = 32
let b = (0..<capacity).map(UInt8.init)
b.withUnsafeBytes {
let span = RawSpan(unsafeBytes: $0, owner: $0)
let prefix = span.extracting(0..<8)
let beyond = prefix.extracting(unchecked: 16..<24)
let span = RawSpan(_unsafeBytes: $0)
var prefix = span
prefix._shrink(to: 0..<8)
var beyond = prefix
beyond._shrink(toUnchecked: 16..<24)
XCTAssertEqual(beyond.byteCount, 8)
XCTAssertEqual(beyond.unsafeLoad(as: UInt8.self), 16)
}
@@ -147,19 +149,16 @@ final class RawSpanTests: XCTestCase {
func testUnsafeBytes() {
let capacity = 4
let array = Array(0..<capacity)
let span = RawSpan(array.storage)
let span = RawSpan(_unsafeSpan: array.storage)
array.withUnsafeBytes { b1 in
span.withUnsafeBytes { b2 in
XCTAssertTrue(b1.elementsEqual(b2))
}
}
//FIXME: rdar://128694495 (Faulty escape diagnostic)
// Should we be able to derive a non-escapable value from a Span via unsafe pointers?
// let copy = span.withUnsafeBytes {
// RawSpan(unsafeBytes: copy $0, owner: span)
// }
// _ = copy
// Should we be able to derive a non-escapable value from a Span via unsafe pointers?
let copy = span.withUnsafeBytes { RawSpan(_unsafeBytes: $0) }
_ = copy
}
func testStrangeBorrow() {
@@ -169,13 +168,13 @@ final class RawSpanTests: XCTestCase {
// let rs = RawSpan(array.storage) // Initializer 'init(_:)' requires that 'String' conform to 'BitwiseCopyable'
// let rs1 = array.storage.withUnsafeBufferPointer {
// RawSpan(unsafeBytes: UnsafeRawBufferPointer($0), owner: array)
// RawSpan(unsafeBytes: UnsafeRawBufferPointer($0))
// } // Lifetime-dependent value escapes its scope
// _ = rs1
// let rs2 = array.storage.withUnsafeBufferPointer {
// UnsafeRawBufferPointer($0).withMemoryRebound(to: UInt8.self) { // requires that `Span` conform to `Escapable`
// return Span(unsafeBufferPointer: $0, owner: array)
// return Span(unsafeBufferPointer: $0)
// }
// }
// _ = rs2
@@ -185,18 +184,18 @@ final class RawSpanTests: XCTestCase {
let capacity = 4
let a = Array(0..<UInt8(capacity))
a.withUnsafeBytes {
let span = RawSpan(unsafeBytes: $0, owner: $0)
let span = RawSpan(_unsafeBytes: $0)
XCTAssertEqual(span.byteCount, capacity)
XCTAssertEqual(span.extracting(first: 1).unsafeLoad(as: UInt8.self), 0)
XCTAssertEqual(span._extracting(first: 1).unsafeLoad(as: UInt8.self), 0)
XCTAssertEqual(
span.extracting(first: capacity).unsafeLoad(
span._extracting(first: capacity).unsafeLoad(
fromByteOffset: capacity-1, as: UInt8.self
),
UInt8(capacity-1)
)
XCTAssertTrue(span.extracting(droppingLast: capacity).isEmpty)
XCTAssertTrue(span._extracting(droppingLast: capacity).isEmpty)
XCTAssertEqual(
span.extracting(droppingLast: 1).unsafeLoad(
span._extracting(droppingLast: 1).unsafeLoad(
fromByteOffset: capacity-2, as: UInt8.self
),
UInt8(capacity-2)
@@ -205,10 +204,10 @@ final class RawSpanTests: XCTestCase {
do {
let b = UnsafeRawBufferPointer(start: nil, count: 0)
let span = RawSpan(unsafeBytes: b, owner: b)
let span = RawSpan(_unsafeBytes: b)
XCTAssertEqual(span.byteCount, b.count)
XCTAssertEqual(span.extracting(first: 1).byteCount, b.count)
XCTAssertEqual(span.extracting(droppingLast: 1).byteCount, b.count)
XCTAssertEqual(span._extracting(first: 1).byteCount, b.count)
XCTAssertEqual(span._extracting(droppingLast: 1).byteCount, b.count)
}
}
@@ -216,78 +215,62 @@ final class RawSpanTests: XCTestCase {
let capacity = 4
let a = Array(0..<UInt8(capacity))
a.withUnsafeBytes {
let span = RawSpan(unsafeBytes: $0, owner: $0)
let span = RawSpan(_unsafeBytes: $0)
XCTAssertEqual(span.byteCount, capacity)
XCTAssertEqual(span.extracting(last: capacity).unsafeLoad(as: UInt8.self), 0)
XCTAssertEqual(span.extracting(last: capacity-1).unsafeLoad(as: UInt8.self), 1)
XCTAssertEqual(span.extracting(last: 1).unsafeLoad(as: UInt8.self), UInt8(capacity-1))
XCTAssertTrue(span.extracting(droppingFirst: capacity).isEmpty)
XCTAssertEqual(span.extracting(droppingFirst: 1).unsafeLoad(as: UInt8.self), 1)
XCTAssertEqual(span._extracting(last: capacity).unsafeLoad(as: UInt8.self), 0)
XCTAssertEqual(span._extracting(last: capacity-1).unsafeLoad(as: UInt8.self), 1)
XCTAssertEqual(span._extracting(last: 1).unsafeLoad(as: UInt8.self), UInt8(capacity-1))
XCTAssertTrue(span._extracting(droppingFirst: capacity).isEmpty)
XCTAssertEqual(span._extracting(droppingFirst: 1).unsafeLoad(as: UInt8.self), 1)
}
do {
let b = UnsafeRawBufferPointer(start: nil, count: 0)
let span = RawSpan(unsafeBytes: b, owner: b)
let span = RawSpan(_unsafeBytes: b)
XCTAssertEqual(span.byteCount, b.count)
XCTAssertEqual(span.extracting(last: 1).byteCount, b.count)
XCTAssertEqual(span.extracting(droppingFirst: 1).byteCount, b.count)
XCTAssertEqual(span._extracting(last: 1).byteCount, b.count)
XCTAssertEqual(span._extracting(droppingFirst: 1).byteCount, b.count)
}
}
func testBoundsChecking() {
let capacity = 4
let a = Array(0..<capacity)
let span = RawSpan(a.storage)
let span = RawSpan(_unsafeSpan: a.storage)
for o in span._byteOffsets {
span.assertValidity(o)
XCTAssertTrue(span.boundsContain(o))
}
// span.assertValidity(span.count)
XCTAssertFalse(span.boundsContain(span.byteCount))
}
func testContainment() {
func testByteOffsetsOf() {
let b = UnsafeMutableRawBufferPointer.allocate(byteCount: 8, alignment: 8)
defer { b.deallocate() }
let span = RawSpan(unsafeBytes: b, owner: b)
let subSpan = span.extracting(last: 2)
let emptySpan = span.extracting(first: 0)
let fakeSpan = RawSpan(
unsafeStart: b.baseAddress!.advanced(by: 8), byteCount: 8, owner: b
)
let span = RawSpan(_unsafeBytes: b)
let subSpan1 = span._extracting(first: 6)
let subSpan2 = span._extracting(last: 6)
let emptySpan = span._extracting(first: 0)
let nilSpan = RawSpan(
unsafeBytes: UnsafeRawBufferPointer(start: nil, count: 0), owner: b
_unsafeBytes: UnsafeRawBufferPointer(start: nil, count: 0)
)
XCTAssertTrue(span.contains(subSpan))
XCTAssertFalse(subSpan.contains(span))
XCTAssertTrue(span.contains(emptySpan))
XCTAssertFalse(emptySpan.contains(span))
XCTAssertFalse(span.contains(fakeSpan))
XCTAssertFalse(fakeSpan.contains(span))
XCTAssertTrue(span.contains(nilSpan))
XCTAssertTrue(fakeSpan.contains(nilSpan))
XCTAssertTrue(nilSpan.contains(emptySpan))
}
func testOffsets() {
let b = UnsafeMutableRawBufferPointer.allocate(byteCount: 8, alignment: 8)
defer { b.deallocate() }
let span = RawSpan(unsafeBytes: b, owner: b)
let subSpan = span.extracting(last: 2)
let emptySpan = span.extracting(first: 0)
let nilSpan = RawSpan(
unsafeBytes: UnsafeRawBufferPointer(start: nil, count: 0), owner: b
)
var bounds: Range<Int>
bounds = span.offsets(of: subSpan)
XCTAssertEqual(bounds, span._byteOffsets.suffix(2))
bounds = span.offsets(of: emptySpan)
XCTAssertEqual(bounds, span._byteOffsets.prefix(0))
bounds = span.offsets(of: nilSpan)
XCTAssertEqual(bounds, 0..<0)
bounds = nilSpan.offsets(of: emptySpan)
var bounds: Range<Int>?
bounds = span.byteOffsets(of: subSpan1)
XCTAssertEqual(bounds, span._byteOffsets.prefix(6))
bounds = span.byteOffsets(of: subSpan2)
XCTAssertEqual(bounds, span._byteOffsets.suffix(6))
bounds = subSpan2.byteOffsets(of: subSpan1)
XCTAssertNil(bounds)
bounds = subSpan1.byteOffsets(of: subSpan2)
XCTAssertNil(bounds)
bounds = subSpan2.byteOffsets(of: span)
XCTAssertNil(bounds)
bounds = nilSpan.byteOffsets(of: emptySpan)
XCTAssertNil(bounds)
bounds = span.byteOffsets(of: nilSpan)
XCTAssertNil(bounds)
bounds = nilSpan.byteOffsets(of: nilSpan)
XCTAssertEqual(bounds, 0..<0)
}
}
+155 -108
View File
@@ -11,7 +11,7 @@
//===----------------------------------------------------------------------===//
import XCTest
import Future
@testable import Future
final class SpanTests: XCTestCase {
@@ -31,19 +31,19 @@ final class SpanTests: XCTestCase {
let capacity = 4
var s = (0..<capacity).map({ "\(#file)+\(#function)--\($0)" })
s.withUnsafeBufferPointer {
var span = Span(unsafeElements: $0, owner: s)
var span = Span(_unsafeElements: $0)
XCTAssertEqual(span.count, capacity)
span = Span(unsafeStart: $0.baseAddress!, count: $0.count, owner: s)
span = Span(_unsafeStart: $0.baseAddress!, count: $0.count)
XCTAssertEqual(span.count, capacity)
}
s.withUnsafeMutableBufferPointer {
var span = Span(unsafeElements: $0, owner: $0)
var span = Span(_unsafeElements: $0)
XCTAssertEqual(span.count, capacity)
let pointer: UnsafeMutablePointer = $0.baseAddress!
span = Span(unsafeStart: pointer, count: $0.count, owner: $0)
span = Span(_unsafeStart: pointer, count: $0.count)
XCTAssertEqual(span.count, capacity)
}
}
@@ -52,45 +52,43 @@ final class SpanTests: XCTestCase {
let capacity = 4
var a = Array(0..<capacity)
a.withUnsafeBufferPointer {
var span = Span(unsafeElements: $0, owner: a)
var span = Span(_unsafeElements: $0)
XCTAssertEqual(span.count, capacity)
span = Span(unsafeStart: $0.baseAddress!, count: $0.count, owner: a)
span = Span(_unsafeStart: $0.baseAddress!, count: $0.count)
XCTAssertEqual(span.count, capacity)
}
a.withUnsafeMutableBufferPointer {
var span = Span(unsafeElements: $0, owner: $0)
var span = Span(_unsafeElements: $0)
XCTAssertEqual(span.count, capacity)
let pointer: UnsafeMutablePointer = $0.baseAddress!
span = Span(unsafeStart: pointer, count: $0.count, owner: $0)
span = Span(_unsafeStart: pointer, count: $0.count)
XCTAssertEqual(span.count, capacity)
}
a.withUnsafeBytes {
let b = Span<UInt>(unsafeBytes: $0, owner: $0)
let b = Span<UInt>(_unsafeBytes: $0)
XCTAssertEqual(b.count, capacity)
let r = Span<Int8>(unsafeBytes: $0, owner: $0)
let r = Span<Int8>(_unsafeBytes: $0)
XCTAssertEqual(r.count, capacity*MemoryLayout<Int>.stride)
let p = Span<Int>(
unsafeStart: $0.baseAddress!,
byteCount: capacity*MemoryLayout<Int>.stride,
owner: $0
_unsafeStart: $0.baseAddress!,
byteCount: capacity*MemoryLayout<Int>.stride
)
XCTAssertEqual(p.count, capacity)
}
a.withUnsafeMutableBytes {
let b = Span<UInt>(unsafeBytes: $0, owner: $0)
let b = Span<UInt>(_unsafeBytes: $0)
XCTAssertEqual(b.count, capacity)
let p = Span<Int>(
unsafeStart: $0.baseAddress!,
byteCount: capacity*MemoryLayout<Int>.stride,
owner: $0
_unsafeStart: $0.baseAddress!,
byteCount: capacity*MemoryLayout<Int>.stride
)
XCTAssertEqual(p.count, capacity)
}
@@ -100,11 +98,11 @@ final class SpanTests: XCTestCase {
let capacity = 4
let a = Array(0..<capacity)
a.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
let span = Span(_unsafeElements: $0)
XCTAssertFalse(span.isEmpty)
let empty = Span(
unsafeElements: .init(rebasing: $0.dropFirst(capacity)), owner: $0
_unsafeElements: .init(rebasing: $0.dropFirst(capacity))
)
XCTAssertTrue(empty.isEmpty)
}
@@ -114,8 +112,8 @@ final class SpanTests: XCTestCase {
let count = 4
let array = Array(0..<count)
array.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
let raw = span.rawSpan
let span = Span(_unsafeElements: $0)
let raw = span._unsafeRawSpan
XCTAssertEqual(raw.byteCount, span.count*MemoryLayout<Int>.stride)
}
}
@@ -124,7 +122,7 @@ final class SpanTests: XCTestCase {
let capacity = 4
let a = Array(0..<capacity)
a.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
let span = Span(_unsafeElements: $0)
XCTAssertEqual(span.count, span._indices.count)
var i = 0
@@ -144,16 +142,16 @@ final class SpanTests: XCTestCase {
$1 = $0.count
}
a.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
let span = Span(_unsafeElements: $0)
XCTAssertEqual(span._elementsEqual(span.extracting(first: 1)), false)
XCTAssertEqual(span.extracting(0..<0)._elementsEqual(span.extracting(last: 0)), true)
XCTAssertEqual(span._elementsEqual(span._extracting(first: 1)), false)
XCTAssertEqual(span._extracting(0..<0)._elementsEqual(span._extracting(last: 0)), true)
XCTAssertEqual(span._elementsEqual(span), true)
XCTAssertEqual(span.extracting(0..<3)._elementsEqual(span.extracting(last: 3)), false)
XCTAssertEqual(span._extracting(0..<3)._elementsEqual(span._extracting(last: 3)), false)
let copy = span.withUnsafeBufferPointer(Array.init)
copy.withUnsafeBufferPointer {
let spanOfCopy = Span(unsafeElements: $0, owner: $0)
let spanOfCopy = Span(_unsafeElements: $0)
XCTAssertTrue(span._elementsEqual(spanOfCopy))
}
}
@@ -163,10 +161,10 @@ final class SpanTests: XCTestCase {
let capacity = 4
let a = Array(0..<capacity)
a.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
let span = Span(_unsafeElements: $0)
XCTAssertEqual(span._elementsEqual(a), true)
XCTAssertEqual(span.extracting(0..<0)._elementsEqual([]), true)
XCTAssertEqual(span._extracting(0..<0)._elementsEqual([]), true)
XCTAssertEqual(span._elementsEqual(a.dropLast()), false)
}
}
@@ -175,11 +173,11 @@ final class SpanTests: XCTestCase {
let capacity = 4
let a = Array(0..<capacity)
a.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
let span = Span(_unsafeElements: $0)
let s = AnySequence(a)
XCTAssertEqual(span._elementsEqual(s), true)
XCTAssertEqual(span.extracting(0..<(capacity-1))._elementsEqual(s), false)
XCTAssertEqual(span._extracting(0..<(capacity-1))._elementsEqual(s), false)
XCTAssertEqual(span._elementsEqual(s.dropFirst()), false)
}
}
@@ -188,11 +186,11 @@ final class SpanTests: XCTestCase {
let capacity = 4
let a = (0..<capacity).map(String.init)
a.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
XCTAssertTrue(span._elementsEqual(span.extracting(0..<span.count)))
XCTAssertTrue(span._elementsEqual(span.extracting(0...)))
XCTAssertTrue(span._elementsEqual(span.extracting(uncheckedBounds: ..<span.count)))
XCTAssertTrue(span._elementsEqual(span.extracting(...)))
let span = Span(_unsafeElements: $0)
XCTAssertTrue(span._elementsEqual(span._extracting(0..<span.count)))
XCTAssertTrue(span._elementsEqual(span._extracting(0...)))
XCTAssertTrue(span._elementsEqual(span._extracting(uncheckedBounds: ..<span.count)))
XCTAssertTrue(span._elementsEqual(span._extracting(...)))
}
}
@@ -200,28 +198,28 @@ final class SpanTests: XCTestCase {
let capacity = 4
let a = Array(0..<capacity)
a.withUnsafeBufferPointer {
let v = Span(unsafeElements: $0, owner: $0)
XCTAssertTrue(v._elementsEqual(v.extracting(0..<v.count)))
XCTAssertTrue(v._elementsEqual(v.extracting(0...)))
XCTAssertTrue(v._elementsEqual(v.extracting(uncheckedBounds: ..<v.count)))
XCTAssertTrue(v._elementsEqual(v.extracting(...)))
let v = Span(_unsafeElements: $0)
XCTAssertTrue(v._elementsEqual(v._extracting(0..<v.count)))
XCTAssertTrue(v._elementsEqual(v._extracting(0...)))
XCTAssertTrue(v._elementsEqual(v._extracting(uncheckedBounds: ..<v.count)))
XCTAssertTrue(v._elementsEqual(v._extracting(...)))
}
}
func testOffsetSubscript() {
func testElementSubscript() {
let capacity = 4
let a = (0..<capacity).map(String.init)
a.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
let span = Span(_unsafeElements: $0)
XCTAssertEqual(span[3], String(3))
}
}
func testOffsetSubscriptBitwiseCopyable() {
func testElementSubscriptBitwiseCopyable() {
let capacity = 4
let a = Array(0..<capacity)
a.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
let span = Span(_unsafeElements: $0)
XCTAssertEqual(span[3], 3)
}
}
@@ -230,10 +228,10 @@ final class SpanTests: XCTestCase {
let capacity = 4
let a = (0..<capacity).map(String.init)
a.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
XCTAssertTrue(span._elementsEqual(span.extracting(0..<capacity)))
XCTAssertTrue(span._elementsEqual(span.extracting(0...)))
XCTAssertTrue(span._elementsEqual(span.extracting(uncheckedBounds: ..<capacity)))
let span = Span(_unsafeElements: $0)
XCTAssertTrue(span._elementsEqual(span._extracting(0..<capacity)))
XCTAssertTrue(span._elementsEqual(span._extracting(0...)))
XCTAssertTrue(span._elementsEqual(span._extracting(uncheckedBounds: ..<capacity)))
}
}
@@ -241,11 +239,11 @@ final class SpanTests: XCTestCase {
let r = Int.random(in: 0..<1000)
let a = [r]
a.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
let span = Span(_unsafeElements: $0)
XCTAssertEqual(span.first, r)
XCTAssertEqual(span.last, r)
let emptySpan = span.extracting(0..<0)
let emptySpan = span._extracting(0..<0)
XCTAssertEqual(emptySpan.first, nil)
XCTAssertEqual(emptySpan.last, nil)
}
@@ -255,20 +253,20 @@ final class SpanTests: XCTestCase {
let capacity = 4
let a = Array(0..<capacity)
a.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
let span = Span(_unsafeElements: $0)
XCTAssertEqual(span.count, capacity)
XCTAssertEqual(span.extracting(first: 1).last, 0)
XCTAssertEqual(span.extracting(first: capacity).last, capacity-1)
XCTAssertEqual(span.extracting(droppingLast: capacity).last, nil)
XCTAssertEqual(span.extracting(droppingLast: 1).last, capacity-2)
XCTAssertEqual(span._extracting(first: 1).last, 0)
XCTAssertEqual(span._extracting(first: capacity).last, capacity-1)
XCTAssertEqual(span._extracting(droppingLast: capacity).last, nil)
XCTAssertEqual(span._extracting(droppingLast: 1).last, capacity-2)
}
do {
let b = UnsafeBufferPointer<Int>(start: nil, count: 0)
let span = Span(unsafeElements: b, owner: b)
let span = Span(_unsafeElements: b)
XCTAssertEqual(span.count, b.count)
XCTAssertEqual(span.extracting(first: 1).count, b.count)
XCTAssertEqual(span.extracting(droppingLast: 1).count, b.count)
XCTAssertEqual(span._extracting(first: 1).count, b.count)
XCTAssertEqual(span._extracting(droppingLast: 1).count, b.count)
}
}
@@ -276,21 +274,21 @@ final class SpanTests: XCTestCase {
let capacity = 4
let a = Array(0..<capacity)
a.withUnsafeBufferPointer {
let span = Span<Int>(unsafeElements: $0, owner: $0)
let span = Span<Int>(_unsafeElements: $0)
XCTAssertEqual(span.count, capacity)
XCTAssertEqual(span.extracting(last: capacity).first, 0)
XCTAssertEqual(span.extracting(last: capacity-1).first, 1)
XCTAssertEqual(span.extracting(last: 1).first, capacity-1)
XCTAssertEqual(span.extracting(droppingFirst: capacity).first, nil)
XCTAssertEqual(span.extracting(droppingFirst: 1).first, 1)
XCTAssertEqual(span._extracting(last: capacity).first, 0)
XCTAssertEqual(span._extracting(last: capacity-1).first, 1)
XCTAssertEqual(span._extracting(last: 1).first, capacity-1)
XCTAssertEqual(span._extracting(droppingFirst: capacity).first, nil)
XCTAssertEqual(span._extracting(droppingFirst: 1).first, 1)
}
do {
let b = UnsafeBufferPointer<Int>(start: nil, count: 0)
let span = Span(unsafeElements: b, owner: b)
let span = Span(_unsafeElements: b)
XCTAssertEqual(span.count, b.count)
XCTAssertEqual(span.extracting(last: 1).count, b.count)
XCTAssertEqual(span.extracting(droppingFirst: 1).count, b.count)
XCTAssertEqual(span._extracting(last: 1).count, b.count)
XCTAssertEqual(span._extracting(droppingFirst: 1).count, b.count)
} }
public func testWithUnsafeBytes() {
@@ -298,7 +296,7 @@ final class SpanTests: XCTestCase {
let a = Array(0..<capacity)
a.withUnsafeBufferPointer {
ub in
let span = Span(unsafeElements: ub, owner: ub)
let span = Span(_unsafeElements: ub)
span.withUnsafeBytes {
let i = Int.random(in: 0..<$0.count)
@@ -317,7 +315,7 @@ final class SpanTests: XCTestCase {
let a = Array(0..<capacity)
a.withUnsafeBufferPointer {
ub in
let span = Span(unsafeElements: ub, owner: ub)
let span = Span(_unsafeElements: ub)
span.withUnsafeBytes {
let i = Int.random(in: 0..<$0.count)
@@ -332,7 +330,8 @@ final class SpanTests: XCTestCase {
let emptyBuffer = UnsafeBufferPointer(rebasing: ub[0..<0])
XCTAssertEqual(emptyBuffer.baseAddress, ub.baseAddress)
let empty = Span(unsafeElements: emptyBuffer, owner: ub)
let empty = Span(_unsafeElements: emptyBuffer)
XCTAssertEqual(empty.count, 0)
empty.withUnsafeBufferPointer {
XCTAssertNil($0.baseAddress)
}
@@ -343,8 +342,8 @@ final class SpanTests: XCTestCase {
let capacity = 8
let a = Array(0..<capacity)
var span = a.storage
let prefix = span.extracting(0..<2)
span = span.extracting(1...)
let prefix = span._extracting(0..<2)
span = span._extracting(1...)
XCTAssertEqual(span.count, capacity-1)
XCTAssertEqual(prefix.count, 2)
}
@@ -353,58 +352,106 @@ final class SpanTests: XCTestCase {
let capacity = 8
let a = Array(0..<capacity)
var span = a.storage
let prefix = span.extracting(0..<2)
span = span.extracting(1...)
let prefix = span._extracting(0..<2)
span = span._extracting(1...)
XCTAssertEqual(span.count, capacity-1)
XCTAssertEqual(prefix.count, 2)
}
func testContainment() {
func testIdentity() {
let b = UnsafeMutableBufferPointer<Int>.allocate(capacity: 8)
_ = b.initialize(fromContentsOf: 0..<8)
defer { b.deallocate() }
let span = Span(unsafeElements: .init(b), owner: b)
let subSpan = span.extracting(last: 2)
let emptySpan = span.extracting(first: 0)
let fakeSpan = Span(
unsafeStart: b.baseAddress!.advanced(by: 8), count: 8, owner: b
)
let nilSpan = Span<Int>(
unsafeElements: UnsafeBufferPointer(start: nil, count: 0), owner: b
)
let span = Span(_unsafeElements: b)
let pre = span._extracting(first: 6)
let suf = span._extracting(last: 6)
XCTAssertTrue(span.contains(subSpan))
XCTAssertFalse(subSpan.contains(span))
XCTAssertTrue(span.contains(emptySpan))
XCTAssertFalse(emptySpan.contains(span))
XCTAssertFalse(span.contains(fakeSpan))
XCTAssertFalse(fakeSpan.contains(span))
XCTAssertTrue(span.contains(nilSpan))
XCTAssertTrue(fakeSpan.contains(nilSpan))
XCTAssertTrue(nilSpan.contains(emptySpan))
XCTAssertFalse(
pre.isIdentical(to: suf)
)
XCTAssertFalse(
pre.isIdentical(to: span)
)
XCTAssertTrue(
pre._extracting(last: 4).isIdentical(to: suf._extracting(first: 4))
)
}
func testOffsets() {
func testIndicesOf() {
let b = UnsafeMutableBufferPointer<Int>.allocate(capacity: 8)
_ = b.initialize(fromContentsOf: 0..<8)
defer { b.deallocate() }
let span = Span(unsafeElements: .init(b), owner: b)
let subSpan = span.extracting(last: 2)
let emptySpan = span.extracting(first: 0)
let span = Span(_unsafeElements: b)
let subSpan1 = span._extracting(first: 6)
let subSpan2 = span._extracting(last: 6)
let emptySpan = span._extracting(first: 0)
/* This isn't relevant until we can support unaligned spans
let unalignedSpan = RawSpan(_unsafeSpan: span)
._extracting(droppingFirst: 6)
._extracting(droppingLast: 2)
.unsafeView(as: Int.self)
*/
let nilSpan = Span<Int>(
unsafeElements: UnsafeBufferPointer(start: nil, count: 0), owner: b
_unsafeElements: UnsafeBufferPointer(start: nil, count: 0)
)
var bounds: Range<Int>
bounds = span.offsets(of: subSpan)
XCTAssertEqual(bounds, span._indices.suffix(2))
bounds = span.offsets(of: emptySpan)
XCTAssertEqual(bounds, span._indices.prefix(0))
bounds = span.offsets(of: nilSpan)
XCTAssertEqual(bounds, 0..<0)
bounds = nilSpan.offsets(of: emptySpan)
var bounds: Range<Int>?
bounds = span.indices(of: subSpan1)
XCTAssertEqual(bounds, span._indices.prefix(6))
bounds = span.indices(of: subSpan2)
XCTAssertEqual(bounds, span._indices.suffix(6))
bounds = subSpan2.indices(of: subSpan1)
XCTAssertNil(bounds)
bounds = subSpan1.indices(of: subSpan2)
XCTAssertNil(bounds)
bounds = subSpan2.indices(of: span)
XCTAssertNil(bounds)
bounds = nilSpan.indices(of: emptySpan)
XCTAssertNil(bounds)
bounds = span.indices(of: nilSpan)
XCTAssertNil(bounds)
bounds = nilSpan.indices(of: nilSpan)
XCTAssertEqual(bounds, 0..<0)
}
func testSpanIterator() {
class C {
let id: Int
init(id: Int) { self.id = id }
}
let b = UnsafeMutableBufferPointer<C>.allocate(capacity: 8)
_ = b.initialize(fromContentsOf: (0..<8).map(C.init(id:)))
defer {
b.deinitialize()
b.deallocate()
}
let span = Span(_unsafeElements: b)
var iterator = Span.Iterator(from: span)
var i = 0
while let c = iterator.next() {
XCTAssertEqual(i, c.id)
i += 1
}
}
func testTypeErasedSpanOfBitwiseCopyable() {
let b = UnsafeMutableRawBufferPointer.allocate(byteCount: 64, alignment: 8)
defer { b.deallocate() }
let initialized = b.initializeMemory(as: UInt8.self, fromContentsOf: 0..<64)
XCTAssertEqual(initialized.count, 64)
defer { initialized.deinitialize() }
func test<T>(_ span: Span<T>) -> T {
span[0]
}
// let span = Span<Int32>(_unsafeBytes: b.dropFirst().dropLast(7))
let span = Span<Int32>(_unsafeBytes: b.dropFirst(4))
let first = test(span)
XCTAssertEqual(first, 0x07060504)
}
}
@@ -0,0 +1,53 @@
//===--- StdlibOutputSpanExtensionTests.swift -----------------------------===//
//
// This source file is part of the Swift.org 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import XCTest
import Foundation
import Future
final class OutputBufferUsageTests: XCTestCase {
func testArrayInitializationExample() {
var array: [UInt8]
array = Array(capacity: 32, initializingWith: { output in
for i in 0..<(output.capacity/2) {
output.appendElement(UInt8(clamping: i))
}
})
XCTAssertEqual(array.count, 16)
XCTAssert(array.elementsEqual(0..<16))
XCTAssertGreaterThanOrEqual(array.capacity, 32)
}
func testDataInitializationExample() {
var data: Data
data = Data(capacity: 32, initializingWith: { output in
for i in 0..<(output.capacity/2) {
output.appendElement(UInt8(clamping: i))
}
})
XCTAssertEqual(data.count, 16)
XCTAssert(data.elementsEqual(0..<16))
}
func testStringInitializationExample() {
var string: String
let c = UInt8(ascii: "A")
string = String(utf8Capacity: 32, initializingWith: { output in
for i in 0..<(output.capacity/2) {
output.appendElement(c + UInt8(clamping: i))
}
})
XCTAssertEqual(string.utf8.count, 16)
XCTAssert(string.utf8.elementsEqual(c..<(c+16)))
}
}
@@ -0,0 +1,182 @@
//===--- StdlibSpanExtensionTests.swift -----------------------------------===//
//
// This source file is part of the Swift.org 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import XCTest
import Foundation
import Future
enum ErrorForTesting: Error, Equatable { case error, errorToo, errorAsWell }
final class StdlibSpanExtensionTests: XCTestCase {
func testDataSpan() throws {
let a = Data(0..<4)
a.withSpan {
for i in $0._indices {
XCTAssertEqual($0[i], UInt8(i))
}
}
do throws(ErrorForTesting) {
try a.withSpan { _ throws(ErrorForTesting) in throw .error }
} catch {
XCTAssertEqual(error, .error)
}
}
func testDataRawSpan() throws {
let a = Data(0..<4)
a.withBytes {
for i in $0._byteOffsets {
XCTAssertEqual(
$0.unsafeLoad(fromByteOffset: i, as: UInt8.self), UInt8(i)
)
}
}
do throws(ErrorForTesting) {
try a.withBytes { _ throws(ErrorForTesting) in throw .error }
} catch {
XCTAssertEqual(error, .error)
}
}
func testArraySpan() throws {
let a = (0..<4).map(String.init(_:))
do throws(ErrorForTesting) {
a.withSpan {
for i in $0._indices {
XCTAssertEqual($0[i], String(i))
}
}
try a.withSpan { _ throws(ErrorForTesting) in throw .error }
} catch {
XCTAssertEqual(error, .error)
}
}
func testArrayRawSpan() throws {
let c = 4
let a = Array(0..<c)
a.withBytes {
for i in 0..<c {
XCTAssertEqual(
i, $0.unsafeLoad(
fromByteOffset: i*MemoryLayout<Int>.stride, as: Int.self
)
)
}
}
do throws(ErrorForTesting) {
try a.withBytes { _ throws(ErrorForTesting) in throw .error }
} catch {
XCTAssertEqual(error, .error)
}
}
func testContiguousArraySpan() throws {
let a = ContiguousArray((0..<4).map(String.init(_:)))
a.withSpan {
for i in $0._indices {
XCTAssertEqual($0[i], String(i))
}
}
do throws(ErrorForTesting) {
try a.withSpan { _ throws(ErrorForTesting) in throw .error }
} catch {
XCTAssertEqual(error, .error)
}
}
func testContiguousArrayRawSpan() throws {
let c = 4
let a = ContiguousArray(0..<c)
a.withBytes {
for i in 0..<c {
XCTAssertEqual(
i, $0.unsafeLoad(
fromByteOffset: i*MemoryLayout<Int>.stride, as: Int.self
)
)
}
}
XCTAssertThrowsError(try a.withBytes({ _ in throw ErrorForTesting.error }))
}
func testArraySliceSpan() throws {
let a = (0..<7).map(String.init(_:)).prefix(upTo: 4)
print(a.count)
a.withSpan {
print($0._indices)
for i in $0._indices {
print(i)
let v = $0[i]
_ = v
XCTAssertEqual($0[i], String(i))
}
}
do throws(ErrorForTesting) {
try a.withSpan { _ throws(ErrorForTesting) in throw .error }
} catch {
XCTAssertEqual(error, .error)
}
}
func testArraySliceRawSpan() throws {
let c = 4
let a = Array(0..<7).prefix(upTo: c)
a.withBytes {
for i in 0..<c {
XCTAssertEqual(
i, $0.unsafeLoad(
fromByteOffset: i*MemoryLayout<Int>.stride, as: Int.self
)
)
}
}
XCTAssertThrowsError(try a.withBytes({ _ in throw ErrorForTesting.error }))
}
func testCollectionOfOneSpan() throws {
let a = CollectionOfOne("CollectionOfOne is an obscure Collection type.")
a.withSpan {
XCTAssertTrue($0._elementsEqual(a))
}
XCTAssertThrowsError(try a.withSpan({ _ in throw ErrorForTesting.error }))
}
func testCollectionOfOneRawSpan() throws {
let a = CollectionOfOne(Int(UInt8.random(in: 0 ..< .max)))
a.withBytes {
for i in $0._byteOffsets {
let v = $0.unsafeLoad(fromByteOffset: i, as: UInt8.self)
if v != 0 {
XCTAssertEqual(Int(v), a.first)
}
}
}
XCTAssertThrowsError(try a.withBytes({ _ in throw ErrorForTesting.error }))
}
func testUTF8ViewSpan() throws {
let strings: [String] = [
"small",
"Not a small string, if I can count code units correctly.",
NSString("legacy string if I can get it to behave.") as String
]
for s in strings {
s.utf8.withSpan {
XCTAssertEqual($0.count, s.utf8.count)
}
}
let a = strings[0].utf8
XCTAssertThrowsError(try a.withSpan({ _ in throw ErrorForTesting.error }))
}
}
@@ -18,13 +18,13 @@ import _CollectionsTestSupport
#endif
class MeasuringHashable: Hashable {
static var equalityChecks = 0
nonisolated(unsafe) static var equalityChecks = 0
static func == (lhs: MeasuringHashable, rhs: MeasuringHashable) -> Bool {
MeasuringHashable.equalityChecks += 1
return lhs._inner == rhs._inner
}
static var hashChecks = 0
nonisolated(unsafe) static var hashChecks = 0
func hash(into hasher: inout Hasher) {
MeasuringHashable.hashChecks += 1
_inner.hash(into: &hasher)
@@ -20,7 +20,7 @@ public final class TestContext {
internal var _trace: [Entry] = []
// FIXME: This ought to be a thread-local variable.
internal static var _current: TestContext?
nonisolated(unsafe) internal static var _current: TestContext?
public init() {}
}