BitFoundation module to centralize shared components#1089
Conversation
9f4fff8 to
a3a3cfb
Compare
a3a3cfb to
f627be8
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f627be84eb
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| import Foundation | ||
| import CryptoKit | ||
|
|
||
| // MARK: - Hex Encoding/Decoding | ||
|
|
||
| extension Data { | ||
| func hexEncodedString() -> String { | ||
| if self.isEmpty { | ||
| return "" | ||
| } | ||
| return self.map { String(format: "%02x", $0) }.joined() | ||
| } | ||
|
|
||
| func sha256Hex() -> String { | ||
| let digest = SHA256.hash(data: self) | ||
| return digest.map { String(format: "%02x", $0) }.joined() | ||
| } | ||
|
|
||
| /// Initialize Data from a hex string. | ||
| /// - Parameter hexString: A hex string, optionally prefixed with "0x" or "0X". | ||
| /// Whitespace is trimmed. Must have even length after prefix removal. | ||
| /// - Returns: nil if the string has odd length or contains invalid hex characters. | ||
| init?(hexString: String) { | ||
| var hex = hexString.trimmingCharacters(in: .whitespaces) | ||
|
|
||
| // Remove optional 0x prefix | ||
| if hex.hasPrefix("0x") || hex.hasPrefix("0X") { | ||
| hex = String(hex.dropFirst(2)) | ||
| } | ||
|
|
||
| // Reject odd-length strings | ||
| guard hex.count % 2 == 0 else { | ||
| return nil | ||
| } | ||
|
|
||
| // Reject empty strings | ||
| guard !hex.isEmpty else { | ||
| self = Data() | ||
| return | ||
| } | ||
|
|
||
| let len = hex.count / 2 | ||
| var data = Data(capacity: len) | ||
| var index = hex.startIndex | ||
|
|
||
| for _ in 0..<len { | ||
| let nextIndex = hex.index(index, offsetBy: 2) | ||
| guard let byte = UInt8(String(hex[index..<nextIndex]), radix: 16) else { | ||
| return nil | ||
| } | ||
| data.append(byte) | ||
| index = nextIndex | ||
| } | ||
|
|
||
| self = data | ||
| } | ||
| } | ||
| import BitFoundation |
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
4eb4ee3 to
5b690de
Compare
|
P3 |
aa26022 to
0c1c4fc
Compare
0c1c4fc to
dc783cb
Compare
|
Depends on #1100 |
dc783cb to
1aa80c5
Compare
fixed |
No description provided.