Skip to content

Commit

Permalink
Convert to Int without using String
Browse files Browse the repository at this point in the history
  • Loading branch information
gjcairo committed Feb 11, 2025
1 parent 5d9732e commit a9de7b9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,8 @@ package enum PeerAddress: Equatable {
var portComponent = addressWithoutType[addressColon...]
_ = portComponent.popFirst()

if let host = String(hostComponent), let port = String(portComponent) {
self = .ipv4(address: host, port: Int(port))
if let host = String(hostComponent), let port = Int(utf8View: portComponent) {
self = .ipv4(address: host, port: port)
} else {
return nil
}
Expand All @@ -179,8 +179,8 @@ package enum PeerAddress: Equatable {

if let firstBracket = hostComponent.popFirst(), let lastBracket = hostComponent.popLast(),
firstBracket == UInt8(ascii: "["), lastBracket == UInt8(ascii: "]"),
let host = String(hostComponent), let port = String(portComponent) {
self = .ipv6(address: host, port: Int(port))
let host = String(hostComponent), let port = Int(utf8View: portComponent) {
self = .ipv6(address: host, port: port)
} else {
// This is some unexpected/unknown format
return nil
Expand All @@ -194,3 +194,19 @@ package enum PeerAddress: Equatable {
}
}
}

extension Int {
package init?(utf8View: Substring.UTF8View.SubSequence) {
var value = 0
for utf8Element in utf8View {
value &*= 10
let elementValue = Int(utf8Element - 48) // ASCII code for 0 is 48
guard elementValue >= 0, elementValue <= 9 else {
// non-digit character
return nil
}
value &+= elementValue
}
self = value
}
}
5 changes: 5 additions & 0 deletions Tests/GRPCOTelTracingInterceptorsTests/PeerAddressTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,9 @@ struct PeerAddressTests {
let address = PeerAddress(address)
#expect(address == nil)
}

@Test("Int.init(utf8View:)")
func testIntInitFromUTF8View() async throws {
#expect(54321 == Int(utf8View: "54321".utf8[...]))
}
}

0 comments on commit a9de7b9

Please sign in to comment.