浏览代码

👋 hello, base32!

Abdullah Aljahdali 4 年之前
当前提交
d1ca08f537

+ 19 - 0
LICENSE.md

@@ -0,0 +1,19 @@
+The MIT License (MIT) Copyright (c) 2020 **Abdullah Aljahdali** Alja7dali@gmail.com
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.

+ 16 - 0
Package.swift

@@ -0,0 +1,16 @@
+// swift-tools-version:5.0
+import PackageDescription
+
+let package = Package(
+  name: "Base32",
+  products: [
+    .library(name: "Base32", targets: ["Base32"]),
+  ],
+  dependencies: [
+    .package(url: "https://github.com/alja7dali/swift-bits", from: "1.0.0"),
+  ],
+  targets: [
+    .target(name: "Base32", dependencies: ["Bits"]),
+    .testTarget(name: "Base32Tests", dependencies: ["Base32"]),
+  ]
+)

+ 33 - 0
README.md

@@ -0,0 +1,33 @@
+###### This is an implementation of [Base32](https://en.wikipedia.org/wiki/Base32) `encode`/`decode` algorithm.
+
+#### Example:
+
+```swift
+import Base32
+
+/// Encoding to Base32
+/// 1. convert string to bytes (utf8 format)
+let bytes = "Hello, World!".makeBytes()
+/// 2. encode bytes using base32 algorithm
+let encodedBytes = Base32.encode(bytes)
+/// 3. converting bytes back to string
+let encodedString = try String(encoded) // "JBSWY3DPFQQFO33SNRSCC==="
+
+
+/// Decoding from Base32
+/// 1. convert string to bytes (utf8 format)
+let bytes = "JBSWY3DPFQQFO33SNRSCC===".makeBytes()
+/// 2. decode bytes using base32 algorithm
+let decodedBytes = try Base32.decode(bytes)
+/// 3. converting bytes back to string
+let decodedString = try String(encoded) // "Hello, World!"
+```
+
+#### Importing Base32:
+
+To include `Base32` in your project, you need to add the following to the `dependencies` attribute defined in your `Package.swift` file.
+```swift
+dependencies: [
+  .package(url: "https://github.com/alja7dali/swift-base32.git", from: "1.0.0")
+]
+```

+ 251 - 0
Sources/Base32/Base32.swift

