Browse Source

make bitPadding mutable to avoid copying

Marcin Krzyżanowski 9 years ago
parent
commit
351f70a818

+ 1 - 1
Sources/CryptoSwift/MD5.swift

@@ -113,7 +113,7 @@ extension MD5: Updatable {
 
         if isLast {
             // Step 1. Append padding
-            self.accumulated = bitPadding(to: self.accumulated, blockSize: MD5.blockSize, allowance: 64 / 8)
+            bitPadding(to: &self.accumulated, blockSize: MD5.blockSize, allowance: 64 / 8)
 
             // Step 2. Append Length a 64-bit representation of lengthInBits
             let lengthInBits = self.accumulatedLength * 8

+ 1 - 1
Sources/CryptoSwift/SHA1.swift

@@ -99,7 +99,7 @@ extension SHA1: Updatable {
 
         if isLast {
             // Step 1. Append padding
-            self.accumulated = bitPadding(to: self.accumulated, blockSize: SHA1.blockSize, allowance: 64 / 8)
+            bitPadding(to: &self.accumulated, blockSize: SHA1.blockSize, allowance: 64 / 8)
 
             // Step 2. Append Length a 64-bit representation of lengthInBits
             let lengthInBits = self.accumulatedLength * 8

+ 1 - 1
Sources/CryptoSwift/SHA2.swift

@@ -265,7 +265,7 @@ extension SHA2: Updatable {
 
         if isLast {
             // Step 1. Append padding
-            self.accumulated = bitPadding(to: self.accumulated, blockSize: self.blockSize, allowance: self.blockSize / 8)
+            bitPadding(to: &self.accumulated, blockSize: self.blockSize, allowance: self.blockSize / 8)
 
             // Step 2. Append Length a 64-bit representation of lengthInBits
             let lengthInBits = self.accumulatedLength * 8

+ 7 - 13
Sources/CryptoSwift/Utils.swift

@@ -68,22 +68,16 @@ func xor(_ a: Array<UInt8>, _ b:Array<UInt8>) -> Array<UInt8> {
  - blockSize: Padding size in bytes.
  - allowance: Excluded trailing number of bytes.
  */
-func bitPadding(to data: Array<UInt8>, blockSize: Int, allowance: Int = 0) -> Array<UInt8> {
-    var tmp = data
-
+@inline(__always)
+func bitPadding(to data: inout Array<UInt8>, blockSize: Int, allowance: Int = 0) {
     // Step 1. Append Padding Bits
     // append one bit (UInt8 with one bit) to message
-    tmp.append(0x80)
+    data.append(0x80)
 
     // Step 2. append "0" bit until message length in bits ≡ 448 (mod 512)
-    let msgLength = tmp.count
-
-    let max = blockSize - allowance // 448, 986
-    if tmp.count % blockSize < max { // 448
-        tmp += Array<UInt8>(repeating: 0, count: max - (msgLength % blockSize))
-    } else {
-        tmp += Array<UInt8>(repeating: 0, count: blockSize + max - (msgLength % blockSize))
-    }
+    let msgLength = data.count
+    let max = blockSize &- allowance
+    let l = msgLength % blockSize
 
-    return tmp
+    data += Array<UInt8>(repeating: 0, count: (l >= max ? blockSize : 0) &+ max &- l)
 }