Conform Unicode.Scalar to Strideable
- Status: Pitch
- Implementation: swiftlang/swift#84258
Introduction
This proposal extends Unicode.Scalar so that it conforms to Strideable.
Motivation
In the standard library, only fixed-width integers (and unsafe pointers) can be used in "countable" ranges.
let codePoints: ClosedRange<UInt32> = 0 ... 0x10FFFF
let unicodeScalars: ClosedRange<Unicode.Scalar> = "\0" ... "\u{10FFFF}"
codePoints.count //-> 1_114_112
unicodeScalars.count //-> ERROR:
// referencing property 'count' on 'ClosedRange' requires
// that 'Unicode.Scalar' conform to 'Strideable'; and also
// that 'Unicode.Scalar.Stride' conform to 'SignedInteger'
There are generic CountableRange and CountableClosedRange type aliases with the same constraints.
Proposed solution
If the standard library extends Unicode.Scalar so that it conforms to Strideable, then ranges of Unicode scalar values will have access to sequence and collection APIs.
let codePoints: ClosedRange<UInt32> = 0 ... 0x10FFFF
let unicodeScalars: ClosedRange<Unicode.Scalar> = "\0" ... "\u{10FFFF}"
codePoints.count //-> 1_114_112
unicodeScalars.count //-> 1_112_064
Notice that there are 2048 fewer Unicode scalar values, because the Surrogates Area is excluded.
Detailed design
The standard library will implement the following Strideable requirements (with suitable @available attributes).
extension Unicode.Scalar: Strideable {
public typealias Stride = Int
public func distance(to other: Self) -> Stride
public func advanced(by n: Stride) -> Self
public static func _step(
after current: (index: Int?, value: Self),
from start: Self,
by distance: Stride
) -> (index: Int?, value: Self)
}
The distance between "\u{D7FF}" and "\u{E000}" will be ±1, because the Surrogates Area is excluded.
The hidden _step(after:from:by:) requirement is used by the stride(from:to:by:) and stride(from:through:by:) APIs.
Source compatibility
Existing clients might have incompatible retroactive conformances.
ABI compatibility
This proposal is purely an extension of the ABI of the standard library.
Implications on adoption
A new version of the standard library will be required.