Skip to content

Commit

Permalink
feat: add data from hex
Browse files Browse the repository at this point in the history
  • Loading branch information
janndriessen committed Sep 10, 2024
1 parent 7fc6f34 commit a4edb3b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
27 changes: 26 additions & 1 deletion Sources/BasedUtils/extensions/Data.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,32 @@ import Foundation

public extension Data {

/// Returns Data from given hex string.
/// - an empty string will return `nil`;
/// - an empty hex string is equal to `"0x"` and will return empty `Data` object.
/// - Parameter hex: bytes represented as string.
/// - Returns: optional raw bytes.
static func fromHex(_ hex: String) -> Data? {
let hex = hex.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
guard !hex.isEmpty else { return nil }
guard hex != "0x" else { return Data() }
let rawHex = hex.removeHexPrefix()
guard rawHex.count % 2 == 0 else { return nil }
var data = Data(capacity: rawHex.count / 2)
var index = rawHex.startIndex
while index < rawHex.endIndex {
let nextIndex = rawHex.index(index, offsetBy: 2)
let byteString = rawHex[index..<nextIndex]
if let byte = UInt8(byteString, radix: 16) {
data.append(byte)
} else {
return nil
}
index = nextIndex
}
return data
}

func base64UrlEncode() -> String {
var base64String = self.base64EncodedString()
// Replace standard Base64 characters to make it URL-safe
Expand All @@ -20,4 +46,3 @@ public extension Data {
}

}

7 changes: 7 additions & 0 deletions Tests/BasedUtilsTests/DataExtensionsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,11 @@ final class DataExtensionsTests: XCTestCase {
XCTAssertEqual(emptyString.base64UrlEncode(), "")
}

func testFromHex() throws {
XCTAssertEqual(Data.fromHex("0x"), Data())
XCTAssertEqual(Data.fromHex("0x61"), Data([97]))
XCTAssertEqual(Data.fromHex("0x48656c6c6f20576f726c6421"), Data([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))
XCTAssertEqual(Data.fromHex("0x420fggf11a"), nil)
}

}

0 comments on commit a4edb3b

Please sign in to comment.