Skip to content

Commit f77c4d4

Browse files
committed
[stdlib] convert inout-taking withUnsafeBytes() to typed throws
1 parent 09a5018 commit f77c4d4

File tree

1 file changed

+24
-10
lines changed

1 file changed

+24
-10
lines changed

stdlib/public/core/UnsafeRawBufferPointer.swift.gyb

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1242,11 +1242,23 @@ public func withUnsafeMutableBytes<T, Result>(
12421242
/// `withUnsafeMutableBytes(of:_:)` instead.
12431243
/// - Returns: The return value, if any, of the `body` closure.
12441244
@inlinable
1245-
public func withUnsafeBytes<T, Result>(
1245+
@_alwaysEmitIntoClient
1246+
public func withUnsafeBytes<T, Result, E: Error>(
1247+
of value: inout T,
1248+
_ body: (UnsafeRawBufferPointer) throws(E) -> Result
1249+
) throws(E) -> Result {
1250+
let address = UnsafeRawPointer(Builtin.addressof(&value))
1251+
return try body(.init(start: address, count: MemoryLayout<T>.size))
1252+
}
1253+
1254+
/// ABI: Historical withUnsafeBytes(of:_:) rethrows,
1255+
/// expressed as "throws", which is ABI-compatible with "rethrows".
1256+
@_silgen_name("$ss15withUnsafeBytes2of_q_xz_q_SWKXEtKr0_lF")
1257+
@usableFromInline
1258+
func __abi_se0413_withUnsafeBytes<T, Result>(
12461259
of value: inout T,
12471260
_ body: (UnsafeRawBufferPointer) throws -> Result
1248-
) rethrows -> Result
1249-
{
1261+
) throws -> Result {
12501262
return try withUnsafePointer(to: &value) {
12511263
try body(UnsafeRawBufferPointer(start: $0, count: MemoryLayout<T>.size))
12521264
}
@@ -1258,14 +1270,16 @@ public func withUnsafeBytes<T, Result>(
12581270
/// This function is similar to `withUnsafeBytes`, except that it
12591271
/// doesn't trigger stack protection for the pointer.
12601272
@_alwaysEmitIntoClient
1261-
public func _withUnprotectedUnsafeBytes<T, Result>(
1273+
public func _withUnprotectedUnsafeBytes<T, Result, E: Error>(
12621274
of value: inout T,
1263-
_ body: (UnsafeRawBufferPointer) throws -> Result
1264-
) rethrows -> Result
1265-
{
1266-
return try _withUnprotectedUnsafePointer(to: &value) {
1267-
try body(UnsafeRawBufferPointer(start: $0, count: MemoryLayout<T>.size))
1268-
}
1275+
_ body: (UnsafeRawBufferPointer) throws(E) -> Result
1276+
) throws(E) -> Result {
1277+
#if $BuiltinUnprotectedAddressOf
1278+
let p = UnsafeRawPointer(Builtin.unprotectedAddressOf(&value))
1279+
#else
1280+
let p = UnsafeRawPointer(Builtin.addressof(&value))
1281+
#endif
1282+
return try body(.init(start: p, count: MemoryLayout<T>.size))
12691283
}
12701284

12711285
/// Invokes the given closure with a buffer pointer covering the raw bytes of

0 commit comments

Comments
 (0)