@@ -0,0 +1,251 @@
+/// Encodes and Decodes bytes using the 
+/// Base32 algorithm
+///
+/// https://en.wikipedia.org/wiki/Base32
+
+// Note: The implementation has 3 different attempts,
+//       the last attempt is the fastest. The previous
+//       two are there just as reference..
+
+/// Maps binary format to base32 encoding
+private let Base32EncodingTable: [Byte: Byte] = [
+   0: .A,      1: .B,     2: .C,     3: .D,
+   4: .E,      5: .F,     6: .G,     7: .H,
+   8: .I,      9: .J,    10: .K,    11: .L,
+  12: .M,     13: .N,    14: .O,    15: .P,
+  16: .Q,     17: .R,    18: .S,    19: .T,
+  20: .U,     21: .V,    22: .W,    23: .X,
+  24: .Y,     25: .Z,    26: .two,  27: .three,
+  28: .four,  29: .five, 30: .six,  31: .seven
+]
+
+private let encode: (Byte) -> Byte = {
+  Base32EncodingTable[$0] ?? .max
+}
+
+/// Maps base32 encoding to binary format
+private let Base32DecodingTable: [Byte: Byte] = [
+   .A: 0,     .B: 1,     .C: 2,        .D: 3,
+   .E: 4,     .F: 5,     .G: 6,        .H: 7,
+   .I: 8,     .J: 9,     .K: 10,       .L: 11,
+   .M: 12,    .N: 13,    .O: 14,       .P: 15,
+   .Q: 16,    .R: 17,    .S: 18,       .T: 19,
+   .U: 20,    .V: 21,    .W: 22,       .X: 23,
+   .Y: 24,    .Z: 25,  .two: 26,   .three: 27,
+.four: 28, .five: 29,  .six: 30,   .seven: 31
+]
+
+private let decode: (Byte) -> Byte = {
+  Base32DecodingTable[$0] ?? .max
+}
+
+public func encode(_ bytes: Bytes) -> Bytes {
+
+  var result = Bytes()
+
+  for byteIndex in stride(from: 0, to: bytes.count, by: 5) {
+    let maxOffset = (byteIndex + 5 >= bytes.count) ? bytes.count : byteIndex + 5
+    var numberOfBytes = maxOffset - byteIndex
+
+    var byte = Bytes(repeating: 0, count: 5)
+    var encodedByte = Bytes(repeating: .equals, count: 8)
+
+    //// Attempt: I
+    // while numberOfBytes > 0 {
+    //     switch numberOfBytes {
+    //     case 5:
+    //         byte[4] = bytes[byteIndex + 4]
+    //         encodedByte[7] = encode( byte[4] & 0x1F )
+    //     case 4:
+    //         byte[3] = bytes[byteIndex + 3]
+    //         encodedByte[6] = encode( ((byte[3] << 3) & 0x18) | ((byte[4] >> 5) & 0x07) )
+    //         encodedByte[5] = encode( ((byte[3] >> 2) & 0x1F) )
+    //     case 3:
+    //         byte[2] = bytes[byteIndex + 2]
+    //         encodedByte[4] = encode( ((byte[2] << 1) & 0x1E) | ((byte[3] >> 7) & 0x01) )
+    //     case 2:
+    //         byte[1] = bytes[byteIndex + 1]
+    //         encodedByte[2] = encode( ((byte[1] >> 1) & 0x1F) )
+    //         encodedByte[3] = encode( ((byte[1] << 4) & 0x10) | ((byte[2] >> 4) & 0x0F) )
+    //     case 1:
+    //         byte[0] = bytes[byteIndex + 0]
+    //         encodedByte[0] = encode( ((byte[0] >> 3) & 0x1F) )
+    //         encodedByte[1] = encode( ((byte[0] << 2) & 0x1C) | ((byte[1] >> 6) & 0x03) )
+    //     default:
+    //         break
+    //     }
+    //     numberOfBytes -= 1
+    // }
+
+    //// Attempt: II
+    // while numberOfBytes > 0 {
+    //     switch numberOfBytes {
+    //     case 5:
+    //         byte[4] = bytes[byteIndex + 4]
+    //         encodedByte[7] = encode( byte[4] & 0x1F )
+    //     case 4:
+    //         byte[3] = bytes[byteIndex + 3]
+
+    //         let b = [(byte[3] << 3) & 0x18, (byte[4] >> 5) & 0x07, (byte[3] >> 2) & 0x1F]
+    //         encodedByte[6] = encode( b[0] | b[1] )
+    //         encodedByte[5] = encode( b[2] )
+    //     case 3:
+    //         byte[2] = bytes[byteIndex + 2]
+
+    //         let b = [(byte[2] << 1) & 0x1E, (byte[3] >> 7) & 0x01]
+    //         encodedByte[4] = encode( b[0] | b[1] )
+    //     case 2:
+    //         byte[1] = bytes[byteIndex + 1]
+
+    //         let b = [(byte[1] >> 1) & 0x1F, (byte[1] << 4) & 0x10, (byte[2] >> 4) & 0x0F]
+    //         encodedByte[2] = encode( b[0] )
+    //         encodedByte[3] = encode( b[1] | b[2] )
+    //     case 1:
+    //         byte[0] = bytes[byteIndex + 0]
+
+    //         let b = [(byte[0] >> 3) & 0x1F, (byte[0] << 2) & 0x1C, (byte[1] >> 6) & 0x03]
+    //         encodedByte[0] = encode( b[0] )
+    //         encodedByte[1] = encode( b[1] | b[2] )
+    //     default:
+    //         break
+    //     }
+    //     numberOfBytes -= 1
+    // }
+
+    // Attempt: III
+    while numberOfBytes > 0 {
+      switch numberOfBytes {
+      case 5:
+        byte[4] = bytes[byteIndex + 4]
+        encodedByte[7] = encode( byte[4] & 0x1F )
+      case 4:
+        byte[3] = bytes[byteIndex + 3]
+
+        let b1 = (byte[3] << 3) & 0x18
+        let b2 = (byte[4] >> 5) & 0x07
+        let b3 = (byte[3] >> 2) & 0x1F
+        encodedByte[6] = encode( b1 | b2 )
+        encodedByte[5] = encode( b3 )
+      case 3:
+        byte[2] = bytes[byteIndex + 2]
+
+        let b1 = (byte[2] << 1) & 0x1E
+        let b2 = (byte[3] >> 7) & 0x01
+        encodedByte[4] = encode( b1 | b2 )
+      case 2:
+        byte[1] = bytes[byteIndex + 1]
+
+        let b1 = (byte[1] >> 1) & 0x1F
+        let b2 = (byte[1] << 4) & 0x10
+        let b3 = (byte[2] >> 4) & 0x0F
+        encodedByte[2] = encode( b1 )
+        encodedByte[3] = encode( b2 | b3 )
+      case 1:
+        byte[0] = bytes[byteIndex + 0]
+
+        let b1 = (byte[0] >> 3) & 0x1F
+        let b2 = (byte[0] << 2) & 0x1C
+        let b3 = (byte[1] >> 6) & 0x03
+        encodedByte[0] = encode( b1 )
+        encodedByte[1] = encode( b2 | b3 )
+      default:
+        break
+      }
+      numberOfBytes -= 1
+    }
+
+    result += encodedByte
+  }
+
+  return result
+}
+
+
+public enum Base32DecodingError: Error {
+  case oddLength
+  case invalidByte(Byte)
+}
+
+public func decode(_ bytes: Bytes) throws -> Bytes {
+
+  guard bytes.count % 2 == 0 else {
+    throw Base32DecodingError.oddLength
+  }
+
+  var temp = Bytes()
+
+  for byte in bytes.uppercased {
+    if Base32DecodingTable[byte] != nil {
+      temp.append(byte)
+    } else if byte != .equals {
+      throw Base32DecodingError.invalidByte(byte)
+    }
+  }
+
+  var result = Bytes()
+
+  for byteIndex in stride(from: 0, to: temp.count, by: 8) {
+    let maxOffset = (byteIndex + 8 >= temp.count) ? temp.count : byteIndex + 8
+    var numberOfBytes = maxOffset - byteIndex
+
+    var encodedByte = Bytes(repeating: 0, count: 8)
+
+    while numberOfBytes > 0 {
+      switch numberOfBytes {
+      case 8: encodedByte[7] = decode( temp[byteIndex + 7] )
+      case 7: encodedByte[6] = decode( temp[byteIndex + 6] )
+      case 6: encodedByte[5] = decode( temp[byteIndex + 5] )
+      case 5: encodedByte[4] = decode( temp[byteIndex + 4] )
+      case 4: encodedByte[3] = decode( temp[byteIndex + 3] )
+      case 3: encodedByte[2] = decode( temp[byteIndex + 2] )
+      case 2: encodedByte[1] = decode( temp[byteIndex + 1] )
+      case 1: encodedByte[0] = decode( temp[byteIndex + 0] )
+      default: break
+      }
+      numberOfBytes -= 1
+    }
+
+    // // Attempt: I
+    // result.append(((encodedByte[0] << 3) & 0xF8) | ((encodedByte[1] >> 2) & 0x07))
+    // result.append(((encodedByte[1] << 6) & 0xC0) | ((encodedByte[2] << 1) & 0x3E) | ((encodedByte[3] >> 4) & 0x01))
+    // result.append(((encodedByte[3] << 4) & 0xF0) | ((encodedByte[4] >> 1) & 0x0F))
+    // result.append(((encodedByte[4] << 7) & 0x80) | ((encodedByte[5] << 2) & 0x7C) | ((encodedByte[6] >> 3) & 0x03))
+    // result.append(((encodedByte[6] << 5) & 0xE0) | (encodedByte[7] & 0x1F))
+
+    //// Attempt: II
+    // var b = [(encodedByte[0] << 3) & 0xF8, (encodedByte[1] >> 2) & 0x07]
+    // result.append(b[0] | b[1])
+    // b = [(encodedByte[1] << 6) & 0xC0, (encodedByte[2] << 1) & 0x3E, (encodedByte[3] >> 4) & 0x01]
+    // result.append(b[0] | b[1] | b[2])
+    // b = [(encodedByte[3] << 4) & 0xF0, (encodedByte[4] >> 1) & 0x0F]
+    // result.append(b[0] | b[1])
+    // b = [(encodedByte[4] << 7) & 0x80, (encodedByte[5] << 2) & 0x7C, (encodedByte[6] >> 3) & 0x03]
+    // result.append(b[0] | b[1] | b[2])
+    // b = [(encodedByte[6] << 5) & 0xE0, (encodedByte[7] & 0x1F)]
+    // result.append(b[0] | b[1])
+
+    // Attempt: III
+    let b01 = (encodedByte[0] << 3) & 0xF8
+    let b02 = (encodedByte[1] >> 2) & 0x07
+    result.append(b01 | b02)
+    let b11 = (encodedByte[1] << 6) & 0xC0
+    let b12 = (encodedByte[2] << 1) & 0x3E
+    let b13 = (encodedByte[3] >> 4) & 0x01
+    result.append(b11 | b12 | b13)
+    let b21 = (encodedByte[3] << 4) & 0xF0
+    let b22 = (encodedByte[4] >> 1) & 0x0F
+    result.append(b21 | b22)
+    let b31 = (encodedByte[4] << 7) & 0x80
+    let b32 = (encodedByte[5] << 2) & 0x7C
+    let b33 = (encodedByte[6] >> 3) & 0x03
+    result.append(b31 | b32 | b33)
+    let b41 = (encodedByte[6] << 5) & 0xE0
+    let b42 = (encodedByte[7] & 0x1F)
+    result.append(b41 | b42)
+  }
+
+  while result.last == 0 {
+    result.removeLast()
+  }
+  return result
+}

