Removed some warnings (#12753)

This commit is contained in:
Ben Cohen
2017-11-30 15:12:56 -08:00
committed by GitHub
parent 5ace363dbc
commit dcab9493ae
20 changed files with 571 additions and 553 deletions

View File

@@ -12,22 +12,15 @@
/// A fixed-width integer that is twice the size of its base type.
@_fixed_layout // FIXME(sil-serialize-all)
public struct DoubleWidth<Base : FixedWidthInteger> :
FixedWidthInteger, _ExpressibleByBuiltinIntegerLiteral
where Base.Words : Collection, Base.Magnitude.Words : Collection {
public struct DoubleWidth<Base : FixedWidthInteger> : _ExpressibleByBuiltinIntegerLiteral
where Base.Words : Collection, Base.Magnitude.Words : Collection {
public typealias High = Base
public typealias Low = Base.Magnitude
@_versioned // FIXME(sil-serialize-all)
internal var _storage: (high: Base, low: Base.Magnitude)
@_inlineable // FIXME(sil-serialize-all)
public // @testable
init(_ _value: (High, Low)) {
self._storage = (high: _value.0, low: _value.1)
}
@_inlineable // FIXME(sil-serialize-all)
public var high: High {
return _storage.high
@@ -38,32 +31,19 @@ public struct DoubleWidth<Base : FixedWidthInteger> :
return _storage.low
}
// Numeric
//
@_inlineable // FIXME(sil-serialize-all)
public // @testable
init(_ _value: (High, Low)) {
self._storage = (high: _value.0, low: _value.1)
}
@_inlineable // FIXME(sil-serialize-all)
public init() {
self.init((0, 0))
}
}
// BinaryInteger
//
@_inlineable // FIXME(sil-serialize-all)
public var magnitude: DoubleWidth<Low> {
if Base.isSigned && _storage.high < (0 as High) {
return self == .min
? DoubleWidth.max.magnitude &+ 1
: (0 - self).magnitude
}
return DoubleWidth<Low>((
_storage.high.magnitude, _storage.low.magnitude))
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(_ _magnitude: Magnitude) {
self.init((High(_magnitude._storage.high), _magnitude._storage.low))
}
extension DoubleWidth: Comparable {
@_inlineable // FIXME(sil-serialize-all)
public static func ==(lhs: DoubleWidth, rhs: DoubleWidth) -> Bool {
return (lhs._storage.high == rhs._storage.high) &&
@@ -80,6 +60,28 @@ public struct DoubleWidth<Base : FixedWidthInteger> :
}
return lhs._storage.low < rhs._storage.low
}
}
extension DoubleWidth: Numeric {
public typealias Magnitude = DoubleWidth<Low>
@_inlineable // FIXME(sil-serialize-all)
public var magnitude: DoubleWidth<Low> {
if Base.isSigned && _storage.high < (0 as High) {
return self == .min
? DoubleWidth.max.magnitude &+ 1
: (0 - self).magnitude
}
return DoubleWidth<Low>((
_storage.high.magnitude, _storage.low.magnitude))
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal init(_ _magnitude: Magnitude) {
self.init((High(_magnitude._storage.high), _magnitude._storage.low))
}
@_inlineable // FIXME(sil-serialize-all)
public init<T : BinaryInteger>(_ source: T) {
@@ -112,7 +114,9 @@ public struct DoubleWidth<Base : FixedWidthInteger> :
self.init((high, low))
}
}
}
extension DoubleWidth {
@_inlineable // FIXME(sil-serialize-all)
public init<T : BinaryFloatingPoint>(_ source: T) {
fatalError()
@@ -177,7 +181,9 @@ public struct DoubleWidth<Base : FixedWidthInteger> :
self.init(exactly: integerPart)
}
}
}
extension DoubleWidth: FixedWidthInteger {
@_fixed_layout // FIXME(sil-serialize-all)
public struct Words : Collection {
public enum _IndexValue {

View File

@@ -455,16 +455,15 @@ internal struct _UnmanagedAnyObjectArray {
/// same copy-on-write optimization that is used when two instances of `Set`
/// share buffer.
@_fixed_layout
public struct Set<Element : Hashable> :
SetAlgebra, Hashable, Collection, ExpressibleByArrayLiteral {
internal typealias _Self = Set<Element>
public struct Set<Element : Hashable> {
internal typealias _VariantBuffer = _VariantSetBuffer<Element>
internal typealias _NativeBuffer = _NativeSetBuffer<Element>
@_versioned
internal var _variantBuffer: _VariantBuffer
}
extension Set {
/// Creates a new, empty set with at least the specified number of elements'
/// worth of buffer.
///
@@ -511,31 +510,45 @@ public struct Set<Element : Hashable> :
_CocoaSetBuffer(cocoaSet: _immutableCocoaSet))
}
#endif
}
/// The starting position for iterating members of the set.
extension Set : ExpressibleByArrayLiteral {
//
// `ExpressibleByArrayLiteral` conformance
//
/// Creates a set containing the elements of the given array literal.
///
/// If the set is empty, `startIndex` is equal to `endIndex`.
@_inlineable // FIXME(sil-serialize-all)
public var startIndex: Index {
return _variantBuffer.startIndex
}
/// The "past the end" position for the set---that is, the position one
/// greater than the last valid subscript argument.
/// Do not call this initializer directly. It is used by the compiler when
/// you use an array literal. Instead, create a new set using an array
/// literal as its value by enclosing a comma-separated list of values in
/// square brackets. You can use an array literal anywhere a set is expected
/// by the type context.
///
/// If the set is empty, `endIndex` is equal to `startIndex`.
/// Here, a set of strings is created from an array literal holding only
/// strings.
///
/// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
/// if ingredients.isSuperset(of: ["sugar", "salt"]) {
/// print("Whatever it is, it's bound to be delicious!")
/// }
/// // Prints "Whatever it is, it's bound to be delicious!"
///
/// - Parameter elements: A variadic list of elements of the new set.
@_inlineable // FIXME(sil-serialize-all)
public var endIndex: Index {
return _variantBuffer.endIndex
public init(arrayLiteral elements: Element...) {
self.init(_nativeBuffer: _NativeSetBuffer.fromArray(elements))
}
}
extension Set : Sequence {
/// Returns an iterator over the members of the set.
@_inlineable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
return _variantBuffer.index(after: i)
@inline(__always)
public func makeIterator() -> SetIterator<Element> {
return _variantBuffer.makeIterator()
}
// APINAMING: complexity docs are broadly missing in this file.
/// Returns a Boolean value that indicates whether the given element exists
/// in the set.
///
@@ -558,6 +571,79 @@ public struct Set<Element : Hashable> :
return _variantBuffer.maybeGet(member) != nil
}
@_inlineable // FIXME(sil-serialize-all)
public func _customContainsEquatableElement(_ member: Element) -> Bool? {
return contains(member)
}
}
// This is not quite Sequence.filter, because that returns [Element], not Self
// (RangeReplaceableCollection.filter returns Self, but Set isn't an RRC)
extension Set {
/// Returns a new set containing the elements of the set that satisfy the
/// given predicate.
///
/// In this example, `filter(_:)` is used to include only names shorter than
/// five characters.
///
/// let cast: Set = ["Vivien", "Marlon", "Kim", "Karl"]
/// let shortNames = cast.filter { $0.count < 5 }
///
/// shortNames.isSubset(of: cast)
/// // true
/// shortNames.contains("Vivien")
/// // false
///
/// - Parameter isIncluded: A closure that takes an element as its argument
/// and returns a Boolean value indicating whether the element should be
/// included in the returned set.
/// - Returns: A set of the elements that `isIncluded` allows.
@_inlineable
@available(swift, introduced: 4.0)
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> Set {
var result = Set()
for element in self {
if try isIncluded(element) {
result.insert(element)
}
}
return result
}
}
extension Set : Collection {
/// The starting position for iterating members of the set.
///
/// If the set is empty, `startIndex` is equal to `endIndex`.
@_inlineable // FIXME(sil-serialize-all)
public var startIndex: Index {
return _variantBuffer.startIndex
}
/// The "past the end" position for the set---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the set is empty, `endIndex` is equal to `startIndex`.
@_inlineable // FIXME(sil-serialize-all)
public var endIndex: Index {
return _variantBuffer.endIndex
}
/// Accesses the member at the given position.
@_inlineable // FIXME(sil-serialize-all)
public subscript(position: Index) -> Element {
return _variantBuffer.assertingGet(position)
}
@_inlineable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
return _variantBuffer.index(after: i)
}
// APINAMING: complexity docs are broadly missing in this file.
/// Returns the index of the given element in the set, or `nil` if the
/// element is not a member of the set.
///
@@ -569,6 +655,149 @@ public struct Set<Element : Hashable> :
return _variantBuffer.index(forKey: member)
}
@_inlineable // FIXME(sil-serialize-all)
public func _customIndexOfEquatableElement(
_ member: Element
) -> Index?? {
return Optional(index(of: member))
}
/// The number of elements in the set.
///
/// - Complexity: O(1).
@_inlineable // FIXME(sil-serialize-all)
public var count: Int {
return _variantBuffer.count
}
/// A Boolean value that indicates whether the set is empty.
@_inlineable // FIXME(sil-serialize-all)
public var isEmpty: Bool {
return count == 0
}
/// The first element of the set.
///
/// The first element of the set is not necessarily the first element added
/// to the set. Don't expect any particular ordering of set elements.
///
/// If the set is empty, the value of this property is `nil`.
@_inlineable // FIXME(sil-serialize-all)
public var first: Element? {
return count > 0 ? self[startIndex] : nil
}
}
/// Check for both subset and equality relationship between
/// a set and some sequence (which may itself be a `Set`).
///
/// (isSubset: lhs ⊂ rhs, isEqual: lhs ⊂ rhs and |lhs| = |rhs|)
@_inlineable
@_versioned
internal func _compareSets<Element>(_ lhs: Set<Element>, _ rhs: Set<Element>)
-> (isSubset: Bool, isEqual: Bool) {
// FIXME(performance): performance could be better if we start by comparing
// counts.
for member in lhs {
if !rhs.contains(member) {
return (false, false)
}
}
return (true, lhs.count == rhs.count)
}
// FIXME: rdar://problem/23549059 (Optimize == for Set)
// Look into initially trying to compare the two sets by directly comparing the
// contents of both buffers in order. If they happen to have the exact same
// ordering we can get the `true` response without ever hashing. If the two
// buffers' contents differ at all then we have to fall back to hashing the
// rest of the elements (but we don't need to hash any prefix that did match).
extension Set : Equatable {
/// Returns a Boolean value indicating whether two sets have equal elements.
///
/// - Parameters:
/// - lhs: A set.
/// - rhs: Another set.
/// - Returns: `true` if the `lhs` and `rhs` have the same elements; otherwise,
/// `false`.
@_inlineable // FIXME(sil-serialize-all)
public static func == (lhs: Set<Element>, rhs: Set<Element>) -> Bool {
switch (lhs._variantBuffer, rhs._variantBuffer) {
case (.native(let lhsNative), .native(let rhsNative)):
if lhsNative._storage === rhsNative._storage {
return true
}
if lhsNative.count != rhsNative.count {
return false
}
for member in lhs {
let (_, found) =
rhsNative._find(member, startBucket: rhsNative._bucket(member))
if !found {
return false
}
}
return true
#if _runtime(_ObjC)
case (_VariantSetBuffer.cocoa(let lhsCocoa),
_VariantSetBuffer.cocoa(let rhsCocoa)):
return _stdlib_NSObject_isEqual(lhsCocoa.cocoaSet, rhsCocoa.cocoaSet)
case (_VariantSetBuffer.native(let lhsNative),
_VariantSetBuffer.cocoa(let rhsCocoa)):
if lhsNative.count != rhsCocoa.count {
return false
}
let endIndex = lhsNative.endIndex
var i = lhsNative.startIndex
while i != endIndex {
let key = lhsNative.assertingGet(i)
let bridgedKey: AnyObject = _bridgeAnythingToObjectiveC(key)
let optRhsValue: AnyObject? = rhsCocoa.maybeGet(bridgedKey)
if let rhsValue = optRhsValue {
if key == _forceBridgeFromObjectiveC(rhsValue, Element.self) {
i = lhsNative.index(after: i)
continue
}
}
i = lhsNative.index(after: i)
return false
}
return true
case (_VariantSetBuffer.cocoa, _VariantSetBuffer.native):
return rhs == lhs
#endif
}
}
}
extension Set : Hashable {
/// The hash value for the set.
///
/// Two sets that are equal will always have equal hash values.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
@_inlineable // FIXME(sil-serialize-all)
public var hashValue: Int {
// FIXME(ABI)#177: <rdar://problem/18915294> Cache Set<T> hashValue
var result: Int = _mixInt(0)
for member in self {
result ^= _mixInt(member.hashValue)
}
return result
}
}
extension Set : SetAlgebra {
/// Inserts the given element in the set if it is not already present.
///
/// If an element equal to `newMember` is already contained in the set, this
@@ -692,57 +921,6 @@ public struct Set<Element : Hashable> :
return remove(at: startIndex)
}
/// The number of elements in the set.
///
/// - Complexity: O(1).
@_inlineable // FIXME(sil-serialize-all)
public var count: Int {
return _variantBuffer.count
}
//
// `Sequence` conformance
//
/// Accesses the member at the given position.
@_inlineable // FIXME(sil-serialize-all)
public subscript(position: Index) -> Element {
return _variantBuffer.assertingGet(position)
}
/// Returns an iterator over the members of the set.
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public func makeIterator() -> SetIterator<Element> {
return _variantBuffer.makeIterator()
}
//
// `ExpressibleByArrayLiteral` conformance
//
/// Creates a set containing the elements of the given array literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use an array literal. Instead, create a new set using an array
/// literal as its value by enclosing a comma-separated list of values in
/// square brackets. You can use an array literal anywhere a set is expected
/// by the type context.
///
/// Here, a set of strings is created from an array literal holding only
/// strings.
///
/// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
/// if ingredients.isSuperset(of: ["sugar", "salt"]) {
/// print("Whatever it is, it's bound to be delicious!")
/// }
/// // Prints "Whatever it is, it's bound to be delicious!"
///
/// - Parameter elements: A variadic list of elements of the new set.
@_inlineable // FIXME(sil-serialize-all)
public init(arrayLiteral elements: Element...) {
self.init(_nativeBuffer: _NativeSetBuffer.fromArray(elements))
}
//
// APIs below this comment should be implemented strictly in terms of
// *public* APIs above. `_variantBuffer` should not be accessed directly.
@@ -813,38 +991,6 @@ public struct Set<Element : Hashable> :
}
}
/// Returns a new set containing the elements of the set that satisfy the
/// given predicate.
///
/// In this example, `filter(_:)` is used to include only names shorter than
/// five characters.
///
/// let cast: Set = ["Vivien", "Marlon", "Kim", "Karl"]
/// let shortNames = cast.filter { $0.count < 5 }
///
/// shortNames.isSubset(of: cast)
/// // true
/// shortNames.contains("Vivien")
/// // false
///
/// - Parameter isIncluded: A closure that takes an element as its argument
/// and returns a Boolean value indicating whether the element should be
/// included in the returned set.
/// - Returns: A set of the elements that `isIncluded` allows.
@_inlineable
@available(swift, introduced: 4.0)
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> Set {
var result = Set()
for element in self {
if try isIncluded(element) {
result.insert(element)
}
}
return result
}
/// Returns a Boolean value that indicates whether the set is a subset of the
/// given sequence.
///
@@ -1177,149 +1323,6 @@ public struct Set<Element : Hashable> :
let otherSet = Set(other)
formSymmetricDifference(otherSet)
}
/// The hash value for the set.
///
/// Two sets that are equal will always have equal hash values.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
@_inlineable // FIXME(sil-serialize-all)
public var hashValue: Int {
// FIXME(ABI)#177: <rdar://problem/18915294> Cache Set<T> hashValue
var result: Int = _mixInt(0)
for member in self {
result ^= _mixInt(member.hashValue)
}
return result
}
//
// `Sequence` conformance
//
@_inlineable // FIXME(sil-serialize-all)
public func _customContainsEquatableElement(_ member: Element) -> Bool? {
return contains(member)
}
@_inlineable // FIXME(sil-serialize-all)
public func _customIndexOfEquatableElement(
_ member: Element
) -> Index?? {
return Optional(index(of: member))
}
//
// Collection conformance
//
/// A Boolean value that indicates whether the set is empty.
@_inlineable // FIXME(sil-serialize-all)
public var isEmpty: Bool {
return count == 0
}
/// The first element of the set.
///
/// The first element of the set is not necessarily the first element added
/// to the set. Don't expect any particular ordering of set elements.
///
/// If the set is empty, the value of this property is `nil`.
@_inlineable // FIXME(sil-serialize-all)
public var first: Element? {
return count > 0 ? self[startIndex] : nil
}
}
/// Check for both subset and equality relationship between
/// a set and some sequence (which may itself be a `Set`).
///
/// (isSubset: lhs ⊂ rhs, isEqual: lhs ⊂ rhs and |lhs| = |rhs|)
@_inlineable
@_versioned
internal func _compareSets<Element>(_ lhs: Set<Element>, _ rhs: Set<Element>)
-> (isSubset: Bool, isEqual: Bool) {
// FIXME(performance): performance could be better if we start by comparing
// counts.
for member in lhs {
if !rhs.contains(member) {
return (false, false)
}
}
return (true, lhs.count == rhs.count)
}
// FIXME: rdar://problem/23549059 (Optimize == for Set)
// Look into initially trying to compare the two sets by directly comparing the
// contents of both buffers in order. If they happen to have the exact same
// ordering we can get the `true` response without ever hashing. If the two
// buffers' contents differ at all then we have to fall back to hashing the
// rest of the elements (but we don't need to hash any prefix that did match).
extension Set {
/// Returns a Boolean value indicating whether two sets have equal elements.
///
/// - Parameters:
/// - lhs: A set.
/// - rhs: Another set.
/// - Returns: `true` if the `lhs` and `rhs` have the same elements; otherwise,
/// `false`.
@_inlineable // FIXME(sil-serialize-all)
public static func == (lhs: Set<Element>, rhs: Set<Element>) -> Bool {
switch (lhs._variantBuffer, rhs._variantBuffer) {
case (.native(let lhsNative), .native(let rhsNative)):
if lhsNative._storage === rhsNative._storage {
return true
}
if lhsNative.count != rhsNative.count {
return false
}
for member in lhs {
let (_, found) =
rhsNative._find(member, startBucket: rhsNative._bucket(member))
if !found {
return false
}
}
return true
#if _runtime(_ObjC)
case (_VariantSetBuffer.cocoa(let lhsCocoa),
_VariantSetBuffer.cocoa(let rhsCocoa)):
return _stdlib_NSObject_isEqual(lhsCocoa.cocoaSet, rhsCocoa.cocoaSet)
case (_VariantSetBuffer.native(let lhsNative),
_VariantSetBuffer.cocoa(let rhsCocoa)):
if lhsNative.count != rhsCocoa.count {
return false
}
let endIndex = lhsNative.endIndex
var i = lhsNative.startIndex
while i != endIndex {
let key = lhsNative.assertingGet(i)
let bridgedKey: AnyObject = _bridgeAnythingToObjectiveC(key)
let optRhsValue: AnyObject? = rhsCocoa.maybeGet(bridgedKey)
if let rhsValue = optRhsValue {
if key == _forceBridgeFromObjectiveC(rhsValue, Element.self) {
i = lhsNative.index(after: i)
continue
}
}
i = lhsNative.index(after: i)
return false
}
return true
case (_VariantSetBuffer.cocoa, _VariantSetBuffer.native):
return rhs == lhs
#endif
}
}
}
extension Set : CustomStringConvertible, CustomDebugStringConvertible {
@@ -1713,8 +1716,7 @@ public func _setBridgeFromObjectiveCConditional<
/// optimization that is used when two instances of `Dictionary` share
/// buffer.
@_fixed_layout
public struct Dictionary<Key : Hashable, Value> :
Collection, ExpressibleByDictionaryLiteral {
public struct Dictionary<Key : Hashable, Value> {
internal typealias _Self = Dictionary<Key, Value>
internal typealias _VariantBuffer = _VariantDictionaryBuffer<Key, Value>
@@ -1887,12 +1889,63 @@ public struct Dictionary<Key : Hashable, Value> :
_CocoaDictionaryBuffer(cocoaDictionary: _immutableCocoaDictionary))
}
#endif
}
//
// All APIs below should dispatch to `_variantBuffer`, without doing any
// additional processing.
//
//
// All APIs below should dispatch to `_variantBuffer`, without doing any
// additional processing.
//
extension Dictionary : Sequence {
/// Returns an iterator over the dictionary's key-value pairs.
///
/// Iterating over a dictionary yields the key-value pairs as two-element
/// tuples. You can decompose the tuple in a `for`-`in` loop, which calls
/// `makeIterator()` behind the scenes, or when calling the iterator's
/// `next()` method directly.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// for (name, hueValue) in hues {
/// print("The hue of \(name) is \(hueValue).")
/// }
/// // Prints "The hue of Heliotrope is 296."
/// // Prints "The hue of Coral is 16."
/// // Prints "The hue of Aquamarine is 156."
///
/// - Returns: An iterator over the dictionary with elements of type
/// `(key: Key, value: Value)`.
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public func makeIterator() -> DictionaryIterator<Key, Value> {
return _variantBuffer.makeIterator()
}
}
// This is not quite Sequence.filter, because that returns [Element], not Self
extension Dictionary {
/// Returns a new dictionary containing the key-value pairs of the dictionary
/// that satisfy the given predicate.
///
/// - Parameter isIncluded: A closure that takes a key-value pair as its
/// argument and returns a Boolean value indicating whether the pair
/// should be included in the returned dictionary.
/// - Returns: A dictionary of the key-value pairs that `isIncluded` allows.
@_inlineable
@available(swift, introduced: 4.0)
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Key: Value] {
var result = Dictionary()
for el in self {
if try isIncluded(el) {
result[el.key] = el.value
}
}
return result
}
}
extension Dictionary: Collection {
/// The position of the first element in a nonempty dictionary.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
@@ -1973,7 +2026,9 @@ public struct Dictionary<Key : Hashable, Value> :
public subscript(position: Index) -> Element {
return _variantBuffer.assertingGet(position)
}
}
extension Dictionary {
/// Accesses the value associated with the given key for reading and writing.
///
/// This *key-based* subscript returns the value for the given key if the key
@@ -2035,7 +2090,59 @@ public struct Dictionary<Key : Hashable, Value> :
}
}
}
/// The number of key-value pairs in the dictionary.
///
/// - Complexity: O(1).
@_inlineable // FIXME(sil-serialize-all)
public var count: Int {
return _variantBuffer.count
}
//
// `Sequence` conformance
//
/// A Boolean value that indicates whether the dictionary is empty.
///
/// Dictionaries are empty when created with an initializer or an empty
/// dictionary literal.
///
/// var frequencies: [String: Int] = [:]
/// print(frequencies.isEmpty)
/// // Prints "true"
@_inlineable // FIXME(sil-serialize-all)
public var isEmpty: Bool {
return count == 0
}
}
extension Dictionary : ExpressibleByDictionaryLiteral {
/// Creates a dictionary initialized with a dictionary literal.
///
/// Do not call this initializer directly. It is called by the compiler to
/// handle dictionary literals. To use a dictionary literal as the initial
/// value of a dictionary, enclose a comma-separated list of key-value pairs
/// in square brackets.
///
/// For example, the code sample below creates a dictionary with string keys
/// and values.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// print(countryCodes)
/// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
///
/// - Parameter elements: The key-value pairs that will make up the new
/// dictionary. Each key in `elements` must be unique.
@_inlineable // FIXME(sil-serialize-all)
@effects(readonly)
public init(dictionaryLiteral elements: (Key, Value)...) {
self.init(_nativeBuffer: _NativeDictionaryBuffer.fromArray(elements))
}
}
extension Dictionary {
/// Accesses the element with the given key, or the specified default value,
/// if the dictionary doesn't contain the given key.
@_inlineable // FIXME(sil-serialize-all)
@@ -2052,27 +2159,6 @@ public struct Dictionary<Key : Hashable, Value> :
}
}
/// Returns a new dictionary containing the key-value pairs of the dictionary
/// that satisfy the given predicate.
///
/// - Parameter isIncluded: A closure that takes a key-value pair as its
/// argument and returns a Boolean value indicating whether the pair
/// should be included in the returned dictionary.
/// - Returns: A dictionary of the key-value pairs that `isIncluded` allows.
@_inlineable
@available(swift, introduced: 4.0)
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Key: Value] {
var result = Dictionary()
for el in self {
if try isIncluded(el) {
result[el.key] = el.value
}
}
return result
}
/// Returns a new dictionary containing the keys of this dictionary with the
/// values transformed by the given closure.
///
@@ -2350,94 +2436,6 @@ public struct Dictionary<Key : Hashable, Value> :
// native buffer.
_variantBuffer.removeAll(keepingCapacity: keepCapacity)
}
/// The number of key-value pairs in the dictionary.
///
/// - Complexity: O(1).
@_inlineable // FIXME(sil-serialize-all)
public var count: Int {
return _variantBuffer.count
}
//
// `Sequence` conformance
//
/// Returns an iterator over the dictionary's key-value pairs.
///
/// Iterating over a dictionary yields the key-value pairs as two-element
/// tuples. You can decompose the tuple in a `for`-`in` loop, which calls
/// `makeIterator()` behind the scenes, or when calling the iterator's
/// `next()` method directly.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// for (name, hueValue) in hues {
/// print("The hue of \(name) is \(hueValue).")
/// }
/// // Prints "The hue of Heliotrope is 296."
/// // Prints "The hue of Coral is 16."
/// // Prints "The hue of Aquamarine is 156."
///
/// - Returns: An iterator over the dictionary with elements of type
/// `(key: Key, value: Value)`.
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public func makeIterator() -> DictionaryIterator<Key, Value> {
return _variantBuffer.makeIterator()
}
//
// ExpressibleByDictionaryLiteral conformance
//
/// Creates a dictionary initialized with a dictionary literal.
///
/// Do not call this initializer directly. It is called by the compiler to
/// handle dictionary literals. To use a dictionary literal as the initial
/// value of a dictionary, enclose a comma-separated list of key-value pairs
/// in square brackets.
///
/// For example, the code sample below creates a dictionary with string keys
/// and values.
///
/// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"]
/// print(countryCodes)
/// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]"
///
/// - Parameter elements: The key-value pairs that will make up the new
/// dictionary. Each key in `elements` must be unique.
@_inlineable // FIXME(sil-serialize-all)
@effects(readonly)
public init(dictionaryLiteral elements: (Key, Value)...) {
self.init(_nativeBuffer: _NativeDictionaryBuffer.fromArray(elements))
}
//
// APIs below this comment should be implemented strictly in terms of
// *public* APIs above. `_variantBuffer` should not be accessed directly.
//
// This separates concerns for testing. Tests for the following APIs need
// not to concern themselves with testing correctness of behavior of
// underlying buffer (and different variants of it), only correctness of the
// API itself.
//
//
// Collection conformance
//
/// A Boolean value that indicates whether the dictionary is empty.
///
/// Dictionaries are empty when created with an initializer or an empty
/// dictionary literal.
///
/// var frequencies: [String: Int] = [:]
/// print(frequencies.isEmpty)
/// // Prints "true"
@_inlineable // FIXME(sil-serialize-all)
public var isEmpty: Bool {
return count == 0
}
}
// Maintain old `keys` and `values` types in Swift 3 mode.

