Skip to content

Commit 22bc234

Browse files
committed
Faster encoding on Swift 5.3
1 parent c1096d0 commit 22bc234

File tree

1 file changed

+35
-16
lines changed

1 file changed

+35
-16
lines changed

Sources/Base64Kit/Base64.swift

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -27,27 +27,46 @@ extension Base64 {
2727
? Base64.encodeBase64Url
2828
: Base64.encodeBase64
2929

30-
var outputBytes = [UInt8]()
31-
outputBytes.reserveCapacity(newCapacity)
32-
3330
var input = bytes.makeIterator()
3431

35-
while let firstByte = input.next() {
36-
let secondByte = input.next()
37-
let thirdByte = input.next()
32+
#if swift(>=5.3) && os(Linux)
33+
return String(unsafeUninitializedCapacity: newCapacity) { buffer in
34+
var i = 0
35+
while let firstByte = input.next() {
36+
let secondByte = input.next()
37+
let thirdByte = input.next()
3838

39-
let firstChar = Base64.encode(alphabet: alphabet, firstByte: firstByte)
40-
let secondChar = Base64.encode(alphabet: alphabet, firstByte: firstByte, secondByte: secondByte)
41-
let thirdChar = Base64.encode(alphabet: alphabet, secondByte: secondByte, thirdByte: thirdByte)
42-
let forthChar = Base64.encode(alphabet: alphabet, thirdByte: thirdByte)
39+
buffer[i] = Base64.encode(alphabet: alphabet, firstByte: firstByte)
40+
buffer[i + 1] = Base64.encode(alphabet: alphabet, firstByte: firstByte, secondByte: secondByte)
41+
buffer[i + 2] = Base64.encode(alphabet: alphabet, secondByte: secondByte, thirdByte: thirdByte)
42+
buffer[i + 3] = Base64.encode(alphabet: alphabet, thirdByte: thirdByte)
4343

44-
outputBytes.append(firstChar)
45-
outputBytes.append(secondChar)
46-
outputBytes.append(thirdChar)
47-
outputBytes.append(forthChar)
48-
}
44+
i += 4
45+
}
46+
47+
return newCapacity
48+
}
49+
#else
50+
var outputBytes = [UInt8]()
51+
outputBytes.reserveCapacity(newCapacity)
52+
53+
while let firstByte = input.next() {
54+
let secondByte = input.next()
55+
let thirdByte = input.next()
56+
57+
let firstChar = Base64.encode(alphabet: alphabet, firstByte: firstByte)
58+
let secondChar = Base64.encode(alphabet: alphabet, firstByte: firstByte, secondByte: secondByte)
59+
let thirdChar = Base64.encode(alphabet: alphabet, secondByte: secondByte, thirdByte: thirdByte)
60+
let forthChar = Base64.encode(alphabet: alphabet, thirdByte: thirdByte)
61+
62+
outputBytes.append(firstChar)
63+
outputBytes.append(secondChar)
64+
outputBytes.append(thirdChar)
65+
outputBytes.append(forthChar)
66+
}
4967

50-
return String(decoding: outputBytes, as: Unicode.UTF8.self)
68+
return String(decoding: outputBytes, as: Unicode.UTF8.self)
69+
#endif
5170
}
5271

5372
// MARK: Internal

0 commit comments

Comments
 (0)