@@ -470,18 +470,17 @@ internal struct _ContiguousArrayBuffer<Element>: _ArrayBufferProtocol {
470470 nonmutating set {
471471 if #available( macOS 9999 , iOS 9999 , watchOS 9999 , tvOS 9999 , * ) {
472472 if ( _COWChecksEnabled ( ) ) {
473- if newValue {
474- if capacity > 0 {
475- let wasImmutable = _swift_setImmutableCOWBuffer ( _storage, true )
473+ // Make sure to not modify the empty array singleton (which has a
474+ // capacity of 0).
475+ if capacity > 0 {
476+ let wasImmutable = _swift_setImmutableCOWBuffer ( _storage, newValue)
477+ if newValue {
476478 _internalInvariant ( !wasImmutable,
477479 " re-setting immutable array buffer to immutable " )
480+ } else {
481+ _internalInvariant ( wasImmutable,
482+ " re-setting mutable array buffer to mutable " )
478483 }
479- } else {
480- _internalInvariant ( capacity > 0 ,
481- " setting empty array buffer to mutable " )
482- let wasImmutable = _swift_setImmutableCOWBuffer ( _storage, false )
483- _internalInvariant ( wasImmutable,
484- " re-setting mutable array buffer to mutable " )
485484 }
486485 }
487486 }
@@ -698,7 +697,7 @@ internal struct _ContiguousArrayBuffer<Element>: _ArrayBufferProtocol {
698697
699698 /// Puts the buffer in an immutable state.
700699 ///
701- /// - Precondition: The buffer must be mutable.
700+ /// - Precondition: The buffer must be mutable or the empty array singleton .
702701 ///
703702 /// - Warning: After a call to `endCOWMutation` the buffer must not be mutated
704703 /// until the next call of `beginCOWMutation`.
0 commit comments