Base16.swift 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. //
  2. // Base16.swift
  3. // Base32
  4. //
  5. // Created by 野村 憲男 on 2/7/15.
  6. //
  7. // Copyright (c) 2015 Norio Nomura
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. // MARK: - Base16 Data <-> String
  28. public func base16Encode(_ data: Data, uppercase: Bool = true) -> String {
  29. return data.withUnsafeBytes {
  30. base16encode($0.baseAddress!, $0.count, uppercase)
  31. }
  32. }
  33. public func base16DecodeToData(_ string: String) -> Data? {
  34. return base16decode(string)?.withUnsafeBufferPointer(Data.init(buffer:))
  35. }
  36. // MARK: - Base16 [UInt8] <-> String
  37. public func base16Encode(_ array: [UInt8], uppercase: Bool = true) -> String {
  38. return base16encode(array, array.count, uppercase)
  39. }
  40. public func base16Decode(_ string: String) -> [UInt8]? {
  41. return base16decode(string)
  42. }
  43. // MARK: extensions
  44. extension String {
  45. // base16
  46. public var base16DecodedData: Data? {
  47. return base16DecodeToData(self)
  48. }
  49. public var base16EncodedString: String {
  50. return utf8CString.withUnsafeBufferPointer {
  51. base16encode($0.baseAddress!, $0.count - 1)
  52. }
  53. }
  54. public func base16DecodedString(_ encoding: String.Encoding = .utf8) -> String? {
  55. return base16DecodedData.flatMap {
  56. String(data: $0, encoding: .utf8)
  57. }
  58. }
  59. }
  60. extension Data {
  61. // base16
  62. public var base16EncodedString: String {
  63. return base16Encode(self)
  64. }
  65. public var base16EncodedData: Data {
  66. return base16EncodedString.dataUsingUTF8StringEncoding
  67. }
  68. public var base16DecodedData: Data? {
  69. return String(data: self, encoding: .utf8).flatMap(base16DecodeToData)
  70. }
  71. }
  72. // MARK: encode
  73. private func base16encode(_ data: UnsafeRawPointer, _ length: Int, _ uppercase: Bool = true) -> String {
  74. let array = UnsafeBufferPointer.init(start: data.bindMemory(to: UInt8.self, capacity: length), count: length)
  75. return array.map { String(format: uppercase ? "%02X" : "%02x", $0) }.reduce("", +)
  76. }
  77. // MARK: decode
  78. extension UnicodeScalar {
  79. fileprivate var hexToUInt8: UInt8? {
  80. switch self {
  81. case "0"..."9": return UInt8(value - UnicodeScalar("0").value)
  82. case "a"..."f": return UInt8(0xa) + UInt8(value - UnicodeScalar("a").value)
  83. case "A"..."F": return UInt8(0xa) + UInt8(value - UnicodeScalar("A").value)
  84. default:
  85. print("base16decode: Invalid hex character \(self)")
  86. return nil
  87. }
  88. }
  89. }
  90. private func base16decode(_ string: String) -> [UInt8]? {
  91. // validate length
  92. let lenght = string.utf8CString.count - 1
  93. if lenght % 2 != 0 {
  94. print("base16decode: String must contain even number of characters")
  95. return nil
  96. }
  97. var g = string.unicodeScalars.makeIterator()
  98. var buffer = Array<UInt8>(repeating: 0, count: lenght / 2)
  99. var index = 0
  100. while let msn = g.next() {
  101. if let msn = msn.hexToUInt8 {
  102. if let lsn = g.next()?.hexToUInt8 {
  103. buffer[index] = msn << 4 | lsn
  104. } else {
  105. return nil
  106. }
  107. } else {
  108. return nil
  109. }
  110. index += 1
  111. }
  112. return buffer
  113. }