Skip to content

Commit b0dd7d9

Browse files
committed
Removes creating intermediate objects in base64 decoding
1 parent 761099f commit b0dd7d9

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

Sources/Foundation/NSData.swift

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -206,8 +206,10 @@ open class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
206206

207207
/// Initializes a data object with the given Base64 encoded string.
208208
public init?(base64Encoded base64String: String, options: Base64DecodingOptions = []) {
209-
let encodedBytes = Array(base64String.utf8)
210-
guard var decodedBytes = NSData.base64DecodeBytes(encodedBytes, options: options) else {
209+
guard var decodedBytes = base64String.utf8CString.withUnsafeBytes( { buffer -> [UInt8]? in
210+
let bufferDroppingTerminatingNul = UnsafeRawBufferPointer(rebasing: buffer.dropLast())
211+
return NSData.base64DecodeBytes(bufferDroppingTerminatingNul, options: options)
212+
}) else {
211213
return nil
212214
}
213215
super.init()
@@ -216,9 +218,8 @@ open class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
216218

217219
/// Initializes a data object with the given Base64 encoded data.
218220
public init?(base64Encoded base64Data: Data, options: Base64DecodingOptions = []) {
219-
var encodedBytes = [UInt8](repeating: 0, count: base64Data.count)
220-
base64Data._nsObject.getBytes(&encodedBytes, length: encodedBytes.count)
221-
guard var decodedBytes = NSData.base64DecodeBytes(encodedBytes, options: options) else {
221+
guard var decodedBytes = base64Data
222+
.withUnsafeBytes({ NSData.base64DecodeBytes($0, options: options) }) else {
222223
return nil
223224
}
224225
super.init()
@@ -670,7 +671,7 @@ open class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
670671
- parameter options: Options for handling invalid input
671672
- returns: The decoded bytes.
672673
*/
673-
private static func base64DecodeBytes(_ bytes: [UInt8], options: Base64DecodingOptions = []) -> [UInt8]? {
674+
private static func base64DecodeBytes(_ bytes: UnsafeRawBufferPointer, options: Base64DecodingOptions = []) -> [UInt8]? {
674675
var decodedBytes = [UInt8]()
675676
decodedBytes.reserveCapacity((bytes.count/3)*2)
676677

0 commit comments

Comments
 (0)