Copy Span prototype to its own branch

This commit is contained in:
Guillaume Lessard authored and Guillaume Lessard committed 2024-10-06 10:24:54 -07:00
1 parent 6c8dcadca4
commit c290bd3d04
8 files changed
+850 -207

No files matched your search

+3 -7
View File
@@ -55,18 +55,14 @@ var defines: [String] = [
let _sharedSettings: [SwiftSetting] = defines.map { .define($0) } + [
.enableExperimentalFeature("BuiltinModule"),
.enableExperimentalFeature("NonescapableTypes"),
.enableExperimentalFeature("BitwiseCopyable"),
.enableExperimentalFeature("RawLayout"),
.enableExperimentalFeature("SuppressedAssociatedTypes"),
]
let _settings: [SwiftSetting] = _sharedSettings + [
.swiftLanguageMode(.v6),
]
let _testSettings: [SwiftSetting] = _sharedSettings + [
.swiftLanguageMode(.v5),
]
let _settings: [SwiftSetting] = _sharedSettings + []
let _testSettings: [SwiftSetting] = _sharedSettings + []
struct CustomTarget {
enum Kind {
+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
)
}
}
+83 -39
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,13 +45,12 @@ 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
)
}
@@ -70,11 +64,10 @@ 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))
}
/// Unsafely create a `RawSpan` over initialized memory.
@@ -88,14 +81,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>`
@@ -107,8 +153,7 @@ extension RawSpan {
public init<T: BitwiseCopyable>(_ span: borrowing Span<T>) {
self.init(
_unchecked: UnsafeRawPointer(span._start),
byteCount: span.count * MemoryLayout<T>.stride,
owner: span
byteCount: span.count * MemoryLayout<T>.stride
)
}
}
@@ -247,8 +292,7 @@ extension RawSpan {
public func extracting(unchecked bounds: Range<Int>) -> Self {
RawSpan(
_unchecked: _pointer?.advanced(by: bounds.lowerBound),
byteCount: bounds.count,
owner: self
byteCount: bounds.count
)
}
@@ -352,7 +396,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)
}
}
@@ -520,7 +564,7 @@ extension RawSpan {
public 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)
}
/// Returns a span over all but the given number of trailing bytes.
@@ -541,7 +585,7 @@ extension RawSpan {
public 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)
}
/// Returns a span containing the trailing bytes of the span,
@@ -564,7 +608,7 @@ extension RawSpan {
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)
}
/// Returns a span over all but the given number of initial bytes.
@@ -586,7 +630,7 @@ extension RawSpan {
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)
return Self(_unchecked: newStart, byteCount: byteCount&-dc)
}
}
+75 -80
View File
@@ -16,33 +16,37 @@ import Builtin
// contains initialized instances of `Element`.
@frozen
public struct Span<Element: ~Copyable /*& ~Escapable*/>: Copyable, ~Escapable {
@usableFromInline
internal let _buffer: UnsafeBufferPointer<Element>
@usableFromInline let _buffer: UnsafeBufferPointer<Element>
@usableFromInline @inline(__always)
internal var _pointer: UnsafePointer<Element>? { _buffer.baseAddress }
var _pointer: UnsafePointer<Element>? { _buffer.baseAddress }
@usableFromInline @inline(__always)
internal var _start: UnsafePointer<Element> { _pointer.unsafelyUnwrapped }
var _start: UnsafePointer<Element> { _pointer.unsafelyUnwrapped }
// @usableFromInline @inline(__always)
// var _start: UnsafeRawPointer { _pointer.unsafelyUnwrapped }
@usableFromInline @inline(__always)
internal var _count: Int { _buffer.count }
var _count: Int { _buffer.count }
@inlinable @inline(__always)
internal init<Owner: ~Copyable & ~Escapable>(
_unchecked elements: UnsafeBufferPointer<Element>,
owner: borrowing Owner
) {
internal init(
_unchecked elements: UnsafeBufferPointer<Element>
) -> dependsOn(immortal) Self {
_buffer = elements
// _pointer = .init(elements.baseAddress)
// _count = elements.count
}
@inlinable @inline(__always)
internal init<Owner: ~Copyable & ~Escapable>(
@_alwaysEmitIntoClient
internal init(
_unchecked start: UnsafePointer<Element>?,
count: Int,
owner: borrowing Owner
) {
self.init(_unchecked: .init(start: start, count: count), owner: owner)
count: Int
) -> dependsOn(immortal) Self {
self.init(_unchecked: .init(start: start, count: count))
// _pointer = .init(start)
// _count = count
}
}
@@ -68,16 +72,15 @@ 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
) {
@_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)"
)
self.init(_unchecked: buffer, owner: owner)
self.init(_unchecked: buffer)
}
/// Unsafely create a `Span` over initialized memory.
@@ -90,11 +93,10 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
/// - 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)
public init(
_unsafeElements buffer: UnsafeMutableBufferPointer<Element>
) -> dependsOn(immortal) Self {
self.init(_unsafeElements: UnsafeBufferPointer(buffer))
}
/// Unsafely create a `Span` over initialized memory.
@@ -108,18 +110,17 @@ 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
) {
@_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(_unchecked: start, count: count)
}
}
@@ -134,12 +135,11 @@ extension Span where Element: BitwiseCopyable {
/// - 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)
@_alwaysEmitIntoClient
public init(
_unsafeElements buffer: UnsafeBufferPointer<Element>
) -> dependsOn(immortal) Self {
self.init(_unchecked: buffer)
}
/// Unsafely create a `Span` over initialized memory.
@@ -152,11 +152,10 @@ extension Span where Element: BitwiseCopyable {
/// - 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)
public init(
_unsafeElements buffer: UnsafeMutableBufferPointer<Element>
) -> dependsOn(immortal) Self {
self.init(_unsafeElements: UnsafeBufferPointer(buffer))
}
/// Unsafely create a `Span` over initialized memory.
@@ -170,14 +169,13 @@ 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 start: UnsafePointer<Element>,
count: Int,
owner: borrowing Owner
) {
@_alwaysEmitIntoClient
public init(
_unsafeStart start: UnsafePointer<Element>,
count: Int
) -> dependsOn(immortal) Self {
precondition(count >= 0, "Count must not be negative")
self.init(_unchecked: start, count: count, owner: owner)
self.init(_unchecked: start, count: count)
}
/// Unsafely create a `Span` over initialized memory.
@@ -194,19 +192,17 @@ 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
) {
@_alwaysEmitIntoClient
public init(
_unsafeBytes buffer: UnsafeRawBufferPointer
) -> dependsOn(immortal) Self {
let (byteCount, stride) = (buffer.count, MemoryLayout<Element>.stride)
assert(byteCount >= 0, "Count must not be negative")
precondition(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
count: count
)
}
@@ -225,11 +221,10 @@ extension Span where Element: BitwiseCopyable {
/// - owner: a binding whose lifetime must exceed that of
/// the newly created `Span`.
@_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,20 +238,18 @@ 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
) {
@_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
count: count
)
}
}
@@ -459,7 +452,10 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
@inlinable @inline(__always)
public subscript(unchecked position: Int) -> Element {
_read {
yield _start.advanced(by: position).pointee
let element = UnsafeRawPointer(_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
}
}
}
@@ -491,7 +487,7 @@ extension Span where Element: BitwiseCopyable {
@inlinable @inline(__always)
public subscript(unchecked position: Int) -> Element {
get {
let address = UnsafeRawPointer(_start.advanced(by: position))
let address = UnsafeRawPointer(_start).advanced(by: position&*MemoryLayout<Element>.stride)
return address.loadUnaligned(as: Element.self)
}
}
@@ -538,8 +534,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
public func extracting(unchecked bounds: Range<Int>) -> Self {
Span(
_unchecked: _pointer?.advanced(by: bounds.lowerBound),
count: bounds.count,
owner: self
count: bounds.count
)
}
@@ -730,7 +725,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
public 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)
}
/// Returns a span over all but the given number of trailing elements.
@@ -751,7 +746,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
public 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)
}
/// Returns a span containing the final elements of the span,
@@ -774,7 +769,7 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
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)
return Self(_unchecked: newStart, count: newCount)
}
/// Returns a span over all but the given number of initial elements.
@@ -796,6 +791,6 @@ extension Span where Element: ~Copyable /*& ~Escapable*/ {
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)
return Self(_unchecked: newStart, count: count&-droppedCount)
}
}
+431
View File
@@ -0,0 +1,431 @@
//===--- 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)))
}
}
#if false //FIXME: rdar://134382237
import struct Foundation.Data
extension Data {
public func withSpan<E: Error, Result>(
_ body: (_ elements: Span<UInt8>) throws(E) -> Result
) throws(E) -> Result {
let result: Swift.Result<Result, E> = withUnsafeBytes {
do throws(E) {
return .success(try body(Span<UInt8>(_unsafeBytes: $0)))
} catch {
return .failure(error)
}
}
switch result {
case .success(let s): return s
case .failure(let e): throw e
}
}
public func withBytes<E: Error, Result>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result {
let result: Swift.Result<Result, E> = withUnsafeBytes {
do throws(E) {
return .success(try body(RawSpan(_unsafeBytes: $0)))
} catch {
return .failure(error)
}
}
switch result {
case .success(let s): return s
case .failure(let e): throw e
}
}
}
#endif
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)
}
switch consume result {
case .success(let s): return s
case .failure(let e): throw e
}
}
public func withBytes<E: Error, Result>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result where Element: BitwiseCopyable {
let result: Swift.Result<Result, E> = withUnsafeBytes {
do throws(E) {
return .success(try body(RawSpan(_unsafeBytes: $0)))
} catch {
return .failure(error)
}
}
switch result {
case .success(let s): return s
case .failure(let e): throw e
}
}
}
extension ContiguousArray {
public func withSpan<E: Error, Result>(
_ body: (_ elements: Span<Element>) throws(E) -> Result
) throws(E) -> Result {
let result: Swift.Result<Result, E> = withUnsafeBufferPointer {
do throws(E) {
return .success(try body(Span(_unsafeElements: $0)))
} catch {
return .failure(error)
}
}
switch result {
case .success(let s): return s
case .failure(let e): throw e
}
}
}
extension ContiguousArray where Element: BitwiseCopyable {
public func withBytes<E: Error, Result>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result {
let result: Swift.Result<Result, E> = withUnsafeBytes {
do throws(E) {
return .success(try body(RawSpan(_unsafeBytes: $0)))
} catch {
return .failure(error)
}
}
switch result {
case .success(let s): return s
case .failure(let e): throw e
}
}
}
extension ArraySlice {
public func withSpan<E, Result>(
_ body: (_ elements: Span<Element>) throws(E) -> Result
) throws(E) -> Result {
let result: Swift.Result<Result, E> = withUnsafeBufferPointer {
do throws(E) {
let span = Span(_unsafeElements: $0)
print(span._start, span.count)
return .success(try body(span))
} catch {
return .failure(error)
}
}
switch result {
case .success(let s): return s
case .failure(let e): throw e
}
}
}
extension ArraySlice where Element: BitwiseCopyable {
public func withBytes<E: Error, Result>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result {
let result: Swift.Result<Result, E> = withUnsafeBytes {
do throws(E) {
return .success(try body(RawSpan(_unsafeBytes: $0)))
} catch {
return .failure(error)
}
}
switch result {
case .success(let s): return s
case .failure(let e): throw e
}
}
}
extension String.UTF8View {
public func withSpan<E: Error, Result>(
_ body: (_ elements: Span<UTF8.CodeUnit>) throws(E) -> Result
) throws(E) -> Result {
let result: Swift.Result<Result, E>? = withContiguousStorageIfAvailable {
do throws(E) {
return .success(try body(Span(_unsafeElements: $0)))
} catch {
return .failure(error)
}
}
switch result {
case .success(let s)?: return s
case .failure(let e)?: throw e
case nil: return try ContiguousArray(self).withSpan(body)
}
}
public func withBytes<E: Error, Result>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result {
let result: Swift.Result<Result, E>? = withContiguousStorageIfAvailable {
do throws(E) {
return .success(try body(RawSpan(_unsafeElements: $0)))
} catch {
return .failure(error)
}
}
switch result {
case .success(let s)?: return s
case .failure(let e)?: throw e
case nil: return try ContiguousArray(self).withBytes(body)
}
}
}
extension Substring.UTF8View {
public func withSpan<E: Error, Result>(
_ body: (_ elements: Span<UTF8.CodeUnit>) throws(E) -> Result
) throws(E) -> Result {
let result: Swift.Result<Result, E>? = withContiguousStorageIfAvailable {
do throws(E) {
return .success(try body(Span(_unsafeElements: $0)))
} catch {
return .failure(error)
}
}
switch result {
case .success(let s)?: return s
case .failure(let e)?: throw e
case nil: return try ContiguousArray(self).withSpan(body)
}
}
public func withBytes<E: Error, Result>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result {
let result: Swift.Result<Result, E>? = withContiguousStorageIfAvailable {
do throws(E) {
return .success(try body(RawSpan(_unsafeElements: $0)))
} catch {
return .failure(error)
}
}
switch result {
case .success(let s)?: return s
case .failure(let e)?: throw e
case nil: return try ContiguousArray(self).withBytes(body)
}
}
}
extension CollectionOfOne {
public func withSpan<E: Error, Result>(
_ body: (_ elements: Span<Element>) throws(E) -> Result
) throws(E) -> Result {
var collection = self
let result: Swift.Result<Result, E> = withUnsafePointer(to: &collection) {
$0.withMemoryRebound(to: Element.self, capacity: 1) {
do throws(E) {
return .success(try body(Span(_unsafeStart: $0, count: 1)))
} catch {
return .failure(error)
}
}
}
switch result {
case .success(let s): return s
case .failure(let e): throw e
}
}
}
extension CollectionOfOne where Element: BitwiseCopyable {
public func withBytes<E: Error, Result>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result {
var collection = self
let r: Swift.Result<Result, E> = Swift.withUnsafeBytes(of: &collection) {
do throws(E) {
return .success(try body(RawSpan(_unsafeBytes: $0)))
} catch {
return .failure(error)
}
}
switch r {
case .success(let s): return s
case .failure(let e): throw e
}
}
}
extension KeyValuePairs {
public func withSpan<E: Error, Result>(
_ body: (
_ elements: Span<(key: Key, value: Value)>
) throws(E) -> Result
) throws(E) -> Result {
try Array(self).withSpan(body)
}
}
extension KeyValuePairs where Element: BitwiseCopyable {
public func withBytes<E: Error, Result>(
_ body: (_ bytes: RawSpan) throws(E) -> Result
) throws(E) -> Result {
try Array(self).withBytes(body)
}
}
extension Span where Element: ~Copyable /*& ~Escapable*/ {
public consuming func withSpan<E: Error, Result>(
_ 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>(
_ body: (_ elements: RawSpan) throws(E) -> Result
) throws(E) -> Result {
try body(RawSpan(self))
}
}
//TODO: extend SIMD vectors with `withSpan` and with `withBytes`.
+24 -29
View File
@@ -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,7 +97,7 @@ 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)
XCTAssertEqual(u0 & 0xff, 2)
@@ -115,7 +113,7 @@ final class RawSpanTests: XCTestCase {
let capacity = 4
let b = (0..<capacity).map(Int8.init)
b.withUnsafeBytes {
let span = RawSpan(unsafeBytes: $0, owner: $0)
let span = RawSpan(_unsafeBytes: $0)
let sub1 = span.extracting(0..<2)
let sub2 = span.extracting(..<2)
let sub3 = span.extracting(...)
@@ -136,7 +134,7 @@ final class RawSpanTests: XCTestCase {
let capacity = 32
let b = (0..<capacity).map(UInt8.init)
b.withUnsafeBytes {
let span = RawSpan(unsafeBytes: $0, owner: $0)
let span = RawSpan(_unsafeBytes: $0)
let prefix = span.extracting(0..<8)
let beyond = prefix.extracting(unchecked: 16..<24)
XCTAssertEqual(beyond.byteCount, 8)
@@ -154,12 +152,9 @@ final class RawSpanTests: XCTestCase {
}
}
//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 +164,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,7 +180,7 @@ 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(
@@ -205,7 +200,7 @@ 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)
@@ -216,7 +211,7 @@ 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)
@@ -227,7 +222,7 @@ 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(last: 1).byteCount, b.count)
XCTAssertEqual(span.extracting(droppingFirst: 1).byteCount, b.count)
@@ -248,14 +243,14 @@ final class RawSpanTests: XCTestCase {
let b = UnsafeMutableRawBufferPointer.allocate(byteCount: 8, alignment: 8)
defer { b.deallocate() }
let span = RawSpan(unsafeBytes: b, owner: b)
let span = RawSpan(_unsafeBytes: 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
_unsafeStart: b.baseAddress!.advanced(by: 8), byteCount: 8
)
let nilSpan = RawSpan(
unsafeBytes: UnsafeRawBufferPointer(start: nil, count: 0), owner: b
_unsafeBytes: UnsafeRawBufferPointer(start: nil, count: 0)
)
XCTAssertTrue(span.contains(subSpan))
@@ -273,11 +268,11 @@ final class RawSpanTests: XCTestCase {
let b = UnsafeMutableRawBufferPointer.allocate(byteCount: 8, alignment: 8)
defer { b.deallocate() }
let span = RawSpan(unsafeBytes: b, owner: b)
let span = RawSpan(_unsafeBytes: b)
let subSpan = span.extracting(last: 2)
let emptySpan = span.extracting(first: 0)
let nilSpan = RawSpan(
unsafeBytes: UnsafeRawBufferPointer(start: nil, count: 0), owner: b
_unsafeBytes: UnsafeRawBufferPointer(start: nil, count: 0)
)
var bounds: Range<Int>
+41 -43
View File
@@ -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,7 +112,7 @@ final class SpanTests: XCTestCase {
let count = 4
let array = Array(0..<count)
array.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
let span = Span(_unsafeElements: $0)
let raw = span.rawSpan
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,7 +142,7 @@ 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)
@@ -153,7 +151,7 @@ final class SpanTests: XCTestCase {
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,7 +161,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._elementsEqual(a), true)
XCTAssertEqual(span.extracting(0..<0)._elementsEqual([]), true)
@@ -175,7 +173,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)
let s = AnySequence(a)
XCTAssertEqual(span._elementsEqual(s), true)
@@ -188,7 +186,7 @@ final class SpanTests: XCTestCase {
let capacity = 4
let a = (0..<capacity).map(String.init)
a.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
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)))
@@ -200,7 +198,7 @@ final class SpanTests: XCTestCase {
let capacity = 4
let a = Array(0..<capacity)
a.withUnsafeBufferPointer {
let v = Span(unsafeElements: $0, owner: $0)
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)))
@@ -212,7 +210,7 @@ final class SpanTests: XCTestCase {
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))
}
}
@@ -221,7 +219,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[3], 3)
}
}
@@ -230,7 +228,7 @@ final class SpanTests: XCTestCase {
let capacity = 4
let a = (0..<capacity).map(String.init)
a.withUnsafeBufferPointer {
let span = Span(unsafeElements: $0, owner: $0)
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,7 +239,7 @@ 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)
@@ -255,7 +253,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, capacity)
XCTAssertEqual(span.extracting(first: 1).last, 0)
XCTAssertEqual(span.extracting(first: capacity).last, capacity-1)
@@ -265,7 +263,7 @@ final class SpanTests: XCTestCase {
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)
@@ -276,7 +274,7 @@ 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)
@@ -287,7 +285,7 @@ final class SpanTests: XCTestCase {
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)
@@ -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,7 @@ 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)
empty.withUnsafeBufferPointer {
XCTAssertNil($0.baseAddress)
}
@@ -364,14 +362,14 @@ final class SpanTests: XCTestCase {
_ = b.initialize(fromContentsOf: 0..<8)
defer { b.deallocate() }
let span = Span(unsafeElements: .init(b), owner: b)
let span = Span(_unsafeElements: 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
_unsafeStart: b.baseAddress!.advanced(by: 8), count: 8
)
let nilSpan = Span<Int>(
unsafeElements: UnsafeBufferPointer(start: nil, count: 0), owner: b
_unsafeElements: UnsafeBufferPointer(start: nil, count: 0)
)
XCTAssertTrue(span.contains(subSpan))
@@ -390,11 +388,11 @@ final class SpanTests: XCTestCase {
_ = b.initialize(fromContentsOf: 0..<8)
defer { b.deallocate() }
let span = Span(unsafeElements: .init(b), owner: b)
let span = Span(_unsafeElements: b)
let subSpan = span.extracting(last: 2)
let emptySpan = span.extracting(first: 0)
let nilSpan = Span<Int>(
unsafeElements: UnsafeBufferPointer(start: nil, count: 0), owner: b
_unsafeElements: UnsafeBufferPointer(start: nil, count: 0)
)
var bounds: Range<Int>
@@ -0,0 +1,184 @@
//===--- 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 Future
enum ErrorForTesting: Error, Equatable { case error, errorToo, errorAsWell }
final class StdlibSpanExtensionTests: XCTestCase {
#if false //FIXME: rdar://134382237 -- nightly toolchain cannot `import Darwin`
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)
}
}
#endif
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.count)
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 }))
}
}