Skip to content

Commit d77fa0b

Browse files
authored
Merge pull request swiftlang#63307 from lorentey/identical-string-check
[stdlib] Add String._isIdentical(to:)
2 parents c6942ee + 1bc3f79 commit d77fa0b

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

stdlib/public/core/String.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -401,6 +401,26 @@ extension String {
401401
}
402402
}
403403

404+
extension String {
405+
/// Returns a boolean value indicating whether this string is identical to
406+
/// `other`.
407+
///
408+
/// Two string values are identical if there is no way to distinguish between
409+
/// them.
410+
///
411+
/// Comparing strings this way includes comparing (normally) hidden
412+
/// implementation details such as the memory location of any underlying
413+
/// string storage object. Therefore, identical strings are guaranteed to
414+
/// compare equal with `==`, but not all equal strings are considered
415+
/// identical.
416+
///
417+
/// - Performance: O(1)
418+
@_alwaysEmitIntoClient
419+
public func _isIdentical(to other: Self) -> Bool {
420+
self._guts.rawBits == other._guts.rawBits
421+
}
422+
}
423+
404424
extension String {
405425
// This force type-casts element to UInt8, since we cannot currently
406426
// communicate to the type checker that we proved this with our dynamic

test/stdlib/StringAPI.swift

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -506,4 +506,28 @@ StringTests.test("Regression/radar-87371813") {
506506
expectEqual(s2.hashValue, s3.hashValue)
507507
}
508508

509+
StringTests.test("_isIdentical(to:)") {
510+
let a = "Hello"
511+
let b = "Hello"
512+
expectTrue(a._isIdentical(to: a))
513+
expectTrue(b._isIdentical(to: b))
514+
expectTrue(a._isIdentical(to: b)) // Both small ASCII strings
515+
expectTrue(b._isIdentical(to: a))
516+
517+
let c = "Cafe\u{301}"
518+
let d = "Cafe\u{301}"
519+
let e = "Café"
520+
expectTrue(c._isIdentical(to: d))
521+
expectTrue(d._isIdentical(to: c))
522+
expectFalse(c._isIdentical(to: e))
523+
expectFalse(d._isIdentical(to: e))
524+
525+
let f = String(repeating: "foo", count: 1000)
526+
let g = String(repeating: "foo", count: 1000)
527+
expectEqual(f, g)
528+
expectFalse(f._isIdentical(to: g)) // Two large, distinct native strings
529+
expectTrue(f._isIdentical(to: f))
530+
expectTrue(g._isIdentical(to: g))
531+
}
532+
509533
runAllTests()

0 commit comments

Comments
 (0)