Skip to content

Commit b24412f

Browse files
committed
[stdlib] a less public association key
- with tweaks in associated object code
1 parent e5ecab0 commit b24412f

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

stdlib/public/core/StringGuts.swift

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -421,22 +421,24 @@ extension _StringGuts {
421421
extension _StringGuts {
422422

423423
private static var associationKey: UnsafeRawPointer {
424+
struct AssociationKey {}
424425
// We never dereference this, we only use this address as a unique key
425-
unsafe unsafeBitCast(
426-
ObjectIdentifier(__StringStorage.self),
426+
return unsafe unsafeBitCast(
427+
ObjectIdentifier(AssociationKey.self),
427428
to: UnsafeRawPointer.self
428429
)
429430
}
430431

431432
internal func getAssociatedStorage() -> __StringStorage? {
433+
_internalInvariant(_object.hasObjCBridgeableObject)
432434
let getter = unsafe unsafeBitCast(
433435
getGetAssociatedObjectPtr(),
434436
to: (@convention(c)(
435437
AnyObject,
436438
UnsafeRawPointer
437439
) -> UnsafeRawPointer?).self
438440
)
439-
_precondition(_object.hasObjCBridgeableObject)
441+
440442
if let assocPtr = unsafe getter(
441443
_object.objCBridgeableObject,
442444
Self.associationKey
@@ -449,6 +451,7 @@ extension _StringGuts {
449451
}
450452

451453
internal func setAssociatedStorage(_ storage: __StringStorage) {
454+
_internalInvariant(_object.hasObjCBridgeableObject)
452455
let setter = unsafe unsafeBitCast(
453456
getSetAssociatedObjectPtr(),
454457
to: (@convention(c)(
@@ -468,7 +471,7 @@ extension _StringGuts {
468471
}
469472

470473
internal func getOrAllocateAssociatedStorage() -> __StringStorage {
471-
_precondition(_object.hasObjCBridgeableObject)
474+
_internalInvariant(_object.hasObjCBridgeableObject)
472475
let unwrapped: __StringStorage
473476
// libobjc already provides the necessary memory barriers for
474477
// double checked locking to be safe, per comments on
@@ -482,8 +485,10 @@ extension _StringGuts {
482485
unwrapped = storage
483486
} else {
484487
var contents = String.UnicodeScalarView()
485-
// always reserve a size larger than a small string
486-
contents.reserveCapacity(Swift.max(_SmallString.capacity + 1, 1 + count + count >> 1))
488+
// always reserve a capacity larger than a small string
489+
contents.reserveCapacity(
490+
Swift.max(_SmallString.capacity + 1, count + count >> 1)
491+
)
487492
for c in String.UnicodeScalarView(self) {
488493
contents.append(c)
489494
}

0 commit comments

Comments
 (0)