Skip to content

Commit 98ada1b

Browse files
[stdlib] Fix buffer size of small-capacity strings (#67929)
1 parent fa0e628 commit 98ada1b

File tree

3 files changed

+11
-4
lines changed

3 files changed

+11
-4
lines changed

stdlib/public/core/SmallString.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
//
33
// This source file is part of the Swift.org open source project
44
//
5-
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
5+
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
66
// Licensed under Apache License v2.0 with Runtime Library Exception
77
//
88
// See https://swift.org/LICENSE.txt for license information
@@ -243,7 +243,9 @@ extension _SmallString {
243243
fileprivate mutating func withMutableCapacity(
244244
_ f: (UnsafeMutableRawBufferPointer) throws -> Int
245245
) rethrows {
246-
let len = try withUnsafeMutableBytes(of: &_storage, f)
246+
let len = try withUnsafeMutableBytes(of: &_storage) {
247+
try f(.init(start: $0.baseAddress, count: _SmallString.capacity))
248+
}
247249

248250
if len <= 0 {
249251
_debugPrecondition(len == 0)

stdlib/public/core/String.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
//
33
// This source file is part of the Swift.org open source project
44
//
5-
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
5+
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
66
// Licensed under Apache License v2.0 with Runtime Library Exception
77
//
88
// See https://swift.org/LICENSE.txt for license information
@@ -558,7 +558,9 @@ extension String {
558558
) throws -> Int
559559
) rethrows {
560560
if _fastPath(capacity <= _SmallString.capacity) {
561-
let smol = try _SmallString(initializingUTF8With: initializer)
561+
let smol = try _SmallString(initializingUTF8With: {
562+
try initializer(.init(start: $0.baseAddress, count: capacity))
563+
})
562564
// Fast case where we fit in a _SmallString and don't need UTF8 validation
563565
if _fastPath(smol.isASCII) {
564566
self = String(_StringGuts(smol))

test/stdlib/StringCreate.swift

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,9 @@ if #available(SwiftStdlib 5.3, *) {
7070
func test(bufferSize: Int, input: [UInt8], expected: String) {
7171
let strs = (0..<100).map { _ in
7272
String(unsafeUninitializedCapacity: bufferSize) { buffer in
73+
if #available(SwiftStdlib 5.10, *) {
74+
expectEqual(bufferSize, buffer.count)
75+
}
7376
_ = buffer.initialize(from: input)
7477
return input.count
7578
}

0 commit comments

Comments
 (0)