Skip to content

Commit

Permalink
Fix buffer initialization and cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Jarema authored Nov 9, 2023
1 parent 74e9651 commit 7f723a2
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions Sources/Base32/Base32.swift
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ private func base32encode(_ data: UnsafeRawPointer, _ length: Int, _ table: [Int

let resultBufferSize = Int(ceil(Double(length) / 5)) * 8 + 1 // need null termination
let resultBuffer = UnsafeMutablePointer<Int8>.allocate(capacity: resultBufferSize)
resultBuffer.initialize(repeating: 0, count: resultBufferSize)
var encoded = resultBuffer

// encode regular blocks
Expand Down Expand Up @@ -208,6 +209,8 @@ private func base32encode(_ data: UnsafeRawPointer, _ length: Int, _ table: [Int
default: break
}

// Calculate the position where the null terminator should be placed
let encodedLength = (encoded - resultBuffer) + (length > 0 ? 8 : 0)
// padding
if padding {
let pad = Int8(UnicodeScalar("=").value)
Expand All @@ -232,14 +235,11 @@ private func base32encode(_ data: UnsafeRawPointer, _ length: Int, _ table: [Int
encoded[8] = 0
break
}
} else {
if length == 0 {
encoded[0] = 0
} else {
encoded[8] = 0
}
}

// Set the null terminator at the correct position
resultBuffer[encodedLength] = 0

// return
if let base32Encoded = String(validatingUTF8: resultBuffer) {
resultBuffer.deallocate()
Expand Down

0 comments on commit 7f723a2

Please sign in to comment.