From adca1f70b1f67bed7431bdfb8cebc3b544e80d28 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Wed, 6 Mar 2024 17:45:23 -0800 Subject: [PATCH] Fix `SystemString.withCSIA()` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The original implementation simply forwarded to the underlying `nullTerminatedStorage`, which contains one element – a null terminator – more than the actual `String`. - This isn’t in keeping with the sperit of `withContiguousStorageIfAvailable()`, which should present exactly the elements of the collection. --- Sources/System/SystemString.swift | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/Sources/System/SystemString.swift b/Sources/System/SystemString.swift index 9bfef49..8ca643b 100644 --- a/Sources/System/SystemString.swift +++ b/Sources/System/SystemString.swift @@ -142,31 +142,38 @@ extension SystemString: RangeReplaceableCollection { nullTerminatedStorage.reserveCapacity(1 + n) } - // TODO: Below include null terminator, is this desired? - internal func withContiguousStorageIfAvailable( _ body: (UnsafeBufferPointer) throws -> R ) rethrows -> R? { - try nullTerminatedStorage.withContiguousStorageIfAvailable(body) + // Do not include the null terminator, it is outside the Collection + try nullTerminatedStorage.withContiguousStorageIfAvailable { + try body(.init(start: $0.baseAddress, count: $0.count-1)) + } } internal mutating func withContiguousMutableStorageIfAvailable( _ body: (inout UnsafeMutableBufferPointer) throws -> R ) rethrows -> R? { defer { _invariantCheck() } - return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable(body) + // Do not include the null terminator, it is outside the Collection + return try nullTerminatedStorage.withContiguousMutableStorageIfAvailable { + var buffer = UnsafeMutableBufferPointer( + start: $0.baseAddress, count: $0.count-1 + ) + return try body(&buffer) + } } } extension SystemString: Hashable, Codable {} extension SystemString { - // TODO: Below include null terminator, is this desired? + // withSystemChars includes the null terminator internal func withSystemChars( _ f: (UnsafeBufferPointer) throws -> T ) rethrows -> T { - try withContiguousStorageIfAvailable(f)! + try nullTerminatedStorage.withContiguousStorageIfAvailable(f)! } internal func withCodeUnits(