From def7b1a70c2fb303693c12eb6852d2e5560deeb5 Mon Sep 17 00:00:00 2001 From: Guillaume Lessard Date: Thu, 7 Mar 2024 16:31:54 -0800 Subject: [PATCH] Fix behaviour of `withCodeUnits()` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The original implementation includes a trailing zero with the full collection, but the implementation for a slice does not. As a result, given a `let s: SystemString`, `s.string` was not equal to `s[…].string` --- Sources/System/SystemString.swift | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/Sources/System/SystemString.swift b/Sources/System/SystemString.swift index f5c558d..67a7ffb 100644 --- a/Sources/System/SystemString.swift +++ b/Sources/System/SystemString.swift @@ -176,17 +176,14 @@ extension SystemString { try nullTerminatedStorage.withContiguousStorageIfAvailable(f)! } + // withCodeUnits does not include the null terminator internal func withCodeUnits( _ f: (UnsafeBufferPointer) throws -> T ) rethrows -> T { - try withSystemChars { chars in - let length = chars.count * MemoryLayout.stride - let count = length / MemoryLayout.stride - return try chars.baseAddress!.withMemoryRebound( - to: CInterop.PlatformUnicodeEncoding.CodeUnit.self, - capacity: count - ) { pointer in - try f(UnsafeBufferPointer(start: pointer, count: count)) + try withSystemChars { + try $0.withMemoryRebound(to: CInterop.PlatformUnicodeEncoding.CodeUnit.self) { + assert($0.last == .zero) + return try f(.init(start: $0.baseAddress, count: $0.count&-1)) } } }