+ 1 - 0
Sources/Base32/exported.swift

@@ -0,0 +1 @@
+@_exported import Bits

+ 31 - 0
Tests/Base32Tests/Base32Tests.swift

@@ -0,0 +1,31 @@
+import XCTest
+@testable import Base32
+
+final class Base32Tests: XCTestCase {
+  func testEncodingToBase32() {
+    do {
+      let bytes = "Hello, World!".makeBytes()
+      let encoded = Base32.encode(bytes)
+      let str = try String(encoded)
+      XCTAssertEqual(str, "JBSWY3DPFQQFO33SNRSCC===")
+    } catch {
+      XCTFail()
+    }
+  }
+
+  func testDecodingToBase32() {
+    do {
+      let bytes = "JBSWY3DPFQQFO33SNRSCC===".makeBytes()
+      let decoded = try Base32.decode(bytes)
+      let str = try String(decoded)
+      XCTAssertEqual(str, "Hello, World!")
+    } catch {
+      XCTFail()
+    }
+  }
+
+  static var allTests = [
+    ("testEncodingToBase32", testEncodingToBase32),
+    ("testDecodingToBase32", testDecodingToBase32),
+  ]
+}

+ 9 - 0
Tests/Base32Tests/XCTestManifests.swift

@@ -0,0 +1,9 @@
+import XCTest
+
+#if !canImport(ObjectiveC)
+public func allTests() -> [XCTestCaseEntry] {
+  return [
+    testCase(Base32Tests.allTests),
+  ]
+}
+#endif

+ 7 - 0
Tests/LinuxMain.swift

@@ -0,0 +1,7 @@
+import XCTest
+
+import Base32Tests
+
+var tests = [XCTestCaseEntry]()
+tests += Base32Tests.allTests()
+XCTMain(tests)