View File

@@ -50,9 +50,7 @@
/// - `x.isStrictSuperset(of: y)` if and only if
/// `x.isSuperset(of: y) && x != y`
/// - `x.isStrictSubset(of: y)` if and only if `x.isSubset(of: y) && x != y`
public protocol SetAlgebra : Equatable, ExpressibleByArrayLiteral {
// FIXME: write tests for SetAlgebra
public protocol SetAlgebra : Equatable, ExpressibleByArrayLiteral {
/// A type for which the conforming type provides a containment test.
associatedtype Element

View File

@@ -163,7 +163,7 @@ extension String : _SwiftStringView {
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal var _persistentContent : String {
return characters._persistentContent
return _characters._persistentContent
}
}

View File

@@ -29,6 +29,10 @@ internal var _LF: UInt8 { return 0x0a }
import SwiftShims
extension String {
@available(swift, deprecated: 3.2, message:
"Please use String or Substring directly")
public typealias CharacterView = _CharacterView
/// A view of a string's contents as a collection of characters.
///
/// In Swift, every string provides a view of its contents as characters. In
@@ -62,9 +66,7 @@ extension String {
/// }
/// // Prints "Marie"
@_fixed_layout // FIXME(sil-serialize-all)
@available(swift, deprecated: 3.2, message:
"Please use String or Substring directly")
public struct CharacterView {
public struct _CharacterView {
@_versioned
internal var _core: _StringCore
@@ -89,6 +91,17 @@ extension String {
self._coreOffset = coreOffset
}
}
/// A view of the string's contents as a collection of characters.
@_transparent // FIXME(sil-serialize-all)
public var _characters: _CharacterView {
get {
return CharacterView(self)
}
set {
self = String(newValue)
}
}
/// A view of the string's contents as a collection of characters.
@_inlineable // FIXME(sil-serialize-all)
@@ -96,10 +109,10 @@ extension String {
"Please use String or Substring directly")
public var characters: CharacterView {
get {
return CharacterView(self)
return _characters
}
set {
self = String(newValue)
_characters = newValue
}
}
@@ -141,7 +154,7 @@ extension String {
// Naively mutating self.characters forces multiple references to
// exist at the point of mutation. Instead, temporarily move the
// core of this string into a CharacterView.
var tmp = CharacterView("")
var tmp = _CharacterView("")
(_core, tmp._core) = (tmp._core, _core)
let r = body(&tmp)
(_core, tmp._core) = (tmp._core, _core)
@@ -165,12 +178,14 @@ extension String {
///
/// - Parameter characters: A character view to convert to a string.
@_inlineable // FIXME(sil-serialize-all)
@available(swift, deprecated: 3.2, message:
"Please use String or Substring directly")
public init(_ characters: CharacterView) {
self.init(characters._core)
}
}
extension String.CharacterView : _SwiftStringView {
extension String._CharacterView : _SwiftStringView {
@_inlineable // FIXME(sil-serialize-all)
@_versioned // FIXME(sil-serialize-all)
internal var _persistentContent : String {
@@ -187,7 +202,7 @@ extension String.CharacterView : _SwiftStringView {
/// `String.CharacterView` is a collection of `Character`.
extension String.CharacterView : BidirectionalCollection {
extension String._CharacterView : BidirectionalCollection {
internal typealias UnicodeScalarView = String.UnicodeScalarView
@_inlineable // FIXME(sil-serialize-all)
@_versioned
@@ -397,7 +412,7 @@ extension String.CharacterView : BidirectionalCollection {
}
// Perform a quick single-code-unit grapheme check.
if _fastPath(String.CharacterView._quickCheckGraphemeBreakBetween(
if _fastPath(String._CharacterView._quickCheckGraphemeBreakBetween(
_core[startOffset],
_core[startOffset+1])
) {
@@ -537,7 +552,7 @@ extension String.CharacterView : BidirectionalCollection {
}
// Perform a quick single-code-unit grapheme check
if _fastPath(String.CharacterView._quickCheckGraphemeBreakBetween(
if _fastPath(String._CharacterView._quickCheckGraphemeBreakBetween(
_core[lastOffset-1], _core[lastOffset])
) {
return 1
@@ -674,7 +689,7 @@ extension String.CharacterView : BidirectionalCollection {
}
}
extension String.CharacterView : RangeReplaceableCollection {
extension String._CharacterView : RangeReplaceableCollection {
/// Creates an empty character view.
@_inlineable // FIXME(sil-serialize-all)
public init() {
@@ -757,7 +772,7 @@ extension String.CharacterView : RangeReplaceableCollection {
}
// Algorithms
extension String.CharacterView {
extension String._CharacterView {
/// Accesses the characters in the given range.
///
/// The example below uses this subscript to access the characters up to, but
@@ -772,8 +787,8 @@ extension String.CharacterView {
/// - Complexity: O(*n*) if the underlying string is bridged from
/// Objective-C, where *n* is the length of the string; otherwise, O(1).
@_inlineable // FIXME(sil-serialize-all)
public subscript(bounds: Range<Index>) -> String.CharacterView {
return String.CharacterView(
public subscript(bounds: Range<Index>) -> String._CharacterView {
return String._CharacterView(
unicodeScalars[bounds]._core,
coreOffset: bounds.lowerBound.encodedOffset)
}

View File

@@ -57,7 +57,7 @@ extension String.Index {
guard target.unicodeScalars._isOnGraphemeClusterBoundary(sourcePosition)
else { return nil }
self = target.characters._index(
self = target._characters._index(
atEncodedOffset: sourcePosition.encodedOffset)
}

View File

@@ -16,7 +16,7 @@ extension String : StringProtocol, RangeReplaceableCollection {
///
/// In Swift, *reachability* refers to the ability to produce one value from
/// the other through zero or more applications of `index(after:)`.
public typealias IndexDistance = CharacterView.IndexDistance
public typealias IndexDistance = _CharacterView.IndexDistance
public typealias SubSequence = Substring
@@ -62,7 +62,7 @@ extension String : StringProtocol, RangeReplaceableCollection {
@_inlineable // FIXME(sil-serialize-all)
public init<S : Sequence & LosslessStringConvertible>(_ other: S)
where S.Element == Character {
self._core = CharacterView(other)._core
self._core = _CharacterView(other)._core
}
// The defaulted argument prevents this initializer from satisfies the
@@ -80,14 +80,14 @@ extension String : StringProtocol, RangeReplaceableCollection {
///
/// In an empty string, `startIndex` is equal to `endIndex`.
@_inlineable // FIXME(sil-serialize-all)
public var startIndex: Index { return characters.startIndex }
public var startIndex: Index { return _characters.startIndex }
/// A string's "past the end" position---that is, the position one greater
/// than the last valid subscript argument.
///
/// In an empty string, `endIndex` is equal to `startIndex`.
@_inlineable // FIXME(sil-serialize-all)
public var endIndex: Index { return characters.endIndex }
public var endIndex: Index { return _characters.endIndex }
/// Returns the position immediately after the given index.
///
@@ -96,13 +96,13 @@ extension String : StringProtocol, RangeReplaceableCollection {
/// - Returns: The index value immediately after `i`.
@_inlineable // FIXME(sil-serialize-all)
public func index(after i: Index) -> Index {
return characters.index(after: i)
return _characters.index(after: i)
}
// TODO: swift-3-indexing-model - add docs
@_inlineable // FIXME(sil-serialize-all)
public func index(before i: Index) -> Index {
return characters.index(before: i)
return _characters.index(before: i)
}
/// Returns an index that is the specified distance from the given index.
@@ -129,7 +129,7 @@ extension String : StringProtocol, RangeReplaceableCollection {
/// - Complexity: O(*n*), where *n* is the absolute value of `n`.
@_inlineable // FIXME(sil-serialize-all)
public func index(_ i: Index, offsetBy n: IndexDistance) -> Index {
return characters.index(i, offsetBy: n)
return _characters.index(i, offsetBy: n)
}
/// Returns an index that is the specified distance from the given index,
@@ -173,7 +173,7 @@ extension String : StringProtocol, RangeReplaceableCollection {
public func index(
_ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index
) -> Index? {
return characters.index(i, offsetBy: n, limitedBy: limit)
return _characters.index(i, offsetBy: n, limitedBy: limit)
}
/// Returns the distance between two indices.
@@ -187,7 +187,7 @@ extension String : StringProtocol, RangeReplaceableCollection {
/// - Complexity: O(*n*), where *n* is the resulting distance.
@_inlineable // FIXME(sil-serialize-all)
public func distance(from start: Index, to end: Index) -> IndexDistance {
return characters.distance(from: start, to: end)
return _characters.distance(from: start, to: end)
}
/// Accesses the character at the given position.
@@ -206,7 +206,7 @@ extension String : StringProtocol, RangeReplaceableCollection {
/// - Parameter i: A valid index of the string. `i` must be less than the
/// string's end index.
@_inlineable // FIXME(sil-serialize-all)
public subscript(i: Index) -> Character { return characters[i] }
public subscript(i: Index) -> Character { return _characters[i] }
}
extension String {
@@ -228,7 +228,7 @@ extension String {
@_inlineable // FIXME(sil-serialize-all)
public init<S : Sequence>(_ characters: S)
where S.Iterator.Element == Character {
self._core = CharacterView(characters)._core
self._core = _CharacterView(characters)._core
}
/// Reserves enough space in the string's underlying storage to store the
@@ -246,7 +246,7 @@ extension String {
@_inlineable // FIXME(sil-serialize-all)
public mutating func reserveCapacity(_ n: Int) {
withMutableCharacters {
(v: inout CharacterView) in v.reserveCapacity(n)
(v: inout _CharacterView) in v.reserveCapacity(n)
}
}
@@ -263,7 +263,7 @@ extension String {
@_inlineable // FIXME(sil-serialize-all)
public mutating func append(_ c: Character) {
withMutableCharacters {
(v: inout CharacterView) in v.append(c)
(v: inout _CharacterView) in v.append(c)
}
}
@@ -274,7 +274,7 @@ extension String {
public mutating func append<S : Sequence>(contentsOf newElements: S)
where S.Iterator.Element == Character {
withMutableCharacters {
(v: inout CharacterView) in v.append(contentsOf: newElements)
(v: inout _CharacterView) in v.append(contentsOf: newElements)
}
}
@@ -298,7 +298,7 @@ extension String {
with newElements: C
) where C : Collection, C.Iterator.Element == Character {
withMutableCharacters {
(v: inout CharacterView)
(v: inout _CharacterView)
in v.replaceSubrange(bounds, with: newElements)
}
}
@@ -317,7 +317,7 @@ extension String {
@_inlineable // FIXME(sil-serialize-all)
public mutating func insert(_ newElement: Character, at i: Index) {
withMutableCharacters {
(v: inout CharacterView) in v.insert(newElement, at: i)
(v: inout _CharacterView) in v.insert(newElement, at: i)
}
}
@@ -340,7 +340,7 @@ extension String {
contentsOf newElements: S, at i: Index
) where S.Iterator.Element == Character {
withMutableCharacters {
(v: inout CharacterView) in v.insert(contentsOf: newElements, at: i)
(v: inout _CharacterView) in v.insert(contentsOf: newElements, at: i)
}
}
@@ -366,7 +366,7 @@ extension String {
@discardableResult
public mutating func remove(at i: Index) -> Character {
return withMutableCharacters {
(v: inout CharacterView) in v.remove(at: i)
(v: inout _CharacterView) in v.remove(at: i)
}
}
@@ -383,7 +383,7 @@ extension String {
@_inlineable // FIXME(sil-serialize-all)
public mutating func removeSubrange(_ bounds: Range<Index>) {
withMutableCharacters {
(v: inout CharacterView) in v.removeSubrange(bounds)
(v: inout _CharacterView) in v.removeSubrange(bounds)
}
}
@@ -399,7 +399,7 @@ extension String {
@_inlineable // FIXME(sil-serialize-all)
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
withMutableCharacters {
(v: inout CharacterView) in v.removeAll(keepingCapacity: keepCapacity)
(v: inout _CharacterView) in v.removeAll(keepingCapacity: keepCapacity)
}
}
}

View File

@@ -712,15 +712,15 @@ extension String {
return element
}
}
extension String.CharacterView {
extension String._CharacterView {
@_inlineable // FIXME(sil-serialize-all)
@available(swift, deprecated: 3.2, obsoleted: 4, message:
"Please use 'first', 'dropFirst()', or 'Substring.CharacterView.popFirst()'.")
public mutating func popFirst() -> String.CharacterView.Element? {
public mutating func popFirst() -> String._CharacterView.Element? {
guard !isEmpty else { return nil }
let element = first!
let nextIdx = self.index(after: self.startIndex)
self = String(self[nextIdx...]).characters
self = String(self[nextIdx...])._characters
return element
}
}

View File

@@ -53,7 +53,7 @@ value(_) // expected-error{{'_' can only appear in a pattern or on the left side
// <rdar://problem/23798944> = vs. == in Swift if string character count statement causes segmentation fault
func f23798944() {
let s = ""
if s.characters.count = 0 { // expected-error {{cannot assign to property: 'count' is a get-only property}}
if s.count = 0 { // expected-error {{cannot assign to property: 'count' is a get-only property}}
}
}

View File

@@ -161,7 +161,7 @@ func rdar20142523() {
// <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral
func rdar21080030() {
var s = "Hello"
if s.characters.count() == 0 {} // expected-error{{cannot call value of non-function type 'String.CharacterView.IndexDistance'}}{{24-26=}}
if s.count() == 0 {} // expected-error{{cannot call value of non-function type 'String.IndexDistance' (aka 'Int')}}{{13-15=}}
}
// <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments
@@ -196,7 +196,7 @@ func r17020197(_ x : Int?, y : Int) {
// <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different
func validateSaveButton(_ text: String) {
return (text.characters.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}}
return (text.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype

View File

@@ -29,7 +29,7 @@ func stateFromPlistLame(_ plist: Dictionary<String, Any>) -> State? {
func stateFromPlistCool(_ plist: Dictionary<String, Any>) -> State? {
switch (plist["name"], plist["population"], plist["abbrev"]) {
case let (name as String, pop as Int, abbr as String)
where abbr.characters.count == 2:
where abbr.count == 2:
return State(name: name,
population: pop,
abbrev: abbr)
@@ -105,7 +105,7 @@ enum Statistic : CustomReflectable {
func statisticFromPlist(_ plist: Dictionary<String, Any>) -> Statistic? {
switch (plist["kind"], plist["name"], plist["population"], plist["abbrev"]) {
case let ("state" as String, name as String, population as Int, abbrev as String)
where abbrev.characters.count == 2:
where abbrev.count == 2:
return Statistic.ForState(State(name: name,
population: population,
abbrev: abbrev))

View File

@@ -47,7 +47,7 @@ func toString(indexes: Int?...) -> String {
let _ = indexes.reduce(0) { print($0); return $0.0 + ($0.1 ?? 0)}
let _ = indexes.reduce(0) { (true ? $0 : (1, 2)).0 + ($0.1 ?? 0) }
let _ = [(1, 2)].contains { $0 != $1 }
_ = ["Hello", "Foo"].sorted { print($0); return $0.0.characters.count > ($0).1.characters.count }
_ = ["Hello", "Foo"].sorted { print($0); return $0.0.count > ($0).1.count }
_ = ["Hello" : 2].map { ($0, ($1)) }
}

View File

@@ -47,7 +47,7 @@ func toString(indexes: Int?...) -> String {
let _ = indexes.reduce(0) { print(($0, $1)); return $0 + ($1 ?? 0)}
let _ = indexes.reduce(0) { (true ? ($0, $1) : (1, 2)).0 + ($1 ?? 0) }
let _ = [(1, 2)].contains { $0 != $1 }
_ = ["Hello", "Foo"].sorted { print(($0, $1)); return $0.characters.count > $1.characters.count }
_ = ["Hello", "Foo"].sorted { print(($0, $1)); return $0.count > $1.count }
_ = ["Hello" : 2].map { ($0, ($1)) }
}

View File

@@ -935,7 +935,7 @@ public struct _BigInt<Word: FixedWidthInteger & UnsignedInteger> :
// Check for a single prefixing hyphen
let negative = source.hasPrefix("-")
if negative {
source = String(source.characters.dropFirst())
source = String(source.dropFirst())
}
// Loop through characters, multiplying

View File

@@ -161,41 +161,41 @@ CharacterTests.test("Hashable") {
CharacterTests.test("CR-LF") {
let asciiString = "qwerty\r\n"
let asciiString_rev = "\r\nytrewq"
expectEqual(asciiString.characters.count, asciiString_rev.characters.count)
expectEqualSequence(asciiString.characters.reversed(), asciiString_rev.characters)
expectEqual(asciiString.count, asciiString_rev.count)
expectEqualSequence(asciiString.reversed(), asciiString_rev)
// Mixed form
let utf16String = "a\u{03B2}c\r\nd\u{03B5}f"
let utf16String_rev = "f\u{03B5}d\r\nc\u{03B2}a"
expectEqual(utf16String.characters.count, utf16String_rev.characters.count)
expectEqualSequence(utf16String.characters.reversed(), utf16String_rev.characters)
expectEqual(utf16String.count, utf16String_rev.count)
expectEqualSequence(utf16String.reversed(), utf16String_rev)
// Substrings
let asciiString_sub = asciiString[asciiString.index(after: asciiString.startIndex)..<asciiString.endIndex]
let asciiString_rev_sub = asciiString_rev[asciiString_rev.startIndex..<asciiString_rev.index(before:asciiString_rev.endIndex)]
expectEqual(asciiString_sub.characters.count, asciiString_rev_sub.characters.count)
expectEqual(asciiString_sub.characters.count, asciiString.characters.count-1)
expectEqualSequence(asciiString_sub.characters.reversed(), asciiString_rev_sub.characters)
expectEqual(asciiString_sub.count, asciiString_rev_sub.count)
expectEqual(asciiString_sub.count, asciiString.count-1)
expectEqualSequence(asciiString_sub.reversed(), asciiString_rev_sub)
let utf16String_sub = utf16String[utf16String.index(after: utf16String.startIndex)..<utf16String.endIndex]
let utf16String_rev_sub = utf16String_rev[utf16String_rev.startIndex..<utf16String_rev.index(before: utf16String_rev.endIndex)]
expectEqual(utf16String_sub.characters.count, utf16String_rev_sub.characters.count)
expectEqual(utf16String_sub.characters.count, utf16String.characters.count-1)
expectEqualSequence(utf16String_sub.characters.reversed(), utf16String_rev_sub.characters)
expectEqual(utf16String_sub.count, utf16String_rev_sub.count)
expectEqual(utf16String_sub.count, utf16String.count-1)
expectEqualSequence(utf16String_sub.reversed(), utf16String_rev_sub)
// Character view slices where the indices are invalid as subsequence-relative offsets
let asciiString_final = "ty\r\n"
let asciiString_final_rev = "\r\nyt"
let finalASCIICharacters = asciiString.characters[asciiString.characters.index(asciiString.characters.endIndex, offsetBy: -3)..<asciiString.characters.endIndex]
expectEqualSequence(finalASCIICharacters, asciiString_final.characters)
expectEqualSequence(finalASCIICharacters.reversed(), asciiString_final_rev.characters)
let finalASCIICharacters = asciiString[asciiString.index(asciiString.endIndex, offsetBy: -3)..<asciiString.endIndex]
expectEqualSequence(finalASCIICharacters, asciiString_final)
expectEqualSequence(finalASCIICharacters.reversed(), asciiString_final_rev)
let unicodeAlphabetString = "abcdefgあいうえおαβγ\r\n"
let unicodeAlphabetString_final = "βγ\r\n"
let unicodeAlphabetString_final_rev = "\r\nγβ"
let finalAlphaCharacters = unicodeAlphabetString.characters[unicodeAlphabetString.characters.index(unicodeAlphabetString.characters.endIndex, offsetBy: -3)..<unicodeAlphabetString.characters.endIndex]
expectEqualSequence(finalAlphaCharacters, unicodeAlphabetString_final.characters)
expectEqualSequence(finalAlphaCharacters.reversed(), unicodeAlphabetString_final_rev.characters)
let finalAlphaCharacters = unicodeAlphabetString[unicodeAlphabetString.index(unicodeAlphabetString.endIndex, offsetBy: -3)..<unicodeAlphabetString.endIndex]
expectEqualSequence(finalAlphaCharacters, unicodeAlphabetString_final)
expectEqualSequence(finalAlphaCharacters.reversed(), unicodeAlphabetString_final_rev)
}
CharacterTests.test("Unicode 9 grapheme breaking") {

View File

@@ -60,10 +60,10 @@ ErrorHandlingTests.test("ErrorHandling/withUnsafeBufferPointer extends lifetime"
}
ErrorHandlingTests.test("ErrorHandling/Optional.map and .flatMap") {
var x: Int? = 222
let x: Int? = 222
do {
let y: String? = try x.map {(n: Int) -> String in
let _: String? = try x.map {(n: Int) -> String in
throw SillyError.JazzHands
return "\(n)"
}
@@ -71,7 +71,7 @@ ErrorHandlingTests.test("ErrorHandling/Optional.map and .flatMap") {
} catch {}
do {
let y: String? = try x.flatMap {(n: Int) -> String? in
let _: String? = try x.flatMap {(n: Int) -> String? in
throw SillyError.JazzHands
return .some("\(n)")
}
@@ -107,7 +107,7 @@ ErrorHandlingTests.test("ErrorHandling/index(where:)") {
ErrorHandlingTests.test("ErrorHandling/split") {
do {
let _: [String.CharacterView] = try "foo".characters.split { _ in
let _: [Substring] = try "foo".split { _ in
throw SillyError.JazzHands
return false
}
@@ -116,7 +116,7 @@ ErrorHandlingTests.test("ErrorHandling/split") {
do {
let _: [AnySequence<Character>]
= try AnySequence("foo".characters).split { _ in
= try AnySequence("foo").split { _ in
throw SillyError.JazzHands
return false
}
@@ -192,7 +192,7 @@ ErrorHandlingTests.test("ErrorHandling/min") {
ErrorHandlingTests.test("ErrorHandling/starts(with:)") {
do {
let x: Bool = try [1, 2, 3].starts(with: [1, 2]) { _, _ in
let _: Bool = try [1, 2, 3].starts(with: [1, 2]) { _, _ in
throw SillyError.JazzHands
return false
}
@@ -202,7 +202,7 @@ ErrorHandlingTests.test("ErrorHandling/starts(with:)") {
ErrorHandlingTests.test("ErrorHandling/elementsEqual") {
do {
let x: Bool = try [1, 2, 3].elementsEqual([1, 2, 3]) { _, _ in
let _: Bool = try [1, 2, 3].elementsEqual([1, 2, 3]) { _, _ in
throw SillyError.JazzHands
return false
}
@@ -212,7 +212,7 @@ ErrorHandlingTests.test("ErrorHandling/elementsEqual") {
ErrorHandlingTests.test("ErrorHandling/lexicographicallyPrecedes(_:)") {
do {
let x: Bool = try [1, 2, 3].lexicographicallyPrecedes([0, 2, 3]) { _, _ in
let _: Bool = try [1, 2, 3].lexicographicallyPrecedes([0, 2, 3]) { _, _ in
throw SillyError.JazzHands
return false
}
@@ -222,7 +222,7 @@ ErrorHandlingTests.test("ErrorHandling/lexicographicallyPrecedes(_:)") {
ErrorHandlingTests.test("ErrorHandling/contains") {
do {
let x: Bool = try [1, 2, 3].contains { _ in
let _: Bool = try [1, 2, 3].contains { _ in
throw SillyError.JazzHands
return false
}
@@ -233,11 +233,11 @@ ErrorHandlingTests.test("ErrorHandling/contains") {
ErrorHandlingTests.test("ErrorHandling/reduce") {
var loopCount = 0
do {
let x: Int = try [1, 2, 3, 4, 5].reduce(0) {
let _: Int = try [1, 2, 3, 4, 5].reduce(0) {
(x: Int, y: Int) -> Int
in
loopCount += 1
var total = x + y
let total = x + y
if total > 5 {
throw SillyError.JazzHands
}
@@ -341,7 +341,7 @@ ErrorHandlingTests.test("ErrorHandling/Collection map") {
}
ErrorHandlingTests.test("ErrorHandling/sort") {
var collection = Array(1...5)
let collection = Array(1...5)
forAllPermutations(collection) { sequence in
for i in 0..<sequence.count {
var s = sequence
@@ -361,10 +361,10 @@ ErrorHandlingTests.test("ErrorHandling/sort") {
}
ErrorHandlingTests.test("ErrorHandling/sorted") {
var collection = Array(1...5)
let collection = Array(1...5)
forAllPermutations(collection) { sequence in
for i in 0..<sequence.count {
var s = sequence
let s = sequence
var thrown = false
let throwElment = sequence[i]
var result: [Int] = []
@@ -391,7 +391,7 @@ ErrorHandlingTests.test("ErrorHandling/sorted") {
}
ErrorHandlingTests.test("ErrorHandling/sort") {
var collection = Array(1...5)
let collection = Array(1...5)
forAllPermutations(collection) { sequence in
for i in 0..<sequence.count {
var s = sequence
@@ -411,10 +411,10 @@ ErrorHandlingTests.test("ErrorHandling/sort") {
}
ErrorHandlingTests.test("ErrorHandling/sorted") {
var collection = Array(1...5)
let collection = Array(1...5)
forAllPermutations(collection) { sequence in
for i in 0..<sequence.count {
var s = sequence
let s = sequence
var thrown = false
let throwElment = sequence[i]
var result: [Int] = []

View File

@@ -52,8 +52,8 @@ mirrors.test("RandomAccessStructure") {
let letters = "abcdefghijklmnopqrstuvwxyz "
func find(_ substring: String, within domain: String) -> String.Index? {
let domainCount = domain.characters.count
let substringCount = substring.characters.count
let domainCount = domain.count
let substringCount = substring.count
if (domainCount < substringCount) { return nil }
var sliceStart = domain.startIndex
@@ -76,19 +76,19 @@ mirrors.test("ForwardStructure") {
var customMirror: Mirror {
return Mirror(
self,
unlabeledChildren: Set(letters.characters),
unlabeledChildren: Set(letters),
displayStyle: .`set`)
}
}
let w = DoubleYou().customMirror
expectEqual(.`set`, w.displayStyle)
expectEqual(letters.characters.count, numericCast(w.children.count))
expectEqual(letters.count, numericCast(w.children.count))
// Because we don't control the order of a Set, we need to do a
// fancy dance in order to validate the result.
let description = w.testDescription
for c in letters.characters {
for c in letters {
let expected = "nil: \"\(c)\""
expectNotNil(find(expected, within: description))
}
@@ -99,7 +99,7 @@ mirrors.test("BidirectionalStructure") {
var customMirror: Mirror {
return Mirror(
self,
unlabeledChildren: letters.characters,
unlabeledChildren: letters,
displayStyle: .collection)
}
}
@@ -111,7 +111,7 @@ mirrors.test("BidirectionalStructure") {
let description = y.testDescription
expectEqual(
"[nil: \"a\", nil: \"b\", nil: \"c\", nil: \"",
description[description.startIndex..<description.characters.index(of: "d")!])
description[description.startIndex..<description.index(of: "d")!])
}
mirrors.test("LabeledStructure") {

View File

@@ -88,10 +88,11 @@ NSStringAPIs.test("NSStringEncoding") {
enc = .utf32BigEndian
enc = .ascii
enc = .utf8
expectEqual(.utf8, enc)
}
NSStringAPIs.test("localizedStringWithFormat(_:...)") {
var world: NSString = "world"
let world: NSString = "world"
expectEqual("Hello, world!%42", String.localizedStringWithFormat(
"Hello, %@!%%%ld", world, 42))
@@ -118,7 +119,7 @@ NSStringAPIs.test("init(contentsOfFile:encoding:error:)") {
}
do {
let content = try String(
let _ = try String(
contentsOfFile: nonExistentPath, encoding: .ascii)
expectUnreachable()
} catch {
@@ -140,7 +141,7 @@ NSStringAPIs.test("init(contentsOfFile:usedEncoding:error:)") {
expectUnreachableCatch(error)
}
var usedEncoding: String.Encoding = String.Encoding(rawValue: 0)
let usedEncoding: String.Encoding = String.Encoding(rawValue: 0)
do {
_ = try String(contentsOfFile: nonExistentPath)
expectUnreachable()
@@ -204,8 +205,8 @@ NSStringAPIs.test("init(cString_:encoding:)") {
}
NSStringAPIs.test("init(utf8String:)") {
var s = "foo あいう"
var up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100)
let s = "foo あいう"
let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100)
var i = 0
for b in s.utf8 {
up[i] = b
@@ -374,13 +375,13 @@ NSStringAPIs.test("compare(_:options:range:locale:)") {
NSStringAPIs.test("completePath(into:caseSensitive:matchesInto:filterTypes)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
do {
var count = nonExistentPath.completePath(caseSensitive: false)
let count = nonExistentPath.completePath(caseSensitive: false)
expectEqual(0, count)
}
do {
var outputName = "None Found"
var count = nonExistentPath.completePath(
let count = nonExistentPath.completePath(
into: &outputName, caseSensitive: false)
expectEqual(0, count)
@@ -390,7 +391,7 @@ NSStringAPIs.test("completePath(into:caseSensitive:matchesInto:filterTypes)") {
do {
var outputName = "None Found"
var outputArray: [String] = ["foo", "bar"]
var count = nonExistentPath.completePath(
let count = nonExistentPath.completePath(
into: &outputName, caseSensitive: false, matchesInto: &outputArray)
expectEqual(0, count)
@@ -399,13 +400,13 @@ NSStringAPIs.test("completePath(into:caseSensitive:matchesInto:filterTypes)") {
}
do {
var count = existingPath.completePath(caseSensitive: false)
let count = existingPath.completePath(caseSensitive: false)
expectEqual(1, count)
}
do {
var outputName = "None Found"
var count = existingPath.completePath(
let count = existingPath.completePath(
into: &outputName, caseSensitive: false)
expectEqual(1, count)
@@ -415,7 +416,7 @@ NSStringAPIs.test("completePath(into:caseSensitive:matchesInto:filterTypes)") {
do {
var outputName = "None Found"
var outputArray: [String] = ["foo", "bar"]
var count = existingPath.completePath(
let count = existingPath.completePath(
into: &outputName, caseSensitive: false, matchesInto: &outputArray)
expectEqual(1, count)
@@ -425,7 +426,7 @@ NSStringAPIs.test("completePath(into:caseSensitive:matchesInto:filterTypes)") {
do {
var outputName = "None Found"
var count = existingPath.completePath(
let count = existingPath.completePath(
into: &outputName, caseSensitive: false, filterTypes: ["txt"])
expectEqual(1, count)
@@ -472,7 +473,7 @@ NSStringAPIs.test("cString(usingEncoding:)") {
expectNil("абв".cString(using: .ascii))
let expectedBytes: [UInt8] = [ 0xd0, 0xb0, 0xd0, 0xb1, 0xd0, 0xb2, 0 ]
var expectedStr: [CChar] = expectedBytes.map { CChar(bitPattern: $0) }
let expectedStr: [CChar] = expectedBytes.map { CChar(bitPattern: $0) }
expectEqual(expectedStr,
"абв".cString(using: .utf8)!)
}
@@ -496,8 +497,8 @@ NSStringAPIs.test("init(data:encoding:)") {
expectNil(String(data: data, encoding: .nonLossyASCII))
expectEqualSequence(
"あいう".characters,
String(data: data, encoding: .utf8)!.characters)
"あいう",
String(data: data, encoding: .utf8)!)
}
NSStringAPIs.test("decomposedStringWithCanonicalMapping") {
@@ -606,7 +607,7 @@ NSStringAPIs.test("getBytes(_:maxLength:usedLength:encoding:options:range:remain
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
var result = s.getBytes(&buffer, maxLength: 11, usedLength: &usedLength,
let result = s.getBytes(&buffer, maxLength: 11, usedLength: &usedLength,
encoding: .utf8,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
@@ -627,7 +628,7 @@ NSStringAPIs.test("getBytes(_:maxLength:usedLength:encoding:options:range:remain
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
var result = s.getBytes(&buffer, maxLength: 11, usedLength: &usedLength,
let result = s.getBytes(&buffer, maxLength: 11, usedLength: &usedLength,
encoding: .utf8,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
@@ -647,7 +648,7 @@ NSStringAPIs.test("getBytes(_:maxLength:usedLength:encoding:options:range:remain
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
var result = s.getBytes(&buffer, maxLength: bufferLength,
let result = s.getBytes(&buffer, maxLength: bufferLength,
usedLength: &usedLength, encoding: .utf8,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
@@ -667,7 +668,7 @@ NSStringAPIs.test("getBytes(_:maxLength:usedLength:encoding:options:range:remain
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
var result = s.getBytes(&buffer, maxLength: bufferLength,
let result = s.getBytes(&buffer, maxLength: bufferLength,
usedLength: &usedLength, encoding: .ascii,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
@@ -680,7 +681,7 @@ NSStringAPIs.test("getBytes(_:maxLength:usedLength:encoding:options:range:remain
}
NSStringAPIs.test("getCString(_:maxLength:encoding:)") {
var s = "abc あかさた"
let s = "abc あかさた"
do {
// The largest buffer that cannot accommodate the string plus null terminator.
let bufferLength = 16
@@ -758,8 +759,8 @@ NSStringAPIs.test("getParagraphStart(_:end:contentsEnd:forRange:)") {
}
NSStringAPIs.test("hash") {
var s: String = "abc"
var nsstr: NSString = "abc"
let s: String = "abc"
let nsstr: NSString = "abc"
expectEqual(nsstr.hash, s.hash)
}
@@ -839,7 +840,7 @@ NSStringAPIs.test("init(format:arguments:)") {
}
NSStringAPIs.test("init(format:locale:_:...)") {
var world: NSString = "world"
let world: NSString = "world"
expectEqual("Hello, world!%42", String(format: "Hello, %@!%%%ld",
locale: nil, world, 42))
}
@@ -875,7 +876,7 @@ NSStringAPIs.test("linguisticTagsIn(_:scheme:options:orthography:tokenRanges:)")
let startIndex = s.index(s.startIndex, offsetBy: 5)
let endIndex = s.index(s.startIndex, offsetBy: 17)
var tokenRanges: [Range<String.Index>] = []
var tags = s.linguisticTags(in: startIndex..<endIndex,
let tags = s.linguisticTags(in: startIndex..<endIndex,
scheme: NSLinguisticTagSchemeTokenType,
options: [],
orthography: nil, tokenRanges: &tokenRanges)

View File

@@ -228,7 +228,7 @@ func checkCharacterComparison(
}
for test in comparisonTests {
if test.lhs.characters.count == 1 && test.rhs.characters.count == 1 {
if test.lhs.count == 1 && test.rhs.count == 1 {
StringTests.test("Character.{Equatable,Hashable,Comparable}: line \(test.loc.line)")
.xfail(test.xfail)
.code {
@@ -262,11 +262,11 @@ func checkHasPrefixHasSuffix(
// To determine the expected results, compare grapheme clusters,
// scalar-to-scalar, of the NFD form of the strings.
let lhsNFDGraphemeClusters =
lhs.decomposedStringWithCanonicalMapping.characters.map {
lhs.decomposedStringWithCanonicalMapping.map {
Array(String($0).unicodeScalars)
}
let rhsNFDGraphemeClusters =
rhs.decomposedStringWithCanonicalMapping.characters.map {
rhs.decomposedStringWithCanonicalMapping.map {
Array(String($0).unicodeScalars)
}
let expectHasPrefix = lhsNFDGraphemeClusters.starts(

View File

@@ -735,7 +735,7 @@ StringTests.test("stringCoreExtensibility")
for boundary in 0..<count {
var x = (
k == 0 ? asciiString("b".characters)
k == 0 ? asciiString("b")
: k == 1 ? ("b" as NSString as String)
: ("b" as NSMutableString as String)
)._core
@@ -775,7 +775,7 @@ StringTests.test("stringCoreReserve")
switch k {
case 0: (base, startedNative) = (String(), true)
case 1: (base, startedNative) = (asciiString("x".characters), true)
case 1: (base, startedNative) = (asciiString("x"), true)
case 2: (base, startedNative) = ("Ξ", true)
case 3: (base, startedNative) = ("x" as NSString as String, false)
case 4: (base, startedNative) = ("x" as NSMutableString as String, false)
@@ -861,12 +861,12 @@ StringTests.test("CharacterViewReplace") {
for s1 in [narrow, wide] {
for s2 in [narrow, wide] {
checkRangeReplaceable(
{ String.CharacterView(makeStringCore(s1)) },
{ String.CharacterView(makeStringCore(s2 + s2)[0..<$0]) }
{ String(makeStringCore(s1)) },
{ String(makeStringCore(s2 + s2)[0..<$0]) }
)
checkRangeReplaceable(
{ String.CharacterView(makeStringCore(s1)) },
{ Array(String.CharacterView(makeStringCore(s2 + s2)[0..<$0])) }
{ String(makeStringCore(s1)) },
{ Array(String(makeStringCore(s2 + s2)[0..<$0])) }
)
}
}
@@ -1281,12 +1281,12 @@ StringTests.test("String.append(_: Character)") {
for prefix in ["", " "] {
let base = baseStrings[baseIdx]
for inputIdx in baseCharacters.indices {
let input = (prefix + String(baseCharacters[inputIdx])).characters.last!
let input = (prefix + String(baseCharacters[inputIdx])).last!
var s = base
s.append(input)
expectEqualSequence(
Array(base.characters) + [input],
Array(s.characters),
Array(base) + [input],
Array(s),
"baseIdx=\(baseIdx) inputIdx=\(inputIdx)")
}
}
@@ -1495,9 +1495,9 @@ let removeSubrangeTests = [
StringTests.test("String.replaceSubrange()/characters/range") {
for test in replaceSubrangeTests {
var theString = test.original
let c = test.original.characters
let c = test.original
let rangeToReplace = test.rangeSelection.range(in: c)
let newCharacters : [Character] = Array(test.newElements.characters)
let newCharacters : [Character] = Array(test.newElements)
theString.replaceSubrange(rangeToReplace, with: newCharacters)
expectEqual(
test.expected,
@@ -1509,7 +1509,7 @@ StringTests.test("String.replaceSubrange()/characters/range") {
StringTests.test("String.replaceSubrange()/string/range") {
for test in replaceSubrangeTests {
var theString = test.original
let c = test.original.characters
let c = test.original
let rangeToReplace = test.rangeSelection.range(in: c)
theString.replaceSubrange(rangeToReplace, with: test.newElements)
expectEqual(
@@ -1525,9 +1525,9 @@ StringTests.test("String.replaceSubrange()/characters/closedRange") {
continue
}
var theString = test.original
let c = test.original.characters
let c = test.original
let rangeToReplace = test.rangeSelection.closedRange(in: c)
let newCharacters = Array(test.newElements.characters)
let newCharacters = Array(test.newElements)
theString.replaceSubrange(rangeToReplace, with: newCharacters)
expectEqual(
closedExpected,
@@ -1542,7 +1542,7 @@ StringTests.test("String.replaceSubrange()/string/closedRange") {
continue
}
var theString = test.original
let c = test.original.characters
let c = test.original
let rangeToReplace = test.rangeSelection.closedRange(in: c)
theString.replaceSubrange(rangeToReplace, with: test.newElements)
expectEqual(
@@ -1555,7 +1555,7 @@ StringTests.test("String.replaceSubrange()/string/closedRange") {
StringTests.test("String.removeSubrange()/range") {
for test in removeSubrangeTests {
var theString = test.original
let c = test.original.characters
let c = test.original
let rangeToRemove = test.rangeSelection.range(in: c)
theString.removeSubrange(rangeToRemove)
expectEqual(
@@ -1572,7 +1572,7 @@ StringTests.test("String.removeSubrange()/closedRange") {
default: break
}
var theString = test.original
let c = test.original.characters
let c = test.original
let rangeToRemove = test.rangeSelection.closedRange(in: c)
theString.removeSubrange(rangeToRemove)
expectEqual(
@@ -1589,7 +1589,7 @@ StringTests.test("String.removeSubrange()/closedRange") {
public let testSuffix = "z"
StringTests.test("COW.Smoke") {
var s1 = "Cypseloides" + testSuffix
var identity1 = s1._rawIdentifier()
let identity1 = s1._rawIdentifier()
var s2 = s1
expectEqual(identity1, s2._rawIdentifier())
@@ -1617,11 +1617,11 @@ var testCases: [COWStringTest] {
for test in testCases {
StringTests.test("COW.\(test.name).IndexesDontAffectUniquenessCheck") {
var s = test.test + testSuffix
let s = test.test + testSuffix
let identity1 = s._rawIdentifier()
var startIndex = s.startIndex
var endIndex = s.endIndex
let startIndex = s.startIndex
let endIndex = s.endIndex
expectNotEqual(startIndex, endIndex)
expectLT(startIndex, endIndex)
expectLE(startIndex, endIndex)
@@ -1638,10 +1638,10 @@ for test in testCases {
for test in testCases {
StringTests.test("COW.\(test.name).SubscriptWithIndexDoesNotReallocate") {
var s = test.test + testSuffix
var identity1 = s._rawIdentifier()
let s = test.test + testSuffix
let identity1 = s._rawIdentifier()
var startIndex = s.startIndex
let startIndex = s.startIndex
let empty = startIndex == s.endIndex
expectNotEqual((s.startIndex < s.endIndex), empty)
expectLE(s.startIndex, s.endIndex)
@@ -1655,7 +1655,7 @@ for test in testCases {
StringTests.test("COW.\(test.name).RemoveAtDoesNotReallocate") {
do {
var s = test.test + testSuffix
var identity1 = s._rawIdentifier()
let identity1 = s._rawIdentifier()
let index1 = s.startIndex
expectEqual(identity1, s._rawIdentifier())
@@ -1665,18 +1665,18 @@ for test in testCases {
}
do {
var s1 = test.test + testSuffix
var identity1 = s1._rawIdentifier()
let s1 = test.test + testSuffix
let identity1 = s1._rawIdentifier()
var s2 = s1
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
var index1 = s1.startIndex
let index1 = s1.startIndex
expectEqual(identity1, s1._rawIdentifier())
expectEqual(identity1, s2._rawIdentifier())
let removed = s2.remove(at: index1)
let _ = s2.remove(at: index1)
expectEqual(identity1, s1._rawIdentifier())
expectTrue(identity1 == s2._rawIdentifier())
@@ -1691,14 +1691,14 @@ for test in testCases {
expectGT(s.count, 0)
s.removeAll()
var identity1 = s._rawIdentifier()
let identity1 = s._rawIdentifier()
expectEqual(0, s.count)
expectEqual(identity1, s._rawIdentifier())
}
do {
var s = test.test + testSuffix
var identity1 = s._rawIdentifier()
let identity1 = s._rawIdentifier()
expectGT(s.count, 3)
s.removeAll(keepingCapacity: true)
@@ -1707,13 +1707,13 @@ for test in testCases {
}
do {
var s1 = test.test + testSuffix
var identity1 = s1._rawIdentifier()
let s1 = test.test + testSuffix
let identity1 = s1._rawIdentifier()
expectGT(s1.count, 0)
var s2 = s1
s2.removeAll()
var identity2 = s2._rawIdentifier()
let identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectTrue(identity2 != identity1)
expectGT(s1.count, 0)
@@ -1725,13 +1725,13 @@ for test in testCases {
}
do {
var s1 = test.test + testSuffix
var identity1 = s1._rawIdentifier()
let s1 = test.test + testSuffix
let identity1 = s1._rawIdentifier()
expectGT(s1.count, 0)
var s2 = s1
s2.removeAll(keepingCapacity: true)
var identity2 = s2._rawIdentifier()
let identity2 = s2._rawIdentifier()
expectEqual(identity1, s1._rawIdentifier())
expectTrue(identity2 != identity1)
expectGT(s1.count, 0)
@@ -1746,8 +1746,8 @@ for test in testCases {
for test in testCases {
StringTests.test("COW.\(test.name).CountDoesNotReallocate") {
var s = test.test + testSuffix
var identity1 = s._rawIdentifier()
let s = test.test + testSuffix
let identity1 = s._rawIdentifier()
expectGT(s.count, 0)
expectEqual(identity1, s._rawIdentifier())
@@ -1756,8 +1756,8 @@ for test in testCases {
for test in testCases {
StringTests.test("COW.\(test.name).GenerateDoesNotReallocate") {
var s = test.test + testSuffix
var identity1 = s._rawIdentifier()
let s = test.test + testSuffix
let identity1 = s._rawIdentifier()
var iter = s.makeIterator()
var copy = String()
@@ -1771,11 +1771,11 @@ for test in testCases {
for test in testCases {
StringTests.test("COW.\(test.name).EqualityTestDoesNotReallocate") {
var s1 = test.test + testSuffix
var identity1 = s1._rawIdentifier()
let s1 = test.test + testSuffix
let identity1 = s1._rawIdentifier()
var s2 = test.test + testSuffix
var identity2 = s2._rawIdentifier()
let identity2 = s2._rawIdentifier()
expectEqual(s1, s2)
expectEqual(identity1, s1._rawIdentifier())