Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Match against strings to improve performance #347

Merged
merged 1 commit into from
Dec 13, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions web3swift/src/Client/Models/EthereumAddress.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,21 @@ public struct EthereumAddress: Codable, Hashable {

private let raw: String
private let numberRepresentation: BigUInt?
private let numberRepresentationAsString: String?
public static let zero: Self = "0x0000000000000000000000000000000000000000"

public init(_ value: String) {
self.raw = value.lowercased()
self.numberRepresentation = BigUInt(hex: raw)
self.numberRepresentationAsString = self.numberRepresentation.map(String.init(describing:))
}

public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let raw = try container.decode(String.self).lowercased()
self.raw = raw
self.numberRepresentation = BigUInt(hex: raw)
self.numberRepresentationAsString = self.numberRepresentation.map(String.init(describing:))
}

public func encode(to encoder: Encoder) throws {
Expand All @@ -33,19 +36,19 @@ public struct EthereumAddress: Codable, Hashable {
}

public func hash(into hasher: inout Hasher) {
if let number = asNumber() {
hasher.combine(number)
if let numberAsString = numberRepresentationAsString {
hasher.combine(numberAsString)
} else {
hasher.combine(asString())
}
}

public static func == (lhs: EthereumAddress, rhs: EthereumAddress) -> Bool {
guard let lhsInt = lhs.asNumber(), let rhsInt = rhs.asNumber() else {
guard let lhs = lhs.numberRepresentationAsString, let rhs = rhs.numberRepresentationAsString else {
return false
}
// Comparing Number representation avoids issues with lowercase and 0-padding
return lhsInt == rhsInt
return lhs == rhs
}
}

Expand Down
Loading