Skip to content

Commit a9de7b9

Browse files
committed
Convert to Int without using String
1 parent 5d9732e commit a9de7b9

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

Sources/GRPCOTelTracingInterceptors/Tracing/SpanAttributes+GRPCTracingKeys.swift

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -162,8 +162,8 @@ package enum PeerAddress: Equatable {
162162
var portComponent = addressWithoutType[addressColon...]
163163
_ = portComponent.popFirst()
164164

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

180180
if let firstBracket = hostComponent.popFirst(), let lastBracket = hostComponent.popLast(),
181181
firstBracket == UInt8(ascii: "["), lastBracket == UInt8(ascii: "]"),
182-
let host = String(hostComponent), let port = String(portComponent) {
183-
self = .ipv6(address: host, port: Int(port))
182+
let host = String(hostComponent), let port = Int(utf8View: portComponent) {
183+
self = .ipv6(address: host, port: port)
184184
} else {
185185
// This is some unexpected/unknown format
186186
return nil
@@ -194,3 +194,19 @@ package enum PeerAddress: Equatable {
194194
}
195195
}
196196
}
197+
198+
extension Int {
199+
package init?(utf8View: Substring.UTF8View.SubSequence) {
200+
var value = 0
201+
for utf8Element in utf8View {
202+
value &*= 10
203+
let elementValue = Int(utf8Element - 48) // ASCII code for 0 is 48
204+
guard elementValue >= 0, elementValue <= 9 else {
205+
// non-digit character
206+
return nil
207+
}
208+
value &+= elementValue
209+
}
210+
self = value
211+
}
212+
}

Tests/GRPCOTelTracingInterceptorsTests/PeerAddressTests.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,4 +56,9 @@ struct PeerAddressTests {
5656
let address = PeerAddress(address)
5757
#expect(address == nil)
5858
}
59+
60+
@Test("Int.init(utf8View:)")
61+
func testIntInitFromUTF8View() async throws {
62+
#expect(54321 == Int(utf8View: "54321".utf8[...]))
63+
}
5964
}

0 commit comments

Comments
 (0)