Skip to content

Commit bce047e

Browse files
authored
Merge pull request #1 from basedxyz/feat/add-base64urlencode
feat: add base64urlencode
2 parents 30352f1 + d1b8597 commit bce047e

File tree

3 files changed

+57
-0
lines changed

3 files changed

+57
-0
lines changed

README.md

+8
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,15 @@ BasedUtils.shortenAddress(address1) // "0xd8dA...6045"
6060

6161
### Extensions
6262

63+
Data
64+
65+
```swift
66+
let data = "https://example.com".data(using: .utf8)!
67+
data.base64UrlEncode() // "aHR0cHM6Ly9leGFtcGxlLmNvbQ"
68+
```
69+
6370
String
71+
6472
```swift
6573
let address = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
6674
let hash = "d8dA6B"
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
//
2+
// Data.swift
3+
//
4+
//
5+
// Created by Jann Driessen on 24.06.24.
6+
//
7+
8+
import Foundation
9+
10+
public extension Data {
11+
12+
func base64UrlEncode() -> String {
13+
var base64String = self.base64EncodedString()
14+
// Replace standard Base64 characters to make it URL-safe
15+
base64String = base64String
16+
.replacingOccurrences(of: "+", with: "-")
17+
.replacingOccurrences(of: "/", with: "_")
18+
.replacingOccurrences(of: "=", with: "")
19+
return base64String
20+
}
21+
22+
}
23+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
//
2+
// DataExtensionsTests.swift
3+
//
4+
//
5+
// Created by Jann Driessen on 24.06.24.
6+
//
7+
8+
import XCTest
9+
@testable import BasedUtils
10+
11+
final class DataExtensionsTests: XCTestCase {
12+
13+
func testBase64UrlEncode() throws {
14+
let basicEncoding = "https://example.com".data(using: .utf8)!
15+
let urlWithQueryParams = "https://example.com/path?query=parameter".data(using: .utf8)!
16+
let urlWithSpecialCharacters = "https://example.com/path?query=param+eter&foo=bar/baz".data(using: .utf8)!
17+
let simpleText = "Hello world".data(using: .utf8)!
18+
let emptyString = "".data(using: .utf8)!
19+
XCTAssertEqual(basicEncoding.base64UrlEncode(), "aHR0cHM6Ly9leGFtcGxlLmNvbQ")
20+
XCTAssertEqual(urlWithQueryParams.base64UrlEncode(), "aHR0cHM6Ly9leGFtcGxlLmNvbS9wYXRoP3F1ZXJ5PXBhcmFtZXRlcg")
21+
XCTAssertEqual(urlWithSpecialCharacters.base64UrlEncode(), "aHR0cHM6Ly9leGFtcGxlLmNvbS9wYXRoP3F1ZXJ5PXBhcmFtK2V0ZXImZm9vPWJhci9iYXo")
22+
XCTAssertEqual(simpleText.base64UrlEncode(), "SGVsbG8gd29ybGQ")
23+
XCTAssertEqual(emptyString.base64UrlEncode(), "")
24+
}
25+
26+
}

0 commit comments

Comments
 (0)