瀏覽代碼

Apply swiftformat

maxep 5 年之前
父節點
當前提交
58f9727664
共有 54 個文件被更改,包括 881 次插入578 次删除
  1. 11 0
      .swiftformat
  2. 42 26
      Package.swift
  3. 8 12
      Sources/Binary/Bytes.swift
  4. 12 12
      Sources/Binary/BytesRepresentable.swift
  5. 0 1
      Sources/Binary/Input.swift
  6. 0 1
      Sources/Binary/Output.swift
  7. 14 23
      Sources/Binary/Streamable.swift
  8. 5 5
      Sources/Binary/TLV.swift
  9. 1 3
      Sources/Crypto/AES.swift
  10. 2 4
      Sources/Crypto/Argon2.swift
  11. 3 4
      Sources/Crypto/ChaCha20.swift
  12. 1 1
      Sources/Crypto/Cipher.swift
  13. 2 2
      Sources/Crypto/Error.swift
  14. 4 7
      Sources/Crypto/Hash.swift
  15. 1 1
      Sources/Crypto/KeyDerivation.swift
  16. 2 3
      Sources/Crypto/Salsa20.swift
  17. 1 2
      Sources/Crypto/Twofish.swift
  18. 12 17
      Sources/Gzip/Gzip.swift
  19. 1 1
      Sources/KDB/CompositeKey.swift
  20. 5 7
      Sources/KDB/Database.swift
  21. 11 13
      Sources/KDB/Date.swift
  22. 17 18
      Sources/KDB/Entry.swift
  23. 13 13
      Sources/KDB/Group.swift
  24. 6 6
      Sources/KDB/Header.swift
  25. 6 5
      Sources/KDB/Row.swift
  26. 1 4
      Sources/KDBX/Cipher.swift
  27. 1 2
      Sources/KDBX/CompositeKey.swift
  28. 1 1
      Sources/KDBX/Database.swift
  29. 1 1
      Sources/KDBX/Database0.swift
  30. 3 3
      Sources/KDBX/Database3.swift
  31. 4 4
      Sources/KDBX/Database4.swift
  32. 4 5
      Sources/KDBX/File.swift
  33. 27 27
      Sources/KDBX/Header.swift
  34. 24 25
      Sources/KDBX/KeyDerivation.swift
  35. 17 22
      Sources/KDBX/Variant.swift
  36. 6 5
      Sources/KeePass/CompositeKey.swift
  37. 1 1
      Sources/KeePass/Database.swift
  38. 24 24
      Sources/KeePass/Entry.swift
  39. 1 1
      Sources/KeePass/Field.swift
  40. 1 1
      Sources/KeePass/Group.swift
  41. 6 8
      Sources/KeePass/KDB.swift
  42. 14 17
      Sources/KeePass/KDBX.swift
  43. 8 8
      Sources/KeePass/KeePass.swift
  44. 10 4
      Sources/KeePass/TypeErasure.swift
  45. 44 45
      Sources/XML/Document.swift
  46. 120 122
      Sources/XML/Element.swift
  47. 11 13
      Sources/XML/Options.swift
  48. 18 19
      Sources/XML/Parser.swift
  49. 2 2
      Sources/XML/XMLError.swift
  50. 2 4
      Tests/BinaryTests/BinaryTests.swift
  51. 174 10
      Tests/CryptoTests/Chacha20Tests.swift
  52. 174 10
      Tests/CryptoTests/Salsa20Tests.swift
  53. 1 2
      Tests/CryptoTests/TwofishTests.swift
  54. 1 1
      Tests/KeePassTests/KeePassTests.swift

+ 11 - 0
.swiftformat

@@ -0,0 +1,11 @@
+--exclude .build
+
+--disable unusedArguments
+--disable wrapSwitchCases
+--disable wrapMultilineStatementBraces
+--disable blankLinesAtStartOfScope
+
+--extensionacl on-declarations
+--ifdef outdent
+--maxwidth 120
+--wrapparameters after-first

+ 42 - 26
Package.swift

@@ -11,68 +11,81 @@ let package = Package(
         // The `Binary` manipulate bytes with ease.
         .library(
             name: "Binary",
-            targets: ["Binary"]),
+            targets: ["Binary"]
+        ),
 
         // `Crypto` defines cryptographic interfaces used by KeePass.
         .library(
             name: "Crypto",
-            targets: ["Crypto"]),
+            targets: ["Crypto"]
+        ),
 
         // `KeePass` library defines interfaces to work with KeePass files.
         .library(
             name: "KeePass",
-            targets: ["KeePass"]),
+            targets: ["KeePass"]
+        ),
     ],
 
     targets: [
 
         .target(
             name: "KeePass",
-            dependencies: [ "Binary",
-                            "KDB",
-                            "KDBX"]),
+            dependencies: ["Binary",
+                           "KDB",
+                           "KDBX"]
+        ),
         .testTarget(
             name: "KeePassTests",
             dependencies: ["KeePass"],
-            resources: [ .process("Fixtures") ]),
+            resources: [.process("Fixtures")]
+        ),
 
         .target(
             name: "KDB",
-            dependencies: [ "Binary",
-                            "Crypto"]),
+            dependencies: ["Binary",
+                           "Crypto"]
+        ),
 
         .target(
             name: "KDBX",
-            dependencies: [ "Binary",
-                            "Crypto",
-                            "Gzip",
-                            "XML"]),
+            dependencies: ["Binary",
+                           "Crypto",
+                           "Gzip",
+                           "XML"]
+        ),
 
         .target(
             name: "Binary",
-            dependencies: []),
+            dependencies: []
+        ),
         .testTarget(
             name: "BinaryTests",
-            dependencies: ["Binary"]),
+            dependencies: ["Binary"]
+        ),
 
         .target(
             name: "Crypto",
-            dependencies: [ "Binary", 
-                            "Sodium", 
-                            "Argon2", 
-                            "Twofish"]),
+            dependencies: ["Binary",
+                           "Sodium",
+                           "Argon2",
+                           "Twofish"]
+        ),
         .testTarget(
             name: "CryptoTests",
-            dependencies: ["Crypto"]),
+            dependencies: ["Crypto"]
+        ),
 
         .target(
             name: "Gzip",
             dependencies: ["Binary"],
-            exclude: ["LICENSE"]),
+            exclude: ["LICENSE"]
+        ),
 
         .target(
             name: "XML",
-            dependencies: []),
+            dependencies: []
+        ),
 
         // MARK: KeePass Cryptographic Libraries
 
@@ -82,16 +95,19 @@ let package = Package(
             exclude: ["LICENSE"],
             cSettings: [
                 .headerSearchPath("include/sodium"),
-                .define("CONFIGURED")
-            ]),
+                .define("CONFIGURED"),
+            ]
+        ),
 
         .target(
             name: "Argon2",
             dependencies: [],
-            exclude: ["LICENSE"]),
+            exclude: ["LICENSE"]
+        ),
 
         .target(
             name: "Twofish",
-            dependencies: []),
+            dependencies: []
+        ),
     ]
 )

+ 8 - 12
Sources/Binary/Bytes.swift

