Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
yaslab committed Jul 24, 2024
1 parent 3140d47 commit 627a05f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 16 deletions.
37 changes: 24 additions & 13 deletions Sources/Hex/Data+Hex.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ extension Data {
guard let bytes = Data.decode(hexData) else {
return nil
}
self = Data(bytes)
self = bytes
}

/// Creates data with the Hexadecimal (also known as Base-16) encoded string.
Expand All @@ -25,21 +25,32 @@ extension Data {
guard let bytes = hexString.withUTF8(Data.decode(_:)) else {
return nil
}
self = Data(bytes)
self = bytes
}

private static func decode(_ input: some Sequence<UInt8>) -> [UInt8]? {
var bytes = [UInt8]()
var it = input.makeIterator()
while true {
switch Base16.decode(&it) {
case .emptyInput:
return bytes
case .error:
return nil
case .byteValue(let byte):
bytes.append(byte)
private static func decode(_ input: some Collection<UInt8>) -> Data? {
let capacity = Base16.estimateDecodedCount(length: input.count)
var bytes = Data(count: capacity)
let count = bytes.withUnsafeMutableBytes { raw in
raw.withMemoryRebound(to: UInt8.self) { buffer in
var i = 0
var it = input.makeIterator()
while true {
switch Base16.decode(&it) {
case .emptyInput:
return i
case .error:
return -1
case .byteValue(let byte):
buffer[i] = byte
i += 1
}
}
}
}
guard count == capacity else {
return nil
}
return bytes
}
}
6 changes: 3 additions & 3 deletions Sources/Hex/Sequence+Hex.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,20 @@ extension Sequence<UInt8> {
/// - Parameter options: Encoding options. Default value is `[]`.
@inlinable
public func hexEncodedData(options: Base16.EncodingOptions = []) -> Data {
Data(EncoderSequence(sequence: self, options: options))
Data(Base16EncodingSequence(sequence: self, options: options))
}

/// Returns the Hexadecimal (also known as Base-16) encoded string.
///
/// - Parameter options: Encoding options. Default value is `[]`.
@inlinable
public func hexEncodedString(options: Base16.EncodingOptions = []) -> String {
String(bytes: EncoderSequence(sequence: self, options: options), encoding: .utf8)!
String(bytes: Base16EncodingSequence(sequence: self, options: options), encoding: .utf8)!
}
}

@usableFromInline
struct EncoderSequence<S: Sequence<UInt8>>: Sequence {
struct Base16EncodingSequence<S: Sequence<UInt8>>: Sequence {
private let sequence: S
private let options: Base16.EncodingOptions

Expand Down

0 comments on commit 627a05f

Please sign in to comment.