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)) } } }