@@ -47,7 +47,7 @@ public struct Bytes: RawRepresentable {
     }
 
     public init(slice: ArraySlice<UInt8>) {
-        self.rawValue = [UInt8](slice)
+        rawValue = [UInt8](slice)
     }
 
     public init(lenght: Int) {
@@ -59,13 +59,13 @@ public struct Bytes: RawRepresentable {
     }
 
     public init(random lenght: Int) throws {
-        self.rawValue = (0..<lenght).map { _ in 
-            UInt8.random(in: UInt8.min...UInt8.max)
+        rawValue = (0 ..< lenght).map { _ in
+            UInt8.random(in: UInt8.min ... UInt8.max)
         }
     }
 
     public init(data: Data) {
-        self.rawValue = data.withUnsafeBytes { Array($0) }
+        rawValue = data.withUnsafeBytes { Array($0) }
     }
 
     public init(contentsOf url: URL) throws {
@@ -93,7 +93,7 @@ public struct Bytes: RawRepresentable {
         let step = utf8.startIndex.advanced(by: 2)
 
         for index in stride(from: start, to: end, by: step) {
-            let hex = "\( UnicodeScalar(utf8[index]) )\( UnicodeScalar(utf8[index.advanced(by: 1)]) )"
+            let hex = "\(UnicodeScalar(utf8[index]))\(UnicodeScalar(utf8[index.advanced(by: 1)]))"
             guard let byte = UInt8(hex, radix: 16) else { return nil }
             array.append(byte)
         }
@@ -101,12 +101,12 @@ public struct Bytes: RawRepresentable {
         rawValue = array
     }
 
-    public subscript (index: Int) -> UInt8 {
+    public subscript(index: Int) -> UInt8 {
         get { rawValue[index] }
         set { rawValue[index] = newValue }
     }
 
-    public subscript (range: CountableRange<Int>) -> Bytes {
+    public subscript(range: CountableRange<Int>) -> Bytes {
         Bytes(slice: rawValue[range])
     }
 
@@ -114,7 +114,7 @@ public struct Bytes: RawRepresentable {
         rawValue.append(byte)
     }
 
-    public mutating func append(_ bytes: Array<UInt8>) {
+    public mutating func append(_ bytes: [UInt8]) {
         rawValue.append(contentsOf: bytes)
     }
 
@@ -151,7 +151,6 @@ public struct Bytes: RawRepresentable {
     public static func += (lhs: inout Bytes, rhs: UInt8) {
         lhs.append(rhs)
     }
-
 }
 
 extension Bytes: Sequence {
@@ -186,7 +185,6 @@ extension Bytes: Sequence {
     public func withContiguousStorageIfAvailable<R>(_ body: (UnsafeBufferPointer<UInt8>) throws -> R) rethrows -> R? {
         try rawValue.withContiguousStorageIfAvailable(body)
     }
-
 }
 
 extension Bytes: ExpressibleByArrayLiteral {
@@ -220,7 +218,6 @@ extension Bytes: DataProtocol {
     public var startIndex: Int { rawValue.startIndex }
 
     public var endIndex: Int { rawValue.endIndex }
-
 }
 
 extension Bytes: Hashable {
@@ -241,5 +238,4 @@ extension Bytes: Hashable {
     public func hash(into hasher: inout Hasher) {
         hasher.combine(rawValue)
     }
-
 }

+ 12 - 12
Sources/Binary/BytesRepresentable.swift

@@ -55,25 +55,25 @@ extension BytesRepresentable where Self: BinaryInteger {
     }
 }
 
-extension Int: BytesRepresentable { }
+extension Int: BytesRepresentable {}
 
-extension Int8: BytesRepresentable { }
+extension Int8: BytesRepresentable {}
 
-extension Int16: BytesRepresentable { }
+extension Int16: BytesRepresentable {}
 
-extension Int32: BytesRepresentable { }
+extension Int32: BytesRepresentable {}
 
-extension Int64: BytesRepresentable { }
+extension Int64: BytesRepresentable {}
 
-extension UInt: BytesRepresentable { }
+extension UInt: BytesRepresentable {}
 
-extension UInt8: BytesRepresentable { }
+extension UInt8: BytesRepresentable {}
 
-extension UInt16: BytesRepresentable { }
+extension UInt16: BytesRepresentable {}
 
-extension UInt32: BytesRepresentable { }
+extension UInt32: BytesRepresentable {}
 
-extension UInt64: BytesRepresentable { }
+extension UInt64: BytesRepresentable {}
 
 // MARK: - Streamable Floating Point
 
@@ -89,9 +89,9 @@ extension BytesRepresentable where Self: FloatingPoint {
     }
 }
 
-extension Double: BytesRepresentable { }
+extension Double: BytesRepresentable {}
 
-extension Float: BytesRepresentable { }
+extension Float: BytesRepresentable {}
 
 // MARK: - RawRepresentable Bytes
 

+ 0 - 1
Sources/Binary/Input.swift

@@ -70,5 +70,4 @@ public class Input {
 
         return array
     }
-
 }

+ 0 - 1
Sources/Binary/Output.swift

@@ -53,5 +53,4 @@ public class Output {
     public func write<T>(_ value: T) throws where T: Writable {
         try value.write(to: self)
     }
-
 }

+ 14 - 23
Sources/Binary/Streamable.swift

@@ -54,7 +54,6 @@ extension Readable where Self: BytesRepresentable {
         let bytes = try input.read(lenght: MemoryLayout<Self>.size)
         self = try Self(bytes)
     }
-
 }
 
 extension Writable where Self: BytesRepresentable {
@@ -62,40 +61,39 @@ extension Writable where Self: BytesRepresentable {
     public func write(to output: Output) throws {
         try output.write(bytes)
     }
-
 }
 
 // MARK: - Streamable Boolean
 
-extension Bool: Streamable { }
+extension Bool: Streamable {}
 
 // MARK: - Streamable Integer
 
-extension Int: Streamable { }
+extension Int: Streamable {}
 
-extension Int8: Streamable { }
+extension Int8: Streamable {}
 
-extension Int16: Streamable { }
+extension Int16: Streamable {}
 
-extension Int32: Streamable { }
+extension Int32: Streamable {}
 
-extension Int64: Streamable { }
+extension Int64: Streamable {}
 
-extension UInt: Streamable { }
+extension UInt: Streamable {}
 
-extension UInt8: Streamable { }
+extension UInt8: Streamable {}
 
-extension UInt16: Streamable { }
+extension UInt16: Streamable {}
 
-extension UInt32: Streamable { }
+extension UInt32: Streamable {}
 
-extension UInt64: Streamable { }
+extension UInt64: Streamable {}
 
 // MARK: - Streamable Floating Point
 
-extension Double: Streamable { }
+extension Double: Streamable {}
 
-extension Float: Streamable { }
+extension Float: Streamable {}
 
 // MARK: - Streamable RawRepresentable
 
@@ -106,7 +104,6 @@ extension Readable where Self: RawRepresentable, RawValue: Readable {
         guard let value = Self(rawValue: rawValue) else { throw BinaryError.invalidValue }
         self = value
     }
-
 }
 
 extension Writable where Self: RawRepresentable, RawValue: Writable {
@@ -124,7 +121,6 @@ extension Readable where Self: OptionSet, RawValue: Readable {
         let rawValue = try RawValue(from: input)
         self = Self(rawValue: rawValue)
     }
-
 }
 
 // MARK: - Writable Array
@@ -134,7 +130,6 @@ extension Array: Writable where Element: Writable {
     public func write(to output: Output) throws {
         try forEach(output.write)
     }
-
 }
 
 // MARK: - Streamable String
@@ -149,7 +144,6 @@ extension String: Streamable {
     public func bytes(using encoding: String.Encoding = .utf8) -> Bytes? {
         data(using: encoding)?.bytes
     }
-
 }
 
 // MARK: - Streamable Data
@@ -165,12 +159,11 @@ extension Data: Streamable {
         let bytes = Bytes(data: self)
         try output.write(bytes)
     }
-
 }
 
 // MARK: - Streamable UUID
 
-extension UUID: Streamable { }
+extension UUID: Streamable {}
 
 // MARK: - Streamable Bytes
 
@@ -183,6 +176,4 @@ extension Bytes: Streamable {
     public func write(to output: Output) throws {
         try output.write(self)
     }
-
 }
-

+ 5 - 5
Sources/Binary/TLV.swift

@@ -62,7 +62,6 @@ extension TLV: Readable where Type: Readable, Lenght: Readable {
         let lenght = try input.read() as Lenght
         value = try input.read(lenght: Int(lenght))
     }
-
 }
 
 extension TLV: Writable where Type: Writable, Lenght: Writable {
@@ -72,7 +71,6 @@ extension TLV: Writable where Type: Writable, Lenght: Writable {
         try output.write(Lenght(value.lenght))
         try output.write(value)
     }
-
 }
 
 extension Sequence where Element: TypeLenghtValue, Element.Type_: Equatable, Element.Value == Bytes {
@@ -81,11 +79,14 @@ extension Sequence where Element: TypeLenghtValue, Element.Type_: Equatable, Ele
         return try first(where: { $0.type == type }).map { try T($0.value) }
     }
 
-    public func first<T>(where type: Element.Type_, _ predicate: (T) throws -> Bool) throws -> Element? where T: BytesRepresentable {
+    public func first<T>(where type: Element.Type_, _ predicate: (T) throws -> Bool) throws -> Element?
+        where T: BytesRepresentable {
         return try first(where: { try predicate(try T($0.value)) })
     }
 
-    public func sorted<T>(field: Element.Type_, by areInIncreasingOrder: (T, T) throws -> Bool) throws -> [Self.Element] where T: BytesRepresentable {
+    public func sorted<T>(field: Element.Type_,
+                          by areInIncreasingOrder: (T, T) throws -> Bool) throws -> [Self.Element]
+        where T: BytesRepresentable {
         return try sorted(by: { try areInIncreasingOrder(try T($0.value), try T($1.value)) })
     }
 
@@ -99,7 +100,6 @@ extension RangeReplaceableCollection where Element: TypeLenghtValue, Element.Typ
     public mutating func removeAll(_ type: Element.Type_) {
         removeAll(where: { $0.type == type })
     }
-
 }
 
 extension TLV: CustomDebugStringConvertible {

+ 1 - 3
Sources/Crypto/AES.swift

@@ -16,9 +16,9 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
 import CommonCrypto
+import Foundation
 
 public final class AESCipher: Cipher {
 
@@ -82,7 +82,6 @@ public final class AESCipher: Cipher {
 
         return out.prefix(count)
     }
-
 }
 
 public final class AESKeyDerivation: KeyDerivation {
@@ -133,5 +132,4 @@ public final class AESKeyDerivation: KeyDerivation {
 
         return SHA256.hash(out)
     }
-
 }

+ 2 - 4
Sources/Crypto/Argon2.swift

@@ -16,9 +16,9 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
-import Binary
 import Argon2
+import Binary
+import Foundation
 
 public final class Argon2: KeyDerivation {
 
@@ -56,5 +56,3 @@ public final class Argon2: KeyDerivation {
         return out
     }
 }
-
-

+ 3 - 4
Sources/Crypto/ChaCha20.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 import Sodium
 
 public final class ChaCha20 {
@@ -31,7 +31,7 @@ public final class ChaCha20 {
         guard key.lenght == crypto_stream_chacha20_ietf_KEYBYTES else {
             throw CryptoError.keyLenght(expecting: "Equal \(crypto_stream_chacha20_ietf_KEYBYTES)", got: key.lenght)
         }
-        
+
         guard nonce.lenght == crypto_stream_chacha20_ietf_NONCEBYTES else {
             throw CryptoError.ivLenght(expecting: "Equal \(crypto_stream_chacha20_ietf_NONCEBYTES)", got: nonce.lenght)
         }
@@ -39,14 +39,13 @@ public final class ChaCha20 {
         self.key = key
         self.nonce = nonce
     }
-
 }
 
 extension ChaCha20: Cipher {
 
     public func encrypt(data: Bytes) throws -> Bytes {
         var out = Bytes(lenght: lenght(data))
-        crypto_stream_chacha20_ietf_xor(&out.rawValue, data.rawValue, lenght(data), nonce.rawValue, key.rawValue);
+        crypto_stream_chacha20_ietf_xor(&out.rawValue, data.rawValue, lenght(data), nonce.rawValue, key.rawValue)
         return out
     }
 

+ 1 - 1
Sources/Crypto/Cipher.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 
 public protocol Cipher {
 

+ 2 - 2
Sources/Crypto/Error.swift

@@ -16,9 +16,9 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
-import CommonCrypto
 import Argon2
+import CommonCrypto
+import Foundation
 
 public enum CryptoError: Error {
     case keyLenght(expecting: String, got: Int)

+ 4 - 7
Sources/Crypto/Hash.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 import Sodium
 
 public final class SHA256 {
@@ -38,7 +38,7 @@ public final class SHA256 {
     }
 
     public func update(_ bytes: Bytes) {
-        crypto_hash_sha256_update(&state, bytes.rawValue, lenght(bytes));
+        crypto_hash_sha256_update(&state, bytes.rawValue, lenght(bytes))
     }
 
     public static func hash(_ bytes: Bytes) -> Bytes {
@@ -46,7 +46,6 @@ public final class SHA256 {
         crypto_hash_sha256(&out.rawValue, bytes.rawValue, lenght(bytes))
         return out
     }
-
 }
 
 public final class SHA512 {
@@ -67,7 +66,7 @@ public final class SHA512 {
     }
 
     public func update(_ bytes: Bytes) {
-        crypto_hash_sha512_update(&state, bytes.rawValue, lenght(bytes));
+        crypto_hash_sha512_update(&state, bytes.rawValue, lenght(bytes))
     }
 
     public static func hash(_ bytes: Bytes) -> Bytes {
@@ -75,7 +74,6 @@ public final class SHA512 {
         crypto_hash_sha512(&out.rawValue, bytes.rawValue, lenght(bytes))
         return out
     }
-
 }
 
 public final class HMACSHA256 {
@@ -96,7 +94,7 @@ public final class HMACSHA256 {
     }
 
     public func update(_ bytes: Bytes) {
-        crypto_auth_hmacsha256_update(&state, bytes.rawValue, lenght(bytes));
+        crypto_auth_hmacsha256_update(&state, bytes.rawValue, lenght(bytes))
     }
 
     public static func authenticate(_ bytes: Bytes, key: Bytes) -> Bytes {
@@ -104,5 +102,4 @@ public final class HMACSHA256 {
         hmac.update(bytes)
         return hmac.final
     }
-
 }

+ 1 - 1
Sources/Crypto/KeyDerivation.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 
 public protocol KeyDerivation {
 

+ 2 - 3
Sources/Crypto/Salsa20.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 import Sodium
 
 public final class Salsa20 {
@@ -45,12 +45,11 @@ extension Salsa20: Cipher {
 
     public func encrypt(data: Bytes) throws -> Bytes {
         var out = Bytes(lenght: lenght(data))
-        crypto_stream_salsa20_xor(&out.rawValue, data.rawValue, lenght(data), nonce.rawValue, key.rawValue);
+        crypto_stream_salsa20_xor(&out.rawValue, data.rawValue, lenght(data), nonce.rawValue, key.rawValue)
         return out
     }
 
     public func decrypt(data: Bytes) throws -> Bytes {
         try encrypt(data: data)
     }
-
 }

+ 1 - 2
Sources/Crypto/Twofish.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 import Twofish
 
 public final class Twofish: Cipher {
@@ -51,5 +51,4 @@ public final class Twofish: Cipher {
         twofish_decrypt(&context, data.rawValue, output_length, &out.rawValue, &output_length)
         return out.prefix(output_length)
     }
-    
 }

+ 12 - 17
Sources/Gzip/Gzip.swift

@@ -26,13 +26,13 @@
  THE SOFTWARE.
  */
 
-import Foundation
 import Binary
+import Foundation
 
 #if os(Linux)
-    import zlibLinux
+import zlibLinux
 #else
-    import zlib
+import zlib
 #endif
 
 /// Compression level whose rawValue is based on the zlib's constants.
@@ -52,10 +52,8 @@ public struct CompressionLevel: RawRepresentable {
     public init(rawValue: Int32) {
         self.rawValue = rawValue
     }
-
 }
 
-
 /// Errors on gzipping/gunzipping based on the zlib error codes.
 public struct GzipError: Swift.Error {
     // cf. http://www.zlib.net/manual.html
@@ -101,14 +99,14 @@ public struct GzipError: Swift.Error {
 
     internal init(code: Int32, msg: UnsafePointer<CChar>?) {
 
-        self.message = {
+        message = {
             guard let msg = msg, let message = String(validatingUTF8: msg) else {
                 return "Unknown gzip error"
             }
             return message
         }()
 
-        self.kind = {
+        kind = {
             switch code {
             case Z_STREAM_ERROR:
                 return .stream
@@ -127,14 +125,13 @@ public struct GzipError: Swift.Error {
     }
 
     public var localizedDescription: String { message }
-
 }
 
 extension Bytes {
 
     /// Whether the receiver is compressed in gzip format.
     public var isGzipped: Bool {
-        starts(with: [0x1f, 0x8b])  // check magic number
+        starts(with: [0x1F, 0x8B]) // check magic number
     }
 
     /// Create a new `Data` object by compressing the receiver using zlib.
@@ -178,7 +175,7 @@ extension Bytes {
 
             try withUnsafeBytes { input in
                 guard let pointer = input.bindMemory(to: Bytef.self).baseAddress else {
-                    throw GzipError.init(code: 0, msg: nil)
+                    throw GzipError(code: 0, msg: nil)
                 }
 
                 stream.next_in = UnsafeMutablePointer<Bytef>(mutating: pointer).advanced(by: Int(stream.total_in))
@@ -186,7 +183,7 @@ extension Bytes {
 
                 try out.withUnsafeMutableBytes { output in
                     guard let pointer = output.bindMemory(to: Bytef.self).baseAddress else {
-                        throw GzipError.init(code: 0, msg: nil)
+                        throw GzipError(code: 0, msg: nil)
                     }
 
                     stream.next_out = pointer.advanced(by: Int(stream.total_out))
@@ -209,7 +206,6 @@ extension Bytes {
         return out.prefix(Int(stream.total_out))
     }
 
-
     /// Create a new `Data` object by decompressing the receiver using zlib.
     /// Throws an error if decompression failed.
     ///
@@ -244,16 +240,16 @@ extension Bytes {
 
             try withUnsafeBytes { input in
                 guard let pointer = input.bindMemory(to: Bytef.self).baseAddress else {
-                    throw GzipError.init(code: 0, msg: nil)
+                    throw GzipError(code: 0, msg: nil)
                 }
 
                 stream.next_in = UnsafeMutablePointer<Bytef>(mutating: pointer).advanced(by: Int(stream.total_in))
-                
+
                 stream.avail_in = uInt(count) - uInt(stream.total_in)
 
                 try out.withUnsafeMutableBytes { output in
                     guard let pointer = output.bindMemory(to: Bytef.self).baseAddress else {
-                        throw GzipError.init(code: 0, msg: nil)
+                        throw GzipError(code: 0, msg: nil)
                     }
 
                     stream.next_out = pointer.advanced(by: Int(stream.total_out))
@@ -281,10 +277,9 @@ extension Bytes {
 
         return out.prefix(Int(stream.total_out))
     }
-
 }
 
-private struct DataSize {
+private enum DataSize {
     static let chunk = 1 << 14
     static let stream = MemoryLayout<z_stream>.size
 }

+ 1 - 1
Sources/KDB/CompositeKey.swift

@@ -45,6 +45,6 @@ extension CompositeKey {
             return key
         }
 
-        return SHA256.hash( SHA256.hash(password) + key )
+        return SHA256.hash(SHA256.hash(password) + key)
     }
 }

+ 5 - 7
Sources/KDB/Database.swift

@@ -16,12 +16,12 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
 import Crypto
+import Foundation
 
-public let FileSignature: UInt32 = 0x9AA2D903
-public let FileFormat: UInt32 = 0xB54BFB65
+public let FileSignature: UInt32 = 0x9AA2_D903
+public let FileFormat: UInt32 = 0xB54B_FB65
 
 public class Database {
 
@@ -43,7 +43,7 @@ public class Database {
         }
 
         let stream = Input(bytes: content)
-        self.root = try Root(from: stream, groups: Int(header.groups), entries: Int(header.entries))
+        root = try Root(from: stream, groups: Int(header.groups), entries: Int(header.entries))
     }
 
     public convenience init(from file: URL, compositeKey: CompositeKey) throws {
@@ -88,7 +88,6 @@ public class Database {
         data = try cipher.encrypt(data: data)
         try output.write(data)
     }
-
 }
 
 private func Root(from input: Input, groups: Int, entries: Int) throws -> Group {
@@ -107,7 +106,7 @@ private func Root(from input: Input, groups: Int, entries: Int) throws -> Group
             continue
         }
 
-        for (j, parent) in groups[0..<i].enumerated().reversed() {
+        for (j, parent) in groups[0 ..< i].enumerated().reversed() {
             guard let level2: UInt16 = parent[.groupLevel] else { throw KDBError.corruptedDatabase }
 
             if level2 < level1 {
@@ -118,7 +117,6 @@ private func Root(from input: Input, groups: Int, entries: Int) throws -> Group
 
             guard j > 0 else { throw KDBError.corruptedDatabase }
         }
-
     }
 
     for entry in entries {

+ 11 - 13
Sources/KDB/Date.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 
 extension Database {
 
@@ -35,12 +35,12 @@ extension Database {
     public static func date(from bytes: Bytes) -> Date? {
         guard bytes.count > 4 else { return nil }
 
-        let year    = ( Int(bytes[0]) << 6) | (Int(bytes[1]) >> 2)
-        let month   = ((Int(bytes[1]) & 0x00000003) << 2) | (Int(bytes[2]) >> 6)
-        let day     = ( Int(bytes[2]) >> 1) & 0x0000001F
-        let hour    = ((Int(bytes[2]) & 0x00000001) << 4) | (Int(bytes[3]) >> 4)
-        let minute  = ((Int(bytes[3]) & 0x0000000F) << 2) | (Int(bytes[4]) >> 6)
-        let second  =   Int(bytes[4]) & 0x0000003F
+        let year = (Int(bytes[0]) << 6) | (Int(bytes[1]) >> 2)
+        let month = ((Int(bytes[1]) & 0x0000_0003) << 2) | (Int(bytes[2]) >> 6)
+        let day = (Int(bytes[2]) >> 1) & 0x0000_001F
+        let hour = ((Int(bytes[2]) & 0x0000_0001) << 4) | (Int(bytes[3]) >> 4)
+        let minute = ((Int(bytes[3]) & 0x0000_000F) << 2) | (Int(bytes[4]) >> 6)
+        let second = Int(bytes[4]) & 0x0000_003F
 
         return DateComponents(calendar: Calendar(identifier: .iso8601),
                               year: year,
@@ -50,17 +50,16 @@ extension Database {
                               minute: minute,
                               second: second,
                               nanosecond: 0).date
-
     }
 
     public static func bytes(from date: Date) -> Bytes {
         let calendar = Calendar(identifier: .iso8601)
         let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
 
-        let year   = components.year!
-        let month  = UInt8(components.month!)
-        let day    = UInt8(components.day!)
-        let hour   = UInt8(components.hour!)
+        let year = components.year!
+        let month = UInt8(components.month!)
+        let day = UInt8(components.day!)
+        let hour = UInt8(components.hour!)
         let minute = UInt8(components.minute!)
         let second = UInt8(components.second!)
 
@@ -71,6 +70,5 @@ extension Database {
         bytes[3] = (hour & 0x0F) << 4 | ((minute >> 2) & 0x0F)
         bytes[4] = ((minute & 0x03) << 6) | (second & 0x3F)
         return bytes
-
     }
 }

+ 17 - 18
Sources/KDB/Entry.swift

@@ -16,28 +16,28 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 
 public final class Entry: Row, Streamable {
 
     public enum Column: UInt16, Streamable, Endable {
-        case reserved           = 0x0000
-        case uuid               = 0x0001
-        case groupID            = 0x0002
-        case iconID             = 0x0003
-        case title              = 0x0004
-        case url                = 0x0005
-        case username           = 0x0006
-        case password           = 0x0007
-        case notes              = 0x0008
-        case creationTime       = 0x0009
-        case lastModifiedTime   = 0x000A
-        case lastAccessTime     = 0x000B
-        case expirationTime     = 0x000C
-        case binaryDesc         = 0x000D
-        case binaryData         = 0x000E
-        case end                = 0xFFFF
+        case reserved = 0x0000
+        case uuid = 0x0001
+        case groupID = 0x0002
+        case iconID = 0x0003
+        case title = 0x0004
+        case url = 0x0005
+        case username = 0x0006
+        case password = 0x0007
+        case notes = 0x0008
+        case creationTime = 0x0009
+        case lastModifiedTime = 0x000A
+        case lastAccessTime = 0x000B
+        case expirationTime = 0x000C
+        case binaryDesc = 0x000D
+        case binaryData = 0x000E
+        case end = 0xFFFF
 
         public static var endValue: Self { .end }
     }
@@ -74,5 +74,4 @@ extension Entry: Hashable {
         hasher.combine(self[.uuid])
         hasher.combine(self[.title])
     }
-
 }

+ 13 - 13
Sources/KDB/Group.swift

@@ -16,23 +16,23 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 
 public final class Group: Row, Streamable {
 
     public enum Column: UInt16, Streamable, Endable {
-        case reserved           = 0x0000
-        case groupID            = 0x0001
-        case name               = 0x0002
-        case creationTime       = 0x0003
-        case lastModifiedTime   = 0x0004
-        case lastAccessTime     = 0x0005
-        case expirationTime     = 0x0006
-        case iconID             = 0x0007
-        case groupLevel         = 0x0008
-        case groupFlags         = 0x0009
-        case end                = 0xFFFF
+        case reserved = 0x0000
+        case groupID = 0x0001
+        case name = 0x0002
+        case creationTime = 0x0003
+        case lastModifiedTime = 0x0004
+        case lastAccessTime = 0x0005
+        case expirationTime = 0x0006
+        case iconID = 0x0007
+        case groupLevel = 0x0008
+        case groupFlags = 0x0009
+        case end = 0xFFFF
 
         public static var endValue: Self { .end }
     }
@@ -84,7 +84,7 @@ extension Group: Hashable {
 
     public static func == (lhs: Group, rhs: Group) -> Bool {
         lhs[.groupID] == rhs[.groupID] &&
-        lhs[.groupLevel] == rhs[.groupLevel]
+            lhs[.groupLevel] == rhs[.groupLevel]
     }
 
     public func hash(into hasher: inout Hasher) {

+ 6 - 6
Sources/KDB/Header.swift

@@ -16,9 +16,9 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
 import Crypto
+import Foundation
 
 struct Header {
     let cipher: Flag
@@ -35,10 +35,10 @@ struct Header {
 struct Flag: OptionSet, Streamable {
     let rawValue: UInt32
 
-    static let sha2     = Flag(rawValue: 1<<0)
-    static let aes      = Flag(rawValue: 1<<1)
-    static let arc4     = Flag(rawValue: 1<<2)
-    static let twofish  = Flag(rawValue: 1<<3)
+    static let sha2 = Flag(rawValue: 1 << 0)
+    static let aes = Flag(rawValue: 1 << 1)
+    static let arc4 = Flag(rawValue: 1 << 2)
+    static let twofish = Flag(rawValue: 1 << 3)
 }
 
 extension Header: Streamable {
@@ -89,6 +89,6 @@ extension Header {
         let kdf = try AESKeyDerivation(seed: transformSeed, rounds: UInt64(transformRounds))
         let derivedKey = try kdf.derive(key: key)
 
-        return SHA256.hash( masterSeed + derivedKey )
+        return SHA256.hash(masterSeed + derivedKey)
     }
 }

+ 6 - 5
Sources/KDB/Row.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 
 public protocol Row: AnyObject {
     associatedtype Column
@@ -70,18 +70,19 @@ extension Row where Column: Equatable {
 
 extension Sequence where Element: Row, Element.Column: Equatable {
 
-    public func first<T>(column: Element.Column, where predicate: (T) throws -> Bool) throws -> Element? where T: BytesRepresentable {
+    public func first<T>(column: Element.Column, where predicate: (T) throws -> Bool) throws -> Element?
+        where T: BytesRepresentable {
         try first(where: {
             guard let bytes = $0[column] else { return false }
             return try predicate(T(bytes))
         })
     }
 
-    public func sorted<T>(column: Element.Column, by areInIncreasingOrder: (T, T) throws -> Bool) throws -> [Element] where T: BytesRepresentable {
+    public func sorted<T>(column: Element.Column, by areInIncreasingOrder: (T, T) throws -> Bool) throws -> [Element]
+        where T: BytesRepresentable {
         try sorted(by: {
             guard let rhs = $0[column], let lhs = $1[column] else { return false }
-            return try areInIncreasingOrder(T(rhs),T(lhs))
+            return try areInIncreasingOrder(T(rhs), T(lhs))
         })
     }
-
 }

+ 1 - 4
Sources/KDBX/Cipher.swift

@@ -16,26 +16,23 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Crypto
+import Foundation
 
 extension AESCipher {
 
     static let UUID = Foundation.UUID(uuid: (0x31, 0xC1, 0xF2, 0xE6, 0xBF, 0x71, 0x43, 0x50,
                                              0xBE, 0x58, 0x05, 0x21, 0x6A, 0xFC, 0x5A, 0xFF))
-
 }
 
 extension ChaCha20 {
 
     static let UUID = Foundation.UUID(uuid: (0xD6, 0x03, 0x8A, 0x2B, 0x8B, 0x6F, 0x4C, 0xB5,
                                              0xA5, 0x24, 0x33, 0x9A, 0x31, 0xDB, 0xB5, 0x9A))
-
 }
 
 extension Twofish {
 
     static let UUID = Foundation.UUID(uuid: (0xAD, 0x68, 0xF2, 0x9F, 0x57, 0x6F, 0x4B, 0xB9,
                                              0xA3, 0x6A, 0xD4, 0x7A, 0xF9, 0x65, 0x34, 0x6C))
-
 }

+ 1 - 2
Sources/KDBX/CompositeKey.swift

@@ -40,7 +40,7 @@ extension CompositeKey {
         let hash = SHA256()
 
         if !password.isEmpty {
-            hash.update( SHA256.hash(password) )
+            hash.update(SHA256.hash(password))
         }
 
         if !key.isEmpty {
@@ -49,5 +49,4 @@ extension CompositeKey {
 
         return hash.final
     }
-
 }

+ 1 - 1
Sources/KDBX/Database.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 import XML
 
 public protocol Database {

+ 1 - 1
Sources/KDBX/Database0.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePass. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 import XML
 
 class Database0: Database {

+ 3 - 3
Sources/KDBX/Database3.swift

@@ -16,9 +16,9 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
 import Crypto
+import Foundation
 import Gzip
 import XML
 
@@ -38,7 +38,7 @@ class Database3: Database {
         let data = try input.read() as Bytes
 
         var key = try header.masterKey(from: compositeKey)
-        key = SHA256.hash( key )
+        key = SHA256.hash(key)
 
         let cipher = try header.cipher(key: key)
 
@@ -59,7 +59,7 @@ class Database3: Database {
             guard size > 0 else { break }
 
             let block = try stream.read(lenght: Int(size))
-            guard SHA256.hash( block ) == hash else { throw KDBXError.corruptedDatabase }
+            guard SHA256.hash(block) == hash else { throw KDBXError.corruptedDatabase }
             content += block
         }
 

+ 4 - 4
Sources/KDBX/Database4.swift

@@ -16,9 +16,9 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
 import Crypto
+import Foundation
 import XML
 
 class Database4: Database {
@@ -40,7 +40,7 @@ class Database4: Database {
                                  data: try input.read(),
                                  key: masterKey)
 
-        let key = SHA256.hash( masterKey )
+        let key = SHA256.hash(masterKey)
         let cipher = try outerHeader.cipher(key: key)
         content = try cipher.decrypt(data: content)
 
@@ -65,11 +65,11 @@ class Database4: Database {
 private func Unhash(header: Bytes, data: Bytes, key: Bytes) throws -> Bytes {
     let stream = Input(bytes: data)
 
-    let key = SHA512.hash( key + 1 )
+    let key = SHA512.hash(key + 1)
     let hmacKey = HmacKey(block: .max, key: key)
 
     guard
-        try stream.read(lenght: SHA256.Lenght) == SHA256.hash( header ),
+        try stream.read(lenght: SHA256.Lenght) == SHA256.hash(header),
         try stream.read(lenght: HMACSHA256.Lenght) == HMACSHA256.authenticate(header, key: hmacKey)
     else { throw KDBXError.invalidCompositeKey }
 

+ 4 - 5
Sources/KDBX/File.swift

@@ -16,12 +16,12 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 
-public let FileSignature: UInt32 = 0x9AA2D903
-public let BetaFileFormat: UInt32 = 0xB54BFB66
-public let FileFormat: UInt32 = 0xB54BFB67
+public let FileSignature: UInt32 = 0x9AA2_D903
+public let BetaFileFormat: UInt32 = 0xB54B_FB66
+public let FileFormat: UInt32 = 0xB54B_FB67
 
 public struct Version {
     let major: UInt16
@@ -90,5 +90,4 @@ extension Version: Streamable {
         try output.write(minor)
         try output.write(major)
     }
-
 }

+ 27 - 27
Sources/KDBX/Header.swift

@@ -16,51 +16,51 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
 import Crypto
+import Foundation
 
 typealias Header<T, L> = [TLV<T, L>] where L: BinaryInteger
 
 enum OuterHeader: UInt8, Streamable, Endable {
-    case end                 = 0
-    case comment             = 1
-    case cipherID            = 2
-    case compressionFlags    = 3
-    case masterSeed          = 4
-    case transformSeed       = 5
-    case transformRounds     = 6
-    case initialVector       = 7
-    case protectedStreamKey  = 8
-    case streamStartBytes    = 9
+    case end = 0
+    case comment = 1
+    case cipherID = 2
+    case compressionFlags = 3
+    case masterSeed = 4
+    case transformSeed = 5
+    case transformRounds = 6
+    case initialVector = 7
+    case protectedStreamKey = 8
+    case streamStartBytes = 9
     case innerRandomStreamID = 10
-    case kdfParameters       = 11
-    case publicCustomData    = 12
+    case kdfParameters = 11
+    case publicCustomData = 12
 
     public static var endValue: OuterHeader { .end }
 }
 
 enum InnerHeader: UInt8, Streamable, Endable {
-    case end                  = 0
-    case innerRandomStreamID  = 1
+    case end = 0
+    case innerRandomStreamID = 1
     case innerRandomStreamKey = 2
-    case binary               = 3
+    case binary = 3
 
     public static var endValue: InnerHeader { .end }
 }
 
 enum Compression: UInt32, BytesRepresentable {
-    case none  = 0
-    case gzip  = 1
+    case none = 0
+    case gzip = 1
     case count = 2
 }
 
 enum RandomStream: UInt32, BytesRepresentable {
-    case none       = 0
-    case arc4       = 1
-    case salsa20    = 2
-    case chacha20   = 3
-    case count      = 4
+    case none = 0
+    case arc4 = 1
+    case salsa20 = 2
+    case chacha20 = 3
+    case count = 4
 }
 
 extension Array where Element: TypeLenghtValue, Element.Type_ == OuterHeader, Element.Value == Bytes {
@@ -97,15 +97,15 @@ extension Array where Element: TypeLenghtValue, Element.Type_ == OuterHeader, El
     }
 
     func kdf() throws -> KeyDerivation {
-        
+
         if let seed: Bytes = self[.transformSeed], let rounds: UInt64 = self[.transformRounds] {
             return try AESKeyDerivation(seed: seed, rounds: rounds)
         }
 
         guard
-             let parameters: KeyDerivationParameters = self[.kdfParameters],
-             let uuid: UUID  = try parameters["$UUID"]?.unwrap()
-         else { throw KDBXError.corruptedDatabase }
+            let parameters: KeyDerivationParameters = self[.kdfParameters],
+            let uuid: UUID = try parameters["$UUID"]?.unwrap()
+        else { throw KDBXError.corruptedDatabase }
 
         switch uuid {
         case Argon2.UUID:

+ 24 - 25
Sources/KDBX/KeyDerivation.swift

@@ -16,24 +16,23 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Crypto
-
+import Foundation
 
 typealias KeyDerivationParameters = [String: Variant]
 
 extension AESKeyDerivation {
 
-    static let UUID = Foundation.UUID(uuid:(0xC9, 0xD9, 0xF3, 0x9A, 0x62, 0x8A, 0x44, 0x60,
-                                            0xBF, 0x74, 0x0D, 0x08, 0xC1, 0x8A, 0x4F, 0xEA))
+    static let UUID = Foundation.UUID(uuid: (0xC9, 0xD9, 0xF3, 0x9A, 0x62, 0x8A, 0x44, 0x60,
+                                             0xBF, 0x74, 0x0D, 0x08, 0xC1, 0x8A, 0x4F, 0xEA))
 
-    static let TransformSeedKey     = "S"
-    static let TransformRoundsKey   = "R"
+    static let TransformSeedKey = "S"
+    static let TransformRoundsKey = "R"
 
     convenience init(parameters: [String: Variant]) throws {
         guard
-            let seed    = parameters[AESKeyDerivation.TransformSeedKey],
-            let rounds  = parameters[AESKeyDerivation.TransformRoundsKey]
+            let seed = parameters[AESKeyDerivation.TransformSeedKey],
+            let rounds = parameters[AESKeyDerivation.TransformRoundsKey]
         else { throw KDBXError.corruptedDatabase }
 
         try self.init(seed: try seed.unwrap(),
@@ -43,28 +42,28 @@ extension AESKeyDerivation {
 
 extension Argon2 {
 
-    static let UUID = Foundation.UUID(uuid:(0xEF, 0x63, 0x6D, 0xDF, 0x8C, 0x29, 0x44, 0x4B,
-                                            0x91, 0xF7, 0xA9, 0xA4, 0x03, 0xE3, 0x0A, 0x0C))
+    static let UUID = Foundation.UUID(uuid: (0xEF, 0x63, 0x6D, 0xDF, 0x8C, 0x29, 0x44, 0x4B,
+                                             0x91, 0xF7, 0xA9, 0xA4, 0x03, 0xE3, 0x0A, 0x0C))
+
+    static let SaltKey = "S"
+    static let ParallelismKey = "P"
+    static let MemoryKey = "M"
+    static let IterationsKey = "I"
+    static let VersionKey = "V"
 
-    static let SaltKey          = "S"
-    static let ParallelismKey   = "P"
-    static let MemoryKey        = "M"
-    static let IterationsKey    = "I"
-    static let VersionKey       = "V"
-    
     convenience init(parameters: [String: Variant]) throws {
         guard
-            let salt        = parameters[Argon2.SaltKey],
+            let salt = parameters[Argon2.SaltKey],
             let parallelism = parameters[Argon2.ParallelismKey],
-            let memory      = parameters[Argon2.MemoryKey],
-            let iterations  = parameters[Argon2.IterationsKey],
-            let version     = parameters[Argon2.VersionKey]
+            let memory = parameters[Argon2.MemoryKey],
+            let iterations = parameters[Argon2.IterationsKey],
+            let version = parameters[Argon2.VersionKey]
         else { throw KDBXError.corruptedDatabase }
 
-        self.init(salt:         try salt.unwrap(),
-                  parallelism:  try parallelism.unwrap(),
-                  memory:       UInt32(try memory.unwrap() as UInt64) / 1024,
-                  iterations:   UInt32(try iterations.unwrap() as UInt64),
-                  version:      try version.unwrap())
+        self.init(salt: try salt.unwrap(),
+                  parallelism: try parallelism.unwrap(),
+                  memory: UInt32(try memory.unwrap() as UInt64) / 1024,
+                  iterations: UInt32(try iterations.unwrap() as UInt64),
+                  version: try version.unwrap())
     }
 }

+ 17 - 22
Sources/KDBX/Variant.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 
 public enum Variant {
 
@@ -36,14 +36,14 @@ public enum Variant {
     case Bytes(Bytes)
 
     enum ID: UInt8, Streamable {
-        case End     = 0x00
-        case Bool    = 0x08
-        case UInt32  = 0x04
-        case UInt64  = 0x05
-        case Int32   = 0x0C
-        case Int64   = 0x0D
-        case String  = 0x18
-        case Bytes   = 0x42
+        case End = 0x00
+        case Bool = 0x08
+        case UInt32 = 0x04
+        case UInt64 = 0x05
+        case Int32 = 0x0C
+        case Int64 = 0x0D
+        case String = 0x18
+        case Bytes = 0x42
     }
 
     var id: ID {
@@ -138,7 +138,6 @@ public enum Variant {
         guard case let .Bytes(bytes) = self else { throw KDBXError.invalidValue }
         return try T(bytes)
     }
-
 }
 
 extension Variant: Writable {
@@ -184,36 +183,35 @@ extension Variant: Writable {
         case .End:
             try output.write(id)
 
-        case .Bool(let value):
+        case let .Bool(value):
             try output.write(MemoryLayout<Bool>.size)
             try output.write(value)
 
-        case .UInt32(let value):
+        case let .UInt32(value):
             try output.write(MemoryLayout<UInt32>.size)
             try output.write(value)
 
-        case .UInt64(let value):
+        case let .UInt64(value):
             try output.write(MemoryLayout<UInt64>.size)
             try output.write(value)
 
-        case .Int32(let value):
+        case let .Int32(value):
             try output.write(MemoryLayout<Int32>.size)
             try output.write(value)
 
-        case .Int64(let value):
+        case let .Int64(value):
             try output.write(MemoryLayout<Int64>.size)
             try output.write(value)
 
-        case .String(let value):
+        case let .String(value):
             try output.write(Swift.UInt32(value.count))
             try output.write(value)
 
-        case .Bytes(let value):
+        case let .Bytes(value):
             try output.write(Swift.UInt32(value.lenght))
             try output.write(value)
         }
     }
-
 }
 
 extension Variant.Version: Streamable {
@@ -227,7 +225,6 @@ extension Variant.Version: Streamable {
         try output.write(minor)
         try output.write(major)
     }
-
 }
 
 extension Dictionary: Streamable where Key == String, Value == Variant {
@@ -254,7 +251,7 @@ extension Dictionary: Streamable where Key == String, Value == Variant {
     public func write(to output: Output) throws {
         let version = Variant.Version(major: 1, minor: 0)
         try output.write(version)
-        
+
         try forEach {
             try output.write($0.value.id)
             try output.write(UInt32($0.key.count))
@@ -264,7 +261,6 @@ extension Dictionary: Streamable where Key == String, Value == Variant {
 
         try output.write(Variant.End)
     }
-
 }
 
 extension Dictionary: BytesRepresentable where Key == String, Value == Variant {
@@ -279,5 +275,4 @@ extension Dictionary: BytesRepresentable where Key == String, Value == Variant {
         try? output.write(self)
         return output.bytes ?? []
     }
-
 }

+ 6 - 5
Sources/KeePass/CompositeKey.swift

@@ -16,9 +16,9 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePass. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
 import Crypto
+import Foundation
 import XML
 
 public struct CompositeKey {
@@ -31,13 +31,14 @@ public struct CompositeKey {
 
     public init(password: String) {
         self.password = password
-        self.key = []
+        key = []
     }
 
     public init(password: String, key: Data) {
         self.password = password
 
-        if let xml = try? XML.Document(xml: key), let base64: String = try? xml.KeyFile.Key.Data.get(), let key = Bytes(base64Encoded: base64) {
+        if let xml = try? XML.Document(xml: key), let base64: String = try? xml.KeyFile.Key.Data.get(),
+           let key = Bytes(base64Encoded: base64) {
             // KeePass 2 XML key file
             self.key = key
 
@@ -45,7 +46,8 @@ public struct CompositeKey {
             // Fixed 32 byte binary
             self.key = Bytes(data: key)
 
-        } else if key.count == 2 * CompositeKey.KeyLength, let hex = String(data: key, encoding: .ascii), let key = Bytes(hex: hex) {
+        } else if key.count == 2 * CompositeKey.KeyLength, let hex = String(data: key, encoding: .ascii),
+                  let key = Bytes(hex: hex) {
             // Fixed 32 byte ASCII hex-encoded binary
             self.key = key
 
@@ -60,5 +62,4 @@ public struct CompositeKey {
         let key = try Data(contentsOf: url)
         self.init(password: password, key: key)
     }
-
 }

+ 1 - 1
Sources/KeePass/Database.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePass. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 
 public protocol Database {
     associatedtype Root: Group

+ 24 - 24
Sources/KeePass/Entry.swift

@@ -18,31 +18,31 @@
 
 import Foundation
 
-public let EntryFieldTitle    = "Title"
+public let EntryFieldTitle = "Title"
 public let EntryFieldUserName = "UserName"
 public let EntryFieldPassword = "Password"
-public let EntryFieldURL      = "URL"
-public let EntryFieldNotes    = "Notes"
-
-public let MetaEntryBinaryDescription   = "bin-stream"
-public let MetaEntryTitle               = "Meta-Info"
-public let MetaEntryUsername            = "SYSTEM"
-public let MetaEntryURL                 = "$"
-
-public let MetaEntryUIState                         = "Simple UI State"
-public let MetaEntryDefaultUsername                 = "Default User Name"
-public let MetaEntrySearchHistoryItem               = "Search History Item"
-public let MetaEntryCustomKVP                       = "Custom KVP"
-public let MetaEntryDatabaseColor                   = "Database Color"
-public let MetaEntryKeePassXCustomIcon              = "KPX_CUSTOM_ICONS_2"
-public let MetaEntryKeePassXCustomIcon2             = "KPX_CUSTOM_ICONS_4"
-public let MetaEntryKeePassXGroupTreeState          = "KPX_GROUP_TREE_STATE"
-public let MetaEntryKeePassKitGroupUUIDs            = "KeePassKit Group UUIDs"
-public let MetaEntryKeePassKitDeletedObjects        = "KeePassKit Deleted Objects"
-public let MetaEntryKeePassKitDatabaseName          = "KeePassKit Database Name"
-public let MetaEntryKeePassKitDatabaseDescription   = "KeePassKit Database Description"
-public let MetaEntryKeePassKitTrash                 = "KeePassKit Trash"
-public let MetaEntryKeePassKitUserTemplates         = "KeePassKit User Templates"
+public let EntryFieldURL = "URL"
+public let EntryFieldNotes = "Notes"
+
+public let MetaEntryBinaryDescription = "bin-stream"
+public let MetaEntryTitle = "Meta-Info"
+public let MetaEntryUsername = "SYSTEM"
+public let MetaEntryURL = "$"
+
+public let MetaEntryUIState = "Simple UI State"
+public let MetaEntryDefaultUsername = "Default User Name"
+public let MetaEntrySearchHistoryItem = "Search History Item"
+public let MetaEntryCustomKVP = "Custom KVP"
+public let MetaEntryDatabaseColor = "Database Color"
+public let MetaEntryKeePassXCustomIcon = "KPX_CUSTOM_ICONS_2"
+public let MetaEntryKeePassXCustomIcon2 = "KPX_CUSTOM_ICONS_4"
+public let MetaEntryKeePassXGroupTreeState = "KPX_GROUP_TREE_STATE"
+public let MetaEntryKeePassKitGroupUUIDs = "KeePassKit Group UUIDs"
+public let MetaEntryKeePassKitDeletedObjects = "KeePassKit Deleted Objects"
+public let MetaEntryKeePassKitDatabaseName = "KeePassKit Database Name"
+public let MetaEntryKeePassKitDatabaseDescription = "KeePassKit Database Description"
+public let MetaEntryKeePassKitTrash = "KeePassKit Trash"
+public let MetaEntryKeePassKitUserTemplates = "KeePassKit User Templates"
 
 public protocol Entry {
 
@@ -51,7 +51,7 @@ public protocol Entry {
     var times: Timestamp { get }
 
     var fields: Fields { get }
-    
+
     mutating func set(_ field: Fields.Element)
 }
 

+ 1 - 1
Sources/KeePass/Field.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePass. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 
 public struct Field {
     public var name: String

+ 1 - 1
Sources/KeePass/Group.swift

@@ -23,7 +23,7 @@ public protocol Group {
     associatedtype Entries: RandomAccessCollection where Entries.Element: Entry
 
     associatedtype Groups: RandomAccessCollection where Groups.Element: Group
-    
+
     var title: String { get set }
 
     var icon: Int { get set }

+ 6 - 8
Sources/KeePass/KDB.swift

@@ -16,16 +16,16 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePass. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 import KDB
 
-extension CompositeKey: KDB.CompositeKey { }
+extension CompositeKey: KDB.CompositeKey {}
 
 extension KDB.Database: Database {
 
     public func write(to output: Output, compositeKey: CompositeKey) throws {
-        try self.write(to: output, compositeKey: compositeKey as KDB.CompositeKey )
+        try write(to: output, compositeKey: compositeKey as KDB.CompositeKey)
     }
 }
 
@@ -64,7 +64,7 @@ extension KDB.Group: Group {
 
     public var icon: Int {
         get { self[.iconID] ?? 0 }
-        set { self[.iconID] =  newValue }
+        set { self[.iconID] = newValue }
     }
 
     public var groups: [KDB.Group] { childs }
@@ -73,7 +73,7 @@ extension KDB.Group: Group {
 extension KDB.Entry: Entry {
 
     public var times: Timestamp {
-         return self
+        return self
     }
 
     public var fields: [Field] {
@@ -84,7 +84,6 @@ extension KDB.Entry: Entry {
         guard let field = TLV<Column, UInt32>(field) else { return }
         set(field)
     }
-
 }
 
 extension KDB.Entry: Timestamp {
@@ -105,9 +104,8 @@ extension KDB.Entry: Timestamp {
 
     public var expirationDate: Date? {
         get { nil }
-        set { }
+        set {}
     }
-
 }
 
 extension Field {

+ 14 - 17
Sources/KeePass/KDBX.swift

@@ -16,21 +16,21 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePass. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
-import XML
+import Foundation
 import KDBX
+import XML
 
 let DateFormatter = ISO8601DateFormatter()
 
-extension CompositeKey: KDBX.CompositeKey { }
+extension CompositeKey: KDBX.CompositeKey {}
 
 extension KDBX.File: Database {
 
     public var root: Element { database.document.root.KeePassFile.Root }
 
     public func write(to output: Output, compositeKey: CompositeKey) throws {
-        try self.write(to: output, compositeKey: compositeKey as KDBX.CompositeKey )
+        try write(to: output, compositeKey: compositeKey as KDBX.CompositeKey)
     }
 }
 
@@ -43,7 +43,6 @@ extension XML.Element {
     convenience init(_ field: Field) {
         self.init(name: field.name, value: field.value, attributes: [:])
     }
-
 }
 
 extension Field {
@@ -59,7 +58,7 @@ extension Field {
 
 extension XML.Element: Entry {
 
-    public var times: Timestamp { self.Times }
+    public var times: Timestamp { Times }
 
     public var fields: [Field] {
         allDescendants(where: { $0.name == "String" }).compactMap { Field($0) }
@@ -68,39 +67,38 @@ extension XML.Element: Entry {
     public func set(_ field: Field) {
         allDescendants(where: { $0.name == field.name })
             .forEach { $0.removeFromParent() }
-        addChild( XML.Element(field) )
+        addChild(XML.Element(field))
     }
 }
 
 extension XML.Element: Timestamp {
 
     public var creationDate: Date {
-        self.CreationTime.date(formatter: DateFormatter) ?? .distantPast
+        CreationTime.date(formatter: DateFormatter) ?? .distantPast
     }
 
     public var lastModifiedDate: Date {
-        get { self.LastModificationTime.date(formatter: DateFormatter) ?? .distantPast }
-        set { self.LastModificationTime.value = DateFormatter.string(from: newValue) }
+        get { LastModificationTime.date(formatter: DateFormatter) ?? .distantPast }
+        set { LastModificationTime.value = DateFormatter.string(from: newValue) }
     }
 
     public var lastAccessDate: Date {
-        get { self.LastAccessTime.date(formatter: DateFormatter) ?? .distantPast }
-        set { self.LastAccessTime.value = DateFormatter.string(from: newValue) }
+        get { LastAccessTime.date(formatter: DateFormatter) ?? .distantPast }
+        set { LastAccessTime.value = DateFormatter.string(from: newValue) }
     }
 
     public var expirationDate: Date? {
-        get { self.ExpiryTime.date(formatter: DateFormatter) }
+        get { ExpiryTime.date(formatter: DateFormatter) }
         set {
             if let value = newValue {
-                self.ExpiryTime.value = DateFormatter.string(from: value)
+                ExpiryTime.value = DateFormatter.string(from: value)
                 addChild(name: "Expires", value: "True")
             } else {
-                self.ExpiryTime.value = DateFormatter.string(from: Date.distantFuture)
+                ExpiryTime.value = DateFormatter.string(from: Date.distantFuture)
                 addChild(name: "Expires", value: "False")
             }
         }
     }
-
 }
 
 extension XML.Element: Group {
@@ -125,5 +123,4 @@ extension XML.Element: Group {
     public var groups: [Element] {
         allDescendants(where: { $0.name == "Group" })
     }
-
 }

+ 8 - 8
Sources/KeePass/KeePass.swift

@@ -16,20 +16,20 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 import KDB
 import KDBX
 
-public let FileSignature: UInt32 = 0x9AA2D903
+public let FileSignature: UInt32 = 0x9AA2_D903
 
 public enum FileFormat: UInt32, Streamable {
-    case kdb        = 0xB54BFB65
-    case prekdbx    = 0xB54BFB66
-    case kdbx       = 0xB54BFB67
+    case kdb = 0xB54B_FB65
+    case prekdbx = 0xB54B_FB66
+    case kdbx = 0xB54B_FB67
 }
 
-public class KeePass {
+public enum KeePass {
 
     public static func open(contentOf url: URL, compositeKey: CompositeKey) throws -> some Database {
 
@@ -44,9 +44,9 @@ public class KeePass {
 
         switch format {
         case KDB.FileFormat:
-            return AnyDatabase( try KDB.Database(from: stream, compositeKey: compositeKey) )
+            return AnyDatabase(try KDB.Database(from: stream, compositeKey: compositeKey))
         case KDBX.BetaFileFormat, KDBX.FileFormat:
-            return AnyDatabase ( try KDBX.File(from: stream, compositeKey: compositeKey) )
+            return AnyDatabase(try KDBX.File(from: stream, compositeKey: compositeKey))
         default:
             throw KeePassError.invalidFileFormat
         }

+ 10 - 4
Sources/KeePass/TypeErasure.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePass. If not, see <https://www.gnu.org/licenses/>.
 
-import Foundation
 import Binary
+import Foundation
 
 @inline(never)
 func _abstract(file: StaticString = #file, line: UInt = #line) -> Never {
@@ -32,7 +32,7 @@ class _AnyDatabaseBoxBase: Database {
 }
 
 final class _AnyDatabaseBox<Base>: _AnyDatabaseBoxBase where Base: Database {
-    override var root: AnyGroup { AnyGroup( _base.root ) }
+    override var root: AnyGroup { AnyGroup(_base.root) }
     var _base: Base
     init(_ base: Base) { _base = base }
     override func write(to output: Output, compositeKey: CompositeKey) throws {
@@ -46,6 +46,7 @@ class AnyDatabase: Database {
     init<T>(_ base: T) where T: Database {
         _box = _AnyDatabaseBox(base)
     }
+
     func write(to output: Output, compositeKey: CompositeKey) throws {
         try _box.write(to: output, compositeKey: compositeKey)
     }
@@ -81,8 +82,13 @@ final class _AnyGroupBox<Base>: _AnyGroupBoxBase where Base: Group {
         set { _base.icon = newValue }
     }
 
-    override var entries: AnyRandomAccessCollection<AnyEntry> { AnyRandomAccessCollection<AnyEntry>(_base.entries.map { AnyEntry($0) }) }
-    override var groups: AnyRandomAccessCollection<AnyGroup> { AnyRandomAccessCollection<AnyGroup>(_base.groups.map { AnyGroup($0) }) }
+    override var entries: AnyRandomAccessCollection<AnyEntry> {
+        AnyRandomAccessCollection<AnyEntry>(_base.entries.map { AnyEntry($0) })
+    }
+
+    override var groups: AnyRandomAccessCollection<AnyGroup> {
+        AnyRandomAccessCollection<AnyGroup>(_base.groups.map { AnyGroup($0) })
+    }
 
     var _base: Base
     init(_ base: Base) { _base = base }

+ 44 - 45
Sources/XML/Document.swift

@@ -10,14 +10,14 @@ import FoundationXML
 #endif
 
 /**
-    This class is inherited from `Element` and has a few addons to represent ** Document**.
+ This class is inherited from `Element` and has a few addons to represent ** Document**.
 
-    XML Parsing is also done with this object.
-*/
+ XML Parsing is also done with this object.
+ */
 open class Document: Element {
-    
+
     // MARK: - Properties
-    
+
     /// Root (the first child element) element of XML Document **(Empty element with error if not exists)**.
     open var root: Element {
         guard let rootElement = children.first else {
@@ -27,84 +27,83 @@ open class Document: Element {
         }
         return rootElement
     }
-    
+
     public let options: Options
-    
+
     // MARK: - Lifecycle
-    
+
     /**
-        Designated initializer - Creates and returns new XML Document object.
-     
-        - parameter root: Root XML element for XML Document (defaults to `nil`).
-        - parameter options: Options for XML Document header and parser settings (defaults to `XMLOptions()`).
-    
-        - returns: Initialized XML Document object.
-    */
+         Designated initializer - Creates and returns new XML Document object.
+
+         - parameter root: Root XML element for XML Document (defaults to `nil`).
+         - parameter options: Options for XML Document header and parser settings (defaults to `XMLOptions()`).
+
+         - returns: Initialized XML Document object.
+     */
     public init(root: Element? = nil, options: Options = Options()) {
         self.options = options
-        
+
         let documentName = String(describing: Document.self)
         super.init(name: documentName)
-        
+
         // document has no parent element
         parent = nil
-        
+
         // add root element to document (if any)
         if let rootElement = root {
             addChild(rootElement)
         }
     }
-    
+
     /**
-        Convenience initializer - used for parsing XML data (by calling `loadXMLData:` internally).
-     
-        - parameter xmlData: XML data to parse.
-        - parameter options: Options for XML Document header and parser settings (defaults to `XMLOptions()`).
-    
-        - returns: Initialized XML Document object containing parsed data. Throws error if data could not be parsed.
-    */
+         Convenience initializer - used for parsing XML data (by calling `loadXMLData:` internally).
+
+         - parameter xmlData: XML data to parse.
+         - parameter options: Options for XML Document header and parser settings (defaults to `XMLOptions()`).
+
+         - returns: Initialized XML Document object containing parsed data. Throws error if data could not be parsed.
+     */
     public convenience init(xml: Data, options: Options = Options()) throws {
         self.init(options: options)
         try load(xml)
     }
-    
+
     /**
-        Convenience initializer - used for parsing XML string (by calling `init(xmlData:options:)` internally).
+         Convenience initializer - used for parsing XML string (by calling `init(xmlData:options:)` internally).
 
-        - parameter xmlString: XML string to parse.
-        - parameter encoding: String encoding for creating `Data` from `xmlString` (defaults to `String.Encoding.utf8`)
-        - parameter options: Options for XML Document header and parser settings (defaults to `XMLOptions()`).
+         - parameter xmlString: XML string to parse.
+         - parameter encoding: String encoding for creating `Data` from `xmlString` (defaults to `String.Encoding.utf8`)
+         - parameter options: Options for XML Document header and parser settings (defaults to `XMLOptions()`).
 
-        - returns: Initialized XML Document object containing parsed data. Throws error if data could not be parsed.
-    */
+         - returns: Initialized XML Document object containing parsed data. Throws error if data could not be parsed.
+     */
     public convenience init(xml: String,
                             encoding: String.Encoding = String.Encoding.utf8,
                             options: Options = Options()) throws {
         guard let data = xml.data(using: encoding) else { throw XMLError.parsingFailed }
         try self.init(xml: data, options: options)
     }
-    
+
     // MARK: - Parse XML
-    
+
     /**
-        Creates instance of `Parser` (private class which is simple wrapper around `Parser`)
-        and starts parsing the given XML data. Throws error if data could not be parsed.
-    
-        - parameter data: XML which should be parsed.
-    */
+         Creates instance of `Parser` (private class which is simple wrapper around `Parser`)
+         and starts parsing the given XML data. Throws error if data could not be parsed.
+
+         - parameter data: XML which should be parsed.
+     */
     open func load(_ data: Data) throws {
         children.removeAll(keepingCapacity: false)
         let xmlParser = Parser(document: self, data: data)
         try xmlParser.parse()
     }
-    
+
     // MARK: - Override
-    
+
     /// Override of `xml` property of `Element` - it just inserts XML Document header at the beginning.
-    open override var xml: String {
-        var xml =  "\(options.documentHeader.xmlString)\n"
+    override open var xml: String {
+        var xml = "\(options.documentHeader.xmlString)\n"
         xml += root.xml
         return xml
     }
-    
 }

+ 120 - 122
Sources/XML/Element.swift

@@ -10,53 +10,53 @@ import FoundationXML
 #endif
 
 /**
-    This is base class for holding XML structure.
+ This is base class for holding XML structure.
 
-    You can access its structure by using subscript like this: `element["foo"]["bar"]` which would
-    return `<bar></bar>` element from `<element><foo><bar></bar></foo></element>` XML as an `Element` object.
-*/
+ You can access its structure by using subscript like this: `element["foo"]["bar"]` which would
+ return `<bar></bar>` element from `<element><foo><bar></bar></foo></element>` XML as an `Element` object.
+ */
 @dynamicMemberLookup
 open class Element {
-    
+
     // MARK: - Properties
-    
+
     /// Every `Element` should have its parent element instead of `XMLDocument` which parent is `nil`.
     open internal(set) weak var parent: Element?
-    
+
     /// Child XML elements.
     open internal(set) var children = [Element]()
-    
+
     /// XML Element name.
     open var name: String
-    
+
     /// XML Element value.
     open var value: String?
-    
+
     /// XML Element attributes.
-    open var attributes: [String : String]
-    
+    open var attributes: [String: String]
+
     /// Error value (`nil` if there is no error).
     open var error: XMLError?
-    
+
     // MARK: - Init
-    
+
     /**
-        Designated initializer - all parameters are optional.
-    
-        - parameter name: XML element name.
-        - parameter value: XML element value (defaults to `nil`).
-        - parameter attributes: XML element attributes (defaults to empty dictionary).
-    
-        - returns: An initialized `Element` object.
-    */
-    public init(name: String, value: String? = nil, attributes: [String : String] = [:]) {
+         Designated initializer - all parameters are optional.
+
+         - parameter name: XML element name.
+         - parameter value: XML element value (defaults to `nil`).
+         - parameter attributes: XML element attributes (defaults to empty dictionary).
+
+         - returns: An initialized `Element` object.
+     */
+    public init(name: String, value: String? = nil, attributes: [String: String] = [:]) {
         self.name = name
         self.value = value
         self.attributes = attributes
     }
-    
+
     // MARK: - XML Read
-    
+
     /// The first element with given name **(Empty element with error if not exists)**.
     open subscript(key: String) -> Element {
         if let first = children.first(where: { $0.name == key }) {
@@ -86,93 +86,93 @@ open class Element {
         guard let value = value else { return nil }
         return formatter.date(from: value)
     }
-    
+
     /// Returns all of the elements with equal name as `self` **(nil if not exists)**.
     open var all: [Element]? { return parent?.children.filter { $0.name == self.name } }
-    
+
     /// Returns the first element with equal name as `self` **(nil if not exists)**.
     open var first: Element? { return all?.first }
-    
+
     /// Returns the last element with equal name as `self` **(nil if not exists)**.
     open var last: Element? { return all?.last }
-    
+
     /// Returns number of all elements with equal name as `self`.
     open var count: Int { return all?.count ?? 0 }
-    
+
     /**
-        Returns all elements with given value.
-        
-        - parameter value: XML element value.
-        
-        - returns: Optional Array of found XML elements.
-    */
+         Returns all elements with given value.
+
+         - parameter value: XML element value.
+
+         - returns: Optional Array of found XML elements.
+     */
     open func all(withValue value: String) -> [Element]? {
         return all?.compactMap { $0.value == value ? $0 : nil }
     }
-    
+
     /**
-        Returns all elements containing given attributes.
+         Returns all elements containing given attributes.
 
-        - parameter attributes: Array of attribute names.
+         - parameter attributes: Array of attribute names.
 
-        - returns: Optional Array of found XML elements.
-    */
+         - returns: Optional Array of found XML elements.
+     */
     open func all(containingAttributeKeys keys: [String]) -> [Element]? {
         return all?.compactMap { element in
-            keys.reduce(true) { (result, key) in
+            keys.reduce(true) { result, key in
                 result && Array(element.attributes.keys).contains(key)
             } ? element : nil
         }
     }
-    
+
     /**
-        Returns all elements with given attributes.
-    
-        - parameter attributes: Dictionary of Keys and Values of attributes.
-    
-        - returns: Optional Array of found XML elements.
-    */
-    open func all(withAttributes attributes: [String : String]) -> [Element]? {
+         Returns all elements with given attributes.
+
+         - parameter attributes: Dictionary of Keys and Values of attributes.
+
+         - returns: Optional Array of found XML elements.
+     */
+    open func all(withAttributes attributes: [String: String]) -> [Element]? {
         let keys = Array(attributes.keys)
         return all(containingAttributeKeys: keys)?.compactMap { element in
-            attributes.reduce(true) { (result, attribute) in
+            attributes.reduce(true) { result, attribute in
                 result && element.attributes[attribute.key] == attribute.value
             } ? element : nil
         }
     }
-    
+
     /**
-        Returns all descendant elements which satisfy the given predicate.
-     
-        Searching is done vertically; children are tested before siblings. Elements appear in the list
-        in the order in which they are found.
-     
-        - parameter predicate: Function which returns `true` for a desired element and `false` otherwise.
-     
-        - returns: Array of found XML elements.
-    */
+         Returns all descendant elements which satisfy the given predicate.
+
+         Searching is done vertically; children are tested before siblings. Elements appear in the list
+         in the order in which they are found.
+
+         - parameter predicate: Function which returns `true` for a desired element and `false` otherwise.
+
+         - returns: Array of found XML elements.
+     */
     open func allDescendants(where predicate: (Element) -> Bool) -> [Element] {
         var result: [Element] = []
-        
+
         for child in children {
             if predicate(child) {
                 result.append(child)
             }
             result.append(contentsOf: child.allDescendants(where: predicate))
         }
-        
+
         return result
     }
-    
+
     /**
-        Returns the first descendant element which satisfies the given predicate, or nil if no such element is found.
-     
-        Searching is done vertically; children are tested before siblings.
-     
-        - parameter predicate: Function which returns `true` for the desired element and `false` otherwise.
-     
-        - returns: Optional Element.
-    */
+         Returns the first descendant element which satisfies the given predicate, or nil if no such element is found.
+
+         Searching is done vertically; children are tested before siblings.
+
+         - parameter predicate: Function which returns `true` for the desired element and `false` otherwise.
+
+         - returns: Optional Element.
+     */
     open func firstDescendant(where predicate: (Element) -> Bool) -> Element? {
         for child in children {
             if predicate(child) {
@@ -183,87 +183,87 @@ open class Element {
         }
         return nil
     }
-    
+
     /**
-        Indicates whether the element has a descendant satisfying the given predicate.
-     
-        - parameter predicate: Function which returns `true` for the desired element and `false` otherwise.
-     
-        - returns: Bool.
-    */
+         Indicates whether the element has a descendant satisfying the given predicate.
+
+         - parameter predicate: Function which returns `true` for the desired element and `false` otherwise.
+
+         - returns: Bool.
+     */
     open func hasDescendant(where predicate: (Element) -> Bool) -> Bool {
         return firstDescendant(where: predicate) != nil
     }
-    
+
     // MARK: - XML Write
-    
+
     /**
-        Adds child XML element to `self`.
-    
-        - parameter child: Child XML element to add.
-    
-        - returns: Child XML element with `self` as `parent`.
-    */
+         Adds child XML element to `self`.
+
+         - parameter child: Child XML element to add.
+
+         - returns: Child XML element with `self` as `parent`.
+     */
     @discardableResult
     open func addChild(_ child: Element) -> Element {
         child.parent = self
         children.append(child)
         return child
     }
-    
+
     /**
-        Adds child XML element to `self`.
-        
-        - parameter name: Child XML element name.
-        - parameter value: Child XML element value (defaults to `nil`).
-        - parameter attributes: Child XML element attributes (defaults to empty dictionary).
-        
-        - returns: Child XML element with `self` as `parent`.
-    */
+         Adds child XML element to `self`.
+
+         - parameter name: Child XML element name.
+         - parameter value: Child XML element value (defaults to `nil`).
+         - parameter attributes: Child XML element attributes (defaults to empty dictionary).
+
+         - returns: Child XML element with `self` as `parent`.
+     */
     @discardableResult
     open func addChild(name: String,
                        value: String? = nil,
-                       attributes: [String : String] = [:]) -> Element {
+                       attributes: [String: String] = [:]) -> Element {
         let child = Element(name: name, value: value, attributes: attributes)
         return addChild(child)
     }
-    
+
     /**
-        Adds an array of XML elements to `self`.
-    
-        - parameter children: Child XML element array to add.
-    
-        - returns: Child XML elements with `self` as `parent`.
-    */
+         Adds an array of XML elements to `self`.
+
+         - parameter children: Child XML element array to add.
+
+         - returns: Child XML elements with `self` as `parent`.
+     */
     @discardableResult
     open func addChildren(_ children: [Element]) -> [Element] {
-        children.forEach{ addChild($0) }
+        children.forEach { addChild($0) }
         return children
     }
-    
+
     /// Removes `self` from `parent` XML element.
     open func removeFromParent() {
         if let index = parent?.children.firstIndex(where: { $0 === self }) {
             parent?.children.remove(at: index)
         }
     }
-    
+
     /// Complete hierarchy of `self` and `children` in **XML** escaped and formatted String
     open var xml: String {
         var xml = String()
-        
+
         // open element
         xml += indent(withDepth: parentsCount - 1)
         xml += "<\(name)"
-        
+
         if attributes.count > 0 {
             // insert attributes
             for (key, value) in attributes.sorted(by: { $0.key < $1.key }) {
                 xml += " \(key)=\"\(value.xmlEscaped)\""
             }
         }
-        
-        if value == nil && children.count == 0 {
+
+        if value == nil, children.count == 0 {
             // close element
             xml += " />"
         } else {
@@ -284,16 +284,16 @@ open class Element {
                 xml += "></\(name)>"
             }
         }
-        
+
         return xml
     }
-    
+
     /// Same as `xmlString` but without `\n` and `\t` characters
     open var xmlCompact: String {
         let chars = CharacterSet(charactersIn: "\n\t")
         return xml.components(separatedBy: chars).joined(separator: "")
     }
-    
+
     /// Same as `xmlString` but with 4 spaces instead '\t' characters
     open var xmlSpaces: String {
         let chars = CharacterSet(charactersIn: "\t")
@@ -325,23 +325,21 @@ open class Element {
 
         return indent
     }
-
 }
 
-public extension String {
-    
+extension String {
+
     /// String representation of self with XML special characters escaped.
-    var xmlEscaped: String {
+    public var xmlEscaped: String {
         // we need to make sure "&" is escaped first. Not doing this may break escaping the other characters
         var escaped = replacingOccurrences(of: "&", with: "&amp;", options: .literal)
-        
+
         // replace the other four special characters
-        let escapeChars = ["<" : "&lt;", ">" : "&gt;", "'" : "&apos;", "\"" : "&quot;"]
+        let escapeChars = ["<": "&lt;", ">": "&gt;", "'": "&apos;", "\"": "&quot;"]
         for (char, echar) in escapeChars {
             escaped = escaped.replacingOccurrences(of: char, with: echar, options: .literal)
         }
-        
+
         return escaped
     }
-    
 }

+ 11 - 13
Sources/XML/Options.swift

@@ -9,49 +9,47 @@ import Foundation
 import FoundationXML
 #endif
 
-
 /// Options used in `Document`
 public struct Options {
-    
+
     /// Values used in XML Document header
     public struct DocumentHeader {
         /// Version value for XML Document header (defaults to 1.0).
         public var version = 1.0
-        
+
         /// Encoding value for XML Document header (defaults to "utf-8").
         public var encoding = "utf-8"
-        
+
         /// Standalone value for XML Document header (defaults to "no").
         public var standalone = "no"
-        
+
         /// XML Document header
         public var xmlString: String {
             return "<?xml version=\"\(version)\" encoding=\"\(encoding)\" standalone=\"\(standalone)\"?>"
         }
     }
-    
+
     /// Settings used by `Foundation.XMLParser`
     public struct ParserSettings {
         /// Parser reports the namespaces and qualified names of elements. (defaults to `false`)
         public var shouldProcessNamespaces = false
-        
+
         /// Parser reports the prefixes indicating the scope of namespace declarations. (defaults to `false`)
         public var shouldReportNamespacePrefixes = false
-        
+
         /// Parser reports declarations of external entities. (defaults to `false`)
         public var shouldResolveExternalEntities = false
-        
+
         /// Parser should trim whitespace from text nodes. (defaults to `true`)
         public var shouldTrimWhitespace = true
     }
-    
+
     /// Values used in XML Document header (defaults to `DocumentHeader()`)
     public var documentHeader = DocumentHeader()
-    
+
     /// Settings used by `Foundation.XMLParser` (defaults to `ParserSettings()`)
     public var parserSettings = ParserSettings()
-    
+
     /// Designated initializer - Creates and returns default `XMLOptions`.
     public init() {}
-    
 }

+ 18 - 19
Sources/XML/Parser.swift

@@ -11,34 +11,34 @@ import FoundationXML
 
 /// Simple wrapper around `Foundation.XMLParser`.
 internal class Parser: NSObject, XMLParserDelegate {
-    
+
     // MARK: - Properties
-    
+
     let document: Document
     let data: Data
-    
+
     var currentParent: Element?
     var currentElement: Element?
     var currentValue = String()
-    
+
     var parseError: Error?
 
     private lazy var parserSettings: Options.ParserSettings = {
-        return document.options.parserSettings
+        document.options.parserSettings
     }()
-    
+
     // MARK: - Lifecycle
-    
+
     init(document: Document, data: Data) {
         self.document = document
         self.data = data
         currentParent = document
-        
+
         super.init()
     }
-    
+
     // MARK: - API
-    
+
     func parse() throws {
         let parser = Foundation.XMLParser(data: data)
         parser.delegate = self
@@ -46,32 +46,32 @@ internal class Parser: NSObject, XMLParserDelegate {
         parser.shouldProcessNamespaces = parserSettings.shouldProcessNamespaces
         parser.shouldReportNamespacePrefixes = parserSettings.shouldReportNamespacePrefixes
         parser.shouldResolveExternalEntities = parserSettings.shouldResolveExternalEntities
-        
+
         let success = parser.parse()
-        
+
         if !success {
             guard let error = parseError else { throw XMLError.parsingFailed }
             throw error
         }
     }
-    
+
     // MARK: - XMLParserDelegate
-    
+
     func parser(_ parser: Foundation.XMLParser,
                 didStartElement elementName: String,
                 namespaceURI: String?,
                 qualifiedName qName: String?,
-                attributes attributeDict: [String : String]) {
+                attributes attributeDict: [String: String]) {
         currentValue = String()
         currentElement = currentParent?.addChild(name: elementName, attributes: attributeDict)
         currentParent = currentElement
     }
-    
+
     func parser(_ parser: Foundation.XMLParser, foundCharacters string: String) {
         currentValue.append(string)
         currentElement?.value = currentValue.isEmpty ? nil : currentValue
     }
-    
+
     func parser(_ parser: Foundation.XMLParser,
                 didEndElement elementName: String,
                 namespaceURI: String?,
@@ -83,9 +83,8 @@ internal class Parser: NSObject, XMLParserDelegate {
         currentParent = currentParent?.parent
         currentElement = nil
     }
-    
+
     func parser(_ parser: Foundation.XMLParser, parseErrorOccurred parseError: Error) {
         self.parseError = parseError
     }
-    
 }

+ 2 - 2
Sources/XML/XMLError.swift

@@ -17,10 +17,10 @@ public enum XMLError: Error {
 
     /// This will be inside `error` property of `XMLElement` when subscript is used for not-existing element.
     case elementNotFound
-    
+
     /// This will be inside `error` property of `XMLDocument` when there is no root element.
     case rootElementMissing
-    
+
     /// `XMLDocument` can throw this error on `init` or `loadXMLData` if parsing with `XMLParser` was not successful.
     case parsingFailed
 }

+ 2 - 4
Tests/BinaryTests/BinaryTests.swift

@@ -1,11 +1,9 @@
-import XCTest
 @testable import Binary
+import XCTest
 
 final class BinaryTests: XCTestCase {
 
-    func testExample() {
-        
-    }
+    func testExample() {}
 
     static var allTests = [
         ("testExample", testExample),

+ 174 - 10
Tests/CryptoTests/Chacha20Tests.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import XCTest
 import Binary
+import XCTest
 
 @testable import Crypto
 
@@ -32,15 +32,180 @@ class Chacha20Tests: XCTestCase {
     }
 
     func testChaCha20() {
-        let keys: [Array<UInt8>] = [
-            [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
-            [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01],
-            [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
-            [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
-            [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f],
+        let keys: [[UInt8]] = [
+            [
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+            ],
+            [
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x01,
+            ],
+            [
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+            ],
+            [
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+            ],
+            [
+                0x00,
+                0x01,
+                0x02,
+                0x03,
+                0x04,
+                0x05,
+                0x06,
+                0x07,
+                0x08,
+                0x09,
+                0x0A,
+                0x0B,
+                0x0C,
+                0x0D,
+                0x0E,
+                0x0F,
+                0x10,
+                0x11,
+                0x12,
+                0x13,
+                0x14,
+                0x15,
+                0x16,
+                0x17,
+                0x18,
+                0x19,
+                0x1A,
+                0x1B,
+                0x1C,
+                0x1D,
+                0x1E,
+                0x1F,
+            ],
         ]
 
-        let ivs: [Array<UInt8>] = [
+        let ivs: [[UInt8]] = [
             [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
             [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
             [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00],
@@ -57,7 +222,7 @@ class Chacha20Tests: XCTestCase {
             "F798A189F195E66982105FFB640BB7757F579DA31602FC93EC01AC56F85AC3C134A4547B733B46413042C9440049176905D3BE59EA1C53F15916155C2BE8241A38008B9A26BC35941E2444177C8ADE6689DE95264986D95889FB60E84629C9BD9A5ACB1CC118BE563EB9B3A4A472F82E09A7E778492B562EF7130E88DFE031C79DB9D4F7C7A899151B9A475032B63FC385245FE054E3DD5A97A5F576FE064025D3CE042C566AB2C507B138DB853E3D6959660996546CC9C4A6EAFDC777C040D70EAF46F76DAD3979E5C5360C3317166A1C894C94A371876A94DF7628FE4EAAF2CCB27D5AAAE0AD7AD0F9D4B6AD3B54098746D4524D38407A6DEB3AB78FAB78C9",
         ]
 
-        for index in 0..<keys.count {
+        for index in 0 ..< keys.count {
 
             let key = Bytes(rawValue: keys[index])
             let iv = Bytes(rawValue: ivs[index])
@@ -80,5 +245,4 @@ class Chacha20Tests: XCTestCase {
     static var allTests = [
         ("testChaCha20", testChaCha20),
     ]
-
 }

+ 174 - 10
Tests/CryptoTests/Salsa20Tests.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import XCTest
 import Binary
+import XCTest
 
 @testable import Crypto
 
@@ -32,15 +32,180 @@ class Salsa20Tests: XCTestCase {
     }
 
     func testSalsa20() {
-        let keys: [Array<UInt8>] = [
-            [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
-            [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01],
-            [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
-            [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
-            [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f],
+        let keys: [[UInt8]] = [
+            [
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+            ],
+            [
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x01,
+            ],
+            [
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+            ],
+            [
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+                0x00,
+            ],
+            [
+                0x00,
+                0x01,
+                0x02,
+                0x03,
+                0x04,
+                0x05,
+                0x06,
+                0x07,
+                0x08,
+                0x09,
+                0x0A,
+                0x0B,
+                0x0C,
+                0x0D,
+                0x0E,
+                0x0F,
+                0x10,
+                0x11,
+                0x12,
+                0x13,
+                0x14,
+                0x15,
+                0x16,
+                0x17,
+                0x18,
+                0x19,
+                0x1A,
+                0x1B,
+                0x1C,
+                0x1D,
+                0x1E,
+                0x1F,
+            ],
         ]
 
-        let ivs: [Array<UInt8>] = [
+        let ivs: [[UInt8]] = [
             [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
             [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
             [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01],
@@ -56,7 +221,7 @@ class Salsa20Tests: XCTestCase {
             "F798A189F195E66982105FFB640BB7757F579DA31602FC93EC01AC56F85AC3C134A4547B733B46413042C9440049176905D3BE59EA1C53F15916155C2BE8241A38008B9A26BC35941E2444177C8ADE6689DE95264986D95889FB60E84629C9BD9A5ACB1CC118BE563EB9B3A4A472F82E09A7E778492B562EF7130E88DFE031C79DB9D4F7C7A899151B9A475032B63FC385245FE054E3DD5A97A5F576FE064025D3CE042C566AB2C507B138DB853E3D6959660996546CC9C4A6EAFDC777C040D70EAF46F76DAD3979E5C5360C3317166A1C894C94A371876A94DF7628FE4EAAF2CCB27D5AAAE0AD7AD0F9D4B6AD3B54098746D4524D38407A6DEB3AB78FAB78C9",
         ]
 
-        for index in 0..<keys.count {
+        for index in 0 ..< keys.count {
 
             let key = Bytes(rawValue: keys[index])
             let iv = Bytes(rawValue: ivs[index])
@@ -79,5 +244,4 @@ class Salsa20Tests: XCTestCase {
     static var allTests = [
         ("testSalsa20", testSalsa20),
     ]
-
 }

+ 1 - 2
Tests/CryptoTests/TwofishTests.swift

@@ -16,8 +16,8 @@
 // You should have received a copy of the GNU General Public License
 // along with KeePassKit. If not, see <https://www.gnu.org/licenses/>.
 
-import XCTest
 import Binary
+import XCTest
 
 @testable import Crypto
 
@@ -334,5 +334,4 @@ class TwofishTests: XCTestCase {
     // static var allTests = [
     //     ("testSalsa20", testSalsa20),
     // ]
-
 }

+ 1 - 1
Tests/KeePassTests/KeePassTests.swift

@@ -1,6 +1,6 @@
-import XCTest
 import Binary
 @testable import KeePass
+import XCTest
 
 final class KeePassTests: XCTestCase {